diff --git a/README.md b/README.md index 2e7f0e90d5d96b27e33b856353c80ffa1ab8c89a..8779c26b68bf5202ecb8bcd317463cddda6ac20c 100644 --- a/README.md +++ b/README.md @@ -109,6 +109,21 @@ To deploy DocVerifyRAG using Docker, follow these steps: Access the web interface and follow the prompts to upload documents, classify them, and verify metadata. The AI-powered anomaly detection system will automatically flag any discrepancies or errors in the document metadata, providing accurate and reliable document management solutions for hospitals. +## Higging Face configuration + +--- +title: Docverifyrag +emoji: 🐠 +colorFrom: indigo +colorTo: indigo +sdk: streamlit +sdk_version: 1.33.0 +app_file: app.py +pinned: false +--- + +Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference + ## Authors | Name | Link | diff --git a/backend/node_modules/.bin/mime b/backend/node_modules/.bin/mime new file mode 120000 index 0000000000000000000000000000000000000000..fbb7ee0eed8d1dd0fe3b5a9d6ff41d1c4f044675 --- /dev/null +++ b/backend/node_modules/.bin/mime @@ -0,0 +1 @@ +../mime/cli.js \ No newline at end of file diff --git a/backend/node_modules/.bin/mkdirp b/backend/node_modules/.bin/mkdirp new file mode 120000 index 0000000000000000000000000000000000000000..017896cebb14168f03f019eb2ca3acb3cac65afb --- /dev/null +++ b/backend/node_modules/.bin/mkdirp @@ -0,0 +1 @@ +../mkdirp/bin/cmd.js \ No newline at end of file diff --git a/backend/node_modules/.bin/openai b/backend/node_modules/.bin/openai new file mode 120000 index 0000000000000000000000000000000000000000..d3dcb0be39ff8c9fb618602b55abe5a0598a7ba6 --- /dev/null +++ b/backend/node_modules/.bin/openai @@ -0,0 +1 @@ +../openai/bin/cli \ No newline at end of file diff --git a/backend/node_modules/.package-lock.json b/backend/node_modules/.package-lock.json new file mode 100644 index 0000000000000000000000000000000000000000..4f81e20573eb43b52807ab454651b09e688b8ec9 --- /dev/null +++ b/backend/node_modules/.package-lock.json @@ -0,0 +1,1148 @@ +{ + "name": "backend", + "lockfileVersion": 3, + "requires": true, + "packages": { + "node_modules/@types/body-parser": { + "version": "1.19.5", + "resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.19.5.tgz", + "integrity": "sha512-fB3Zu92ucau0iQ0JMCFQE7b/dv8Ot07NI3KaZIkIUNXq82k4eBAqUaneXfleGY9JWskeS9y+u0nXMyspcuQrCg==", + "dependencies": { + "@types/connect": "*", + "@types/node": "*" + } + }, + "node_modules/@types/connect": { + "version": "3.4.38", + "resolved": "https://registry.npmjs.org/@types/connect/-/connect-3.4.38.tgz", + "integrity": "sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug==", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/express": { + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/@types/express/-/express-4.17.21.tgz", + "integrity": "sha512-ejlPM315qwLpaQlQDTjPdsUFSc6ZsP4AN6AlWnogPjQ7CVi7PYF3YVz+CY3jE2pwYf7E/7HlDAN0rV2GxTG0HQ==", + "dev": true, + "dependencies": { + "@types/body-parser": "*", + "@types/express-serve-static-core": "^4.17.33", + "@types/qs": "*", + "@types/serve-static": "*" + } + }, + "node_modules/@types/express-serve-static-core": { + "version": "4.19.0", + "resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-4.19.0.tgz", + "integrity": "sha512-bGyep3JqPCRry1wq+O5n7oiBgGWmeIJXPjXXCo8EK0u8duZGSYar7cGqd3ML2JUsLGeB7fmc06KYo9fLGWqPvQ==", + "dev": true, + "dependencies": { + "@types/node": "*", + "@types/qs": "*", + "@types/range-parser": "*", + "@types/send": "*" + } + }, + "node_modules/@types/http-errors": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/@types/http-errors/-/http-errors-2.0.4.tgz", + "integrity": "sha512-D0CFMMtydbJAegzOyHjtiKPLlvnm3iTZyZRSZoLq2mRhDdmLfIWOCYPfQJ4cu2erKghU++QvjcUjp/5h7hESpA==", + "dev": true + }, + "node_modules/@types/mime": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/@types/mime/-/mime-1.3.5.tgz", + "integrity": "sha512-/pyBZWSLD2n0dcHE3hq8s8ZvcETHtEuF+3E7XVt0Ig2nvsVQXdghHVcEkIWjy9A0wKfTn97a/PSDYohKIlnP/w==", + "dev": true + }, + "node_modules/@types/multer": { + "version": "1.4.11", + "resolved": "https://registry.npmjs.org/@types/multer/-/multer-1.4.11.tgz", + "integrity": "sha512-svK240gr6LVWvv3YGyhLlA+6LRRWA4mnGIU7RcNmgjBYFl6665wcXrRfxGp5tEPVHUNm5FMcmq7too9bxCwX/w==", + "dev": true, + "dependencies": { + "@types/express": "*" + } + }, + "node_modules/@types/node": { + "version": "18.19.31", + "resolved": "https://registry.npmjs.org/@types/node/-/node-18.19.31.tgz", + "integrity": "sha512-ArgCD39YpyyrtFKIqMDvjz79jto5fcI/SVUs2HwB+f0dAzq68yqOdyaSivLiLugSziTpNXLQrVb7RZFmdZzbhA==", + "dependencies": { + "undici-types": "~5.26.4" + } + }, + "node_modules/@types/node-fetch": { + "version": "2.6.11", + "resolved": "https://registry.npmjs.org/@types/node-fetch/-/node-fetch-2.6.11.tgz", + "integrity": "sha512-24xFj9R5+rfQJLRyM56qh+wnVSYhyXC2tkoBndtY0U+vubqNsYXGjufB2nn8Q6gt0LrARwL6UBtMCSVCwl4B1g==", + "dependencies": { + "@types/node": "*", + "form-data": "^4.0.0" + } + }, + "node_modules/@types/qs": { + "version": "6.9.15", + "resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.9.15.tgz", + "integrity": "sha512-uXHQKES6DQKKCLh441Xv/dwxOq1TVS3JPUMlEqoEglvlhR6Mxnlew/Xq/LRVHpLyk7iK3zODe1qYHIMltO7XGg==", + "dev": true + }, + "node_modules/@types/range-parser": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/@types/range-parser/-/range-parser-1.2.7.tgz", + "integrity": "sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ==", + "dev": true + }, + "node_modules/@types/send": { + "version": "0.17.4", + "resolved": "https://registry.npmjs.org/@types/send/-/send-0.17.4.tgz", + "integrity": "sha512-x2EM6TJOybec7c52BX0ZspPodMsQUd5L6PRwOunVyVUhXiBSKf3AezDL8Dgvgt5o0UfKNfuA0eMLr2wLT4AiBA==", + "dev": true, + "dependencies": { + "@types/mime": "^1", + "@types/node": "*" + } + }, + "node_modules/@types/serve-static": { + "version": "1.15.7", + "resolved": "https://registry.npmjs.org/@types/serve-static/-/serve-static-1.15.7.tgz", + "integrity": "sha512-W8Ym+h8nhuRwaKPaDw34QUkwsGi6Rc4yYqvKFo5rm2FUEhCFbzVWrxXUxuKK8TASjWsysJY0nsmNCGhCOIsrOw==", + "dev": true, + "dependencies": { + "@types/http-errors": "*", + "@types/node": "*", + "@types/send": "*" + } + }, + "node_modules/abort-controller": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz", + "integrity": "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==", + "dependencies": { + "event-target-shim": "^5.0.0" + }, + "engines": { + "node": ">=6.5" + } + }, + "node_modules/accepts": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", + "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", + "dependencies": { + "mime-types": "~2.1.34", + "negotiator": "0.6.3" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/agentkeepalive": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/agentkeepalive/-/agentkeepalive-4.5.0.tgz", + "integrity": "sha512-5GG/5IbQQpC9FpkRGsSvZI5QYeSCzlJHdpBQntCsuTOxhKD8lqKhrleg2Yi7yvMIf82Ycmmqln9U8V9qwEiJew==", + "dependencies": { + "humanize-ms": "^1.2.1" + }, + "engines": { + "node": ">= 8.0.0" + } + }, + "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==" + }, + "node_modules/array-flatten": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", + "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==" + }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==" + }, + "node_modules/body-parser": { + "version": "1.20.2", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.2.tgz", + "integrity": "sha512-ml9pReCu3M61kGlqoTm2umSXTlRTuGTx0bfYj+uIUKKYycG5NtSbeetV3faSU6R7ajOPw0g/J1PvK4qNy7s5bA==", + "dependencies": { + "bytes": "3.1.2", + "content-type": "~1.0.5", + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "http-errors": "2.0.0", + "iconv-lite": "0.4.24", + "on-finished": "2.4.1", + "qs": "6.11.0", + "raw-body": "2.5.2", + "type-is": "~1.6.18", + "unpipe": "1.0.0" + }, + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "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==" + }, + "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==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.7.tgz", + "integrity": "sha512-GHTSNSYICQ7scH7sZ+M2rFopRoLh8t2bLSW6BbgrtLsahOIB5iyAVJf9GjWK3cYTDaMj4XdBpM1cA6pIS0Kv2w==", + "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "set-function-length": "^1.2.1" + }, + "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==", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/concat-stream": { + "version": "1.6.2", + "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-1.6.2.tgz", + "integrity": "sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw==", + "engines": [ + "node >= 0.8" + ], + "dependencies": { + "buffer-from": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^2.2.2", + "typedarray": "^0.0.6" + } + }, + "node_modules/content-disposition": { + "version": "0.5.4", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", + "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==", + "dependencies": { + "safe-buffer": "5.2.1" + }, + "engines": { + "node": ">= 0.6" + } + }, + "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==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.6.0.tgz", + "integrity": "sha512-U71cyTamuh1CRNCfpGY6to28lxvNwPG4Guz/EVjgf3Jmzv0vlDp1atT9eS5dDjMYHucpHbWns6Lwf3BKz6svdw==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", + "integrity": "sha512-QADzlaHc8icV8I7vbaJXJwod9HWYp8uCqf1xa4OfNu1T7JVxQIrUgOWtHdNDtPiywmFbiS12VjotIXLrKM3orQ==" + }, + "node_modules/core-util-is": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", + "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==" + }, + "node_modules/cors": { + "version": "2.8.5", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz", + "integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==", + "dependencies": { + "object-assign": "^4", + "vary": "^1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/define-data-property": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz", + "integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==", + "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "gopd": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "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==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/destroy": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", + "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==", + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "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==" + }, + "node_modules/encodeurl": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", + "integrity": "sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/es-define-property": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.0.tgz", + "integrity": "sha512-jxayLKShrEqqzJ0eumQbVhTYQM27CfT1T35+gCgDFoL82JLsXqTJ76zv6A0YLOgEnLUMvLzsDsGIrl8NFpT2gQ==", + "dependencies": { + "get-intrinsic": "^1.2.4" + }, + "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==", + "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==" + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/event-target-shim": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz", + "integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==", + "engines": { + "node": ">=6" + } + }, + "node_modules/express": { + "version": "4.19.2", + "resolved": "https://registry.npmjs.org/express/-/express-4.19.2.tgz", + "integrity": "sha512-5T6nhjsT+EOMzuck8JjBHARTHfMht0POzlA60WV2pMD3gyXw2LZnZ+ueGdNxG+0calOJcWKbpFcuzLZ91YWq9Q==", + "dependencies": { + "accepts": "~1.3.8", + "array-flatten": "1.1.1", + "body-parser": "1.20.2", + "content-disposition": "0.5.4", + "content-type": "~1.0.4", + "cookie": "0.6.0", + "cookie-signature": "1.0.6", + "debug": "2.6.9", + "depd": "2.0.0", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "finalhandler": "1.2.0", + "fresh": "0.5.2", + "http-errors": "2.0.0", + "merge-descriptors": "1.0.1", + "methods": "~1.1.2", + "on-finished": "2.4.1", + "parseurl": "~1.3.3", + "path-to-regexp": "0.1.7", + "proxy-addr": "~2.0.7", + "qs": "6.11.0", + "range-parser": "~1.2.1", + "safe-buffer": "5.2.1", + "send": "0.18.0", + "serve-static": "1.15.0", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "type-is": "~1.6.18", + "utils-merge": "1.0.1", + "vary": "~1.1.2" + }, + "engines": { + "node": ">= 0.10.0" + } + }, + "node_modules/finalhandler": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.2.0.tgz", + "integrity": "sha512-5uXcUVftlQMFnWC9qu/svkWv3GTd2PfUhK/3PLkYNAe7FbqJMt3515HaxE6eRL74GdsriiwujiawdaB1BpEISg==", + "dependencies": { + "debug": "2.6.9", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "on-finished": "2.4.1", + "parseurl": "~1.3.3", + "statuses": "2.0.1", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/form-data": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz", + "integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "mime-types": "^2.1.12" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/form-data-encoder": { + "version": "1.7.2", + "resolved": "https://registry.npmjs.org/form-data-encoder/-/form-data-encoder-1.7.2.tgz", + "integrity": "sha512-qfqtYan3rxrnCk1VYaA4H+Ms9xdpPqvLZa6xmMgFvhO32x7/3J/ExcTd6qpxM0vH2GdMI+poehyBZvqfMTto8A==" + }, + "node_modules/formdata-node": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/formdata-node/-/formdata-node-4.4.1.tgz", + "integrity": "sha512-0iirZp3uVDjVGt9p49aTaqjk84TrglENEDuqfdlZQ1roC9CWlPk6Avf8EEnZNcAqPonwkG35x4n3ww/1THYAeQ==", + "dependencies": { + "node-domexception": "1.0.0", + "web-streams-polyfill": "4.0.0-beta.3" + }, + "engines": { + "node": ">= 12.20" + } + }, + "node_modules/formdata-node/node_modules/web-streams-polyfill": { + "version": "4.0.0-beta.3", + "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-4.0.0-beta.3.tgz", + "integrity": "sha512-QW95TCTaHmsYfHDybGMwO5IJIM93I/6vTRk+daHTWFPhwh+C8Cg7j7XyKrwrj8Ib6vYXe0ocYNrmzY4xAAN6ug==", + "engines": { + "node": ">= 14" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", + "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==", + "engines": { + "node": ">= 0.6" + } + }, + "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==", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.4.tgz", + "integrity": "sha512-5uYhsJH8VJBTv7oslg4BznJYhDoRI6waYCxMmCdnTrcCrHA/fCFKoTFz2JKKE0HdDFUF7/oQuhzumXJK7paBRQ==", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "has-proto": "^1.0.1", + "has-symbols": "^1.0.3", + "hasown": "^2.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/gopd": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.0.1.tgz", + "integrity": "sha512-d65bNlIadxvpb/A2abVdlqKqV563juRnZ1Wtk6s1sIR8uNsXR70xqIzVqxVf1eTqDunwT2MkczEeaezCKTZhwA==", + "dependencies": { + "get-intrinsic": "^1.1.3" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-property-descriptors": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz", + "integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==", + "dependencies": { + "es-define-property": "^1.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-proto": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has-proto/-/has-proto-1.0.3.tgz", + "integrity": "sha512-SJ1amZAJUiZS+PhsVLf5tGydlaVB8EdFpaSO4gmiUKUOxk8qzn5AIy4ZeJUmh22znIdk/uMAUT2pl3FxzVUH+Q==", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.3.tgz", + "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/http-errors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz", + "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", + "dependencies": { + "depd": "2.0.0", + "inherits": "2.0.4", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "toidentifier": "1.0.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/humanize-ms": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/humanize-ms/-/humanize-ms-1.2.1.tgz", + "integrity": "sha512-Fl70vYtsAFb/C06PTS9dZBo7ihau+Tu/DNCk/OyHhea07S+aeMWpFFkUaXRa8fI+ScZbEI8dfSxwY7gxZ9SAVQ==", + "dependencies": { + "ms": "^2.0.0" + } + }, + "node_modules/iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" + }, + "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==", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==" + }, + "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==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/merge-descriptors": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz", + "integrity": "sha512-cCi6g3/Zr1iqQi6ySbseM1Xvooa98N0w31jzUYrXPX2xqObmFGHJ0tQ5u74H3mVh7wLouTseZyYIq39g8cNp1w==" + }, + "node_modules/methods": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", + "integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", + "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4" + } + }, + "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==", + "engines": { + "node": ">= 0.6" + } + }, + "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==", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/mkdirp": { + "version": "0.5.6", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.6.tgz", + "integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==", + "dependencies": { + "minimist": "^1.2.6" + }, + "bin": { + "mkdirp": "bin/cmd.js" + } + }, + "node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==" + }, + "node_modules/multer": { + "version": "1.4.5-lts.1", + "resolved": "https://registry.npmjs.org/multer/-/multer-1.4.5-lts.1.tgz", + "integrity": "sha512-ywPWvcDMeH+z9gQq5qYHCCy+ethsk4goepZ45GLD63fOu0YcNecQxi64nDs3qluZB+murG3/D4dJ7+dGctcCQQ==", + "dependencies": { + "append-field": "^1.0.0", + "busboy": "^1.0.0", + "concat-stream": "^1.5.2", + "mkdirp": "^0.5.4", + "object-assign": "^4.1.1", + "type-is": "^1.6.4", + "xtend": "^4.0.0" + }, + "engines": { + "node": ">= 6.0.0" + } + }, + "node_modules/negotiator": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", + "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/node-domexception": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz", + "integrity": "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + }, + { + "type": "github", + "url": "https://paypal.me/jimmywarting" + } + ], + "engines": { + "node": ">=10.5.0" + } + }, + "node_modules/node-fetch": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", + "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "engines": { + "node": "4.x || >=6.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-inspect": { + "version": "1.13.1", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.1.tgz", + "integrity": "sha512-5qoj1RUiKOMsCCNLV1CBiPYE10sziTsnmNxkAI/rZhiD63CF7IqdFGC/XzjWjpSgLf0LxXX3bDFIh0E18f6UhQ==", + "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==", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/openai": { + "version": "4.35.0", + "resolved": "https://registry.npmjs.org/openai/-/openai-4.35.0.tgz", + "integrity": "sha512-K8GY7k4h+dT2GSmn3JGSjkwElpo8cPa4eQ6p++uK1HSrrIBp6NalD3A3DIamvX1AnIyrKqe8M//HoQWgjntUiA==", + "dependencies": { + "@types/node": "^18.11.18", + "@types/node-fetch": "^2.6.4", + "abort-controller": "^3.0.0", + "agentkeepalive": "^4.2.1", + "form-data-encoder": "1.7.2", + "formdata-node": "^4.3.2", + "node-fetch": "^2.6.7", + "web-streams-polyfill": "^3.2.1" + }, + "bin": { + "openai": "bin/cli" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-to-regexp": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz", + "integrity": "sha512-5DFkuoqlv1uYQKxy8omFBeJPQcdoE07Kv2sferDCrAq1ohOU+MSDswDIbnx3YAM60qIOnYa53wBhXW0EbMonrQ==" + }, + "node_modules/process-nextick-args": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", + "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==" + }, + "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==", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/qs": { + "version": "6.11.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.11.0.tgz", + "integrity": "sha512-MvjoMCJwEarSbUYk5O+nmoSzSutSsTwF85zcHPQ9OrlFoZOYIjaqBAJIqIXjptyD5vThxGq52Xu/MaJzRkIk4Q==", + "dependencies": { + "side-channel": "^1.0.4" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "2.5.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.2.tgz", + "integrity": "sha512-8zGqypfENjCIqGhgXToC8aB2r7YrBX+AQAfIPs/Mlk+BtPTztOvTS01NRW/3Eh60J+a48lt8qsCzirQ6loCVfA==", + "dependencies": { + "bytes": "3.1.2", + "http-errors": "2.0.0", + "iconv-lite": "0.4.24", + "unpipe": "1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/readable-stream": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz", + "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/readable-stream/node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==" + }, + "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" + } + ] + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" + }, + "node_modules/send": { + "version": "0.18.0", + "resolved": "https://registry.npmjs.org/send/-/send-0.18.0.tgz", + "integrity": "sha512-qqWzuOjSFOuqPjFe4NOsMLafToQQwBSOEpS+FwEt3A2V3vKubTquT3vmLTQpFgMXp8AlFWFuP1qKaJZOtPpVXg==", + "dependencies": { + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "fresh": "0.5.2", + "http-errors": "2.0.0", + "mime": "1.6.0", + "ms": "2.1.3", + "on-finished": "2.4.1", + "range-parser": "~1.2.1", + "statuses": "2.0.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/send/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==" + }, + "node_modules/serve-static": { + "version": "1.15.0", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.15.0.tgz", + "integrity": "sha512-XGuRDNjXUijsUL0vl6nSD7cwURuzEgglbOaFuZM9g3kwDXOWVTck0jLzjPzGD+TazWbboZYu52/9/XPdUgne9g==", + "dependencies": { + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "parseurl": "~1.3.3", + "send": "0.18.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/set-function-length": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz", + "integrity": "sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==", + "dependencies": { + "define-data-property": "^1.1.4", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "gopd": "^1.0.1", + "has-property-descriptors": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==" + }, + "node_modules/side-channel": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.6.tgz", + "integrity": "sha512-fDW/EZ6Q9RiO8eFG8Hj+7u/oW+XrPTIChwCOM2+th2A6OblDtYYIpve9m+KvI9Z4C9qSEXlaGR6bTEYHReuglA==", + "dependencies": { + "call-bind": "^1.0.7", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.4", + "object-inspect": "^1.13.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/statuses": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", + "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", + "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.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, + "node_modules/string_decoder/node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==" + }, + "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==", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/tr46": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", + "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==" + }, + "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==", + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + }, + "engines": { + "node": ">= 0.6" + } + }, + "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==" + }, + "node_modules/undici-types": { + "version": "5.26.5", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz", + "integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==" + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "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==" + }, + "node_modules/utils-merge": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", + "integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==", + "engines": { + "node": ">= 0.4.0" + } + }, + "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==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/web-streams-polyfill": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.3.3.tgz", + "integrity": "sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==", + "engines": { + "node": ">= 8" + } + }, + "node_modules/webidl-conversions": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", + "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==" + }, + "node_modules/whatwg-url": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", + "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + } + }, + "node_modules/xtend": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", + "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==", + "engines": { + "node": ">=0.4" + } + } + } +} diff --git a/backend/node_modules/@types/body-parser/LICENSE b/backend/node_modules/@types/body-parser/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/backend/node_modules/@types/body-parser/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/backend/node_modules/@types/body-parser/README.md b/backend/node_modules/@types/body-parser/README.md new file mode 100644 index 0000000000000000000000000000000000000000..0d280422c67c455f60b2e3a38b8ffcf61f499845 --- /dev/null +++ b/backend/node_modules/@types/body-parser/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/body-parser` + +# Summary +This package contains type definitions for body-parser (https://github.com/expressjs/body-parser). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/body-parser. + +### Additional Details + * Last updated: Mon, 06 Nov 2023 22:41:05 GMT + * Dependencies: [@types/connect](https://npmjs.com/package/@types/connect), [@types/node](https://npmjs.com/package/@types/node) + +# Credits +These definitions were written by [Santi Albo](https://github.com/santialbo), [Vilic Vane](https://github.com/vilic), [Jonathan Häberle](https://github.com/dreampulse), [Gevik Babakhani](https://github.com/blendsdk), [Tomasz Łaziuk](https://github.com/tlaziuk), [Jason Walton](https://github.com/jwalton), and [Piotr Błażejewicz](https://github.com/peterblazejewicz). diff --git a/backend/node_modules/@types/body-parser/index.d.ts b/backend/node_modules/@types/body-parser/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..96feda8227381251f826ebc70b70b3ee18bffe94 --- /dev/null +++ b/backend/node_modules/@types/body-parser/index.d.ts @@ -0,0 +1,95 @@ +/// + +import { NextHandleFunction } from "connect"; +import * as http from "http"; + +// for docs go to https://github.com/expressjs/body-parser/tree/1.19.0#body-parser + +declare namespace bodyParser { + interface BodyParser { + /** + * @deprecated use individual json/urlencoded middlewares + */ + (options?: OptionsJson & OptionsText & OptionsUrlencoded): NextHandleFunction; + /** + * Returns middleware that only parses json and only looks at requests + * where the Content-Type header matches the type option. + */ + json(options?: OptionsJson): NextHandleFunction; + /** + * Returns middleware that parses all bodies as a Buffer and only looks at requests + * where the Content-Type header matches the type option. + */ + raw(options?: Options): NextHandleFunction; + + /** + * Returns middleware that parses all bodies as a string and only looks at requests + * where the Content-Type header matches the type option. + */ + text(options?: OptionsText): NextHandleFunction; + /** + * Returns middleware that only parses urlencoded bodies and only looks at requests + * where the Content-Type header matches the type option + */ + urlencoded(options?: OptionsUrlencoded): NextHandleFunction; + } + + interface Options { + /** When set to true, then deflated (compressed) bodies will be inflated; when false, deflated bodies are rejected. Defaults to true. */ + inflate?: boolean | undefined; + /** + * 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 library for parsing. Defaults to '100kb'. + */ + limit?: number | string | undefined; + /** + * The type option is used to determine what media type the middleware will parse + */ + type?: string | string[] | ((req: http.IncomingMessage) => any) | undefined; + /** + * 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. + */ + verify?(req: http.IncomingMessage, res: http.ServerResponse, buf: Buffer, encoding: string): void; + } + + interface OptionsJson extends Options { + /** + * The reviver option is passed directly to JSON.parse as the second argument. + */ + reviver?(key: string, value: any): any; + /** + * When set to `true`, will only accept arrays and objects; + * when `false` will accept anything JSON.parse accepts. Defaults to `true`. + */ + strict?: boolean | undefined; + } + + interface OptionsText extends Options { + /** + * 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`. + */ + defaultCharset?: string | undefined; + } + + interface OptionsUrlencoded extends Options { + /** + * The extended option allows to choose between parsing the URL-encoded data + * with the querystring library (when `false`) or the qs library (when `true`). + */ + extended?: boolean | undefined; + /** + * 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. + */ + parameterLimit?: number | undefined; + } +} + +declare const bodyParser: bodyParser.BodyParser; + +export = bodyParser; diff --git a/backend/node_modules/@types/body-parser/package.json b/backend/node_modules/@types/body-parser/package.json new file mode 100644 index 0000000000000000000000000000000000000000..71f1218dfd5c12e16c563223e4b88c89ac097933 --- /dev/null +++ b/backend/node_modules/@types/body-parser/package.json @@ -0,0 +1,58 @@ +{ + "name": "@types/body-parser", + "version": "1.19.5", + "description": "TypeScript definitions for body-parser", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/body-parser", + "license": "MIT", + "contributors": [ + { + "name": "Santi Albo", + "githubUsername": "santialbo", + "url": "https://github.com/santialbo" + }, + { + "name": "Vilic Vane", + "githubUsername": "vilic", + "url": "https://github.com/vilic" + }, + { + "name": "Jonathan Häberle", + "githubUsername": "dreampulse", + "url": "https://github.com/dreampulse" + }, + { + "name": "Gevik Babakhani", + "githubUsername": "blendsdk", + "url": "https://github.com/blendsdk" + }, + { + "name": "Tomasz Łaziuk", + "githubUsername": "tlaziuk", + "url": "https://github.com/tlaziuk" + }, + { + "name": "Jason Walton", + "githubUsername": "jwalton", + "url": "https://github.com/jwalton" + }, + { + "name": "Piotr Błażejewicz", + "githubUsername": "peterblazejewicz", + "url": "https://github.com/peterblazejewicz" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/body-parser" + }, + "scripts": {}, + "dependencies": { + "@types/connect": "*", + "@types/node": "*" + }, + "typesPublisherContentHash": "7be737b78c8aabd5436be840558b283182b44c3cf9da24fb1f2ff8f414db5802", + "typeScriptVersion": "4.5" +} \ No newline at end of file diff --git a/backend/node_modules/@types/connect/LICENSE b/backend/node_modules/@types/connect/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/backend/node_modules/@types/connect/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/backend/node_modules/@types/connect/README.md b/backend/node_modules/@types/connect/README.md new file mode 100644 index 0000000000000000000000000000000000000000..1746fab041cf010a873df90aa8b34561e4f08b5f --- /dev/null +++ b/backend/node_modules/@types/connect/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/connect` + +# Summary +This package contains type definitions for connect (https://github.com/senchalabs/connect). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/connect. + +### Additional Details + * Last updated: Mon, 06 Nov 2023 22:41:05 GMT + * Dependencies: [@types/node](https://npmjs.com/package/@types/node) + +# Credits +These definitions were written by [Maxime LUCE](https://github.com/SomaticIT), and [Evan Hahn](https://github.com/EvanHahn). diff --git a/backend/node_modules/@types/connect/index.d.ts b/backend/node_modules/@types/connect/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8355d781a4b678f8d2fe260d180ae3522446bc6c --- /dev/null +++ b/backend/node_modules/@types/connect/index.d.ts @@ -0,0 +1,91 @@ +/// + +import * as http from "http"; + +/** + * Create a new connect server. + */ +declare function createServer(): createServer.Server; + +declare namespace createServer { + export type ServerHandle = HandleFunction | http.Server; + + export class IncomingMessage extends http.IncomingMessage { + originalUrl?: http.IncomingMessage["url"] | undefined; + } + + type NextFunction = (err?: any) => void; + + export type SimpleHandleFunction = (req: IncomingMessage, res: http.ServerResponse) => void; + export type NextHandleFunction = (req: IncomingMessage, res: http.ServerResponse, next: NextFunction) => void; + export type ErrorHandleFunction = ( + err: any, + req: IncomingMessage, + res: http.ServerResponse, + next: NextFunction, + ) => void; + export type HandleFunction = SimpleHandleFunction | NextHandleFunction | ErrorHandleFunction; + + export interface ServerStackItem { + route: string; + handle: ServerHandle; + } + + export interface Server extends NodeJS.EventEmitter { + (req: http.IncomingMessage, res: http.ServerResponse, next?: Function): void; + + route: string; + stack: ServerStackItem[]; + + /** + * Utilize the given middleware `handle` to the given `route`, + * defaulting to _/_. This "route" is the mount-point for the + * middleware, when given a value other than _/_ the middleware + * is only effective when that segment is present in the request's + * pathname. + * + * For example if we were to mount a function at _/admin_, it would + * be invoked on _/admin_, and _/admin/settings_, however it would + * not be invoked for _/_, or _/posts_. + */ + use(fn: NextHandleFunction): Server; + use(fn: HandleFunction): Server; + use(route: string, fn: NextHandleFunction): Server; + use(route: string, fn: HandleFunction): Server; + + /** + * Handle server requests, punting them down + * the middleware stack. + */ + handle(req: http.IncomingMessage, res: http.ServerResponse, next: Function): void; + + /** + * Listen for connections. + * + * This method takes the same arguments + * as node's `http.Server#listen()`. + * + * HTTP and HTTPS: + * + * If you run your application both as HTTP + * and HTTPS you may wrap them individually, + * since your Connect "server" is really just + * a JavaScript `Function`. + * + * var connect = require('connect') + * , http = require('http') + * , https = require('https'); + * + * var app = connect(); + * + * http.createServer(app).listen(80); + * https.createServer(options, app).listen(443); + */ + listen(port: number, hostname?: string, backlog?: number, callback?: Function): http.Server; + listen(port: number, hostname?: string, callback?: Function): http.Server; + listen(path: string, callback?: Function): http.Server; + listen(handle: any, listeningListener?: Function): http.Server; + } +} + +export = createServer; diff --git a/backend/node_modules/@types/connect/package.json b/backend/node_modules/@types/connect/package.json new file mode 100644 index 0000000000000000000000000000000000000000..207078e56ca3258219af0367008602c2ea46ef17 --- /dev/null +++ b/backend/node_modules/@types/connect/package.json @@ -0,0 +1,32 @@ +{ + "name": "@types/connect", + "version": "3.4.38", + "description": "TypeScript definitions for connect", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/connect", + "license": "MIT", + "contributors": [ + { + "name": "Maxime LUCE", + "githubUsername": "SomaticIT", + "url": "https://github.com/SomaticIT" + }, + { + "name": "Evan Hahn", + "githubUsername": "EvanHahn", + "url": "https://github.com/EvanHahn" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/connect" + }, + "scripts": {}, + "dependencies": { + "@types/node": "*" + }, + "typesPublisherContentHash": "8990242237504bdec53088b79e314b94bec69286df9de56db31f22de403b4092", + "typeScriptVersion": "4.5" +} \ No newline at end of file diff --git a/backend/node_modules/@types/express-serve-static-core/LICENSE b/backend/node_modules/@types/express-serve-static-core/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/backend/node_modules/@types/express-serve-static-core/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/backend/node_modules/@types/express-serve-static-core/README.md b/backend/node_modules/@types/express-serve-static-core/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d4473c08124fa4f8d021c9283520ad7498524402 --- /dev/null +++ b/backend/node_modules/@types/express-serve-static-core/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/express-serve-static-core` + +# Summary +This package contains type definitions for express-serve-static-core (http://expressjs.com). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/express-serve-static-core. + +### Additional Details + * Last updated: Thu, 04 Apr 2024 22:35:44 GMT + * Dependencies: [@types/node](https://npmjs.com/package/@types/node), [@types/qs](https://npmjs.com/package/@types/qs), [@types/range-parser](https://npmjs.com/package/@types/range-parser), [@types/send](https://npmjs.com/package/@types/send) + +# Credits +These definitions were written by [Boris Yankov](https://github.com/borisyankov), [Satana Charuwichitratana](https://github.com/micksatana), [Sami Jaber](https://github.com/samijaber), [Jose Luis Leon](https://github.com/JoseLion), [David Stephens](https://github.com/dwrss), and [Shin Ando](https://github.com/andoshin11). diff --git a/backend/node_modules/@types/express-serve-static-core/index.d.ts b/backend/node_modules/@types/express-serve-static-core/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..486fe2840ddd69c64ea5426e399254808120d04c --- /dev/null +++ b/backend/node_modules/@types/express-serve-static-core/index.d.ts @@ -0,0 +1,1284 @@ +// This extracts the core definitions from express to prevent a circular dependency between express and serve-static +/// + +import { SendOptions } from "send"; + +declare global { + namespace Express { + // These open interfaces may be extended in an application-specific manner via declaration merging. + // See for example method-override.d.ts (https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/method-override/index.d.ts) + interface Request {} + interface Response {} + interface Locals {} + interface Application {} + } +} + +import { EventEmitter } from "events"; +import * as http from "http"; +import { ParsedQs } from "qs"; +import { Options as RangeParserOptions, Ranges as RangeParserRanges, Result as RangeParserResult } from "range-parser"; + +export {}; + +export type Query = ParsedQs; + +export interface NextFunction { + (err?: any): void; + /** + * "Break-out" of a router by calling {next('router')}; + * @see {https://expressjs.com/en/guide/using-middleware.html#middleware.router} + */ + (deferToNext: "router"): void; + /** + * "Break-out" of a route by calling {next('route')}; + * @see {https://expressjs.com/en/guide/using-middleware.html#middleware.application} + */ + (deferToNext: "route"): void; +} + +export interface Dictionary { + [key: string]: T; +} + +export interface ParamsDictionary { + [key: string]: string; +} +export type ParamsArray = string[]; +export type Params = ParamsDictionary | ParamsArray; + +export interface Locals extends Express.Locals {} + +export interface RequestHandler< + P = ParamsDictionary, + ResBody = any, + ReqBody = any, + ReqQuery = ParsedQs, + LocalsObj extends Record = Record, +> { + // tslint:disable-next-line callable-types (This is extended from and can't extend from a type alias in ts<2.2) + ( + req: Request, + res: Response, + next: NextFunction, + ): void; +} + +export type ErrorRequestHandler< + P = ParamsDictionary, + ResBody = any, + ReqBody = any, + ReqQuery = ParsedQs, + LocalsObj extends Record = Record, +> = ( + err: any, + req: Request, + res: Response, + next: NextFunction, +) => void; + +export type PathParams = string | RegExp | Array; + +export type RequestHandlerParams< + P = ParamsDictionary, + ResBody = any, + ReqBody = any, + ReqQuery = ParsedQs, + LocalsObj extends Record = Record, +> = + | RequestHandler + | ErrorRequestHandler + | Array | ErrorRequestHandler

>; + +type RemoveTail = S extends `${infer P}${Tail}` ? P : S; +type GetRouteParameter = RemoveTail< + RemoveTail, `-${string}`>, + `.${string}` +>; + +// prettier-ignore +export type RouteParameters = string extends Route ? ParamsDictionary + : Route extends `${string}(${string}` ? ParamsDictionary // TODO: handling for regex parameters + : Route extends `${string}:${infer Rest}` ? + & ( + GetRouteParameter extends never ? ParamsDictionary + : GetRouteParameter extends `${infer ParamName}?` ? { [P in ParamName]?: string } + : { [P in GetRouteParameter]: string } + ) + & (Rest extends `${GetRouteParameter}${infer Next}` ? RouteParameters : unknown) + : {}; + +/* eslint-disable @definitelytyped/no-unnecessary-generics */ +export interface IRouterMatcher< + T, + Method extends "all" | "get" | "post" | "put" | "delete" | "patch" | "options" | "head" = any, +> { + < + Route extends string, + P = RouteParameters, + ResBody = any, + ReqBody = any, + ReqQuery = ParsedQs, + LocalsObj extends Record = Record, + >( + // (it's used as the default type parameter for P) + path: Route, + // (This generic is meant to be passed explicitly.) + ...handlers: Array> + ): T; + < + Path extends string, + P = RouteParameters, + ResBody = any, + ReqBody = any, + ReqQuery = ParsedQs, + LocalsObj extends Record = Record, + >( + // (it's used as the default type parameter for P) + path: Path, + // (This generic is meant to be passed explicitly.) + ...handlers: Array> + ): T; + < + P = ParamsDictionary, + ResBody = any, + ReqBody = any, + ReqQuery = ParsedQs, + LocalsObj extends Record = Record, + >( + path: PathParams, + // (This generic is meant to be passed explicitly.) + ...handlers: Array> + ): T; + < + P = ParamsDictionary, + ResBody = any, + ReqBody = any, + ReqQuery = ParsedQs, + LocalsObj extends Record = Record, + >( + path: PathParams, + // (This generic is meant to be passed explicitly.) + ...handlers: Array> + ): T; + (path: PathParams, subApplication: Application): T; +} + +export interface IRouterHandler { + (...handlers: Array>>): T; + (...handlers: Array>>): T; + < + P = RouteParameters, + ResBody = any, + ReqBody = any, + ReqQuery = ParsedQs, + LocalsObj extends Record = Record, + >( + // (This generic is meant to be passed explicitly.) + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + ...handlers: Array> + ): T; + < + P = RouteParameters, + ResBody = any, + ReqBody = any, + ReqQuery = ParsedQs, + LocalsObj extends Record = Record, + >( + // (This generic is meant to be passed explicitly.) + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + ...handlers: Array> + ): T; + < + P = ParamsDictionary, + ResBody = any, + ReqBody = any, + ReqQuery = ParsedQs, + LocalsObj extends Record = Record, + >( + // (This generic is meant to be passed explicitly.) + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + ...handlers: Array> + ): T; + < + P = ParamsDictionary, + ResBody = any, + ReqBody = any, + ReqQuery = ParsedQs, + LocalsObj extends Record = Record, + >( + // (This generic is meant to be passed explicitly.) + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + ...handlers: Array> + ): T; +} +/* eslint-enable @definitelytyped/no-unnecessary-generics */ + +export interface IRouter extends RequestHandler { + /** + * Map the given param placeholder `name`(s) to the given callback(s). + * + * Parameter mapping is used to provide pre-conditions to routes + * which use normalized placeholders. For example a _:user_id_ parameter + * could automatically load a user's information from the database without + * any additional code, + * + * The callback uses the samesignature as middleware, the only differencing + * being that the value of the placeholder is passed, in this case the _id_ + * of the user. Once the `next()` function is invoked, just like middleware + * it will continue on to execute the route, or subsequent parameter functions. + * + * app.param('user_id', function(req, res, next, id){ + * User.find(id, function(err, user){ + * if (err) { + * next(err); + * } else if (user) { + * req.user = user; + * next(); + * } else { + * next(new Error('failed to load user')); + * } + * }); + * }); + */ + param(name: string, handler: RequestParamHandler): this; + + /** + * Alternatively, you can pass only a callback, in which case you have the opportunity to alter the app.param() + * + * @deprecated since version 4.11 + */ + param(callback: (name: string, matcher: RegExp) => RequestParamHandler): this; + + /** + * Special-cased "all" method, applying the given route `path`, + * middleware, and callback to _every_ HTTP method. + */ + all: IRouterMatcher; + get: IRouterMatcher; + post: IRouterMatcher; + put: IRouterMatcher; + delete: IRouterMatcher; + patch: IRouterMatcher; + options: IRouterMatcher; + head: IRouterMatcher; + + checkout: IRouterMatcher; + connect: IRouterMatcher; + copy: IRouterMatcher; + lock: IRouterMatcher; + merge: IRouterMatcher; + mkactivity: IRouterMatcher; + mkcol: IRouterMatcher; + move: IRouterMatcher; + "m-search": IRouterMatcher; + notify: IRouterMatcher; + propfind: IRouterMatcher; + proppatch: IRouterMatcher; + purge: IRouterMatcher; + report: IRouterMatcher; + search: IRouterMatcher; + subscribe: IRouterMatcher; + trace: IRouterMatcher; + unlock: IRouterMatcher; + unsubscribe: IRouterMatcher; + link: IRouterMatcher; + unlink: IRouterMatcher; + + use: IRouterHandler & IRouterMatcher; + + route(prefix: T): IRoute; + route(prefix: PathParams): IRoute; + /** + * Stack of configured routes + */ + stack: any[]; +} + +export interface IRoute { + path: string; + stack: any; + all: IRouterHandler; + get: IRouterHandler; + post: IRouterHandler; + put: IRouterHandler; + delete: IRouterHandler; + patch: IRouterHandler; + options: IRouterHandler; + head: IRouterHandler; + + checkout: IRouterHandler; + copy: IRouterHandler; + lock: IRouterHandler; + merge: IRouterHandler; + mkactivity: IRouterHandler; + mkcol: IRouterHandler; + move: IRouterHandler; + "m-search": IRouterHandler; + notify: IRouterHandler; + purge: IRouterHandler; + report: IRouterHandler; + search: IRouterHandler; + subscribe: IRouterHandler; + trace: IRouterHandler; + unlock: IRouterHandler; + unsubscribe: IRouterHandler; +} + +export interface Router extends IRouter {} + +/** + * Options passed down into `res.cookie` + * @link https://expressjs.com/en/api.html#res.cookie + */ +export interface CookieOptions { + /** Convenient option for setting the expiry time relative to the current time in **milliseconds**. */ + maxAge?: number | undefined; + /** Indicates if the cookie should be signed. */ + signed?: boolean | undefined; + /** Expiry date of the cookie in GMT. If not specified or set to 0, creates a session cookie. */ + expires?: Date | undefined; + /** Flags the cookie to be accessible only by the web server. */ + httpOnly?: boolean | undefined; + /** Path for the cookie. Defaults to “/”. */ + path?: string | undefined; + /** Domain name for the cookie. Defaults to the domain name of the app. */ + domain?: string | undefined; + /** Marks the cookie to be used with HTTPS only. */ + secure?: boolean | undefined; + /** A synchronous function used for cookie value encoding. Defaults to encodeURIComponent. */ + encode?: ((val: string) => string) | undefined; + /** + * Value of the “SameSite” Set-Cookie attribute. + * @link https://tools.ietf.org/html/draft-ietf-httpbis-cookie-same-site-00#section-4.1.1. + */ + sameSite?: boolean | "lax" | "strict" | "none" | undefined; + /** + * Value of the “Priority” Set-Cookie attribute. + * @link https://datatracker.ietf.org/doc/html/draft-west-cookie-priority-00#section-4.3 + */ + priority?: "low" | "medium" | "high"; + /** Marks the cookie to use partioned storage. */ + partitioned?: boolean | undefined; +} + +export interface ByteRange { + start: number; + end: number; +} + +export interface RequestRanges extends RangeParserRanges {} + +export type Errback = (err: Error) => void; + +/** + * @param P For most requests, this should be `ParamsDictionary`, but if you're + * using this in a route handler for a route that uses a `RegExp` or a wildcard + * `string` path (e.g. `'/user/*'`), then `req.params` will be an array, in + * which case you should use `ParamsArray` instead. + * + * @see https://expressjs.com/en/api.html#req.params + * + * @example + * app.get('/user/:id', (req, res) => res.send(req.params.id)); // implicitly `ParamsDictionary` + * app.get(/user\/(.*)/, (req, res) => res.send(req.params[0])); + * app.get('/user/*', (req, res) => res.send(req.params[0])); + */ +export interface Request< + P = ParamsDictionary, + ResBody = any, + ReqBody = any, + ReqQuery = ParsedQs, + LocalsObj extends Record = Record, +> extends http.IncomingMessage, Express.Request { + /** + * Return request header. + * + * The `Referrer` header field is special-cased, + * both `Referrer` and `Referer` are interchangeable. + * + * Examples: + * + * req.get('Content-Type'); + * // => "text/plain" + * + * req.get('content-type'); + * // => "text/plain" + * + * req.get('Something'); + * // => undefined + * + * Aliased as `req.header()`. + */ + get(name: "set-cookie"): string[] | undefined; + get(name: string): string | undefined; + + header(name: "set-cookie"): string[] | undefined; + header(name: string): string | undefined; + + /** + * 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", a comma-delimted list such as "json, html, text/plain", + * 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 + * req.accepts('html'); + * // => "html" + * + * // Accept: text/*, application/json + * req.accepts('html'); + * // => "html" + * req.accepts('text/html'); + * // => "text/html" + * req.accepts('json, text'); + * // => "json" + * req.accepts('application/json'); + * // => "application/json" + * + * // Accept: text/*, application/json + * req.accepts('image/png'); + * req.accepts('png'); + * // => false + * + * // Accept: text/*;q=.5, application/json + * req.accepts(['html', 'json']); + * req.accepts('html, json'); + * // => "json" + */ + accepts(): string[]; + accepts(type: string): string | false; + accepts(type: string[]): string | false; + accepts(...type: string[]): string | false; + + /** + * Returns the first accepted charset of the specified character sets, + * based on the request's Accept-Charset HTTP header field. + * If none of the specified charsets is accepted, returns false. + * + * For more information, or if you have issues or concerns, see accepts. + */ + acceptsCharsets(): string[]; + acceptsCharsets(charset: string): string | false; + acceptsCharsets(charset: string[]): string | false; + acceptsCharsets(...charset: string[]): string | false; + + /** + * Returns the first accepted encoding of the specified encodings, + * based on the request's Accept-Encoding HTTP header field. + * If none of the specified encodings is accepted, returns false. + * + * For more information, or if you have issues or concerns, see accepts. + */ + acceptsEncodings(): string[]; + acceptsEncodings(encoding: string): string | false; + acceptsEncodings(encoding: string[]): string | false; + acceptsEncodings(...encoding: string[]): string | false; + + /** + * Returns the first accepted language of the specified languages, + * based on the request's Accept-Language HTTP header field. + * If none of the specified languages is accepted, returns false. + * + * For more information, or if you have issues or concerns, see accepts. + */ + acceptsLanguages(): string[]; + acceptsLanguages(lang: string): string | false; + acceptsLanguages(lang: string[]): string | false; + acceptsLanguages(...lang: string[]): string | false; + + /** + * Parse Range header field, capping to the given `size`. + * + * Unspecified ranges such as "0-" require knowledge of your resource length. In + * the case of a byte range this is of course the total number of bytes. + * If the Range header field is not given `undefined` is returned. + * If the Range header field is given, return value is a result of range-parser. + * See more ./types/range-parser/index.d.ts + * + * NOTE: remember that ranges are inclusive, so for example "Range: users=0-3" + * should respond with 4 users when available, not 3. + */ + range(size: number, options?: RangeParserOptions): RangeParserRanges | RangeParserResult | undefined; + + /** + * Return an array of Accepted media types + * ordered from highest quality to lowest. + */ + accepted: MediaType[]; + + /** + * @deprecated since 4.11 Use either req.params, req.body or req.query, as applicable. + * + * Return the value of param `name` when present or `defaultValue`. + * + * - Checks route placeholders, ex: _/user/:id_ + * - Checks body params, ex: id=12, {"id":12} + * - Checks query string params, ex: ?id=12 + * + * To utilize request bodies, `req.body` + * should be an object. This can be done by using + * the `connect.bodyParser()` middleware. + */ + param(name: string, defaultValue?: any): string; + + /** + * Check if the incoming request contains the "Content-Type" + * header field, and it contains the give mime `type`. + * + * Examples: + * + * // With Content-Type: text/html; charset=utf-8 + * req.is('html'); + * req.is('text/html'); + * req.is('text/*'); + * // => true + * + * // When Content-Type is application/json + * req.is('json'); + * req.is('application/json'); + * req.is('application/*'); + * // => true + * + * req.is('html'); + * // => false + */ + is(type: string | string[]): string | false | null; + + /** + * Return the protocol string "http" or "https" + * when requested with TLS. When the "trust proxy" + * setting is enabled the "X-Forwarded-Proto" header + * field will be trusted. If you're running behind + * a reverse proxy that supplies https for you this + * may be enabled. + */ + protocol: string; + + /** + * Short-hand for: + * + * req.protocol == 'https' + */ + secure: boolean; + + /** + * Return the remote address, or when + * "trust proxy" is `true` return + * the upstream addr. + * + * Value may be undefined if the `req.socket` is destroyed + * (for example, if the client disconnected). + */ + ip: string | undefined; + + /** + * When "trust proxy" is `true`, parse + * the "X-Forwarded-For" ip address list. + * + * For example if the value were "client, proxy1, proxy2" + * you would receive the array `["client", "proxy1", "proxy2"]` + * where "proxy2" is the furthest down-stream. + */ + ips: string[]; + + /** + * Return subdomains as an array. + * + * Subdomains are the dot-separated parts of the host before the main domain of + * the app. By default, the domain of the app is assumed to be the last two + * parts of the host. This can be changed by setting "subdomain offset". + * + * For example, if the domain is "tobi.ferrets.example.com": + * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`. + * If "subdomain offset" is 3, req.subdomains is `["tobi"]`. + */ + subdomains: string[]; + + /** + * Short-hand for `url.parse(req.url).pathname`. + */ + path: string; + + /** + * Parse the "Host" header field hostname. + */ + hostname: string; + + /** + * @deprecated Use hostname instead. + */ + host: string; + + /** + * Check if the request is fresh, aka + * Last-Modified and/or the ETag + * still match. + */ + fresh: boolean; + + /** + * Check if the request is stale, aka + * "Last-Modified" and / or the "ETag" for the + * resource has changed. + */ + stale: boolean; + + /** + * Check if the request was an _XMLHttpRequest_. + */ + xhr: boolean; + + // body: { username: string; password: string; remember: boolean; title: string; }; + body: ReqBody; + + // cookies: { string; remember: boolean; }; + cookies: any; + + method: string; + + params: P; + + query: ReqQuery; + + route: any; + + signedCookies: any; + + originalUrl: string; + + url: string; + + baseUrl: string; + + app: Application; + + /** + * After middleware.init executed, Request will contain res and next properties + * See: express/lib/middleware/init.js + */ + res?: Response | undefined; + next?: NextFunction | undefined; +} + +export interface MediaType { + value: string; + quality: number; + type: string; + subtype: string; +} + +export type Send> = (body?: ResBody) => T; + +export interface SendFileOptions extends SendOptions { + /** Object containing HTTP headers to serve with the file. */ + headers?: Record; +} + +export interface DownloadOptions extends SendOptions { + /** Object containing HTTP headers to serve with the file. The header `Content-Disposition` will be overridden by the filename argument. */ + headers?: Record; +} + +export interface Response< + ResBody = any, + LocalsObj extends Record = Record, + StatusCode extends number = number, +> extends http.ServerResponse, Express.Response { + /** + * Set status `code`. + */ + status(code: StatusCode): this; + + /** + * Set the response HTTP status code to `statusCode` and send its string representation as the response body. + * @link http://expressjs.com/4x/api.html#res.sendStatus + * + * Examples: + * + * res.sendStatus(200); // equivalent to res.status(200).send('OK') + * res.sendStatus(403); // equivalent to res.status(403).send('Forbidden') + * res.sendStatus(404); // equivalent to res.status(404).send('Not Found') + * res.sendStatus(500); // equivalent to res.status(500).send('Internal Server Error') + */ + sendStatus(code: StatusCode): this; + + /** + * Set Link header field with the given `links`. + * + * Examples: + * + * res.links({ + * next: 'http://api.example.com/users?page=2', + * last: 'http://api.example.com/users?page=5' + * }); + */ + links(links: any): this; + + /** + * Send a response. + * + * Examples: + * + * res.send(new Buffer('wahoo')); + * res.send({ some: 'json' }); + * res.send('

some html

'); + * res.status(404).send('Sorry, cant find that'); + */ + send: Send; + + /** + * Send JSON response. + * + * Examples: + * + * res.json(null); + * res.json({ user: 'tj' }); + * res.status(500).json('oh noes!'); + * res.status(404).json('I dont have that'); + */ + json: Send; + + /** + * Send JSON response with JSONP callback support. + * + * Examples: + * + * res.jsonp(null); + * res.jsonp({ user: 'tj' }); + * res.status(500).jsonp('oh noes!'); + * res.status(404).jsonp('I dont have that'); + */ + jsonp: Send; + + /** + * Transfer the file at the given `path`. + * + * Automatically sets the _Content-Type_ response header field. + * The callback `fn(err)` is invoked when the transfer is complete + * or when an error occurs. Be sure to check `res.headersSent` + * if you wish to attempt responding, as the header and some data + * may have already been transferred. + * + * Options: + * + * - `maxAge` defaulting to 0 (can be string converted by `ms`) + * - `root` root directory for relative filenames + * - `headers` object of headers to serve with file + * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them + * + * Other options are passed along to `send`. + * + * Examples: + * + * The following example illustrates how `res.sendFile()` may + * be used as an alternative for the `static()` middleware for + * dynamic situations. The code backing `res.sendFile()` is actually + * the same code, so HTTP cache support etc is identical. + * + * app.get('/user/:uid/photos/:file', function(req, res){ + * var uid = req.params.uid + * , file = req.params.file; + * + * req.user.mayViewFilesFrom(uid, function(yes){ + * if (yes) { + * res.sendFile('/uploads/' + uid + '/' + file); + * } else { + * res.send(403, 'Sorry! you cant see that.'); + * } + * }); + * }); + * + * @api public + */ + sendFile(path: string, fn?: Errback): void; + sendFile(path: string, options: SendFileOptions, fn?: Errback): void; + + /** + * @deprecated Use sendFile instead. + */ + sendfile(path: string): void; + /** + * @deprecated Use sendFile instead. + */ + sendfile(path: string, options: SendFileOptions): void; + /** + * @deprecated Use sendFile instead. + */ + sendfile(path: string, fn: Errback): void; + /** + * @deprecated Use sendFile instead. + */ + sendfile(path: string, options: SendFileOptions, fn: Errback): void; + + /** + * Transfer the file at the given `path` as an attachment. + * + * Optionally providing an alternate attachment `filename`, + * and optional callback `fn(err)`. The callback is invoked + * when the data transfer is complete, or when an error has + * ocurred. Be sure to check `res.headersSent` if you plan to respond. + * + * The optional options argument passes through to the underlying + * res.sendFile() call, and takes the exact same parameters. + * + * This method uses `res.sendfile()`. + */ + download(path: string, fn?: Errback): void; + download(path: string, filename: string, fn?: Errback): void; + download(path: string, filename: string, options: DownloadOptions, fn?: Errback): void; + + /** + * Set _Content-Type_ response header with `type` through `mime.lookup()` + * when it does not contain "/", or set the Content-Type to `type` otherwise. + * + * Examples: + * + * res.type('.html'); + * res.type('html'); + * res.type('json'); + * res.type('application/json'); + * res.type('png'); + */ + contentType(type: string): this; + + /** + * Set _Content-Type_ response header with `type` through `mime.lookup()` + * when it does not contain "/", or set the Content-Type to `type` otherwise. + * + * Examples: + * + * res.type('.html'); + * res.type('html'); + * res.type('json'); + * res.type('application/json'); + * res.type('png'); + */ + type(type: string): this; + + /** + * Respond to the Acceptable formats using an `obj` + * of mime-type callbacks. + * + * This method uses `req.accepted`, an array of + * acceptable types ordered by their quality values. + * When "Accept" is not present the _first_ callback + * is invoked, otherwise the first match is used. When + * no match is performed the server responds with + * 406 "Not Acceptable". + * + * Content-Type is set for you, however if you choose + * you may alter this within the callback using `res.type()` + * or `res.set('Content-Type', ...)`. + * + * res.format({ + * 'text/plain': function(){ + * res.send('hey'); + * }, + * + * 'text/html': function(){ + * res.send('

hey

'); + * }, + * + * 'appliation/json': function(){ + * res.send({ message: 'hey' }); + * } + * }); + * + * In addition to canonicalized MIME types you may + * also use extnames mapped to these types: + * + * res.format({ + * text: function(){ + * res.send('hey'); + * }, + * + * html: function(){ + * res.send('

hey

'); + * }, + * + * json: function(){ + * res.send({ message: 'hey' }); + * } + * }); + * + * By default Express passes an `Error` + * with a `.status` of 406 to `next(err)` + * if a match is not made. If you provide + * a `.default` callback it will be invoked + * instead. + */ + format(obj: any): this; + + /** + * Set _Content-Disposition_ header to _attachment_ with optional `filename`. + */ + attachment(filename?: string): this; + + /** + * Set header `field` to `val`, or pass + * an object of header fields. + * + * Examples: + * + * res.set('Foo', ['bar', 'baz']); + * res.set('Accept', 'application/json'); + * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' }); + * + * Aliased as `res.header()`. + */ + set(field: any): this; + set(field: string, value?: string | string[]): this; + + header(field: any): this; + header(field: string, value?: string | string[]): this; + + // Property indicating if HTTP headers has been sent for the response. + headersSent: boolean; + + /** Get value for header `field`. */ + get(field: string): string | undefined; + + /** Clear cookie `name`. */ + clearCookie(name: string, options?: CookieOptions): this; + + /** + * Set cookie `name` to `val`, with the given `options`. + * + * Options: + * + * - `maxAge` max-age in milliseconds, converted to `expires` + * - `signed` sign the cookie + * - `path` defaults to "/" + * + * Examples: + * + * // "Remember Me" for 15 minutes + * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true }); + * + * // save as above + * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true }) + */ + cookie(name: string, val: string, options: CookieOptions): this; + cookie(name: string, val: any, options: CookieOptions): this; + cookie(name: string, val: any): this; + + /** + * Set the location header to `url`. + * + * The given `url` can also be the name of a mapped url, for + * example by default express supports "back" which redirects + * to the _Referrer_ or _Referer_ headers or "/". + * + * Examples: + * + * res.location('/foo/bar').; + * res.location('http://example.com'); + * res.location('../login'); // /blog/post/1 -> /blog/login + * + * Mounting: + * + * When an application is mounted and `res.location()` + * is given a path that does _not_ lead with "/" it becomes + * relative to the mount-point. For example if the application + * is mounted at "/blog", the following would become "/blog/login". + * + * res.location('login'); + * + * While the leading slash would result in a location of "/login": + * + * res.location('/login'); + */ + location(url: string): this; + + /** + * Redirect to the given `url` with optional response `status` + * defaulting to 302. + * + * The resulting `url` is determined by `res.location()`, so + * it will play nicely with mounted apps, relative paths, + * `"back"` etc. + * + * Examples: + * + * res.redirect('back'); + * res.redirect('/foo/bar'); + * res.redirect('http://example.com'); + * res.redirect(301, 'http://example.com'); + * res.redirect('http://example.com', 301); + * res.redirect('../login'); // /blog/post/1 -> /blog/login + */ + redirect(url: string): void; + redirect(status: number, url: string): void; + /** @deprecated use res.redirect(status, url) instead */ + redirect(url: string, status: number): void; + + /** + * Render `view` with the given `options` and optional callback `fn`. + * When a callback function is given a response will _not_ be made + * automatically, otherwise a response of _200_ and _text/html_ is given. + * + * Options: + * + * - `cache` boolean hinting to the engine it should cache + * - `filename` filename of the view being rendered + */ + render(view: string, options?: object, callback?: (err: Error, html: string) => void): void; + render(view: string, callback?: (err: Error, html: string) => void): void; + + locals: LocalsObj & Locals; + + charset: string; + + /** + * Adds the field to the Vary response header, if it is not there already. + * Examples: + * + * res.vary('User-Agent').render('docs'); + */ + vary(field: string): this; + + app: Application; + + /** + * Appends the specified value to the HTTP response header field. + * If the header is not already set, it creates the header with the specified value. + * The value parameter can be a string or an array. + * + * Note: calling res.set() after res.append() will reset the previously-set header value. + * + * @since 4.11.0 + */ + append(field: string, value?: string[] | string): this; + + /** + * After middleware.init executed, Response will contain req property + * See: express/lib/middleware/init.js + */ + req: Request; +} + +export interface Handler extends RequestHandler {} + +export type RequestParamHandler = (req: Request, res: Response, next: NextFunction, value: any, name: string) => any; + +export type ApplicationRequestHandler = + & IRouterHandler + & IRouterMatcher + & ((...handlers: RequestHandlerParams[]) => T); + +export interface Application< + LocalsObj extends Record = Record, +> extends EventEmitter, IRouter, Express.Application { + /** + * Express instance itself is a request handler, which could be invoked without + * third argument. + */ + (req: Request | http.IncomingMessage, res: Response | http.ServerResponse): any; + + /** + * Initialize the server. + * + * - setup default configuration + * - setup default middleware + * - setup route reflection methods + */ + init(): void; + + /** + * Initialize application configuration. + */ + defaultConfiguration(): void; + + /** + * Register the given template engine callback `fn` + * as `ext`. + * + * By default will `require()` the engine based on the + * file extension. For example if you try to render + * a "foo.jade" file Express will invoke the following internally: + * + * app.engine('jade', require('jade').__express); + * + * For engines that do not provide `.__express` out of the box, + * or if you wish to "map" a different extension to the template engine + * you may use this method. For example mapping the EJS template engine to + * ".html" files: + * + * app.engine('html', require('ejs').renderFile); + * + * In this case EJS provides a `.renderFile()` method with + * the same signature that Express expects: `(path, options, callback)`, + * though note that it aliases this method as `ejs.__express` internally + * so if you're using ".ejs" extensions you dont need to do anything. + * + * Some template engines do not follow this convention, the + * [Consolidate.js](https://github.com/visionmedia/consolidate.js) + * library was created to map all of node's popular template + * engines to follow this convention, thus allowing them to + * work seamlessly within Express. + */ + engine( + ext: string, + fn: (path: string, options: object, callback: (e: any, rendered?: string) => void) => void, + ): this; + + /** + * Assign `setting` to `val`, or return `setting`'s value. + * + * app.set('foo', 'bar'); + * app.get('foo'); + * // => "bar" + * app.set('foo', ['bar', 'baz']); + * app.get('foo'); + * // => ["bar", "baz"] + * + * Mounted servers inherit their parent server's settings. + */ + set(setting: string, val: any): this; + get: ((name: string) => any) & IRouterMatcher; + + param(name: string | string[], handler: RequestParamHandler): this; + + /** + * Alternatively, you can pass only a callback, in which case you have the opportunity to alter the app.param() + * + * @deprecated since version 4.11 + */ + param(callback: (name: string, matcher: RegExp) => RequestParamHandler): this; + + /** + * Return the app's absolute pathname + * based on the parent(s) that have + * mounted it. + * + * For example if the application was + * mounted as "/admin", which itself + * was mounted as "/blog" then the + * return value would be "/blog/admin". + */ + path(): string; + + /** + * Check if `setting` is enabled (truthy). + * + * app.enabled('foo') + * // => false + * + * app.enable('foo') + * app.enabled('foo') + * // => true + */ + enabled(setting: string): boolean; + + /** + * Check if `setting` is disabled. + * + * app.disabled('foo') + * // => true + * + * app.enable('foo') + * app.disabled('foo') + * // => false + */ + disabled(setting: string): boolean; + + /** Enable `setting`. */ + enable(setting: string): this; + + /** Disable `setting`. */ + disable(setting: string): this; + + /** + * Render the given view `name` name with `options` + * and a callback accepting an error and the + * rendered template string. + * + * Example: + * + * app.render('email', { name: 'Tobi' }, function(err, html){ + * // ... + * }) + */ + render(name: string, options?: object, callback?: (err: Error, html: string) => void): void; + render(name: string, callback: (err: Error, html: string) => void): void; + + /** + * Listen for connections. + * + * A node `http.Server` is returned, with this + * application (which is a `Function`) as its + * callback. If you wish to create both an HTTP + * and HTTPS server you may do so with the "http" + * and "https" modules as shown here: + * + * var http = require('http') + * , https = require('https') + * , express = require('express') + * , app = express(); + * + * http.createServer(app).listen(80); + * https.createServer({ ... }, app).listen(443); + */ + listen(port: number, hostname: string, backlog: number, callback?: () => void): http.Server; + listen(port: number, hostname: string, callback?: () => void): http.Server; + listen(port: number, callback?: () => void): http.Server; + listen(callback?: () => void): http.Server; + listen(path: string, callback?: () => void): http.Server; + listen(handle: any, listeningListener?: () => void): http.Server; + + router: string; + + settings: any; + + resource: any; + + map: any; + + locals: LocalsObj & Locals; + + /** + * The app.routes object houses all of the routes defined mapped by the + * associated HTTP verb. This object may be used for introspection + * capabilities, for example Express uses this internally not only for + * routing but to provide default OPTIONS behaviour unless app.options() + * is used. Your application or framework may also remove routes by + * simply by removing them from this object. + */ + routes: any; + + /** + * Used to get all registered routes in Express Application + */ + _router: any; + + use: ApplicationRequestHandler; + + /** + * The mount event is fired on a sub-app, when it is mounted on a parent app. + * The parent app is passed to the callback function. + * + * NOTE: + * Sub-apps will: + * - Not inherit the value of settings that have a default value. You must set the value in the sub-app. + * - Inherit the value of settings with no default value. + */ + on: (event: string, callback: (parent: Application) => void) => this; + + /** + * The app.mountpath property contains one or more path patterns on which a sub-app was mounted. + */ + mountpath: string | string[]; +} + +export interface Express extends Application { + request: Request; + response: Response; +} diff --git a/backend/node_modules/@types/express-serve-static-core/package.json b/backend/node_modules/@types/express-serve-static-core/package.json new file mode 100644 index 0000000000000000000000000000000000000000..1fe90a9798acc033f74a97ebf43b42a2554ecc30 --- /dev/null +++ b/backend/node_modules/@types/express-serve-static-core/package.json @@ -0,0 +1,55 @@ +{ + "name": "@types/express-serve-static-core", + "version": "4.19.0", + "description": "TypeScript definitions for express-serve-static-core", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/express-serve-static-core", + "license": "MIT", + "contributors": [ + { + "name": "Boris Yankov", + "githubUsername": "borisyankov", + "url": "https://github.com/borisyankov" + }, + { + "name": "Satana Charuwichitratana", + "githubUsername": "micksatana", + "url": "https://github.com/micksatana" + }, + { + "name": "Sami Jaber", + "githubUsername": "samijaber", + "url": "https://github.com/samijaber" + }, + { + "name": "Jose Luis Leon", + "githubUsername": "JoseLion", + "url": "https://github.com/JoseLion" + }, + { + "name": "David Stephens", + "githubUsername": "dwrss", + "url": "https://github.com/dwrss" + }, + { + "name": "Shin Ando", + "githubUsername": "andoshin11", + "url": "https://github.com/andoshin11" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/express-serve-static-core" + }, + "scripts": {}, + "dependencies": { + "@types/node": "*", + "@types/qs": "*", + "@types/range-parser": "*", + "@types/send": "*" + }, + "typesPublisherContentHash": "a69ff76a4af51a72b9c21aef5507a22ae657992a35a887436806eeedff4c5348", + "typeScriptVersion": "4.7" +} \ No newline at end of file diff --git a/backend/node_modules/@types/express/LICENSE b/backend/node_modules/@types/express/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/backend/node_modules/@types/express/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/backend/node_modules/@types/express/README.md b/backend/node_modules/@types/express/README.md new file mode 100644 index 0000000000000000000000000000000000000000..1e95940a74c1cabfe1cf8debb5e5fd68e6272f6d --- /dev/null +++ b/backend/node_modules/@types/express/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/express` + +# Summary +This package contains type definitions for express (http://expressjs.com). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/express. + +### Additional Details + * Last updated: Tue, 07 Nov 2023 03:09:36 GMT + * Dependencies: [@types/body-parser](https://npmjs.com/package/@types/body-parser), [@types/express-serve-static-core](https://npmjs.com/package/@types/express-serve-static-core), [@types/qs](https://npmjs.com/package/@types/qs), [@types/serve-static](https://npmjs.com/package/@types/serve-static) + +# Credits +These definitions were written by [Boris Yankov](https://github.com/borisyankov), [China Medical University Hospital](https://github.com/CMUH), [Puneet Arora](https://github.com/puneetar), and [Dylan Frankland](https://github.com/dfrankland). diff --git a/backend/node_modules/@types/express/index.d.ts b/backend/node_modules/@types/express/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b92b15c8a3dbf0126e396efbc87265b630321e25 --- /dev/null +++ b/backend/node_modules/@types/express/index.d.ts @@ -0,0 +1,128 @@ +/* =================== USAGE =================== + + import express = require("express"); + var app = express(); + + =============================================== */ + +/// +/// + +import * as bodyParser from "body-parser"; +import * as core from "express-serve-static-core"; +import * as qs from "qs"; +import * as serveStatic from "serve-static"; + +/** + * Creates an Express application. The express() function is a top-level function exported by the express module. + */ +declare function e(): core.Express; + +declare namespace e { + /** + * This is a built-in middleware function in Express. It parses incoming requests with JSON payloads and is based on body-parser. + * @since 4.16.0 + */ + var json: typeof bodyParser.json; + + /** + * This is a built-in middleware function in Express. It parses incoming requests with Buffer payloads and is based on body-parser. + * @since 4.17.0 + */ + var raw: typeof bodyParser.raw; + + /** + * This is a built-in middleware function in Express. It parses incoming requests with text payloads and is based on body-parser. + * @since 4.17.0 + */ + var text: typeof bodyParser.text; + + /** + * These are the exposed prototypes. + */ + var application: Application; + var request: Request; + var response: Response; + + /** + * This is a built-in middleware function in Express. It serves static files and is based on serve-static. + */ + var static: serveStatic.RequestHandlerConstructor; + + /** + * This is a built-in middleware function in Express. It parses incoming requests with urlencoded payloads and is based on body-parser. + * @since 4.16.0 + */ + var urlencoded: typeof bodyParser.urlencoded; + + /** + * This is a built-in middleware function in Express. It parses incoming request query parameters. + */ + export function query(options: qs.IParseOptions | typeof qs.parse): Handler; + + export function Router(options?: RouterOptions): core.Router; + + interface RouterOptions { + /** + * Enable case sensitivity. + */ + caseSensitive?: boolean | undefined; + + /** + * Preserve the req.params values from the parent router. + * If the parent and the child have conflicting param names, the child’s value take precedence. + * + * @default false + * @since 4.5.0 + */ + mergeParams?: boolean | undefined; + + /** + * Enable strict routing. + */ + strict?: boolean | undefined; + } + + interface Application extends core.Application {} + interface CookieOptions extends core.CookieOptions {} + interface Errback extends core.Errback {} + interface ErrorRequestHandler< + P = core.ParamsDictionary, + ResBody = any, + ReqBody = any, + ReqQuery = core.Query, + Locals extends Record = Record, + > extends core.ErrorRequestHandler {} + interface Express extends core.Express {} + interface Handler extends core.Handler {} + interface IRoute extends core.IRoute {} + interface IRouter extends core.IRouter {} + interface IRouterHandler extends core.IRouterHandler {} + interface IRouterMatcher extends core.IRouterMatcher {} + interface MediaType extends core.MediaType {} + interface NextFunction extends core.NextFunction {} + interface Locals extends core.Locals {} + interface Request< + P = core.ParamsDictionary, + ResBody = any, + ReqBody = any, + ReqQuery = core.Query, + Locals extends Record = Record, + > extends core.Request {} + interface RequestHandler< + P = core.ParamsDictionary, + ResBody = any, + ReqBody = any, + ReqQuery = core.Query, + Locals extends Record = Record, + > extends core.RequestHandler {} + interface RequestParamHandler extends core.RequestParamHandler {} + interface Response< + ResBody = any, + Locals extends Record = Record, + > extends core.Response {} + interface Router extends core.Router {} + interface Send extends core.Send {} +} + +export = e; diff --git a/backend/node_modules/@types/express/package.json b/backend/node_modules/@types/express/package.json new file mode 100644 index 0000000000000000000000000000000000000000..0ab36cfbffb315f8a8705c4c43ac3921cb1932ee --- /dev/null +++ b/backend/node_modules/@types/express/package.json @@ -0,0 +1,45 @@ +{ + "name": "@types/express", + "version": "4.17.21", + "description": "TypeScript definitions for express", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/express", + "license": "MIT", + "contributors": [ + { + "name": "Boris Yankov", + "githubUsername": "borisyankov", + "url": "https://github.com/borisyankov" + }, + { + "name": "China Medical University Hospital", + "githubUsername": "CMUH", + "url": "https://github.com/CMUH" + }, + { + "name": "Puneet Arora", + "githubUsername": "puneetar", + "url": "https://github.com/puneetar" + }, + { + "name": "Dylan Frankland", + "githubUsername": "dfrankland", + "url": "https://github.com/dfrankland" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/express" + }, + "scripts": {}, + "dependencies": { + "@types/body-parser": "*", + "@types/express-serve-static-core": "^4.17.33", + "@types/qs": "*", + "@types/serve-static": "*" + }, + "typesPublisherContentHash": "fa18ce9be07653182e2674f9a13cf8347ffb270031a7a8d22ba0e785bbc16ce4", + "typeScriptVersion": "4.5" +} \ No newline at end of file diff --git a/backend/node_modules/@types/http-errors/LICENSE b/backend/node_modules/@types/http-errors/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/backend/node_modules/@types/http-errors/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/backend/node_modules/@types/http-errors/README.md b/backend/node_modules/@types/http-errors/README.md new file mode 100644 index 0000000000000000000000000000000000000000..0de54023a2926ed2625cb76ac1fd32bcc921e541 --- /dev/null +++ b/backend/node_modules/@types/http-errors/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/http-errors` + +# Summary +This package contains type definitions for http-errors (https://github.com/jshttp/http-errors). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/http-errors. + +### Additional Details + * Last updated: Tue, 07 Nov 2023 03:09:37 GMT + * Dependencies: none + +# Credits +These definitions were written by [Tanguy Krotoff](https://github.com/tkrotoff), and [BendingBender](https://github.com/BendingBender). diff --git a/backend/node_modules/@types/http-errors/index.d.ts b/backend/node_modules/@types/http-errors/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e7fb2a8da5861ac4c657b326c4b8e9af64d9ff73 --- /dev/null +++ b/backend/node_modules/@types/http-errors/index.d.ts @@ -0,0 +1,77 @@ +export = createHttpError; + +declare const createHttpError: createHttpError.CreateHttpError & createHttpError.NamedConstructors & { + isHttpError: createHttpError.IsHttpError; +}; + +declare namespace createHttpError { + interface HttpError extends Error { + status: N; + statusCode: N; + expose: boolean; + headers?: { + [key: string]: string; + } | undefined; + [key: string]: any; + } + + type UnknownError = Error | string | { [key: string]: any }; + + interface HttpErrorConstructor { + (msg?: string): HttpError; + new(msg?: string): HttpError; + } + + interface CreateHttpError { + (arg: N, ...rest: UnknownError[]): HttpError; + (...rest: UnknownError[]): HttpError; + } + + type IsHttpError = (error: unknown) => error is HttpError; + + type NamedConstructors = + & { + HttpError: HttpErrorConstructor; + } + & Record<"BadRequest" | "400", HttpErrorConstructor<400>> + & Record<"Unauthorized" | "401", HttpErrorConstructor<401>> + & Record<"PaymentRequired" | "402", HttpErrorConstructor<402>> + & Record<"Forbidden" | "403", HttpErrorConstructor<403>> + & Record<"NotFound" | "404", HttpErrorConstructor<404>> + & Record<"MethodNotAllowed" | "405", HttpErrorConstructor<405>> + & Record<"NotAcceptable" | "406", HttpErrorConstructor<406>> + & Record<"ProxyAuthenticationRequired" | "407", HttpErrorConstructor<407>> + & Record<"RequestTimeout" | "408", HttpErrorConstructor<408>> + & Record<"Conflict" | "409", HttpErrorConstructor<409>> + & Record<"Gone" | "410", HttpErrorConstructor<410>> + & Record<"LengthRequired" | "411", HttpErrorConstructor<411>> + & Record<"PreconditionFailed" | "412", HttpErrorConstructor<412>> + & Record<"PayloadTooLarge" | "413", HttpErrorConstructor<413>> + & Record<"URITooLong" | "414", HttpErrorConstructor<414>> + & Record<"UnsupportedMediaType" | "415", HttpErrorConstructor<415>> + & Record<"RangeNotSatisfiable" | "416", HttpErrorConstructor<416>> + & Record<"ExpectationFailed" | "417", HttpErrorConstructor<417>> + & Record<"ImATeapot" | "418", HttpErrorConstructor<418>> + & Record<"MisdirectedRequest" | "421", HttpErrorConstructor<421>> + & Record<"UnprocessableEntity" | "422", HttpErrorConstructor<422>> + & Record<"Locked" | "423", HttpErrorConstructor<423>> + & Record<"FailedDependency" | "424", HttpErrorConstructor<424>> + & Record<"TooEarly" | "425", HttpErrorConstructor<425>> + & Record<"UpgradeRequired" | "426", HttpErrorConstructor<426>> + & Record<"PreconditionRequired" | "428", HttpErrorConstructor<428>> + & Record<"TooManyRequests" | "429", HttpErrorConstructor<429>> + & Record<"RequestHeaderFieldsTooLarge" | "431", HttpErrorConstructor<431>> + & Record<"UnavailableForLegalReasons" | "451", HttpErrorConstructor<451>> + & Record<"InternalServerError" | "500", HttpErrorConstructor<500>> + & Record<"NotImplemented" | "501", HttpErrorConstructor<501>> + & Record<"BadGateway" | "502", HttpErrorConstructor<502>> + & Record<"ServiceUnavailable" | "503", HttpErrorConstructor<503>> + & Record<"GatewayTimeout" | "504", HttpErrorConstructor<504>> + & Record<"HTTPVersionNotSupported" | "505", HttpErrorConstructor<505>> + & Record<"VariantAlsoNegotiates" | "506", HttpErrorConstructor<506>> + & Record<"InsufficientStorage" | "507", HttpErrorConstructor<507>> + & Record<"LoopDetected" | "508", HttpErrorConstructor<508>> + & Record<"BandwidthLimitExceeded" | "509", HttpErrorConstructor<509>> + & Record<"NotExtended" | "510", HttpErrorConstructor<510>> + & Record<"NetworkAuthenticationRequire" | "511", HttpErrorConstructor<511>>; +} diff --git a/backend/node_modules/@types/http-errors/package.json b/backend/node_modules/@types/http-errors/package.json new file mode 100644 index 0000000000000000000000000000000000000000..247f9d4062876d917a2d4400ae7dbd974aa7ae6d --- /dev/null +++ b/backend/node_modules/@types/http-errors/package.json @@ -0,0 +1,30 @@ +{ + "name": "@types/http-errors", + "version": "2.0.4", + "description": "TypeScript definitions for http-errors", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/http-errors", + "license": "MIT", + "contributors": [ + { + "name": "Tanguy Krotoff", + "githubUsername": "tkrotoff", + "url": "https://github.com/tkrotoff" + }, + { + "name": "BendingBender", + "githubUsername": "BendingBender", + "url": "https://github.com/BendingBender" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/http-errors" + }, + "scripts": {}, + "dependencies": {}, + "typesPublisherContentHash": "06e33723b60f818facd3b7dd2025f043142fb7c56ab4832babafeb9470f2086f", + "typeScriptVersion": "4.5" +} \ No newline at end of file diff --git a/backend/node_modules/@types/mime/LICENSE b/backend/node_modules/@types/mime/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/backend/node_modules/@types/mime/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/backend/node_modules/@types/mime/Mime.d.ts b/backend/node_modules/@types/mime/Mime.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a516bd409c05ed7538bd4ed457b879ee6ae92aff --- /dev/null +++ b/backend/node_modules/@types/mime/Mime.d.ts @@ -0,0 +1,10 @@ +import { TypeMap } from "./index"; + +export default class Mime { + constructor(mimes: TypeMap); + + lookup(path: string, fallback?: string): string; + extension(mime: string): string | undefined; + load(filepath: string): void; + define(mimes: TypeMap): void; +} diff --git a/backend/node_modules/@types/mime/README.md b/backend/node_modules/@types/mime/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a08301c8870fc35740a71acf5be7f4a79b4fafd5 --- /dev/null +++ b/backend/node_modules/@types/mime/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/mime` + +# Summary +This package contains type definitions for mime (https://github.com/broofa/node-mime). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/mime/v1. + +### Additional Details + * Last updated: Tue, 07 Nov 2023 20:08:00 GMT + * Dependencies: none + +# Credits +These definitions were written by [Jeff Goddard](https://github.com/jedigo), and [Daniel Hritzkiv](https://github.com/dhritzkiv). diff --git a/backend/node_modules/@types/mime/index.d.ts b/backend/node_modules/@types/mime/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..93e825995c0a4f4227182903949f7710ce573a48 --- /dev/null +++ b/backend/node_modules/@types/mime/index.d.ts @@ -0,0 +1,31 @@ +// Originally imported from: https://github.com/soywiz/typescript-node-definitions/mime.d.ts + +export as namespace mime; + +export interface TypeMap { + [key: string]: string[]; +} + +/** + * Look up a mime type based on extension. + * + * If not found, uses the fallback argument if provided, and otherwise + * uses `default_type`. + */ +export function lookup(path: string, fallback?: string): string; +/** + * Return a file extensions associated with a mime type. + */ +export function extension(mime: string): string | undefined; +/** + * Load an Apache2-style ".types" file. + */ +export function load(filepath: string): void; +export function define(mimes: TypeMap): void; + +export interface Charsets { + lookup(mime: string, fallback: string): string; +} + +export const charsets: Charsets; +export const default_type: string; diff --git a/backend/node_modules/@types/mime/lite.d.ts b/backend/node_modules/@types/mime/lite.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ffebaec5b9b2e95ebceae967ca75df5f8e770498 --- /dev/null +++ b/backend/node_modules/@types/mime/lite.d.ts @@ -0,0 +1,7 @@ +import { default as Mime } from "./Mime"; + +declare const mimelite: Mime; + +export as namespace mimelite; + +export = mimelite; diff --git a/backend/node_modules/@types/mime/package.json b/backend/node_modules/@types/mime/package.json new file mode 100644 index 0000000000000000000000000000000000000000..98a29ff1fd9806050aeab0f9ab38c62d1bada02d --- /dev/null +++ b/backend/node_modules/@types/mime/package.json @@ -0,0 +1,30 @@ +{ + "name": "@types/mime", + "version": "1.3.5", + "description": "TypeScript definitions for mime", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/mime", + "license": "MIT", + "contributors": [ + { + "name": "Jeff Goddard", + "githubUsername": "jedigo", + "url": "https://github.com/jedigo" + }, + { + "name": "Daniel Hritzkiv", + "githubUsername": "dhritzkiv", + "url": "https://github.com/dhritzkiv" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/mime" + }, + "scripts": {}, + "dependencies": {}, + "typesPublisherContentHash": "2ad7ee9a549e6721825e733c6a1a7e8bee0ca7ba93d9ab922c8f4558def52d77", + "typeScriptVersion": "4.5" +} \ No newline at end of file diff --git a/backend/node_modules/@types/multer/LICENSE b/backend/node_modules/@types/multer/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/backend/node_modules/@types/multer/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/backend/node_modules/@types/multer/README.md b/backend/node_modules/@types/multer/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e15cb0b860d986094806a4a9c8e22544a09933a2 --- /dev/null +++ b/backend/node_modules/@types/multer/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/multer` + +# Summary +This package contains type definitions for multer (https://github.com/expressjs/multer). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/multer. + +### Additional Details + * Last updated: Mon, 20 Nov 2023 23:36:24 GMT + * Dependencies: [@types/express](https://npmjs.com/package/@types/express) + +# Credits +These definitions were written by [jt000](https://github.com/jt000), [vilicvane](https://github.com/vilic), [David Broder-Rodgers](https://github.com/DavidBR-SW), [Michael Ledin](https://github.com/mxl), [HyunSeob Lee](https://github.com/hyunseob), [Pierre Tchuente](https://github.com/PierreTchuente), [Oliver Emery](https://github.com/thrymgjol), and [Piotr Błażejewicz](https://github.com/peterblazejewicz). diff --git a/backend/node_modules/@types/multer/index.d.ts b/backend/node_modules/@types/multer/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f07613d6ee4cdad8c51cc9483202883631a8d387 --- /dev/null +++ b/backend/node_modules/@types/multer/index.d.ts @@ -0,0 +1,316 @@ +import { Request, RequestHandler } from "express"; +import { Readable } from "stream"; + +declare global { + namespace Express { + namespace Multer { + /** Object containing file metadata and access information. */ + interface File { + /** Name of the form field associated with this file. */ + fieldname: string; + /** Name of the file on the uploader's computer. */ + originalname: string; + /** + * Value of the `Content-Transfer-Encoding` header for this file. + * @deprecated since July 2015 + * @see RFC 7578, Section 4.7 + */ + encoding: string; + /** Value of the `Content-Type` header for this file. */ + mimetype: string; + /** Size of the file in bytes. */ + size: number; + /** + * A readable stream of this file. Only available to the `_handleFile` + * callback for custom `StorageEngine`s. + */ + stream: Readable; + /** `DiskStorage` only: Directory to which this file has been uploaded. */ + destination: string; + /** `DiskStorage` only: Name of this file within `destination`. */ + filename: string; + /** `DiskStorage` only: Full path to the uploaded file. */ + path: string; + /** `MemoryStorage` only: A Buffer containing the entire file. */ + buffer: Buffer; + } + } + + interface Request { + /** `Multer.File` object populated by `single()` middleware. */ + file?: Multer.File | undefined; + /** + * Array or dictionary of `Multer.File` object populated by `array()`, + * `fields()`, and `any()` middleware. + */ + files?: + | { + [fieldname: string]: Multer.File[]; + } + | Multer.File[] + | undefined; + } + } +} + +/** + * Returns a Multer instance that provides several methods for generating + * middleware that process files uploaded in `multipart/form-data` format. + * + * The `StorageEngine` specified in `storage` will be used to store files. If + * `storage` is not set and `dest` is, files will be stored in `dest` on the + * local file system with random names. If neither are set, files will be stored + * in memory. + * + * In addition to files, all generated middleware process all text fields in + * the request. For each non-file field, the `Request.body` object will be + * populated with an entry mapping the field name to its string value, or array + * of string values if multiple fields share the same name. + */ +declare function multer(options?: multer.Options): multer.Multer; + +declare namespace multer { + /** + * @see {@link https://github.com/expressjs/multer#api} + */ + interface Multer { + /** + * Returns middleware that processes a single file associated with the + * given form field. + * + * The `Request` object will be populated with a `file` object containing + * information about the processed file. + * + * @param fieldName Name of the multipart form field to process. + */ + single(fieldName: string): RequestHandler; + /** + * Returns middleware that processes multiple files sharing the same field + * name. + * + * The `Request` object will be populated with a `files` array containing + * an information object for each processed file. + * + * @param fieldName Shared name of the multipart form fields to process. + * @param maxCount Optional. Maximum number of files to process. (default: Infinity) + * @throws `MulterError('LIMIT_UNEXPECTED_FILE')` if more than `maxCount` files are associated with `fieldName` + */ + array(fieldName: string, maxCount?: number): RequestHandler; + /** + * Returns middleware that processes multiple files associated with the + * given form fields. + * + * The `Request` object will be populated with a `files` object which + * maps each field name to an array of the associated file information + * objects. + * + * @param fields Array of `Field` objects describing multipart form fields to process. + * @throws `MulterError('LIMIT_UNEXPECTED_FILE')` if more than `maxCount` files are associated with `fieldName` for any field. + */ + fields(fields: readonly Field[]): RequestHandler; + /** + * Returns middleware that processes all files contained in the multipart + * request. + * + * The `Request` object will be populated with a `files` array containing + * an information object for each processed file. + */ + any(): RequestHandler; + /** + * Returns middleware that accepts only non-file multipart form fields. + * + * @throws `MulterError('LIMIT_UNEXPECTED_FILE')` if any file is encountered. + */ + none(): RequestHandler; + } + + /** + * Returns a `StorageEngine` implementation configured to store files on + * the local file system. + * + * A string or function may be specified to determine the destination + * directory, and a function to determine filenames. If no options are set, + * files will be stored in the system's temporary directory with random 32 + * character filenames. + */ + function diskStorage(options: DiskStorageOptions): StorageEngine; + + /** + * Returns a `StorageEngine` implementation configured to store files in + * memory as `Buffer` objects. + */ + function memoryStorage(): StorageEngine; + + type ErrorCode = + | "LIMIT_PART_COUNT" + | "LIMIT_FILE_SIZE" + | "LIMIT_FILE_COUNT" + | "LIMIT_FIELD_KEY" + | "LIMIT_FIELD_VALUE" + | "LIMIT_FIELD_COUNT" + | "LIMIT_UNEXPECTED_FILE"; + + class MulterError extends Error { + constructor(code: ErrorCode, field?: string); + /** Name of the MulterError constructor. */ + name: string; + /** Identifying error code. */ + code: ErrorCode; + /** Descriptive error message. */ + message: string; + /** Name of the multipart form field associated with this error. */ + field?: string | undefined; + } + + /** + * a function to control which files should be uploaded and which should be skipped + * pass a boolean to indicate if the file should be accepted + * pass an error if something goes wrong + */ + interface FileFilterCallback { + (error: Error): void; + (error: null, acceptFile: boolean): void; + } + + /** Options for initializing a Multer instance. */ + interface Options { + /** + * A `StorageEngine` responsible for processing files uploaded via Multer. + * Takes precedence over `dest`. + */ + storage?: StorageEngine | undefined; + /** + * The destination directory for uploaded files. If `storage` is not set + * and `dest` is, Multer will create a `DiskStorage` instance configured + * to store files at `dest` with random filenames. + * + * Ignored if `storage` is set. + */ + dest?: string | undefined; + /** + * An object specifying various limits on incoming data. This object is + * passed to Busboy directly, and the details of properties can be found + * at https://github.com/mscdex/busboy#busboy-methods. + */ + limits?: { + /** Maximum size of each form field name in bytes. (Default: 100) */ + fieldNameSize?: number | undefined; + /** Maximum size of each form field value in bytes. (Default: 1048576) */ + fieldSize?: number | undefined; + /** Maximum number of non-file form fields. (Default: Infinity) */ + fields?: number | undefined; + /** Maximum size of each file in bytes. (Default: Infinity) */ + fileSize?: number | undefined; + /** Maximum number of file fields. (Default: Infinity) */ + files?: number | undefined; + /** Maximum number of parts (non-file fields + files). (Default: Infinity) */ + parts?: number | undefined; + /** Maximum number of headers. (Default: 2000) */ + headerPairs?: number | undefined; + } | undefined; + /** Preserve the full path of the original filename rather than the basename. (Default: false) */ + preservePath?: boolean | undefined; + /** + * Optional function to control which files are uploaded. This is called + * for every file that is processed. + * + * @param req The Express `Request` object. + * @param file Object containing information about the processed file. + * @param callback a function to control which files should be uploaded and which should be skipped. + */ + fileFilter?( + req: Request, + file: Express.Multer.File, + callback: FileFilterCallback, + ): void; + } + + /** + * Implementations of this interface are responsible for storing files + * encountered by Multer and returning information on how to access them + * once stored. Implementations must also provide a method for removing + * files in the event that an error occurs. + */ + interface StorageEngine { + /** + * Store the file described by `file`, then invoke the callback with + * information about the stored file. + * + * File contents are available as a stream via `file.stream`. Information + * passed to the callback will be merged with `file` for subsequent + * middleware. + * + * @param req The Express `Request` object. + * @param file Object with `stream`, `fieldname`, `originalname`, `encoding`, and `mimetype` defined. + * @param callback Callback to specify file information. + */ + _handleFile( + req: Request, + file: Express.Multer.File, + callback: (error?: any, info?: Partial) => void, + ): void; + /** + * Remove the file described by `file`, then invoke the callback with. + * + * `file` contains all the properties available to `_handleFile`, as + * well as those returned by `_handleFile`. + * + * @param req The Express `Request` object. + * @param file Object containing information about the processed file. + * @param callback Callback to indicate completion. + */ + _removeFile( + req: Request, + file: Express.Multer.File, + callback: (error: Error | null) => void, + ): void; + } + + interface DiskStorageOptions { + /** + * A string or function that determines the destination path for uploaded + * files. If a string is passed and the directory does not exist, Multer + * attempts to create it recursively. If neither a string or a function + * is passed, the destination defaults to `os.tmpdir()`. + * + * @param req The Express `Request` object. + * @param file Object containing information about the processed file. + * @param callback Callback to determine the destination path. + */ + destination?: + | string + | (( + req: Request, + file: Express.Multer.File, + callback: (error: Error | null, destination: string) => void, + ) => void) + | undefined; + /** + * A function that determines the name of the uploaded file. If nothing + * is passed, Multer will generate a 32 character pseudorandom hex string + * with no extension. + * + * @param req The Express `Request` object. + * @param file Object containing information about the processed file. + * @param callback Callback to determine the name of the uploaded file. + */ + filename?( + req: Request, + file: Express.Multer.File, + callback: (error: Error | null, filename: string) => void, + ): void; + } + + /** + * An object describing a field name and the maximum number of files with + * that field name to accept. + */ + interface Field { + /** The field name. */ + name: string; + /** Optional maximum number of files per field to accept. (Default: Infinity) */ + maxCount?: number | undefined; + } +} + +export = multer; diff --git a/backend/node_modules/@types/multer/package.json b/backend/node_modules/@types/multer/package.json new file mode 100644 index 0000000000000000000000000000000000000000..b0d09e1d263939aa760bba9c6791356d1a29cbbc --- /dev/null +++ b/backend/node_modules/@types/multer/package.json @@ -0,0 +1,62 @@ +{ + "name": "@types/multer", + "version": "1.4.11", + "description": "TypeScript definitions for multer", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/multer", + "license": "MIT", + "contributors": [ + { + "name": "jt000", + "githubUsername": "jt000", + "url": "https://github.com/jt000" + }, + { + "name": "vilicvane", + "githubUsername": "vilic", + "url": "https://github.com/vilic" + }, + { + "name": "David Broder-Rodgers", + "githubUsername": "DavidBR-SW", + "url": "https://github.com/DavidBR-SW" + }, + { + "name": "Michael Ledin", + "githubUsername": "mxl", + "url": "https://github.com/mxl" + }, + { + "name": "HyunSeob Lee", + "githubUsername": "hyunseob", + "url": "https://github.com/hyunseob" + }, + { + "name": "Pierre Tchuente", + "githubUsername": "PierreTchuente", + "url": "https://github.com/PierreTchuente" + }, + { + "name": "Oliver Emery", + "githubUsername": "thrymgjol", + "url": "https://github.com/thrymgjol" + }, + { + "name": "Piotr Błażejewicz", + "githubUsername": "peterblazejewicz", + "url": "https://github.com/peterblazejewicz" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/multer" + }, + "scripts": {}, + "dependencies": { + "@types/express": "*" + }, + "typesPublisherContentHash": "b37b2751db6482b0d3da4c4b7dd8d1bfd189749a4393f0cccb635e743fccab7a", + "typeScriptVersion": "4.5" +} \ No newline at end of file diff --git a/backend/node_modules/@types/node-fetch/LICENSE b/backend/node_modules/@types/node-fetch/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/backend/node_modules/@types/node-fetch/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/backend/node_modules/@types/node-fetch/README.md b/backend/node_modules/@types/node-fetch/README.md new file mode 100644 index 0000000000000000000000000000000000000000..13425ed468c356da1779537b8ac7660ad3ddbc84 --- /dev/null +++ b/backend/node_modules/@types/node-fetch/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/node-fetch` + +# Summary +This package contains type definitions for node-fetch (https://github.com/bitinn/node-fetch). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node-fetch. + +### Additional Details + * Last updated: Tue, 16 Jan 2024 23:07:00 GMT + * Dependencies: [@types/node](https://npmjs.com/package/@types/node), [form-data](https://npmjs.com/package/form-data) + +# Credits +These definitions were written by [Torsten Werner](https://github.com/torstenwerner), [Niklas Lindgren](https://github.com/nikcorg), [Vinay Bedre](https://github.com/vinaybedre), [Antonio Román](https://github.com/kyranet), [Andrew Leedham](https://github.com/AndrewLeedham), [Jason Li](https://github.com/JasonLi914), [Steve Faulkner](https://github.com/southpolesteve), [ExE Boss](https://github.com/ExE-Boss), [Alex Savin](https://github.com/alexandrusavin), [Alexis Tyler](https://github.com/OmgImAlexis), [Jakub Kisielewski](https://github.com/kbkk), and [David Glasser](https://github.com/glasser). diff --git a/backend/node_modules/@types/node-fetch/externals.d.ts b/backend/node_modules/@types/node-fetch/externals.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..20f14672206042d2951533611e875fc4f776305c --- /dev/null +++ b/backend/node_modules/@types/node-fetch/externals.d.ts @@ -0,0 +1,32 @@ +// `AbortSignal` is defined here to prevent a dependency on a particular +// implementation like the `abort-controller` package, and to avoid requiring +// the `dom` library in `tsconfig.json`. + +export interface AbortSignal { + aborted: boolean; + reason: any; + + addEventListener: ( + type: "abort", + listener: (this: AbortSignal, event: any) => any, + options?: boolean | { + capture?: boolean | undefined; + once?: boolean | undefined; + passive?: boolean | undefined; + }, + ) => void; + + removeEventListener: ( + type: "abort", + listener: (this: AbortSignal, event: any) => any, + options?: boolean | { + capture?: boolean | undefined; + }, + ) => void; + + dispatchEvent: (event: any) => boolean; + + onabort: null | ((this: AbortSignal, event: any) => any); + + throwIfAborted(): void; +} diff --git a/backend/node_modules/@types/node-fetch/index.d.ts b/backend/node_modules/@types/node-fetch/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9000ab9fdbf0e65a3dd309cef8aec754f85c1bc3 --- /dev/null +++ b/backend/node_modules/@types/node-fetch/index.d.ts @@ -0,0 +1,238 @@ +/// + +import FormData = require("form-data"); +import { RequestOptions } from "http"; +import { URL, URLSearchParams } from "url"; +import { AbortSignal } from "./externals"; + +declare class Request extends Body { + constructor(input: RequestInfo, init?: RequestInit); + clone(): Request; + context: RequestContext; + headers: Headers; + method: string; + redirect: RequestRedirect; + referrer: string; + url: string; + + // node-fetch extensions to the whatwg/fetch spec + agent?: RequestOptions["agent"] | ((parsedUrl: URL) => RequestOptions["agent"]); + compress: boolean; + counter: number; + follow: number; + hostname: string; + port?: number | undefined; + protocol: string; + size: number; + timeout: number; +} + +interface RequestInit { + // whatwg/fetch standard options + body?: BodyInit | undefined; + headers?: HeadersInit | undefined; + method?: string | undefined; + redirect?: RequestRedirect | undefined; + signal?: AbortSignal | null | undefined; + + // node-fetch extensions + agent?: RequestOptions["agent"] | ((parsedUrl: URL) => RequestOptions["agent"]); // =null http.Agent instance, allows custom proxy, certificate etc. + compress?: boolean | undefined; // =true support gzip/deflate content encoding. false to disable + follow?: number | undefined; // =20 maximum redirect count. 0 to not follow redirect + size?: number | undefined; // =0 maximum response body size in bytes. 0 to disable + timeout?: number | undefined; // =0 req/res timeout in ms, it resets on redirect. 0 to disable (OS limit applies) + + // node-fetch does not support mode, cache or credentials options +} + +type RequestContext = + | "audio" + | "beacon" + | "cspreport" + | "download" + | "embed" + | "eventsource" + | "favicon" + | "fetch" + | "font" + | "form" + | "frame" + | "hyperlink" + | "iframe" + | "image" + | "imageset" + | "import" + | "internal" + | "location" + | "manifest" + | "object" + | "ping" + | "plugin" + | "prefetch" + | "script" + | "serviceworker" + | "sharedworker" + | "style" + | "subresource" + | "track" + | "video" + | "worker" + | "xmlhttprequest" + | "xslt"; +type RequestMode = "cors" | "no-cors" | "same-origin"; +type RequestRedirect = "error" | "follow" | "manual"; +type RequestCredentials = "omit" | "include" | "same-origin"; + +type RequestCache = + | "default" + | "force-cache" + | "no-cache" + | "no-store" + | "only-if-cached" + | "reload"; + +declare class Headers implements Iterable<[string, string]> { + constructor(init?: HeadersInit); + forEach(callback: (value: string, name: string) => void): void; + append(name: string, value: string): void; + delete(name: string): void; + get(name: string): string | null; + has(name: string): boolean; + raw(): { [k: string]: string[] }; + set(name: string, value: string): void; + + // Iterable methods + entries(): IterableIterator<[string, string]>; + keys(): IterableIterator; + values(): IterableIterator; + [Symbol.iterator](): Iterator<[string, string]>; +} + +type BlobPart = ArrayBuffer | ArrayBufferView | Blob | string; + +interface BlobOptions { + type?: string | undefined; + endings?: "transparent" | "native" | undefined; +} + +declare class Blob { + constructor(blobParts?: BlobPart[], options?: BlobOptions); + readonly type: string; + readonly size: number; + slice(start?: number, end?: number): Blob; + text(): Promise; +} + +declare class Body { + constructor(body?: any, opts?: { size?: number | undefined; timeout?: number | undefined }); + arrayBuffer(): Promise; + blob(): Promise; + body: NodeJS.ReadableStream; + bodyUsed: boolean; + buffer(): Promise; + json(): Promise; + size: number; + text(): Promise; + textConverted(): Promise; + timeout: number; +} + +interface SystemError extends Error { + code?: string | undefined; +} + +declare class AbortError extends Error { + readonly name: "AbortError"; + constructor(message: string); + readonly type: "aborted"; +} + +declare class FetchError extends Error { + name: "FetchError"; + constructor(message: string, type: string, systemError?: SystemError); + type: string; + code?: string | undefined; + errno?: string | undefined; +} + +declare class Response extends Body { + constructor(body?: BodyInit, init?: ResponseInit); + static error(): Response; + static redirect(url: string, status: number): Response; + clone(): Response; + headers: Headers; + ok: boolean; + redirected: boolean; + status: number; + statusText: string; + type: ResponseType; + url: string; +} + +type ResponseType = + | "basic" + | "cors" + | "default" + | "error" + | "opaque" + | "opaqueredirect"; + +interface ResponseInit { + headers?: HeadersInit | undefined; + size?: number | undefined; + status?: number | undefined; + statusText?: string | undefined; + timeout?: number | undefined; + url?: string | undefined; + counter?: number | undefined; +} + +interface URLLike { + href: string; +} + +type HeadersInit = Headers | string[][] | { [key: string]: string | string[] }; +type BodyInit = + | ArrayBuffer + | ArrayBufferView + | NodeJS.ReadableStream + | string + | URLSearchParams + | FormData; +type RequestInfo = string | URLLike | Request; + +declare function fetch( + url: RequestInfo, + init?: RequestInit, +): Promise; + +declare namespace fetch { + export { + AbortError, + Blob, + Body, + BodyInit, + FetchError, + Headers, + HeadersInit, + // HeaderInit is exported to support backwards compatibility. See PR #34382 + HeadersInit as HeaderInit, + Request, + RequestCache, + RequestContext, + RequestCredentials, + RequestInfo, + RequestInit, + RequestMode, + RequestRedirect, + Response, + ResponseInit, + ResponseType, + }; + export function isRedirect(code: number): boolean; + + import _default = fetch; + export { _default as default }; +} + +export = fetch; diff --git a/backend/node_modules/@types/node-fetch/package.json b/backend/node_modules/@types/node-fetch/package.json new file mode 100644 index 0000000000000000000000000000000000000000..84884d5df33260c83ea1a4576ae558e101289647 --- /dev/null +++ b/backend/node_modules/@types/node-fetch/package.json @@ -0,0 +1,83 @@ +{ + "name": "@types/node-fetch", + "version": "2.6.11", + "description": "TypeScript definitions for node-fetch", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node-fetch", + "license": "MIT", + "contributors": [ + { + "name": "Torsten Werner", + "githubUsername": "torstenwerner", + "url": "https://github.com/torstenwerner" + }, + { + "name": "Niklas Lindgren", + "githubUsername": "nikcorg", + "url": "https://github.com/nikcorg" + }, + { + "name": "Vinay Bedre", + "githubUsername": "vinaybedre", + "url": "https://github.com/vinaybedre" + }, + { + "name": "Antonio Román", + "githubUsername": "kyranet", + "url": "https://github.com/kyranet" + }, + { + "name": "Andrew Leedham", + "githubUsername": "AndrewLeedham", + "url": "https://github.com/AndrewLeedham" + }, + { + "name": "Jason Li", + "githubUsername": "JasonLi914", + "url": "https://github.com/JasonLi914" + }, + { + "name": "Steve Faulkner", + "githubUsername": "southpolesteve", + "url": "https://github.com/southpolesteve" + }, + { + "name": "ExE Boss", + "githubUsername": "ExE-Boss", + "url": "https://github.com/ExE-Boss" + }, + { + "name": "Alex Savin", + "githubUsername": "alexandrusavin", + "url": "https://github.com/alexandrusavin" + }, + { + "name": "Alexis Tyler", + "githubUsername": "OmgImAlexis", + "url": "https://github.com/OmgImAlexis" + }, + { + "name": "Jakub Kisielewski", + "githubUsername": "kbkk", + "url": "https://github.com/kbkk" + }, + { + "name": "David Glasser", + "githubUsername": "glasser", + "url": "https://github.com/glasser" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/node-fetch" + }, + "scripts": {}, + "dependencies": { + "@types/node": "*", + "form-data": "^4.0.0" + }, + "typesPublisherContentHash": "912e2c03935d0f960f529de6f688e52c77e78b7ca935198cd500804e69ea371f", + "typeScriptVersion": "4.6" +} \ No newline at end of file diff --git a/backend/node_modules/@types/node/LICENSE b/backend/node_modules/@types/node/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/backend/node_modules/@types/node/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/backend/node_modules/@types/node/README.md b/backend/node_modules/@types/node/README.md new file mode 100644 index 0000000000000000000000000000000000000000..36b7eb79bfc6948258ec6d3b7753febd1f39f92a --- /dev/null +++ b/backend/node_modules/@types/node/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/node` + +# Summary +This package contains type definitions for node (https://nodejs.org/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node/v18. + +### Additional Details + * Last updated: Tue, 09 Apr 2024 04:08:23 GMT + * Dependencies: [undici-types](https://npmjs.com/package/undici-types) + +# Credits +These definitions were written by [Microsoft TypeScript](https://github.com/Microsoft), [Alberto Schiabel](https://github.com/jkomyno), [Alvis HT Tang](https://github.com/alvis), [Andrew Makarov](https://github.com/r3nya), [Benjamin Toueg](https://github.com/btoueg), [Chigozirim C.](https://github.com/smac89), [David Junger](https://github.com/touffy), [Deividas Bakanas](https://github.com/DeividasBakanas), [Eugene Y. Q. Shen](https://github.com/eyqs), [Hannes Magnusson](https://github.com/Hannes-Magnusson-CK), [Huw](https://github.com/hoo29), [Kelvin Jin](https://github.com/kjin), [Klaus Meinhardt](https://github.com/ajafff), [Lishude](https://github.com/islishude), [Mariusz Wiktorczyk](https://github.com/mwiktorczyk), [Mohsen Azimi](https://github.com/mohsen1), [Nikita Galkin](https://github.com/galkin), [Parambir Singh](https://github.com/parambirs), [Sebastian Silbermann](https://github.com/eps1lon), [Simon Schick](https://github.com/SimonSchick), [Thomas den Hollander](https://github.com/ThomasdenH), [Wilco Bakker](https://github.com/WilcoBakker), [wwwy3y3](https://github.com/wwwy3y3), [Samuel Ainsworth](https://github.com/samuela), [Kyle Uehlein](https://github.com/kuehlein), [Thanik Bhongbhibhat](https://github.com/bhongy), [Marcin Kopacz](https://github.com/chyzwar), [Trivikram Kamat](https://github.com/trivikr), [Junxiao Shi](https://github.com/yoursunny), [Ilia Baryshnikov](https://github.com/qwelias), [ExE Boss](https://github.com/ExE-Boss), [Piotr Błażejewicz](https://github.com/peterblazejewicz), [Anna Henningsen](https://github.com/addaleax), [Victor Perin](https://github.com/victorperin), [Yongsheng Zhang](https://github.com/ZYSzys), [NodeJS Contributors](https://github.com/NodeJS), [Linus Unnebäck](https://github.com/LinusU), [wafuwafu13](https://github.com/wafuwafu13), [Matteo Collina](https://github.com/mcollina), and [Dmitry Semigradsky](https://github.com/Semigradsky). diff --git a/backend/node_modules/@types/node/assert.d.ts b/backend/node_modules/@types/node/assert.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e4a8a78d6db95fbbaec75e412ed21454c9307dbe --- /dev/null +++ b/backend/node_modules/@types/node/assert.d.ts @@ -0,0 +1,985 @@ +/** + * The `assert` module provides a set of assertion functions for verifying + * invariants. + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/assert.js) + */ +declare module "assert" { + /** + * An alias of {@link ok}. + * @since v0.5.9 + * @param value The input that is checked for being truthy. + */ + function assert(value: unknown, message?: string | Error): asserts value; + namespace assert { + /** + * Indicates the failure of an assertion. All errors thrown by the `assert` module + * will be instances of the `AssertionError` class. + */ + class AssertionError extends Error { + actual: unknown; + expected: unknown; + operator: string; + generatedMessage: boolean; + code: "ERR_ASSERTION"; + constructor(options?: { + /** If provided, the error message is set to this value. */ + message?: string | undefined; + /** The `actual` property on the error instance. */ + actual?: unknown | undefined; + /** The `expected` property on the error instance. */ + expected?: unknown | undefined; + /** The `operator` property on the error instance. */ + operator?: string | undefined; + /** If provided, the generated stack trace omits frames before this function. */ + // eslint-disable-next-line @typescript-eslint/ban-types + stackStartFn?: Function | undefined; + }); + } + /** + * This feature is currently experimental and behavior might still change. + * @since v14.2.0, v12.19.0 + * @experimental + */ + class CallTracker { + /** + * The wrapper function is expected to be called exactly `exact` times. If the + * function has not been called exactly `exact` times when `tracker.verify()` is called, then `tracker.verify()` will throw an + * error. + * + * ```js + * import assert from 'assert'; + * + * // Creates call tracker. + * const tracker = new assert.CallTracker(); + * + * function func() {} + * + * // Returns a function that wraps func() that must be called exact times + * // before tracker.verify(). + * const callsfunc = tracker.calls(func); + * ``` + * @since v14.2.0, v12.19.0 + * @param [fn='A no-op function'] + * @param [exact=1] + * @return that wraps `fn`. + */ + calls(exact?: number): () => void; + calls any>(fn?: Func, exact?: number): Func; + /** + * Example: + * + * ```js + * import assert from 'node:assert'; + * + * const tracker = new assert.CallTracker(); + * + * function func() {} + * const callsfunc = tracker.calls(func); + * callsfunc(1, 2, 3); + * + * assert.deepStrictEqual(tracker.getCalls(callsfunc), + * [{ thisArg: this, arguments: [1, 2, 3 ] }]); + * ``` + * + * @since v18.8.0, v16.18.0 + * @param fn + * @returns An Array with the calls to a tracked function. + */ + getCalls(fn: Function): CallTrackerCall[]; + /** + * The arrays contains information about the expected and actual number of calls of + * the functions that have not been called the expected number of times. + * + * ```js + * import assert from 'assert'; + * + * // Creates call tracker. + * const tracker = new assert.CallTracker(); + * + * function func() {} + * + * function foo() {} + * + * // Returns a function that wraps func() that must be called exact times + * // before tracker.verify(). + * const callsfunc = tracker.calls(func, 2); + * + * // Returns an array containing information on callsfunc() + * tracker.report(); + * // [ + * // { + * // message: 'Expected the func function to be executed 2 time(s) but was + * // executed 0 time(s).', + * // actual: 0, + * // expected: 2, + * // operator: 'func', + * // stack: stack trace + * // } + * // ] + * ``` + * @since v14.2.0, v12.19.0 + * @return of objects containing information about the wrapper functions returned by `calls`. + */ + report(): CallTrackerReportInformation[]; + /** + * Reset calls of the call tracker. + * If a tracked function is passed as an argument, the calls will be reset for it. + * If no arguments are passed, all tracked functions will be reset. + * + * ```js + * import assert from 'node:assert'; + * + * const tracker = new assert.CallTracker(); + * + * function func() {} + * const callsfunc = tracker.calls(func); + * + * callsfunc(); + * // Tracker was called once + * tracker.getCalls(callsfunc).length === 1; + * + * tracker.reset(callsfunc); + * tracker.getCalls(callsfunc).length === 0; + * ``` + * + * @since v18.8.0, v16.18.0 + * @param fn a tracked function to reset. + */ + reset(fn?: Function): void; + /** + * Iterates through the list of functions passed to `tracker.calls()` and will throw an error for functions that + * have not been called the expected number of times. + * + * ```js + * import assert from 'assert'; + * + * // Creates call tracker. + * const tracker = new assert.CallTracker(); + * + * function func() {} + * + * // Returns a function that wraps func() that must be called exact times + * // before tracker.verify(). + * const callsfunc = tracker.calls(func, 2); + * + * callsfunc(); + * + * // Will throw an error since callsfunc() was only called once. + * tracker.verify(); + * ``` + * @since v14.2.0, v12.19.0 + */ + verify(): void; + } + interface CallTrackerCall { + thisArg: object; + arguments: unknown[]; + } + interface CallTrackerReportInformation { + message: string; + /** The actual number of times the function was called. */ + actual: number; + /** The number of times the function was expected to be called. */ + expected: number; + /** The name of the function that is wrapped. */ + operator: string; + /** A stack trace of the function. */ + stack: object; + } + type AssertPredicate = RegExp | (new() => object) | ((thrown: unknown) => boolean) | object | Error; + /** + * Throws an `AssertionError` with the provided error message or a default + * error message. If the `message` parameter is an instance of an `Error` then + * it will be thrown instead of the `AssertionError`. + * + * ```js + * import assert from 'assert/strict'; + * + * assert.fail(); + * // AssertionError [ERR_ASSERTION]: Failed + * + * assert.fail('boom'); + * // AssertionError [ERR_ASSERTION]: boom + * + * assert.fail(new TypeError('need array')); + * // TypeError: need array + * ``` + * + * Using `assert.fail()` with more than two arguments is possible but deprecated. + * See below for further details. + * @since v0.1.21 + * @param [message='Failed'] + */ + function fail(message?: string | Error): never; + /** @deprecated since v10.0.0 - use fail([message]) or other assert functions instead. */ + function fail( + actual: unknown, + expected: unknown, + message?: string | Error, + operator?: string, + // eslint-disable-next-line @typescript-eslint/ban-types + stackStartFn?: Function, + ): never; + /** + * Tests if `value` is truthy. It is equivalent to`assert.equal(!!value, true, message)`. + * + * If `value` is not truthy, an `AssertionError` is thrown with a `message`property set equal to the value of the `message` parameter. If the `message`parameter is `undefined`, a default + * error message is assigned. If the `message`parameter is an instance of an `Error` then it will be thrown instead of the`AssertionError`. + * If no arguments are passed in at all `message` will be set to the string:`` 'No value argument passed to `assert.ok()`' ``. + * + * Be aware that in the `repl` the error message will be different to the one + * thrown in a file! See below for further details. + * + * ```js + * import assert from 'assert/strict'; + * + * assert.ok(true); + * // OK + * assert.ok(1); + * // OK + * + * assert.ok(); + * // AssertionError: No value argument passed to `assert.ok()` + * + * assert.ok(false, 'it\'s false'); + * // AssertionError: it's false + * + * // In the repl: + * assert.ok(typeof 123 === 'string'); + * // AssertionError: false == true + * + * // In a file (e.g. test.js): + * assert.ok(typeof 123 === 'string'); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert.ok(typeof 123 === 'string') + * + * assert.ok(false); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert.ok(false) + * + * assert.ok(0); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert.ok(0) + * ``` + * + * ```js + * import assert from 'assert/strict'; + * + * // Using `assert()` works the same: + * assert(0); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert(0) + * ``` + * @since v0.1.21 + */ + function ok(value: unknown, message?: string | Error): asserts value; + /** + * **Strict assertion mode** + * + * An alias of {@link strictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link strictEqual} instead. + * + * Tests shallow, coercive equality between the `actual` and `expected` parameters + * using the [`==` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Equality). `NaN` is specially handled + * and treated as being identical if both sides are `NaN`. + * + * ```js + * import assert from 'assert'; + * + * assert.equal(1, 1); + * // OK, 1 == 1 + * assert.equal(1, '1'); + * // OK, 1 == '1' + * assert.equal(NaN, NaN); + * // OK + * + * assert.equal(1, 2); + * // AssertionError: 1 == 2 + * assert.equal({ a: { b: 1 } }, { a: { b: 1 } }); + * // AssertionError: { a: { b: 1 } } == { a: { b: 1 } } + * ``` + * + * If the values are not equal, an `AssertionError` is thrown with a `message`property set equal to the value of the `message` parameter. If the `message`parameter is undefined, a default + * error message is assigned. If the `message`parameter is an instance of an `Error` then it will be thrown instead of the`AssertionError`. + * @since v0.1.21 + */ + function equal(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * **Strict assertion mode** + * + * An alias of {@link notStrictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link notStrictEqual} instead. + * + * Tests shallow, coercive inequality with the [`!=` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Inequality). `NaN` is + * specially handled and treated as being identical if both sides are `NaN`. + * + * ```js + * import assert from 'assert'; + * + * assert.notEqual(1, 2); + * // OK + * + * assert.notEqual(1, 1); + * // AssertionError: 1 != 1 + * + * assert.notEqual(1, '1'); + * // AssertionError: 1 != '1' + * ``` + * + * If the values are equal, an `AssertionError` is thrown with a `message`property set equal to the value of the `message` parameter. If the `message`parameter is undefined, a default error + * message is assigned. If the `message`parameter is an instance of an `Error` then it will be thrown instead of the`AssertionError`. + * @since v0.1.21 + */ + function notEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * **Strict assertion mode** + * + * An alias of {@link deepStrictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link deepStrictEqual} instead. + * + * Tests for deep equality between the `actual` and `expected` parameters. Consider + * using {@link deepStrictEqual} instead. {@link deepEqual} can have + * surprising results. + * + * _Deep equality_ means that the enumerable "own" properties of child objects + * are also recursively evaluated by the following rules. + * @since v0.1.21 + */ + function deepEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * **Strict assertion mode** + * + * An alias of {@link notDeepStrictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link notDeepStrictEqual} instead. + * + * Tests for any deep inequality. Opposite of {@link deepEqual}. + * + * ```js + * import assert from 'assert'; + * + * const obj1 = { + * a: { + * b: 1 + * } + * }; + * const obj2 = { + * a: { + * b: 2 + * } + * }; + * const obj3 = { + * a: { + * b: 1 + * } + * }; + * const obj4 = Object.create(obj1); + * + * assert.notDeepEqual(obj1, obj1); + * // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } } + * + * assert.notDeepEqual(obj1, obj2); + * // OK + * + * assert.notDeepEqual(obj1, obj3); + * // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } } + * + * assert.notDeepEqual(obj1, obj4); + * // OK + * ``` + * + * If the values are deeply equal, an `AssertionError` is thrown with a`message` property set equal to the value of the `message` parameter. If the`message` parameter is undefined, a default + * error message is assigned. If the`message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v0.1.21 + */ + function notDeepEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * Tests strict equality between the `actual` and `expected` parameters as + * determined by [`Object.is()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). + * + * ```js + * import assert from 'assert/strict'; + * + * assert.strictEqual(1, 2); + * // AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal: + * // + * // 1 !== 2 + * + * assert.strictEqual(1, 1); + * // OK + * + * assert.strictEqual('Hello foobar', 'Hello World!'); + * // AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal: + * // + actual - expected + * // + * // + 'Hello foobar' + * // - 'Hello World!' + * // ^ + * + * const apples = 1; + * const oranges = 2; + * assert.strictEqual(apples, oranges, `apples ${apples} !== oranges ${oranges}`); + * // AssertionError [ERR_ASSERTION]: apples 1 !== oranges 2 + * + * assert.strictEqual(1, '1', new TypeError('Inputs are not identical')); + * // TypeError: Inputs are not identical + * ``` + * + * If the values are not strictly equal, an `AssertionError` is thrown with a`message` property set equal to the value of the `message` parameter. If the`message` parameter is undefined, a + * default error message is assigned. If the`message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v0.1.21 + */ + function strictEqual(actual: unknown, expected: T, message?: string | Error): asserts actual is T; + /** + * Tests strict inequality between the `actual` and `expected` parameters as + * determined by [`Object.is()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). + * + * ```js + * import assert from 'assert/strict'; + * + * assert.notStrictEqual(1, 2); + * // OK + * + * assert.notStrictEqual(1, 1); + * // AssertionError [ERR_ASSERTION]: Expected "actual" to be strictly unequal to: + * // + * // 1 + * + * assert.notStrictEqual(1, '1'); + * // OK + * ``` + * + * If the values are strictly equal, an `AssertionError` is thrown with a`message` property set equal to the value of the `message` parameter. If the`message` parameter is undefined, a + * default error message is assigned. If the`message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v0.1.21 + */ + function notStrictEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * Tests for deep equality between the `actual` and `expected` parameters. + * "Deep" equality means that the enumerable "own" properties of child objects + * are recursively evaluated also by the following rules. + * @since v1.2.0 + */ + function deepStrictEqual(actual: unknown, expected: T, message?: string | Error): asserts actual is T; + /** + * Tests for deep strict inequality. Opposite of {@link deepStrictEqual}. + * + * ```js + * import assert from 'assert/strict'; + * + * assert.notDeepStrictEqual({ a: 1 }, { a: '1' }); + * // OK + * ``` + * + * If the values are deeply and strictly equal, an `AssertionError` is thrown + * with a `message` property set equal to the value of the `message` parameter. If + * the `message` parameter is undefined, a default error message is assigned. If + * the `message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v1.2.0 + */ + function notDeepStrictEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * Expects the function `fn` to throw an error. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), a validation function, + * a validation object where each property will be tested for strict deep equality, + * or an instance of error where each property will be tested for strict deep + * equality including the non-enumerable `message` and `name` properties. When + * using an object, it is also possible to use a regular expression, when + * validating against a string property. See below for examples. + * + * If specified, `message` will be appended to the message provided by the`AssertionError` if the `fn` call fails to throw or in case the error validation + * fails. + * + * Custom validation object/error instance: + * + * ```js + * import assert from 'assert/strict'; + * + * const err = new TypeError('Wrong value'); + * err.code = 404; + * err.foo = 'bar'; + * err.info = { + * nested: true, + * baz: 'text' + * }; + * err.reg = /abc/i; + * + * assert.throws( + * () => { + * throw err; + * }, + * { + * name: 'TypeError', + * message: 'Wrong value', + * info: { + * nested: true, + * baz: 'text' + * } + * // Only properties on the validation object will be tested for. + * // Using nested objects requires all properties to be present. Otherwise + * // the validation is going to fail. + * } + * ); + * + * // Using regular expressions to validate error properties: + * throws( + * () => { + * throw err; + * }, + * { + * // The `name` and `message` properties are strings and using regular + * // expressions on those will match against the string. If they fail, an + * // error is thrown. + * name: /^TypeError$/, + * message: /Wrong/, + * foo: 'bar', + * info: { + * nested: true, + * // It is not possible to use regular expressions for nested properties! + * baz: 'text' + * }, + * // The `reg` property contains a regular expression and only if the + * // validation object contains an identical regular expression, it is going + * // to pass. + * reg: /abc/i + * } + * ); + * + * // Fails due to the different `message` and `name` properties: + * throws( + * () => { + * const otherErr = new Error('Not found'); + * // Copy all enumerable properties from `err` to `otherErr`. + * for (const [key, value] of Object.entries(err)) { + * otherErr[key] = value; + * } + * throw otherErr; + * }, + * // The error's `message` and `name` properties will also be checked when using + * // an error as validation object. + * err + * ); + * ``` + * + * Validate instanceof using constructor: + * + * ```js + * import assert from 'assert/strict'; + * + * assert.throws( + * () => { + * throw new Error('Wrong value'); + * }, + * Error + * ); + * ``` + * + * Validate error message using [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions): + * + * Using a regular expression runs `.toString` on the error object, and will + * therefore also include the error name. + * + * ```js + * import assert from 'assert/strict'; + * + * assert.throws( + * () => { + * throw new Error('Wrong value'); + * }, + * /^Error: Wrong value$/ + * ); + * ``` + * + * Custom error validation: + * + * The function must return `true` to indicate all internal validations passed. + * It will otherwise fail with an `AssertionError`. + * + * ```js + * import assert from 'assert/strict'; + * + * assert.throws( + * () => { + * throw new Error('Wrong value'); + * }, + * (err) => { + * assert(err instanceof Error); + * assert(/value/.test(err)); + * // Avoid returning anything from validation functions besides `true`. + * // Otherwise, it's not clear what part of the validation failed. Instead, + * // throw an error about the specific validation that failed (as done in this + * // example) and add as much helpful debugging information to that error as + * // possible. + * return true; + * }, + * 'unexpected error' + * ); + * ``` + * + * `error` cannot be a string. If a string is provided as the second + * argument, then `error` is assumed to be omitted and the string will be used for`message` instead. This can lead to easy-to-miss mistakes. Using the same + * message as the thrown error message is going to result in an`ERR_AMBIGUOUS_ARGUMENT` error. Please read the example below carefully if using + * a string as the second argument gets considered: + * + * ```js + * import assert from 'assert/strict'; + * + * function throwingFirst() { + * throw new Error('First'); + * } + * + * function throwingSecond() { + * throw new Error('Second'); + * } + * + * function notThrowing() {} + * + * // The second argument is a string and the input function threw an Error. + * // The first case will not throw as it does not match for the error message + * // thrown by the input function! + * assert.throws(throwingFirst, 'Second'); + * // In the next example the message has no benefit over the message from the + * // error and since it is not clear if the user intended to actually match + * // against the error message, Node.js throws an `ERR_AMBIGUOUS_ARGUMENT` error. + * assert.throws(throwingSecond, 'Second'); + * // TypeError [ERR_AMBIGUOUS_ARGUMENT] + * + * // The string is only used (as message) in case the function does not throw: + * assert.throws(notThrowing, 'Second'); + * // AssertionError [ERR_ASSERTION]: Missing expected exception: Second + * + * // If it was intended to match for the error message do this instead: + * // It does not throw because the error messages match. + * assert.throws(throwingSecond, /Second$/); + * + * // If the error message does not match, an AssertionError is thrown. + * assert.throws(throwingFirst, /Second$/); + * // AssertionError [ERR_ASSERTION] + * ``` + * + * Due to the confusing error-prone notation, avoid a string as the second + * argument. + * @since v0.1.21 + */ + function throws(block: () => unknown, message?: string | Error): void; + function throws(block: () => unknown, error: AssertPredicate, message?: string | Error): void; + /** + * Asserts that the function `fn` does not throw an error. + * + * Using `assert.doesNotThrow()` is actually not useful because there + * is no benefit in catching an error and then rethrowing it. Instead, consider + * adding a comment next to the specific code path that should not throw and keep + * error messages as expressive as possible. + * + * When `assert.doesNotThrow()` is called, it will immediately call the `fn`function. + * + * If an error is thrown and it is the same type as that specified by the `error`parameter, then an `AssertionError` is thrown. If the error is of a + * different type, or if the `error` parameter is undefined, the error is + * propagated back to the caller. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) or a validation + * function. See {@link throws} for more details. + * + * The following, for instance, will throw the `TypeError` because there is no + * matching error type in the assertion: + * + * ```js + * import assert from 'assert/strict'; + * + * assert.doesNotThrow( + * () => { + * throw new TypeError('Wrong value'); + * }, + * SyntaxError + * ); + * ``` + * + * However, the following will result in an `AssertionError` with the message + * 'Got unwanted exception...': + * + * ```js + * import assert from 'assert/strict'; + * + * assert.doesNotThrow( + * () => { + * throw new TypeError('Wrong value'); + * }, + * TypeError + * ); + * ``` + * + * If an `AssertionError` is thrown and a value is provided for the `message`parameter, the value of `message` will be appended to the `AssertionError` message: + * + * ```js + * import assert from 'assert/strict'; + * + * assert.doesNotThrow( + * () => { + * throw new TypeError('Wrong value'); + * }, + * /Wrong value/, + * 'Whoops' + * ); + * // Throws: AssertionError: Got unwanted exception: Whoops + * ``` + * @since v0.1.21 + */ + function doesNotThrow(block: () => unknown, message?: string | Error): void; + function doesNotThrow(block: () => unknown, error: AssertPredicate, message?: string | Error): void; + /** + * Throws `value` if `value` is not `undefined` or `null`. This is useful when + * testing the `error` argument in callbacks. The stack trace contains all frames + * from the error passed to `ifError()` including the potential new frames for`ifError()` itself. + * + * ```js + * import assert from 'assert/strict'; + * + * assert.ifError(null); + * // OK + * assert.ifError(0); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 0 + * assert.ifError('error'); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 'error' + * assert.ifError(new Error()); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: Error + * + * // Create some random error frames. + * let err; + * (function errorFrame() { + * err = new Error('test error'); + * })(); + * + * (function ifErrorFrame() { + * assert.ifError(err); + * })(); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: test error + * // at ifErrorFrame + * // at errorFrame + * ``` + * @since v0.1.97 + */ + function ifError(value: unknown): asserts value is null | undefined; + /** + * Awaits the `asyncFn` promise or, if `asyncFn` is a function, immediately + * calls the function and awaits the returned promise to complete. It will then + * check that the promise is rejected. + * + * If `asyncFn` is a function and it throws an error synchronously,`assert.rejects()` will return a rejected `Promise` with that error. If the + * function does not return a promise, `assert.rejects()` will return a rejected`Promise` with an `ERR_INVALID_RETURN_VALUE` error. In both cases the error + * handler is skipped. + * + * Besides the async nature to await the completion behaves identically to {@link throws}. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), a validation function, + * an object where each property will be tested for, or an instance of error where + * each property will be tested for including the non-enumerable `message` and`name` properties. + * + * If specified, `message` will be the message provided by the `AssertionError` if the `asyncFn` fails to reject. + * + * ```js + * import assert from 'assert/strict'; + * + * await assert.rejects( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * { + * name: 'TypeError', + * message: 'Wrong value' + * } + * ); + * ``` + * + * ```js + * import assert from 'assert/strict'; + * + * await assert.rejects( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * (err) => { + * assert.strictEqual(err.name, 'TypeError'); + * assert.strictEqual(err.message, 'Wrong value'); + * return true; + * } + * ); + * ``` + * + * ```js + * import assert from 'assert/strict'; + * + * assert.rejects( + * Promise.reject(new Error('Wrong value')), + * Error + * ).then(() => { + * // ... + * }); + * ``` + * + * `error` cannot be a string. If a string is provided as the second + * argument, then `error` is assumed to be omitted and the string will be used for`message` instead. This can lead to easy-to-miss mistakes. Please read the + * example in {@link throws} carefully if using a string as the second + * argument gets considered. + * @since v10.0.0 + */ + function rejects(block: (() => Promise) | Promise, message?: string | Error): Promise; + function rejects( + block: (() => Promise) | Promise, + error: AssertPredicate, + message?: string | Error, + ): Promise; + /** + * Awaits the `asyncFn` promise or, if `asyncFn` is a function, immediately + * calls the function and awaits the returned promise to complete. It will then + * check that the promise is not rejected. + * + * If `asyncFn` is a function and it throws an error synchronously,`assert.doesNotReject()` will return a rejected `Promise` with that error. If + * the function does not return a promise, `assert.doesNotReject()` will return a + * rejected `Promise` with an `ERR_INVALID_RETURN_VALUE` error. In both cases + * the error handler is skipped. + * + * Using `assert.doesNotReject()` is actually not useful because there is little + * benefit in catching a rejection and then rejecting it again. Instead, consider + * adding a comment next to the specific code path that should not reject and keep + * error messages as expressive as possible. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) or a validation + * function. See {@link throws} for more details. + * + * Besides the async nature to await the completion behaves identically to {@link doesNotThrow}. + * + * ```js + * import assert from 'assert/strict'; + * + * await assert.doesNotReject( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * SyntaxError + * ); + * ``` + * + * ```js + * import assert from 'assert/strict'; + * + * assert.doesNotReject(Promise.reject(new TypeError('Wrong value'))) + * .then(() => { + * // ... + * }); + * ``` + * @since v10.0.0 + */ + function doesNotReject( + block: (() => Promise) | Promise, + message?: string | Error, + ): Promise; + function doesNotReject( + block: (() => Promise) | Promise, + error: AssertPredicate, + message?: string | Error, + ): Promise; + /** + * Expects the `string` input to match the regular expression. + * + * ```js + * import assert from 'assert/strict'; + * + * assert.match('I will fail', /pass/); + * // AssertionError [ERR_ASSERTION]: The input did not match the regular ... + * + * assert.match(123, /pass/); + * // AssertionError [ERR_ASSERTION]: The "string" argument must be of type string. + * + * assert.match('I will pass', /pass/); + * // OK + * ``` + * + * If the values do not match, or if the `string` argument is of another type than`string`, an `AssertionError` is thrown with a `message` property set equal + * to the value of the `message` parameter. If the `message` parameter is + * undefined, a default error message is assigned. If the `message` parameter is an + * instance of an `Error` then it will be thrown instead of the `AssertionError`. + * @since v13.6.0, v12.16.0 + */ + function match(value: string, regExp: RegExp, message?: string | Error): void; + /** + * Expects the `string` input not to match the regular expression. + * + * ```js + * import assert from 'assert/strict'; + * + * assert.doesNotMatch('I will fail', /fail/); + * // AssertionError [ERR_ASSERTION]: The input was expected to not match the ... + * + * assert.doesNotMatch(123, /pass/); + * // AssertionError [ERR_ASSERTION]: The "string" argument must be of type string. + * + * assert.doesNotMatch('I will pass', /different/); + * // OK + * ``` + * + * If the values do match, or if the `string` argument is of another type than`string`, an `AssertionError` is thrown with a `message` property set equal + * to the value of the `message` parameter. If the `message` parameter is + * undefined, a default error message is assigned. If the `message` parameter is an + * instance of an `Error` then it will be thrown instead of the `AssertionError`. + * @since v13.6.0, v12.16.0 + */ + function doesNotMatch(value: string, regExp: RegExp, message?: string | Error): void; + const strict: + & Omit< + typeof assert, + | "equal" + | "notEqual" + | "deepEqual" + | "notDeepEqual" + | "ok" + | "strictEqual" + | "deepStrictEqual" + | "ifError" + | "strict" + > + & { + (value: unknown, message?: string | Error): asserts value; + equal: typeof strictEqual; + notEqual: typeof notStrictEqual; + deepEqual: typeof deepStrictEqual; + notDeepEqual: typeof notDeepStrictEqual; + // Mapped types and assertion functions are incompatible? + // TS2775: Assertions require every name in the call target + // to be declared with an explicit type annotation. + ok: typeof ok; + strictEqual: typeof strictEqual; + deepStrictEqual: typeof deepStrictEqual; + ifError: typeof ifError; + strict: typeof strict; + }; + } + export = assert; +} +declare module "node:assert" { + import assert = require("assert"); + export = assert; +} diff --git a/backend/node_modules/@types/node/assert/strict.d.ts b/backend/node_modules/@types/node/assert/strict.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f333913a4565f7067b05ddbc415490e585f2d1e1 --- /dev/null +++ b/backend/node_modules/@types/node/assert/strict.d.ts @@ -0,0 +1,8 @@ +declare module "assert/strict" { + import { strict } from "node:assert"; + export = strict; +} +declare module "node:assert/strict" { + import { strict } from "node:assert"; + export = strict; +} diff --git a/backend/node_modules/@types/node/async_hooks.d.ts b/backend/node_modules/@types/node/async_hooks.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1ae688538873eb682a847c38629d40e627a1395e --- /dev/null +++ b/backend/node_modules/@types/node/async_hooks.d.ts @@ -0,0 +1,522 @@ +/** + * The `async_hooks` module provides an API to track asynchronous resources. It + * can be accessed using: + * + * ```js + * import async_hooks from 'async_hooks'; + * ``` + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/async_hooks.js) + */ +declare module "async_hooks" { + /** + * ```js + * import { executionAsyncId } from 'async_hooks'; + * + * console.log(executionAsyncId()); // 1 - bootstrap + * fs.open(path, 'r', (err, fd) => { + * console.log(executionAsyncId()); // 6 - open() + * }); + * ``` + * + * The ID returned from `executionAsyncId()` is related to execution timing, not + * causality (which is covered by `triggerAsyncId()`): + * + * ```js + * const server = net.createServer((conn) => { + * // Returns the ID of the server, not of the new connection, because the + * // callback runs in the execution scope of the server's MakeCallback(). + * async_hooks.executionAsyncId(); + * + * }).listen(port, () => { + * // Returns the ID of a TickObject (process.nextTick()) because all + * // callbacks passed to .listen() are wrapped in a nextTick(). + * async_hooks.executionAsyncId(); + * }); + * ``` + * + * Promise contexts may not get precise `executionAsyncIds` by default. + * See the section on `promise execution tracking`. + * @since v8.1.0 + * @return The `asyncId` of the current execution context. Useful to track when something calls. + */ + function executionAsyncId(): number; + /** + * Resource objects returned by `executionAsyncResource()` are most often internal + * Node.js handle objects with undocumented APIs. Using any functions or properties + * on the object is likely to crash your application and should be avoided. + * + * Using `executionAsyncResource()` in the top-level execution context will + * return an empty object as there is no handle or request object to use, + * but having an object representing the top-level can be helpful. + * + * ```js + * import { open } from 'fs'; + * import { executionAsyncId, executionAsyncResource } from 'async_hooks'; + * + * console.log(executionAsyncId(), executionAsyncResource()); // 1 {} + * open(new URL(import.meta.url), 'r', (err, fd) => { + * console.log(executionAsyncId(), executionAsyncResource()); // 7 FSReqWrap + * }); + * ``` + * + * This can be used to implement continuation local storage without the + * use of a tracking `Map` to store the metadata: + * + * ```js + * import { createServer } from 'http'; + * import { + * executionAsyncId, + * executionAsyncResource, + * createHook + * } from 'async_hooks'; + * const sym = Symbol('state'); // Private symbol to avoid pollution + * + * createHook({ + * init(asyncId, type, triggerAsyncId, resource) { + * const cr = executionAsyncResource(); + * if (cr) { + * resource[sym] = cr[sym]; + * } + * } + * }).enable(); + * + * const server = createServer((req, res) => { + * executionAsyncResource()[sym] = { state: req.url }; + * setTimeout(function() { + * res.end(JSON.stringify(executionAsyncResource()[sym])); + * }, 100); + * }).listen(3000); + * ``` + * @since v13.9.0, v12.17.0 + * @return The resource representing the current execution. Useful to store data within the resource. + */ + function executionAsyncResource(): object; + /** + * ```js + * const server = net.createServer((conn) => { + * // The resource that caused (or triggered) this callback to be called + * // was that of the new connection. Thus the return value of triggerAsyncId() + * // is the asyncId of "conn". + * async_hooks.triggerAsyncId(); + * + * }).listen(port, () => { + * // Even though all callbacks passed to .listen() are wrapped in a nextTick() + * // the callback itself exists because the call to the server's .listen() + * // was made. So the return value would be the ID of the server. + * async_hooks.triggerAsyncId(); + * }); + * ``` + * + * Promise contexts may not get valid `triggerAsyncId`s by default. See + * the section on `promise execution tracking`. + * @return The ID of the resource responsible for calling the callback that is currently being executed. + */ + function triggerAsyncId(): number; + interface HookCallbacks { + /** + * Called when a class is constructed that has the possibility to emit an asynchronous event. + * @param asyncId a unique ID for the async resource + * @param type the type of the async resource + * @param triggerAsyncId the unique ID of the async resource in whose execution context this async resource was created + * @param resource reference to the resource representing the async operation, needs to be released during destroy + */ + init?(asyncId: number, type: string, triggerAsyncId: number, resource: object): void; + /** + * When an asynchronous operation is initiated or completes a callback is called to notify the user. + * The before callback is called just before said callback is executed. + * @param asyncId the unique identifier assigned to the resource about to execute the callback. + */ + before?(asyncId: number): void; + /** + * Called immediately after the callback specified in before is completed. + * @param asyncId the unique identifier assigned to the resource which has executed the callback. + */ + after?(asyncId: number): void; + /** + * Called when a promise has resolve() called. This may not be in the same execution id + * as the promise itself. + * @param asyncId the unique id for the promise that was resolve()d. + */ + promiseResolve?(asyncId: number): void; + /** + * Called after the resource corresponding to asyncId is destroyed + * @param asyncId a unique ID for the async resource + */ + destroy?(asyncId: number): void; + } + interface AsyncHook { + /** + * Enable the callbacks for a given AsyncHook instance. If no callbacks are provided enabling is a noop. + */ + enable(): this; + /** + * Disable the callbacks for a given AsyncHook instance from the global pool of AsyncHook callbacks to be executed. Once a hook has been disabled it will not be called again until enabled. + */ + disable(): this; + } + /** + * Registers functions to be called for different lifetime events of each async + * operation. + * + * The callbacks `init()`/`before()`/`after()`/`destroy()` are called for the + * respective asynchronous event during a resource's lifetime. + * + * All callbacks are optional. For example, if only resource cleanup needs to + * be tracked, then only the `destroy` callback needs to be passed. The + * specifics of all functions that can be passed to `callbacks` is in the `Hook Callbacks` section. + * + * ```js + * import { createHook } from 'async_hooks'; + * + * const asyncHook = createHook({ + * init(asyncId, type, triggerAsyncId, resource) { }, + * destroy(asyncId) { } + * }); + * ``` + * + * The callbacks will be inherited via the prototype chain: + * + * ```js + * class MyAsyncCallbacks { + * init(asyncId, type, triggerAsyncId, resource) { } + * destroy(asyncId) {} + * } + * + * class MyAddedCallbacks extends MyAsyncCallbacks { + * before(asyncId) { } + * after(asyncId) { } + * } + * + * const asyncHook = async_hooks.createHook(new MyAddedCallbacks()); + * ``` + * + * Because promises are asynchronous resources whose lifecycle is tracked + * via the async hooks mechanism, the `init()`, `before()`, `after()`, and`destroy()` callbacks _must not_ be async functions that return promises. + * @since v8.1.0 + * @param callbacks The `Hook Callbacks` to register + * @return Instance used for disabling and enabling hooks + */ + function createHook(callbacks: HookCallbacks): AsyncHook; + interface AsyncResourceOptions { + /** + * The ID of the execution context that created this async event. + * @default executionAsyncId() + */ + triggerAsyncId?: number | undefined; + /** + * Disables automatic `emitDestroy` when the object is garbage collected. + * This usually does not need to be set (even if `emitDestroy` is called + * manually), unless the resource's `asyncId` is retrieved and the + * sensitive API's `emitDestroy` is called with it. + * @default false + */ + requireManualDestroy?: boolean | undefined; + } + /** + * The class `AsyncResource` is designed to be extended by the embedder's async + * resources. Using this, users can easily trigger the lifetime events of their + * own resources. + * + * The `init` hook will trigger when an `AsyncResource` is instantiated. + * + * The following is an overview of the `AsyncResource` API. + * + * ```js + * import { AsyncResource, executionAsyncId } from 'async_hooks'; + * + * // AsyncResource() is meant to be extended. Instantiating a + * // new AsyncResource() also triggers init. If triggerAsyncId is omitted then + * // async_hook.executionAsyncId() is used. + * const asyncResource = new AsyncResource( + * type, { triggerAsyncId: executionAsyncId(), requireManualDestroy: false } + * ); + * + * // Run a function in the execution context of the resource. This will + * // * establish the context of the resource + * // * trigger the AsyncHooks before callbacks + * // * call the provided function `fn` with the supplied arguments + * // * trigger the AsyncHooks after callbacks + * // * restore the original execution context + * asyncResource.runInAsyncScope(fn, thisArg, ...args); + * + * // Call AsyncHooks destroy callbacks. + * asyncResource.emitDestroy(); + * + * // Return the unique ID assigned to the AsyncResource instance. + * asyncResource.asyncId(); + * + * // Return the trigger ID for the AsyncResource instance. + * asyncResource.triggerAsyncId(); + * ``` + */ + class AsyncResource { + /** + * AsyncResource() is meant to be extended. Instantiating a + * new AsyncResource() also triggers init. If triggerAsyncId is omitted then + * async_hook.executionAsyncId() is used. + * @param type The type of async event. + * @param triggerAsyncId The ID of the execution context that created + * this async event (default: `executionAsyncId()`), or an + * AsyncResourceOptions object (since v9.3.0) + */ + constructor(type: string, triggerAsyncId?: number | AsyncResourceOptions); + /** + * Binds the given function to the current execution context. + * + * The returned function will have an `asyncResource` property referencing + * the `AsyncResource` to which the function is bound. + * @since v14.8.0, v12.19.0 + * @param fn The function to bind to the current execution context. + * @param type An optional name to associate with the underlying `AsyncResource`. + */ + static bind any, ThisArg>( + fn: Func, + type?: string, + thisArg?: ThisArg, + ): Func & { + asyncResource: AsyncResource; + }; + /** + * Binds the given function to execute to this `AsyncResource`'s scope. + * + * The returned function will have an `asyncResource` property referencing + * the `AsyncResource` to which the function is bound. + * @since v14.8.0, v12.19.0 + * @param fn The function to bind to the current `AsyncResource`. + */ + bind any>( + fn: Func, + ): Func & { + asyncResource: AsyncResource; + }; + /** + * Call the provided function with the provided arguments in the execution context + * of the async resource. This will establish the context, trigger the AsyncHooks + * before callbacks, call the function, trigger the AsyncHooks after callbacks, and + * then restore the original execution context. + * @since v9.6.0 + * @param fn The function to call in the execution context of this async resource. + * @param thisArg The receiver to be used for the function call. + * @param args Optional arguments to pass to the function. + */ + runInAsyncScope( + fn: (this: This, ...args: any[]) => Result, + thisArg?: This, + ...args: any[] + ): Result; + /** + * Call all `destroy` hooks. This should only ever be called once. An error will + * be thrown if it is called more than once. This **must** be manually called. If + * the resource is left to be collected by the GC then the `destroy` hooks will + * never be called. + * @return A reference to `asyncResource`. + */ + emitDestroy(): this; + /** + * @return The unique `asyncId` assigned to the resource. + */ + asyncId(): number; + /** + * @return The same `triggerAsyncId` that is passed to the `AsyncResource` constructor. + */ + triggerAsyncId(): number; + } + /** + * This class creates stores that stay coherent through asynchronous operations. + * + * While you can create your own implementation on top of the `async_hooks` module,`AsyncLocalStorage` should be preferred as it is a performant and memory safe + * implementation that involves significant optimizations that are non-obvious to + * implement. + * + * The following example uses `AsyncLocalStorage` to build a simple logger + * that assigns IDs to incoming HTTP requests and includes them in messages + * logged within each request. + * + * ```js + * import http from 'http'; + * import { AsyncLocalStorage } from 'async_hooks'; + * + * const asyncLocalStorage = new AsyncLocalStorage(); + * + * function logWithId(msg) { + * const id = asyncLocalStorage.getStore(); + * console.log(`${id !== undefined ? id : '-'}:`, msg); + * } + * + * let idSeq = 0; + * http.createServer((req, res) => { + * asyncLocalStorage.run(idSeq++, () => { + * logWithId('start'); + * // Imagine any chain of async operations here + * setImmediate(() => { + * logWithId('finish'); + * res.end(); + * }); + * }); + * }).listen(8080); + * + * http.get('http://localhost:8080'); + * http.get('http://localhost:8080'); + * // Prints: + * // 0: start + * // 1: start + * // 0: finish + * // 1: finish + * ``` + * + * Each instance of `AsyncLocalStorage` maintains an independent storage context. + * Multiple instances can safely exist simultaneously without risk of interfering + * with each other's data. + * @since v13.10.0, v12.17.0 + */ + class AsyncLocalStorage { + /** + * Binds the given function to the current execution context. + * @since v18.16.0 + * @param fn The function to bind to the current execution context. + * @returns A new function that calls `fn` within the captured execution context. + */ + static bind any>(fn: Func): Func & { + asyncResource: AsyncResource; + }; + /** + * Captures the current execution context and returns a function that accepts a function as an argument. + * Whenever the returned function is called, it calls the function passed to it within the captured context. + * @since v18.16.0 + */ + static snapshot(): ((fn: (...args: TArgs) => R, ...args: TArgs) => R) & { + asyncResource: AsyncResource; + }; + /** + * Disables the instance of `AsyncLocalStorage`. All subsequent calls + * to `asyncLocalStorage.getStore()` will return `undefined` until`asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()` is called again. + * + * When calling `asyncLocalStorage.disable()`, all current contexts linked to the + * instance will be exited. + * + * Calling `asyncLocalStorage.disable()` is required before the`asyncLocalStorage` can be garbage collected. This does not apply to stores + * provided by the `asyncLocalStorage`, as those objects are garbage collected + * along with the corresponding async resources. + * + * Use this method when the `asyncLocalStorage` is not in use anymore + * in the current process. + * @since v13.10.0, v12.17.0 + * @experimental + */ + disable(): void; + /** + * Returns the current store. + * If called outside of an asynchronous context initialized by + * calling `asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()`, it + * returns `undefined`. + * @since v13.10.0, v12.17.0 + */ + getStore(): T | undefined; + /** + * Runs a function synchronously within a context and returns its + * return value. The store is not accessible outside of the callback function. + * The store is accessible to any asynchronous operations created within the + * callback. + * + * The optional `args` are passed to the callback function. + * + * If the callback function throws an error, the error is thrown by `run()` too. + * The stacktrace is not impacted by this call and the context is exited. + * + * Example: + * + * ```js + * const store = { id: 2 }; + * try { + * asyncLocalStorage.run(store, () => { + * asyncLocalStorage.getStore(); // Returns the store object + * setTimeout(() => { + * asyncLocalStorage.getStore(); // Returns the store object + * }, 200); + * throw new Error(); + * }); + * } catch (e) { + * asyncLocalStorage.getStore(); // Returns undefined + * // The error will be caught here + * } + * ``` + * @since v13.10.0, v12.17.0 + */ + run(store: T, callback: () => R): R; + run(store: T, callback: (...args: TArgs) => R, ...args: TArgs): R; + /** + * Runs a function synchronously outside of a context and returns its + * return value. The store is not accessible within the callback function or + * the asynchronous operations created within the callback. Any `getStore()`call done within the callback function will always return `undefined`. + * + * The optional `args` are passed to the callback function. + * + * If the callback function throws an error, the error is thrown by `exit()` too. + * The stacktrace is not impacted by this call and the context is re-entered. + * + * Example: + * + * ```js + * // Within a call to run + * try { + * asyncLocalStorage.getStore(); // Returns the store object or value + * asyncLocalStorage.exit(() => { + * asyncLocalStorage.getStore(); // Returns undefined + * throw new Error(); + * }); + * } catch (e) { + * asyncLocalStorage.getStore(); // Returns the same object or value + * // The error will be caught here + * } + * ``` + * @since v13.10.0, v12.17.0 + * @experimental + */ + exit(callback: (...args: TArgs) => R, ...args: TArgs): R; + /** + * Transitions into the context for the remainder of the current + * synchronous execution and then persists the store through any following + * asynchronous calls. + * + * Example: + * + * ```js + * const store = { id: 1 }; + * // Replaces previous store with the given store object + * asyncLocalStorage.enterWith(store); + * asyncLocalStorage.getStore(); // Returns the store object + * someAsyncOperation(() => { + * asyncLocalStorage.getStore(); // Returns the same object + * }); + * ``` + * + * This transition will continue for the _entire_ synchronous execution. + * This means that if, for example, the context is entered within an event + * handler subsequent event handlers will also run within that context unless + * specifically bound to another context with an `AsyncResource`. That is why`run()` should be preferred over `enterWith()` unless there are strong reasons + * to use the latter method. + * + * ```js + * const store = { id: 1 }; + * + * emitter.on('my-event', () => { + * asyncLocalStorage.enterWith(store); + * }); + * emitter.on('my-event', () => { + * asyncLocalStorage.getStore(); // Returns the same object + * }); + * + * asyncLocalStorage.getStore(); // Returns undefined + * emitter.emit('my-event'); + * asyncLocalStorage.getStore(); // Returns the same object + * ``` + * @since v13.11.0, v12.17.0 + * @experimental + */ + enterWith(store: T): void; + } +} +declare module "node:async_hooks" { + export * from "async_hooks"; +} diff --git a/backend/node_modules/@types/node/buffer.d.ts b/backend/node_modules/@types/node/buffer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..dd03c71f66316ebd10f7858881eb973095e6c27f --- /dev/null +++ b/backend/node_modules/@types/node/buffer.d.ts @@ -0,0 +1,2353 @@ +/** + * `Buffer` objects are used to represent a fixed-length sequence of bytes. Many + * Node.js APIs support `Buffer`s. + * + * The `Buffer` class is a subclass of JavaScript's [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) class and + * extends it with methods that cover additional use cases. Node.js APIs accept + * plain [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) s wherever `Buffer`s are supported as well. + * + * While the `Buffer` class is available within the global scope, it is still + * recommended to explicitly reference it via an import or require statement. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Creates a zero-filled Buffer of length 10. + * const buf1 = Buffer.alloc(10); + * + * // Creates a Buffer of length 10, + * // filled with bytes which all have the value `1`. + * const buf2 = Buffer.alloc(10, 1); + * + * // Creates an uninitialized buffer of length 10. + * // This is faster than calling Buffer.alloc() but the returned + * // Buffer instance might contain old data that needs to be + * // overwritten using fill(), write(), or other functions that fill the Buffer's + * // contents. + * const buf3 = Buffer.allocUnsafe(10); + * + * // Creates a Buffer containing the bytes [1, 2, 3]. + * const buf4 = Buffer.from([1, 2, 3]); + * + * // Creates a Buffer containing the bytes [1, 1, 1, 1] – the entries + * // are all truncated using `(value & 255)` to fit into the range 0–255. + * const buf5 = Buffer.from([257, 257.5, -255, '1']); + * + * // Creates a Buffer containing the UTF-8-encoded bytes for the string 'tést': + * // [0x74, 0xc3, 0xa9, 0x73, 0x74] (in hexadecimal notation) + * // [116, 195, 169, 115, 116] (in decimal notation) + * const buf6 = Buffer.from('tést'); + * + * // Creates a Buffer containing the Latin-1 bytes [0x74, 0xe9, 0x73, 0x74]. + * const buf7 = Buffer.from('tést', 'latin1'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.19.0/lib/buffer.js) + */ +declare module "buffer" { + import { BinaryLike } from "node:crypto"; + import { ReadableStream as WebReadableStream } from "node:stream/web"; + /** + * This function returns `true` if `input` contains only valid UTF-8-encoded data, + * including the case in which `input` is empty. + * + * Throws if the `input` is a detached array buffer. + * @since v18.14.0 + * @param input The input to validate. + */ + export function isUtf8(input: Buffer | ArrayBuffer | NodeJS.TypedArray): boolean; + /** + * This function returns `true` if `input` contains only valid ASCII-encoded data, + * including the case in which `input` is empty. + * + * Throws if the `input` is a detached array buffer. + * @since v18.15.0 + * @param input The input to validate. + */ + export function isAscii(input: Buffer | ArrayBuffer | NodeJS.TypedArray): boolean; + export const INSPECT_MAX_BYTES: number; + export const kMaxLength: number; + export const kStringMaxLength: number; + export const constants: { + MAX_LENGTH: number; + MAX_STRING_LENGTH: number; + }; + export type TranscodeEncoding = "ascii" | "utf8" | "utf16le" | "ucs2" | "latin1" | "binary"; + /** + * Re-encodes the given `Buffer` or `Uint8Array` instance from one character + * encoding to another. Returns a new `Buffer` instance. + * + * Throws if the `fromEnc` or `toEnc` specify invalid character encodings or if + * conversion from `fromEnc` to `toEnc` is not permitted. + * + * Encodings supported by `buffer.transcode()` are: `'ascii'`, `'utf8'`,`'utf16le'`, `'ucs2'`, `'latin1'`, and `'binary'`. + * + * The transcoding process will use substitution characters if a given byte + * sequence cannot be adequately represented in the target encoding. For instance: + * + * ```js + * import { Buffer, transcode } from 'node:buffer'; + * + * const newBuf = transcode(Buffer.from('€'), 'utf8', 'ascii'); + * console.log(newBuf.toString('ascii')); + * // Prints: '?' + * ``` + * + * Because the Euro (`€`) sign is not representable in US-ASCII, it is replaced + * with `?` in the transcoded `Buffer`. + * @since v7.1.0 + * @param source A `Buffer` or `Uint8Array` instance. + * @param fromEnc The current encoding. + * @param toEnc To target encoding. + */ + export function transcode(source: Uint8Array, fromEnc: TranscodeEncoding, toEnc: TranscodeEncoding): Buffer; + export const SlowBuffer: { + /** @deprecated since v6.0.0, use `Buffer.allocUnsafeSlow()` */ + new(size: number): Buffer; + prototype: Buffer; + }; + /** + * Resolves a `'blob:nodedata:...'` an associated `Blob` object registered using + * a prior call to `URL.createObjectURL()`. + * @since v16.7.0 + * @experimental + * @param id A `'blob:nodedata:...` URL string returned by a prior call to `URL.createObjectURL()`. + */ + export function resolveObjectURL(id: string): Blob | undefined; + export { Buffer }; + /** + * @experimental + */ + export interface BlobOptions { + /** + * One of either `'transparent'` or `'native'`. When set to `'native'`, line endings in string source parts + * will be converted to the platform native line-ending as specified by `require('node:os').EOL`. + */ + endings?: "transparent" | "native"; + /** + * The Blob content-type. The intent is for `type` to convey + * the MIME media type of the data, however no validation of the type format + * is performed. + */ + type?: string | undefined; + } + /** + * A [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) encapsulates immutable, raw data that can be safely shared across + * multiple worker threads. + * @since v15.7.0, v14.18.0 + */ + export class Blob { + /** + * The total size of the `Blob` in bytes. + * @since v15.7.0, v14.18.0 + */ + readonly size: number; + /** + * The content-type of the `Blob`. + * @since v15.7.0, v14.18.0 + */ + readonly type: string; + /** + * Creates a new `Blob` object containing a concatenation of the given sources. + * + * {ArrayBuffer}, {TypedArray}, {DataView}, and {Buffer} sources are copied into + * the 'Blob' and can therefore be safely modified after the 'Blob' is created. + * + * String sources are also copied into the `Blob`. + */ + constructor(sources: Array, options?: BlobOptions); + /** + * Returns a promise that fulfills with an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) containing a copy of + * the `Blob` data. + * @since v15.7.0, v14.18.0 + */ + arrayBuffer(): Promise; + /** + * Creates and returns a new `Blob` containing a subset of this `Blob` objects + * data. The original `Blob` is not altered. + * @since v15.7.0, v14.18.0 + * @param start The starting index. + * @param end The ending index. + * @param type The content-type for the new `Blob` + */ + slice(start?: number, end?: number, type?: string): Blob; + /** + * Returns a promise that fulfills with the contents of the `Blob` decoded as a + * UTF-8 string. + * @since v15.7.0, v14.18.0 + */ + text(): Promise; + /** + * Returns a new `ReadableStream` that allows the content of the `Blob` to be read. + * @since v16.7.0 + */ + stream(): WebReadableStream; + } + export interface FileOptions { + /** + * One of either `'transparent'` or `'native'`. When set to `'native'`, line endings in string source parts will be + * converted to the platform native line-ending as specified by `require('node:os').EOL`. + */ + endings?: "native" | "transparent"; + /** The File content-type. */ + type?: string; + /** The last modified date of the file. `Default`: Date.now(). */ + lastModified?: number; + } + /** + * A [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File) provides information about files. + * @since v18.13.0 + */ + export class File extends Blob { + constructor(sources: Array, fileName: string, options?: FileOptions); + /** + * The name of the `File`. + * @since v18.13.0 + */ + readonly name: string; + /** + * The last modified date of the `File`. + * @since v18.13.0 + */ + readonly lastModified: number; + } + export import atob = globalThis.atob; + export import btoa = globalThis.btoa; + import { Blob as NodeBlob } from "buffer"; + // This conditional type will be the existing global Blob in a browser, or + // the copy below in a Node environment. + type __Blob = typeof globalThis extends { onmessage: any; Blob: any } ? {} : NodeBlob; + global { + namespace NodeJS { + export { BufferEncoding }; + } + // Buffer class + type BufferEncoding = + | "ascii" + | "utf8" + | "utf-8" + | "utf16le" + | "ucs2" + | "ucs-2" + | "base64" + | "base64url" + | "latin1" + | "binary" + | "hex"; + type WithImplicitCoercion = + | T + | { + valueOf(): T; + }; + /** + * Raw data is stored in instances of the Buffer class. + * A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized. + * Valid string encodings: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'base64url'|'binary'(deprecated)|'hex' + */ + interface BufferConstructor { + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + * @deprecated since v10.0.0 - Use `Buffer.from(string[, encoding])` instead. + */ + new(str: string, encoding?: BufferEncoding): Buffer; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @deprecated since v10.0.0 - Use `Buffer.alloc()` instead (also see `Buffer.allocUnsafe()`). + */ + new(size: number): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + new(array: Uint8Array): Buffer; + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}/{SharedArrayBuffer}. + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + * @deprecated since v10.0.0 - Use `Buffer.from(arrayBuffer[, byteOffset[, length]])` instead. + */ + new(arrayBuffer: ArrayBuffer | SharedArrayBuffer): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + new(array: readonly any[]): Buffer; + /** + * Copies the passed {buffer} data onto a new {Buffer} instance. + * + * @param buffer The buffer to copy. + * @deprecated since v10.0.0 - Use `Buffer.from(buffer)` instead. + */ + new(buffer: Buffer): Buffer; + /** + * Allocates a new `Buffer` using an `array` of bytes in the range `0` – `255`. + * Array entries outside that range will be truncated to fit into it. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'. + * const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); + * ``` + * + * If `array` is an `Array`\-like object (that is, one with a `length` property of + * type `number`), it is treated as if it is an array, unless it is a `Buffer` or + * a `Uint8Array`. This means all other `TypedArray` variants get treated as an`Array`. To create a `Buffer` from the bytes backing a `TypedArray`, use `Buffer.copyBytesFrom()`. + * + * A `TypeError` will be thrown if `array` is not an `Array` or another type + * appropriate for `Buffer.from()` variants. + * + * `Buffer.from(array)` and `Buffer.from(string)` may also use the internal`Buffer` pool like `Buffer.allocUnsafe()` does. + * @since v5.10.0 + */ + from( + arrayBuffer: WithImplicitCoercion, + byteOffset?: number, + length?: number, + ): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param data data to create a new Buffer + */ + from(data: Uint8Array | readonly number[]): Buffer; + from(data: WithImplicitCoercion): Buffer; + /** + * Creates a new Buffer containing the given JavaScript string {str}. + * If provided, the {encoding} parameter identifies the character encoding. + * If not provided, {encoding} defaults to 'utf8'. + */ + from( + str: + | WithImplicitCoercion + | { + [Symbol.toPrimitive](hint: "string"): string; + }, + encoding?: BufferEncoding, + ): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param values to create a new Buffer + */ + of(...items: number[]): Buffer; + /** + * Returns `true` if `obj` is a `Buffer`, `false` otherwise. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * Buffer.isBuffer(Buffer.alloc(10)); // true + * Buffer.isBuffer(Buffer.from('foo')); // true + * Buffer.isBuffer('a string'); // false + * Buffer.isBuffer([]); // false + * Buffer.isBuffer(new Uint8Array(1024)); // false + * ``` + * @since v0.1.101 + */ + isBuffer(obj: any): obj is Buffer; + /** + * Returns `true` if `encoding` is the name of a supported character encoding, + * or `false` otherwise. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * console.log(Buffer.isEncoding('utf8')); + * // Prints: true + * + * console.log(Buffer.isEncoding('hex')); + * // Prints: true + * + * console.log(Buffer.isEncoding('utf/8')); + * // Prints: false + * + * console.log(Buffer.isEncoding('')); + * // Prints: false + * ``` + * @since v0.9.1 + * @param encoding A character encoding name to check. + */ + isEncoding(encoding: string): encoding is BufferEncoding; + /** + * Returns the byte length of a string when encoded using `encoding`. + * This is not the same as [`String.prototype.length`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length), which does not account + * for the encoding that is used to convert the string into bytes. + * + * For `'base64'`, `'base64url'`, and `'hex'`, this function assumes valid input. + * For strings that contain non-base64/hex-encoded data (e.g. whitespace), the + * return value might be greater than the length of a `Buffer` created from the + * string. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const str = '\u00bd + \u00bc = \u00be'; + * + * console.log(`${str}: ${str.length} characters, ` + + * `${Buffer.byteLength(str, 'utf8')} bytes`); + * // Prints: ½ + ¼ = ¾: 9 characters, 12 bytes + * ``` + * + * When `string` is a + * `Buffer`/[`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)/[`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/- + * Reference/Global_Objects/TypedArray)/[`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)/[`SharedArrayBuffer`](https://develop- + * er.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer), the byte length as reported by `.byteLength`is returned. + * @since v0.1.90 + * @param string A value to calculate the length of. + * @param [encoding='utf8'] If `string` is a string, this is its encoding. + * @return The number of bytes contained within `string`. + */ + byteLength( + string: string | Buffer | NodeJS.ArrayBufferView | ArrayBuffer | SharedArrayBuffer, + encoding?: BufferEncoding, + ): number; + /** + * Returns a new `Buffer` which is the result of concatenating all the `Buffer`instances in the `list` together. + * + * If the list has no items, or if the `totalLength` is 0, then a new zero-length`Buffer` is returned. + * + * If `totalLength` is not provided, it is calculated from the `Buffer` instances + * in `list` by adding their lengths. + * + * If `totalLength` is provided, it is coerced to an unsigned integer. If the + * combined length of the `Buffer`s in `list` exceeds `totalLength`, the result is + * truncated to `totalLength`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Create a single `Buffer` from a list of three `Buffer` instances. + * + * const buf1 = Buffer.alloc(10); + * const buf2 = Buffer.alloc(14); + * const buf3 = Buffer.alloc(18); + * const totalLength = buf1.length + buf2.length + buf3.length; + * + * console.log(totalLength); + * // Prints: 42 + * + * const bufA = Buffer.concat([buf1, buf2, buf3], totalLength); + * + * console.log(bufA); + * // Prints: + * console.log(bufA.length); + * // Prints: 42 + * ``` + * + * `Buffer.concat()` may also use the internal `Buffer` pool like `Buffer.allocUnsafe()` does. + * @since v0.7.11 + * @param list List of `Buffer` or {@link Uint8Array} instances to concatenate. + * @param totalLength Total length of the `Buffer` instances in `list` when concatenated. + */ + concat(list: readonly Uint8Array[], totalLength?: number): Buffer; + /** + * Copies the underlying memory of `view` into a new `Buffer`. + * + * ```js + * const u16 = new Uint16Array([0, 0xffff]); + * const buf = Buffer.copyBytesFrom(u16, 1, 1); + * u16[1] = 0; + * console.log(buf.length); // 2 + * console.log(buf[0]); // 255 + * console.log(buf[1]); // 255 + * ``` + * @since v18.16.0 + * @param view The {TypedArray} to copy. + * @param [offset=0] The starting offset within `view`. + * @param [length=view.length - offset] The number of elements from `view` to copy. + */ + copyBytesFrom(view: NodeJS.TypedArray, offset?: number, length?: number): Buffer; + /** + * Compares `buf1` to `buf2`, typically for the purpose of sorting arrays of`Buffer` instances. This is equivalent to calling `buf1.compare(buf2)`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from('1234'); + * const buf2 = Buffer.from('0123'); + * const arr = [buf1, buf2]; + * + * console.log(arr.sort(Buffer.compare)); + * // Prints: [ , ] + * // (This result is equal to: [buf2, buf1].) + * ``` + * @since v0.11.13 + * @return Either `-1`, `0`, or `1`, depending on the result of the comparison. See `compare` for details. + */ + compare(buf1: Uint8Array, buf2: Uint8Array): -1 | 0 | 1; + /** + * Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the`Buffer` will be zero-filled. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(5); + * + * console.log(buf); + * // Prints: + * ``` + * + * If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. + * + * If `fill` is specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill)`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(5, 'a'); + * + * console.log(buf); + * // Prints: + * ``` + * + * If both `fill` and `encoding` are specified, the allocated `Buffer` will be + * initialized by calling `buf.fill(fill, encoding)`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); + * + * console.log(buf); + * // Prints: + * ``` + * + * Calling `Buffer.alloc()` can be measurably slower than the alternative `Buffer.allocUnsafe()` but ensures that the newly created `Buffer` instance + * contents will never contain sensitive data from previous allocations, including + * data that might not have been allocated for `Buffer`s. + * + * A `TypeError` will be thrown if `size` is not a number. + * @since v5.10.0 + * @param size The desired length of the new `Buffer`. + * @param [fill=0] A value to pre-fill the new `Buffer` with. + * @param [encoding='utf8'] If `fill` is a string, this is its encoding. + */ + alloc(size: number, fill?: string | Uint8Array | number, encoding?: BufferEncoding): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. + * + * The underlying memory for `Buffer` instances created in this way is _not_ + * _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `Buffer.alloc()` instead to initialize`Buffer` instances with zeroes. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(10); + * + * console.log(buf); + * // Prints (contents may vary): + * + * buf.fill(0); + * + * console.log(buf); + * // Prints: + * ``` + * + * A `TypeError` will be thrown if `size` is not a number. + * + * The `Buffer` module pre-allocates an internal `Buffer` instance of + * size `Buffer.poolSize` that is used as a pool for the fast allocation of new `Buffer` instances created using `Buffer.allocUnsafe()`, `Buffer.from(array)`, + * and `Buffer.concat()` only when `size` is less than `Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). + * + * Use of this pre-allocated internal memory pool is a key difference between + * calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. + * Specifically, `Buffer.alloc(size, fill)` will _never_ use the internal `Buffer`pool, while `Buffer.allocUnsafe(size).fill(fill)`_will_ use the internal`Buffer` pool if `size` is less + * than or equal to half `Buffer.poolSize`. The + * difference is subtle but can be important when an application requires the + * additional performance that `Buffer.allocUnsafe()` provides. + * @since v5.10.0 + * @param size The desired length of the new `Buffer`. + */ + allocUnsafe(size: number): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. A zero-length `Buffer` is created if + * `size` is 0. + * + * The underlying memory for `Buffer` instances created in this way is _not_ + * _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `buf.fill(0)` to initialize + * such `Buffer` instances with zeroes. + * + * When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, + * allocations under 4 KiB are sliced from a single pre-allocated `Buffer`. This + * allows applications to avoid the garbage collection overhead of creating many + * individually allocated `Buffer` instances. This approach improves both + * performance and memory usage by eliminating the need to track and clean up as + * many individual `ArrayBuffer` objects. + * + * However, in the case where a developer may need to retain a small chunk of + * memory from a pool for an indeterminate amount of time, it may be appropriate + * to create an un-pooled `Buffer` instance using `Buffer.allocUnsafeSlow()` and + * then copying out the relevant bits. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Need to keep around a few small chunks of memory. + * const store = []; + * + * socket.on('readable', () => { + * let data; + * while (null !== (data = readable.read())) { + * // Allocate for retained data. + * const sb = Buffer.allocUnsafeSlow(10); + * + * // Copy the data into the new allocation. + * data.copy(sb, 0, 0, 10); + * + * store.push(sb); + * } + * }); + * ``` + * + * A `TypeError` will be thrown if `size` is not a number. + * @since v5.12.0 + * @param size The desired length of the new `Buffer`. + */ + allocUnsafeSlow(size: number): Buffer; + /** + * This is the size (in bytes) of pre-allocated internal `Buffer` instances used + * for pooling. This value may be modified. + * @since v0.11.3 + */ + poolSize: number; + } + interface Buffer extends Uint8Array { + /** + * Writes `string` to `buf` at `offset` according to the character encoding in`encoding`. The `length` parameter is the number of bytes to write. If `buf` did + * not contain enough space to fit the entire string, only part of `string` will be + * written. However, partially encoded characters will not be written. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(256); + * + * const len = buf.write('\u00bd + \u00bc = \u00be', 0); + * + * console.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`); + * // Prints: 12 bytes: ½ + ¼ = ¾ + * + * const buffer = Buffer.alloc(10); + * + * const length = buffer.write('abcd', 8); + * + * console.log(`${length} bytes: ${buffer.toString('utf8', 8, 10)}`); + * // Prints: 2 bytes : ab + * ``` + * @since v0.1.90 + * @param string String to write to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write `string`. + * @param [length=buf.length - offset] Maximum number of bytes to write (written bytes will not exceed `buf.length - offset`). + * @param [encoding='utf8'] The character encoding of `string`. + * @return Number of bytes written. + */ + write(string: string, encoding?: BufferEncoding): number; + write(string: string, offset: number, encoding?: BufferEncoding): number; + write(string: string, offset: number, length: number, encoding?: BufferEncoding): number; + /** + * Decodes `buf` to a string according to the specified character encoding in`encoding`. `start` and `end` may be passed to decode only a subset of `buf`. + * + * If `encoding` is `'utf8'` and a byte sequence in the input is not valid UTF-8, + * then each invalid byte is replaced with the replacement character `U+FFFD`. + * + * The maximum length of a string instance (in UTF-16 code units) is available + * as {@link constants.MAX_STRING_LENGTH}. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * console.log(buf1.toString('utf8')); + * // Prints: abcdefghijklmnopqrstuvwxyz + * console.log(buf1.toString('utf8', 0, 5)); + * // Prints: abcde + * + * const buf2 = Buffer.from('tést'); + * + * console.log(buf2.toString('hex')); + * // Prints: 74c3a97374 + * console.log(buf2.toString('utf8', 0, 3)); + * // Prints: té + * console.log(buf2.toString(undefined, 0, 3)); + * // Prints: té + * ``` + * @since v0.1.90 + * @param [encoding='utf8'] The character encoding to use. + * @param [start=0] The byte offset to start decoding at. + * @param [end=buf.length] The byte offset to stop decoding at (not inclusive). + */ + toString(encoding?: BufferEncoding, start?: number, end?: number): string; + /** + * Returns a JSON representation of `buf`. [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) implicitly calls + * this function when stringifying a `Buffer` instance. + * + * `Buffer.from()` accepts objects in the format returned from this method. + * In particular, `Buffer.from(buf.toJSON())` works like `Buffer.from(buf)`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]); + * const json = JSON.stringify(buf); + * + * console.log(json); + * // Prints: {"type":"Buffer","data":[1,2,3,4,5]} + * + * const copy = JSON.parse(json, (key, value) => { + * return value && value.type === 'Buffer' ? + * Buffer.from(value) : + * value; + * }); + * + * console.log(copy); + * // Prints: + * ``` + * @since v0.9.2 + */ + toJSON(): { + type: "Buffer"; + data: number[]; + }; + /** + * Returns `true` if both `buf` and `otherBuffer` have exactly the same bytes,`false` otherwise. Equivalent to `buf.compare(otherBuffer) === 0`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from('ABC'); + * const buf2 = Buffer.from('414243', 'hex'); + * const buf3 = Buffer.from('ABCD'); + * + * console.log(buf1.equals(buf2)); + * // Prints: true + * console.log(buf1.equals(buf3)); + * // Prints: false + * ``` + * @since v0.11.13 + * @param otherBuffer A `Buffer` or {@link Uint8Array} with which to compare `buf`. + */ + equals(otherBuffer: Uint8Array): boolean; + /** + * Compares `buf` with `target` and returns a number indicating whether `buf`comes before, after, or is the same as `target` in sort order. + * Comparison is based on the actual sequence of bytes in each `Buffer`. + * + * * `0` is returned if `target` is the same as `buf` + * * `1` is returned if `target` should come _before_`buf` when sorted. + * * `-1` is returned if `target` should come _after_`buf` when sorted. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from('ABC'); + * const buf2 = Buffer.from('BCD'); + * const buf3 = Buffer.from('ABCD'); + * + * console.log(buf1.compare(buf1)); + * // Prints: 0 + * console.log(buf1.compare(buf2)); + * // Prints: -1 + * console.log(buf1.compare(buf3)); + * // Prints: -1 + * console.log(buf2.compare(buf1)); + * // Prints: 1 + * console.log(buf2.compare(buf3)); + * // Prints: 1 + * console.log([buf1, buf2, buf3].sort(Buffer.compare)); + * // Prints: [ , , ] + * // (This result is equal to: [buf1, buf3, buf2].) + * ``` + * + * The optional `targetStart`, `targetEnd`, `sourceStart`, and `sourceEnd`arguments can be used to limit the comparison to specific ranges within `target`and `buf` respectively. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]); + * const buf2 = Buffer.from([5, 6, 7, 8, 9, 1, 2, 3, 4]); + * + * console.log(buf1.compare(buf2, 5, 9, 0, 4)); + * // Prints: 0 + * console.log(buf1.compare(buf2, 0, 6, 4)); + * // Prints: -1 + * console.log(buf1.compare(buf2, 5, 6, 5)); + * // Prints: 1 + * ``` + * + * `ERR_OUT_OF_RANGE` is thrown if `targetStart < 0`, `sourceStart < 0`,`targetEnd > target.byteLength`, or `sourceEnd > source.byteLength`. + * @since v0.11.13 + * @param target A `Buffer` or {@link Uint8Array} with which to compare `buf`. + * @param [targetStart=0] The offset within `target` at which to begin comparison. + * @param [targetEnd=target.length] The offset within `target` at which to end comparison (not inclusive). + * @param [sourceStart=0] The offset within `buf` at which to begin comparison. + * @param [sourceEnd=buf.length] The offset within `buf` at which to end comparison (not inclusive). + */ + compare( + target: Uint8Array, + targetStart?: number, + targetEnd?: number, + sourceStart?: number, + sourceEnd?: number, + ): -1 | 0 | 1; + /** + * Copies data from a region of `buf` to a region in `target`, even if the `target`memory region overlaps with `buf`. + * + * [`TypedArray.prototype.set()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/set) performs the same operation, and is available + * for all TypedArrays, including Node.js `Buffer`s, although it takes + * different function arguments. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Create two `Buffer` instances. + * const buf1 = Buffer.allocUnsafe(26); + * const buf2 = Buffer.allocUnsafe(26).fill('!'); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * // Copy `buf1` bytes 16 through 19 into `buf2` starting at byte 8 of `buf2`. + * buf1.copy(buf2, 8, 16, 20); + * // This is equivalent to: + * // buf2.set(buf1.subarray(16, 20), 8); + * + * console.log(buf2.toString('ascii', 0, 25)); + * // Prints: !!!!!!!!qrst!!!!!!!!!!!!! + * ``` + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Create a `Buffer` and copy data from one region to an overlapping region + * // within the same `Buffer`. + * + * const buf = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf[i] = i + 97; + * } + * + * buf.copy(buf, 0, 4, 10); + * + * console.log(buf.toString()); + * // Prints: efghijghijklmnopqrstuvwxyz + * ``` + * @since v0.1.90 + * @param target A `Buffer` or {@link Uint8Array} to copy into. + * @param [targetStart=0] The offset within `target` at which to begin writing. + * @param [sourceStart=0] The offset within `buf` from which to begin copying. + * @param [sourceEnd=buf.length] The offset within `buf` at which to stop copying (not inclusive). + * @return The number of bytes copied. + */ + copy(target: Uint8Array, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + /** + * Returns a new `Buffer` that references the same memory as the original, but + * offset and cropped by the `start` and `end` indices. + * + * This method is not compatible with the `Uint8Array.prototype.slice()`, + * which is a superclass of `Buffer`. To copy the slice, use`Uint8Array.prototype.slice()`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('buffer'); + * + * const copiedBuf = Uint8Array.prototype.slice.call(buf); + * copiedBuf[0]++; + * console.log(copiedBuf.toString()); + * // Prints: cuffer + * + * console.log(buf.toString()); + * // Prints: buffer + * + * // With buf.slice(), the original buffer is modified. + * const notReallyCopiedBuf = buf.slice(); + * notReallyCopiedBuf[0]++; + * console.log(notReallyCopiedBuf.toString()); + * // Prints: cuffer + * console.log(buf.toString()); + * // Also prints: cuffer (!) + * ``` + * @since v0.3.0 + * @deprecated Use `subarray` instead. + * @param [start=0] Where the new `Buffer` will start. + * @param [end=buf.length] Where the new `Buffer` will end (not inclusive). + */ + slice(start?: number, end?: number): Buffer; + /** + * Returns a new `Buffer` that references the same memory as the original, but + * offset and cropped by the `start` and `end` indices. + * + * Specifying `end` greater than `buf.length` will return the same result as + * that of `end` equal to `buf.length`. + * + * This method is inherited from [`TypedArray.prototype.subarray()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray). + * + * Modifying the new `Buffer` slice will modify the memory in the original `Buffer`because the allocated memory of the two objects overlap. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte + * // from the original `Buffer`. + * + * const buf1 = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * const buf2 = buf1.subarray(0, 3); + * + * console.log(buf2.toString('ascii', 0, buf2.length)); + * // Prints: abc + * + * buf1[0] = 33; + * + * console.log(buf2.toString('ascii', 0, buf2.length)); + * // Prints: !bc + * ``` + * + * Specifying negative indexes causes the slice to be generated relative to the + * end of `buf` rather than the beginning. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('buffer'); + * + * console.log(buf.subarray(-6, -1).toString()); + * // Prints: buffe + * // (Equivalent to buf.subarray(0, 5).) + * + * console.log(buf.subarray(-6, -2).toString()); + * // Prints: buff + * // (Equivalent to buf.subarray(0, 4).) + * + * console.log(buf.subarray(-5, -2).toString()); + * // Prints: uff + * // (Equivalent to buf.subarray(1, 4).) + * ``` + * @since v3.0.0 + * @param [start=0] Where the new `Buffer` will start. + * @param [end=buf.length] Where the new `Buffer` will end (not inclusive). + */ + subarray(start?: number, end?: number): Buffer; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. + * + * `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigInt64BE(0x0102030405060708n, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigInt64BE(value: bigint, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. + * + * `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigInt64LE(0x0102030405060708n, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigInt64LE(value: bigint, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. + * + * This function is also available under the `writeBigUint64BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigUInt64BE(0xdecafafecacefaden, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigUInt64BE(value: bigint, offset?: number): number; + /** + * @alias Buffer.writeBigUInt64BE + * @since v14.10.0, v12.19.0 + */ + writeBigUint64BE(value: bigint, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigUInt64LE(0xdecafafecacefaden, 0); + * + * console.log(buf); + * // Prints: + * ``` + * + * This function is also available under the `writeBigUint64LE` alias. + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigUInt64LE(value: bigint, offset?: number): number; + /** + * @alias Buffer.writeBigUInt64LE + * @since v14.10.0, v12.19.0 + */ + writeBigUint64LE(value: bigint, offset?: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined + * when `value` is anything other than an unsigned integer. + * + * This function is also available under the `writeUintLE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeUIntLE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeUIntLE(value: number, offset: number, byteLength: number): number; + /** + * @alias Buffer.writeUIntLE + * @since v14.9.0, v12.19.0 + */ + writeUintLE(value: number, offset: number, byteLength: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined + * when `value` is anything other than an unsigned integer. + * + * This function is also available under the `writeUintBE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeUIntBE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeUIntBE(value: number, offset: number, byteLength: number): number; + /** + * @alias Buffer.writeUIntBE + * @since v14.9.0, v12.19.0 + */ + writeUintBE(value: number, offset: number, byteLength: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined + * when `value` is anything other than a signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeIntLE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeIntLE(value: number, offset: number, byteLength: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined when`value` is anything other than a + * signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeIntBE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeIntBE(value: number, offset: number, byteLength: number): number; + /** + * Reads an unsigned, big-endian 64-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readBigUint64BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]); + * + * console.log(buf.readBigUInt64BE(0)); + * // Prints: 4294967295n + * ``` + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigUInt64BE(offset?: number): bigint; + /** + * @alias Buffer.readBigUInt64BE + * @since v14.10.0, v12.19.0 + */ + readBigUint64BE(offset?: number): bigint; + /** + * Reads an unsigned, little-endian 64-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readBigUint64LE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]); + * + * console.log(buf.readBigUInt64LE(0)); + * // Prints: 18446744069414584320n + * ``` + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigUInt64LE(offset?: number): bigint; + /** + * @alias Buffer.readBigUInt64LE + * @since v14.10.0, v12.19.0 + */ + readBigUint64LE(offset?: number): bigint; + /** + * Reads a signed, big-endian 64-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed + * values. + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigInt64BE(offset?: number): bigint; + /** + * Reads a signed, little-endian 64-bit integer from `buf` at the specified`offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed + * values. + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigInt64LE(offset?: number): bigint; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset`and interprets the result as an unsigned, little-endian integer supporting + * up to 48 bits of accuracy. + * + * This function is also available under the `readUintLE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readUIntLE(0, 6).toString(16)); + * // Prints: ab9078563412 + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readUIntLE(offset: number, byteLength: number): number; + /** + * @alias Buffer.readUIntLE + * @since v14.9.0, v12.19.0 + */ + readUintLE(offset: number, byteLength: number): number; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset`and interprets the result as an unsigned big-endian integer supporting + * up to 48 bits of accuracy. + * + * This function is also available under the `readUintBE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readUIntBE(0, 6).toString(16)); + * // Prints: 1234567890ab + * console.log(buf.readUIntBE(1, 6).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readUIntBE(offset: number, byteLength: number): number; + /** + * @alias Buffer.readUIntBE + * @since v14.9.0, v12.19.0 + */ + readUintBE(offset: number, byteLength: number): number; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset`and interprets the result as a little-endian, two's complement signed value + * supporting up to 48 bits of accuracy. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readIntLE(0, 6).toString(16)); + * // Prints: -546f87a9cbee + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readIntLE(offset: number, byteLength: number): number; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset`and interprets the result as a big-endian, two's complement signed value + * supporting up to 48 bits of accuracy. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readIntBE(0, 6).toString(16)); + * // Prints: 1234567890ab + * console.log(buf.readIntBE(1, 6).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * console.log(buf.readIntBE(1, 0).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readIntBE(offset: number, byteLength: number): number; + /** + * Reads an unsigned 8-bit integer from `buf` at the specified `offset`. + * + * This function is also available under the `readUint8` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([1, -2]); + * + * console.log(buf.readUInt8(0)); + * // Prints: 1 + * console.log(buf.readUInt8(1)); + * // Prints: 254 + * console.log(buf.readUInt8(2)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 1`. + */ + readUInt8(offset?: number): number; + /** + * @alias Buffer.readUInt8 + * @since v14.9.0, v12.19.0 + */ + readUint8(offset?: number): number; + /** + * Reads an unsigned, little-endian 16-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint16LE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56]); + * + * console.log(buf.readUInt16LE(0).toString(16)); + * // Prints: 3412 + * console.log(buf.readUInt16LE(1).toString(16)); + * // Prints: 5634 + * console.log(buf.readUInt16LE(2).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readUInt16LE(offset?: number): number; + /** + * @alias Buffer.readUInt16LE + * @since v14.9.0, v12.19.0 + */ + readUint16LE(offset?: number): number; + /** + * Reads an unsigned, big-endian 16-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint16BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56]); + * + * console.log(buf.readUInt16BE(0).toString(16)); + * // Prints: 1234 + * console.log(buf.readUInt16BE(1).toString(16)); + * // Prints: 3456 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readUInt16BE(offset?: number): number; + /** + * @alias Buffer.readUInt16BE + * @since v14.9.0, v12.19.0 + */ + readUint16BE(offset?: number): number; + /** + * Reads an unsigned, little-endian 32-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint32LE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]); + * + * console.log(buf.readUInt32LE(0).toString(16)); + * // Prints: 78563412 + * console.log(buf.readUInt32LE(1).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readUInt32LE(offset?: number): number; + /** + * @alias Buffer.readUInt32LE + * @since v14.9.0, v12.19.0 + */ + readUint32LE(offset?: number): number; + /** + * Reads an unsigned, big-endian 32-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint32BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]); + * + * console.log(buf.readUInt32BE(0).toString(16)); + * // Prints: 12345678 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readUInt32BE(offset?: number): number; + /** + * @alias Buffer.readUInt32BE + * @since v14.9.0, v12.19.0 + */ + readUint32BE(offset?: number): number; + /** + * Reads a signed 8-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([-1, 5]); + * + * console.log(buf.readInt8(0)); + * // Prints: -1 + * console.log(buf.readInt8(1)); + * // Prints: 5 + * console.log(buf.readInt8(2)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 1`. + */ + readInt8(offset?: number): number; + /** + * Reads a signed, little-endian 16-bit integer from `buf` at the specified`offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0, 5]); + * + * console.log(buf.readInt16LE(0)); + * // Prints: 1280 + * console.log(buf.readInt16LE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readInt16LE(offset?: number): number; + /** + * Reads a signed, big-endian 16-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0, 5]); + * + * console.log(buf.readInt16BE(0)); + * // Prints: 5 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readInt16BE(offset?: number): number; + /** + * Reads a signed, little-endian 32-bit integer from `buf` at the specified`offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0, 0, 0, 5]); + * + * console.log(buf.readInt32LE(0)); + * // Prints: 83886080 + * console.log(buf.readInt32LE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readInt32LE(offset?: number): number; + /** + * Reads a signed, big-endian 32-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0, 0, 0, 5]); + * + * console.log(buf.readInt32BE(0)); + * // Prints: 5 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readInt32BE(offset?: number): number; + /** + * Reads a 32-bit, little-endian float from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4]); + * + * console.log(buf.readFloatLE(0)); + * // Prints: 1.539989614439558e-36 + * console.log(buf.readFloatLE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readFloatLE(offset?: number): number; + /** + * Reads a 32-bit, big-endian float from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4]); + * + * console.log(buf.readFloatBE(0)); + * // Prints: 2.387939260590663e-38 + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readFloatBE(offset?: number): number; + /** + * Reads a 64-bit, little-endian double from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); + * + * console.log(buf.readDoubleLE(0)); + * // Prints: 5.447603722011605e-270 + * console.log(buf.readDoubleLE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 8`. + */ + readDoubleLE(offset?: number): number; + /** + * Reads a 64-bit, big-endian double from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); + * + * console.log(buf.readDoubleBE(0)); + * // Prints: 8.20788039913184e-304 + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 8`. + */ + readDoubleBE(offset?: number): number; + reverse(): this; + /** + * Interprets `buf` as an array of unsigned 16-bit integers and swaps the + * byte order _in-place_. Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 2. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); + * + * console.log(buf1); + * // Prints: + * + * buf1.swap16(); + * + * console.log(buf1); + * // Prints: + * + * const buf2 = Buffer.from([0x1, 0x2, 0x3]); + * + * buf2.swap16(); + * // Throws ERR_INVALID_BUFFER_SIZE. + * ``` + * + * One convenient use of `buf.swap16()` is to perform a fast in-place conversion + * between UTF-16 little-endian and UTF-16 big-endian: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('This is little-endian UTF-16', 'utf16le'); + * buf.swap16(); // Convert to big-endian UTF-16 text. + * ``` + * @since v5.10.0 + * @return A reference to `buf`. + */ + swap16(): Buffer; + /** + * Interprets `buf` as an array of unsigned 32-bit integers and swaps the + * byte order _in-place_. Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 4. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); + * + * console.log(buf1); + * // Prints: + * + * buf1.swap32(); + * + * console.log(buf1); + * // Prints: + * + * const buf2 = Buffer.from([0x1, 0x2, 0x3]); + * + * buf2.swap32(); + * // Throws ERR_INVALID_BUFFER_SIZE. + * ``` + * @since v5.10.0 + * @return A reference to `buf`. + */ + swap32(): Buffer; + /** + * Interprets `buf` as an array of 64-bit numbers and swaps byte order _in-place_. + * Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 8. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); + * + * console.log(buf1); + * // Prints: + * + * buf1.swap64(); + * + * console.log(buf1); + * // Prints: + * + * const buf2 = Buffer.from([0x1, 0x2, 0x3]); + * + * buf2.swap64(); + * // Throws ERR_INVALID_BUFFER_SIZE. + * ``` + * @since v6.3.0 + * @return A reference to `buf`. + */ + swap64(): Buffer; + /** + * Writes `value` to `buf` at the specified `offset`. `value` must be a + * valid unsigned 8-bit integer. Behavior is undefined when `value` is anything + * other than an unsigned 8-bit integer. + * + * This function is also available under the `writeUint8` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt8(0x3, 0); + * buf.writeUInt8(0x4, 1); + * buf.writeUInt8(0x23, 2); + * buf.writeUInt8(0x42, 3); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 1`. + * @return `offset` plus the number of bytes written. + */ + writeUInt8(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt8 + * @since v14.9.0, v12.19.0 + */ + writeUint8(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a valid unsigned 16-bit integer. Behavior is undefined when `value` is + * anything other than an unsigned 16-bit integer. + * + * This function is also available under the `writeUint16LE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt16LE(0xdead, 0); + * buf.writeUInt16LE(0xbeef, 2); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeUInt16LE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt16LE + * @since v14.9.0, v12.19.0 + */ + writeUint16LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a valid unsigned 16-bit integer. Behavior is undefined when `value`is anything other than an + * unsigned 16-bit integer. + * + * This function is also available under the `writeUint16BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt16BE(0xdead, 0); + * buf.writeUInt16BE(0xbeef, 2); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeUInt16BE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt16BE + * @since v14.9.0, v12.19.0 + */ + writeUint16BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a valid unsigned 32-bit integer. Behavior is undefined when `value` is + * anything other than an unsigned 32-bit integer. + * + * This function is also available under the `writeUint32LE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt32LE(0xfeedface, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeUInt32LE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt32LE + * @since v14.9.0, v12.19.0 + */ + writeUint32LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a valid unsigned 32-bit integer. Behavior is undefined when `value`is anything other than an + * unsigned 32-bit integer. + * + * This function is also available under the `writeUint32BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt32BE(0xfeedface, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeUInt32BE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt32BE + * @since v14.9.0, v12.19.0 + */ + writeUint32BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset`. `value` must be a valid + * signed 8-bit integer. Behavior is undefined when `value` is anything other than + * a signed 8-bit integer. + * + * `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(2); + * + * buf.writeInt8(2, 0); + * buf.writeInt8(-2, 1); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 1`. + * @return `offset` plus the number of bytes written. + */ + writeInt8(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a valid signed 16-bit integer. Behavior is undefined when `value` is + * anything other than a signed 16-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(2); + * + * buf.writeInt16LE(0x0304, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeInt16LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a valid signed 16-bit integer. Behavior is undefined when `value` is + * anything other than a signed 16-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(2); + * + * buf.writeInt16BE(0x0102, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeInt16BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a valid signed 32-bit integer. Behavior is undefined when `value` is + * anything other than a signed 32-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeInt32LE(0x05060708, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeInt32LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a valid signed 32-bit integer. Behavior is undefined when `value` is + * anything other than a signed 32-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeInt32BE(0x01020304, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeInt32BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. Behavior is + * undefined when `value` is anything other than a JavaScript number. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeFloatLE(0xcafebabe, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeFloatLE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. Behavior is + * undefined when `value` is anything other than a JavaScript number. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeFloatBE(0xcafebabe, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeFloatBE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a JavaScript number. Behavior is undefined when `value` is anything + * other than a JavaScript number. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeDoubleLE(123.456, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeDoubleLE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a JavaScript number. Behavior is undefined when `value` is anything + * other than a JavaScript number. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeDoubleBE(123.456, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeDoubleBE(value: number, offset?: number): number; + /** + * Fills `buf` with the specified `value`. If the `offset` and `end` are not given, + * the entire `buf` will be filled: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Fill a `Buffer` with the ASCII character 'h'. + * + * const b = Buffer.allocUnsafe(50).fill('h'); + * + * console.log(b.toString()); + * // Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh + * + * // Fill a buffer with empty string + * const c = Buffer.allocUnsafe(5).fill(''); + * + * console.log(c.fill('')); + * // Prints: + * ``` + * + * `value` is coerced to a `uint32` value if it is not a string, `Buffer`, or + * integer. If the resulting integer is greater than `255` (decimal), `buf` will be + * filled with `value & 255`. + * + * If the final write of a `fill()` operation falls on a multi-byte character, + * then only the bytes of that character that fit into `buf` are written: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Fill a `Buffer` with character that takes up two bytes in UTF-8. + * + * console.log(Buffer.allocUnsafe(5).fill('\u0222')); + * // Prints: + * ``` + * + * If `value` contains invalid characters, it is truncated; if no valid + * fill data remains, an exception is thrown: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(5); + * + * console.log(buf.fill('a')); + * // Prints: + * console.log(buf.fill('aazz', 'hex')); + * // Prints: + * console.log(buf.fill('zz', 'hex')); + * // Throws an exception. + * ``` + * @since v0.5.0 + * @param value The value with which to fill `buf`. Empty value (string, Uint8Array, Buffer) is coerced to `0`. + * @param [offset=0] Number of bytes to skip before starting to fill `buf`. + * @param [end=buf.length] Where to stop filling `buf` (not inclusive). + * @param [encoding='utf8'] The encoding for `value` if `value` is a string. + * @return A reference to `buf`. + */ + fill(value: string | Uint8Array | number, offset?: number, end?: number, encoding?: BufferEncoding): this; + /** + * If `value` is: + * + * * a string, `value` is interpreted according to the character encoding in`encoding`. + * * a `Buffer` or [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array), `value` will be used in its entirety. + * To compare a partial `Buffer`, use `buf.subarray`. + * * a number, `value` will be interpreted as an unsigned 8-bit integer + * value between `0` and `255`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('this is a buffer'); + * + * console.log(buf.indexOf('this')); + * // Prints: 0 + * console.log(buf.indexOf('is')); + * // Prints: 2 + * console.log(buf.indexOf(Buffer.from('a buffer'))); + * // Prints: 8 + * console.log(buf.indexOf(97)); + * // Prints: 8 (97 is the decimal ASCII value for 'a') + * console.log(buf.indexOf(Buffer.from('a buffer example'))); + * // Prints: -1 + * console.log(buf.indexOf(Buffer.from('a buffer example').slice(0, 8))); + * // Prints: 8 + * + * const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le'); + * + * console.log(utf16Buffer.indexOf('\u03a3', 0, 'utf16le')); + * // Prints: 4 + * console.log(utf16Buffer.indexOf('\u03a3', -4, 'utf16le')); + * // Prints: 6 + * ``` + * + * If `value` is not a string, number, or `Buffer`, this method will throw a`TypeError`. If `value` is a number, it will be coerced to a valid byte value, + * an integer between 0 and 255. + * + * If `byteOffset` is not a number, it will be coerced to a number. If the result + * of coercion is `NaN` or `0`, then the entire buffer will be searched. This + * behavior matches [`String.prototype.indexOf()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf). + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const b = Buffer.from('abcdef'); + * + * // Passing a value that's a number, but not a valid byte. + * // Prints: 2, equivalent to searching for 99 or 'c'. + * console.log(b.indexOf(99.9)); + * console.log(b.indexOf(256 + 99)); + * + * // Passing a byteOffset that coerces to NaN or 0. + * // Prints: 1, searching the whole buffer. + * console.log(b.indexOf('b', undefined)); + * console.log(b.indexOf('b', {})); + * console.log(b.indexOf('b', null)); + * console.log(b.indexOf('b', [])); + * ``` + * + * If `value` is an empty string or empty `Buffer` and `byteOffset` is less + * than `buf.length`, `byteOffset` will be returned. If `value` is empty and`byteOffset` is at least `buf.length`, `buf.length` will be returned. + * @since v1.5.0 + * @param value What to search for. + * @param [byteOffset=0] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. + * @param [encoding='utf8'] If `value` is a string, this is the encoding used to determine the binary representation of the string that will be searched for in `buf`. + * @return The index of the first occurrence of `value` in `buf`, or `-1` if `buf` does not contain `value`. + */ + indexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; + /** + * Identical to `buf.indexOf()`, except the last occurrence of `value` is found + * rather than the first occurrence. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('this buffer is a buffer'); + * + * console.log(buf.lastIndexOf('this')); + * // Prints: 0 + * console.log(buf.lastIndexOf('buffer')); + * // Prints: 17 + * console.log(buf.lastIndexOf(Buffer.from('buffer'))); + * // Prints: 17 + * console.log(buf.lastIndexOf(97)); + * // Prints: 15 (97 is the decimal ASCII value for 'a') + * console.log(buf.lastIndexOf(Buffer.from('yolo'))); + * // Prints: -1 + * console.log(buf.lastIndexOf('buffer', 5)); + * // Prints: 5 + * console.log(buf.lastIndexOf('buffer', 4)); + * // Prints: -1 + * + * const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le'); + * + * console.log(utf16Buffer.lastIndexOf('\u03a3', undefined, 'utf16le')); + * // Prints: 6 + * console.log(utf16Buffer.lastIndexOf('\u03a3', -5, 'utf16le')); + * // Prints: 4 + * ``` + * + * If `value` is not a string, number, or `Buffer`, this method will throw a`TypeError`. If `value` is a number, it will be coerced to a valid byte value, + * an integer between 0 and 255. + * + * If `byteOffset` is not a number, it will be coerced to a number. Any arguments + * that coerce to `NaN`, like `{}` or `undefined`, will search the whole buffer. + * This behavior matches [`String.prototype.lastIndexOf()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf). + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const b = Buffer.from('abcdef'); + * + * // Passing a value that's a number, but not a valid byte. + * // Prints: 2, equivalent to searching for 99 or 'c'. + * console.log(b.lastIndexOf(99.9)); + * console.log(b.lastIndexOf(256 + 99)); + * + * // Passing a byteOffset that coerces to NaN. + * // Prints: 1, searching the whole buffer. + * console.log(b.lastIndexOf('b', undefined)); + * console.log(b.lastIndexOf('b', {})); + * + * // Passing a byteOffset that coerces to 0. + * // Prints: -1, equivalent to passing 0. + * console.log(b.lastIndexOf('b', null)); + * console.log(b.lastIndexOf('b', [])); + * ``` + * + * If `value` is an empty string or empty `Buffer`, `byteOffset` will be returned. + * @since v6.0.0 + * @param value What to search for. + * @param [byteOffset=buf.length - 1] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. + * @param [encoding='utf8'] If `value` is a string, this is the encoding used to determine the binary representation of the string that will be searched for in `buf`. + * @return The index of the last occurrence of `value` in `buf`, or `-1` if `buf` does not contain `value`. + */ + lastIndexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; + /** + * Creates and returns an [iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) of `[index, byte]` pairs from the contents + * of `buf`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Log the entire contents of a `Buffer`. + * + * const buf = Buffer.from('buffer'); + * + * for (const pair of buf.entries()) { + * console.log(pair); + * } + * // Prints: + * // [0, 98] + * // [1, 117] + * // [2, 102] + * // [3, 102] + * // [4, 101] + * // [5, 114] + * ``` + * @since v1.1.0 + */ + entries(): IterableIterator<[number, number]>; + /** + * Equivalent to `buf.indexOf() !== -1`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('this is a buffer'); + * + * console.log(buf.includes('this')); + * // Prints: true + * console.log(buf.includes('is')); + * // Prints: true + * console.log(buf.includes(Buffer.from('a buffer'))); + * // Prints: true + * console.log(buf.includes(97)); + * // Prints: true (97 is the decimal ASCII value for 'a') + * console.log(buf.includes(Buffer.from('a buffer example'))); + * // Prints: false + * console.log(buf.includes(Buffer.from('a buffer example').slice(0, 8))); + * // Prints: true + * console.log(buf.includes('this', 4)); + * // Prints: false + * ``` + * @since v5.3.0 + * @param value What to search for. + * @param [byteOffset=0] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. + * @param [encoding='utf8'] If `value` is a string, this is its encoding. + * @return `true` if `value` was found in `buf`, `false` otherwise. + */ + includes(value: string | number | Buffer, byteOffset?: number, encoding?: BufferEncoding): boolean; + /** + * Creates and returns an [iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) of `buf` keys (indices). + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('buffer'); + * + * for (const key of buf.keys()) { + * console.log(key); + * } + * // Prints: + * // 0 + * // 1 + * // 2 + * // 3 + * // 4 + * // 5 + * ``` + * @since v1.1.0 + */ + keys(): IterableIterator; + /** + * Creates and returns an [iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) for `buf` values (bytes). This function is + * called automatically when a `Buffer` is used in a `for..of` statement. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('buffer'); + * + * for (const value of buf.values()) { + * console.log(value); + * } + * // Prints: + * // 98 + * // 117 + * // 102 + * // 102 + * // 101 + * // 114 + * + * for (const value of buf) { + * console.log(value); + * } + * // Prints: + * // 98 + * // 117 + * // 102 + * // 102 + * // 101 + * // 114 + * ``` + * @since v1.1.0 + */ + values(): IterableIterator; + } + var Buffer: BufferConstructor; + /** + * Decodes a string of Base64-encoded data into bytes, and encodes those bytes + * into a string using Latin-1 (ISO-8859-1). + * + * The `data` may be any JavaScript-value that can be coerced into a string. + * + * **This function is only provided for compatibility with legacy web platform APIs** + * **and should never be used in new code, because they use strings to represent** + * **binary data and predate the introduction of typed arrays in JavaScript.** + * **For code running using Node.js APIs, converting between base64-encoded strings** + * **and binary data should be performed using `Buffer.from(str, 'base64')` and`buf.toString('base64')`.** + * @since v15.13.0, v14.17.0 + * @legacy Use `Buffer.from(data, 'base64')` instead. + * @param data The Base64-encoded input string. + */ + function atob(data: string): string; + /** + * Decodes a string into bytes using Latin-1 (ISO-8859), and encodes those bytes + * into a string using Base64. + * + * The `data` may be any JavaScript-value that can be coerced into a string. + * + * **This function is only provided for compatibility with legacy web platform APIs** + * **and should never be used in new code, because they use strings to represent** + * **binary data and predate the introduction of typed arrays in JavaScript.** + * **For code running using Node.js APIs, converting between base64-encoded strings** + * **and binary data should be performed using `Buffer.from(str, 'base64')` and`buf.toString('base64')`.** + * @since v15.13.0, v14.17.0 + * @legacy Use `buf.toString('base64')` instead. + * @param data An ASCII (Latin1) string. + */ + function btoa(data: string): string; + interface Blob extends __Blob {} + /** + * `Blob` class is a global reference for `require('node:buffer').Blob` + * https://nodejs.org/api/buffer.html#class-blob + * @since v18.0.0 + */ + var Blob: typeof globalThis extends { + onmessage: any; + Blob: infer T; + } ? T + : typeof NodeBlob; + } +} +declare module "node:buffer" { + export * from "buffer"; +} diff --git a/backend/node_modules/@types/node/child_process.d.ts b/backend/node_modules/@types/node/child_process.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6c7a2c16335b7521049b848a852e0e60d4cdacfd --- /dev/null +++ b/backend/node_modules/@types/node/child_process.d.ts @@ -0,0 +1,1544 @@ +/** + * The `child_process` module provides the ability to spawn subprocesses in + * a manner that is similar, but not identical, to [`popen(3)`](http://man7.org/linux/man-pages/man3/popen.3.html). This capability + * is primarily provided by the {@link spawn} function: + * + * ```js + * const { spawn } = require('child_process'); + * const ls = spawn('ls', ['-lh', '/usr']); + * + * ls.stdout.on('data', (data) => { + * console.log(`stdout: ${data}`); + * }); + * + * ls.stderr.on('data', (data) => { + * console.error(`stderr: ${data}`); + * }); + * + * ls.on('close', (code) => { + * console.log(`child process exited with code ${code}`); + * }); + * ``` + * + * By default, pipes for `stdin`, `stdout`, and `stderr` are established between + * the parent Node.js process and the spawned subprocess. These pipes have + * limited (and platform-specific) capacity. If the subprocess writes to + * stdout in excess of that limit without the output being captured, the + * subprocess blocks waiting for the pipe buffer to accept more data. This is + * identical to the behavior of pipes in the shell. Use the `{ stdio: 'ignore' }`option if the output will not be consumed. + * + * The command lookup is performed using the `options.env.PATH` environment + * variable if `env` is in the `options` object. Otherwise, `process.env.PATH` is + * used. If `options.env` is set without `PATH`, lookup on Unix is performed + * on a default search path search of `/usr/bin:/bin` (see your operating system's + * manual for execvpe/execvp), on Windows the current processes environment + * variable `PATH` is used. + * + * On Windows, environment variables are case-insensitive. Node.js + * lexicographically sorts the `env` keys and uses the first one that + * case-insensitively matches. Only first (in lexicographic order) entry will be + * passed to the subprocess. This might lead to issues on Windows when passing + * objects to the `env` option that have multiple variants of the same key, such as`PATH` and `Path`. + * + * The {@link spawn} method spawns the child process asynchronously, + * without blocking the Node.js event loop. The {@link spawnSync} function provides equivalent functionality in a synchronous manner that blocks + * the event loop until the spawned process either exits or is terminated. + * + * For convenience, the `child_process` module provides a handful of synchronous + * and asynchronous alternatives to {@link spawn} and {@link spawnSync}. Each of these alternatives are implemented on + * top of {@link spawn} or {@link spawnSync}. + * + * * {@link exec}: spawns a shell and runs a command within that + * shell, passing the `stdout` and `stderr` to a callback function when + * complete. + * * {@link execFile}: similar to {@link exec} except + * that it spawns the command directly without first spawning a shell by + * default. + * * {@link fork}: spawns a new Node.js process and invokes a + * specified module with an IPC communication channel established that allows + * sending messages between parent and child. + * * {@link execSync}: a synchronous version of {@link exec} that will block the Node.js event loop. + * * {@link execFileSync}: a synchronous version of {@link execFile} that will block the Node.js event loop. + * + * For certain use cases, such as automating shell scripts, the `synchronous counterparts` may be more convenient. In many cases, however, + * the synchronous methods can have significant impact on performance due to + * stalling the event loop while spawned processes complete. + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/child_process.js) + */ +declare module "child_process" { + import { ObjectEncodingOptions } from "node:fs"; + import { Abortable, EventEmitter } from "node:events"; + import * as net from "node:net"; + import { Pipe, Readable, Stream, Writable } from "node:stream"; + import { URL } from "node:url"; + type Serializable = string | object | number | boolean | bigint; + type SendHandle = net.Socket | net.Server; + /** + * Instances of the `ChildProcess` represent spawned child processes. + * + * Instances of `ChildProcess` are not intended to be created directly. Rather, + * use the {@link spawn}, {@link exec},{@link execFile}, or {@link fork} methods to create + * instances of `ChildProcess`. + * @since v2.2.0 + */ + class ChildProcess extends EventEmitter { + /** + * A `Writable Stream` that represents the child process's `stdin`. + * + * If a child process waits to read all of its input, the child will not continue + * until this stream has been closed via `end()`. + * + * If the child was spawned with `stdio[0]` set to anything other than `'pipe'`, + * then this will be `null`. + * + * `subprocess.stdin` is an alias for `subprocess.stdio[0]`. Both properties will + * refer to the same value. + * + * The `subprocess.stdin` property can be `undefined` if the child process could + * not be successfully spawned. + * @since v0.1.90 + */ + stdin: Writable | null; + /** + * A `Readable Stream` that represents the child process's `stdout`. + * + * If the child was spawned with `stdio[1]` set to anything other than `'pipe'`, + * then this will be `null`. + * + * `subprocess.stdout` is an alias for `subprocess.stdio[1]`. Both properties will + * refer to the same value. + * + * ```js + * const { spawn } = require('child_process'); + * + * const subprocess = spawn('ls'); + * + * subprocess.stdout.on('data', (data) => { + * console.log(`Received chunk ${data}`); + * }); + * ``` + * + * The `subprocess.stdout` property can be `null` if the child process could + * not be successfully spawned. + * @since v0.1.90 + */ + stdout: Readable | null; + /** + * A `Readable Stream` that represents the child process's `stderr`. + * + * If the child was spawned with `stdio[2]` set to anything other than `'pipe'`, + * then this will be `null`. + * + * `subprocess.stderr` is an alias for `subprocess.stdio[2]`. Both properties will + * refer to the same value. + * + * The `subprocess.stderr` property can be `null` if the child process could + * not be successfully spawned. + * @since v0.1.90 + */ + stderr: Readable | null; + /** + * The `subprocess.channel` property is a reference to the child's IPC channel. If + * no IPC channel currently exists, this property is `undefined`. + * @since v7.1.0 + */ + readonly channel?: Pipe | null | undefined; + /** + * A sparse array of pipes to the child process, corresponding with positions in + * the `stdio` option passed to {@link spawn} that have been set + * to the value `'pipe'`. `subprocess.stdio[0]`, `subprocess.stdio[1]`, and`subprocess.stdio[2]` are also available as `subprocess.stdin`,`subprocess.stdout`, and `subprocess.stderr`, + * respectively. + * + * In the following example, only the child's fd `1` (stdout) is configured as a + * pipe, so only the parent's `subprocess.stdio[1]` is a stream, all other values + * in the array are `null`. + * + * ```js + * const assert = require('assert'); + * const fs = require('fs'); + * const child_process = require('child_process'); + * + * const subprocess = child_process.spawn('ls', { + * stdio: [ + * 0, // Use parent's stdin for child. + * 'pipe', // Pipe child's stdout to parent. + * fs.openSync('err.out', 'w'), // Direct child's stderr to a file. + * ] + * }); + * + * assert.strictEqual(subprocess.stdio[0], null); + * assert.strictEqual(subprocess.stdio[0], subprocess.stdin); + * + * assert(subprocess.stdout); + * assert.strictEqual(subprocess.stdio[1], subprocess.stdout); + * + * assert.strictEqual(subprocess.stdio[2], null); + * assert.strictEqual(subprocess.stdio[2], subprocess.stderr); + * ``` + * + * The `subprocess.stdio` property can be `undefined` if the child process could + * not be successfully spawned. + * @since v0.7.10 + */ + readonly stdio: [ + Writable | null, + // stdin + Readable | null, + // stdout + Readable | null, + // stderr + Readable | Writable | null | undefined, + // extra + Readable | Writable | null | undefined, // extra + ]; + /** + * The `subprocess.killed` property indicates whether the child process + * successfully received a signal from `subprocess.kill()`. The `killed` property + * does not indicate that the child process has been terminated. + * @since v0.5.10 + */ + readonly killed: boolean; + /** + * Returns the process identifier (PID) of the child process. If the child process + * fails to spawn due to errors, then the value is `undefined` and `error` is + * emitted. + * + * ```js + * const { spawn } = require('child_process'); + * const grep = spawn('grep', ['ssh']); + * + * console.log(`Spawned child pid: ${grep.pid}`); + * grep.stdin.end(); + * ``` + * @since v0.1.90 + */ + readonly pid?: number | undefined; + /** + * The `subprocess.connected` property indicates whether it is still possible to + * send and receive messages from a child process. When `subprocess.connected` is`false`, it is no longer possible to send or receive messages. + * @since v0.7.2 + */ + readonly connected: boolean; + /** + * The `subprocess.exitCode` property indicates the exit code of the child process. + * If the child process is still running, the field will be `null`. + */ + readonly exitCode: number | null; + /** + * The `subprocess.signalCode` property indicates the signal received by + * the child process if any, else `null`. + */ + readonly signalCode: NodeJS.Signals | null; + /** + * The `subprocess.spawnargs` property represents the full list of command-line + * arguments the child process was launched with. + */ + readonly spawnargs: string[]; + /** + * The `subprocess.spawnfile` property indicates the executable file name of + * the child process that is launched. + * + * For {@link fork}, its value will be equal to `process.execPath`. + * For {@link spawn}, its value will be the name of + * the executable file. + * For {@link exec}, its value will be the name of the shell + * in which the child process is launched. + */ + readonly spawnfile: string; + /** + * The `subprocess.kill()` method sends a signal to the child process. If no + * argument is given, the process will be sent the `'SIGTERM'` signal. See [`signal(7)`](http://man7.org/linux/man-pages/man7/signal.7.html) for a list of available signals. This function + * returns `true` if [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) succeeds, and `false` otherwise. + * + * ```js + * const { spawn } = require('child_process'); + * const grep = spawn('grep', ['ssh']); + * + * grep.on('close', (code, signal) => { + * console.log( + * `child process terminated due to receipt of signal ${signal}`); + * }); + * + * // Send SIGHUP to process. + * grep.kill('SIGHUP'); + * ``` + * + * The `ChildProcess` object may emit an `'error'` event if the signal + * cannot be delivered. Sending a signal to a child process that has already exited + * is not an error but may have unforeseen consequences. Specifically, if the + * process identifier (PID) has been reassigned to another process, the signal will + * be delivered to that process instead which can have unexpected results. + * + * While the function is called `kill`, the signal delivered to the child process + * may not actually terminate the process. + * + * See [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) for reference. + * + * On Windows, where POSIX signals do not exist, the `signal` argument will be + * ignored, and the process will be killed forcefully and abruptly (similar to`'SIGKILL'`). + * See `Signal Events` for more details. + * + * On Linux, child processes of child processes will not be terminated + * when attempting to kill their parent. This is likely to happen when running a + * new process in a shell or with the use of the `shell` option of `ChildProcess`: + * + * ```js + * 'use strict'; + * const { spawn } = require('child_process'); + * + * const subprocess = spawn( + * 'sh', + * [ + * '-c', + * `node -e "setInterval(() => { + * console.log(process.pid, 'is alive') + * }, 500);"`, + * ], { + * stdio: ['inherit', 'inherit', 'inherit'] + * } + * ); + * + * setTimeout(() => { + * subprocess.kill(); // Does not terminate the Node.js process in the shell. + * }, 2000); + * ``` + * @since v0.1.90 + */ + kill(signal?: NodeJS.Signals | number): boolean; + /** + * Calls {@link ChildProcess.kill} with `'SIGTERM'`. + * @since v18.18.0 + */ + [Symbol.dispose](): void; + /** + * When an IPC channel has been established between the parent and child ( + * i.e. when using {@link fork}), the `subprocess.send()` method can + * be used to send messages to the child process. When the child process is a + * Node.js instance, these messages can be received via the `'message'` event. + * + * The message goes through serialization and parsing. The resulting + * message might not be the same as what is originally sent. + * + * For example, in the parent script: + * + * ```js + * const cp = require('child_process'); + * const n = cp.fork(`${__dirname}/sub.js`); + * + * n.on('message', (m) => { + * console.log('PARENT got message:', m); + * }); + * + * // Causes the child to print: CHILD got message: { hello: 'world' } + * n.send({ hello: 'world' }); + * ``` + * + * And then the child script, `'sub.js'` might look like this: + * + * ```js + * process.on('message', (m) => { + * console.log('CHILD got message:', m); + * }); + * + * // Causes the parent to print: PARENT got message: { foo: 'bar', baz: null } + * process.send({ foo: 'bar', baz: NaN }); + * ``` + * + * Child Node.js processes will have a `process.send()` method of their own + * that allows the child to send messages back to the parent. + * + * There is a special case when sending a `{cmd: 'NODE_foo'}` message. Messages + * containing a `NODE_` prefix in the `cmd` property are reserved for use within + * Node.js core and will not be emitted in the child's `'message'` event. Rather, such messages are emitted using the`'internalMessage'` event and are consumed internally by Node.js. + * Applications should avoid using such messages or listening for`'internalMessage'` events as it is subject to change without notice. + * + * The optional `sendHandle` argument that may be passed to `subprocess.send()` is + * for passing a TCP server or socket object to the child process. The child will + * receive the object as the second argument passed to the callback function + * registered on the `'message'` event. Any data that is received + * and buffered in the socket will not be sent to the child. + * + * The optional `callback` is a function that is invoked after the message is + * sent but before the child may have received it. The function is called with a + * single argument: `null` on success, or an `Error` object on failure. + * + * If no `callback` function is provided and the message cannot be sent, an`'error'` event will be emitted by the `ChildProcess` object. This can + * happen, for instance, when the child process has already exited. + * + * `subprocess.send()` will return `false` if the channel has closed or when the + * backlog of unsent messages exceeds a threshold that makes it unwise to send + * more. Otherwise, the method returns `true`. The `callback` function can be + * used to implement flow control. + * + * #### Example: sending a server object + * + * The `sendHandle` argument can be used, for instance, to pass the handle of + * a TCP server object to the child process as illustrated in the example below: + * + * ```js + * const subprocess = require('child_process').fork('subprocess.js'); + * + * // Open up the server object and send the handle. + * const server = require('net').createServer(); + * server.on('connection', (socket) => { + * socket.end('handled by parent'); + * }); + * server.listen(1337, () => { + * subprocess.send('server', server); + * }); + * ``` + * + * The child would then receive the server object as: + * + * ```js + * process.on('message', (m, server) => { + * if (m === 'server') { + * server.on('connection', (socket) => { + * socket.end('handled by child'); + * }); + * } + * }); + * ``` + * + * Once the server is now shared between the parent and child, some connections + * can be handled by the parent and some by the child. + * + * While the example above uses a server created using the `net` module, `dgram`module servers use exactly the same workflow with the exceptions of listening on + * a `'message'` event instead of `'connection'` and using `server.bind()` instead + * of `server.listen()`. This is, however, currently only supported on Unix + * platforms. + * + * #### Example: sending a socket object + * + * Similarly, the `sendHandler` argument can be used to pass the handle of a + * socket to the child process. The example below spawns two children that each + * handle connections with "normal" or "special" priority: + * + * ```js + * const { fork } = require('child_process'); + * const normal = fork('subprocess.js', ['normal']); + * const special = fork('subprocess.js', ['special']); + * + * // Open up the server and send sockets to child. Use pauseOnConnect to prevent + * // the sockets from being read before they are sent to the child process. + * const server = require('net').createServer({ pauseOnConnect: true }); + * server.on('connection', (socket) => { + * + * // If this is special priority... + * if (socket.remoteAddress === '74.125.127.100') { + * special.send('socket', socket); + * return; + * } + * // This is normal priority. + * normal.send('socket', socket); + * }); + * server.listen(1337); + * ``` + * + * The `subprocess.js` would receive the socket handle as the second argument + * passed to the event callback function: + * + * ```js + * process.on('message', (m, socket) => { + * if (m === 'socket') { + * if (socket) { + * // Check that the client socket exists. + * // It is possible for the socket to be closed between the time it is + * // sent and the time it is received in the child process. + * socket.end(`Request handled with ${process.argv[2]} priority`); + * } + * } + * }); + * ``` + * + * Do not use `.maxConnections` on a socket that has been passed to a subprocess. + * The parent cannot track when the socket is destroyed. + * + * Any `'message'` handlers in the subprocess should verify that `socket` exists, + * as the connection may have been closed during the time it takes to send the + * connection to the child. + * @since v0.5.9 + * @param options The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. `options` supports the following properties: + */ + send(message: Serializable, callback?: (error: Error | null) => void): boolean; + send(message: Serializable, sendHandle?: SendHandle, callback?: (error: Error | null) => void): boolean; + send( + message: Serializable, + sendHandle?: SendHandle, + options?: MessageOptions, + callback?: (error: Error | null) => void, + ): boolean; + /** + * Closes the IPC channel between parent and child, allowing the child to exit + * gracefully once there are no other connections keeping it alive. After calling + * this method the `subprocess.connected` and `process.connected` properties in + * both the parent and child (respectively) will be set to `false`, and it will be + * no longer possible to pass messages between the processes. + * + * The `'disconnect'` event will be emitted when there are no messages in the + * process of being received. This will most often be triggered immediately after + * calling `subprocess.disconnect()`. + * + * When the child process is a Node.js instance (e.g. spawned using {@link fork}), the `process.disconnect()` method can be invoked + * within the child process to close the IPC channel as well. + * @since v0.7.2 + */ + disconnect(): void; + /** + * By default, the parent will wait for the detached child to exit. To prevent the + * parent from waiting for a given `subprocess` to exit, use the`subprocess.unref()` method. Doing so will cause the parent's event loop to not + * include the child in its reference count, allowing the parent to exit + * independently of the child, unless there is an established IPC channel between + * the child and the parent. + * + * ```js + * const { spawn } = require('child_process'); + * + * const subprocess = spawn(process.argv[0], ['child_program.js'], { + * detached: true, + * stdio: 'ignore' + * }); + * + * subprocess.unref(); + * ``` + * @since v0.7.10 + */ + unref(): void; + /** + * Calling `subprocess.ref()` after making a call to `subprocess.unref()` will + * restore the removed reference count for the child process, forcing the parent + * to wait for the child to exit before exiting itself. + * + * ```js + * const { spawn } = require('child_process'); + * + * const subprocess = spawn(process.argv[0], ['child_program.js'], { + * detached: true, + * stdio: 'ignore' + * }); + * + * subprocess.unref(); + * subprocess.ref(); + * ``` + * @since v0.7.10 + */ + ref(): void; + /** + * events.EventEmitter + * 1. close + * 2. disconnect + * 3. error + * 4. exit + * 5. message + * 6. spawn + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + addListener(event: "disconnect", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + addListener(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; + addListener(event: "spawn", listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close", code: number | null, signal: NodeJS.Signals | null): boolean; + emit(event: "disconnect"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "exit", code: number | null, signal: NodeJS.Signals | null): boolean; + emit(event: "message", message: Serializable, sendHandle: SendHandle): boolean; + emit(event: "spawn", listener: () => void): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + on(event: "disconnect", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + on(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; + on(event: "spawn", listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + once(event: "disconnect", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + once(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; + once(event: "spawn", listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + prependListener(event: "disconnect", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + prependListener(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; + prependListener(event: "spawn", listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener( + event: "close", + listener: (code: number | null, signal: NodeJS.Signals | null) => void, + ): this; + prependOnceListener(event: "disconnect", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener( + event: "exit", + listener: (code: number | null, signal: NodeJS.Signals | null) => void, + ): this; + prependOnceListener(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; + prependOnceListener(event: "spawn", listener: () => void): this; + } + // return this object when stdio option is undefined or not specified + interface ChildProcessWithoutNullStreams extends ChildProcess { + stdin: Writable; + stdout: Readable; + stderr: Readable; + readonly stdio: [ + Writable, + Readable, + Readable, + // stderr + Readable | Writable | null | undefined, + // extra, no modification + Readable | Writable | null | undefined, // extra, no modification + ]; + } + // return this object when stdio option is a tuple of 3 + interface ChildProcessByStdio + extends ChildProcess + { + stdin: I; + stdout: O; + stderr: E; + readonly stdio: [ + I, + O, + E, + Readable | Writable | null | undefined, + // extra, no modification + Readable | Writable | null | undefined, // extra, no modification + ]; + } + interface MessageOptions { + keepOpen?: boolean | undefined; + } + type IOType = "overlapped" | "pipe" | "ignore" | "inherit"; + type StdioOptions = IOType | Array; + type SerializationType = "json" | "advanced"; + interface MessagingOptions extends Abortable { + /** + * Specify the kind of serialization used for sending messages between processes. + * @default 'json' + */ + serialization?: SerializationType | undefined; + /** + * The signal value to be used when the spawned process will be killed by the abort signal. + * @default 'SIGTERM' + */ + killSignal?: NodeJS.Signals | number | undefined; + /** + * In milliseconds the maximum amount of time the process is allowed to run. + */ + timeout?: number | undefined; + } + interface ProcessEnvOptions { + uid?: number | undefined; + gid?: number | undefined; + cwd?: string | URL | undefined; + env?: NodeJS.ProcessEnv | undefined; + } + interface CommonOptions extends ProcessEnvOptions { + /** + * @default false + */ + windowsHide?: boolean | undefined; + /** + * @default 0 + */ + timeout?: number | undefined; + } + interface CommonSpawnOptions extends CommonOptions, MessagingOptions, Abortable { + argv0?: string | undefined; + /** + * Can be set to 'pipe', 'inherit', 'overlapped', or 'ignore', or an array of these strings. + * If passed as an array, the first element is used for `stdin`, the second for + * `stdout`, and the third for `stderr`. A fourth element can be used to + * specify the `stdio` behavior beyond the standard streams. See + * {@link ChildProcess.stdio} for more information. + * + * @default 'pipe' + */ + stdio?: StdioOptions | undefined; + shell?: boolean | string | undefined; + windowsVerbatimArguments?: boolean | undefined; + } + interface SpawnOptions extends CommonSpawnOptions { + detached?: boolean | undefined; + } + interface SpawnOptionsWithoutStdio extends SpawnOptions { + stdio?: StdioPipeNamed | StdioPipe[] | undefined; + } + type StdioNull = "inherit" | "ignore" | Stream; + type StdioPipeNamed = "pipe" | "overlapped"; + type StdioPipe = undefined | null | StdioPipeNamed; + interface SpawnOptionsWithStdioTuple< + Stdin extends StdioNull | StdioPipe, + Stdout extends StdioNull | StdioPipe, + Stderr extends StdioNull | StdioPipe, + > extends SpawnOptions { + stdio: [Stdin, Stdout, Stderr]; + } + /** + * The `child_process.spawn()` method spawns a new process using the given`command`, with command-line arguments in `args`. If omitted, `args` defaults + * to an empty array. + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * + * A third argument may be used to specify additional options, with these defaults: + * + * ```js + * const defaults = { + * cwd: undefined, + * env: process.env + * }; + * ``` + * + * Use `cwd` to specify the working directory from which the process is spawned. + * If not given, the default is to inherit the current working directory. If given, + * but the path does not exist, the child process emits an `ENOENT` error + * and exits immediately. `ENOENT` is also emitted when the command + * does not exist. + * + * Use `env` to specify environment variables that will be visible to the new + * process, the default is `process.env`. + * + * `undefined` values in `env` will be ignored. + * + * Example of running `ls -lh /usr`, capturing `stdout`, `stderr`, and the + * exit code: + * + * ```js + * const { spawn } = require('child_process'); + * const ls = spawn('ls', ['-lh', '/usr']); + * + * ls.stdout.on('data', (data) => { + * console.log(`stdout: ${data}`); + * }); + * + * ls.stderr.on('data', (data) => { + * console.error(`stderr: ${data}`); + * }); + * + * ls.on('close', (code) => { + * console.log(`child process exited with code ${code}`); + * }); + * ``` + * + * Example: A very elaborate way to run `ps ax | grep ssh` + * + * ```js + * const { spawn } = require('child_process'); + * const ps = spawn('ps', ['ax']); + * const grep = spawn('grep', ['ssh']); + * + * ps.stdout.on('data', (data) => { + * grep.stdin.write(data); + * }); + * + * ps.stderr.on('data', (data) => { + * console.error(`ps stderr: ${data}`); + * }); + * + * ps.on('close', (code) => { + * if (code !== 0) { + * console.log(`ps process exited with code ${code}`); + * } + * grep.stdin.end(); + * }); + * + * grep.stdout.on('data', (data) => { + * console.log(data.toString()); + * }); + * + * grep.stderr.on('data', (data) => { + * console.error(`grep stderr: ${data}`); + * }); + * + * grep.on('close', (code) => { + * if (code !== 0) { + * console.log(`grep process exited with code ${code}`); + * } + * }); + * ``` + * + * Example of checking for failed `spawn`: + * + * ```js + * const { spawn } = require('child_process'); + * const subprocess = spawn('bad_command'); + * + * subprocess.on('error', (err) => { + * console.error('Failed to start subprocess.'); + * }); + * ``` + * + * Certain platforms (macOS, Linux) will use the value of `argv[0]` for the process + * title while others (Windows, SunOS) will use `command`. + * + * Node.js currently overwrites `argv[0]` with `process.execPath` on startup, so`process.argv[0]` in a Node.js child process will not match the `argv0`parameter passed to `spawn` from the parent, + * retrieve it with the`process.argv0` property instead. + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * const { spawn } = require('child_process'); + * const controller = new AbortController(); + * const { signal } = controller; + * const grep = spawn('grep', ['ssh'], { signal }); + * grep.on('error', (err) => { + * // This will be called with err being an AbortError if the controller aborts + * }); + * controller.abort(); // Stops the child process + * ``` + * @since v0.1.90 + * @param command The command to run. + * @param args List of string arguments. + */ + function spawn(command: string, options?: SpawnOptionsWithoutStdio): ChildProcessWithoutNullStreams; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn(command: string, options: SpawnOptions): ChildProcess; + // overloads of spawn with 'args' + function spawn( + command: string, + args?: readonly string[], + options?: SpawnOptionsWithoutStdio, + ): ChildProcessWithoutNullStreams; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn(command: string, args: readonly string[], options: SpawnOptions): ChildProcess; + interface ExecOptions extends CommonOptions { + shell?: string | undefined; + signal?: AbortSignal | undefined; + maxBuffer?: number | undefined; + killSignal?: NodeJS.Signals | number | undefined; + } + interface ExecOptionsWithStringEncoding extends ExecOptions { + encoding: BufferEncoding; + } + interface ExecOptionsWithBufferEncoding extends ExecOptions { + encoding: BufferEncoding | null; // specify `null`. + } + interface ExecException extends Error { + cmd?: string | undefined; + killed?: boolean | undefined; + code?: number | undefined; + signal?: NodeJS.Signals | undefined; + } + /** + * Spawns a shell then executes the `command` within that shell, buffering any + * generated output. The `command` string passed to the exec function is processed + * directly by the shell and special characters (vary based on [shell](https://en.wikipedia.org/wiki/List_of_command-line_interpreters)) + * need to be dealt with accordingly: + * + * ```js + * const { exec } = require('child_process'); + * + * exec('"/path/to/test file/test.sh" arg1 arg2'); + * // Double quotes are used so that the space in the path is not interpreted as + * // a delimiter of multiple arguments. + * + * exec('echo "The \\$HOME variable is $HOME"'); + * // The $HOME variable is escaped in the first instance, but not in the second. + * ``` + * + * **Never pass unsanitized user input to this function. Any input containing shell** + * **metacharacters may be used to trigger arbitrary command execution.** + * + * If a `callback` function is provided, it is called with the arguments`(error, stdout, stderr)`. On success, `error` will be `null`. On error,`error` will be an instance of `Error`. The + * `error.code` property will be + * the exit code of the process. By convention, any exit code other than `0`indicates an error. `error.signal` will be the signal that terminated the + * process. + * + * The `stdout` and `stderr` arguments passed to the callback will contain the + * stdout and stderr output of the child process. By default, Node.js will decode + * the output as UTF-8 and pass strings to the callback. The `encoding` option + * can be used to specify the character encoding used to decode the stdout and + * stderr output. If `encoding` is `'buffer'`, or an unrecognized character + * encoding, `Buffer` objects will be passed to the callback instead. + * + * ```js + * const { exec } = require('child_process'); + * exec('cat *.js missing_file | wc -l', (error, stdout, stderr) => { + * if (error) { + * console.error(`exec error: ${error}`); + * return; + * } + * console.log(`stdout: ${stdout}`); + * console.error(`stderr: ${stderr}`); + * }); + * ``` + * + * If `timeout` is greater than `0`, the parent will send the signal + * identified by the `killSignal` property (the default is `'SIGTERM'`) if the + * child runs longer than `timeout` milliseconds. + * + * Unlike the [`exec(3)`](http://man7.org/linux/man-pages/man3/exec.3.html) POSIX system call, `child_process.exec()` does not replace + * the existing process and uses a shell to execute the command. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned`ChildProcess` instance is attached to the `Promise` as a `child` property. In + * case of an error (including any error resulting in an exit code other than 0), a + * rejected promise is returned, with the same `error` object given in the + * callback, but with two additional properties `stdout` and `stderr`. + * + * ```js + * const util = require('util'); + * const exec = util.promisify(require('child_process').exec); + * + * async function lsExample() { + * const { stdout, stderr } = await exec('ls'); + * console.log('stdout:', stdout); + * console.error('stderr:', stderr); + * } + * lsExample(); + * ``` + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * const { exec } = require('child_process'); + * const controller = new AbortController(); + * const { signal } = controller; + * const child = exec('grep ssh', { signal }, (error) => { + * console.log(error); // an AbortError + * }); + * controller.abort(); + * ``` + * @since v0.1.90 + * @param command The command to run, with space-separated arguments. + * @param callback called with the output when process terminates. + */ + function exec( + command: string, + callback?: (error: ExecException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. + function exec( + command: string, + options: { + encoding: "buffer" | null; + } & ExecOptions, + callback?: (error: ExecException | null, stdout: Buffer, stderr: Buffer) => void, + ): ChildProcess; + // `options` with well known `encoding` means stdout/stderr are definitely `string`. + function exec( + command: string, + options: { + encoding: BufferEncoding; + } & ExecOptions, + callback?: (error: ExecException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + // `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`. + // There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`. + function exec( + command: string, + options: { + encoding: BufferEncoding; + } & ExecOptions, + callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void, + ): ChildProcess; + // `options` without an `encoding` means stdout/stderr are definitely `string`. + function exec( + command: string, + options: ExecOptions, + callback?: (error: ExecException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + // fallback if nothing else matches. Worst case is always `string | Buffer`. + function exec( + command: string, + options: (ObjectEncodingOptions & ExecOptions) | undefined | null, + callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void, + ): ChildProcess; + interface PromiseWithChild extends Promise { + child: ChildProcess; + } + namespace exec { + function __promisify__(command: string): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + command: string, + options: { + encoding: "buffer" | null; + } & ExecOptions, + ): PromiseWithChild<{ + stdout: Buffer; + stderr: Buffer; + }>; + function __promisify__( + command: string, + options: { + encoding: BufferEncoding; + } & ExecOptions, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + command: string, + options: ExecOptions, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + command: string, + options?: (ObjectEncodingOptions & ExecOptions) | null, + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + } + interface ExecFileOptions extends CommonOptions, Abortable { + maxBuffer?: number | undefined; + killSignal?: NodeJS.Signals | number | undefined; + windowsVerbatimArguments?: boolean | undefined; + shell?: boolean | string | undefined; + signal?: AbortSignal | undefined; + } + interface ExecFileOptionsWithStringEncoding extends ExecFileOptions { + encoding: BufferEncoding; + } + interface ExecFileOptionsWithBufferEncoding extends ExecFileOptions { + encoding: "buffer" | null; + } + interface ExecFileOptionsWithOtherEncoding extends ExecFileOptions { + encoding: BufferEncoding; + } + type ExecFileException = + & Omit + & Omit + & { code?: string | number | undefined | null }; + /** + * The `child_process.execFile()` function is similar to {@link exec} except that it does not spawn a shell by default. Rather, the specified + * executable `file` is spawned directly as a new process making it slightly more + * efficient than {@link exec}. + * + * The same options as {@link exec} are supported. Since a shell is + * not spawned, behaviors such as I/O redirection and file globbing are not + * supported. + * + * ```js + * const { execFile } = require('child_process'); + * const child = execFile('node', ['--version'], (error, stdout, stderr) => { + * if (error) { + * throw error; + * } + * console.log(stdout); + * }); + * ``` + * + * The `stdout` and `stderr` arguments passed to the callback will contain the + * stdout and stderr output of the child process. By default, Node.js will decode + * the output as UTF-8 and pass strings to the callback. The `encoding` option + * can be used to specify the character encoding used to decode the stdout and + * stderr output. If `encoding` is `'buffer'`, or an unrecognized character + * encoding, `Buffer` objects will be passed to the callback instead. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned`ChildProcess` instance is attached to the `Promise` as a `child` property. In + * case of an error (including any error resulting in an exit code other than 0), a + * rejected promise is returned, with the same `error` object given in the + * callback, but with two additional properties `stdout` and `stderr`. + * + * ```js + * const util = require('util'); + * const execFile = util.promisify(require('child_process').execFile); + * async function getVersion() { + * const { stdout } = await execFile('node', ['--version']); + * console.log(stdout); + * } + * getVersion(); + * ``` + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * const { execFile } = require('child_process'); + * const controller = new AbortController(); + * const { signal } = controller; + * const child = execFile('node', ['--version'], { signal }, (error) => { + * console.log(error); // an AbortError + * }); + * controller.abort(); + * ``` + * @since v0.1.91 + * @param file The name or path of the executable file to run. + * @param args List of string arguments. + * @param callback Called with the output when process terminates. + */ + function execFile(file: string): ChildProcess; + function execFile( + file: string, + options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, + ): ChildProcess; + function execFile(file: string, args?: readonly string[] | null): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, + ): ChildProcess; + // no `options` definitely means stdout/stderr are `string`. + function execFile( + file: string, + callback: (error: ExecFileException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + callback: (error: ExecFileException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. + function execFile( + file: string, + options: ExecFileOptionsWithBufferEncoding, + callback: (error: ExecFileException | null, stdout: Buffer, stderr: Buffer) => void, + ): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithBufferEncoding, + callback: (error: ExecFileException | null, stdout: Buffer, stderr: Buffer) => void, + ): ChildProcess; + // `options` with well known `encoding` means stdout/stderr are definitely `string`. + function execFile( + file: string, + options: ExecFileOptionsWithStringEncoding, + callback: (error: ExecFileException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithStringEncoding, + callback: (error: ExecFileException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + // `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`. + // There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`. + function execFile( + file: string, + options: ExecFileOptionsWithOtherEncoding, + callback: (error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void, + ): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithOtherEncoding, + callback: (error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void, + ): ChildProcess; + // `options` without an `encoding` means stdout/stderr are definitely `string`. + function execFile( + file: string, + options: ExecFileOptions, + callback: (error: ExecFileException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptions, + callback: (error: ExecFileException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + // fallback if nothing else matches. Worst case is always `string | Buffer`. + function execFile( + file: string, + options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, + callback: + | ((error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void) + | undefined + | null, + ): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, + callback: + | ((error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void) + | undefined + | null, + ): ChildProcess; + namespace execFile { + function __promisify__(file: string): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + options: ExecFileOptionsWithBufferEncoding, + ): PromiseWithChild<{ + stdout: Buffer; + stderr: Buffer; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithBufferEncoding, + ): PromiseWithChild<{ + stdout: Buffer; + stderr: Buffer; + }>; + function __promisify__( + file: string, + options: ExecFileOptionsWithStringEncoding, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithStringEncoding, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + options: ExecFileOptionsWithOtherEncoding, + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithOtherEncoding, + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + function __promisify__( + file: string, + options: ExecFileOptions, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptions, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + } + interface ForkOptions extends ProcessEnvOptions, MessagingOptions, Abortable { + execPath?: string | undefined; + execArgv?: string[] | undefined; + silent?: boolean | undefined; + /** + * Can be set to 'pipe', 'inherit', 'overlapped', or 'ignore', or an array of these strings. + * If passed as an array, the first element is used for `stdin`, the second for + * `stdout`, and the third for `stderr`. A fourth element can be used to + * specify the `stdio` behavior beyond the standard streams. See + * {@link ChildProcess.stdio} for more information. + * + * @default 'pipe' + */ + stdio?: StdioOptions | undefined; + detached?: boolean | undefined; + windowsVerbatimArguments?: boolean | undefined; + } + /** + * The `child_process.fork()` method is a special case of {@link spawn} used specifically to spawn new Node.js processes. + * Like {@link spawn}, a `ChildProcess` object is returned. The + * returned `ChildProcess` will have an additional communication channel + * built-in that allows messages to be passed back and forth between the parent and + * child. See `subprocess.send()` for details. + * + * Keep in mind that spawned Node.js child processes are + * independent of the parent with exception of the IPC communication channel + * that is established between the two. Each process has its own memory, with + * their own V8 instances. Because of the additional resource allocations + * required, spawning a large number of child Node.js processes is not + * recommended. + * + * By default, `child_process.fork()` will spawn new Node.js instances using the `process.execPath` of the parent process. The `execPath` property in the`options` object allows for an alternative + * execution path to be used. + * + * Node.js processes launched with a custom `execPath` will communicate with the + * parent process using the file descriptor (fd) identified using the + * environment variable `NODE_CHANNEL_FD` on the child process. + * + * Unlike the [`fork(2)`](http://man7.org/linux/man-pages/man2/fork.2.html) POSIX system call, `child_process.fork()` does not clone the + * current process. + * + * The `shell` option available in {@link spawn} is not supported by`child_process.fork()` and will be ignored if set. + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * if (process.argv[2] === 'child') { + * setTimeout(() => { + * console.log(`Hello from ${process.argv[2]}!`); + * }, 1_000); + * } else { + * const { fork } = require('child_process'); + * const controller = new AbortController(); + * const { signal } = controller; + * const child = fork(__filename, ['child'], { signal }); + * child.on('error', (err) => { + * // This will be called with err being an AbortError if the controller aborts + * }); + * controller.abort(); // Stops the child process + * } + * ``` + * @since v0.5.0 + * @param modulePath The module to run in the child. + * @param args List of string arguments. + */ + function fork(modulePath: string, options?: ForkOptions): ChildProcess; + function fork(modulePath: string, args?: readonly string[], options?: ForkOptions): ChildProcess; + interface SpawnSyncOptions extends CommonSpawnOptions { + input?: string | NodeJS.ArrayBufferView | undefined; + maxBuffer?: number | undefined; + encoding?: BufferEncoding | "buffer" | null | undefined; + } + interface SpawnSyncOptionsWithStringEncoding extends SpawnSyncOptions { + encoding: BufferEncoding; + } + interface SpawnSyncOptionsWithBufferEncoding extends SpawnSyncOptions { + encoding?: "buffer" | null | undefined; + } + interface SpawnSyncReturns { + pid: number; + output: Array; + stdout: T; + stderr: T; + status: number | null; + signal: NodeJS.Signals | null; + error?: Error | undefined; + } + /** + * The `child_process.spawnSync()` method is generally identical to {@link spawn} with the exception that the function will not return + * until the child process has fully closed. When a timeout has been encountered + * and `killSignal` is sent, the method won't return until the process has + * completely exited. If the process intercepts and handles the `SIGTERM` signal + * and doesn't exit, the parent process will wait until the child process has + * exited. + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * @since v0.11.12 + * @param command The command to run. + * @param args List of string arguments. + */ + function spawnSync(command: string): SpawnSyncReturns; + function spawnSync(command: string, options: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; + function spawnSync(command: string, options: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; + function spawnSync(command: string, options?: SpawnSyncOptions): SpawnSyncReturns; + function spawnSync(command: string, args: readonly string[]): SpawnSyncReturns; + function spawnSync( + command: string, + args: readonly string[], + options: SpawnSyncOptionsWithStringEncoding, + ): SpawnSyncReturns; + function spawnSync( + command: string, + args: readonly string[], + options: SpawnSyncOptionsWithBufferEncoding, + ): SpawnSyncReturns; + function spawnSync( + command: string, + args?: readonly string[], + options?: SpawnSyncOptions, + ): SpawnSyncReturns; + interface CommonExecOptions extends CommonOptions { + input?: string | NodeJS.ArrayBufferView | undefined; + /** + * Can be set to 'pipe', 'inherit', 'overlapped', or 'ignore', or an array of these strings. + * If passed as an array, the first element is used for `stdin`, the second for + * `stdout`, and the third for `stderr`. A fourth element can be used to + * specify the `stdio` behavior beyond the standard streams. See + * {@link ChildProcess.stdio} for more information. + * + * @default 'pipe' + */ + stdio?: StdioOptions | undefined; + killSignal?: NodeJS.Signals | number | undefined; + maxBuffer?: number | undefined; + encoding?: BufferEncoding | "buffer" | null | undefined; + } + interface ExecSyncOptions extends CommonExecOptions { + shell?: string | undefined; + } + interface ExecSyncOptionsWithStringEncoding extends ExecSyncOptions { + encoding: BufferEncoding; + } + interface ExecSyncOptionsWithBufferEncoding extends ExecSyncOptions { + encoding?: "buffer" | null | undefined; + } + /** + * The `child_process.execSync()` method is generally identical to {@link exec} with the exception that the method will not return + * until the child process has fully closed. When a timeout has been encountered + * and `killSignal` is sent, the method won't return until the process has + * completely exited. If the child process intercepts and handles the `SIGTERM`signal and doesn't exit, the parent process will wait until the child process + * has exited. + * + * If the process times out or has a non-zero exit code, this method will throw. + * The `Error` object will contain the entire result from {@link spawnSync}. + * + * **Never pass unsanitized user input to this function. Any input containing shell** + * **metacharacters may be used to trigger arbitrary command execution.** + * @since v0.11.12 + * @param command The command to run. + * @return The stdout from the command. + */ + function execSync(command: string): Buffer; + function execSync(command: string, options: ExecSyncOptionsWithStringEncoding): string; + function execSync(command: string, options: ExecSyncOptionsWithBufferEncoding): Buffer; + function execSync(command: string, options?: ExecSyncOptions): string | Buffer; + interface ExecFileSyncOptions extends CommonExecOptions { + shell?: boolean | string | undefined; + } + interface ExecFileSyncOptionsWithStringEncoding extends ExecFileSyncOptions { + encoding: BufferEncoding; + } + interface ExecFileSyncOptionsWithBufferEncoding extends ExecFileSyncOptions { + encoding?: "buffer" | null; // specify `null`. + } + /** + * The `child_process.execFileSync()` method is generally identical to {@link execFile} with the exception that the method will not + * return until the child process has fully closed. When a timeout has been + * encountered and `killSignal` is sent, the method won't return until the process + * has completely exited. + * + * If the child process intercepts and handles the `SIGTERM` signal and + * does not exit, the parent process will still wait until the child process has + * exited. + * + * If the process times out or has a non-zero exit code, this method will throw an `Error` that will include the full result of the underlying {@link spawnSync}. + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * @since v0.11.12 + * @param file The name or path of the executable file to run. + * @param args List of string arguments. + * @return The stdout from the command. + */ + function execFileSync(file: string): Buffer; + function execFileSync(file: string, options: ExecFileSyncOptionsWithStringEncoding): string; + function execFileSync(file: string, options: ExecFileSyncOptionsWithBufferEncoding): Buffer; + function execFileSync(file: string, options?: ExecFileSyncOptions): string | Buffer; + function execFileSync(file: string, args: readonly string[]): Buffer; + function execFileSync( + file: string, + args: readonly string[], + options: ExecFileSyncOptionsWithStringEncoding, + ): string; + function execFileSync( + file: string, + args: readonly string[], + options: ExecFileSyncOptionsWithBufferEncoding, + ): Buffer; + function execFileSync(file: string, args?: readonly string[], options?: ExecFileSyncOptions): string | Buffer; +} +declare module "node:child_process" { + export * from "child_process"; +} diff --git a/backend/node_modules/@types/node/cluster.d.ts b/backend/node_modules/@types/node/cluster.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..27143b882fb88b3b455d58b1fc5ffea0b3a14b29 --- /dev/null +++ b/backend/node_modules/@types/node/cluster.d.ts @@ -0,0 +1,578 @@ +/** + * Clusters of Node.js processes can be used to run multiple instances of Node.js + * that can distribute workloads among their application threads. When process isolation + * is not needed, use the [`worker_threads`](https://nodejs.org/docs/latest-v18.x/api/worker_threads.html) + * module instead, which allows running multiple application threads within a single Node.js instance. + * + * The cluster module allows easy creation of child processes that all share + * server ports. + * + * ```js + * import cluster from 'node:cluster'; + * import http from 'node:http'; + * import { availableParallelism } from 'node:os'; + * import process from 'node:process'; + * + * const numCPUs = availableParallelism(); + * + * if (cluster.isPrimary) { + * console.log(`Primary ${process.pid} is running`); + * + * // Fork workers. + * for (let i = 0; i < numCPUs; i++) { + * cluster.fork(); + * } + * + * cluster.on('exit', (worker, code, signal) => { + * console.log(`worker ${worker.process.pid} died`); + * }); + * } else { + * // Workers can share any TCP connection + * // In this case it is an HTTP server + * http.createServer((req, res) => { + * res.writeHead(200); + * res.end('hello world\n'); + * }).listen(8000); + * + * console.log(`Worker ${process.pid} started`); + * } + * ``` + * + * Running Node.js will now share port 8000 between the workers: + * + * ```console + * $ node server.js + * Primary 3596 is running + * Worker 4324 started + * Worker 4520 started + * Worker 6056 started + * Worker 5644 started + * ``` + * + * On Windows, it is not yet possible to set up a named pipe server in a worker. + * @see [source](https://github.com/nodejs/node/blob/v18.19.1/lib/cluster.js) + */ +declare module "cluster" { + import * as child from "node:child_process"; + import EventEmitter = require("node:events"); + import * as net from "node:net"; + type SerializationType = "json" | "advanced"; + export interface ClusterSettings { + /** + * List of string arguments passed to the Node.js executable. + * @default process.execArgv + */ + execArgv?: string[] | undefined; + /** + * File path to worker file. + * @default process.argv[1] + */ + exec?: string | undefined; + /** + * String arguments passed to worker. + * @default process.argv.slice(2) + */ + args?: string[] | undefined; + /** + * Whether or not to send output to parent's stdio. + * @default false + */ + silent?: boolean | undefined; + /** + * Configures the stdio of forked processes. Because the cluster module relies on IPC to function, this configuration must + * contain an `'ipc'` entry. When this option is provided, it overrides `silent`. See [`child_prcess.spawn()`](https://nodejs.org/docs/latest-v18.x/api/child_process.html#child_processspawncommand-args-options)'s + * [`stdio`](https://nodejs.org/docs/latest-v18.x/api/child_process.html#optionsstdio). + */ + stdio?: any[] | undefined; + /** + * Sets the user identity of the process. (See [`setuid(2)`](https://man7.org/linux/man-pages/man2/setuid.2.html).) + */ + uid?: number | undefined; + /** + * Sets the group identity of the process. (See [`setgid(2)`](https://man7.org/linux/man-pages/man2/setgid.2.html).) + */ + gid?: number | undefined; + /** + * Sets inspector port of worker. This can be a number, or a function that takes no arguments and returns a number. + * By default each worker gets its own port, incremented from the primary's `process.debugPort`. + */ + inspectPort?: number | (() => number) | undefined; + /** + * Specify the kind of serialization used for sending messages between processes. Possible values are `'json'` and `'advanced'`. + * See [Advanced serialization for `child_process`](https://nodejs.org/docs/latest-v18.x/api/child_process.html#advanced-serialization) for more details. + * @default false + */ + serialization?: SerializationType | undefined; + /** + * Current working directory of the worker process. + * @default undefined (inherits from parent process) + */ + cwd?: string | undefined; + /** + * Hide the forked processes console window that would normally be created on Windows systems. + * @default false + */ + windowsHide?: boolean | undefined; + } + export interface Address { + address: string; + port: number; + /** + * The `addressType` is one of: + * + * * `4` (TCPv4) + * * `6` (TCPv6) + * * `-1` (Unix domain socket) + * * `'udp4'` or `'udp6'` (UDPv4 or UDPv6) + */ + addressType: 4 | 6 | -1 | "udp4" | "udp6"; + } + /** + * A `Worker` object contains all public information and method about a worker. + * In the primary it can be obtained using `cluster.workers`. In a worker + * it can be obtained using `cluster.worker`. + * @since v0.7.0 + */ + export class Worker extends EventEmitter { + /** + * Each new worker is given its own unique id, this id is stored in the `id`. + * + * While a worker is alive, this is the key that indexes it in `cluster.workers`. + * @since v0.8.0 + */ + id: number; + /** + * All workers are created using [`child_process.fork()`](https://nodejs.org/docs/latest-v18.x/api/child_process.html#child_processforkmodulepath-args-options), the returned object + * from this function is stored as `.process`. In a worker, the global `process` is stored. + * + * See: [Child Process module](https://nodejs.org/docs/latest-v18.x/api/child_process.html#child_processforkmodulepath-args-options). + * + * Workers will call `process.exit(0)` if the `'disconnect'` event occurs + * on `process` and `.exitedAfterDisconnect` is not `true`. This protects against + * accidental disconnection. + * @since v0.7.0 + */ + process: child.ChildProcess; + /** + * Send a message to a worker or primary, optionally with a handle. + * + * In the primary, this sends a message to a specific worker. It is identical to [`ChildProcess.send()`](https://nodejs.org/docs/latest-v18.x/api/child_process.html#subprocesssendmessage-sendhandle-options-callback). + * + * In a worker, this sends a message to the primary. It is identical to `process.send()`. + * + * This example will echo back all messages from the primary: + * + * ```js + * if (cluster.isPrimary) { + * const worker = cluster.fork(); + * worker.send('hi there'); + * + * } else if (cluster.isWorker) { + * process.on('message', (msg) => { + * process.send(msg); + * }); + * } + * ``` + * @since v0.7.0 + * @param options The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. + */ + send(message: child.Serializable, callback?: (error: Error | null) => void): boolean; + send( + message: child.Serializable, + sendHandle: child.SendHandle, + callback?: (error: Error | null) => void, + ): boolean; + send( + message: child.Serializable, + sendHandle: child.SendHandle, + options?: child.MessageOptions, + callback?: (error: Error | null) => void, + ): boolean; + /** + * This function will kill the worker. In the primary worker, it does this by + * disconnecting the `worker.process`, and once disconnected, killing with `signal`. In the worker, it does it by killing the process with `signal`. + * + * The `kill()` function kills the worker process without waiting for a graceful + * disconnect, it has the same behavior as `worker.process.kill()`. + * + * This method is aliased as `worker.destroy()` for backwards compatibility. + * + * In a worker, `process.kill()` exists, but it is not this function; + * it is [`kill()`](https://nodejs.org/docs/latest-v18.x/api/process.html#processkillpid-signal). + * @since v0.9.12 + * @param [signal='SIGTERM'] Name of the kill signal to send to the worker process. + */ + kill(signal?: string): void; + destroy(signal?: string): void; + /** + * In a worker, this function will close all servers, wait for the `'close'` event + * on those servers, and then disconnect the IPC channel. + * + * In the primary, an internal message is sent to the worker causing it to call `.disconnect()` on itself. + * + * Causes `.exitedAfterDisconnect` to be set. + * + * After a server is closed, it will no longer accept new connections, + * but connections may be accepted by any other listening worker. Existing + * connections will be allowed to close as usual. When no more connections exist, + * see `server.close()`, the IPC channel to the worker will close allowing it + * to die gracefully. + * + * The above applies _only_ to server connections, client connections are not + * automatically closed by workers, and disconnect does not wait for them to close + * before exiting. + * + * In a worker, `process.disconnect` exists, but it is not this function; + * it is `disconnect()`. + * + * Because long living server connections may block workers from disconnecting, it + * may be useful to send a message, so application specific actions may be taken to + * close them. It also may be useful to implement a timeout, killing a worker if + * the `'disconnect'` event has not been emitted after some time. + * + * ```js + * if (cluster.isPrimary) { + * const worker = cluster.fork(); + * let timeout; + * + * worker.on('listening', (address) => { + * worker.send('shutdown'); + * worker.disconnect(); + * timeout = setTimeout(() => { + * worker.kill(); + * }, 2000); + * }); + * + * worker.on('disconnect', () => { + * clearTimeout(timeout); + * }); + * + * } else if (cluster.isWorker) { + * const net = require('node:net'); + * const server = net.createServer((socket) => { + * // Connections never end + * }); + * + * server.listen(8000); + * + * process.on('message', (msg) => { + * if (msg === 'shutdown') { + * // Initiate graceful close of any connections to server + * } + * }); + * } + * ``` + * @since v0.7.7 + * @return A reference to `worker`. + */ + disconnect(): void; + /** + * This function returns `true` if the worker is connected to its primary via its + * IPC channel, `false` otherwise. A worker is connected to its primary after it + * has been created. It is disconnected after the `'disconnect'` event is emitted. + * @since v0.11.14 + */ + isConnected(): boolean; + /** + * This function returns `true` if the worker's process has terminated (either + * because of exiting or being signaled). Otherwise, it returns `false`. + * + * ```js + * import cluster from 'node:cluster'; + * import http from 'node:http'; + * import { availableParallelism } from 'node:os'; + * import process from 'node:process'; + * + * const numCPUs = availableParallelism(); + * + * if (cluster.isPrimary) { + * console.log(`Primary ${process.pid} is running`); + * + * // Fork workers. + * for (let i = 0; i < numCPUs; i++) { + * cluster.fork(); + * } + * + * cluster.on('fork', (worker) => { + * console.log('worker is dead:', worker.isDead()); + * }); + * + * cluster.on('exit', (worker, code, signal) => { + * console.log('worker is dead:', worker.isDead()); + * }); + * } else { + * // Workers can share any TCP connection. In this case, it is an HTTP server. + * http.createServer((req, res) => { + * res.writeHead(200); + * res.end(`Current process\n ${process.pid}`); + * process.kill(process.pid); + * }).listen(8000); + * } + * ``` + * @since v0.11.14 + */ + isDead(): boolean; + /** + * This property is `true` if the worker exited due to `.disconnect()`. + * If the worker exited any other way, it is `false`. If the + * worker has not exited, it is `undefined`. + * + * The boolean `worker.exitedAfterDisconnect` allows distinguishing between + * voluntary and accidental exit, the primary may choose not to respawn a worker + * based on this value. + * + * ```js + * cluster.on('exit', (worker, code, signal) => { + * if (worker.exitedAfterDisconnect === true) { + * console.log('Oh, it was just voluntary – no need to worry'); + * } + * }); + * + * // kill worker + * worker.kill(); + * ``` + * @since v6.0.0 + */ + exitedAfterDisconnect: boolean; + /** + * events.EventEmitter + * 1. disconnect + * 2. error + * 3. exit + * 4. listening + * 5. message + * 6. online + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "disconnect", listener: () => void): this; + addListener(event: "error", listener: (error: Error) => void): this; + addListener(event: "exit", listener: (code: number, signal: string) => void): this; + addListener(event: "listening", listener: (address: Address) => void): this; + addListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + addListener(event: "online", listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "disconnect"): boolean; + emit(event: "error", error: Error): boolean; + emit(event: "exit", code: number, signal: string): boolean; + emit(event: "listening", address: Address): boolean; + emit(event: "message", message: any, handle: net.Socket | net.Server): boolean; + emit(event: "online"): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "disconnect", listener: () => void): this; + on(event: "error", listener: (error: Error) => void): this; + on(event: "exit", listener: (code: number, signal: string) => void): this; + on(event: "listening", listener: (address: Address) => void): this; + on(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + on(event: "online", listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "disconnect", listener: () => void): this; + once(event: "error", listener: (error: Error) => void): this; + once(event: "exit", listener: (code: number, signal: string) => void): this; + once(event: "listening", listener: (address: Address) => void): this; + once(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + once(event: "online", listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "disconnect", listener: () => void): this; + prependListener(event: "error", listener: (error: Error) => void): this; + prependListener(event: "exit", listener: (code: number, signal: string) => void): this; + prependListener(event: "listening", listener: (address: Address) => void): this; + prependListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependListener(event: "online", listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "disconnect", listener: () => void): this; + prependOnceListener(event: "error", listener: (error: Error) => void): this; + prependOnceListener(event: "exit", listener: (code: number, signal: string) => void): this; + prependOnceListener(event: "listening", listener: (address: Address) => void): this; + prependOnceListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependOnceListener(event: "online", listener: () => void): this; + } + export interface Cluster extends EventEmitter { + disconnect(callback?: () => void): void; + /** + * Spawn a new worker process. + * + * This can only be called from the primary process. + * @param env Key/value pairs to add to worker process environment. + * @since v0.6.0 + */ + fork(env?: any): Worker; + /** @deprecated since v16.0.0 - use isPrimary. */ + readonly isMaster: boolean; + /** + * True if the process is a primary. This is determined by the `process.env.NODE_UNIQUE_ID`. If `process.env.NODE_UNIQUE_ID` + * is undefined, then `isPrimary` is `true`. + * @since v16.0.0 + */ + readonly isPrimary: boolean; + /** + * True if the process is not a primary (it is the negation of `cluster.isPrimary`). + * @since v0.6.0 + */ + readonly isWorker: boolean; + /** + * The scheduling policy, either `cluster.SCHED_RR` for round-robin or `cluster.SCHED_NONE` to leave it to the operating system. This is a global + * setting and effectively frozen once either the first worker is spawned, or [`.setupPrimary()`](https://nodejs.org/docs/latest-v18.x/api/cluster.html#clustersetupprimarysettings) + * is called, whichever comes first. + * + * `SCHED_RR` is the default on all operating systems except Windows. Windows will change to `SCHED_RR` once libuv is able to effectively distribute + * IOCP handles without incurring a large performance hit. + * + * `cluster.schedulingPolicy` can also be set through the `NODE_CLUSTER_SCHED_POLICY` environment variable. Valid values are `'rr'` and `'none'`. + * @since v0.11.2 + */ + schedulingPolicy: number; + /** + * After calling [`.setupPrimary()`](https://nodejs.org/docs/latest-v18.x/api/cluster.html#clustersetupprimarysettings) + * (or [`.fork()`](https://nodejs.org/docs/latest-v18.x/api/cluster.html#clusterforkenv)) this settings object will contain + * the settings, including the default values. + * + * This object is not intended to be changed or set manually. + * @since v0.7.1 + */ + readonly settings: ClusterSettings; + /** @deprecated since v16.0.0 - use [`.setupPrimary()`](https://nodejs.org/docs/latest-v18.x/api/cluster.html#clustersetupprimarysettings) instead. */ + setupMaster(settings?: ClusterSettings): void; + /** + * `setupPrimary` is used to change the default 'fork' behavior. Once called, the settings will be present in `cluster.settings`. + * + * Any settings changes only affect future calls to [`.fork()`](https://nodejs.org/docs/latest-v18.x/api/cluster.html#clusterforkenv) + * and have no effect on workers that are already running. + * + * The only attribute of a worker that cannot be set via `.setupPrimary()` is the `env` passed to + * [`.fork()`](https://nodejs.org/docs/latest-v18.x/api/cluster.html#clusterforkenv). + * + * The defaults above apply to the first call only; the defaults for later calls are the current values at the time of + * `cluster.setupPrimary()` is called. + * + * ```js + * import cluster from 'node:cluster'; + * + * cluster.setupPrimary({ + * exec: 'worker.js', + * args: ['--use', 'https'], + * silent: true, + * }); + * cluster.fork(); // https worker + * cluster.setupPrimary({ + * exec: 'worker.js', + * args: ['--use', 'http'], + * }); + * cluster.fork(); // http worker + * ``` + * + * This can only be called from the primary process. + * @since v16.0.0 + */ + setupPrimary(settings?: ClusterSettings): void; + /** + * A reference to the current worker object. Not available in the primary process. + * + * ```js + * import cluster from 'node:cluster'; + * + * if (cluster.isPrimary) { + * console.log('I am primary'); + * cluster.fork(); + * cluster.fork(); + * } else if (cluster.isWorker) { + * console.log(`I am worker #${cluster.worker.id}`); + * } + * ``` + * @since v0.7.0 + */ + readonly worker?: Worker | undefined; + /** + * A hash that stores the active worker objects, keyed by `id` field. This makes it easy to loop through all the workers. It is only available in the primary process. + * + * A worker is removed from `cluster.workers` after the worker has disconnected _and_ exited. The order between these two events cannot be determined in advance. However, it + * is guaranteed that the removal from the `cluster.workers` list happens before the last `'disconnect'` or `'exit'` event is emitted. + * + * ```js + * import cluster from 'node:cluster'; + * + * for (const worker of Object.values(cluster.workers)) { + * worker.send('big announcement to all workers'); + * } + * ``` + * @since v0.7.0 + */ + readonly workers?: NodeJS.Dict | undefined; + readonly SCHED_NONE: number; + readonly SCHED_RR: number; + /** + * events.EventEmitter + * 1. disconnect + * 2. exit + * 3. fork + * 4. listening + * 5. message + * 6. online + * 7. setup + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "disconnect", listener: (worker: Worker) => void): this; + addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + addListener(event: "fork", listener: (worker: Worker) => void): this; + addListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + addListener( + event: "message", + listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void, + ): this; // the handle is a net.Socket or net.Server object, or undefined. + addListener(event: "online", listener: (worker: Worker) => void): this; + addListener(event: "setup", listener: (settings: ClusterSettings) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "disconnect", worker: Worker): boolean; + emit(event: "exit", worker: Worker, code: number, signal: string): boolean; + emit(event: "fork", worker: Worker): boolean; + emit(event: "listening", worker: Worker, address: Address): boolean; + emit(event: "message", worker: Worker, message: any, handle: net.Socket | net.Server): boolean; + emit(event: "online", worker: Worker): boolean; + emit(event: "setup", settings: ClusterSettings): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "disconnect", listener: (worker: Worker) => void): this; + on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + on(event: "fork", listener: (worker: Worker) => void): this; + on(event: "listening", listener: (worker: Worker, address: Address) => void): this; + on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + on(event: "online", listener: (worker: Worker) => void): this; + on(event: "setup", listener: (settings: ClusterSettings) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "disconnect", listener: (worker: Worker) => void): this; + once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + once(event: "fork", listener: (worker: Worker) => void): this; + once(event: "listening", listener: (worker: Worker, address: Address) => void): this; + once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + once(event: "online", listener: (worker: Worker) => void): this; + once(event: "setup", listener: (settings: ClusterSettings) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "disconnect", listener: (worker: Worker) => void): this; + prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + prependListener(event: "fork", listener: (worker: Worker) => void): this; + prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + // the handle is a net.Socket or net.Server object, or undefined. + prependListener( + event: "message", + listener: (worker: Worker, message: any, handle?: net.Socket | net.Server) => void, + ): this; + prependListener(event: "online", listener: (worker: Worker) => void): this; + prependListener(event: "setup", listener: (settings: ClusterSettings) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): this; + prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + prependOnceListener(event: "fork", listener: (worker: Worker) => void): this; + prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + // the handle is a net.Socket or net.Server object, or undefined. + prependOnceListener( + event: "message", + listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void, + ): this; + prependOnceListener(event: "online", listener: (worker: Worker) => void): this; + prependOnceListener(event: "setup", listener: (settings: ClusterSettings) => void): this; + } + const cluster: Cluster; + export default cluster; +} +declare module "node:cluster" { + export * from "cluster"; + export { default as default } from "cluster"; +} diff --git a/backend/node_modules/@types/node/console.d.ts b/backend/node_modules/@types/node/console.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6fd7a28fb46e204d60c1a69535b23c58f60b35d7 --- /dev/null +++ b/backend/node_modules/@types/node/console.d.ts @@ -0,0 +1,452 @@ +/** + * The `node:console` module provides a simple debugging console that is similar to + * the JavaScript console mechanism provided by web browsers. + * + * The module exports two specific components: + * + * * A `Console` class with methods such as `console.log()`, `console.error()`, and `console.warn()` that can be used to write to any Node.js stream. + * * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v18.x/api/process.html#processstdout) and + * [`process.stderr`](https://nodejs.org/docs/latest-v18.x/api/process.html#processstderr). The global `console` can be used without calling `require('node:console')`. + * + * _**Warning**_: The global console object's methods are neither consistently + * synchronous like the browser APIs they resemble, nor are they consistently + * asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v18.x/api/process.html#a-note-on-process-io) for + * more information. + * + * Example using the global `console`: + * + * ```js + * console.log('hello world'); + * // Prints: hello world, to stdout + * console.log('hello %s', 'world'); + * // Prints: hello world, to stdout + * console.error(new Error('Whoops, something bad happened')); + * // Prints error message and stack trace to stderr: + * // Error: Whoops, something bad happened + * // at [eval]:5:15 + * // at Script.runInThisContext (node:vm:132:18) + * // at Object.runInThisContext (node:vm:309:38) + * // at node:internal/process/execution:77:19 + * // at [eval]-wrapper:6:22 + * // at evalScript (node:internal/process/execution:76:60) + * // at node:internal/main/eval_string:23:3 + * + * const name = 'Will Robinson'; + * console.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to stderr + * ``` + * + * Example using the `Console` class: + * + * ```js + * const out = getStreamSomehow(); + * const err = getStreamSomehow(); + * const myConsole = new console.Console(out, err); + * + * myConsole.log('hello world'); + * // Prints: hello world, to out + * myConsole.log('hello %s', 'world'); + * // Prints: hello world, to out + * myConsole.error(new Error('Whoops, something bad happened')); + * // Prints: [Error: Whoops, something bad happened], to err + * + * const name = 'Will Robinson'; + * myConsole.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to err + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.20.1/lib/console.js) + */ +declare module "console" { + import console = require("node:console"); + export = console; +} +declare module "node:console" { + import { InspectOptions } from "node:util"; + global { + // This needs to be global to avoid TS2403 in case lib.dom.d.ts is present in the same build + interface Console { + Console: console.ConsoleConstructor; + /** + * `console.assert()` writes a message if `value` is [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) or omitted. It only + * writes a message and does not otherwise affect execution. The output always + * starts with `"Assertion failed"`. If provided, `message` is formatted using + * [`util.format()`](https://nodejs.org/docs/latest-v18.x/api/util.html#utilformatformat-args). + * + * If `value` is [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy), nothing happens. + * + * ```js + * console.assert(true, 'does nothing'); + * + * console.assert(false, 'Whoops %s work', 'didn\'t'); + * // Assertion failed: Whoops didn't work + * + * console.assert(); + * // Assertion failed + * ``` + * @since v0.1.101 + * @param value The value tested for being truthy. + * @param message All arguments besides `value` are used as error message. + */ + assert(value: any, message?: string, ...optionalParams: any[]): void; + /** + * When `stdout` is a TTY, calling `console.clear()` will attempt to clear the + * TTY. When `stdout` is not a TTY, this method does nothing. + * + * The specific operation of `console.clear()` can vary across operating systems + * and terminal types. For most Linux operating systems, `console.clear()` operates similarly to the `clear` shell command. On Windows, `console.clear()` will clear only the output in the + * current terminal viewport for the Node.js + * binary. + * @since v8.3.0 + */ + clear(): void; + /** + * Maintains an internal counter specific to `label` and outputs to `stdout` the + * number of times `console.count()` has been called with the given `label`. + * + * ```js + * > console.count() + * default: 1 + * undefined + * > console.count('default') + * default: 2 + * undefined + * > console.count('abc') + * abc: 1 + * undefined + * > console.count('xyz') + * xyz: 1 + * undefined + * > console.count('abc') + * abc: 2 + * undefined + * > console.count() + * default: 3 + * undefined + * > + * ``` + * @since v8.3.0 + * @param [label='default'] The display label for the counter. + */ + count(label?: string): void; + /** + * Resets the internal counter specific to `label`. + * + * ```js + * > console.count('abc'); + * abc: 1 + * undefined + * > console.countReset('abc'); + * undefined + * > console.count('abc'); + * abc: 1 + * undefined + * > + * ``` + * @since v8.3.0 + * @param [label='default'] The display label for the counter. + */ + countReset(label?: string): void; + /** + * The `console.debug()` function is an alias for {@link log}. + * @since v8.0.0 + */ + debug(message?: any, ...optionalParams: any[]): void; + /** + * Uses [`util.inspect()`](https://nodejs.org/docs/latest-v18.x/api/util.html#utilinspectobject-options) on `obj` and prints the resulting string to `stdout`. + * This function bypasses any custom `inspect()` function defined on `obj`. + * @since v0.1.101 + */ + dir(obj: any, options?: InspectOptions): void; + /** + * This method calls `console.log()` passing it the arguments received. + * This method does not produce any XML formatting. + * @since v8.0.0 + */ + dirxml(...data: any[]): void; + /** + * Prints to `stderr` with newline. Multiple arguments can be passed, with the + * first used as the primary message and all additional used as substitution + * values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) + * (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v18.x/api/util.html#utilformatformat-args)). + * + * ```js + * const code = 5; + * console.error('error #%d', code); + * // Prints: error #5, to stderr + * console.error('error', code); + * // Prints: error 5, to stderr + * ``` + * + * If formatting elements (e.g. `%d`) are not found in the first string then + * [`util.inspect()`](https://nodejs.org/docs/latest-v18.x/api/util.html#utilinspectobject-options) is called on each argument and the + * resulting string values are concatenated. See [`util.format()`](https://nodejs.org/docs/latest-v18.x/api/util.html#utilformatformat-args) + * for more information. + * @since v0.1.100 + */ + error(message?: any, ...optionalParams: any[]): void; + /** + * Increases indentation of subsequent lines by spaces for `groupIndentation` length. + * + * If one or more `label`s are provided, those are printed first without the + * additional indentation. + * @since v8.5.0 + */ + group(...label: any[]): void; + /** + * An alias for {@link group}. + * @since v8.5.0 + */ + groupCollapsed(...label: any[]): void; + /** + * Decreases indentation of subsequent lines by spaces for `groupIndentation` length. + * @since v8.5.0 + */ + groupEnd(): void; + /** + * The `console.info()` function is an alias for {@link log}. + * @since v0.1.100 + */ + info(message?: any, ...optionalParams: any[]): void; + /** + * Prints to `stdout` with newline. Multiple arguments can be passed, with the + * first used as the primary message and all additional used as substitution + * values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) + * (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v18.x/api/util.html#utilformatformat-args)). + * + * ```js + * const count = 5; + * console.log('count: %d', count); + * // Prints: count: 5, to stdout + * console.log('count:', count); + * // Prints: count: 5, to stdout + * ``` + * + * See [`util.format()`](https://nodejs.org/docs/latest-v18.x/api/util.html#utilformatformat-args) for more information. + * @since v0.1.100 + */ + log(message?: any, ...optionalParams: any[]): void; + /** + * Try to construct a table with the columns of the properties of `tabularData` (or use `properties`) and rows of `tabularData` and log it. Falls back to just + * logging the argument if it can't be parsed as tabular. + * + * ```js + * // These can't be parsed as tabular data + * console.table(Symbol()); + * // Symbol() + * + * console.table(undefined); + * // undefined + * + * console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }]); + * // ┌─────────┬─────┬─────┐ + * // │ (index) │ a │ b │ + * // ├─────────┼─────┼─────┤ + * // │ 0 │ 1 │ 'Y' │ + * // │ 1 │ 'Z' │ 2 │ + * // └─────────┴─────┴─────┘ + * + * console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }], ['a']); + * // ┌─────────┬─────┐ + * // │ (index) │ a │ + * // ├─────────┼─────┤ + * // │ 0 │ 1 │ + * // │ 1 │ 'Z' │ + * // └─────────┴─────┘ + * ``` + * @since v10.0.0 + * @param properties Alternate properties for constructing the table. + */ + table(tabularData: any, properties?: readonly string[]): void; + /** + * Starts a timer that can be used to compute the duration of an operation. Timers + * are identified by a unique `label`. Use the same `label` when calling {@link timeEnd} to stop the timer and output the elapsed time in + * suitable time units to `stdout`. For example, if the elapsed + * time is 3869ms, `console.timeEnd()` displays "3.869s". + * @since v0.1.104 + * @param [label='default'] + */ + time(label?: string): void; + /** + * Stops a timer that was previously started by calling {@link time} and + * prints the result to `stdout`: + * + * ```js + * console.time('bunch-of-stuff'); + * // Do a bunch of stuff. + * console.timeEnd('bunch-of-stuff'); + * // Prints: bunch-of-stuff: 225.438ms + * ``` + * @since v0.1.104 + * @param [label='default'] + */ + timeEnd(label?: string): void; + /** + * For a timer that was previously started by calling {@link time}, prints + * the elapsed time and other `data` arguments to `stdout`: + * + * ```js + * console.time('process'); + * const value = expensiveProcess1(); // Returns 42 + * console.timeLog('process', value); + * // Prints "process: 365.227ms 42". + * doExpensiveProcess2(value); + * console.timeEnd('process'); + * ``` + * @since v10.7.0 + * @param [label='default'] + */ + timeLog(label?: string, ...data: any[]): void; + /** + * Prints to `stderr` the string `'Trace: '`, followed by the [`util.format()`](https://nodejs.org/docs/latest-v18.x/api/util.html#utilformatformat-args) + * formatted message and stack trace to the current position in the code. + * + * ```js + * console.trace('Show me'); + * // Prints: (stack trace will vary based on where trace is called) + * // Trace: Show me + * // at repl:2:9 + * // at REPLServer.defaultEval (repl.js:248:27) + * // at bound (domain.js:287:14) + * // at REPLServer.runBound [as eval] (domain.js:300:12) + * // at REPLServer. (repl.js:412:12) + * // at emitOne (events.js:82:20) + * // at REPLServer.emit (events.js:169:7) + * // at REPLServer.Interface._onLine (readline.js:210:10) + * // at REPLServer.Interface._line (readline.js:549:8) + * // at REPLServer.Interface._ttyWrite (readline.js:826:14) + * ``` + * @since v0.1.104 + */ + trace(message?: any, ...optionalParams: any[]): void; + /** + * The `console.warn()` function is an alias for {@link error}. + * @since v0.1.100 + */ + warn(message?: any, ...optionalParams: any[]): void; + // --- Inspector mode only --- + /** + * This method does not display anything unless used in the inspector. The `console.profile()` + * method starts a JavaScript CPU profile with an optional label until {@link profileEnd} + * is called. The profile is then added to the Profile panel of the inspector. + * + * ```js + * console.profile('MyLabel'); + * // Some code + * console.profileEnd('MyLabel'); + * // Adds the profile 'MyLabel' to the Profiles panel of the inspector. + * ``` + * @since v8.0.0 + */ + profile(label?: string): void; + /** + * This method does not display anything unless used in the inspector. Stops the current + * JavaScript CPU profiling session if one has been started and prints the report to the + * Profiles panel of the inspector. See {@link profile} for an example. + * + * If this method is called without a label, the most recently started profile is stopped. + * @since v8.0.0 + */ + profileEnd(label?: string): void; + /** + * This method does not display anything unless used in the inspector. The `console.timeStamp()` + * method adds an event with the label `'label'` to the Timeline panel of the inspector. + * @since v8.0.0 + */ + timeStamp(label?: string): void; + } + /** + * The `console` module provides a simple debugging console that is similar to the + * JavaScript console mechanism provided by web browsers. + * + * The module exports two specific components: + * + * * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. + * * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v18.x/api/process.html#processstdout) and + * [`process.stderr`](https://nodejs.org/docs/latest-v18.x/api/process.html#processstderr). The global `console` can be used without calling `require('console')`. + * + * _**Warning**_: The global console object's methods are neither consistently + * synchronous like the browser APIs they resemble, nor are they consistently + * asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v18.x/api/process.html#a-note-on-process-io) for + * more information. + * + * Example using the global `console`: + * + * ```js + * console.log('hello world'); + * // Prints: hello world, to stdout + * console.log('hello %s', 'world'); + * // Prints: hello world, to stdout + * console.error(new Error('Whoops, something bad happened')); + * // Prints error message and stack trace to stderr: + * // Error: Whoops, something bad happened + * // at [eval]:5:15 + * // at Script.runInThisContext (node:vm:132:18) + * // at Object.runInThisContext (node:vm:309:38) + * // at node:internal/process/execution:77:19 + * // at [eval]-wrapper:6:22 + * // at evalScript (node:internal/process/execution:76:60) + * // at node:internal/main/eval_string:23:3 + * + * const name = 'Will Robinson'; + * console.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to stderr + * ``` + * + * Example using the `Console` class: + * + * ```js + * const out = getStreamSomehow(); + * const err = getStreamSomehow(); + * const myConsole = new console.Console(out, err); + * + * myConsole.log('hello world'); + * // Prints: hello world, to out + * myConsole.log('hello %s', 'world'); + * // Prints: hello world, to out + * myConsole.error(new Error('Whoops, something bad happened')); + * // Prints: [Error: Whoops, something bad happened], to err + * + * const name = 'Will Robinson'; + * myConsole.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to err + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.19.1/lib/console.js) + */ + namespace console { + interface ConsoleConstructorOptions { + stdout: NodeJS.WritableStream; + stderr?: NodeJS.WritableStream | undefined; + /** + * Ignore errors when writing to the underlying streams. + * @default true + */ + ignoreErrors?: boolean | undefined; + /** + * Set color support for this `Console` instance. Setting to true enables coloring while inspecting + * values. Setting to `false` disables coloring while inspecting values. Setting to `'auto'` makes color + * support depend on the value of the `isTTY` property and the value returned by `getColorDepth()` on the + * respective stream. This option can not be used, if `inspectOptions.colors` is set as well. + * @default auto + */ + colorMode?: boolean | "auto" | undefined; + /** + * Specifies options that are passed along to + * [`util.inspect()`](https://nodejs.org/docs/latest-v18.x/api/util.html#utilinspectobject-options). + */ + inspectOptions?: InspectOptions | undefined; + /** + * Set group indentation. + * @default 2 + */ + groupIndentation?: number | undefined; + } + interface ConsoleConstructor { + prototype: Console; + new(stdout: NodeJS.WritableStream, stderr?: NodeJS.WritableStream, ignoreErrors?: boolean): Console; + new(options: ConsoleConstructorOptions): Console; + } + } + var console: Console; + } + export = globalThis.console; +} diff --git a/backend/node_modules/@types/node/constants.d.ts b/backend/node_modules/@types/node/constants.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c3ac2b826436020bc945c03bb85c9a9479245f2f --- /dev/null +++ b/backend/node_modules/@types/node/constants.d.ts @@ -0,0 +1,19 @@ +/** @deprecated since v6.3.0 - use constants property exposed by the relevant module instead. */ +declare module "constants" { + import { constants as osConstants, SignalConstants } from "node:os"; + import { constants as cryptoConstants } from "node:crypto"; + import { constants as fsConstants } from "node:fs"; + + const exp: + & typeof osConstants.errno + & typeof osConstants.priority + & SignalConstants + & typeof cryptoConstants + & typeof fsConstants; + export = exp; +} + +declare module "node:constants" { + import constants = require("constants"); + export = constants; +} diff --git a/backend/node_modules/@types/node/crypto.d.ts b/backend/node_modules/@types/node/crypto.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d19f881c0234cfe2abdce1bbb698bb7c29b47e75 --- /dev/null +++ b/backend/node_modules/@types/node/crypto.d.ts @@ -0,0 +1,4457 @@ +/** + * The `crypto` module provides cryptographic functionality that includes a set of + * wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify functions. + * + * ```js + * const { createHmac } = await import('crypto'); + * + * const secret = 'abcdefg'; + * const hash = createHmac('sha256', secret) + * .update('I love cupcakes') + * .digest('hex'); + * console.log(hash); + * // Prints: + * // c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/crypto.js) + */ +declare module "crypto" { + import * as stream from "node:stream"; + import { PeerCertificate } from "node:tls"; + /** + * SPKAC is a Certificate Signing Request mechanism originally implemented by + * Netscape and was specified formally as part of [HTML5's `keygen` element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/keygen). + * + * `` is deprecated since [HTML 5.2](https://www.w3.org/TR/html52/changes.html#features-removed) and new projects + * should not use this element anymore. + * + * The `crypto` module provides the `Certificate` class for working with SPKAC + * data. The most common usage is handling output generated by the HTML5`` element. Node.js uses [OpenSSL's SPKAC + * implementation](https://www.openssl.org/docs/man1.1.0/apps/openssl-spkac.html) internally. + * @since v0.11.8 + */ + class Certificate { + /** + * ```js + * const { Certificate } = await import('crypto'); + * const spkac = getSpkacSomehow(); + * const challenge = Certificate.exportChallenge(spkac); + * console.log(challenge.toString('utf8')); + * // Prints: the challenge as a UTF8 string + * ``` + * @since v9.0.0 + * @param encoding The `encoding` of the `spkac` string. + * @return The challenge component of the `spkac` data structure, which includes a public key and a challenge. + */ + static exportChallenge(spkac: BinaryLike): Buffer; + /** + * ```js + * const { Certificate } = await import('crypto'); + * const spkac = getSpkacSomehow(); + * const publicKey = Certificate.exportPublicKey(spkac); + * console.log(publicKey); + * // Prints: the public key as + * ``` + * @since v9.0.0 + * @param encoding The `encoding` of the `spkac` string. + * @return The public key component of the `spkac` data structure, which includes a public key and a challenge. + */ + static exportPublicKey(spkac: BinaryLike, encoding?: string): Buffer; + /** + * ```js + * import { Buffer } from 'buffer'; + * const { Certificate } = await import('crypto'); + * + * const spkac = getSpkacSomehow(); + * console.log(Certificate.verifySpkac(Buffer.from(spkac))); + * // Prints: true or false + * ``` + * @since v9.0.0 + * @param encoding The `encoding` of the `spkac` string. + * @return `true` if the given `spkac` data structure is valid, `false` otherwise. + */ + static verifySpkac(spkac: NodeJS.ArrayBufferView): boolean; + /** + * @deprecated + * @param spkac + * @returns The challenge component of the `spkac` data structure, + * which includes a public key and a challenge. + */ + exportChallenge(spkac: BinaryLike): Buffer; + /** + * @deprecated + * @param spkac + * @param encoding The encoding of the spkac string. + * @returns The public key component of the `spkac` data structure, + * which includes a public key and a challenge. + */ + exportPublicKey(spkac: BinaryLike, encoding?: string): Buffer; + /** + * @deprecated + * @param spkac + * @returns `true` if the given `spkac` data structure is valid, + * `false` otherwise. + */ + verifySpkac(spkac: NodeJS.ArrayBufferView): boolean; + } + namespace constants { + // https://nodejs.org/dist/latest-v10.x/docs/api/crypto.html#crypto_crypto_constants + const OPENSSL_VERSION_NUMBER: number; + /** Applies multiple bug workarounds within OpenSSL. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html for detail. */ + const SSL_OP_ALL: number; + /** Allows legacy insecure renegotiation between OpenSSL and unpatched clients or servers. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */ + const SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number; + /** Attempts to use the server's preferences instead of the client's when selecting a cipher. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */ + const SSL_OP_CIPHER_SERVER_PREFERENCE: number; + /** Instructs OpenSSL to use Cisco's version identifier of DTLS_BAD_VER. */ + const SSL_OP_CISCO_ANYCONNECT: number; + /** Instructs OpenSSL to turn on cookie exchange. */ + const SSL_OP_COOKIE_EXCHANGE: number; + /** Instructs OpenSSL to add server-hello extension from an early version of the cryptopro draft. */ + const SSL_OP_CRYPTOPRO_TLSEXT_BUG: number; + /** Instructs OpenSSL to disable a SSL 3.0/TLS 1.0 vulnerability workaround added in OpenSSL 0.9.6d. */ + const SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number; + /** Instructs OpenSSL to always use the tmp_rsa key when performing RSA operations. */ + const SSL_OP_EPHEMERAL_RSA: number; + /** Allows initial connection to servers that do not support RI. */ + const SSL_OP_LEGACY_SERVER_CONNECT: number; + const SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: number; + const SSL_OP_MICROSOFT_SESS_ID_BUG: number; + /** Instructs OpenSSL to disable the workaround for a man-in-the-middle protocol-version vulnerability in the SSL 2.0 server implementation. */ + const SSL_OP_MSIE_SSLV2_RSA_PADDING: number; + const SSL_OP_NETSCAPE_CA_DN_BUG: number; + const SSL_OP_NETSCAPE_CHALLENGE_BUG: number; + const SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG: number; + const SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: number; + /** Instructs OpenSSL to disable support for SSL/TLS compression. */ + const SSL_OP_NO_COMPRESSION: number; + const SSL_OP_NO_QUERY_MTU: number; + /** Instructs OpenSSL to always start a new session when performing renegotiation. */ + const SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number; + const SSL_OP_NO_SSLv2: number; + const SSL_OP_NO_SSLv3: number; + const SSL_OP_NO_TICKET: number; + const SSL_OP_NO_TLSv1: number; + const SSL_OP_NO_TLSv1_1: number; + const SSL_OP_NO_TLSv1_2: number; + const SSL_OP_PKCS1_CHECK_1: number; + const SSL_OP_PKCS1_CHECK_2: number; + /** Instructs OpenSSL to always create a new key when using temporary/ephemeral DH parameters. */ + const SSL_OP_SINGLE_DH_USE: number; + /** Instructs OpenSSL to always create a new key when using temporary/ephemeral ECDH parameters. */ + const SSL_OP_SINGLE_ECDH_USE: number; + const SSL_OP_SSLEAY_080_CLIENT_DH_BUG: number; + const SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG: number; + const SSL_OP_TLS_BLOCK_PADDING_BUG: number; + const SSL_OP_TLS_D5_BUG: number; + /** Instructs OpenSSL to disable version rollback attack detection. */ + const SSL_OP_TLS_ROLLBACK_BUG: number; + const ENGINE_METHOD_RSA: number; + const ENGINE_METHOD_DSA: number; + const ENGINE_METHOD_DH: number; + const ENGINE_METHOD_RAND: number; + const ENGINE_METHOD_EC: number; + const ENGINE_METHOD_CIPHERS: number; + const ENGINE_METHOD_DIGESTS: number; + const ENGINE_METHOD_PKEY_METHS: number; + const ENGINE_METHOD_PKEY_ASN1_METHS: number; + const ENGINE_METHOD_ALL: number; + const ENGINE_METHOD_NONE: number; + const DH_CHECK_P_NOT_SAFE_PRIME: number; + const DH_CHECK_P_NOT_PRIME: number; + const DH_UNABLE_TO_CHECK_GENERATOR: number; + const DH_NOT_SUITABLE_GENERATOR: number; + const ALPN_ENABLED: number; + const RSA_PKCS1_PADDING: number; + const RSA_SSLV23_PADDING: number; + const RSA_NO_PADDING: number; + const RSA_PKCS1_OAEP_PADDING: number; + const RSA_X931_PADDING: number; + const RSA_PKCS1_PSS_PADDING: number; + /** Sets the salt length for RSA_PKCS1_PSS_PADDING to the digest size when signing or verifying. */ + const RSA_PSS_SALTLEN_DIGEST: number; + /** Sets the salt length for RSA_PKCS1_PSS_PADDING to the maximum permissible value when signing data. */ + const RSA_PSS_SALTLEN_MAX_SIGN: number; + /** Causes the salt length for RSA_PKCS1_PSS_PADDING to be determined automatically when verifying a signature. */ + const RSA_PSS_SALTLEN_AUTO: number; + const POINT_CONVERSION_COMPRESSED: number; + const POINT_CONVERSION_UNCOMPRESSED: number; + const POINT_CONVERSION_HYBRID: number; + /** Specifies the built-in default cipher list used by Node.js (colon-separated values). */ + const defaultCoreCipherList: string; + /** Specifies the active default cipher list used by the current Node.js process (colon-separated values). */ + const defaultCipherList: string; + } + interface HashOptions extends stream.TransformOptions { + /** + * For XOF hash functions such as `shake256`, the + * outputLength option can be used to specify the desired output length in bytes. + */ + outputLength?: number | undefined; + } + /** @deprecated since v10.0.0 */ + const fips: boolean; + /** + * Creates and returns a `Hash` object that can be used to generate hash digests + * using the given `algorithm`. Optional `options` argument controls stream + * behavior. For XOF hash functions such as `'shake256'`, the `outputLength` option + * can be used to specify the desired output length in bytes. + * + * The `algorithm` is dependent on the available algorithms supported by the + * version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc. + * On recent releases of OpenSSL, `openssl list -digest-algorithms` will + * display the available digest algorithms. + * + * Example: generating the sha256 sum of a file + * + * ```js + * import { + * createReadStream + * } from 'fs'; + * import { argv } from 'process'; + * const { + * createHash + * } = await import('crypto'); + * + * const filename = argv[2]; + * + * const hash = createHash('sha256'); + * + * const input = createReadStream(filename); + * input.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = input.read(); + * if (data) + * hash.update(data); + * else { + * console.log(`${hash.digest('hex')} ${filename}`); + * } + * }); + * ``` + * @since v0.1.92 + * @param options `stream.transform` options + */ + function createHash(algorithm: string, options?: HashOptions): Hash; + /** + * Creates and returns an `Hmac` object that uses the given `algorithm` and `key`. + * Optional `options` argument controls stream behavior. + * + * The `algorithm` is dependent on the available algorithms supported by the + * version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc. + * On recent releases of OpenSSL, `openssl list -digest-algorithms` will + * display the available digest algorithms. + * + * The `key` is the HMAC key used to generate the cryptographic HMAC hash. If it is + * a `KeyObject`, its type must be `secret`. + * + * Example: generating the sha256 HMAC of a file + * + * ```js + * import { + * createReadStream + * } from 'fs'; + * import { argv } from 'process'; + * const { + * createHmac + * } = await import('crypto'); + * + * const filename = argv[2]; + * + * const hmac = createHmac('sha256', 'a secret'); + * + * const input = createReadStream(filename); + * input.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = input.read(); + * if (data) + * hmac.update(data); + * else { + * console.log(`${hmac.digest('hex')} ${filename}`); + * } + * }); + * ``` + * @since v0.1.94 + * @param options `stream.transform` options + */ + function createHmac(algorithm: string, key: BinaryLike | KeyObject, options?: stream.TransformOptions): Hmac; + // https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings + type BinaryToTextEncoding = "base64" | "base64url" | "hex" | "binary"; + type CharacterEncoding = "utf8" | "utf-8" | "utf16le" | "latin1"; + type LegacyCharacterEncoding = "ascii" | "binary" | "ucs2" | "ucs-2"; + type Encoding = BinaryToTextEncoding | CharacterEncoding | LegacyCharacterEncoding; + type ECDHKeyFormat = "compressed" | "uncompressed" | "hybrid"; + /** + * The `Hash` class is a utility for creating hash digests of data. It can be + * used in one of two ways: + * + * * As a `stream` that is both readable and writable, where data is written + * to produce a computed hash digest on the readable side, or + * * Using the `hash.update()` and `hash.digest()` methods to produce the + * computed hash. + * + * The {@link createHash} method is used to create `Hash` instances. `Hash`objects are not to be created directly using the `new` keyword. + * + * Example: Using `Hash` objects as streams: + * + * ```js + * const { + * createHash + * } = await import('crypto'); + * + * const hash = createHash('sha256'); + * + * hash.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = hash.read(); + * if (data) { + * console.log(data.toString('hex')); + * // Prints: + * // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50 + * } + * }); + * + * hash.write('some data to hash'); + * hash.end(); + * ``` + * + * Example: Using `Hash` and piped streams: + * + * ```js + * import { createReadStream } from 'fs'; + * import { stdout } from 'process'; + * const { createHash } = await import('crypto'); + * + * const hash = createHash('sha256'); + * + * const input = createReadStream('test.js'); + * input.pipe(hash).setEncoding('hex').pipe(stdout); + * ``` + * + * Example: Using the `hash.update()` and `hash.digest()` methods: + * + * ```js + * const { + * createHash + * } = await import('crypto'); + * + * const hash = createHash('sha256'); + * + * hash.update('some data to hash'); + * console.log(hash.digest('hex')); + * // Prints: + * // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50 + * ``` + * @since v0.1.92 + */ + class Hash extends stream.Transform { + private constructor(); + /** + * Creates a new `Hash` object that contains a deep copy of the internal state + * of the current `Hash` object. + * + * The optional `options` argument controls stream behavior. For XOF hash + * functions such as `'shake256'`, the `outputLength` option can be used to + * specify the desired output length in bytes. + * + * An error is thrown when an attempt is made to copy the `Hash` object after + * its `hash.digest()` method has been called. + * + * ```js + * // Calculate a rolling hash. + * const { + * createHash + * } = await import('crypto'); + * + * const hash = createHash('sha256'); + * + * hash.update('one'); + * console.log(hash.copy().digest('hex')); + * + * hash.update('two'); + * console.log(hash.copy().digest('hex')); + * + * hash.update('three'); + * console.log(hash.copy().digest('hex')); + * + * // Etc. + * ``` + * @since v13.1.0 + * @param options `stream.transform` options + */ + copy(options?: stream.TransformOptions): Hash; + /** + * Updates the hash content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `encoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.92 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): Hash; + update(data: string, inputEncoding: Encoding): Hash; + /** + * Calculates the digest of all of the data passed to be hashed (using the `hash.update()` method). + * If `encoding` is provided a string will be returned; otherwise + * a `Buffer` is returned. + * + * The `Hash` object can not be used again after `hash.digest()` method has been + * called. Multiple calls will cause an error to be thrown. + * @since v0.1.92 + * @param encoding The `encoding` of the return value. + */ + digest(): Buffer; + digest(encoding: BinaryToTextEncoding): string; + } + /** + * The `Hmac` class is a utility for creating cryptographic HMAC digests. It can + * be used in one of two ways: + * + * * As a `stream` that is both readable and writable, where data is written + * to produce a computed HMAC digest on the readable side, or + * * Using the `hmac.update()` and `hmac.digest()` methods to produce the + * computed HMAC digest. + * + * The {@link createHmac} method is used to create `Hmac` instances. `Hmac`objects are not to be created directly using the `new` keyword. + * + * Example: Using `Hmac` objects as streams: + * + * ```js + * const { + * createHmac + * } = await import('crypto'); + * + * const hmac = createHmac('sha256', 'a secret'); + * + * hmac.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = hmac.read(); + * if (data) { + * console.log(data.toString('hex')); + * // Prints: + * // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e + * } + * }); + * + * hmac.write('some data to hash'); + * hmac.end(); + * ``` + * + * Example: Using `Hmac` and piped streams: + * + * ```js + * import { createReadStream } from 'fs'; + * import { stdout } from 'process'; + * const { + * createHmac + * } = await import('crypto'); + * + * const hmac = createHmac('sha256', 'a secret'); + * + * const input = createReadStream('test.js'); + * input.pipe(hmac).pipe(stdout); + * ``` + * + * Example: Using the `hmac.update()` and `hmac.digest()` methods: + * + * ```js + * const { + * createHmac + * } = await import('crypto'); + * + * const hmac = createHmac('sha256', 'a secret'); + * + * hmac.update('some data to hash'); + * console.log(hmac.digest('hex')); + * // Prints: + * // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e + * ``` + * @since v0.1.94 + */ + class Hmac extends stream.Transform { + private constructor(); + /** + * Updates the `Hmac` content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `encoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.94 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): Hmac; + update(data: string, inputEncoding: Encoding): Hmac; + /** + * Calculates the HMAC digest of all of the data passed using `hmac.update()`. + * If `encoding` is + * provided a string is returned; otherwise a `Buffer` is returned; + * + * The `Hmac` object can not be used again after `hmac.digest()` has been + * called. Multiple calls to `hmac.digest()` will result in an error being thrown. + * @since v0.1.94 + * @param encoding The `encoding` of the return value. + */ + digest(): Buffer; + digest(encoding: BinaryToTextEncoding): string; + } + type KeyObjectType = "secret" | "public" | "private"; + interface KeyExportOptions { + type: "pkcs1" | "spki" | "pkcs8" | "sec1"; + format: T; + cipher?: string | undefined; + passphrase?: string | Buffer | undefined; + } + interface JwkKeyExportOptions { + format: "jwk"; + } + interface JsonWebKey { + crv?: string | undefined; + d?: string | undefined; + dp?: string | undefined; + dq?: string | undefined; + e?: string | undefined; + k?: string | undefined; + kty?: string | undefined; + n?: string | undefined; + p?: string | undefined; + q?: string | undefined; + qi?: string | undefined; + x?: string | undefined; + y?: string | undefined; + [key: string]: unknown; + } + interface AsymmetricKeyDetails { + /** + * Key size in bits (RSA, DSA). + */ + modulusLength?: number | undefined; + /** + * Public exponent (RSA). + */ + publicExponent?: bigint | undefined; + /** + * Name of the message digest (RSA-PSS). + */ + hashAlgorithm?: string | undefined; + /** + * Name of the message digest used by MGF1 (RSA-PSS). + */ + mgf1HashAlgorithm?: string | undefined; + /** + * Minimal salt length in bytes (RSA-PSS). + */ + saltLength?: number | undefined; + /** + * Size of q in bits (DSA). + */ + divisorLength?: number | undefined; + /** + * Name of the curve (EC). + */ + namedCurve?: string | undefined; + } + /** + * Node.js uses a `KeyObject` class to represent a symmetric or asymmetric key, + * and each kind of key exposes different functions. The {@link createSecretKey}, {@link createPublicKey} and {@link createPrivateKey} methods are used to create `KeyObject`instances. `KeyObject` + * objects are not to be created directly using the `new`keyword. + * + * Most applications should consider using the new `KeyObject` API instead of + * passing keys as strings or `Buffer`s due to improved security features. + * + * `KeyObject` instances can be passed to other threads via `postMessage()`. + * The receiver obtains a cloned `KeyObject`, and the `KeyObject` does not need to + * be listed in the `transferList` argument. + * @since v11.6.0 + */ + class KeyObject { + private constructor(); + /** + * Example: Converting a `CryptoKey` instance to a `KeyObject`: + * + * ```js + * const { webcrypto, KeyObject } = await import('crypto'); + * const { subtle } = webcrypto; + * + * const key = await subtle.generateKey({ + * name: 'HMAC', + * hash: 'SHA-256', + * length: 256 + * }, true, ['sign', 'verify']); + * + * const keyObject = KeyObject.from(key); + * console.log(keyObject.symmetricKeySize); + * // Prints: 32 (symmetric key size in bytes) + * ``` + * @since v15.0.0 + */ + static from(key: webcrypto.CryptoKey): KeyObject; + /** + * For asymmetric keys, this property represents the type of the key. Supported key + * types are: + * + * * `'rsa'` (OID 1.2.840.113549.1.1.1) + * * `'rsa-pss'` (OID 1.2.840.113549.1.1.10) + * * `'dsa'` (OID 1.2.840.10040.4.1) + * * `'ec'` (OID 1.2.840.10045.2.1) + * * `'x25519'` (OID 1.3.101.110) + * * `'x448'` (OID 1.3.101.111) + * * `'ed25519'` (OID 1.3.101.112) + * * `'ed448'` (OID 1.3.101.113) + * * `'dh'` (OID 1.2.840.113549.1.3.1) + * + * This property is `undefined` for unrecognized `KeyObject` types and symmetric + * keys. + * @since v11.6.0 + */ + asymmetricKeyType?: KeyType | undefined; + /** + * For asymmetric keys, this property represents the size of the embedded key in + * bytes. This property is `undefined` for symmetric keys. + */ + asymmetricKeySize?: number | undefined; + /** + * This property exists only on asymmetric keys. Depending on the type of the key, + * this object contains information about the key. None of the information obtained + * through this property can be used to uniquely identify a key or to compromise + * the security of the key. + * + * For RSA-PSS keys, if the key material contains a `RSASSA-PSS-params` sequence, + * the `hashAlgorithm`, `mgf1HashAlgorithm`, and `saltLength` properties will be + * set. + * + * Other key details might be exposed via this API using additional attributes. + * @since v15.7.0 + */ + asymmetricKeyDetails?: AsymmetricKeyDetails | undefined; + /** + * For symmetric keys, the following encoding options can be used: + * + * For public keys, the following encoding options can be used: + * + * For private keys, the following encoding options can be used: + * + * The result type depends on the selected encoding format, when PEM the + * result is a string, when DER it will be a buffer containing the data + * encoded as DER, when [JWK](https://tools.ietf.org/html/rfc7517) it will be an object. + * + * When [JWK](https://tools.ietf.org/html/rfc7517) encoding format was selected, all other encoding options are + * ignored. + * + * PKCS#1, SEC1, and PKCS#8 type keys can be encrypted by using a combination of + * the `cipher` and `format` options. The PKCS#8 `type` can be used with any`format` to encrypt any key algorithm (RSA, EC, or DH) by specifying a`cipher`. PKCS#1 and SEC1 can only be + * encrypted by specifying a `cipher`when the PEM `format` is used. For maximum compatibility, use PKCS#8 for + * encrypted private keys. Since PKCS#8 defines its own + * encryption mechanism, PEM-level encryption is not supported when encrypting + * a PKCS#8 key. See [RFC 5208](https://www.rfc-editor.org/rfc/rfc5208.txt) for PKCS#8 encryption and [RFC 1421](https://www.rfc-editor.org/rfc/rfc1421.txt) for + * PKCS#1 and SEC1 encryption. + * @since v11.6.0 + */ + export(options: KeyExportOptions<"pem">): string | Buffer; + export(options?: KeyExportOptions<"der">): Buffer; + export(options?: JwkKeyExportOptions): JsonWebKey; + /** + * Returns `true` or `false` depending on whether the keys have exactly the same type, value, and parameters. + * This method is not [constant time](https://en.wikipedia.org/wiki/Timing_attack). + * @since v16.15.0 + */ + equals(otherKeyObject: KeyObject): boolean; + /** + * For secret keys, this property represents the size of the key in bytes. This + * property is `undefined` for asymmetric keys. + * @since v11.6.0 + */ + symmetricKeySize?: number | undefined; + /** + * Depending on the type of this `KeyObject`, this property is either`'secret'` for secret (symmetric) keys, `'public'` for public (asymmetric) keys + * or `'private'` for private (asymmetric) keys. + * @since v11.6.0 + */ + type: KeyObjectType; + } + type CipherCCMTypes = "aes-128-ccm" | "aes-192-ccm" | "aes-256-ccm" | "chacha20-poly1305"; + type CipherGCMTypes = "aes-128-gcm" | "aes-192-gcm" | "aes-256-gcm"; + type CipherOCBTypes = "aes-128-ocb" | "aes-192-ocb" | "aes-256-ocb"; + type BinaryLike = string | NodeJS.ArrayBufferView; + type CipherKey = BinaryLike | KeyObject; + interface CipherCCMOptions extends stream.TransformOptions { + authTagLength: number; + } + interface CipherGCMOptions extends stream.TransformOptions { + authTagLength?: number | undefined; + } + interface CipherOCBOptions extends stream.TransformOptions { + authTagLength: number; + } + /** + * Creates and returns a `Cipher` object that uses the given `algorithm` and`password`. + * + * The `options` argument controls stream behavior and is optional except when a + * cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the`authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength`option is not required but can be used to set the length of the authentication + * tag that will be returned by `getAuthTag()` and defaults to 16 bytes. + * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes. + * + * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On + * recent OpenSSL releases, `openssl list -cipher-algorithms` will + * display the available cipher algorithms. + * + * The `password` is used to derive the cipher key and initialization vector (IV). + * The value must be either a `'latin1'` encoded string, a `Buffer`, a`TypedArray`, or a `DataView`. + * + * The implementation of `crypto.createCipher()` derives keys using the OpenSSL + * function [`EVP_BytesToKey`](https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html) with the digest algorithm set to MD5, one + * iteration, and no salt. The lack of salt allows dictionary attacks as the same + * password always creates the same key. The low iteration count and + * non-cryptographically secure hash algorithm allow passwords to be tested very + * rapidly. + * + * In line with OpenSSL's recommendation to use a more modern algorithm instead of [`EVP_BytesToKey`](https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html) it is recommended that + * developers derive a key and IV on + * their own using {@link scrypt} and to use {@link createCipheriv} to create the `Cipher` object. Users should not use ciphers with counter mode + * (e.g. CTR, GCM, or CCM) in `crypto.createCipher()`. A warning is emitted when + * they are used in order to avoid the risk of IV reuse that causes + * vulnerabilities. For the case when IV is reused in GCM, see [Nonce-Disrespecting Adversaries](https://github.com/nonce-disrespect/nonce-disrespect) for details. + * @since v0.1.94 + * @deprecated Since v10.0.0 - Use {@link createCipheriv} instead. + * @param options `stream.transform` options + */ + function createCipher(algorithm: CipherCCMTypes, password: BinaryLike, options: CipherCCMOptions): CipherCCM; + /** @deprecated since v10.0.0 use `createCipheriv()` */ + function createCipher(algorithm: CipherGCMTypes, password: BinaryLike, options?: CipherGCMOptions): CipherGCM; + /** @deprecated since v10.0.0 use `createCipheriv()` */ + function createCipher(algorithm: string, password: BinaryLike, options?: stream.TransformOptions): Cipher; + /** + * Creates and returns a `Cipher` object, with the given `algorithm`, `key` and + * initialization vector (`iv`). + * + * The `options` argument controls stream behavior and is optional except when a + * cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the`authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength`option is not required but can be used to set the length of the authentication + * tag that will be returned by `getAuthTag()` and defaults to 16 bytes. + * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes. + * + * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On + * recent OpenSSL releases, `openssl list -cipher-algorithms` will + * display the available cipher algorithms. + * + * The `key` is the raw key used by the `algorithm` and `iv` is an [initialization vector](https://en.wikipedia.org/wiki/Initialization_vector). Both arguments must be `'utf8'` encoded + * strings,`Buffers`, `TypedArray`, or `DataView`s. The `key` may optionally be + * a `KeyObject` of type `secret`. If the cipher does not need + * an initialization vector, `iv` may be `null`. + * + * When passing strings for `key` or `iv`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * Initialization vectors should be unpredictable and unique; ideally, they will be + * cryptographically random. They do not have to be secret: IVs are typically just + * added to ciphertext messages unencrypted. It may sound contradictory that + * something has to be unpredictable and unique, but does not have to be secret; + * remember that an attacker must not be able to predict ahead of time what a + * given IV will be. + * @since v0.1.94 + * @param options `stream.transform` options + */ + function createCipheriv( + algorithm: CipherCCMTypes, + key: CipherKey, + iv: BinaryLike, + options: CipherCCMOptions, + ): CipherCCM; + function createCipheriv( + algorithm: CipherOCBTypes, + key: CipherKey, + iv: BinaryLike, + options: CipherOCBOptions, + ): CipherOCB; + function createCipheriv( + algorithm: CipherGCMTypes, + key: CipherKey, + iv: BinaryLike, + options?: CipherGCMOptions, + ): CipherGCM; + function createCipheriv( + algorithm: string, + key: CipherKey, + iv: BinaryLike | null, + options?: stream.TransformOptions, + ): Cipher; + /** + * Instances of the `Cipher` class are used to encrypt data. The class can be + * used in one of two ways: + * + * * As a `stream` that is both readable and writable, where plain unencrypted + * data is written to produce encrypted data on the readable side, or + * * Using the `cipher.update()` and `cipher.final()` methods to produce + * the encrypted data. + * + * The {@link createCipher} or {@link createCipheriv} methods are + * used to create `Cipher` instances. `Cipher` objects are not to be created + * directly using the `new` keyword. + * + * Example: Using `Cipher` objects as streams: + * + * ```js + * const { + * scrypt, + * randomFill, + * createCipheriv + * } = await import('crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * + * // First, we'll generate the key. The key length is dependent on the algorithm. + * // In this case for aes192, it is 24 bytes (192 bits). + * scrypt(password, 'salt', 24, (err, key) => { + * if (err) throw err; + * // Then, we'll generate a random initialization vector + * randomFill(new Uint8Array(16), (err, iv) => { + * if (err) throw err; + * + * // Once we have the key and iv, we can create and use the cipher... + * const cipher = createCipheriv(algorithm, key, iv); + * + * let encrypted = ''; + * cipher.setEncoding('hex'); + * + * cipher.on('data', (chunk) => encrypted += chunk); + * cipher.on('end', () => console.log(encrypted)); + * + * cipher.write('some clear text data'); + * cipher.end(); + * }); + * }); + * ``` + * + * Example: Using `Cipher` and piped streams: + * + * ```js + * import { + * createReadStream, + * createWriteStream, + * } from 'fs'; + * + * import { + * pipeline + * } from 'stream'; + * + * const { + * scrypt, + * randomFill, + * createCipheriv + * } = await import('crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * + * // First, we'll generate the key. The key length is dependent on the algorithm. + * // In this case for aes192, it is 24 bytes (192 bits). + * scrypt(password, 'salt', 24, (err, key) => { + * if (err) throw err; + * // Then, we'll generate a random initialization vector + * randomFill(new Uint8Array(16), (err, iv) => { + * if (err) throw err; + * + * const cipher = createCipheriv(algorithm, key, iv); + * + * const input = createReadStream('test.js'); + * const output = createWriteStream('test.enc'); + * + * pipeline(input, cipher, output, (err) => { + * if (err) throw err; + * }); + * }); + * }); + * ``` + * + * Example: Using the `cipher.update()` and `cipher.final()` methods: + * + * ```js + * const { + * scrypt, + * randomFill, + * createCipheriv + * } = await import('crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * + * // First, we'll generate the key. The key length is dependent on the algorithm. + * // In this case for aes192, it is 24 bytes (192 bits). + * scrypt(password, 'salt', 24, (err, key) => { + * if (err) throw err; + * // Then, we'll generate a random initialization vector + * randomFill(new Uint8Array(16), (err, iv) => { + * if (err) throw err; + * + * const cipher = createCipheriv(algorithm, key, iv); + * + * let encrypted = cipher.update('some clear text data', 'utf8', 'hex'); + * encrypted += cipher.final('hex'); + * console.log(encrypted); + * }); + * }); + * ``` + * @since v0.1.94 + */ + class Cipher extends stream.Transform { + private constructor(); + /** + * Updates the cipher with `data`. If the `inputEncoding` argument is given, + * the `data`argument is a string using the specified encoding. If the `inputEncoding`argument is not given, `data` must be a `Buffer`, `TypedArray`, or`DataView`. If `data` is a `Buffer`, + * `TypedArray`, or `DataView`, then`inputEncoding` is ignored. + * + * The `outputEncoding` specifies the output format of the enciphered + * data. If the `outputEncoding`is specified, a string using the specified encoding is returned. If no`outputEncoding` is provided, a `Buffer` is returned. + * + * The `cipher.update()` method can be called multiple times with new data until `cipher.final()` is called. Calling `cipher.update()` after `cipher.final()` will result in an error being + * thrown. + * @since v0.1.94 + * @param inputEncoding The `encoding` of the data. + * @param outputEncoding The `encoding` of the return value. + */ + update(data: BinaryLike): Buffer; + update(data: string, inputEncoding: Encoding): Buffer; + update(data: NodeJS.ArrayBufferView, inputEncoding: undefined, outputEncoding: Encoding): string; + update(data: string, inputEncoding: Encoding | undefined, outputEncoding: Encoding): string; + /** + * Once the `cipher.final()` method has been called, the `Cipher` object can no + * longer be used to encrypt data. Attempts to call `cipher.final()` more than + * once will result in an error being thrown. + * @since v0.1.94 + * @param outputEncoding The `encoding` of the return value. + * @return Any remaining enciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a {@link Buffer} is returned. + */ + final(): Buffer; + final(outputEncoding: BufferEncoding): string; + /** + * When using block encryption algorithms, the `Cipher` class will automatically + * add padding to the input data to the appropriate block size. To disable the + * default padding call `cipher.setAutoPadding(false)`. + * + * When `autoPadding` is `false`, the length of the entire input data must be a + * multiple of the cipher's block size or `cipher.final()` will throw an error. + * Disabling automatic padding is useful for non-standard padding, for instance + * using `0x0` instead of PKCS padding. + * + * The `cipher.setAutoPadding()` method must be called before `cipher.final()`. + * @since v0.7.1 + * @param [autoPadding=true] + * @return for method chaining. + */ + setAutoPadding(autoPadding?: boolean): this; + } + interface CipherCCM extends Cipher { + setAAD( + buffer: NodeJS.ArrayBufferView, + options: { + plaintextLength: number; + }, + ): this; + getAuthTag(): Buffer; + } + interface CipherGCM extends Cipher { + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + }, + ): this; + getAuthTag(): Buffer; + } + interface CipherOCB extends Cipher { + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + }, + ): this; + getAuthTag(): Buffer; + } + /** + * Creates and returns a `Decipher` object that uses the given `algorithm` and`password` (key). + * + * The `options` argument controls stream behavior and is optional except when a + * cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the`authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. + * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes. + * + * The implementation of `crypto.createDecipher()` derives keys using the OpenSSL + * function [`EVP_BytesToKey`](https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html) with the digest algorithm set to MD5, one + * iteration, and no salt. The lack of salt allows dictionary attacks as the same + * password always creates the same key. The low iteration count and + * non-cryptographically secure hash algorithm allow passwords to be tested very + * rapidly. + * + * In line with OpenSSL's recommendation to use a more modern algorithm instead of [`EVP_BytesToKey`](https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html) it is recommended that + * developers derive a key and IV on + * their own using {@link scrypt} and to use {@link createDecipheriv} to create the `Decipher` object. + * @since v0.1.94 + * @deprecated Since v10.0.0 - Use {@link createDecipheriv} instead. + * @param options `stream.transform` options + */ + function createDecipher(algorithm: CipherCCMTypes, password: BinaryLike, options: CipherCCMOptions): DecipherCCM; + /** @deprecated since v10.0.0 use `createDecipheriv()` */ + function createDecipher(algorithm: CipherGCMTypes, password: BinaryLike, options?: CipherGCMOptions): DecipherGCM; + /** @deprecated since v10.0.0 use `createDecipheriv()` */ + function createDecipher(algorithm: string, password: BinaryLike, options?: stream.TransformOptions): Decipher; + /** + * Creates and returns a `Decipher` object that uses the given `algorithm`, `key`and initialization vector (`iv`). + * + * The `options` argument controls stream behavior and is optional except when a + * cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the`authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength`option is not required but can be used to restrict accepted authentication tags + * to those with the specified length. + * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes. + * + * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On + * recent OpenSSL releases, `openssl list -cipher-algorithms` will + * display the available cipher algorithms. + * + * The `key` is the raw key used by the `algorithm` and `iv` is an [initialization vector](https://en.wikipedia.org/wiki/Initialization_vector). Both arguments must be `'utf8'` encoded + * strings,`Buffers`, `TypedArray`, or `DataView`s. The `key` may optionally be + * a `KeyObject` of type `secret`. If the cipher does not need + * an initialization vector, `iv` may be `null`. + * + * When passing strings for `key` or `iv`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * Initialization vectors should be unpredictable and unique; ideally, they will be + * cryptographically random. They do not have to be secret: IVs are typically just + * added to ciphertext messages unencrypted. It may sound contradictory that + * something has to be unpredictable and unique, but does not have to be secret; + * remember that an attacker must not be able to predict ahead of time what a given + * IV will be. + * @since v0.1.94 + * @param options `stream.transform` options + */ + function createDecipheriv( + algorithm: CipherCCMTypes, + key: CipherKey, + iv: BinaryLike, + options: CipherCCMOptions, + ): DecipherCCM; + function createDecipheriv( + algorithm: CipherOCBTypes, + key: CipherKey, + iv: BinaryLike, + options: CipherOCBOptions, + ): DecipherOCB; + function createDecipheriv( + algorithm: CipherGCMTypes, + key: CipherKey, + iv: BinaryLike, + options?: CipherGCMOptions, + ): DecipherGCM; + function createDecipheriv( + algorithm: string, + key: CipherKey, + iv: BinaryLike | null, + options?: stream.TransformOptions, + ): Decipher; + /** + * Instances of the `Decipher` class are used to decrypt data. The class can be + * used in one of two ways: + * + * * As a `stream` that is both readable and writable, where plain encrypted + * data is written to produce unencrypted data on the readable side, or + * * Using the `decipher.update()` and `decipher.final()` methods to + * produce the unencrypted data. + * + * The {@link createDecipher} or {@link createDecipheriv} methods are + * used to create `Decipher` instances. `Decipher` objects are not to be created + * directly using the `new` keyword. + * + * Example: Using `Decipher` objects as streams: + * + * ```js + * import { Buffer } from 'buffer'; + * const { + * scryptSync, + * createDecipheriv + * } = await import('crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * // Key length is dependent on the algorithm. In this case for aes192, it is + * // 24 bytes (192 bits). + * // Use the async `crypto.scrypt()` instead. + * const key = scryptSync(password, 'salt', 24); + * // The IV is usually passed along with the ciphertext. + * const iv = Buffer.alloc(16, 0); // Initialization vector. + * + * const decipher = createDecipheriv(algorithm, key, iv); + * + * let decrypted = ''; + * decipher.on('readable', () => { + * while (null !== (chunk = decipher.read())) { + * decrypted += chunk.toString('utf8'); + * } + * }); + * decipher.on('end', () => { + * console.log(decrypted); + * // Prints: some clear text data + * }); + * + * // Encrypted with same algorithm, key and iv. + * const encrypted = + * 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa'; + * decipher.write(encrypted, 'hex'); + * decipher.end(); + * ``` + * + * Example: Using `Decipher` and piped streams: + * + * ```js + * import { + * createReadStream, + * createWriteStream, + * } from 'fs'; + * import { Buffer } from 'buffer'; + * const { + * scryptSync, + * createDecipheriv + * } = await import('crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * // Use the async `crypto.scrypt()` instead. + * const key = scryptSync(password, 'salt', 24); + * // The IV is usually passed along with the ciphertext. + * const iv = Buffer.alloc(16, 0); // Initialization vector. + * + * const decipher = createDecipheriv(algorithm, key, iv); + * + * const input = createReadStream('test.enc'); + * const output = createWriteStream('test.js'); + * + * input.pipe(decipher).pipe(output); + * ``` + * + * Example: Using the `decipher.update()` and `decipher.final()` methods: + * + * ```js + * import { Buffer } from 'buffer'; + * const { + * scryptSync, + * createDecipheriv + * } = await import('crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * // Use the async `crypto.scrypt()` instead. + * const key = scryptSync(password, 'salt', 24); + * // The IV is usually passed along with the ciphertext. + * const iv = Buffer.alloc(16, 0); // Initialization vector. + * + * const decipher = createDecipheriv(algorithm, key, iv); + * + * // Encrypted using same algorithm, key and iv. + * const encrypted = + * 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa'; + * let decrypted = decipher.update(encrypted, 'hex', 'utf8'); + * decrypted += decipher.final('utf8'); + * console.log(decrypted); + * // Prints: some clear text data + * ``` + * @since v0.1.94 + */ + class Decipher extends stream.Transform { + private constructor(); + /** + * Updates the decipher with `data`. If the `inputEncoding` argument is given, + * the `data`argument is a string using the specified encoding. If the `inputEncoding`argument is not given, `data` must be a `Buffer`. If `data` is a `Buffer` then `inputEncoding` is + * ignored. + * + * The `outputEncoding` specifies the output format of the enciphered + * data. If the `outputEncoding`is specified, a string using the specified encoding is returned. If no`outputEncoding` is provided, a `Buffer` is returned. + * + * The `decipher.update()` method can be called multiple times with new data until `decipher.final()` is called. Calling `decipher.update()` after `decipher.final()` will result in an error + * being thrown. + * @since v0.1.94 + * @param inputEncoding The `encoding` of the `data` string. + * @param outputEncoding The `encoding` of the return value. + */ + update(data: NodeJS.ArrayBufferView): Buffer; + update(data: string, inputEncoding: Encoding): Buffer; + update(data: NodeJS.ArrayBufferView, inputEncoding: undefined, outputEncoding: Encoding): string; + update(data: string, inputEncoding: Encoding | undefined, outputEncoding: Encoding): string; + /** + * Once the `decipher.final()` method has been called, the `Decipher` object can + * no longer be used to decrypt data. Attempts to call `decipher.final()` more + * than once will result in an error being thrown. + * @since v0.1.94 + * @param outputEncoding The `encoding` of the return value. + * @return Any remaining deciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a {@link Buffer} is returned. + */ + final(): Buffer; + final(outputEncoding: BufferEncoding): string; + /** + * When data has been encrypted without standard block padding, calling`decipher.setAutoPadding(false)` will disable automatic padding to prevent `decipher.final()` from checking for and + * removing padding. + * + * Turning auto padding off will only work if the input data's length is a + * multiple of the ciphers block size. + * + * The `decipher.setAutoPadding()` method must be called before `decipher.final()`. + * @since v0.7.1 + * @param [autoPadding=true] + * @return for method chaining. + */ + setAutoPadding(auto_padding?: boolean): this; + } + interface DecipherCCM extends Decipher { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options: { + plaintextLength: number; + }, + ): this; + } + interface DecipherGCM extends Decipher { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + }, + ): this; + } + interface DecipherOCB extends Decipher { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + }, + ): this; + } + interface PrivateKeyInput { + key: string | Buffer; + format?: KeyFormat | undefined; + type?: "pkcs1" | "pkcs8" | "sec1" | undefined; + passphrase?: string | Buffer | undefined; + encoding?: string | undefined; + } + interface PublicKeyInput { + key: string | Buffer; + format?: KeyFormat | undefined; + type?: "pkcs1" | "spki" | undefined; + encoding?: string | undefined; + } + /** + * Asynchronously generates a new random secret key of the given `length`. The`type` will determine which validations will be performed on the `length`. + * + * ```js + * const { + * generateKey + * } = await import('crypto'); + * + * generateKey('hmac', { length: 64 }, (err, key) => { + * if (err) throw err; + * console.log(key.export().toString('hex')); // 46e..........620 + * }); + * ``` + * @since v15.0.0 + * @param type The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`. + */ + function generateKey( + type: "hmac" | "aes", + options: { + length: number; + }, + callback: (err: Error | null, key: KeyObject) => void, + ): void; + /** + * Synchronously generates a new random secret key of the given `length`. The`type` will determine which validations will be performed on the `length`. + * + * ```js + * const { + * generateKeySync + * } = await import('crypto'); + * + * const key = generateKeySync('hmac', { length: 64 }); + * console.log(key.export().toString('hex')); // e89..........41e + * ``` + * @since v15.0.0 + * @param type The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`. + */ + function generateKeySync( + type: "hmac" | "aes", + options: { + length: number; + }, + ): KeyObject; + interface JsonWebKeyInput { + key: JsonWebKey; + format: "jwk"; + } + /** + * Creates and returns a new key object containing a private key. If `key` is a + * string or `Buffer`, `format` is assumed to be `'pem'`; otherwise, `key`must be an object with the properties described above. + * + * If the private key is encrypted, a `passphrase` must be specified. The length + * of the passphrase is limited to 1024 bytes. + * @since v11.6.0 + */ + function createPrivateKey(key: PrivateKeyInput | string | Buffer | JsonWebKeyInput): KeyObject; + /** + * Creates and returns a new key object containing a public key. If `key` is a + * string or `Buffer`, `format` is assumed to be `'pem'`; if `key` is a `KeyObject`with type `'private'`, the public key is derived from the given private key; + * otherwise, `key` must be an object with the properties described above. + * + * If the format is `'pem'`, the `'key'` may also be an X.509 certificate. + * + * Because public keys can be derived from private keys, a private key may be + * passed instead of a public key. In that case, this function behaves as if {@link createPrivateKey} had been called, except that the type of the + * returned `KeyObject` will be `'public'` and that the private key cannot be + * extracted from the returned `KeyObject`. Similarly, if a `KeyObject` with type`'private'` is given, a new `KeyObject` with type `'public'` will be returned + * and it will be impossible to extract the private key from the returned object. + * @since v11.6.0 + */ + function createPublicKey(key: PublicKeyInput | string | Buffer | KeyObject | JsonWebKeyInput): KeyObject; + /** + * Creates and returns a new key object containing a secret key for symmetric + * encryption or `Hmac`. + * @since v11.6.0 + * @param encoding The string encoding when `key` is a string. + */ + function createSecretKey(key: NodeJS.ArrayBufferView): KeyObject; + function createSecretKey(key: string, encoding: BufferEncoding): KeyObject; + /** + * Creates and returns a `Sign` object that uses the given `algorithm`. Use {@link getHashes} to obtain the names of the available digest algorithms. + * Optional `options` argument controls the `stream.Writable` behavior. + * + * In some cases, a `Sign` instance can be created using the name of a signature + * algorithm, such as `'RSA-SHA256'`, instead of a digest algorithm. This will use + * the corresponding digest algorithm. This does not work for all signature + * algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest + * algorithm names. + * @since v0.1.92 + * @param options `stream.Writable` options + */ + function createSign(algorithm: string, options?: stream.WritableOptions): Sign; + type DSAEncoding = "der" | "ieee-p1363"; + interface SigningOptions { + /** + * @see crypto.constants.RSA_PKCS1_PADDING + */ + padding?: number | undefined; + saltLength?: number | undefined; + dsaEncoding?: DSAEncoding | undefined; + } + interface SignPrivateKeyInput extends PrivateKeyInput, SigningOptions {} + interface SignKeyObjectInput extends SigningOptions { + key: KeyObject; + } + interface VerifyPublicKeyInput extends PublicKeyInput, SigningOptions {} + interface VerifyKeyObjectInput extends SigningOptions { + key: KeyObject; + } + interface VerifyJsonWebKeyInput extends JsonWebKeyInput, SigningOptions {} + type KeyLike = string | Buffer | KeyObject; + /** + * The `Sign` class is a utility for generating signatures. It can be used in one + * of two ways: + * + * * As a writable `stream`, where data to be signed is written and the `sign.sign()` method is used to generate and return the signature, or + * * Using the `sign.update()` and `sign.sign()` methods to produce the + * signature. + * + * The {@link createSign} method is used to create `Sign` instances. The + * argument is the string name of the hash function to use. `Sign` objects are not + * to be created directly using the `new` keyword. + * + * Example: Using `Sign` and `Verify` objects as streams: + * + * ```js + * const { + * generateKeyPairSync, + * createSign, + * createVerify + * } = await import('crypto'); + * + * const { privateKey, publicKey } = generateKeyPairSync('ec', { + * namedCurve: 'sect239k1' + * }); + * + * const sign = createSign('SHA256'); + * sign.write('some data to sign'); + * sign.end(); + * const signature = sign.sign(privateKey, 'hex'); + * + * const verify = createVerify('SHA256'); + * verify.write('some data to sign'); + * verify.end(); + * console.log(verify.verify(publicKey, signature, 'hex')); + * // Prints: true + * ``` + * + * Example: Using the `sign.update()` and `verify.update()` methods: + * + * ```js + * const { + * generateKeyPairSync, + * createSign, + * createVerify + * } = await import('crypto'); + * + * const { privateKey, publicKey } = generateKeyPairSync('rsa', { + * modulusLength: 2048, + * }); + * + * const sign = createSign('SHA256'); + * sign.update('some data to sign'); + * sign.end(); + * const signature = sign.sign(privateKey); + * + * const verify = createVerify('SHA256'); + * verify.update('some data to sign'); + * verify.end(); + * console.log(verify.verify(publicKey, signature)); + * // Prints: true + * ``` + * @since v0.1.92 + */ + class Sign extends stream.Writable { + private constructor(); + /** + * Updates the `Sign` content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `encoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.92 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): this; + update(data: string, inputEncoding: Encoding): this; + /** + * Calculates the signature on all the data passed through using either `sign.update()` or `sign.write()`. + * + * If `privateKey` is not a `KeyObject`, this function behaves as if`privateKey` had been passed to {@link createPrivateKey}. If it is an + * object, the following additional properties can be passed: + * + * If `outputEncoding` is provided a string is returned; otherwise a `Buffer` is returned. + * + * The `Sign` object can not be again used after `sign.sign()` method has been + * called. Multiple calls to `sign.sign()` will result in an error being thrown. + * @since v0.1.92 + */ + sign(privateKey: KeyLike | SignKeyObjectInput | SignPrivateKeyInput): Buffer; + sign( + privateKey: KeyLike | SignKeyObjectInput | SignPrivateKeyInput, + outputFormat: BinaryToTextEncoding, + ): string; + } + /** + * Creates and returns a `Verify` object that uses the given algorithm. + * Use {@link getHashes} to obtain an array of names of the available + * signing algorithms. Optional `options` argument controls the`stream.Writable` behavior. + * + * In some cases, a `Verify` instance can be created using the name of a signature + * algorithm, such as `'RSA-SHA256'`, instead of a digest algorithm. This will use + * the corresponding digest algorithm. This does not work for all signature + * algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest + * algorithm names. + * @since v0.1.92 + * @param options `stream.Writable` options + */ + function createVerify(algorithm: string, options?: stream.WritableOptions): Verify; + /** + * The `Verify` class is a utility for verifying signatures. It can be used in one + * of two ways: + * + * * As a writable `stream` where written data is used to validate against the + * supplied signature, or + * * Using the `verify.update()` and `verify.verify()` methods to verify + * the signature. + * + * The {@link createVerify} method is used to create `Verify` instances.`Verify` objects are not to be created directly using the `new` keyword. + * + * See `Sign` for examples. + * @since v0.1.92 + */ + class Verify extends stream.Writable { + private constructor(); + /** + * Updates the `Verify` content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `inputEncoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.92 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): Verify; + update(data: string, inputEncoding: Encoding): Verify; + /** + * Verifies the provided data using the given `object` and `signature`. + * + * If `object` is not a `KeyObject`, this function behaves as if`object` had been passed to {@link createPublicKey}. If it is an + * object, the following additional properties can be passed: + * + * The `signature` argument is the previously calculated signature for the data, in + * the `signatureEncoding`. + * If a `signatureEncoding` is specified, the `signature` is expected to be a + * string; otherwise `signature` is expected to be a `Buffer`,`TypedArray`, or `DataView`. + * + * The `verify` object can not be used again after `verify.verify()` has been + * called. Multiple calls to `verify.verify()` will result in an error being + * thrown. + * + * Because public keys can be derived from private keys, a private key may + * be passed instead of a public key. + * @since v0.1.92 + */ + verify( + object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, + signature: NodeJS.ArrayBufferView, + ): boolean; + verify( + object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, + signature: string, + signature_format?: BinaryToTextEncoding, + ): boolean; + } + /** + * Creates a `DiffieHellman` key exchange object using the supplied `prime` and an + * optional specific `generator`. + * + * The `generator` argument can be a number, string, or `Buffer`. If`generator` is not specified, the value `2` is used. + * + * If `primeEncoding` is specified, `prime` is expected to be a string; otherwise + * a `Buffer`, `TypedArray`, or `DataView` is expected. + * + * If `generatorEncoding` is specified, `generator` is expected to be a string; + * otherwise a number, `Buffer`, `TypedArray`, or `DataView` is expected. + * @since v0.11.12 + * @param primeEncoding The `encoding` of the `prime` string. + * @param [generator=2] + * @param generatorEncoding The `encoding` of the `generator` string. + */ + function createDiffieHellman(primeLength: number, generator?: number): DiffieHellman; + function createDiffieHellman( + prime: ArrayBuffer | NodeJS.ArrayBufferView, + generator?: number | ArrayBuffer | NodeJS.ArrayBufferView, + ): DiffieHellman; + function createDiffieHellman( + prime: ArrayBuffer | NodeJS.ArrayBufferView, + generator: string, + generatorEncoding: BinaryToTextEncoding, + ): DiffieHellman; + function createDiffieHellman( + prime: string, + primeEncoding: BinaryToTextEncoding, + generator?: number | ArrayBuffer | NodeJS.ArrayBufferView, + ): DiffieHellman; + function createDiffieHellman( + prime: string, + primeEncoding: BinaryToTextEncoding, + generator: string, + generatorEncoding: BinaryToTextEncoding, + ): DiffieHellman; + /** + * The `DiffieHellman` class is a utility for creating Diffie-Hellman key + * exchanges. + * + * Instances of the `DiffieHellman` class can be created using the {@link createDiffieHellman} function. + * + * ```js + * import assert from 'assert'; + * + * const { + * createDiffieHellman + * } = await import('crypto'); + * + * // Generate Alice's keys... + * const alice = createDiffieHellman(2048); + * const aliceKey = alice.generateKeys(); + * + * // Generate Bob's keys... + * const bob = createDiffieHellman(alice.getPrime(), alice.getGenerator()); + * const bobKey = bob.generateKeys(); + * + * // Exchange and generate the secret... + * const aliceSecret = alice.computeSecret(bobKey); + * const bobSecret = bob.computeSecret(aliceKey); + * + * // OK + * assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); + * ``` + * @since v0.5.0 + */ + class DiffieHellman { + private constructor(); + /** + * Generates private and public Diffie-Hellman key values, and returns + * the public key in the specified `encoding`. This key should be + * transferred to the other party. + * If `encoding` is provided a string is returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + generateKeys(): Buffer; + generateKeys(encoding: BinaryToTextEncoding): string; + /** + * Computes the shared secret using `otherPublicKey` as the other + * party's public key and returns the computed shared secret. The supplied + * key is interpreted using the specified `inputEncoding`, and secret is + * encoded using specified `outputEncoding`. + * If the `inputEncoding` is not + * provided, `otherPublicKey` is expected to be a `Buffer`,`TypedArray`, or `DataView`. + * + * If `outputEncoding` is given a string is returned; otherwise, a `Buffer` is returned. + * @since v0.5.0 + * @param inputEncoding The `encoding` of an `otherPublicKey` string. + * @param outputEncoding The `encoding` of the return value. + */ + computeSecret(otherPublicKey: NodeJS.ArrayBufferView, inputEncoding?: null, outputEncoding?: null): Buffer; + computeSecret(otherPublicKey: string, inputEncoding: BinaryToTextEncoding, outputEncoding?: null): Buffer; + computeSecret( + otherPublicKey: NodeJS.ArrayBufferView, + inputEncoding: null, + outputEncoding: BinaryToTextEncoding, + ): string; + computeSecret( + otherPublicKey: string, + inputEncoding: BinaryToTextEncoding, + outputEncoding: BinaryToTextEncoding, + ): string; + /** + * Returns the Diffie-Hellman prime in the specified `encoding`. + * If `encoding` is provided a string is + * returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getPrime(): Buffer; + getPrime(encoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman generator in the specified `encoding`. + * If `encoding` is provided a string is + * returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getGenerator(): Buffer; + getGenerator(encoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman public key in the specified `encoding`. + * If `encoding` is provided a + * string is returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getPublicKey(): Buffer; + getPublicKey(encoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman private key in the specified `encoding`. + * If `encoding` is provided a + * string is returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getPrivateKey(): Buffer; + getPrivateKey(encoding: BinaryToTextEncoding): string; + /** + * Sets the Diffie-Hellman public key. If the `encoding` argument is provided,`publicKey` is expected + * to be a string. If no `encoding` is provided, `publicKey` is expected + * to be a `Buffer`, `TypedArray`, or `DataView`. + * @since v0.5.0 + * @param encoding The `encoding` of the `publicKey` string. + */ + setPublicKey(publicKey: NodeJS.ArrayBufferView): void; + setPublicKey(publicKey: string, encoding: BufferEncoding): void; + /** + * Sets the Diffie-Hellman private key. If the `encoding` argument is provided,`privateKey` is expected + * to be a string. If no `encoding` is provided, `privateKey` is expected + * to be a `Buffer`, `TypedArray`, or `DataView`. + * @since v0.5.0 + * @param encoding The `encoding` of the `privateKey` string. + */ + setPrivateKey(privateKey: NodeJS.ArrayBufferView): void; + setPrivateKey(privateKey: string, encoding: BufferEncoding): void; + /** + * A bit field containing any warnings and/or errors resulting from a check + * performed during initialization of the `DiffieHellman` object. + * + * The following values are valid for this property (as defined in `constants`module): + * + * * `DH_CHECK_P_NOT_SAFE_PRIME` + * * `DH_CHECK_P_NOT_PRIME` + * * `DH_UNABLE_TO_CHECK_GENERATOR` + * * `DH_NOT_SUITABLE_GENERATOR` + * @since v0.11.12 + */ + verifyError: number; + } + /** + * The `DiffieHellmanGroup` class takes a well-known modp group as its argument. + * It works the same as `DiffieHellman`, except that it does not allow changing its keys after creation. + * In other words, it does not implement `setPublicKey()` or `setPrivateKey()` methods. + * + * ```js + * const { createDiffieHellmanGroup } = await import('node:crypto'); + * const dh = createDiffieHellmanGroup('modp1'); + * ``` + * The name (e.g. `'modp1'`) is taken from [RFC 2412](https://www.rfc-editor.org/rfc/rfc2412.txt) (modp1 and 2) and [RFC 3526](https://www.rfc-editor.org/rfc/rfc3526.txt): + * ```bash + * $ perl -ne 'print "$1\n" if /"(modp\d+)"/' src/node_crypto_groups.h + * modp1 # 768 bits + * modp2 # 1024 bits + * modp5 # 1536 bits + * modp14 # 2048 bits + * modp15 # etc. + * modp16 + * modp17 + * modp18 + * ``` + * @since v0.7.5 + */ + const DiffieHellmanGroup: DiffieHellmanGroupConstructor; + interface DiffieHellmanGroupConstructor { + new(name: string): DiffieHellmanGroup; + (name: string): DiffieHellmanGroup; + readonly prototype: DiffieHellmanGroup; + } + type DiffieHellmanGroup = Omit; + /** + * Creates a predefined `DiffieHellmanGroup` key exchange object. The + * supported groups are: `'modp1'`, `'modp2'`, `'modp5'` (defined in [RFC 2412](https://www.rfc-editor.org/rfc/rfc2412.txt), but see `Caveats`) and `'modp14'`, `'modp15'`,`'modp16'`, `'modp17'`, + * `'modp18'` (defined in [RFC 3526](https://www.rfc-editor.org/rfc/rfc3526.txt)). The + * returned object mimics the interface of objects created by {@link createDiffieHellman}, but will not allow changing + * the keys (with `diffieHellman.setPublicKey()`, for example). The + * advantage of using this method is that the parties do not have to + * generate nor exchange a group modulus beforehand, saving both processor + * and communication time. + * + * Example (obtaining a shared secret): + * + * ```js + * const { + * getDiffieHellman + * } = await import('crypto'); + * const alice = getDiffieHellman('modp14'); + * const bob = getDiffieHellman('modp14'); + * + * alice.generateKeys(); + * bob.generateKeys(); + * + * const aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex'); + * const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex'); + * + * // aliceSecret and bobSecret should be the same + * console.log(aliceSecret === bobSecret); + * ``` + * @since v0.7.5 + */ + function getDiffieHellman(groupName: string): DiffieHellmanGroup; + /** + * An alias for {@link getDiffieHellman} + * @since v0.9.3 + */ + function createDiffieHellmanGroup(name: string): DiffieHellmanGroup; + /** + * Provides an asynchronous Password-Based Key Derivation Function 2 (PBKDF2) + * implementation. A selected HMAC digest algorithm specified by `digest` is + * applied to derive a key of the requested byte length (`keylen`) from the`password`, `salt` and `iterations`. + * + * The supplied `callback` function is called with two arguments: `err` and`derivedKey`. If an error occurs while deriving the key, `err` will be set; + * otherwise `err` will be `null`. By default, the successfully generated`derivedKey` will be passed to the callback as a `Buffer`. An error will be + * thrown if any of the input arguments specify invalid values or types. + * + * If `digest` is `null`, `'sha1'` will be used. This behavior is deprecated, + * please specify a `digest` explicitly. + * + * The `iterations` argument must be a number set as high as possible. The + * higher the number of iterations, the more secure the derived key will be, + * but will take a longer amount of time to complete. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * ```js + * const { + * pbkdf2 + * } = await import('crypto'); + * + * pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // '3745e48...08d59ae' + * }); + * ``` + * + * The `crypto.DEFAULT_ENCODING` property can be used to change the way the`derivedKey` is passed to the callback. This property, however, has been + * deprecated and use should be avoided. + * + * ```js + * import crypto from 'crypto'; + * crypto.DEFAULT_ENCODING = 'hex'; + * crypto.pbkdf2('secret', 'salt', 100000, 512, 'sha512', (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey); // '3745e48...aa39b34' + * }); + * ``` + * + * An array of supported digest functions can be retrieved using {@link getHashes}. + * + * This API uses libuv's threadpool, which can have surprising and + * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information. + * @since v0.5.5 + */ + function pbkdf2( + password: BinaryLike, + salt: BinaryLike, + iterations: number, + keylen: number, + digest: string, + callback: (err: Error | null, derivedKey: Buffer) => void, + ): void; + /** + * Provides a synchronous Password-Based Key Derivation Function 2 (PBKDF2) + * implementation. A selected HMAC digest algorithm specified by `digest` is + * applied to derive a key of the requested byte length (`keylen`) from the`password`, `salt` and `iterations`. + * + * If an error occurs an `Error` will be thrown, otherwise the derived key will be + * returned as a `Buffer`. + * + * If `digest` is `null`, `'sha1'` will be used. This behavior is deprecated, + * please specify a `digest` explicitly. + * + * The `iterations` argument must be a number set as high as possible. The + * higher the number of iterations, the more secure the derived key will be, + * but will take a longer amount of time to complete. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * ```js + * const { + * pbkdf2Sync + * } = await import('crypto'); + * + * const key = pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512'); + * console.log(key.toString('hex')); // '3745e48...08d59ae' + * ``` + * + * The `crypto.DEFAULT_ENCODING` property may be used to change the way the`derivedKey` is returned. This property, however, is deprecated and use + * should be avoided. + * + * ```js + * import crypto from 'crypto'; + * crypto.DEFAULT_ENCODING = 'hex'; + * const key = crypto.pbkdf2Sync('secret', 'salt', 100000, 512, 'sha512'); + * console.log(key); // '3745e48...aa39b34' + * ``` + * + * An array of supported digest functions can be retrieved using {@link getHashes}. + * @since v0.9.3 + */ + function pbkdf2Sync( + password: BinaryLike, + salt: BinaryLike, + iterations: number, + keylen: number, + digest: string, + ): Buffer; + /** + * Generates cryptographically strong pseudorandom data. The `size` argument + * is a number indicating the number of bytes to generate. + * + * If a `callback` function is provided, the bytes are generated asynchronously + * and the `callback` function is invoked with two arguments: `err` and `buf`. + * If an error occurs, `err` will be an `Error` object; otherwise it is `null`. The`buf` argument is a `Buffer` containing the generated bytes. + * + * ```js + * // Asynchronous + * const { + * randomBytes + * } = await import('crypto'); + * + * randomBytes(256, (err, buf) => { + * if (err) throw err; + * console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`); + * }); + * ``` + * + * If the `callback` function is not provided, the random bytes are generated + * synchronously and returned as a `Buffer`. An error will be thrown if + * there is a problem generating the bytes. + * + * ```js + * // Synchronous + * const { + * randomBytes + * } = await import('crypto'); + * + * const buf = randomBytes(256); + * console.log( + * `${buf.length} bytes of random data: ${buf.toString('hex')}`); + * ``` + * + * The `crypto.randomBytes()` method will not complete until there is + * sufficient entropy available. + * This should normally never take longer than a few milliseconds. The only time + * when generating the random bytes may conceivably block for a longer period of + * time is right after boot, when the whole system is still low on entropy. + * + * This API uses libuv's threadpool, which can have surprising and + * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information. + * + * The asynchronous version of `crypto.randomBytes()` is carried out in a single + * threadpool request. To minimize threadpool task length variation, partition + * large `randomBytes` requests when doing so as part of fulfilling a client + * request. + * @since v0.5.8 + * @param size The number of bytes to generate. The `size` must not be larger than `2**31 - 1`. + * @return if the `callback` function is not provided. + */ + function randomBytes(size: number): Buffer; + function randomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void; + function pseudoRandomBytes(size: number): Buffer; + function pseudoRandomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void; + /** + * Return a random integer `n` such that `min <= n < max`. This + * implementation avoids [modulo bias](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#Modulo_bias). + * + * The range (`max - min`) must be less than 2^48. `min` and `max` must + * be [safe integers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger). + * + * If the `callback` function is not provided, the random integer is + * generated synchronously. + * + * ```js + * // Asynchronous + * const { + * randomInt + * } = await import('crypto'); + * + * randomInt(3, (err, n) => { + * if (err) throw err; + * console.log(`Random number chosen from (0, 1, 2): ${n}`); + * }); + * ``` + * + * ```js + * // Synchronous + * const { + * randomInt + * } = await import('crypto'); + * + * const n = randomInt(3); + * console.log(`Random number chosen from (0, 1, 2): ${n}`); + * ``` + * + * ```js + * // With `min` argument + * const { + * randomInt + * } = await import('crypto'); + * + * const n = randomInt(1, 7); + * console.log(`The dice rolled: ${n}`); + * ``` + * @since v14.10.0, v12.19.0 + * @param [min=0] Start of random range (inclusive). + * @param max End of random range (exclusive). + * @param callback `function(err, n) {}`. + */ + function randomInt(max: number): number; + function randomInt(min: number, max: number): number; + function randomInt(max: number, callback: (err: Error | null, value: number) => void): void; + function randomInt(min: number, max: number, callback: (err: Error | null, value: number) => void): void; + /** + * Synchronous version of {@link randomFill}. + * + * ```js + * import { Buffer } from 'buffer'; + * const { randomFillSync } = await import('crypto'); + * + * const buf = Buffer.alloc(10); + * console.log(randomFillSync(buf).toString('hex')); + * + * randomFillSync(buf, 5); + * console.log(buf.toString('hex')); + * + * // The above is equivalent to the following: + * randomFillSync(buf, 5, 5); + * console.log(buf.toString('hex')); + * ``` + * + * Any `ArrayBuffer`, `TypedArray` or `DataView` instance may be passed as`buffer`. + * + * ```js + * import { Buffer } from 'buffer'; + * const { randomFillSync } = await import('crypto'); + * + * const a = new Uint32Array(10); + * console.log(Buffer.from(randomFillSync(a).buffer, + * a.byteOffset, a.byteLength).toString('hex')); + * + * const b = new DataView(new ArrayBuffer(10)); + * console.log(Buffer.from(randomFillSync(b).buffer, + * b.byteOffset, b.byteLength).toString('hex')); + * + * const c = new ArrayBuffer(10); + * console.log(Buffer.from(randomFillSync(c)).toString('hex')); + * ``` + * @since v7.10.0, v6.13.0 + * @param buffer Must be supplied. The size of the provided `buffer` must not be larger than `2**31 - 1`. + * @param [offset=0] + * @param [size=buffer.length - offset] + * @return The object passed as `buffer` argument. + */ + function randomFillSync(buffer: T, offset?: number, size?: number): T; + /** + * This function is similar to {@link randomBytes} but requires the first + * argument to be a `Buffer` that will be filled. It also + * requires that a callback is passed in. + * + * If the `callback` function is not provided, an error will be thrown. + * + * ```js + * import { Buffer } from 'buffer'; + * const { randomFill } = await import('crypto'); + * + * const buf = Buffer.alloc(10); + * randomFill(buf, (err, buf) => { + * if (err) throw err; + * console.log(buf.toString('hex')); + * }); + * + * randomFill(buf, 5, (err, buf) => { + * if (err) throw err; + * console.log(buf.toString('hex')); + * }); + * + * // The above is equivalent to the following: + * randomFill(buf, 5, 5, (err, buf) => { + * if (err) throw err; + * console.log(buf.toString('hex')); + * }); + * ``` + * + * Any `ArrayBuffer`, `TypedArray`, or `DataView` instance may be passed as`buffer`. + * + * While this includes instances of `Float32Array` and `Float64Array`, this + * function should not be used to generate random floating-point numbers. The + * result may contain `+Infinity`, `-Infinity`, and `NaN`, and even if the array + * contains finite numbers only, they are not drawn from a uniform random + * distribution and have no meaningful lower or upper bounds. + * + * ```js + * import { Buffer } from 'buffer'; + * const { randomFill } = await import('crypto'); + * + * const a = new Uint32Array(10); + * randomFill(a, (err, buf) => { + * if (err) throw err; + * console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength) + * .toString('hex')); + * }); + * + * const b = new DataView(new ArrayBuffer(10)); + * randomFill(b, (err, buf) => { + * if (err) throw err; + * console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength) + * .toString('hex')); + * }); + * + * const c = new ArrayBuffer(10); + * randomFill(c, (err, buf) => { + * if (err) throw err; + * console.log(Buffer.from(buf).toString('hex')); + * }); + * ``` + * + * This API uses libuv's threadpool, which can have surprising and + * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information. + * + * The asynchronous version of `crypto.randomFill()` is carried out in a single + * threadpool request. To minimize threadpool task length variation, partition + * large `randomFill` requests when doing so as part of fulfilling a client + * request. + * @since v7.10.0, v6.13.0 + * @param buffer Must be supplied. The size of the provided `buffer` must not be larger than `2**31 - 1`. + * @param [offset=0] + * @param [size=buffer.length - offset] + * @param callback `function(err, buf) {}`. + */ + function randomFill( + buffer: T, + callback: (err: Error | null, buf: T) => void, + ): void; + function randomFill( + buffer: T, + offset: number, + callback: (err: Error | null, buf: T) => void, + ): void; + function randomFill( + buffer: T, + offset: number, + size: number, + callback: (err: Error | null, buf: T) => void, + ): void; + interface ScryptOptions { + cost?: number | undefined; + blockSize?: number | undefined; + parallelization?: number | undefined; + N?: number | undefined; + r?: number | undefined; + p?: number | undefined; + maxmem?: number | undefined; + } + /** + * Provides an asynchronous [scrypt](https://en.wikipedia.org/wiki/Scrypt) implementation. Scrypt is a password-based + * key derivation function that is designed to be expensive computationally and + * memory-wise in order to make brute-force attacks unrewarding. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * The `callback` function is called with two arguments: `err` and `derivedKey`.`err` is an exception object when key derivation fails, otherwise `err` is`null`. `derivedKey` is passed to the + * callback as a `Buffer`. + * + * An exception is thrown when any of the input arguments specify invalid values + * or types. + * + * ```js + * const { + * scrypt + * } = await import('crypto'); + * + * // Using the factory defaults. + * scrypt('password', 'salt', 64, (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // '3745e48...08d59ae' + * }); + * // Using a custom N parameter. Must be a power of two. + * scrypt('password', 'salt', 64, { N: 1024 }, (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // '3745e48...aa39b34' + * }); + * ``` + * @since v10.5.0 + */ + function scrypt( + password: BinaryLike, + salt: BinaryLike, + keylen: number, + callback: (err: Error | null, derivedKey: Buffer) => void, + ): void; + function scrypt( + password: BinaryLike, + salt: BinaryLike, + keylen: number, + options: ScryptOptions, + callback: (err: Error | null, derivedKey: Buffer) => void, + ): void; + /** + * Provides a synchronous [scrypt](https://en.wikipedia.org/wiki/Scrypt) implementation. Scrypt is a password-based + * key derivation function that is designed to be expensive computationally and + * memory-wise in order to make brute-force attacks unrewarding. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * An exception is thrown when key derivation fails, otherwise the derived key is + * returned as a `Buffer`. + * + * An exception is thrown when any of the input arguments specify invalid values + * or types. + * + * ```js + * const { + * scryptSync + * } = await import('crypto'); + * // Using the factory defaults. + * + * const key1 = scryptSync('password', 'salt', 64); + * console.log(key1.toString('hex')); // '3745e48...08d59ae' + * // Using a custom N parameter. Must be a power of two. + * const key2 = scryptSync('password', 'salt', 64, { N: 1024 }); + * console.log(key2.toString('hex')); // '3745e48...aa39b34' + * ``` + * @since v10.5.0 + */ + function scryptSync(password: BinaryLike, salt: BinaryLike, keylen: number, options?: ScryptOptions): Buffer; + interface RsaPublicKey { + key: KeyLike; + padding?: number | undefined; + } + interface RsaPrivateKey { + key: KeyLike; + passphrase?: string | undefined; + /** + * @default 'sha1' + */ + oaepHash?: string | undefined; + oaepLabel?: NodeJS.TypedArray | undefined; + padding?: number | undefined; + } + /** + * Encrypts the content of `buffer` with `key` and returns a new `Buffer` with encrypted content. The returned data can be decrypted using + * the corresponding private key, for example using {@link privateDecrypt}. + * + * If `key` is not a `KeyObject`, this function behaves as if`key` had been passed to {@link createPublicKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses`RSA_PKCS1_OAEP_PADDING`. + * + * Because RSA public keys can be derived from private keys, a private key may + * be passed instead of a public key. + * @since v0.11.14 + */ + function publicEncrypt(key: RsaPublicKey | RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer; + /** + * Decrypts `buffer` with `key`.`buffer` was previously encrypted using + * the corresponding private key, for example using {@link privateEncrypt}. + * + * If `key` is not a `KeyObject`, this function behaves as if`key` had been passed to {@link createPublicKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses`RSA_PKCS1_PADDING`. + * + * Because RSA public keys can be derived from private keys, a private key may + * be passed instead of a public key. + * @since v1.1.0 + */ + function publicDecrypt(key: RsaPublicKey | RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer; + /** + * Decrypts `buffer` with `privateKey`. `buffer` was previously encrypted using + * the corresponding public key, for example using {@link publicEncrypt}. + * + * If `privateKey` is not a `KeyObject`, this function behaves as if`privateKey` had been passed to {@link createPrivateKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses`RSA_PKCS1_OAEP_PADDING`. + * @since v0.11.14 + */ + function privateDecrypt(privateKey: RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer; + /** + * Encrypts `buffer` with `privateKey`. The returned data can be decrypted using + * the corresponding public key, for example using {@link publicDecrypt}. + * + * If `privateKey` is not a `KeyObject`, this function behaves as if`privateKey` had been passed to {@link createPrivateKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses`RSA_PKCS1_PADDING`. + * @since v1.1.0 + */ + function privateEncrypt(privateKey: RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer; + /** + * ```js + * const { + * getCiphers + * } = await import('crypto'); + * + * console.log(getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...] + * ``` + * @since v0.9.3 + * @return An array with the names of the supported cipher algorithms. + */ + function getCiphers(): string[]; + /** + * ```js + * const { + * getCurves + * } = await import('crypto'); + * + * console.log(getCurves()); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...] + * ``` + * @since v2.3.0 + * @return An array with the names of the supported elliptic curves. + */ + function getCurves(): string[]; + /** + * @since v10.0.0 + * @return `1` if and only if a FIPS compliant crypto provider is currently in use, `0` otherwise. A future semver-major release may change the return type of this API to a {boolean}. + */ + function getFips(): 1 | 0; + /** + * Enables the FIPS compliant crypto provider in a FIPS-enabled Node.js build. Throws an error if FIPS mode is not available. + * @since v10.0.0 + * @param bool `true` to enable FIPS mode. + */ + function setFips(bool: boolean): void; + /** + * ```js + * const { + * getHashes + * } = await import('crypto'); + * + * console.log(getHashes()); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...] + * ``` + * @since v0.9.3 + * @return An array of the names of the supported hash algorithms, such as `'RSA-SHA256'`. Hash algorithms are also called "digest" algorithms. + */ + function getHashes(): string[]; + /** + * The `ECDH` class is a utility for creating Elliptic Curve Diffie-Hellman (ECDH) + * key exchanges. + * + * Instances of the `ECDH` class can be created using the {@link createECDH} function. + * + * ```js + * import assert from 'assert'; + * + * const { + * createECDH + * } = await import('crypto'); + * + * // Generate Alice's keys... + * const alice = createECDH('secp521r1'); + * const aliceKey = alice.generateKeys(); + * + * // Generate Bob's keys... + * const bob = createECDH('secp521r1'); + * const bobKey = bob.generateKeys(); + * + * // Exchange and generate the secret... + * const aliceSecret = alice.computeSecret(bobKey); + * const bobSecret = bob.computeSecret(aliceKey); + * + * assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); + * // OK + * ``` + * @since v0.11.14 + */ + class ECDH { + private constructor(); + /** + * Converts the EC Diffie-Hellman public key specified by `key` and `curve` to the + * format specified by `format`. The `format` argument specifies point encoding + * and can be `'compressed'`, `'uncompressed'` or `'hybrid'`. The supplied key is + * interpreted using the specified `inputEncoding`, and the returned key is encoded + * using the specified `outputEncoding`. + * + * Use {@link getCurves} to obtain a list of available curve names. + * On recent OpenSSL releases, `openssl ecparam -list_curves` will also display + * the name and description of each available elliptic curve. + * + * If `format` is not specified the point will be returned in `'uncompressed'`format. + * + * If the `inputEncoding` is not provided, `key` is expected to be a `Buffer`,`TypedArray`, or `DataView`. + * + * Example (uncompressing a key): + * + * ```js + * const { + * createECDH, + * ECDH + * } = await import('crypto'); + * + * const ecdh = createECDH('secp256k1'); + * ecdh.generateKeys(); + * + * const compressedKey = ecdh.getPublicKey('hex', 'compressed'); + * + * const uncompressedKey = ECDH.convertKey(compressedKey, + * 'secp256k1', + * 'hex', + * 'hex', + * 'uncompressed'); + * + * // The converted key and the uncompressed public key should be the same + * console.log(uncompressedKey === ecdh.getPublicKey('hex')); + * ``` + * @since v10.0.0 + * @param inputEncoding The `encoding` of the `key` string. + * @param outputEncoding The `encoding` of the return value. + * @param [format='uncompressed'] + */ + static convertKey( + key: BinaryLike, + curve: string, + inputEncoding?: BinaryToTextEncoding, + outputEncoding?: "latin1" | "hex" | "base64" | "base64url", + format?: "uncompressed" | "compressed" | "hybrid", + ): Buffer | string; + /** + * Generates private and public EC Diffie-Hellman key values, and returns + * the public key in the specified `format` and `encoding`. This key should be + * transferred to the other party. + * + * The `format` argument specifies point encoding and can be `'compressed'` or`'uncompressed'`. If `format` is not specified, the point will be returned in`'uncompressed'` format. + * + * If `encoding` is provided a string is returned; otherwise a `Buffer` is returned. + * @since v0.11.14 + * @param encoding The `encoding` of the return value. + * @param [format='uncompressed'] + */ + generateKeys(): Buffer; + generateKeys(encoding: BinaryToTextEncoding, format?: ECDHKeyFormat): string; + /** + * Computes the shared secret using `otherPublicKey` as the other + * party's public key and returns the computed shared secret. The supplied + * key is interpreted using specified `inputEncoding`, and the returned secret + * is encoded using the specified `outputEncoding`. + * If the `inputEncoding` is not + * provided, `otherPublicKey` is expected to be a `Buffer`, `TypedArray`, or`DataView`. + * + * If `outputEncoding` is given a string will be returned; otherwise a `Buffer` is returned. + * + * `ecdh.computeSecret` will throw an`ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY` error when `otherPublicKey`lies outside of the elliptic curve. Since `otherPublicKey` is + * usually supplied from a remote user over an insecure network, + * be sure to handle this exception accordingly. + * @since v0.11.14 + * @param inputEncoding The `encoding` of the `otherPublicKey` string. + * @param outputEncoding The `encoding` of the return value. + */ + computeSecret(otherPublicKey: NodeJS.ArrayBufferView): Buffer; + computeSecret(otherPublicKey: string, inputEncoding: BinaryToTextEncoding): Buffer; + computeSecret(otherPublicKey: NodeJS.ArrayBufferView, outputEncoding: BinaryToTextEncoding): string; + computeSecret( + otherPublicKey: string, + inputEncoding: BinaryToTextEncoding, + outputEncoding: BinaryToTextEncoding, + ): string; + /** + * If `encoding` is specified, a string is returned; otherwise a `Buffer` is + * returned. + * @since v0.11.14 + * @param encoding The `encoding` of the return value. + * @return The EC Diffie-Hellman in the specified `encoding`. + */ + getPrivateKey(): Buffer; + getPrivateKey(encoding: BinaryToTextEncoding): string; + /** + * The `format` argument specifies point encoding and can be `'compressed'` or`'uncompressed'`. If `format` is not specified the point will be returned in`'uncompressed'` format. + * + * If `encoding` is specified, a string is returned; otherwise a `Buffer` is + * returned. + * @since v0.11.14 + * @param [encoding] The `encoding` of the return value. + * @param [format='uncompressed'] + * @return The EC Diffie-Hellman public key in the specified `encoding` and `format`. + */ + getPublicKey(encoding?: null, format?: ECDHKeyFormat): Buffer; + getPublicKey(encoding: BinaryToTextEncoding, format?: ECDHKeyFormat): string; + /** + * Sets the EC Diffie-Hellman private key. + * If `encoding` is provided, `privateKey` is expected + * to be a string; otherwise `privateKey` is expected to be a `Buffer`,`TypedArray`, or `DataView`. + * + * If `privateKey` is not valid for the curve specified when the `ECDH` object was + * created, an error is thrown. Upon setting the private key, the associated + * public point (key) is also generated and set in the `ECDH` object. + * @since v0.11.14 + * @param encoding The `encoding` of the `privateKey` string. + */ + setPrivateKey(privateKey: NodeJS.ArrayBufferView): void; + setPrivateKey(privateKey: string, encoding: BinaryToTextEncoding): void; + } + /** + * Creates an Elliptic Curve Diffie-Hellman (`ECDH`) key exchange object using a + * predefined curve specified by the `curveName` string. Use {@link getCurves} to obtain a list of available curve names. On recent + * OpenSSL releases, `openssl ecparam -list_curves` will also display the name + * and description of each available elliptic curve. + * @since v0.11.14 + */ + function createECDH(curveName: string): ECDH; + /** + * This function is based on a constant-time algorithm. + * Returns true if `a` is equal to `b`, without leaking timing information that + * would allow an attacker to guess one of the values. This is suitable for + * comparing HMAC digests or secret values like authentication cookies or [capability urls](https://www.w3.org/TR/capability-urls/). + * + * `a` and `b` must both be `Buffer`s, `TypedArray`s, or `DataView`s, and they + * must have the same byte length. An error is thrown if `a` and `b` have + * different byte lengths. + * + * If at least one of `a` and `b` is a `TypedArray` with more than one byte per + * entry, such as `Uint16Array`, the result will be computed using the platform + * byte order. + * + * Use of `crypto.timingSafeEqual` does not guarantee that the _surrounding_ code + * is timing-safe. Care should be taken to ensure that the surrounding code does + * not introduce timing vulnerabilities. + * @since v6.6.0 + */ + function timingSafeEqual(a: NodeJS.ArrayBufferView, b: NodeJS.ArrayBufferView): boolean; + /** @deprecated since v10.0.0 */ + const DEFAULT_ENCODING: BufferEncoding; + type KeyType = "rsa" | "rsa-pss" | "dsa" | "ec" | "ed25519" | "ed448" | "x25519" | "x448"; + type KeyFormat = "pem" | "der" | "jwk"; + interface BasePrivateKeyEncodingOptions { + format: T; + cipher?: string | undefined; + passphrase?: string | undefined; + } + interface KeyPairKeyObjectResult { + publicKey: KeyObject; + privateKey: KeyObject; + } + interface ED25519KeyPairKeyObjectOptions {} + interface ED448KeyPairKeyObjectOptions {} + interface X25519KeyPairKeyObjectOptions {} + interface X448KeyPairKeyObjectOptions {} + interface ECKeyPairKeyObjectOptions { + /** + * Name of the curve to use + */ + namedCurve: string; + /** + * Must be `'named'` or `'explicit'`. Default: `'named'`. + */ + paramEncoding?: "explicit" | "named" | undefined; + } + interface RSAKeyPairKeyObjectOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + } + interface RSAPSSKeyPairKeyObjectOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + /** + * Name of the message digest + */ + hashAlgorithm?: string; + /** + * Name of the message digest used by MGF1 + */ + mgf1HashAlgorithm?: string; + /** + * Minimal salt length in bytes + */ + saltLength?: string; + } + interface DSAKeyPairKeyObjectOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Size of q in bits + */ + divisorLength: number; + } + interface RSAKeyPairOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + publicKeyEncoding: { + type: "pkcs1" | "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs1" | "pkcs8"; + }; + } + interface RSAPSSKeyPairOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + /** + * Name of the message digest + */ + hashAlgorithm?: string; + /** + * Name of the message digest used by MGF1 + */ + mgf1HashAlgorithm?: string; + /** + * Minimal salt length in bytes + */ + saltLength?: string; + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface DSAKeyPairOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Size of q in bits + */ + divisorLength: number; + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface ECKeyPairOptions extends ECKeyPairKeyObjectOptions { + publicKeyEncoding: { + type: "pkcs1" | "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "sec1" | "pkcs8"; + }; + } + interface ED25519KeyPairOptions { + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface ED448KeyPairOptions { + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface X25519KeyPairOptions { + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface X448KeyPairOptions { + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface KeyPairSyncResult { + publicKey: T1; + privateKey: T2; + } + /** + * Generates a new asymmetric key pair of the given `type`. RSA, RSA-PSS, DSA, EC, + * Ed25519, Ed448, X25519, X448, and DH are currently supported. + * + * If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function + * behaves as if `keyObject.export()` had been called on its result. Otherwise, + * the respective part of the key is returned as a `KeyObject`. + * + * When encoding public keys, it is recommended to use `'spki'`. When encoding + * private keys, it is recommended to use `'pkcs8'` with a strong passphrase, + * and to keep the passphrase confidential. + * + * ```js + * const { + * generateKeyPairSync + * } = await import('crypto'); + * + * const { + * publicKey, + * privateKey, + * } = generateKeyPairSync('rsa', { + * modulusLength: 4096, + * publicKeyEncoding: { + * type: 'spki', + * format: 'pem' + * }, + * privateKeyEncoding: { + * type: 'pkcs8', + * format: 'pem', + * cipher: 'aes-256-cbc', + * passphrase: 'top secret' + * } + * }); + * ``` + * + * The return value `{ publicKey, privateKey }` represents the generated key pair. + * When PEM encoding was selected, the respective key will be a string, otherwise + * it will be a buffer containing the data encoded as DER. + * @since v10.12.0 + * @param type Must be `'rsa'`, `'rsa-pss'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`. + */ + function generateKeyPairSync( + type: "rsa", + options: RSAKeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "rsa", + options: RSAKeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "rsa", + options: RSAKeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "rsa", + options: RSAKeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "rsa", options: RSAKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "rsa-pss", options: RSAPSSKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "dsa", + options: DSAKeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "dsa", + options: DSAKeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "dsa", + options: DSAKeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "dsa", + options: DSAKeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "dsa", options: DSAKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "ec", + options: ECKeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ec", + options: ECKeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ec", + options: ECKeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ec", + options: ECKeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "ec", options: ECKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "ed25519", options?: ED25519KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "ed448", + options: ED448KeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ed448", + options: ED448KeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ed448", + options: ED448KeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ed448", + options: ED448KeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "ed448", options?: ED448KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "x25519", + options: X25519KeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "x25519", + options: X25519KeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "x25519", + options: X25519KeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "x25519", + options: X25519KeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "x25519", options?: X25519KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "x448", + options: X448KeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "x448", + options: X448KeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "x448", + options: X448KeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "x448", + options: X448KeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "x448", options?: X448KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + /** + * Generates a new asymmetric key pair of the given `type`. RSA, RSA-PSS, DSA, EC, + * Ed25519, Ed448, X25519, X448, and DH are currently supported. + * + * If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function + * behaves as if `keyObject.export()` had been called on its result. Otherwise, + * the respective part of the key is returned as a `KeyObject`. + * + * It is recommended to encode public keys as `'spki'` and private keys as`'pkcs8'` with encryption for long-term storage: + * + * ```js + * const { + * generateKeyPair + * } = await import('crypto'); + * + * generateKeyPair('rsa', { + * modulusLength: 4096, + * publicKeyEncoding: { + * type: 'spki', + * format: 'pem' + * }, + * privateKeyEncoding: { + * type: 'pkcs8', + * format: 'pem', + * cipher: 'aes-256-cbc', + * passphrase: 'top secret' + * } + * }, (err, publicKey, privateKey) => { + * // Handle errors and use the generated key pair. + * }); + * ``` + * + * On completion, `callback` will be called with `err` set to `undefined` and`publicKey` / `privateKey` representing the generated key pair. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a `Promise` for an `Object` with `publicKey` and `privateKey` properties. + * @since v10.12.0 + * @param type Must be `'rsa'`, `'rsa-pss'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`. + */ + function generateKeyPair( + type: "rsa", + options: RSAKeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "rsa", + options: RSAKeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "rsa", + options: RSAKeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "rsa", + options: RSAKeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "rsa", + options: RSAKeyPairKeyObjectOptions, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "rsa-pss", + options: RSAPSSKeyPairKeyObjectOptions, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "dsa", + options: DSAKeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "dsa", + options: DSAKeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "dsa", + options: DSAKeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "dsa", + options: DSAKeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "dsa", + options: DSAKeyPairKeyObjectOptions, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "ec", + options: ECKeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ec", + options: ECKeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "ec", + options: ECKeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ec", + options: ECKeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "ec", + options: ECKeyPairKeyObjectOptions, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "ed25519", + options: ED25519KeyPairKeyObjectOptions | undefined, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "ed448", + options: ED448KeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ed448", + options: ED448KeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "ed448", + options: ED448KeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ed448", + options: ED448KeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "ed448", + options: ED448KeyPairKeyObjectOptions | undefined, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "x25519", + options: X25519KeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "x25519", + options: X25519KeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "x25519", + options: X25519KeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "x25519", + options: X25519KeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "x25519", + options: X25519KeyPairKeyObjectOptions | undefined, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "x448", + options: X448KeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "x448", + options: X448KeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "x448", + options: X448KeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "x448", + options: X448KeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "x448", + options: X448KeyPairKeyObjectOptions | undefined, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + namespace generateKeyPair { + function __promisify__( + type: "rsa", + options: RSAKeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "rsa", + options: RSAKeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "rsa", + options: RSAKeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "rsa", + options: RSAKeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: "rsa", options: RSAKeyPairKeyObjectOptions): Promise; + function __promisify__( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__( + type: "rsa-pss", + options: RSAPSSKeyPairKeyObjectOptions, + ): Promise; + function __promisify__( + type: "dsa", + options: DSAKeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "dsa", + options: DSAKeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "dsa", + options: DSAKeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "dsa", + options: DSAKeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: "dsa", options: DSAKeyPairKeyObjectOptions): Promise; + function __promisify__( + type: "ec", + options: ECKeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "ec", + options: ECKeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "ec", + options: ECKeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "ec", + options: ECKeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: "ec", options: ECKeyPairKeyObjectOptions): Promise; + function __promisify__( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__( + type: "ed25519", + options?: ED25519KeyPairKeyObjectOptions, + ): Promise; + function __promisify__( + type: "ed448", + options: ED448KeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "ed448", + options: ED448KeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "ed448", + options: ED448KeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "ed448", + options: ED448KeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: "ed448", options?: ED448KeyPairKeyObjectOptions): Promise; + function __promisify__( + type: "x25519", + options: X25519KeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "x25519", + options: X25519KeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "x25519", + options: X25519KeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "x25519", + options: X25519KeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__( + type: "x25519", + options?: X25519KeyPairKeyObjectOptions, + ): Promise; + function __promisify__( + type: "x448", + options: X448KeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "x448", + options: X448KeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "x448", + options: X448KeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "x448", + options: X448KeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: "x448", options?: X448KeyPairKeyObjectOptions): Promise; + } + /** + * Calculates and returns the signature for `data` using the given private key and + * algorithm. If `algorithm` is `null` or `undefined`, then the algorithm is + * dependent upon the key type (especially Ed25519 and Ed448). + * + * If `key` is not a `KeyObject`, this function behaves as if `key` had been + * passed to {@link createPrivateKey}. If it is an object, the following + * additional properties can be passed: + * + * If the `callback` function is provided this function uses libuv's threadpool. + * @since v12.0.0 + */ + function sign( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput, + ): Buffer; + function sign( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput, + callback: (error: Error | null, data: Buffer) => void, + ): void; + /** + * Verifies the given signature for `data` using the given key and algorithm. If`algorithm` is `null` or `undefined`, then the algorithm is dependent upon the + * key type (especially Ed25519 and Ed448). + * + * If `key` is not a `KeyObject`, this function behaves as if `key` had been + * passed to {@link createPublicKey}. If it is an object, the following + * additional properties can be passed: + * + * The `signature` argument is the previously calculated signature for the `data`. + * + * Because public keys can be derived from private keys, a private key or a public + * key may be passed for `key`. + * + * If the `callback` function is provided this function uses libuv's threadpool. + * @since v12.0.0 + */ + function verify( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, + signature: NodeJS.ArrayBufferView, + ): boolean; + function verify( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, + signature: NodeJS.ArrayBufferView, + callback: (error: Error | null, result: boolean) => void, + ): void; + /** + * Computes the Diffie-Hellman secret based on a `privateKey` and a `publicKey`. + * Both keys must have the same `asymmetricKeyType`, which must be one of `'dh'`(for Diffie-Hellman), `'ec'` (for ECDH), `'x448'`, or `'x25519'` (for ECDH-ES). + * @since v13.9.0, v12.17.0 + */ + function diffieHellman(options: { privateKey: KeyObject; publicKey: KeyObject }): Buffer; + type CipherMode = "cbc" | "ccm" | "cfb" | "ctr" | "ecb" | "gcm" | "ocb" | "ofb" | "stream" | "wrap" | "xts"; + interface CipherInfoOptions { + /** + * A test key length. + */ + keyLength?: number | undefined; + /** + * A test IV length. + */ + ivLength?: number | undefined; + } + interface CipherInfo { + /** + * The name of the cipher. + */ + name: string; + /** + * The nid of the cipher. + */ + nid: number; + /** + * The block size of the cipher in bytes. + * This property is omitted when mode is 'stream'. + */ + blockSize?: number | undefined; + /** + * The expected or default initialization vector length in bytes. + * This property is omitted if the cipher does not use an initialization vector. + */ + ivLength?: number | undefined; + /** + * The expected or default key length in bytes. + */ + keyLength: number; + /** + * The cipher mode. + */ + mode: CipherMode; + } + /** + * Returns information about a given cipher. + * + * Some ciphers accept variable length keys and initialization vectors. By default, + * the `crypto.getCipherInfo()` method will return the default values for these + * ciphers. To test if a given key length or iv length is acceptable for given + * cipher, use the `keyLength` and `ivLength` options. If the given values are + * unacceptable, `undefined` will be returned. + * @since v15.0.0 + * @param nameOrNid The name or nid of the cipher to query. + */ + function getCipherInfo(nameOrNid: string | number, options?: CipherInfoOptions): CipherInfo | undefined; + /** + * HKDF is a simple key derivation function defined in RFC 5869\. The given `ikm`,`salt` and `info` are used with the `digest` to derive a key of `keylen` bytes. + * + * The supplied `callback` function is called with two arguments: `err` and`derivedKey`. If an errors occurs while deriving the key, `err` will be set; + * otherwise `err` will be `null`. The successfully generated `derivedKey` will + * be passed to the callback as an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). An error will be thrown if any + * of the input arguments specify invalid values or types. + * + * ```js + * import { Buffer } from 'buffer'; + * const { + * hkdf + * } = await import('crypto'); + * + * hkdf('sha512', 'key', 'salt', 'info', 64, (err, derivedKey) => { + * if (err) throw err; + * console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653' + * }); + * ``` + * @since v15.0.0 + * @param digest The digest algorithm to use. + * @param ikm The input keying material. It must be at least one byte in length. + * @param salt The salt value. Must be provided but can be zero-length. + * @param info Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes. + * @param keylen The length of the key to generate. Must be greater than 0. The maximum allowable value is `255` times the number of bytes produced by the selected digest function (e.g. `sha512` + * generates 64-byte hashes, making the maximum HKDF output 16320 bytes). + */ + function hkdf( + digest: string, + irm: BinaryLike | KeyObject, + salt: BinaryLike, + info: BinaryLike, + keylen: number, + callback: (err: Error | null, derivedKey: ArrayBuffer) => void, + ): void; + /** + * Provides a synchronous HKDF key derivation function as defined in RFC 5869\. The + * given `ikm`, `salt` and `info` are used with the `digest` to derive a key of`keylen` bytes. + * + * The successfully generated `derivedKey` will be returned as an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). + * + * An error will be thrown if any of the input arguments specify invalid values or + * types, or if the derived key cannot be generated. + * + * ```js + * import { Buffer } from 'buffer'; + * const { + * hkdfSync + * } = await import('crypto'); + * + * const derivedKey = hkdfSync('sha512', 'key', 'salt', 'info', 64); + * console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653' + * ``` + * @since v15.0.0 + * @param digest The digest algorithm to use. + * @param ikm The input keying material. It must be at least one byte in length. + * @param salt The salt value. Must be provided but can be zero-length. + * @param info Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes. + * @param keylen The length of the key to generate. Must be greater than 0. The maximum allowable value is `255` times the number of bytes produced by the selected digest function (e.g. `sha512` + * generates 64-byte hashes, making the maximum HKDF output 16320 bytes). + */ + function hkdfSync( + digest: string, + ikm: BinaryLike | KeyObject, + salt: BinaryLike, + info: BinaryLike, + keylen: number, + ): ArrayBuffer; + interface SecureHeapUsage { + /** + * The total allocated secure heap size as specified using the `--secure-heap=n` command-line flag. + */ + total: number; + /** + * The minimum allocation from the secure heap as specified using the `--secure-heap-min` command-line flag. + */ + min: number; + /** + * The total number of bytes currently allocated from the secure heap. + */ + used: number; + /** + * The calculated ratio of `used` to `total` allocated bytes. + */ + utilization: number; + } + /** + * @since v15.6.0 + */ + function secureHeapUsed(): SecureHeapUsage; + interface RandomUUIDOptions { + /** + * By default, to improve performance, + * Node.js will pre-emptively generate and persistently cache enough + * random data to generate up to 128 random UUIDs. To generate a UUID + * without using the cache, set `disableEntropyCache` to `true`. + * + * @default `false` + */ + disableEntropyCache?: boolean | undefined; + } + type UUID = `${string}-${string}-${string}-${string}-${string}`; + /** + * Generates a random [RFC 4122](https://www.rfc-editor.org/rfc/rfc4122.txt) version 4 UUID. The UUID is generated using a + * cryptographic pseudorandom number generator. + * @since v15.6.0, v14.17.0 + */ + function randomUUID(options?: RandomUUIDOptions): UUID; + interface X509CheckOptions { + /** + * @default 'always' + */ + subject?: "always" | "default" | "never"; + /** + * @default true + */ + wildcards?: boolean; + /** + * @default true + */ + partialWildcards?: boolean; + /** + * @default false + */ + multiLabelWildcards?: boolean; + /** + * @default false + */ + singleLabelSubdomains?: boolean; + } + /** + * Encapsulates an X509 certificate and provides read-only access to + * its information. + * + * ```js + * const { X509Certificate } = await import('crypto'); + * + * const x509 = new X509Certificate('{... pem encoded cert ...}'); + * + * console.log(x509.subject); + * ``` + * @since v15.6.0 + */ + class X509Certificate { + /** + * Will be \`true\` if this is a Certificate Authority (CA) certificate. + * @since v15.6.0 + */ + readonly ca: boolean; + /** + * The SHA-1 fingerprint of this certificate. + * + * Because SHA-1 is cryptographically broken and because the security of SHA-1 is + * significantly worse than that of algorithms that are commonly used to sign + * certificates, consider using `x509.fingerprint256` instead. + * @since v15.6.0 + */ + readonly fingerprint: string; + /** + * The SHA-256 fingerprint of this certificate. + * @since v15.6.0 + */ + readonly fingerprint256: string; + /** + * The SHA-512 fingerprint of this certificate. + * @since v16.14.0 + */ + readonly fingerprint512: string; + /** + * The complete subject of this certificate. + * @since v15.6.0 + */ + readonly subject: string; + /** + * The subject alternative name specified for this certificate or `undefined` + * if not available. + * @since v15.6.0 + */ + readonly subjectAltName: string | undefined; + /** + * The information access content of this certificate or `undefined` if not + * available. + * @since v15.6.0 + */ + readonly infoAccess: string | undefined; + /** + * An array detailing the key usages for this certificate. + * @since v15.6.0 + */ + readonly keyUsage: string[]; + /** + * The issuer identification included in this certificate. + * @since v15.6.0 + */ + readonly issuer: string; + /** + * The issuer certificate or `undefined` if the issuer certificate is not + * available. + * @since v15.9.0 + */ + readonly issuerCertificate?: X509Certificate | undefined; + /** + * The public key `KeyObject` for this certificate. + * @since v15.6.0 + */ + readonly publicKey: KeyObject; + /** + * A `Buffer` containing the DER encoding of this certificate. + * @since v15.6.0 + */ + readonly raw: Buffer; + /** + * The serial number of this certificate. + * + * Serial numbers are assigned by certificate authorities and do not uniquely + * identify certificates. Consider using `x509.fingerprint256` as a unique + * identifier instead. + * @since v15.6.0 + */ + readonly serialNumber: string; + /** + * The date/time from which this certificate is considered valid. + * @since v15.6.0 + */ + readonly validFrom: string; + /** + * The date/time until which this certificate is considered valid. + * @since v15.6.0 + */ + readonly validTo: string; + constructor(buffer: BinaryLike); + /** + * Checks whether the certificate matches the given email address. + * + * If the `'subject'` option is undefined or set to `'default'`, the certificate + * subject is only considered if the subject alternative name extension either does + * not exist or does not contain any email addresses. + * + * If the `'subject'` option is set to `'always'` and if the subject alternative + * name extension either does not exist or does not contain a matching email + * address, the certificate subject is considered. + * + * If the `'subject'` option is set to `'never'`, the certificate subject is never + * considered, even if the certificate contains no subject alternative names. + * @since v15.6.0 + * @return Returns `email` if the certificate matches, `undefined` if it does not. + */ + checkEmail(email: string, options?: Pick): string | undefined; + /** + * Checks whether the certificate matches the given host name. + * + * If the certificate matches the given host name, the matching subject name is + * returned. The returned name might be an exact match (e.g., `foo.example.com`) + * or it might contain wildcards (e.g., `*.example.com`). Because host name + * comparisons are case-insensitive, the returned subject name might also differ + * from the given `name` in capitalization. + * + * If the `'subject'` option is undefined or set to `'default'`, the certificate + * subject is only considered if the subject alternative name extension either does + * not exist or does not contain any DNS names. This behavior is consistent with [RFC 2818](https://www.rfc-editor.org/rfc/rfc2818.txt) ("HTTP Over TLS"). + * + * If the `'subject'` option is set to `'always'` and if the subject alternative + * name extension either does not exist or does not contain a matching DNS name, + * the certificate subject is considered. + * + * If the `'subject'` option is set to `'never'`, the certificate subject is never + * considered, even if the certificate contains no subject alternative names. + * @since v15.6.0 + * @return Returns a subject name that matches `name`, or `undefined` if no subject name matches `name`. + */ + checkHost(name: string, options?: X509CheckOptions): string | undefined; + /** + * Checks whether the certificate matches the given IP address (IPv4 or IPv6). + * + * Only [RFC 5280](https://www.rfc-editor.org/rfc/rfc5280.txt) `iPAddress` subject alternative names are considered, and they + * must match the given `ip` address exactly. Other subject alternative names as + * well as the subject field of the certificate are ignored. + * @since v15.6.0 + * @return Returns `ip` if the certificate matches, `undefined` if it does not. + */ + checkIP(ip: string): string | undefined; + /** + * Checks whether this certificate was issued by the given `otherCert`. + * @since v15.6.0 + */ + checkIssued(otherCert: X509Certificate): boolean; + /** + * Checks whether the public key for this certificate is consistent with + * the given private key. + * @since v15.6.0 + * @param privateKey A private key. + */ + checkPrivateKey(privateKey: KeyObject): boolean; + /** + * There is no standard JSON encoding for X509 certificates. The`toJSON()` method returns a string containing the PEM encoded + * certificate. + * @since v15.6.0 + */ + toJSON(): string; + /** + * Returns information about this certificate using the legacy `certificate object` encoding. + * @since v15.6.0 + */ + toLegacyObject(): PeerCertificate; + /** + * Returns the PEM-encoded certificate. + * @since v15.6.0 + */ + toString(): string; + /** + * Verifies that this certificate was signed by the given public key. + * Does not perform any other validation checks on the certificate. + * @since v15.6.0 + * @param publicKey A public key. + */ + verify(publicKey: KeyObject): boolean; + } + type LargeNumberLike = NodeJS.ArrayBufferView | SharedArrayBuffer | ArrayBuffer | bigint; + interface GeneratePrimeOptions { + add?: LargeNumberLike | undefined; + rem?: LargeNumberLike | undefined; + /** + * @default false + */ + safe?: boolean | undefined; + bigint?: boolean | undefined; + } + interface GeneratePrimeOptionsBigInt extends GeneratePrimeOptions { + bigint: true; + } + interface GeneratePrimeOptionsArrayBuffer extends GeneratePrimeOptions { + bigint?: false | undefined; + } + /** + * Generates a pseudorandom prime of `size` bits. + * + * If `options.safe` is `true`, the prime will be a safe prime -- that is,`(prime - 1) / 2` will also be a prime. + * + * The `options.add` and `options.rem` parameters can be used to enforce additional + * requirements, e.g., for Diffie-Hellman: + * + * * If `options.add` and `options.rem` are both set, the prime will satisfy the + * condition that `prime % add = rem`. + * * If only `options.add` is set and `options.safe` is not `true`, the prime will + * satisfy the condition that `prime % add = 1`. + * * If only `options.add` is set and `options.safe` is set to `true`, the prime + * will instead satisfy the condition that `prime % add = 3`. This is necessary + * because `prime % add = 1` for `options.add > 2` would contradict the condition + * enforced by `options.safe`. + * * `options.rem` is ignored if `options.add` is not given. + * + * Both `options.add` and `options.rem` must be encoded as big-endian sequences + * if given as an `ArrayBuffer`, `SharedArrayBuffer`, `TypedArray`, `Buffer`, or`DataView`. + * + * By default, the prime is encoded as a big-endian sequence of octets + * in an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). If the `bigint` option is `true`, then a + * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) is provided. + * @since v15.8.0 + * @param size The size (in bits) of the prime to generate. + */ + function generatePrime(size: number, callback: (err: Error | null, prime: ArrayBuffer) => void): void; + function generatePrime( + size: number, + options: GeneratePrimeOptionsBigInt, + callback: (err: Error | null, prime: bigint) => void, + ): void; + function generatePrime( + size: number, + options: GeneratePrimeOptionsArrayBuffer, + callback: (err: Error | null, prime: ArrayBuffer) => void, + ): void; + function generatePrime( + size: number, + options: GeneratePrimeOptions, + callback: (err: Error | null, prime: ArrayBuffer | bigint) => void, + ): void; + /** + * Generates a pseudorandom prime of `size` bits. + * + * If `options.safe` is `true`, the prime will be a safe prime -- that is,`(prime - 1) / 2` will also be a prime. + * + * The `options.add` and `options.rem` parameters can be used to enforce additional + * requirements, e.g., for Diffie-Hellman: + * + * * If `options.add` and `options.rem` are both set, the prime will satisfy the + * condition that `prime % add = rem`. + * * If only `options.add` is set and `options.safe` is not `true`, the prime will + * satisfy the condition that `prime % add = 1`. + * * If only `options.add` is set and `options.safe` is set to `true`, the prime + * will instead satisfy the condition that `prime % add = 3`. This is necessary + * because `prime % add = 1` for `options.add > 2` would contradict the condition + * enforced by `options.safe`. + * * `options.rem` is ignored if `options.add` is not given. + * + * Both `options.add` and `options.rem` must be encoded as big-endian sequences + * if given as an `ArrayBuffer`, `SharedArrayBuffer`, `TypedArray`, `Buffer`, or`DataView`. + * + * By default, the prime is encoded as a big-endian sequence of octets + * in an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). If the `bigint` option is `true`, then a + * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) is provided. + * @since v15.8.0 + * @param size The size (in bits) of the prime to generate. + */ + function generatePrimeSync(size: number): ArrayBuffer; + function generatePrimeSync(size: number, options: GeneratePrimeOptionsBigInt): bigint; + function generatePrimeSync(size: number, options: GeneratePrimeOptionsArrayBuffer): ArrayBuffer; + function generatePrimeSync(size: number, options: GeneratePrimeOptions): ArrayBuffer | bigint; + interface CheckPrimeOptions { + /** + * The number of Miller-Rabin probabilistic primality iterations to perform. + * When the value is 0 (zero), a number of checks is used that yields a false positive rate of at most `2**-64` for random input. + * Care must be used when selecting a number of checks. + * Refer to the OpenSSL documentation for the BN_is_prime_ex function nchecks options for more details. + * + * @default 0 + */ + checks?: number | undefined; + } + /** + * Checks the primality of the `candidate`. + * @since v15.8.0 + * @param candidate A possible prime encoded as a sequence of big endian octets of arbitrary length. + */ + function checkPrime(value: LargeNumberLike, callback: (err: Error | null, result: boolean) => void): void; + function checkPrime( + value: LargeNumberLike, + options: CheckPrimeOptions, + callback: (err: Error | null, result: boolean) => void, + ): void; + /** + * Checks the primality of the `candidate`. + * @since v15.8.0 + * @param candidate A possible prime encoded as a sequence of big endian octets of arbitrary length. + * @return `true` if the candidate is a prime with an error probability less than `0.25 ** options.checks`. + */ + function checkPrimeSync(candidate: LargeNumberLike, options?: CheckPrimeOptions): boolean; + /** + * Load and set the `engine` for some or all OpenSSL functions (selected by flags). + * + * `engine` could be either an id or a path to the engine's shared library. + * + * The optional `flags` argument uses `ENGINE_METHOD_ALL` by default. + * The `flags` is a bit field taking one of or a mix of the following flags (defined in `crypto.constants`): + * + * - `crypto.constants.ENGINE_METHOD_RSA` + * - `crypto.constants.ENGINE_METHOD_DSA` + * - `crypto.constants.ENGINE_METHOD_DH` + * - `crypto.constants.ENGINE_METHOD_RAND` + * - `crypto.constants.ENGINE_METHOD_EC` + * - `crypto.constants.ENGINE_METHOD_CIPHERS` + * - `crypto.constants.ENGINE_METHOD_DIGESTS` + * - `crypto.constants.ENGINE_METHOD_PKEY_METHS` + * - `crypto.constants.ENGINE_METHOD_PKEY_ASN1_METHS` + * - `crypto.constants.ENGINE_METHOD_ALL` + * - `crypto.constants.ENGINE_METHOD_NONE` + * + * The flags below are deprecated in OpenSSL-1.1.0. + * + * - `crypto.constants.ENGINE_METHOD_ECDH` + * - `crypto.constants.ENGINE_METHOD_ECDSA` + * - `crypto.constants.ENGINE_METHOD_STORE` + * @since v0.11.11 + * @param [flags=crypto.constants.ENGINE_METHOD_ALL] + */ + function setEngine(engine: string, flags?: number): void; + /** + * A convenient alias for `crypto.webcrypto.getRandomValues()`. + * This implementation is not compliant with the Web Crypto spec, + * to write web-compatible code use `crypto.webcrypto.getRandomValues()` instead. + * @since v17.4.0 + * @returns Returns `typedArray`. + */ + function getRandomValues(typedArray: T): T; + /** + * A convenient alias for `crypto.webcrypto.subtle`. + * @since v17.4.0 + */ + const subtle: webcrypto.SubtleCrypto; + /** + * An implementation of the Web Crypto API standard. + * + * See the {@link https://nodejs.org/docs/latest/api/webcrypto.html Web Crypto API documentation} for details. + * @since v15.0.0 + */ + const webcrypto: webcrypto.Crypto; + namespace webcrypto { + type BufferSource = ArrayBufferView | ArrayBuffer; + type KeyFormat = "jwk" | "pkcs8" | "raw" | "spki"; + type KeyType = "private" | "public" | "secret"; + type KeyUsage = + | "decrypt" + | "deriveBits" + | "deriveKey" + | "encrypt" + | "sign" + | "unwrapKey" + | "verify" + | "wrapKey"; + type AlgorithmIdentifier = Algorithm | string; + type HashAlgorithmIdentifier = AlgorithmIdentifier; + type NamedCurve = string; + type BigInteger = Uint8Array; + interface AesCbcParams extends Algorithm { + iv: BufferSource; + } + interface AesCtrParams extends Algorithm { + counter: BufferSource; + length: number; + } + interface AesDerivedKeyParams extends Algorithm { + length: number; + } + interface AesGcmParams extends Algorithm { + additionalData?: BufferSource; + iv: BufferSource; + tagLength?: number; + } + interface AesKeyAlgorithm extends KeyAlgorithm { + length: number; + } + interface AesKeyGenParams extends Algorithm { + length: number; + } + interface Algorithm { + name: string; + } + interface EcKeyAlgorithm extends KeyAlgorithm { + namedCurve: NamedCurve; + } + interface EcKeyGenParams extends Algorithm { + namedCurve: NamedCurve; + } + interface EcKeyImportParams extends Algorithm { + namedCurve: NamedCurve; + } + interface EcdhKeyDeriveParams extends Algorithm { + public: CryptoKey; + } + interface EcdsaParams extends Algorithm { + hash: HashAlgorithmIdentifier; + } + interface Ed448Params extends Algorithm { + context?: BufferSource; + } + interface HkdfParams extends Algorithm { + hash: HashAlgorithmIdentifier; + info: BufferSource; + salt: BufferSource; + } + interface HmacImportParams extends Algorithm { + hash: HashAlgorithmIdentifier; + length?: number; + } + interface HmacKeyAlgorithm extends KeyAlgorithm { + hash: KeyAlgorithm; + length: number; + } + interface HmacKeyGenParams extends Algorithm { + hash: HashAlgorithmIdentifier; + length?: number; + } + interface JsonWebKey { + alg?: string; + crv?: string; + d?: string; + dp?: string; + dq?: string; + e?: string; + ext?: boolean; + k?: string; + key_ops?: string[]; + kty?: string; + n?: string; + oth?: RsaOtherPrimesInfo[]; + p?: string; + q?: string; + qi?: string; + use?: string; + x?: string; + y?: string; + } + interface KeyAlgorithm { + name: string; + } + interface Pbkdf2Params extends Algorithm { + hash: HashAlgorithmIdentifier; + iterations: number; + salt: BufferSource; + } + interface RsaHashedImportParams extends Algorithm { + hash: HashAlgorithmIdentifier; + } + interface RsaHashedKeyAlgorithm extends RsaKeyAlgorithm { + hash: KeyAlgorithm; + } + interface RsaHashedKeyGenParams extends RsaKeyGenParams { + hash: HashAlgorithmIdentifier; + } + interface RsaKeyAlgorithm extends KeyAlgorithm { + modulusLength: number; + publicExponent: BigInteger; + } + interface RsaKeyGenParams extends Algorithm { + modulusLength: number; + publicExponent: BigInteger; + } + interface RsaOaepParams extends Algorithm { + label?: BufferSource; + } + interface RsaOtherPrimesInfo { + d?: string; + r?: string; + t?: string; + } + interface RsaPssParams extends Algorithm { + saltLength: number; + } + /** + * Calling `require('node:crypto').webcrypto` returns an instance of the `Crypto` class. + * `Crypto` is a singleton that provides access to the remainder of the crypto API. + * @since v15.0.0 + */ + interface Crypto { + /** + * Provides access to the `SubtleCrypto` API. + * @since v15.0.0 + */ + readonly subtle: SubtleCrypto; + /** + * Generates cryptographically strong random values. + * The given `typedArray` is filled with random values, and a reference to `typedArray` is returned. + * + * The given `typedArray` must be an integer-based instance of {@link NodeJS.TypedArray}, i.e. `Float32Array` and `Float64Array` are not accepted. + * + * An error will be thrown if the given `typedArray` is larger than 65,536 bytes. + * @since v15.0.0 + */ + getRandomValues>(typedArray: T): T; + /** + * Generates a random {@link https://www.rfc-editor.org/rfc/rfc4122.txt RFC 4122} version 4 UUID. + * The UUID is generated using a cryptographic pseudorandom number generator. + * @since v16.7.0 + */ + randomUUID(): UUID; + CryptoKey: CryptoKeyConstructor; + } + // This constructor throws ILLEGAL_CONSTRUCTOR so it should not be newable. + interface CryptoKeyConstructor { + /** Illegal constructor */ + (_: { readonly _: unique symbol }): never; // Allows instanceof to work but not be callable by the user. + readonly length: 0; + readonly name: "CryptoKey"; + readonly prototype: CryptoKey; + } + /** + * @since v15.0.0 + */ + interface CryptoKey { + /** + * An object detailing the algorithm for which the key can be used along with additional algorithm-specific parameters. + * @since v15.0.0 + */ + readonly algorithm: KeyAlgorithm; + /** + * When `true`, the {@link CryptoKey} can be extracted using either `subtleCrypto.exportKey()` or `subtleCrypto.wrapKey()`. + * @since v15.0.0 + */ + readonly extractable: boolean; + /** + * A string identifying whether the key is a symmetric (`'secret'`) or asymmetric (`'private'` or `'public'`) key. + * @since v15.0.0 + */ + readonly type: KeyType; + /** + * An array of strings identifying the operations for which the key may be used. + * + * The possible usages are: + * - `'encrypt'` - The key may be used to encrypt data. + * - `'decrypt'` - The key may be used to decrypt data. + * - `'sign'` - The key may be used to generate digital signatures. + * - `'verify'` - The key may be used to verify digital signatures. + * - `'deriveKey'` - The key may be used to derive a new key. + * - `'deriveBits'` - The key may be used to derive bits. + * - `'wrapKey'` - The key may be used to wrap another key. + * - `'unwrapKey'` - The key may be used to unwrap another key. + * + * Valid key usages depend on the key algorithm (identified by `cryptokey.algorithm.name`). + * @since v15.0.0 + */ + readonly usages: KeyUsage[]; + } + /** + * The `CryptoKeyPair` is a simple dictionary object with `publicKey` and `privateKey` properties, representing an asymmetric key pair. + * @since v15.0.0 + */ + interface CryptoKeyPair { + /** + * A {@link CryptoKey} whose type will be `'private'`. + * @since v15.0.0 + */ + privateKey: CryptoKey; + /** + * A {@link CryptoKey} whose type will be `'public'`. + * @since v15.0.0 + */ + publicKey: CryptoKey; + } + /** + * @since v15.0.0 + */ + interface SubtleCrypto { + /** + * Using the method and parameters specified in `algorithm` and the keying material provided by `key`, + * `subtle.decrypt()` attempts to decipher the provided `data`. If successful, + * the returned promise will be resolved with an `` containing the plaintext result. + * + * The algorithms currently supported include: + * + * - `'RSA-OAEP'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * @since v15.0.0 + */ + decrypt( + algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, + key: CryptoKey, + data: BufferSource, + ): Promise; + /** + * Using the method and parameters specified in `algorithm` and the keying material provided by `baseKey`, + * `subtle.deriveBits()` attempts to generate `length` bits. + * The Node.js implementation requires that when `length` is a number it must be multiple of `8`. + * When `length` is `null` the maximum number of bits for a given algorithm is generated. This is allowed + * for the `'ECDH'`, `'X25519'`, and `'X448'` algorithms. + * If successful, the returned promise will be resolved with an `` containing the generated data. + * + * The algorithms currently supported include: + * + * - `'ECDH'` + * - `'X25519'` + * - `'X448'` + * - `'HKDF'` + * - `'PBKDF2'` + * @since v15.0.0 + */ + deriveBits(algorithm: EcdhKeyDeriveParams, baseKey: CryptoKey, length: number | null): Promise; + deriveBits( + algorithm: AlgorithmIdentifier | HkdfParams | Pbkdf2Params, + baseKey: CryptoKey, + length: number, + ): Promise; + /** + * Using the method and parameters specified in `algorithm`, and the keying material provided by `baseKey`, + * `subtle.deriveKey()` attempts to generate a new ` based on the method and parameters in `derivedKeyAlgorithm`. + * + * Calling `subtle.deriveKey()` is equivalent to calling `subtle.deriveBits()` to generate raw keying material, + * then passing the result into the `subtle.importKey()` method using the `deriveKeyAlgorithm`, `extractable`, and `keyUsages` parameters as input. + * + * The algorithms currently supported include: + * + * - `'ECDH'` + * - `'X25519'` + * - `'X448'` + * - `'HKDF'` + * - `'PBKDF2'` + * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}. + * @since v15.0.0 + */ + deriveKey( + algorithm: AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params, + baseKey: CryptoKey, + derivedKeyAlgorithm: + | AlgorithmIdentifier + | AesDerivedKeyParams + | HmacImportParams + | HkdfParams + | Pbkdf2Params, + extractable: boolean, + keyUsages: readonly KeyUsage[], + ): Promise; + /** + * Using the method identified by `algorithm`, `subtle.digest()` attempts to generate a digest of `data`. + * If successful, the returned promise is resolved with an `` containing the computed digest. + * + * If `algorithm` is provided as a ``, it must be one of: + * + * - `'SHA-1'` + * - `'SHA-256'` + * - `'SHA-384'` + * - `'SHA-512'` + * + * If `algorithm` is provided as an ``, it must have a `name` property whose value is one of the above. + * @since v15.0.0 + */ + digest(algorithm: AlgorithmIdentifier, data: BufferSource): Promise; + /** + * Using the method and parameters specified by `algorithm` and the keying material provided by `key`, + * `subtle.encrypt()` attempts to encipher `data`. If successful, + * the returned promise is resolved with an `` containing the encrypted result. + * + * The algorithms currently supported include: + * + * - `'RSA-OAEP'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * @since v15.0.0 + */ + encrypt( + algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, + key: CryptoKey, + data: BufferSource, + ): Promise; + /** + * Exports the given key into the specified format, if supported. + * + * If the `` is not extractable, the returned promise will reject. + * + * When `format` is either `'pkcs8'` or `'spki'` and the export is successful, + * the returned promise will be resolved with an `` containing the exported key data. + * + * When `format` is `'jwk'` and the export is successful, the returned promise will be resolved with a + * JavaScript object conforming to the {@link https://tools.ietf.org/html/rfc7517 JSON Web Key} specification. + * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`. + * @returns `` containing ``. + * @since v15.0.0 + */ + exportKey(format: "jwk", key: CryptoKey): Promise; + exportKey(format: Exclude, key: CryptoKey): Promise; + /** + * Using the method and parameters provided in `algorithm`, + * `subtle.generateKey()` attempts to generate new keying material. + * Depending the method used, the method may generate either a single `` or a ``. + * + * The `` (public and private key) generating algorithms supported include: + * + * - `'RSASSA-PKCS1-v1_5'` + * - `'RSA-PSS'` + * - `'RSA-OAEP'` + * - `'ECDSA'` + * - `'Ed25519'` + * - `'Ed448'` + * - `'ECDH'` + * - `'X25519'` + * - `'X448'` + * The `` (secret key) generating algorithms supported include: + * + * - `'HMAC'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * - `'AES-KW'` + * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}. + * @since v15.0.0 + */ + generateKey( + algorithm: RsaHashedKeyGenParams | EcKeyGenParams, + extractable: boolean, + keyUsages: readonly KeyUsage[], + ): Promise; + generateKey( + algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params, + extractable: boolean, + keyUsages: readonly KeyUsage[], + ): Promise; + generateKey( + algorithm: AlgorithmIdentifier, + extractable: boolean, + keyUsages: KeyUsage[], + ): Promise; + /** + * The `subtle.importKey()` method attempts to interpret the provided `keyData` as the given `format` + * to create a `` instance using the provided `algorithm`, `extractable`, and `keyUsages` arguments. + * If the import is successful, the returned promise will be resolved with the created ``. + * + * If importing a `'PBKDF2'` key, `extractable` must be `false`. + * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`. + * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}. + * @since v15.0.0 + */ + importKey( + format: "jwk", + keyData: JsonWebKey, + algorithm: + | AlgorithmIdentifier + | RsaHashedImportParams + | EcKeyImportParams + | HmacImportParams + | AesKeyAlgorithm, + extractable: boolean, + keyUsages: readonly KeyUsage[], + ): Promise; + importKey( + format: Exclude, + keyData: BufferSource, + algorithm: + | AlgorithmIdentifier + | RsaHashedImportParams + | EcKeyImportParams + | HmacImportParams + | AesKeyAlgorithm, + extractable: boolean, + keyUsages: KeyUsage[], + ): Promise; + /** + * Using the method and parameters given by `algorithm` and the keying material provided by `key`, + * `subtle.sign()` attempts to generate a cryptographic signature of `data`. If successful, + * the returned promise is resolved with an `` containing the generated signature. + * + * The algorithms currently supported include: + * + * - `'RSASSA-PKCS1-v1_5'` + * - `'RSA-PSS'` + * - `'ECDSA'` + * - `'Ed25519'` + * - `'Ed448'` + * - `'HMAC'` + * @since v15.0.0 + */ + sign( + algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams | Ed448Params, + key: CryptoKey, + data: BufferSource, + ): Promise; + /** + * In cryptography, "wrapping a key" refers to exporting and then encrypting the keying material. + * The `subtle.unwrapKey()` method attempts to decrypt a wrapped key and create a `` instance. + * It is equivalent to calling `subtle.decrypt()` first on the encrypted key data (using the `wrappedKey`, `unwrapAlgo`, and `unwrappingKey` arguments as input) + * then passing the results in to the `subtle.importKey()` method using the `unwrappedKeyAlgo`, `extractable`, and `keyUsages` arguments as inputs. + * If successful, the returned promise is resolved with a `` object. + * + * The wrapping algorithms currently supported include: + * + * - `'RSA-OAEP'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * - `'AES-KW'` + * + * The unwrapped key algorithms supported include: + * + * - `'RSASSA-PKCS1-v1_5'` + * - `'RSA-PSS'` + * - `'RSA-OAEP'` + * - `'ECDSA'` + * - `'Ed25519'` + * - `'Ed448'` + * - `'ECDH'` + * - `'X25519'` + * - `'X448'` + * - `'HMAC'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * - `'AES-KW'` + * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`. + * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}. + * @since v15.0.0 + */ + unwrapKey( + format: KeyFormat, + wrappedKey: BufferSource, + unwrappingKey: CryptoKey, + unwrapAlgorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, + unwrappedKeyAlgorithm: + | AlgorithmIdentifier + | RsaHashedImportParams + | EcKeyImportParams + | HmacImportParams + | AesKeyAlgorithm, + extractable: boolean, + keyUsages: KeyUsage[], + ): Promise; + /** + * Using the method and parameters given in `algorithm` and the keying material provided by `key`, + * `subtle.verify()` attempts to verify that `signature` is a valid cryptographic signature of `data`. + * The returned promise is resolved with either `true` or `false`. + * + * The algorithms currently supported include: + * + * - `'RSASSA-PKCS1-v1_5'` + * - `'RSA-PSS'` + * - `'ECDSA'` + * - `'Ed25519'` + * - `'Ed448'` + * - `'HMAC'` + * @since v15.0.0 + */ + verify( + algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams | Ed448Params, + key: CryptoKey, + signature: BufferSource, + data: BufferSource, + ): Promise; + /** + * In cryptography, "wrapping a key" refers to exporting and then encrypting the keying material. + * The `subtle.wrapKey()` method exports the keying material into the format identified by `format`, + * then encrypts it using the method and parameters specified by `wrapAlgo` and the keying material provided by `wrappingKey`. + * It is the equivalent to calling `subtle.exportKey()` using `format` and `key` as the arguments, + * then passing the result to the `subtle.encrypt()` method using `wrappingKey` and `wrapAlgo` as inputs. + * If successful, the returned promise will be resolved with an `` containing the encrypted key data. + * + * The wrapping algorithms currently supported include: + * + * - `'RSA-OAEP'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * - `'AES-KW'` + * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`. + * @since v15.0.0 + */ + wrapKey( + format: KeyFormat, + key: CryptoKey, + wrappingKey: CryptoKey, + wrapAlgorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, + ): Promise; + } + } +} +declare module "node:crypto" { + export * from "crypto"; +} diff --git a/backend/node_modules/@types/node/dgram.d.ts b/backend/node_modules/@types/node/dgram.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..25a4f652d62f30bad9a97b0d7ad868f2c38772aa --- /dev/null +++ b/backend/node_modules/@types/node/dgram.d.ts @@ -0,0 +1,596 @@ +/** + * The `dgram` module provides an implementation of UDP datagram sockets. + * + * ```js + * import dgram from 'dgram'; + * + * const server = dgram.createSocket('udp4'); + * + * server.on('error', (err) => { + * console.log(`server error:\n${err.stack}`); + * server.close(); + * }); + * + * server.on('message', (msg, rinfo) => { + * console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); + * }); + * + * server.on('listening', () => { + * const address = server.address(); + * console.log(`server listening ${address.address}:${address.port}`); + * }); + * + * server.bind(41234); + * // Prints: server listening 0.0.0.0:41234 + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/dgram.js) + */ +declare module "dgram" { + import { AddressInfo } from "node:net"; + import * as dns from "node:dns"; + import { Abortable, EventEmitter } from "node:events"; + interface RemoteInfo { + address: string; + family: "IPv4" | "IPv6"; + port: number; + size: number; + } + interface BindOptions { + port?: number | undefined; + address?: string | undefined; + exclusive?: boolean | undefined; + fd?: number | undefined; + } + type SocketType = "udp4" | "udp6"; + interface SocketOptions extends Abortable { + type: SocketType; + reuseAddr?: boolean | undefined; + /** + * @default false + */ + ipv6Only?: boolean | undefined; + recvBufferSize?: number | undefined; + sendBufferSize?: number | undefined; + lookup?: + | (( + hostname: string, + options: dns.LookupOneOptions, + callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void, + ) => void) + | undefined; + } + /** + * Creates a `dgram.Socket` object. Once the socket is created, calling `socket.bind()` will instruct the socket to begin listening for datagram + * messages. When `address` and `port` are not passed to `socket.bind()` the + * method will bind the socket to the "all interfaces" address on a random port + * (it does the right thing for both `udp4` and `udp6` sockets). The bound address + * and port can be retrieved using `socket.address().address` and `socket.address().port`. + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.close()` on the socket: + * + * ```js + * const controller = new AbortController(); + * const { signal } = controller; + * const server = dgram.createSocket({ type: 'udp4', signal }); + * server.on('message', (msg, rinfo) => { + * console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); + * }); + * // Later, when you want to close the server. + * controller.abort(); + * ``` + * @since v0.11.13 + * @param options Available options are: + * @param callback Attached as a listener for `'message'` events. Optional. + */ + function createSocket(type: SocketType, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; + function createSocket(options: SocketOptions, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; + /** + * Encapsulates the datagram functionality. + * + * New instances of `dgram.Socket` are created using {@link createSocket}. + * The `new` keyword is not to be used to create `dgram.Socket` instances. + * @since v0.1.99 + */ + class Socket extends EventEmitter { + /** + * Tells the kernel to join a multicast group at the given `multicastAddress` and`multicastInterface` using the `IP_ADD_MEMBERSHIP` socket option. If the`multicastInterface` argument is not + * specified, the operating system will choose + * one interface and will add membership to it. To add membership to every + * available interface, call `addMembership` multiple times, once per interface. + * + * When called on an unbound socket, this method will implicitly bind to a random + * port, listening on all interfaces. + * + * When sharing a UDP socket across multiple `cluster` workers, the`socket.addMembership()` function must be called only once or an`EADDRINUSE` error will occur: + * + * ```js + * import cluster from 'cluster'; + * import dgram from 'dgram'; + * + * if (cluster.isPrimary) { + * cluster.fork(); // Works ok. + * cluster.fork(); // Fails with EADDRINUSE. + * } else { + * const s = dgram.createSocket('udp4'); + * s.bind(1234, () => { + * s.addMembership('224.0.0.114'); + * }); + * } + * ``` + * @since v0.6.9 + */ + addMembership(multicastAddress: string, multicastInterface?: string): void; + /** + * Returns an object containing the address information for a socket. + * For UDP sockets, this object will contain `address`, `family` and `port`properties. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.1.99 + */ + address(): AddressInfo; + /** + * For UDP sockets, causes the `dgram.Socket` to listen for datagram + * messages on a named `port` and optional `address`. If `port` is not + * specified or is `0`, the operating system will attempt to bind to a + * random port. If `address` is not specified, the operating system will + * attempt to listen on all addresses. Once binding is complete, a`'listening'` event is emitted and the optional `callback` function is + * called. + * + * Specifying both a `'listening'` event listener and passing a`callback` to the `socket.bind()` method is not harmful but not very + * useful. + * + * A bound datagram socket keeps the Node.js process running to receive + * datagram messages. + * + * If binding fails, an `'error'` event is generated. In rare case (e.g. + * attempting to bind with a closed socket), an `Error` may be thrown. + * + * Example of a UDP server listening on port 41234: + * + * ```js + * import dgram from 'dgram'; + * + * const server = dgram.createSocket('udp4'); + * + * server.on('error', (err) => { + * console.log(`server error:\n${err.stack}`); + * server.close(); + * }); + * + * server.on('message', (msg, rinfo) => { + * console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); + * }); + * + * server.on('listening', () => { + * const address = server.address(); + * console.log(`server listening ${address.address}:${address.port}`); + * }); + * + * server.bind(41234); + * // Prints: server listening 0.0.0.0:41234 + * ``` + * @since v0.1.99 + * @param callback with no parameters. Called when binding is complete. + */ + bind(port?: number, address?: string, callback?: () => void): this; + bind(port?: number, callback?: () => void): this; + bind(callback?: () => void): this; + bind(options: BindOptions, callback?: () => void): this; + /** + * Close the underlying socket and stop listening for data on it. If a callback is + * provided, it is added as a listener for the `'close'` event. + * @since v0.1.99 + * @param callback Called when the socket has been closed. + */ + close(callback?: () => void): this; + /** + * Associates the `dgram.Socket` to a remote address and port. Every + * message sent by this handle is automatically sent to that destination. Also, + * the socket will only receive messages from that remote peer. + * Trying to call `connect()` on an already connected socket will result + * in an `ERR_SOCKET_DGRAM_IS_CONNECTED` exception. If `address` is not + * provided, `'127.0.0.1'` (for `udp4` sockets) or `'::1'` (for `udp6` sockets) + * will be used by default. Once the connection is complete, a `'connect'` event + * is emitted and the optional `callback` function is called. In case of failure, + * the `callback` is called or, failing this, an `'error'` event is emitted. + * @since v12.0.0 + * @param callback Called when the connection is completed or on error. + */ + connect(port: number, address?: string, callback?: () => void): void; + connect(port: number, callback: () => void): void; + /** + * A synchronous function that disassociates a connected `dgram.Socket` from + * its remote address. Trying to call `disconnect()` on an unbound or already + * disconnected socket will result in an `ERR_SOCKET_DGRAM_NOT_CONNECTED` exception. + * @since v12.0.0 + */ + disconnect(): void; + /** + * Instructs the kernel to leave a multicast group at `multicastAddress` using the`IP_DROP_MEMBERSHIP` socket option. This method is automatically called by the + * kernel when the socket is closed or the process terminates, so most apps will + * never have reason to call this. + * + * If `multicastInterface` is not specified, the operating system will attempt to + * drop membership on all valid interfaces. + * @since v0.6.9 + */ + dropMembership(multicastAddress: string, multicastInterface?: string): void; + /** + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + * @return the `SO_RCVBUF` socket receive buffer size in bytes. + */ + getRecvBufferSize(): number; + /** + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + * @return the `SO_SNDBUF` socket send buffer size in bytes. + */ + getSendBufferSize(): number; + /** + * @since v18.8.0 + * @return the number of bytes queued for sending. + */ + getSendQueueSize(): number; + /** + * @since v18.8.0 + * @return the number of send requests currently in the queue awaiting to be processed. + */ + getSendQueueCount(): number; + /** + * By default, binding a socket will cause it to block the Node.js process from + * exiting as long as the socket is open. The `socket.unref()` method can be used + * to exclude the socket from the reference counting that keeps the Node.js + * process active. The `socket.ref()` method adds the socket back to the reference + * counting and restores the default behavior. + * + * Calling `socket.ref()` multiples times will have no additional effect. + * + * The `socket.ref()` method returns a reference to the socket so calls can be + * chained. + * @since v0.9.1 + */ + ref(): this; + /** + * Returns an object containing the `address`, `family`, and `port` of the remote + * endpoint. This method throws an `ERR_SOCKET_DGRAM_NOT_CONNECTED` exception + * if the socket is not connected. + * @since v12.0.0 + */ + remoteAddress(): AddressInfo; + /** + * Broadcasts a datagram on the socket. + * For connectionless sockets, the destination `port` and `address` must be + * specified. Connected sockets, on the other hand, will use their associated + * remote endpoint, so the `port` and `address` arguments must not be set. + * + * The `msg` argument contains the message to be sent. + * Depending on its type, different behavior can apply. If `msg` is a `Buffer`, + * any `TypedArray` or a `DataView`, + * the `offset` and `length` specify the offset within the `Buffer` where the + * message begins and the number of bytes in the message, respectively. + * If `msg` is a `String`, then it is automatically converted to a `Buffer`with `'utf8'` encoding. With messages that + * contain multi-byte characters, `offset` and `length` will be calculated with + * respect to `byte length` and not the character position. + * If `msg` is an array, `offset` and `length` must not be specified. + * + * The `address` argument is a string. If the value of `address` is a host name, + * DNS will be used to resolve the address of the host. If `address` is not + * provided or otherwise nullish, `'127.0.0.1'` (for `udp4` sockets) or `'::1'`(for `udp6` sockets) will be used by default. + * + * If the socket has not been previously bound with a call to `bind`, the socket + * is assigned a random port number and is bound to the "all interfaces" address + * (`'0.0.0.0'` for `udp4` sockets, `'::0'` for `udp6` sockets.) + * + * An optional `callback` function may be specified to as a way of reporting + * DNS errors or for determining when it is safe to reuse the `buf` object. + * DNS lookups delay the time to send for at least one tick of the + * Node.js event loop. + * + * The only way to know for sure that the datagram has been sent is by using a`callback`. If an error occurs and a `callback` is given, the error will be + * passed as the first argument to the `callback`. If a `callback` is not given, + * the error is emitted as an `'error'` event on the `socket` object. + * + * Offset and length are optional but both _must_ be set if either are used. + * They are supported only when the first argument is a `Buffer`, a `TypedArray`, + * or a `DataView`. + * + * This method throws `ERR_SOCKET_BAD_PORT` if called on an unbound socket. + * + * Example of sending a UDP packet to a port on `localhost`; + * + * ```js + * import dgram from 'dgram'; + * import { Buffer } from 'buffer'; + * + * const message = Buffer.from('Some bytes'); + * const client = dgram.createSocket('udp4'); + * client.send(message, 41234, 'localhost', (err) => { + * client.close(); + * }); + * ``` + * + * Example of sending a UDP packet composed of multiple buffers to a port on`127.0.0.1`; + * + * ```js + * import dgram from 'dgram'; + * import { Buffer } from 'buffer'; + * + * const buf1 = Buffer.from('Some '); + * const buf2 = Buffer.from('bytes'); + * const client = dgram.createSocket('udp4'); + * client.send([buf1, buf2], 41234, (err) => { + * client.close(); + * }); + * ``` + * + * Sending multiple buffers might be faster or slower depending on the + * application and operating system. Run benchmarks to + * determine the optimal strategy on a case-by-case basis. Generally speaking, + * however, sending multiple buffers is faster. + * + * Example of sending a UDP packet using a socket connected to a port on`localhost`: + * + * ```js + * import dgram from 'dgram'; + * import { Buffer } from 'buffer'; + * + * const message = Buffer.from('Some bytes'); + * const client = dgram.createSocket('udp4'); + * client.connect(41234, 'localhost', (err) => { + * client.send(message, (err) => { + * client.close(); + * }); + * }); + * ``` + * @since v0.1.99 + * @param msg Message to be sent. + * @param offset Offset in the buffer where the message starts. + * @param length Number of bytes in the message. + * @param port Destination port. + * @param address Destination host name or IP address. + * @param callback Called when the message has been sent. + */ + send( + msg: string | Uint8Array | readonly any[], + port?: number, + address?: string, + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | Uint8Array | readonly any[], + port?: number, + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | Uint8Array | readonly any[], + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | Uint8Array, + offset: number, + length: number, + port?: number, + address?: string, + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | Uint8Array, + offset: number, + length: number, + port?: number, + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | Uint8Array, + offset: number, + length: number, + callback?: (error: Error | null, bytes: number) => void, + ): void; + /** + * Sets or clears the `SO_BROADCAST` socket option. When set to `true`, UDP + * packets may be sent to a local interface's broadcast address. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.6.9 + */ + setBroadcast(flag: boolean): void; + /** + * _All references to scope in this section are referring to [IPv6 Zone Indices](https://en.wikipedia.org/wiki/IPv6_address#Scoped_literal_IPv6_addresses), which are defined by [RFC + * 4007](https://tools.ietf.org/html/rfc4007). In string form, an IP_ + * _with a scope index is written as `'IP%scope'` where scope is an interface name_ + * _or interface number._ + * + * Sets the default outgoing multicast interface of the socket to a chosen + * interface or back to system interface selection. The `multicastInterface` must + * be a valid string representation of an IP from the socket's family. + * + * For IPv4 sockets, this should be the IP configured for the desired physical + * interface. All packets sent to multicast on the socket will be sent on the + * interface determined by the most recent successful use of this call. + * + * For IPv6 sockets, `multicastInterface` should include a scope to indicate the + * interface as in the examples that follow. In IPv6, individual `send` calls can + * also use explicit scope in addresses, so only packets sent to a multicast + * address without specifying an explicit scope are affected by the most recent + * successful use of this call. + * + * This method throws `EBADF` if called on an unbound socket. + * + * #### Example: IPv6 outgoing multicast interface + * + * On most systems, where scope format uses the interface name: + * + * ```js + * const socket = dgram.createSocket('udp6'); + * + * socket.bind(1234, () => { + * socket.setMulticastInterface('::%eth1'); + * }); + * ``` + * + * On Windows, where scope format uses an interface number: + * + * ```js + * const socket = dgram.createSocket('udp6'); + * + * socket.bind(1234, () => { + * socket.setMulticastInterface('::%2'); + * }); + * ``` + * + * #### Example: IPv4 outgoing multicast interface + * + * All systems use an IP of the host on the desired physical interface: + * + * ```js + * const socket = dgram.createSocket('udp4'); + * + * socket.bind(1234, () => { + * socket.setMulticastInterface('10.0.0.2'); + * }); + * ``` + * @since v8.6.0 + */ + setMulticastInterface(multicastInterface: string): void; + /** + * Sets or clears the `IP_MULTICAST_LOOP` socket option. When set to `true`, + * multicast packets will also be received on the local interface. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.3.8 + */ + setMulticastLoopback(flag: boolean): boolean; + /** + * Sets the `IP_MULTICAST_TTL` socket option. While TTL generally stands for + * "Time to Live", in this context it specifies the number of IP hops that a + * packet is allowed to travel through, specifically for multicast traffic. Each + * router or gateway that forwards a packet decrements the TTL. If the TTL is + * decremented to 0 by a router, it will not be forwarded. + * + * The `ttl` argument may be between 0 and 255\. The default on most systems is `1`. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.3.8 + */ + setMulticastTTL(ttl: number): number; + /** + * Sets the `SO_RCVBUF` socket option. Sets the maximum socket receive buffer + * in bytes. + * + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + */ + setRecvBufferSize(size: number): void; + /** + * Sets the `SO_SNDBUF` socket option. Sets the maximum socket send buffer + * in bytes. + * + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + */ + setSendBufferSize(size: number): void; + /** + * Sets the `IP_TTL` socket option. While TTL generally stands for "Time to Live", + * in this context it specifies the number of IP hops that a packet is allowed to + * travel through. Each router or gateway that forwards a packet decrements the + * TTL. If the TTL is decremented to 0 by a router, it will not be forwarded. + * Changing TTL values is typically done for network probes or when multicasting. + * + * The `ttl` argument may be between 1 and 255\. The default on most systems + * is 64. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.1.101 + */ + setTTL(ttl: number): number; + /** + * By default, binding a socket will cause it to block the Node.js process from + * exiting as long as the socket is open. The `socket.unref()` method can be used + * to exclude the socket from the reference counting that keeps the Node.js + * process active, allowing the process to exit even if the socket is still + * listening. + * + * Calling `socket.unref()` multiple times will have no addition effect. + * + * The `socket.unref()` method returns a reference to the socket so calls can be + * chained. + * @since v0.9.1 + */ + unref(): this; + /** + * Tells the kernel to join a source-specific multicast channel at the given`sourceAddress` and `groupAddress`, using the `multicastInterface` with the`IP_ADD_SOURCE_MEMBERSHIP` socket + * option. If the `multicastInterface` argument + * is not specified, the operating system will choose one interface and will add + * membership to it. To add membership to every available interface, call`socket.addSourceSpecificMembership()` multiple times, once per interface. + * + * When called on an unbound socket, this method will implicitly bind to a random + * port, listening on all interfaces. + * @since v13.1.0, v12.16.0 + */ + addSourceSpecificMembership(sourceAddress: string, groupAddress: string, multicastInterface?: string): void; + /** + * Instructs the kernel to leave a source-specific multicast channel at the given`sourceAddress` and `groupAddress` using the `IP_DROP_SOURCE_MEMBERSHIP`socket option. This method is + * automatically called by the kernel when the + * socket is closed or the process terminates, so most apps will never have + * reason to call this. + * + * If `multicastInterface` is not specified, the operating system will attempt to + * drop membership on all valid interfaces. + * @since v13.1.0, v12.16.0 + */ + dropSourceSpecificMembership(sourceAddress: string, groupAddress: string, multicastInterface?: string): void; + /** + * events.EventEmitter + * 1. close + * 2. connect + * 3. error + * 4. listening + * 5. message + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "connect", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + addListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "connect"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + emit(event: "message", msg: Buffer, rinfo: RemoteInfo): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "connect", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + on(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "connect", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + once(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "connect", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + prependListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "connect", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + prependOnceListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + /** + * Calls `socket.close()` and returns a promise that fulfills when the socket has closed. + * @since v18.18.0 + */ + [Symbol.asyncDispose](): Promise; + } +} +declare module "node:dgram" { + export * from "dgram"; +} diff --git a/backend/node_modules/@types/node/diagnostics_channel.d.ts b/backend/node_modules/@types/node/diagnostics_channel.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e5f1202b4dddaafb4b69753d76bcf16e472a47b0 --- /dev/null +++ b/backend/node_modules/@types/node/diagnostics_channel.d.ts @@ -0,0 +1,546 @@ +/** + * The `diagnostics_channel` module provides an API to create named channels + * to report arbitrary message data for diagnostics purposes. + * + * It can be accessed using: + * + * ```js + * import diagnostics_channel from 'diagnostics_channel'; + * ``` + * + * It is intended that a module writer wanting to report diagnostics messages + * will create one or many top-level channels to report messages through. + * Channels may also be acquired at runtime but it is not encouraged + * due to the additional overhead of doing so. Channels may be exported for + * convenience, but as long as the name is known it can be acquired anywhere. + * + * If you intend for your module to produce diagnostics data for others to + * consume it is recommended that you include documentation of what named + * channels are used along with the shape of the message data. Channel names + * should generally include the module name to avoid collisions with data from + * other modules. + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/diagnostics_channel.js) + */ +declare module "diagnostics_channel" { + import { AsyncLocalStorage } from "node:async_hooks"; + /** + * Check if there are active subscribers to the named channel. This is helpful if + * the message you want to send might be expensive to prepare. + * + * This API is optional but helpful when trying to publish messages from very + * performance-sensitive code. + * + * ```js + * import diagnostics_channel from 'diagnostics_channel'; + * + * if (diagnostics_channel.hasSubscribers('my-channel')) { + * // There are subscribers, prepare and publish message + * } + * ``` + * @since v15.1.0, v14.17.0 + * @param name The channel name + * @return If there are active subscribers + */ + function hasSubscribers(name: string | symbol): boolean; + /** + * This is the primary entry-point for anyone wanting to interact with a named + * channel. It produces a channel object which is optimized to reduce overhead at + * publish time as much as possible. + * + * ```js + * import diagnostics_channel from 'diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * ``` + * @since v15.1.0, v14.17.0 + * @param name The channel name + * @return The named channel object + */ + function channel(name: string | symbol): Channel; + type ChannelListener = (message: unknown, name: string | symbol) => void; + /** + * Register a message handler to subscribe to this channel. This message handler will be run synchronously + * whenever a message is published to the channel. Any errors thrown in the message handler will + * trigger an 'uncaughtException'. + * + * ```js + * import diagnostics_channel from 'diagnostics_channel'; + * + * diagnostics_channel.subscribe('my-channel', (message, name) => { + * // Received data + * }); + * ``` + * + * @since v18.7.0, v16.17.0 + * @param name The channel name + * @param onMessage The handler to receive channel messages + */ + function subscribe(name: string | symbol, onMessage: ChannelListener): void; + /** + * Remove a message handler previously registered to this channel with diagnostics_channel.subscribe(name, onMessage). + * + * ```js + * import diagnostics_channel from 'diagnostics_channel'; + * + * function onMessage(message, name) { + * // Received data + * } + * + * diagnostics_channel.subscribe('my-channel', onMessage); + * + * diagnostics_channel.unsubscribe('my-channel', onMessage); + * ``` + * + * @since v18.7.0, v16.17.0 + * @param name The channel name + * @param onMessage The previous subscribed handler to remove + * @returns `true` if the handler was found, `false` otherwise + */ + function unsubscribe(name: string | symbol, onMessage: ChannelListener): boolean; + /** + * Creates a `TracingChannel` wrapper for the given `TracingChannel Channels`. If a name is given, the corresponding tracing + * channels will be created in the form of `tracing:${name}:${eventType}` where`eventType` corresponds to the types of `TracingChannel Channels`. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channelsByName = diagnostics_channel.tracingChannel('my-channel'); + * + * // or... + * + * const channelsByCollection = diagnostics_channel.tracingChannel({ + * start: diagnostics_channel.channel('tracing:my-channel:start'), + * end: diagnostics_channel.channel('tracing:my-channel:end'), + * asyncStart: diagnostics_channel.channel('tracing:my-channel:asyncStart'), + * asyncEnd: diagnostics_channel.channel('tracing:my-channel:asyncEnd'), + * error: diagnostics_channel.channel('tracing:my-channel:error'), + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param nameOrChannels Channel name or object containing all the `TracingChannel Channels` + * @return Collection of channels to trace with + */ + function tracingChannel< + StoreType = unknown, + ContextType extends object = StoreType extends object ? StoreType : object, + >( + nameOrChannels: string | TracingChannelCollection, + ): TracingChannel; + /** + * The class `Channel` represents an individual named channel within the data + * pipeline. It is use to track subscribers and to publish messages when there + * are subscribers present. It exists as a separate object to avoid channel + * lookups at publish time, enabling very fast publish speeds and allowing + * for heavy use while incurring very minimal cost. Channels are created with {@link channel}, constructing a channel directly + * with `new Channel(name)` is not supported. + * @since v15.1.0, v14.17.0 + */ + class Channel { + readonly name: string | symbol; + /** + * Check if there are active subscribers to this channel. This is helpful if + * the message you want to send might be expensive to prepare. + * + * This API is optional but helpful when trying to publish messages from very + * performance-sensitive code. + * + * ```js + * import diagnostics_channel from 'diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * if (channel.hasSubscribers) { + * // There are subscribers, prepare and publish message + * } + * ``` + * @since v15.1.0, v14.17.0 + */ + readonly hasSubscribers: boolean; + private constructor(name: string | symbol); + /** + * Publish a message to any subscribers to the channel. This will + * trigger message handlers synchronously so they will execute within + * the same context. + * + * ```js + * import diagnostics_channel from 'diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.publish({ + * some: 'message' + * }); + * ``` + * @since v15.1.0, v14.17.0 + * @param message The message to send to the channel subscribers + */ + publish(message: unknown): void; + /** + * Register a message handler to subscribe to this channel. This message handler + * will be run synchronously whenever a message is published to the channel. Any + * errors thrown in the message handler will trigger an `'uncaughtException'`. + * + * ```js + * import diagnostics_channel from 'diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.subscribe((message, name) => { + * // Received data + * }); + * ``` + * @since v15.1.0, v14.17.0 + * @param onMessage The handler to receive channel messages + */ + subscribe(onMessage: ChannelListener): void; + /** + * Remove a message handler previously registered to this channel with `channel.subscribe(onMessage)`. + * + * ```js + * import diagnostics_channel from 'diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * function onMessage(message, name) { + * // Received data + * } + * + * channel.subscribe(onMessage); + * + * channel.unsubscribe(onMessage); + * ``` + * @since v15.1.0, v14.17.0 + * @param onMessage The previous subscribed handler to remove + * @return `true` if the handler was found, `false` otherwise. + */ + unsubscribe(onMessage: ChannelListener): void; + /** + * When `channel.runStores(context, ...)` is called, the given context data + * will be applied to any store bound to the channel. If the store has already been + * bound the previous `transform` function will be replaced with the new one. + * The `transform` function may be omitted to set the given context data as the + * context directly. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * import { AsyncLocalStorage } from 'node:async_hooks'; + * + * const store = new AsyncLocalStorage(); + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.bindStore(store, (data) => { + * return { data }; + * }); + * ``` + * @since v18.19.0 + * @experimental + * @param store The store to which to bind the context data + * @param transform Transform context data before setting the store context + */ + bindStore(store: AsyncLocalStorage, transform?: (context: ContextType) => StoreType): void; + /** + * Remove a message handler previously registered to this channel with `channel.bindStore(store)`. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * import { AsyncLocalStorage } from 'node:async_hooks'; + * + * const store = new AsyncLocalStorage(); + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.bindStore(store); + * channel.unbindStore(store); + * ``` + * @since v18.19.0 + * @experimental + * @param store The store to unbind from the channel. + * @return `true` if the store was found, `false` otherwise. + */ + unbindStore(store: any): void; + /** + * Applies the given data to any AsyncLocalStorage instances bound to the channel + * for the duration of the given function, then publishes to the channel within + * the scope of that data is applied to the stores. + * + * If a transform function was given to `channel.bindStore(store)` it will be + * applied to transform the message data before it becomes the context value for + * the store. The prior storage context is accessible from within the transform + * function in cases where context linking is required. + * + * The context applied to the store should be accessible in any async code which + * continues from execution which began during the given function, however + * there are some situations in which `context loss` may occur. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * import { AsyncLocalStorage } from 'node:async_hooks'; + * + * const store = new AsyncLocalStorage(); + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.bindStore(store, (message) => { + * const parent = store.getStore(); + * return new Span(message, parent); + * }); + * channel.runStores({ some: 'message' }, () => { + * store.getStore(); // Span({ some: 'message' }) + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param context Message to send to subscribers and bind to stores + * @param fn Handler to run within the entered storage context + * @param thisArg The receiver to be used for the function call. + * @param args Optional arguments to pass to the function. + */ + runStores(): void; + } + interface TracingChannelSubscribers { + start: (message: ContextType) => void; + end: ( + message: ContextType & { + error?: unknown; + result?: unknown; + }, + ) => void; + asyncStart: ( + message: ContextType & { + error?: unknown; + result?: unknown; + }, + ) => void; + asyncEnd: ( + message: ContextType & { + error?: unknown; + result?: unknown; + }, + ) => void; + error: ( + message: ContextType & { + error: unknown; + }, + ) => void; + } + interface TracingChannelCollection { + start: Channel; + end: Channel; + asyncStart: Channel; + asyncEnd: Channel; + error: Channel; + } + /** + * The class `TracingChannel` is a collection of `TracingChannel Channels` which + * together express a single traceable action. It is used to formalize and + * simplify the process of producing events for tracing application flow.{@link tracingChannel} is used to construct a`TracingChannel`. As with `Channel` it is recommended to create and reuse a + * single `TracingChannel` at the top-level of the file rather than creating them + * dynamically. + * @since v18.19.0 + * @experimental + */ + class TracingChannel implements TracingChannelCollection { + start: Channel; + end: Channel; + asyncStart: Channel; + asyncEnd: Channel; + error: Channel; + /** + * Helper to subscribe a collection of functions to the corresponding channels. + * This is the same as calling `channel.subscribe(onMessage)` on each channel + * individually. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * channels.subscribe({ + * start(message) { + * // Handle start message + * }, + * end(message) { + * // Handle end message + * }, + * asyncStart(message) { + * // Handle asyncStart message + * }, + * asyncEnd(message) { + * // Handle asyncEnd message + * }, + * error(message) { + * // Handle error message + * }, + * }); + * ``` + * @since v18.19.0 + * @experimental + * @param subscribers Set of `TracingChannel Channels` subscribers + */ + subscribe(subscribers: TracingChannelSubscribers): void; + /** + * Helper to unsubscribe a collection of functions from the corresponding channels. + * This is the same as calling `channel.unsubscribe(onMessage)` on each channel + * individually. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * channels.unsubscribe({ + * start(message) { + * // Handle start message + * }, + * end(message) { + * // Handle end message + * }, + * asyncStart(message) { + * // Handle asyncStart message + * }, + * asyncEnd(message) { + * // Handle asyncEnd message + * }, + * error(message) { + * // Handle error message + * }, + * }); + * ``` + * @since v18.19.0 + * @experimental + * @param subscribers Set of `TracingChannel Channels` subscribers + * @return `true` if all handlers were successfully unsubscribed, and `false` otherwise. + */ + unsubscribe(subscribers: TracingChannelSubscribers): void; + /** + * Trace a synchronous function call. This will always produce a `start event` and `end event` around the execution and may produce an `error event` if the given function throws an error. + * This will run the given function using `channel.runStores(context, ...)` on the `start` channel which ensures all + * events should have any bound stores set to match this trace context. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * channels.traceSync(() => { + * // Do something + * }, { + * some: 'thing', + * }); + * ``` + * @since v18.19.0 + * @experimental + * @param fn Function to wrap a trace around + * @param context Shared object to correlate events through + * @param thisArg The receiver to be used for the function call + * @param args Optional arguments to pass to the function + * @return The return value of the given function + */ + traceSync( + fn: (this: ThisArg, ...args: Args) => any, + context?: ContextType, + thisArg?: ThisArg, + ...args: Args + ): void; + /** + * Trace a promise-returning function call. This will always produce a `start event` and `end event` around the synchronous portion of the + * function execution, and will produce an `asyncStart event` and `asyncEnd event` when a promise continuation is reached. It may also + * produce an `error event` if the given function throws an error or the + * returned promise rejects. This will run the given function using `channel.runStores(context, ...)` on the `start` channel which ensures all + * events should have any bound stores set to match this trace context. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * channels.tracePromise(async () => { + * // Do something + * }, { + * some: 'thing', + * }); + * ``` + * @since v18.19.0 + * @experimental + * @param fn Promise-returning function to wrap a trace around + * @param context Shared object to correlate trace events through + * @param thisArg The receiver to be used for the function call + * @param args Optional arguments to pass to the function + * @return Chained from promise returned by the given function + */ + tracePromise( + fn: (this: ThisArg, ...args: Args) => Promise, + context?: ContextType, + thisArg?: ThisArg, + ...args: Args + ): void; + /** + * Trace a callback-receiving function call. This will always produce a `start event` and `end event` around the synchronous portion of the + * function execution, and will produce a `asyncStart event` and `asyncEnd event` around the callback execution. It may also produce an `error event` if the given function throws an error or + * the returned + * promise rejects. This will run the given function using `channel.runStores(context, ...)` on the `start` channel which ensures all + * events should have any bound stores set to match this trace context. + * + * The `position` will be -1 by default to indicate the final argument should + * be used as the callback. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * channels.traceCallback((arg1, callback) => { + * // Do something + * callback(null, 'result'); + * }, 1, { + * some: 'thing', + * }, thisArg, arg1, callback); + * ``` + * + * The callback will also be run with `channel.runStores(context, ...)` which + * enables context loss recovery in some cases. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * import { AsyncLocalStorage } from 'node:async_hooks'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * const myStore = new AsyncLocalStorage(); + * + * // The start channel sets the initial store data to something + * // and stores that store data value on the trace context object + * channels.start.bindStore(myStore, (data) => { + * const span = new Span(data); + * data.span = span; + * return span; + * }); + * + * // Then asyncStart can restore from that data it stored previously + * channels.asyncStart.bindStore(myStore, (data) => { + * return data.span; + * }); + * ``` + * @since v18.19.0 + * @experimental + * @param fn callback using function to wrap a trace around + * @param position Zero-indexed argument position of expected callback + * @param context Shared object to correlate trace events through + * @param thisArg The receiver to be used for the function call + * @param args Optional arguments to pass to the function + * @return The return value of the given function + */ + traceCallback any>( + fn: Fn, + position: number | undefined, + context: ContextType | undefined, + thisArg: any, + ...args: Parameters + ): void; + } +} +declare module "node:diagnostics_channel" { + export * from "diagnostics_channel"; +} diff --git a/backend/node_modules/@types/node/dns.d.ts b/backend/node_modules/@types/node/dns.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6767cf66ff49cac92c3c75b9b8e39943a87d9e21 --- /dev/null +++ b/backend/node_modules/@types/node/dns.d.ts @@ -0,0 +1,853 @@ +/** + * The `node:dns` module enables name resolution. For example, use it to look up IP + * addresses of host names. + * + * Although named for the [Domain Name System (DNS)](https://en.wikipedia.org/wiki/Domain_Name_System), it does not always use the + * DNS protocol for lookups. {@link lookup} uses the operating system + * facilities to perform name resolution. It may not need to perform any network + * communication. To perform name resolution the way other applications on the same + * system do, use {@link lookup}. + * + * ```js + * const dns = require('node:dns'); + * + * dns.lookup('example.org', (err, address, family) => { + * console.log('address: %j family: IPv%s', address, family); + * }); + * // address: "93.184.216.34" family: IPv4 + * ``` + * + * All other functions in the `node:dns` module connect to an actual DNS server to + * perform name resolution. They will always use the network to perform DNS + * queries. These functions do not use the same set of configuration files used by {@link lookup} (e.g. `/etc/hosts`). Use these functions to always perform + * DNS queries, bypassing other name-resolution facilities. + * + * ```js + * const dns = require('node:dns'); + * + * dns.resolve4('archive.org', (err, addresses) => { + * if (err) throw err; + * + * console.log(`addresses: ${JSON.stringify(addresses)}`); + * + * addresses.forEach((a) => { + * dns.reverse(a, (err, hostnames) => { + * if (err) { + * throw err; + * } + * console.log(`reverse for ${a}: ${JSON.stringify(hostnames)}`); + * }); + * }); + * }); + * ``` + * + * See the [Implementation considerations section](https://nodejs.org/docs/latest-v18.x/api/dns.html#implementation-considerations) for more information. + * @see [source](https://github.com/nodejs/node/blob/v18.19.1/lib/dns.js) + */ +declare module "dns" { + import * as dnsPromises from "node:dns/promises"; + // Supported getaddrinfo flags. + /** + * Limits returned address types to the types of non-loopback addresses configured on the system. For example, IPv4 addresses are + * only returned if the current system has at least one IPv4 address configured. + */ + export const ADDRCONFIG: number; + /** + * If the IPv6 family was specified, but no IPv6 addresses were found, then return IPv4 mapped IPv6 addresses. It is not supported + * on some operating systems (e.g. FreeBSD 10.1). + */ + export const V4MAPPED: number; + /** + * If `dns.V4MAPPED` is specified, return resolved IPv6 addresses as + * well as IPv4 mapped IPv6 addresses. + */ + export const ALL: number; + export interface LookupOptions { + /** + * The record family. Must be `4`, `6`, or `0`. For backward compatibility reasons,`'IPv4'` and `'IPv6'` are interpreted + * as `4` and `6` respectively. The value 0 indicates that either an IPv4 or IPv6 address is returned. If the value `0` is used + * with `{ all: true } (see below)`, both IPv4 and IPv6 addresses are returned. + * @default 0 + */ + family?: number | "IPv4" | "IPv6" | undefined; + /** + * One or more [supported `getaddrinfo`](https://nodejs.org/docs/latest-v18.x/api/dns.html#supported-getaddrinfo-flags) flags. Multiple flags may be + * passed by bitwise `OR`ing their values. + */ + hints?: number | undefined; + /** + * When `true`, the callback returns all resolved addresses in an array. Otherwise, returns a single address. + * @default false + */ + all?: boolean | undefined; + /** + * When `true`, the callback receives IPv4 and IPv6 addresses in the order the DNS resolver returned them. When `false`, IPv4 + * addresses are placed before IPv6 addresses. Default value is configurable using {@link setDefaultResultOrder()} + * or [`--dns-result-order`](https://nodejs.org/docs/latest-v18.x/api/cli.html#--dns-result-orderorder). + * @default true (addresses are not reordered) + */ + verbatim?: boolean | undefined; + } + export interface LookupOneOptions extends LookupOptions { + all?: false | undefined; + } + export interface LookupAllOptions extends LookupOptions { + all: true; + } + export interface LookupAddress { + /** + * A string representation of an IPv4 or IPv6 address. + */ + address: string; + /** + * `4` or `6`, denoting the family of `address`, or `0` if the address is not an IPv4 or IPv6 address. `0` is a likely indicator of a + * bug in the name resolution service used by the operating system. + */ + family: number; + } + /** + * Resolves a host name (e.g. `'nodejs.org'`) into the first found A (IPv4) or + * AAAA (IPv6) record. All `option` properties are optional. If `options` is an + * integer, then it must be `4` or `6` – if `options` is `0` or not provided, then + * IPv4 and IPv6 addresses are both returned if found. + * + * With the `all` option set to `true`, the arguments for `callback` change to `(err, addresses)`, with `addresses` being an array of objects with the + * properties `address` and `family`. + * + * On error, `err` is an `Error` object, where `err.code` is the error code. + * Keep in mind that `err.code` will be set to `'ENOTFOUND'` not only when + * the host name does not exist but also when the lookup fails in other ways + * such as no available file descriptors. + * + * `dns.lookup()` does not necessarily have anything to do with the DNS protocol. + * The implementation uses an operating system facility that can associate names + * with addresses and vice versa. This implementation can have subtle but + * important consequences on the behavior of any Node.js program. Please take some + * time to consult the [Implementation considerations section](https://nodejs.org/docs/latest-v18.x/api/dns.html#implementation-considerations) + * before using `dns.lookup()`. + * + * Example usage: + * + * ```js + * const dns = require('node:dns'); + * const options = { + * family: 6, + * hints: dns.ADDRCONFIG | dns.V4MAPPED, + * }; + * dns.lookup('example.com', options, (err, address, family) => + * console.log('address: %j family: IPv%s', address, family)); + * // address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6 + * + * // When options.all is true, the result will be an Array. + * options.all = true; + * dns.lookup('example.com', options, (err, addresses) => + * console.log('addresses: %j', addresses)); + * // addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}] + * ``` + * + * If this method is invoked as its [util.promisify()](https://nodejs.org/docs/latest-v18.x/api/util.html#utilpromisifyoriginal) ed + * version, and `all` is not set to `true`, it returns a `Promise` for an `Object` with `address` and `family` properties. + * @since v0.1.90 + */ + export function lookup( + hostname: string, + family: number, + callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void, + ): void; + export function lookup( + hostname: string, + options: LookupOneOptions, + callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void, + ): void; + export function lookup( + hostname: string, + options: LookupAllOptions, + callback: (err: NodeJS.ErrnoException | null, addresses: LookupAddress[]) => void, + ): void; + export function lookup( + hostname: string, + options: LookupOptions, + callback: (err: NodeJS.ErrnoException | null, address: string | LookupAddress[], family: number) => void, + ): void; + export function lookup( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void, + ): void; + export namespace lookup { + function __promisify__(hostname: string, options: LookupAllOptions): Promise; + function __promisify__(hostname: string, options?: LookupOneOptions | number): Promise; + function __promisify__(hostname: string, options: LookupOptions): Promise; + } + /** + * Resolves the given `address` and `port` into a host name and service using + * the operating system's underlying `getnameinfo` implementation. + * + * If `address` is not a valid IP address, a `TypeError` will be thrown. + * The `port` will be coerced to a number. If it is not a legal port, a `TypeError` will be thrown. + * + * On an error, `err` is an [`Error`](https://nodejs.org/docs/latest-v18.x/api/errors.html#class-error) object, + * where `err.code` is the error code. + * + * ```js + * const dns = require('node:dns'); + * dns.lookupService('127.0.0.1', 22, (err, hostname, service) => { + * console.log(hostname, service); + * // Prints: localhost ssh + * }); + * ``` + * + * If this method is invoked as its [util.promisify()](https://nodejs.org/docs/latest-v18.x/api/util.html#utilpromisifyoriginal) ed + * version, it returns a `Promise` for an `Object` with `hostname` and `service` properties. + * @since v0.11.14 + */ + export function lookupService( + address: string, + port: number, + callback: (err: NodeJS.ErrnoException | null, hostname: string, service: string) => void, + ): void; + export namespace lookupService { + function __promisify__( + address: string, + port: number, + ): Promise<{ + hostname: string; + service: string; + }>; + } + export interface ResolveOptions { + ttl: boolean; + } + export interface ResolveWithTtlOptions extends ResolveOptions { + ttl: true; + } + export interface RecordWithTtl { + address: string; + ttl: number; + } + /** @deprecated Use `AnyARecord` or `AnyAaaaRecord` instead. */ + export type AnyRecordWithTtl = AnyARecord | AnyAaaaRecord; + export interface AnyARecord extends RecordWithTtl { + type: "A"; + } + export interface AnyAaaaRecord extends RecordWithTtl { + type: "AAAA"; + } + export interface CaaRecord { + critical: number; + issue?: string | undefined; + issuewild?: string | undefined; + iodef?: string | undefined; + contactemail?: string | undefined; + contactphone?: string | undefined; + } + export interface MxRecord { + priority: number; + exchange: string; + } + export interface AnyMxRecord extends MxRecord { + type: "MX"; + } + export interface NaptrRecord { + flags: string; + service: string; + regexp: string; + replacement: string; + order: number; + preference: number; + } + export interface AnyNaptrRecord extends NaptrRecord { + type: "NAPTR"; + } + export interface SoaRecord { + nsname: string; + hostmaster: string; + serial: number; + refresh: number; + retry: number; + expire: number; + minttl: number; + } + export interface AnySoaRecord extends SoaRecord { + type: "SOA"; + } + export interface SrvRecord { + priority: number; + weight: number; + port: number; + name: string; + } + export interface AnySrvRecord extends SrvRecord { + type: "SRV"; + } + export interface AnyTxtRecord { + type: "TXT"; + entries: string[]; + } + export interface AnyNsRecord { + type: "NS"; + value: string; + } + export interface AnyPtrRecord { + type: "PTR"; + value: string; + } + export interface AnyCnameRecord { + type: "CNAME"; + value: string; + } + export type AnyRecord = + | AnyARecord + | AnyAaaaRecord + | AnyCnameRecord + | AnyMxRecord + | AnyNaptrRecord + | AnyNsRecord + | AnyPtrRecord + | AnySoaRecord + | AnySrvRecord + | AnyTxtRecord; + /** + * Uses the DNS protocol to resolve a host name (e.g. `'nodejs.org'`) into an array + * of the resource records. The `callback` function has arguments `(err, records)`. When successful, `records` will be an array of resource + * records. The type and structure of individual results varies based on `rrtype`: + * + * + * + * On error, `err` is an [`Error`](https://nodejs.org/docs/latest-v18.x/api/errors.html#class-error) object, + * where `err.code` is one of the `DNS error codes`. + * @since v0.1.27 + * @param hostname Host name to resolve. + * @param [rrtype='A'] Resource record type. + */ + export function resolve( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "A", + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "AAAA", + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "ANY", + callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "CNAME", + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "MX", + callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "NAPTR", + callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "NS", + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "PTR", + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "SOA", + callback: (err: NodeJS.ErrnoException | null, addresses: SoaRecord) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "SRV", + callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "TXT", + callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: string, + callback: ( + err: NodeJS.ErrnoException | null, + addresses: string[] | MxRecord[] | NaptrRecord[] | SoaRecord | SrvRecord[] | string[][] | AnyRecord[], + ) => void, + ): void; + export namespace resolve { + function __promisify__(hostname: string, rrtype?: "A" | "AAAA" | "CNAME" | "NS" | "PTR"): Promise; + function __promisify__(hostname: string, rrtype: "ANY"): Promise; + function __promisify__(hostname: string, rrtype: "MX"): Promise; + function __promisify__(hostname: string, rrtype: "NAPTR"): Promise; + function __promisify__(hostname: string, rrtype: "SOA"): Promise; + function __promisify__(hostname: string, rrtype: "SRV"): Promise; + function __promisify__(hostname: string, rrtype: "TXT"): Promise; + function __promisify__( + hostname: string, + rrtype: string, + ): Promise; + } + /** + * Uses the DNS protocol to resolve a IPv4 addresses (`A` records) for the `hostname`. The `addresses` argument passed to the `callback` function + * will contain an array of IPv4 addresses (e.g.`['74.125.79.104', '74.125.79.105', '74.125.79.106']`). + * @since v0.1.16 + * @param hostname Host name to resolve. + */ + export function resolve4( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export function resolve4( + hostname: string, + options: ResolveWithTtlOptions, + callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void, + ): void; + export function resolve4( + hostname: string, + options: ResolveOptions, + callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void, + ): void; + export namespace resolve4 { + function __promisify__(hostname: string): Promise; + function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise; + function __promisify__(hostname: string, options?: ResolveOptions): Promise; + } + /** + * Uses the DNS protocol to resolve IPv6 addresses (`AAAA` records) for the `hostname`. The `addresses` argument passed to the `callback` function + * will contain an array of IPv6 addresses. + * @since v0.1.16 + * @param hostname Host name to resolve. + */ + export function resolve6( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export function resolve6( + hostname: string, + options: ResolveWithTtlOptions, + callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void, + ): void; + export function resolve6( + hostname: string, + options: ResolveOptions, + callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void, + ): void; + export namespace resolve6 { + function __promisify__(hostname: string): Promise; + function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise; + function __promisify__(hostname: string, options?: ResolveOptions): Promise; + } + /** + * Uses the DNS protocol to resolve `CNAME` records for the `hostname`. The `addresses` argument passed to the `callback` function + * will contain an array of canonical name records available for the `hostname` (e.g. `['bar.example.com']`). + * @since v0.3.2 + */ + export function resolveCname( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export namespace resolveCname { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve `CAA` records for the `hostname`. The `addresses` argument passed to the `callback` function + * will contain an array of certification authority authorization records + * available for the `hostname` (e.g. `[{critical: 0, iodef: 'mailto:pki@example.com'}, {critical: 128, issue: 'pki.example.com'}]`). + * @since v15.0.0, v14.17.0 + */ + export function resolveCaa( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, records: CaaRecord[]) => void, + ): void; + export namespace resolveCaa { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve mail exchange records (`MX` records) for the `hostname`. The `addresses` argument passed to the `callback` function will + * contain an array of objects containing both a `priority` and `exchange` property (e.g. `[{priority: 10, exchange: 'mx.example.com'}, ...]`). + * @since v0.1.27 + */ + export function resolveMx( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void, + ): void; + export namespace resolveMx { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve regular expression-based records (`NAPTR` records) for the `hostname`. The `addresses` argument passed to the `callback` function will contain an array of + * objects with the following properties: + * + * * `flags` + * * `service` + * * `regexp` + * * `replacement` + * * `order` + * * `preference` + * + * ```js + * { + * flags: 's', + * service: 'SIP+D2U', + * regexp: '', + * replacement: '_sip._udp.example.com', + * order: 30, + * preference: 100 + * } + * ``` + * @since v0.9.12 + */ + export function resolveNaptr( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void, + ): void; + export namespace resolveNaptr { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve name server records (`NS` records) for the `hostname`. The `addresses` argument passed to the `callback` function will + * contain an array of name server records available for `hostname` (e.g. `['ns1.example.com', 'ns2.example.com']`). + * @since v0.1.90 + */ + export function resolveNs( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export namespace resolveNs { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve pointer records (`PTR` records) for the `hostname`. The `addresses` argument passed to the `callback` function will + * be an array of strings containing the reply records. + * @since v6.0.0 + */ + export function resolvePtr( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export namespace resolvePtr { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve a start of authority record (`SOA` record) for + * the `hostname`. The `address` argument passed to the `callback` function will + * be an object with the following properties: + * + * * `nsname` + * * `hostmaster` + * * `serial` + * * `refresh` + * * `retry` + * * `expire` + * * `minttl` + * + * ```js + * { + * nsname: 'ns.example.com', + * hostmaster: 'root.example.com', + * serial: 2013101809, + * refresh: 10000, + * retry: 2400, + * expire: 604800, + * minttl: 3600 + * } + * ``` + * @since v0.11.10 + */ + export function resolveSoa( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, address: SoaRecord) => void, + ): void; + export namespace resolveSoa { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve service records (`SRV` records) for the `hostname`. The `addresses` argument passed to the `callback` function will + * be an array of objects with the following properties: + * + * * `priority` + * * `weight` + * * `port` + * * `name` + * + * ```js + * { + * priority: 10, + * weight: 5, + * port: 21223, + * name: 'service.example.com' + * } + * ``` + * @since v0.1.27 + */ + export function resolveSrv( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void, + ): void; + export namespace resolveSrv { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve text queries (`TXT` records) for the `hostname`. The `records` argument passed to the `callback` function is a + * two-dimensional array of the text records available for `hostname` (e.g.`[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]`). Each sub-array contains TXT chunks of + * one record. Depending on the use case, these could be either joined together or + * treated separately. + * @since v0.1.27 + */ + export function resolveTxt( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void, + ): void; + export namespace resolveTxt { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve all records (also known as `ANY` or `*` query). + * The `ret` argument passed to the `callback` function will be an array containing + * various types of records. Each object has a property `type` that indicates the + * type of the current record. And depending on the `type`, additional properties + * will be present on the object: + * + * + * + * Here is an example of the `ret` object passed to the callback: + * + * ```js + * [ { type: 'A', address: '127.0.0.1', ttl: 299 }, + * { type: 'CNAME', value: 'example.com' }, + * { type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 }, + * { type: 'NS', value: 'ns1.example.com' }, + * { type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] }, + * { type: 'SOA', + * nsname: 'ns1.example.com', + * hostmaster: 'admin.example.com', + * serial: 156696742, + * refresh: 900, + * retry: 900, + * expire: 1800, + * minttl: 60 } ] + * ``` + * + * DNS server operators may choose not to respond to `ANY` queries. It may be better to call individual methods like {@link resolve4}, {@link resolveMx}, and so on. For more details, see + * [RFC 8482](https://tools.ietf.org/html/rfc8482). + */ + export function resolveAny( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void, + ): void; + export namespace resolveAny { + function __promisify__(hostname: string): Promise; + } + /** + * Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an + * array of host names. + * + * On error, `err` is an [`Error`](https://nodejs.org/docs/latest-v18.x/api/errors.html#class-error) object, where `err.code` is + * one of the [DNS error codes](https://nodejs.org/docs/latest-v18.x/api/dns.html#error-codes). + * @since v0.1.16 + */ + export function reverse( + ip: string, + callback: (err: NodeJS.ErrnoException | null, hostnames: string[]) => void, + ): void; + /** + * Get the default value for `verbatim` in {@link lookup} and [`dnsPromises.lookup()`](https://nodejs.org/docs/latest-v18.x/api/dns.html#dnspromiseslookuphostname-options). + * The value could be: + * + * * `ipv4first`: for `verbatim` defaulting to `false`. + * * `verbatim`: for `verbatim` defaulting to `true`. + * @since v18.17.0 + */ + export function getDefaultResultOrder(): "ipv4first" | "verbatim"; + /** + * Sets the IP address and port of servers to be used when performing DNS + * resolution. The `servers` argument is an array of [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6) formatted + * addresses. If the port is the IANA default DNS port (53) it can be omitted. + * + * ```js + * dns.setServers([ + * '4.4.4.4', + * '[2001:4860:4860::8888]', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ]); + * ``` + * + * An error will be thrown if an invalid address is provided. + * + * The `dns.setServers()` method must not be called while a DNS query is in + * progress. + * + * The {@link setServers} method affects only {@link resolve}, `dns.resolve*()` and {@link reverse} (and specifically _not_ {@link lookup}). + * + * This method works much like [resolve.conf](https://man7.org/linux/man-pages/man5/resolv.conf.5.html). + * That is, if attempting to resolve with the first server provided results in a `NOTFOUND` error, the `resolve()` method will _not_ attempt to resolve with + * subsequent servers provided. Fallback DNS servers will only be used if the + * earlier ones time out or result in some other error. + * @since v0.11.3 + * @param servers array of [RFC 5952](https://datatracker.ietf.org/doc/html/rfc5952#section-6) formatted addresses + */ + export function setServers(servers: readonly string[]): void; + /** + * Returns an array of IP address strings, formatted according to [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6), + * that are currently configured for DNS resolution. A string will include a port + * section if a custom port is used. + * + * ```js + * [ + * '4.4.4.4', + * '2001:4860:4860::8888', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ] + * ``` + * @since v0.11.3 + */ + export function getServers(): string[]; + /** + * Set the default value of `verbatim` in {@link lookup} and [`dnsPromises.lookup()`](https://nodejs.org/docs/latest-v18.x/api/dns.html#dnspromiseslookuphostname-options). + * The value could be: + * + * * `ipv4first`: sets default `verbatim` `false`. + * * `verbatim`: sets default `verbatim` `true`. + * + * The default is `verbatim` and {@link setDefaultResultOrder} have higher + * priority than [`--dns-result-order`](https://nodejs.org/docs/latest-v18.x/api/cli.html#--dns-result-orderorder). When using + * [worker threads](https://nodejs.org/docs/latest-v18.x/api/worker_threads.html), {@link setDefaultResultOrder} from the main + * thread won't affect the default dns orders in workers. + * @since v16.4.0, v14.18.0 + * @param order must be `'ipv4first'` or `'verbatim'`. + */ + export function setDefaultResultOrder(order: "ipv4first" | "verbatim"): void; + // Error codes + export const NODATA: "NODATA"; + export const FORMERR: "FORMERR"; + export const SERVFAIL: "SERVFAIL"; + export const NOTFOUND: "NOTFOUND"; + export const NOTIMP: "NOTIMP"; + export const REFUSED: "REFUSED"; + export const BADQUERY: "BADQUERY"; + export const BADNAME: "BADNAME"; + export const BADFAMILY: "BADFAMILY"; + export const BADRESP: "BADRESP"; + export const CONNREFUSED: "TIMEOUT"; + export const TIMEOUT: "TIMEOUT"; + export const EOF: "EOF"; + export const FILE: "FILE"; + export const NOMEM: "NOMEM"; + export const DESTRUCTION: "DESTRUCTION"; + export const BADSTR: "BADSTR"; + export const BADFLAGS: "BADFLAGS"; + export const NONAME: "NONAME"; + export const BADHINTS: "BADHINTS"; + export const NOTINITIALIZED: "NOTINITIALIZED"; + export const LOADIPHLPAPI: "LOADIPHLPAPI"; + export const ADDRGETNETWORKPARAMS: "ADDRGETNETWORKPARAMS"; + export const CANCELLED: "CANCELLED"; + export interface ResolverOptions { + /** + * Query timeout in milliseconds, or `-1` to use the default timeout. + */ + timeout?: number | undefined; + /** + * The number of tries the resolver will try contacting each name server before giving up. + * @default 4 + */ + tries?: number; + } + /** + * An independent resolver for DNS requests. + * + * Creating a new resolver uses the default server settings. Setting + * the servers used for a resolver using [`resolver.setServers()`](https://nodejs.org/docs/latest-v18.x/api/dns.html#dnssetserversservers) does not affect + * other resolvers: + * + * ```js + * const { Resolver } = require('node:dns'); + * const resolver = new Resolver(); + * resolver.setServers(['4.4.4.4']); + * + * // This request will use the server at 4.4.4.4, independent of global settings. + * resolver.resolve4('example.org', (err, addresses) => { + * // ... + * }); + * ``` + * + * The following methods from the `node:dns` module are available: + * + * * `resolver.getServers()` + * * `resolver.resolve()` + * * `resolver.resolve4()` + * * `resolver.resolve6()` + * * `resolver.resolveAny()` + * * `resolver.resolveCaa()` + * * `resolver.resolveCname()` + * * `resolver.resolveMx()` + * * `resolver.resolveNaptr()` + * * `resolver.resolveNs()` + * * `resolver.resolvePtr()` + * * `resolver.resolveSoa()` + * * `resolver.resolveSrv()` + * * `resolver.resolveTxt()` + * * `resolver.reverse()` + * * `resolver.setServers()` + * @since v8.3.0 + */ + export class Resolver { + constructor(options?: ResolverOptions); + /** + * Cancel all outstanding DNS queries made by this resolver. The corresponding + * callbacks will be called with an error with code `ECANCELLED`. + * @since v8.3.0 + */ + cancel(): void; + getServers: typeof getServers; + resolve: typeof resolve; + resolve4: typeof resolve4; + resolve6: typeof resolve6; + resolveAny: typeof resolveAny; + resolveCaa: typeof resolveCaa; + resolveCname: typeof resolveCname; + resolveMx: typeof resolveMx; + resolveNaptr: typeof resolveNaptr; + resolveNs: typeof resolveNs; + resolvePtr: typeof resolvePtr; + resolveSoa: typeof resolveSoa; + resolveSrv: typeof resolveSrv; + resolveTxt: typeof resolveTxt; + reverse: typeof reverse; + /** + * The resolver instance will send its requests from the specified IP address. + * This allows programs to specify outbound interfaces when used on multi-homed + * systems. + * + * If a v4 or v6 address is not specified, it is set to the default and the + * operating system will choose a local address automatically. + * + * The resolver will use the v4 local address when making requests to IPv4 DNS + * servers, and the v6 local address when making requests to IPv6 DNS servers. + * The `rrtype` of resolution requests has no impact on the local address used. + * @since v15.1.0, v14.17.0 + * @param [ipv4='0.0.0.0'] A string representation of an IPv4 address. + * @param [ipv6='::0'] A string representation of an IPv6 address. + */ + setLocalAddress(ipv4?: string, ipv6?: string): void; + setServers: typeof setServers; + } + export { dnsPromises as promises }; +} +declare module "node:dns" { + export * from "dns"; +} diff --git a/backend/node_modules/@types/node/dns/promises.d.ts b/backend/node_modules/@types/node/dns/promises.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..15e63d3c5df661e7563d5a4c4ed0c079e1b2b5a1 --- /dev/null +++ b/backend/node_modules/@types/node/dns/promises.d.ts @@ -0,0 +1,473 @@ +/** + * The `dns.promises` API provides an alternative set of asynchronous DNS methods + * that return `Promise` objects rather than using callbacks. The API is accessible + * via `require('node:dns').promises` or `require('node:dns/promises')`. + * @since v10.6.0 + */ +declare module "dns/promises" { + import { + AnyRecord, + CaaRecord, + LookupAddress, + LookupAllOptions, + LookupOneOptions, + LookupOptions, + MxRecord, + NaptrRecord, + RecordWithTtl, + ResolveOptions, + ResolverOptions, + ResolveWithTtlOptions, + SoaRecord, + SrvRecord, + } from "node:dns"; + /** + * Returns an array of IP address strings, formatted according to [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6), + * that are currently configured for DNS resolution. A string will include a port + * section if a custom port is used. + * + * ```js + * [ + * '4.4.4.4', + * '2001:4860:4860::8888', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ] + * ``` + * @since v10.6.0 + */ + function getServers(): string[]; + /** + * Resolves a host name (e.g. `'nodejs.org'`) into the first found A (IPv4) or + * AAAA (IPv6) record. All `option` properties are optional. If `options` is an + * integer, then it must be `4` or `6` – if `options` is not provided, then IPv4 + * and IPv6 addresses are both returned if found. + * + * With the `all` option set to `true`, the `Promise` is resolved with `addresses` being an array of objects with the properties `address` and `family`. + * + * On error, the `Promise` is rejected with an [`Error`](https://nodejs.org/docs/latest-v18.x/api/errors.html#class-error) object, where `err.code` is the error code. + * Keep in mind that `err.code` will be set to `'ENOTFOUND'` not only when + * the host name does not exist but also when the lookup fails in other ways + * such as no available file descriptors. + * + * [`dnsPromises.lookup()`](https://nodejs.org/docs/latest-v18.x/api/dns.html#dnspromiseslookuphostname-options) does not necessarily have anything to do with the DNS + * protocol. The implementation uses an operating system facility that can + * associate names with addresses and vice versa. This implementation can have + * subtle but important consequences on the behavior of any Node.js program. Please + * take some time to consult the [Implementation considerations section](https://nodejs.org/docs/latest-v18.x/api/dns.html#implementation-considerations) before + * using `dnsPromises.lookup()`. + * + * Example usage: + * + * ```js + * const dns = require('node:dns'); + * const dnsPromises = dns.promises; + * const options = { + * family: 6, + * hints: dns.ADDRCONFIG | dns.V4MAPPED, + * }; + * + * dnsPromises.lookup('example.com', options).then((result) => { + * console.log('address: %j family: IPv%s', result.address, result.family); + * // address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6 + * }); + * + * // When options.all is true, the result will be an Array. + * options.all = true; + * dnsPromises.lookup('example.com', options).then((result) => { + * console.log('addresses: %j', result); + * // addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}] + * }); + * ``` + * @since v10.6.0 + */ + function lookup(hostname: string, family: number): Promise; + function lookup(hostname: string, options: LookupOneOptions): Promise; + function lookup(hostname: string, options: LookupAllOptions): Promise; + function lookup(hostname: string, options: LookupOptions): Promise; + function lookup(hostname: string): Promise; + /** + * Resolves the given `address` and `port` into a host name and service using + * the operating system's underlying `getnameinfo` implementation. + * + * If `address` is not a valid IP address, a `TypeError` will be thrown. + * The `port` will be coerced to a number. If it is not a legal port, a `TypeError` will be thrown. + * + * On error, the `Promise` is rejected with an [`Error`](https://nodejs.org/docs/latest-v18.x/api/errors.html#class-error) object, where `err.code` is the error code. + * + * ```js + * const dnsPromises = require('node:dns').promises; + * dnsPromises.lookupService('127.0.0.1', 22).then((result) => { + * console.log(result.hostname, result.service); + * // Prints: localhost ssh + * }); + * ``` + * @since v10.6.0 + */ + function lookupService( + address: string, + port: number, + ): Promise<{ + hostname: string; + service: string; + }>; + /** + * Uses the DNS protocol to resolve a host name (e.g. `'nodejs.org'`) into an array + * of the resource records. When successful, the `Promise` is resolved with an + * array of resource records. The type and structure of individual results vary + * based on `rrtype`: + * + * + * + * On error, the `Promise` is rejected with an [`Error`](https://nodejs.org/docs/latest-v18.x/api/errors.html#class-error) object, where `err.code` + * is one of the [DNS error codes](https://nodejs.org/docs/latest-v18.x/api/dns.html#error-codes). + * @since v10.6.0 + * @param hostname Host name to resolve. + * @param [rrtype='A'] Resource record type. + */ + function resolve(hostname: string): Promise; + function resolve(hostname: string, rrtype: "A"): Promise; + function resolve(hostname: string, rrtype: "AAAA"): Promise; + function resolve(hostname: string, rrtype: "ANY"): Promise; + function resolve(hostname: string, rrtype: "CAA"): Promise; + function resolve(hostname: string, rrtype: "CNAME"): Promise; + function resolve(hostname: string, rrtype: "MX"): Promise; + function resolve(hostname: string, rrtype: "NAPTR"): Promise; + function resolve(hostname: string, rrtype: "NS"): Promise; + function resolve(hostname: string, rrtype: "PTR"): Promise; + function resolve(hostname: string, rrtype: "SOA"): Promise; + function resolve(hostname: string, rrtype: "SRV"): Promise; + function resolve(hostname: string, rrtype: "TXT"): Promise; + function resolve( + hostname: string, + rrtype: string, + ): Promise; + /** + * Uses the DNS protocol to resolve IPv4 addresses (`A` records) for the `hostname`. On success, the `Promise` is resolved with an array of IPv4 + * addresses (e.g. `['74.125.79.104', '74.125.79.105', '74.125.79.106']`). + * @since v10.6.0 + * @param hostname Host name to resolve. + */ + function resolve4(hostname: string): Promise; + function resolve4(hostname: string, options: ResolveWithTtlOptions): Promise; + function resolve4(hostname: string, options: ResolveOptions): Promise; + /** + * Uses the DNS protocol to resolve IPv6 addresses (`AAAA` records) for the `hostname`. On success, the `Promise` is resolved with an array of IPv6 + * addresses. + * @since v10.6.0 + * @param hostname Host name to resolve. + */ + function resolve6(hostname: string): Promise; + function resolve6(hostname: string, options: ResolveWithTtlOptions): Promise; + function resolve6(hostname: string, options: ResolveOptions): Promise; + /** + * Uses the DNS protocol to resolve all records (also known as `ANY` or `*` query). + * On success, the `Promise` is resolved with an array containing various types of + * records. Each object has a property `type` that indicates the type of the + * current record. And depending on the `type`, additional properties will be + * present on the object: + * + * + * + * Here is an example of the result object: + * + * ```js + * [ { type: 'A', address: '127.0.0.1', ttl: 299 }, + * { type: 'CNAME', value: 'example.com' }, + * { type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 }, + * { type: 'NS', value: 'ns1.example.com' }, + * { type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] }, + * { type: 'SOA', + * nsname: 'ns1.example.com', + * hostmaster: 'admin.example.com', + * serial: 156696742, + * refresh: 900, + * retry: 900, + * expire: 1800, + * minttl: 60 } ] + * ``` + * @since v10.6.0 + */ + function resolveAny(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve `CAA` records for the `hostname`. On success, + * the `Promise` is resolved with an array of objects containing available + * certification authority authorization records available for the `hostname` (e.g. `[{critical: 0, iodef: 'mailto:pki@example.com'},{critical: 128, issue: 'pki.example.com'}]`). + * @since v15.0.0, v14.17.0 + */ + function resolveCaa(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve `CNAME` records for the `hostname`. On success, + * the `Promise` is resolved with an array of canonical name records available for + * the `hostname` (e.g. `['bar.example.com']`). + * @since v10.6.0 + */ + function resolveCname(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve mail exchange records (`MX` records) for the `hostname`. On success, the `Promise` is resolved with an array of objects + * containing both a `priority` and `exchange` property (e.g.`[{priority: 10, exchange: 'mx.example.com'}, ...]`). + * @since v10.6.0 + */ + function resolveMx(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve regular expression-based records (`NAPTR` records) for the `hostname`. On success, the `Promise` is resolved with an array + * of objects with the following properties: + * + * * `flags` + * * `service` + * * `regexp` + * * `replacement` + * * `order` + * * `preference` + * + * ```js + * { + * flags: 's', + * service: 'SIP+D2U', + * regexp: '', + * replacement: '_sip._udp.example.com', + * order: 30, + * preference: 100 + * } + * ``` + * @since v10.6.0 + */ + function resolveNaptr(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve name server records (`NS` records) for the `hostname`. On success, the `Promise` is resolved with an array of name server + * records available for `hostname` (e.g.`['ns1.example.com', 'ns2.example.com']`). + * @since v10.6.0 + */ + function resolveNs(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve pointer records (`PTR` records) for the `hostname`. On success, the `Promise` is resolved with an array of strings + * containing the reply records. + * @since v10.6.0 + */ + function resolvePtr(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve a start of authority record (`SOA` record) for + * the `hostname`. On success, the `Promise` is resolved with an object with the + * following properties: + * + * * `nsname` + * * `hostmaster` + * * `serial` + * * `refresh` + * * `retry` + * * `expire` + * * `minttl` + * + * ```js + * { + * nsname: 'ns.example.com', + * hostmaster: 'root.example.com', + * serial: 2013101809, + * refresh: 10000, + * retry: 2400, + * expire: 604800, + * minttl: 3600 + * } + * ``` + * @since v10.6.0 + */ + function resolveSoa(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve service records (`SRV` records) for the `hostname`. On success, the `Promise` is resolved with an array of objects with + * the following properties: + * + * * `priority` + * * `weight` + * * `port` + * * `name` + * + * ```js + * { + * priority: 10, + * weight: 5, + * port: 21223, + * name: 'service.example.com' + * } + * ``` + * @since v10.6.0 + */ + function resolveSrv(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve text queries (`TXT` records) for the `hostname`. On success, the `Promise` is resolved with a two-dimensional array + * of the text records available for `hostname` (e.g.`[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]`). Each sub-array contains TXT chunks of + * one record. Depending on the use case, these could be either joined together or + * treated separately. + * @since v10.6.0 + */ + function resolveTxt(hostname: string): Promise; + /** + * Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an + * array of host names. + * + * On error, the `Promise` is rejected with an [`Error`](https://nodejs.org/docs/latest-v18.x/api/errors.html#class-error) object, where `err.code` + * is one of the [DNS error codes](https://nodejs.org/docs/latest-v18.x/api/dns.html#error-codes). + * @since v10.6.0 + */ + function reverse(ip: string): Promise; + /** + * Get the default value for `verbatim` in {@link lookup} and [dnsPromises.lookup()](https://nodejs.org/docs/latest-v18.x/api/dns.html#dnspromiseslookuphostname-options). + * The value could be: + * + * * `ipv4first`: for `verbatim` defaulting to `false`. + * * `verbatim`: for `verbatim` defaulting to `true`. + * @since v18.17.0 + */ + function getDefaultResultOrder(): "ipv4first" | "verbatim"; + /** + * Sets the IP address and port of servers to be used when performing DNS + * resolution. The `servers` argument is an array of [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6) formatted + * addresses. If the port is the IANA default DNS port (53) it can be omitted. + * + * ```js + * dnsPromises.setServers([ + * '4.4.4.4', + * '[2001:4860:4860::8888]', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ]); + * ``` + * + * An error will be thrown if an invalid address is provided. + * + * The `dnsPromises.setServers()` method must not be called while a DNS query is in + * progress. + * + * This method works much like [resolve.conf](https://man7.org/linux/man-pages/man5/resolv.conf.5.html). + * That is, if attempting to resolve with the first server provided results in a`NOTFOUND` error, the `resolve()` method will _not_ attempt to resolve with + * subsequent servers provided. Fallback DNS servers will only be used if the + * earlier ones time out or result in some other error. + * @since v10.6.0 + * @param servers array of `RFC 5952` formatted addresses + */ + function setServers(servers: readonly string[]): void; + /** + * Set the default value of `verbatim` in `dns.lookup()` and `dnsPromises.lookup()`. The value could be: + * + * * `ipv4first`: sets default `verbatim` `false`. + * * `verbatim`: sets default `verbatim` `true`. + * + * The default is `verbatim` and [dnsPromises.setDefaultResultOrder()](https://nodejs.org/docs/latest-v18.x/api/dns.html#dnspromisessetdefaultresultorderorder) + * have higher priority than [`--dns-result-order`](https://nodejs.org/docs/latest-v18.x/api/cli.html#--dns-result-orderorder). + * When using [worker threads](https://nodejs.org/docs/latest-v18.x/api/worker_threads.html), [`dnsPromises.setDefaultResultOrder()`](https://nodejs.org/docs/latest-v18.x/api/dns.html#dnspromisessetdefaultresultorderorder) + * from the main thread won't affect the default dns orders in workers. + * @since v16.4.0, v14.18.0 + * @param order must be `'ipv4first'` or `'verbatim'`. + */ + function setDefaultResultOrder(order: "ipv4first" | "verbatim"): void; + const NODATA: "NODATA"; + const FORMERR: "FORMERR"; + const SERVFAIL: "SERVFAIL"; + const NOTFOUND: "NOTFOUND"; + const NOTIMP: "NOTIMP"; + const REFUSED: "REFUSED"; + const BADQUERY: "BADQUERY"; + const BADNAME: "BADNAME"; + const BADFAMILY: "BADFAMILY"; + const BADRESP: "BADRESP"; + const CONNREFUSED: "TIMEOUT"; + const TIMEOUT: "TIMEOUT"; + const EOF: "EOF"; + const FILE: "FILE"; + const NOMEM: "NOMEM"; + const DESTRUCTION: "DESTRUCTION"; + const BADSTR: "BADSTR"; + const BADFLAGS: "BADFLAGS"; + const NONAME: "NONAME"; + const BADHINTS: "BADHINTS"; + const NOTINITIALIZED: "NOTINITIALIZED"; + const LOADIPHLPAPI: "LOADIPHLPAPI"; + const ADDRGETNETWORKPARAMS: "ADDRGETNETWORKPARAMS"; + const CANCELLED: "CANCELLED"; + /** + * An independent resolver for DNS requests. + * + * Creating a new resolver uses the default server settings. Setting + * the servers used for a resolver using [`resolver.setServers()`](https://nodejs.org/docs/latest-v18.x/api/dns.html#dnspromisessetserversservers) does not affect + * other resolvers: + * + * ```js + * const { Resolver } = require('node:dns').promises; + * const resolver = new Resolver(); + * resolver.setServers(['4.4.4.4']); + * + * // This request will use the server at 4.4.4.4, independent of global settings. + * resolver.resolve4('example.org').then((addresses) => { + * // ... + * }); + * + * // Alternatively, the same code can be written using async-await style. + * (async function() { + * const addresses = await resolver.resolve4('example.org'); + * })(); + * ``` + * + * The following methods from the `dnsPromises` API are available: + * + * * `resolver.getServers()` + * * `resolver.resolve()` + * * `resolver.resolve4()` + * * `resolver.resolve6()` + * * `resolver.resolveAny()` + * * `resolver.resolveCaa()` + * * `resolver.resolveCname()` + * * `resolver.resolveMx()` + * * `resolver.resolveNaptr()` + * * `resolver.resolveNs()` + * * `resolver.resolvePtr()` + * * `resolver.resolveSoa()` + * * `resolver.resolveSrv()` + * * `resolver.resolveTxt()` + * * `resolver.reverse()` + * * `resolver.setServers()` + * @since v10.6.0 + */ + class Resolver { + constructor(options?: ResolverOptions); + /** + * Cancel all outstanding DNS queries made by this resolver. The corresponding + * callbacks will be called with an error with code `ECANCELLED`. + * @since v8.3.0 + */ + cancel(): void; + getServers: typeof getServers; + resolve: typeof resolve; + resolve4: typeof resolve4; + resolve6: typeof resolve6; + resolveAny: typeof resolveAny; + resolveCaa: typeof resolveCaa; + resolveCname: typeof resolveCname; + resolveMx: typeof resolveMx; + resolveNaptr: typeof resolveNaptr; + resolveNs: typeof resolveNs; + resolvePtr: typeof resolvePtr; + resolveSoa: typeof resolveSoa; + resolveSrv: typeof resolveSrv; + resolveTxt: typeof resolveTxt; + reverse: typeof reverse; + /** + * The resolver instance will send its requests from the specified IP address. + * This allows programs to specify outbound interfaces when used on multi-homed + * systems. + * + * If a v4 or v6 address is not specified, it is set to the default and the + * operating system will choose a local address automatically. + * + * The resolver will use the v4 local address when making requests to IPv4 DNS + * servers, and the v6 local address when making requests to IPv6 DNS servers. + * The `rrtype` of resolution requests has no impact on the local address used. + * @since v15.1.0, v14.17.0 + * @param [ipv4='0.0.0.0'] A string representation of an IPv4 address. + * @param [ipv6='::0'] A string representation of an IPv6 address. + */ + setLocalAddress(ipv4?: string, ipv6?: string): void; + setServers: typeof setServers; + } +} +declare module "node:dns/promises" { + export * from "dns/promises"; +} diff --git a/backend/node_modules/@types/node/dom-events.d.ts b/backend/node_modules/@types/node/dom-events.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f47f71d63866904b6a83bbd68f100db0f96adb00 --- /dev/null +++ b/backend/node_modules/@types/node/dom-events.d.ts @@ -0,0 +1,124 @@ +export {}; // Don't export anything! + +//// DOM-like Events +// NB: The Event / EventTarget / EventListener implementations below were copied +// from lib.dom.d.ts, then edited to reflect Node's documentation at +// https://nodejs.org/api/events.html#class-eventtarget. +// Please read that link to understand important implementation differences. + +// This conditional type will be the existing global Event in a browser, or +// the copy below in a Node environment. +type __Event = typeof globalThis extends { onmessage: any; Event: any } ? {} + : { + /** This is not used in Node.js and is provided purely for completeness. */ + readonly bubbles: boolean; + /** Alias for event.stopPropagation(). This is not used in Node.js and is provided purely for completeness. */ + cancelBubble: () => void; + /** True if the event was created with the cancelable option */ + readonly cancelable: boolean; + /** This is not used in Node.js and is provided purely for completeness. */ + readonly composed: boolean; + /** Returns an array containing the current EventTarget as the only entry or empty if the event is not being dispatched. This is not used in Node.js and is provided purely for completeness. */ + composedPath(): [EventTarget?]; + /** Alias for event.target. */ + readonly currentTarget: EventTarget | null; + /** Is true if cancelable is true and event.preventDefault() has been called. */ + readonly defaultPrevented: boolean; + /** This is not used in Node.js and is provided purely for completeness. */ + readonly eventPhase: 0 | 2; + /** The `AbortSignal` "abort" event is emitted with `isTrusted` set to `true`. The value is `false` in all other cases. */ + readonly isTrusted: boolean; + /** Sets the `defaultPrevented` property to `true` if `cancelable` is `true`. */ + preventDefault(): void; + /** This is not used in Node.js and is provided purely for completeness. */ + returnValue: boolean; + /** Alias for event.target. */ + readonly srcElement: EventTarget | null; + /** Stops the invocation of event listeners after the current one completes. */ + stopImmediatePropagation(): void; + /** This is not used in Node.js and is provided purely for completeness. */ + stopPropagation(): void; + /** The `EventTarget` dispatching the event */ + readonly target: EventTarget | null; + /** The millisecond timestamp when the Event object was created. */ + readonly timeStamp: number; + /** Returns the type of event, e.g. "click", "hashchange", or "submit". */ + readonly type: string; + }; + +// See comment above explaining conditional type +type __EventTarget = typeof globalThis extends { onmessage: any; EventTarget: any } ? {} + : { + /** + * Adds a new handler for the `type` event. Any given `listener` is added only once per `type` and per `capture` option value. + * + * If the `once` option is true, the `listener` is removed after the next time a `type` event is dispatched. + * + * The `capture` option is not used by Node.js in any functional way other than tracking registered event listeners per the `EventTarget` specification. + * Specifically, the `capture` option is used as part of the key when registering a `listener`. + * Any individual `listener` may be added once with `capture = false`, and once with `capture = true`. + */ + addEventListener( + type: string, + listener: EventListener | EventListenerObject, + options?: AddEventListenerOptions | boolean, + ): void; + /** Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. */ + dispatchEvent(event: Event): boolean; + /** Removes the event listener in target's event listener list with the same type, callback, and options. */ + removeEventListener( + type: string, + listener: EventListener | EventListenerObject, + options?: EventListenerOptions | boolean, + ): void; + }; + +interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} + +interface EventListenerOptions { + /** Not directly used by Node.js. Added for API completeness. Default: `false`. */ + capture?: boolean; +} + +interface AddEventListenerOptions extends EventListenerOptions { + /** When `true`, the listener is automatically removed when it is first invoked. Default: `false`. */ + once?: boolean; + /** When `true`, serves as a hint that the listener will not call the `Event` object's `preventDefault()` method. Default: false. */ + passive?: boolean; + /** The listener will be removed when the given AbortSignal object's `abort()` method is called. */ + signal?: AbortSignal; +} + +interface EventListener { + (evt: Event): void; +} + +interface EventListenerObject { + handleEvent(object: Event): void; +} + +import {} from "events"; // Make this an ambient declaration +declare global { + /** An event which takes place in the DOM. */ + interface Event extends __Event {} + var Event: typeof globalThis extends { onmessage: any; Event: infer T } ? T + : { + prototype: __Event; + new(type: string, eventInitDict?: EventInit): __Event; + }; + + /** + * EventTarget is a DOM interface implemented by objects that can + * receive events and may have listeners for them. + */ + interface EventTarget extends __EventTarget {} + var EventTarget: typeof globalThis extends { onmessage: any; EventTarget: infer T } ? T + : { + prototype: __EventTarget; + new(): __EventTarget; + }; +} diff --git a/backend/node_modules/@types/node/domain.d.ts b/backend/node_modules/@types/node/domain.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ca8728f19db4fe2da4004a8792ffd03a0908fe88 --- /dev/null +++ b/backend/node_modules/@types/node/domain.d.ts @@ -0,0 +1,170 @@ +/** + * **This module is pending deprecation.** Once a replacement API has been + * finalized, this module will be fully deprecated. Most developers should + * **not** have cause to use this module. Users who absolutely must have + * the functionality that domains provide may rely on it for the time being + * but should expect to have to migrate to a different solution + * in the future. + * + * Domains provide a way to handle multiple different IO operations as a + * single group. If any of the event emitters or callbacks registered to a + * domain emit an `'error'` event, or throw an error, then the domain object + * will be notified, rather than losing the context of the error in the`process.on('uncaughtException')` handler, or causing the program to + * exit immediately with an error code. + * @deprecated Since v1.4.2 - Deprecated + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/domain.js) + */ +declare module "domain" { + import EventEmitter = require("node:events"); + /** + * The `Domain` class encapsulates the functionality of routing errors and + * uncaught exceptions to the active `Domain` object. + * + * To handle the errors that it catches, listen to its `'error'` event. + */ + class Domain extends EventEmitter { + /** + * An array of timers and event emitters that have been explicitly added + * to the domain. + */ + members: Array; + /** + * The `enter()` method is plumbing used by the `run()`, `bind()`, and`intercept()` methods to set the active domain. It sets `domain.active` and`process.domain` to the domain, and implicitly + * pushes the domain onto the domain + * stack managed by the domain module (see {@link exit} for details on the + * domain stack). The call to `enter()` delimits the beginning of a chain of + * asynchronous calls and I/O operations bound to a domain. + * + * Calling `enter()` changes only the active domain, and does not alter the domain + * itself. `enter()` and `exit()` can be called an arbitrary number of times on a + * single domain. + */ + enter(): void; + /** + * The `exit()` method exits the current domain, popping it off the domain stack. + * Any time execution is going to switch to the context of a different chain of + * asynchronous calls, it's important to ensure that the current domain is exited. + * The call to `exit()` delimits either the end of or an interruption to the chain + * of asynchronous calls and I/O operations bound to a domain. + * + * If there are multiple, nested domains bound to the current execution context,`exit()` will exit any domains nested within this domain. + * + * Calling `exit()` changes only the active domain, and does not alter the domain + * itself. `enter()` and `exit()` can be called an arbitrary number of times on a + * single domain. + */ + exit(): void; + /** + * Run the supplied function in the context of the domain, implicitly + * binding all event emitters, timers, and lowlevel requests that are + * created in that context. Optionally, arguments can be passed to + * the function. + * + * This is the most basic way to use a domain. + * + * ```js + * const domain = require('domain'); + * const fs = require('fs'); + * const d = domain.create(); + * d.on('error', (er) => { + * console.error('Caught error!', er); + * }); + * d.run(() => { + * process.nextTick(() => { + * setTimeout(() => { // Simulating some various async stuff + * fs.open('non-existent file', 'r', (er, fd) => { + * if (er) throw er; + * // proceed... + * }); + * }, 100); + * }); + * }); + * ``` + * + * In this example, the `d.on('error')` handler will be triggered, rather + * than crashing the program. + */ + run(fn: (...args: any[]) => T, ...args: any[]): T; + /** + * Explicitly adds an emitter to the domain. If any event handlers called by + * the emitter throw an error, or if the emitter emits an `'error'` event, it + * will be routed to the domain's `'error'` event, just like with implicit + * binding. + * + * This also works with timers that are returned from `setInterval()` and `setTimeout()`. If their callback function throws, it will be caught by + * the domain `'error'` handler. + * + * If the Timer or `EventEmitter` was already bound to a domain, it is removed + * from that one, and bound to this one instead. + * @param emitter emitter or timer to be added to the domain + */ + add(emitter: EventEmitter | NodeJS.Timer): void; + /** + * The opposite of {@link add}. Removes domain handling from the + * specified emitter. + * @param emitter emitter or timer to be removed from the domain + */ + remove(emitter: EventEmitter | NodeJS.Timer): void; + /** + * The returned function will be a wrapper around the supplied callback + * function. When the returned function is called, any errors that are + * thrown will be routed to the domain's `'error'` event. + * + * ```js + * const d = domain.create(); + * + * function readSomeFile(filename, cb) { + * fs.readFile(filename, 'utf8', d.bind((er, data) => { + * // If this throws, it will also be passed to the domain. + * return cb(er, data ? JSON.parse(data) : null); + * })); + * } + * + * d.on('error', (er) => { + * // An error occurred somewhere. If we throw it now, it will crash the program + * // with the normal line number and stack message. + * }); + * ``` + * @param callback The callback function + * @return The bound function + */ + bind(callback: T): T; + /** + * This method is almost identical to {@link bind}. However, in + * addition to catching thrown errors, it will also intercept `Error` objects sent as the first argument to the function. + * + * In this way, the common `if (err) return callback(err);` pattern can be replaced + * with a single error handler in a single place. + * + * ```js + * const d = domain.create(); + * + * function readSomeFile(filename, cb) { + * fs.readFile(filename, 'utf8', d.intercept((data) => { + * // Note, the first argument is never passed to the + * // callback since it is assumed to be the 'Error' argument + * // and thus intercepted by the domain. + * + * // If this throws, it will also be passed to the domain + * // so the error-handling logic can be moved to the 'error' + * // event on the domain instead of being repeated throughout + * // the program. + * return cb(null, JSON.parse(data)); + * })); + * } + * + * d.on('error', (er) => { + * // An error occurred somewhere. If we throw it now, it will crash the program + * // with the normal line number and stack message. + * }); + * ``` + * @param callback The callback function + * @return The intercepted function + */ + intercept(callback: T): T; + } + function create(): Domain; +} +declare module "node:domain" { + export * from "domain"; +} diff --git a/backend/node_modules/@types/node/events.d.ts b/backend/node_modules/@types/node/events.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b1f6ebafd81fd87cb49f1b65f245570ffe810027 --- /dev/null +++ b/backend/node_modules/@types/node/events.d.ts @@ -0,0 +1,819 @@ +/** + * Much of the Node.js core API is built around an idiomatic asynchronous + * event-driven architecture in which certain kinds of objects (called "emitters") + * emit named events that cause `Function` objects ("listeners") to be called. + * + * For instance: a `net.Server` object emits an event each time a peer + * connects to it; a `fs.ReadStream` emits an event when the file is opened; + * a `stream` emits an event whenever data is available to be read. + * + * All objects that emit events are instances of the `EventEmitter` class. These + * objects expose an `eventEmitter.on()` function that allows one or more + * functions to be attached to named events emitted by the object. Typically, + * event names are camel-cased strings but any valid JavaScript property key + * can be used. + * + * When the `EventEmitter` object emits an event, all of the functions attached + * to that specific event are called _synchronously_. Any values returned by the + * called listeners are _ignored_ and discarded. + * + * The following example shows a simple `EventEmitter` instance with a single + * listener. The `eventEmitter.on()` method is used to register listeners, while + * the `eventEmitter.emit()` method is used to trigger the event. + * + * ```js + * const EventEmitter = require('events'); + * + * class MyEmitter extends EventEmitter {} + * + * const myEmitter = new MyEmitter(); + * myEmitter.on('event', () => { + * console.log('an event occurred!'); + * }); + * myEmitter.emit('event'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/events.js) + */ +declare module "events" { + import { AsyncResource, AsyncResourceOptions } from "node:async_hooks"; + + // NOTE: This class is in the docs but is **not actually exported** by Node. + // If https://github.com/nodejs/node/issues/39903 gets resolved and Node + // actually starts exporting the class, uncomment below. + + // import { EventListener, EventListenerObject } from '__dom-events'; + // /** The NodeEventTarget is a Node.js-specific extension to EventTarget that emulates a subset of the EventEmitter API. */ + // interface NodeEventTarget extends EventTarget { + // /** + // * Node.js-specific extension to the `EventTarget` class that emulates the equivalent `EventEmitter` API. + // * The only difference between `addListener()` and `addEventListener()` is that addListener() will return a reference to the EventTarget. + // */ + // addListener(type: string, listener: EventListener | EventListenerObject, options?: { once: boolean }): this; + // /** Node.js-specific extension to the `EventTarget` class that returns an array of event `type` names for which event listeners are registered. */ + // eventNames(): string[]; + // /** Node.js-specific extension to the `EventTarget` class that returns the number of event listeners registered for the `type`. */ + // listenerCount(type: string): number; + // /** Node.js-specific alias for `eventTarget.removeListener()`. */ + // off(type: string, listener: EventListener | EventListenerObject): this; + // /** Node.js-specific alias for `eventTarget.addListener()`. */ + // on(type: string, listener: EventListener | EventListenerObject, options?: { once: boolean }): this; + // /** Node.js-specific extension to the `EventTarget` class that adds a `once` listener for the given event `type`. This is equivalent to calling `on` with the `once` option set to `true`. */ + // once(type: string, listener: EventListener | EventListenerObject): this; + // /** + // * Node.js-specific extension to the `EventTarget` class. + // * If `type` is specified, removes all registered listeners for `type`, + // * otherwise removes all registered listeners. + // */ + // removeAllListeners(type: string): this; + // /** + // * Node.js-specific extension to the `EventTarget` class that removes the listener for the given `type`. + // * The only difference between `removeListener()` and `removeEventListener()` is that `removeListener()` will return a reference to the `EventTarget`. + // */ + // removeListener(type: string, listener: EventListener | EventListenerObject): this; + // } + + interface EventEmitterOptions { + /** + * Enables automatic capturing of promise rejection. + */ + captureRejections?: boolean | undefined; + } + // Any EventTarget with a Node-style `once` function + interface _NodeEventTarget { + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + } + // Any EventTarget with a DOM-style `addEventListener` + interface _DOMEventTarget { + addEventListener( + eventName: string, + listener: (...args: any[]) => void, + opts?: { + once: boolean; + }, + ): any; + } + interface StaticEventEmitterOptions { + signal?: AbortSignal | undefined; + } + interface EventEmitter = DefaultEventMap> extends NodeJS.EventEmitter {} + type EventMap = Record | DefaultEventMap; + type DefaultEventMap = [never]; + type AnyRest = [...args: any[]]; + type Args = T extends DefaultEventMap ? AnyRest : ( + K extends keyof T ? T[K] : never + ); + type Key = T extends DefaultEventMap ? string | symbol : K | keyof T; + type Key2 = T extends DefaultEventMap ? string | symbol : K & keyof T; + type Listener = T extends DefaultEventMap ? F : ( + K extends keyof T ? ( + T[K] extends unknown[] ? (...args: T[K]) => void : never + ) + : never + ); + type Listener1 = Listener void>; + type Listener2 = Listener; + /** + * The `EventEmitter` class is defined and exposed by the `events` module: + * + * ```js + * const EventEmitter = require('events'); + * ``` + * + * All `EventEmitter`s emit the event `'newListener'` when new listeners are + * added and `'removeListener'` when existing listeners are removed. + * + * It supports the following option: + * @since v0.1.26 + */ + class EventEmitter = DefaultEventMap> { + constructor(options?: EventEmitterOptions); + + [EventEmitter.captureRejectionSymbol]?(error: Error, event: Key, ...args: Args): void; + + /** + * Creates a `Promise` that is fulfilled when the `EventEmitter` emits the given + * event or that is rejected if the `EventEmitter` emits `'error'` while waiting. + * The `Promise` will resolve with an array of all the arguments emitted to the + * given event. + * + * This method is intentionally generic and works with the web platform [EventTarget](https://dom.spec.whatwg.org/#interface-eventtarget) interface, which has no special`'error'` event + * semantics and does not listen to the `'error'` event. + * + * ```js + * const { once, EventEmitter } = require('events'); + * + * async function run() { + * const ee = new EventEmitter(); + * + * process.nextTick(() => { + * ee.emit('myevent', 42); + * }); + * + * const [value] = await once(ee, 'myevent'); + * console.log(value); + * + * const err = new Error('kaboom'); + * process.nextTick(() => { + * ee.emit('error', err); + * }); + * + * try { + * await once(ee, 'myevent'); + * } catch (err) { + * console.log('error happened', err); + * } + * } + * + * run(); + * ``` + * + * The special handling of the `'error'` event is only used when `events.once()`is used to wait for another event. If `events.once()` is used to wait for the + * '`error'` event itself, then it is treated as any other kind of event without + * special handling: + * + * ```js + * const { EventEmitter, once } = require('events'); + * + * const ee = new EventEmitter(); + * + * once(ee, 'error') + * .then(([err]) => console.log('ok', err.message)) + * .catch((err) => console.log('error', err.message)); + * + * ee.emit('error', new Error('boom')); + * + * // Prints: ok boom + * ``` + * + * An `AbortSignal` can be used to cancel waiting for the event: + * + * ```js + * const { EventEmitter, once } = require('events'); + * + * const ee = new EventEmitter(); + * const ac = new AbortController(); + * + * async function foo(emitter, event, signal) { + * try { + * await once(emitter, event, { signal }); + * console.log('event emitted!'); + * } catch (error) { + * if (error.name === 'AbortError') { + * console.error('Waiting for the event was canceled!'); + * } else { + * console.error('There was an error', error.message); + * } + * } + * } + * + * foo(ee, 'foo', ac.signal); + * ac.abort(); // Abort waiting for the event + * ee.emit('foo'); // Prints: Waiting for the event was canceled! + * ``` + * @since v11.13.0, v10.16.0 + */ + static once( + emitter: _NodeEventTarget, + eventName: string | symbol, + options?: StaticEventEmitterOptions, + ): Promise; + static once(emitter: _DOMEventTarget, eventName: string, options?: StaticEventEmitterOptions): Promise; + /** + * ```js + * const { on, EventEmitter } = require('events'); + * + * (async () => { + * const ee = new EventEmitter(); + * + * // Emit later on + * process.nextTick(() => { + * ee.emit('foo', 'bar'); + * ee.emit('foo', 42); + * }); + * + * for await (const event of on(ee, 'foo')) { + * // The execution of this inner block is synchronous and it + * // processes one event at a time (even with await). Do not use + * // if concurrent execution is required. + * console.log(event); // prints ['bar'] [42] + * } + * // Unreachable here + * })(); + * ``` + * + * Returns an `AsyncIterator` that iterates `eventName` events. It will throw + * if the `EventEmitter` emits `'error'`. It removes all listeners when + * exiting the loop. The `value` returned by each iteration is an array + * composed of the emitted event arguments. + * + * An `AbortSignal` can be used to cancel waiting on events: + * + * ```js + * const { on, EventEmitter } = require('events'); + * const ac = new AbortController(); + * + * (async () => { + * const ee = new EventEmitter(); + * + * // Emit later on + * process.nextTick(() => { + * ee.emit('foo', 'bar'); + * ee.emit('foo', 42); + * }); + * + * for await (const event of on(ee, 'foo', { signal: ac.signal })) { + * // The execution of this inner block is synchronous and it + * // processes one event at a time (even with await). Do not use + * // if concurrent execution is required. + * console.log(event); // prints ['bar'] [42] + * } + * // Unreachable here + * })(); + * + * process.nextTick(() => ac.abort()); + * ``` + * @since v13.6.0, v12.16.0 + * @param eventName The name of the event being listened for + * @return that iterates `eventName` events emitted by the `emitter` + */ + static on( + emitter: NodeJS.EventEmitter, + eventName: string, + options?: StaticEventEmitterOptions, + ): AsyncIterableIterator; + /** + * A class method that returns the number of listeners for the given `eventName`registered on the given `emitter`. + * + * ```js + * const { EventEmitter, listenerCount } = require('events'); + * const myEmitter = new EventEmitter(); + * myEmitter.on('event', () => {}); + * myEmitter.on('event', () => {}); + * console.log(listenerCount(myEmitter, 'event')); + * // Prints: 2 + * ``` + * @since v0.9.12 + * @deprecated Since v3.2.0 - Use `listenerCount` instead. + * @param emitter The emitter to query + * @param eventName The event name + */ + static listenerCount(emitter: NodeJS.EventEmitter, eventName: string | symbol): number; + /** + * Returns a copy of the array of listeners for the event named `eventName`. + * + * For `EventEmitter`s this behaves exactly the same as calling `.listeners` on + * the emitter. + * + * For `EventTarget`s this is the only way to get the event listeners for the + * event target. This is useful for debugging and diagnostic purposes. + * + * ```js + * const { getEventListeners, EventEmitter } = require('events'); + * + * { + * const ee = new EventEmitter(); + * const listener = () => console.log('Events are fun'); + * ee.on('foo', listener); + * getEventListeners(ee, 'foo'); // [listener] + * } + * { + * const et = new EventTarget(); + * const listener = () => console.log('Events are fun'); + * et.addEventListener('foo', listener); + * getEventListeners(et, 'foo'); // [listener] + * } + * ``` + * @since v15.2.0, v14.17.0 + */ + static getEventListeners(emitter: _DOMEventTarget | NodeJS.EventEmitter, name: string | symbol): Function[]; + /** + * Returns the currently set max amount of listeners. + * + * For `EventEmitter`s this behaves exactly the same as calling `.getMaxListeners` on + * the emitter. + * + * For `EventTarget`s this is the only way to get the max event listeners for the + * event target. If the number of event handlers on a single EventTarget exceeds + * the max set, the EventTarget will print a warning. + * + * ```js + * import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events'; + * + * { + * const ee = new EventEmitter(); + * console.log(getMaxListeners(ee)); // 10 + * setMaxListeners(11, ee); + * console.log(getMaxListeners(ee)); // 11 + * } + * { + * const et = new EventTarget(); + * console.log(getMaxListeners(et)); // 10 + * setMaxListeners(11, et); + * console.log(getMaxListeners(et)); // 11 + * } + * ``` + * @since v18.17.0 + */ + static getMaxListeners(emitter: _DOMEventTarget | NodeJS.EventEmitter): number; + /** + * ```js + * const { + * setMaxListeners, + * EventEmitter + * } = require('events'); + * + * const target = new EventTarget(); + * const emitter = new EventEmitter(); + * + * setMaxListeners(5, target, emitter); + * ``` + * @since v15.4.0 + * @param n A non-negative number. The maximum number of listeners per `EventTarget` event. + * @param eventsTargets Zero or more {EventTarget} or {EventEmitter} instances. If none are specified, `n` is set as the default max for all newly created {EventTarget} and {EventEmitter} + * objects. + */ + static setMaxListeners(n?: number, ...eventTargets: Array<_DOMEventTarget | NodeJS.EventEmitter>): void; + /** + * Listens once to the `abort` event on the provided `signal`. + * + * Listening to the `abort` event on abort signals is unsafe and may + * lead to resource leaks since another third party with the signal can + * call `e.stopImmediatePropagation()`. Unfortunately Node.js cannot change + * this since it would violate the web standard. Additionally, the original + * API makes it easy to forget to remove listeners. + * + * This API allows safely using `AbortSignal`s in Node.js APIs by solving these + * two issues by listening to the event such that `stopImmediatePropagation` does + * not prevent the listener from running. + * + * Returns a disposable so that it may be unsubscribed from more easily. + * + * ```js + * import { addAbortListener } from 'node:events'; + * + * function example(signal) { + * let disposable; + * try { + * signal.addEventListener('abort', (e) => e.stopImmediatePropagation()); + * disposable = addAbortListener(signal, (e) => { + * // Do something when signal is aborted. + * }); + * } finally { + * disposable?.[Symbol.dispose](); + * } + * } + * ``` + * @since v18.18.0 + * @experimental + * @return Disposable that removes the `abort` listener. + */ + static addAbortListener(signal: AbortSignal, resource: (event: Event) => void): Disposable; + /** + * This symbol shall be used to install a listener for only monitoring `'error'` + * events. Listeners installed using this symbol are called before the regular + * `'error'` listeners are called. + * + * Installing a listener using this symbol does not change the behavior once an + * `'error'` event is emitted, therefore the process will still crash if no + * regular `'error'` listener is installed. + */ + static readonly errorMonitor: unique symbol; + static readonly captureRejectionSymbol: unique symbol; + /** + * Sets or gets the default captureRejection value for all emitters. + */ + // TODO: These should be described using static getter/setter pairs: + static captureRejections: boolean; + static defaultMaxListeners: number; + } + import internal = require("node:events"); + namespace EventEmitter { + // Should just be `export { EventEmitter }`, but that doesn't work in TypeScript 3.4 + export { internal as EventEmitter }; + export interface Abortable { + /** + * When provided the corresponding `AbortController` can be used to cancel an asynchronous action. + */ + signal?: AbortSignal | undefined; + } + + export interface EventEmitterReferencingAsyncResource extends AsyncResource { + readonly eventEmitter: EventEmitterAsyncResource; + } + + export interface EventEmitterAsyncResourceOptions extends AsyncResourceOptions, EventEmitterOptions { + /** + * The type of async event, this is required when instantiating `EventEmitterAsyncResource` + * directly rather than as a child class. + * @default new.target.name if instantiated as a child class. + */ + name?: string; + } + + /** + * Integrates `EventEmitter` with `AsyncResource` for `EventEmitter`s that require + * manual async tracking. Specifically, all events emitted by instances of + * `EventEmitterAsyncResource` will run within its async context. + * + * The EventEmitterAsyncResource class has the same methods and takes the + * same options as EventEmitter and AsyncResource themselves. + * @throws if `options.name` is not provided when instantiated directly. + * @since v17.4.0, v16.14.0 + */ + export class EventEmitterAsyncResource extends EventEmitter { + /** + * @param options Only optional in child class. + */ + constructor(options?: EventEmitterAsyncResourceOptions); + /** + * Call all destroy hooks. This should only ever be called once. An + * error will be thrown if it is called more than once. This must be + * manually called. If the resource is left to be collected by the GC then + * the destroy hooks will never be called. + */ + emitDestroy(): void; + /** The unique asyncId assigned to the resource. */ + readonly asyncId: number; + /** The same triggerAsyncId that is passed to the AsyncResource constructor. */ + readonly triggerAsyncId: number; + /** The underlying AsyncResource */ + readonly asyncResource: EventEmitterReferencingAsyncResource; + } + } + global { + namespace NodeJS { + interface EventEmitter = DefaultEventMap> { + [EventEmitter.captureRejectionSymbol]?(error: Error, event: Key, ...args: Args): void; + /** + * Alias for `emitter.on(eventName, listener)`. + * @since v0.1.26 + */ + addListener(eventName: Key, listener: Listener1): this; + /** + * Adds the `listener` function to the end of the listeners array for the + * event named `eventName`. No checks are made to see if the `listener` has + * already been added. Multiple calls passing the same combination of `eventName`and `listener` will result in the `listener` being added, and called, multiple + * times. + * + * ```js + * server.on('connection', (stream) => { + * console.log('someone connected!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * + * By default, event listeners are invoked in the order they are added. The`emitter.prependListener()` method can be used as an alternative to add the + * event listener to the beginning of the listeners array. + * + * ```js + * const myEE = new EventEmitter(); + * myEE.on('foo', () => console.log('a')); + * myEE.prependListener('foo', () => console.log('b')); + * myEE.emit('foo'); + * // Prints: + * // b + * // a + * ``` + * @since v0.1.101 + * @param eventName The name of the event. + * @param listener The callback function + */ + on(eventName: Key, listener: Listener1): this; + /** + * Adds a **one-time**`listener` function for the event named `eventName`. The + * next time `eventName` is triggered, this listener is removed and then invoked. + * + * ```js + * server.once('connection', (stream) => { + * console.log('Ah, we have our first user!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * + * By default, event listeners are invoked in the order they are added. The`emitter.prependOnceListener()` method can be used as an alternative to add the + * event listener to the beginning of the listeners array. + * + * ```js + * const myEE = new EventEmitter(); + * myEE.once('foo', () => console.log('a')); + * myEE.prependOnceListener('foo', () => console.log('b')); + * myEE.emit('foo'); + * // Prints: + * // b + * // a + * ``` + * @since v0.3.0 + * @param eventName The name of the event. + * @param listener The callback function + */ + once(eventName: Key, listener: Listener1): this; + /** + * Removes the specified `listener` from the listener array for the event named`eventName`. + * + * ```js + * const callback = (stream) => { + * console.log('someone connected!'); + * }; + * server.on('connection', callback); + * // ... + * server.removeListener('connection', callback); + * ``` + * + * `removeListener()` will remove, at most, one instance of a listener from the + * listener array. If any single listener has been added multiple times to the + * listener array for the specified `eventName`, then `removeListener()` must be + * called multiple times to remove each instance. + * + * Once an event is emitted, all listeners attached to it at the + * time of emitting are called in order. This implies that any`removeListener()` or `removeAllListeners()` calls _after_ emitting and _before_ the last listener finishes execution + * will not remove them from`emit()` in progress. Subsequent events behave as expected. + * + * ```js + * const myEmitter = new MyEmitter(); + * + * const callbackA = () => { + * console.log('A'); + * myEmitter.removeListener('event', callbackB); + * }; + * + * const callbackB = () => { + * console.log('B'); + * }; + * + * myEmitter.on('event', callbackA); + * + * myEmitter.on('event', callbackB); + * + * // callbackA removes listener callbackB but it will still be called. + * // Internal listener array at time of emit [callbackA, callbackB] + * myEmitter.emit('event'); + * // Prints: + * // A + * // B + * + * // callbackB is now removed. + * // Internal listener array [callbackA] + * myEmitter.emit('event'); + * // Prints: + * // A + * ``` + * + * Because listeners are managed using an internal array, calling this will + * change the position indices of any listener registered _after_ the listener + * being removed. This will not impact the order in which listeners are called, + * but it means that any copies of the listener array as returned by + * the `emitter.listeners()` method will need to be recreated. + * + * When a single function has been added as a handler multiple times for a single + * event (as in the example below), `removeListener()` will remove the most + * recently added instance. In the example the `once('ping')`listener is removed: + * + * ```js + * const ee = new EventEmitter(); + * + * function pong() { + * console.log('pong'); + * } + * + * ee.on('ping', pong); + * ee.once('ping', pong); + * ee.removeListener('ping', pong); + * + * ee.emit('ping'); + * ee.emit('ping'); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v0.1.26 + */ + removeListener(eventName: Key, listener: Listener1): this; + /** + * Alias for `emitter.removeListener()`. + * @since v10.0.0 + */ + off(eventName: Key, listener: Listener1): this; + /** + * Removes all listeners, or those of the specified `eventName`. + * + * It is bad practice to remove listeners added elsewhere in the code, + * particularly when the `EventEmitter` instance was created by some other + * component or module (e.g. sockets or file streams). + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v0.1.26 + */ + removeAllListeners(event?: Key): this; + /** + * By default `EventEmitter`s will print a warning if more than `10` listeners are + * added for a particular event. This is a useful default that helps finding + * memory leaks. The `emitter.setMaxListeners()` method allows the limit to be + * modified for this specific `EventEmitter` instance. The value can be set to`Infinity` (or `0`) to indicate an unlimited number of listeners. + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v0.3.5 + */ + setMaxListeners(n: number): this; + /** + * Returns the current max listener value for the `EventEmitter` which is either + * set by `emitter.setMaxListeners(n)` or defaults to {@link defaultMaxListeners}. + * @since v1.0.0 + */ + getMaxListeners(): number; + /** + * Returns a copy of the array of listeners for the event named `eventName`. + * + * ```js + * server.on('connection', (stream) => { + * console.log('someone connected!'); + * }); + * console.log(util.inspect(server.listeners('connection'))); + * // Prints: [ [Function] ] + * ``` + * @since v0.1.26 + */ + listeners(eventName: Key): Array>; + /** + * Returns a copy of the array of listeners for the event named `eventName`, + * including any wrappers (such as those created by `.once()`). + * + * ```js + * const emitter = new EventEmitter(); + * emitter.once('log', () => console.log('log once')); + * + * // Returns a new Array with a function `onceWrapper` which has a property + * // `listener` which contains the original listener bound above + * const listeners = emitter.rawListeners('log'); + * const logFnWrapper = listeners[0]; + * + * // Logs "log once" to the console and does not unbind the `once` event + * logFnWrapper.listener(); + * + * // Logs "log once" to the console and removes the listener + * logFnWrapper(); + * + * emitter.on('log', () => console.log('log persistently')); + * // Will return a new Array with a single function bound by `.on()` above + * const newListeners = emitter.rawListeners('log'); + * + * // Logs "log persistently" twice + * newListeners[0](); + * emitter.emit('log'); + * ``` + * @since v9.4.0 + */ + rawListeners(eventName: Key): Array>; + /** + * Synchronously calls each of the listeners registered for the event named`eventName`, in the order they were registered, passing the supplied arguments + * to each. + * + * Returns `true` if the event had listeners, `false` otherwise. + * + * ```js + * const EventEmitter = require('events'); + * const myEmitter = new EventEmitter(); + * + * // First listener + * myEmitter.on('event', function firstListener() { + * console.log('Helloooo! first listener'); + * }); + * // Second listener + * myEmitter.on('event', function secondListener(arg1, arg2) { + * console.log(`event with parameters ${arg1}, ${arg2} in second listener`); + * }); + * // Third listener + * myEmitter.on('event', function thirdListener(...args) { + * const parameters = args.join(', '); + * console.log(`event with parameters ${parameters} in third listener`); + * }); + * + * console.log(myEmitter.listeners('event')); + * + * myEmitter.emit('event', 1, 2, 3, 4, 5); + * + * // Prints: + * // [ + * // [Function: firstListener], + * // [Function: secondListener], + * // [Function: thirdListener] + * // ] + * // Helloooo! first listener + * // event with parameters 1, 2 in second listener + * // event with parameters 1, 2, 3, 4, 5 in third listener + * ``` + * @since v0.1.26 + */ + emit(eventName: Key, ...args: Args): boolean; + /** + * Returns the number of listeners listening to the event named `eventName`. + * + * If `listener` is provided, it will return how many times the listener + * is found in the list of the listeners of the event. + * @since v3.2.0 + * @param eventName The name of the event being listened for + * @param listener The event handler function + */ + listenerCount(eventName: Key, listener?: Listener2): number; + /** + * Adds the `listener` function to the _beginning_ of the listeners array for the + * event named `eventName`. No checks are made to see if the `listener` has + * already been added. Multiple calls passing the same combination of `eventName`and `listener` will result in the `listener` being added, and called, multiple + * times. + * + * ```js + * server.prependListener('connection', (stream) => { + * console.log('someone connected!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v6.0.0 + * @param eventName The name of the event. + * @param listener The callback function + */ + prependListener(eventName: Key, listener: Listener1): this; + /** + * Adds a **one-time**`listener` function for the event named `eventName` to the _beginning_ of the listeners array. The next time `eventName` is triggered, this + * listener is removed, and then invoked. + * + * ```js + * server.prependOnceListener('connection', (stream) => { + * console.log('Ah, we have our first user!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v6.0.0 + * @param eventName The name of the event. + * @param listener The callback function + */ + prependOnceListener(eventName: Key, listener: Listener1): this; + /** + * Returns an array listing the events for which the emitter has registered + * listeners. The values in the array are strings or `Symbol`s. + * + * ```js + * const EventEmitter = require('events'); + * const myEE = new EventEmitter(); + * myEE.on('foo', () => {}); + * myEE.on('bar', () => {}); + * + * const sym = Symbol('symbol'); + * myEE.on(sym, () => {}); + * + * console.log(myEE.eventNames()); + * // Prints: [ 'foo', 'bar', Symbol(symbol) ] + * ``` + * @since v6.0.0 + */ + eventNames(): Array<(string | symbol) & Key2>; + } + } + } + export = EventEmitter; +} +declare module "node:events" { + import events = require("events"); + export = events; +} diff --git a/backend/node_modules/@types/node/fs.d.ts b/backend/node_modules/@types/node/fs.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b36d51c99098c917ae6e46a8f834dcd781ba1e7a --- /dev/null +++ b/backend/node_modules/@types/node/fs.d.ts @@ -0,0 +1,4231 @@ +/** + * The `fs` module enables interacting with the file system in a + * way modeled on standard POSIX functions. + * + * To use the promise-based APIs: + * + * ```js + * import * as fs from 'fs/promises'; + * ``` + * + * To use the callback and sync APIs: + * + * ```js + * import * as fs from 'fs'; + * ``` + * + * All file system operations have synchronous, callback, and promise-based + * forms, and are accessible using both CommonJS syntax and ES6 Modules (ESM). + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/fs.js) + */ +declare module "fs" { + import * as stream from "node:stream"; + import { Abortable, EventEmitter } from "node:events"; + import { URL } from "node:url"; + import * as promises from "node:fs/promises"; + export { promises }; + /** + * Valid types for path values in "fs". + */ + export type PathLike = string | Buffer | URL; + export type PathOrFileDescriptor = PathLike | number; + export type TimeLike = string | number | Date; + export type NoParamCallback = (err: NodeJS.ErrnoException | null) => void; + export type BufferEncodingOption = + | "buffer" + | { + encoding: "buffer"; + }; + export interface ObjectEncodingOptions { + encoding?: BufferEncoding | null | undefined; + } + export type EncodingOption = ObjectEncodingOptions | BufferEncoding | undefined | null; + export type OpenMode = number | string; + export type Mode = number | string; + export interface StatsBase { + isFile(): boolean; + isDirectory(): boolean; + isBlockDevice(): boolean; + isCharacterDevice(): boolean; + isSymbolicLink(): boolean; + isFIFO(): boolean; + isSocket(): boolean; + dev: T; + ino: T; + mode: T; + nlink: T; + uid: T; + gid: T; + rdev: T; + size: T; + blksize: T; + blocks: T; + atimeMs: T; + mtimeMs: T; + ctimeMs: T; + birthtimeMs: T; + atime: Date; + mtime: Date; + ctime: Date; + birthtime: Date; + } + export interface Stats extends StatsBase {} + /** + * A `fs.Stats` object provides information about a file. + * + * Objects returned from {@link stat}, {@link lstat} and {@link fstat} and + * their synchronous counterparts are of this type. + * If `bigint` in the `options` passed to those methods is true, the numeric values + * will be `bigint` instead of `number`, and the object will contain additional + * nanosecond-precision properties suffixed with `Ns`. + * + * ```console + * Stats { + * dev: 2114, + * ino: 48064969, + * mode: 33188, + * nlink: 1, + * uid: 85, + * gid: 100, + * rdev: 0, + * size: 527, + * blksize: 4096, + * blocks: 8, + * atimeMs: 1318289051000.1, + * mtimeMs: 1318289051000.1, + * ctimeMs: 1318289051000.1, + * birthtimeMs: 1318289051000.1, + * atime: Mon, 10 Oct 2011 23:24:11 GMT, + * mtime: Mon, 10 Oct 2011 23:24:11 GMT, + * ctime: Mon, 10 Oct 2011 23:24:11 GMT, + * birthtime: Mon, 10 Oct 2011 23:24:11 GMT } + * ``` + * + * `bigint` version: + * + * ```console + * BigIntStats { + * dev: 2114n, + * ino: 48064969n, + * mode: 33188n, + * nlink: 1n, + * uid: 85n, + * gid: 100n, + * rdev: 0n, + * size: 527n, + * blksize: 4096n, + * blocks: 8n, + * atimeMs: 1318289051000n, + * mtimeMs: 1318289051000n, + * ctimeMs: 1318289051000n, + * birthtimeMs: 1318289051000n, + * atimeNs: 1318289051000000000n, + * mtimeNs: 1318289051000000000n, + * ctimeNs: 1318289051000000000n, + * birthtimeNs: 1318289051000000000n, + * atime: Mon, 10 Oct 2011 23:24:11 GMT, + * mtime: Mon, 10 Oct 2011 23:24:11 GMT, + * ctime: Mon, 10 Oct 2011 23:24:11 GMT, + * birthtime: Mon, 10 Oct 2011 23:24:11 GMT } + * ``` + * @since v0.1.21 + */ + export class Stats {} + + export interface StatsFsBase { + /** Type of file system. */ + type: T; + /** Optimal transfer block size. */ + bsize: T; + /** Total data blocks in file system. */ + blocks: T; + /** Free blocks in file system. */ + bfree: T; + /** Available blocks for unprivileged users */ + bavail: T; + /** Total file nodes in file system. */ + files: T; + /** Free file nodes in file system. */ + ffree: T; + } + + export interface StatsFs extends StatsFsBase {} + + /** + * Provides information about a mounted file system + * + * Objects returned from {@link statfs} and {@link statfsSync} are of this type. + * If `bigint` in the `options` passed to those methods is true, the numeric values + * will be `bigint` instead of `number`. + * @since v18.15.0 + */ + export class StatsFs {} + + export interface BigIntStatsFs extends StatsFsBase {} + + export interface StatFsOptions { + bigint?: boolean | undefined; + } + + /** + * A representation of a directory entry, which can be a file or a subdirectory + * within the directory, as returned by reading from an `fs.Dir`. The + * directory entry is a combination of the file name and file type pairs. + * + * Additionally, when {@link readdir} or {@link readdirSync} is called with + * the `withFileTypes` option set to `true`, the resulting array is filled with `fs.Dirent` objects, rather than strings or `Buffer` s. + * @since v10.10.0 + */ + export class Dirent { + /** + * Returns `true` if the `fs.Dirent` object describes a regular file. + * @since v10.10.0 + */ + isFile(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a file system + * directory. + * @since v10.10.0 + */ + isDirectory(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a block device. + * @since v10.10.0 + */ + isBlockDevice(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a character device. + * @since v10.10.0 + */ + isCharacterDevice(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a symbolic link. + * @since v10.10.0 + */ + isSymbolicLink(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a first-in-first-out + * (FIFO) pipe. + * @since v10.10.0 + */ + isFIFO(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a socket. + * @since v10.10.0 + */ + isSocket(): boolean; + /** + * The file name that this `fs.Dirent` object refers to. The type of this + * value is determined by the `options.encoding` passed to {@link readdir} or {@link readdirSync}. + * @since v10.10.0 + */ + name: string; + /** + * The base path that this `fs.Dirent` object refers to. + * @since v18.17.0 + */ + path: string; + } + /** + * A class representing a directory stream. + * + * Created by {@link opendir}, {@link opendirSync}, or `fsPromises.opendir()`. + * + * ```js + * import { opendir } from 'fs/promises'; + * + * try { + * const dir = await opendir('./'); + * for await (const dirent of dir) + * console.log(dirent.name); + * } catch (err) { + * console.error(err); + * } + * ``` + * + * When using the async iterator, the `fs.Dir` object will be automatically + * closed after the iterator exits. + * @since v12.12.0 + */ + export class Dir implements AsyncIterable { + /** + * The read-only path of this directory as was provided to {@link opendir},{@link opendirSync}, or `fsPromises.opendir()`. + * @since v12.12.0 + */ + readonly path: string; + /** + * Asynchronously iterates over the directory via `readdir(3)` until all entries have been read. + */ + [Symbol.asyncIterator](): AsyncIterableIterator; + /** + * Asynchronously close the directory's underlying resource handle. + * Subsequent reads will result in errors. + * + * A promise is returned that will be resolved after the resource has been + * closed. + * @since v12.12.0 + */ + close(): Promise; + close(cb: NoParamCallback): void; + /** + * Synchronously close the directory's underlying resource handle. + * Subsequent reads will result in errors. + * @since v12.12.0 + */ + closeSync(): void; + /** + * Asynchronously read the next directory entry via [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) as an `fs.Dirent`. + * + * A promise is returned that will be resolved with an `fs.Dirent`, or `null`if there are no more directory entries to read. + * + * Directory entries returned by this function are in no particular order as + * provided by the operating system's underlying directory mechanisms. + * Entries added or removed while iterating over the directory might not be + * included in the iteration results. + * @since v12.12.0 + * @return containing {fs.Dirent|null} + */ + read(): Promise; + read(cb: (err: NodeJS.ErrnoException | null, dirEnt: Dirent | null) => void): void; + /** + * Synchronously read the next directory entry as an `fs.Dirent`. See the + * POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more detail. + * + * If there are no more directory entries to read, `null` will be returned. + * + * Directory entries returned by this function are in no particular order as + * provided by the operating system's underlying directory mechanisms. + * Entries added or removed while iterating over the directory might not be + * included in the iteration results. + * @since v12.12.0 + */ + readSync(): Dirent | null; + } + /** + * Class: fs.StatWatcher + * @since v14.3.0, v12.20.0 + * Extends `EventEmitter` + * A successful call to {@link watchFile} method will return a new fs.StatWatcher object. + */ + export interface StatWatcher extends EventEmitter { + /** + * When called, requests that the Node.js event loop _not_ exit so long as the `fs.StatWatcher` is active. Calling `watcher.ref()` multiple times will have + * no effect. + * + * By default, all `fs.StatWatcher` objects are "ref'ed", making it normally + * unnecessary to call `watcher.ref()` unless `watcher.unref()` had been + * called previously. + * @since v14.3.0, v12.20.0 + */ + ref(): this; + /** + * When called, the active `fs.StatWatcher` object will not require the Node.js + * event loop to remain active. If there is no other activity keeping the + * event loop running, the process may exit before the `fs.StatWatcher` object's + * callback is invoked. Calling `watcher.unref()` multiple times will have + * no effect. + * @since v14.3.0, v12.20.0 + */ + unref(): this; + } + export interface FSWatcher extends EventEmitter { + /** + * Stop watching for changes on the given `fs.FSWatcher`. Once stopped, the `fs.FSWatcher` object is no longer usable. + * @since v0.5.8 + */ + close(): void; + /** + * When called, requests that the Node.js event loop _not_ exit so long as the `fs.FSWatcher` is active. Calling `watcher.ref()` multiple times will have + * no effect. + * + * By default, all `fs.FSWatcher` objects are "ref'ed", making it normally + * unnecessary to call `watcher.ref()` unless `watcher.unref()` had been + * called previously. + * @since v14.3.0, v12.20.0 + */ + ref(): this; + /** + * When called, the active `fs.FSWatcher` object will not require the Node.js + * event loop to remain active. If there is no other activity keeping the + * event loop running, the process may exit before the `fs.FSWatcher` object's + * callback is invoked. Calling `watcher.unref()` multiple times will have + * no effect. + * @since v14.3.0, v12.20.0 + */ + unref(): this; + /** + * events.EventEmitter + * 1. change + * 2. close + * 3. error + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "error", listener: (error: Error) => void): this; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + on(event: "close", listener: () => void): this; + on(event: "error", listener: (error: Error) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + once(event: "close", listener: () => void): this; + once(event: "error", listener: (error: Error) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "error", listener: (error: Error) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "error", listener: (error: Error) => void): this; + } + /** + * Instances of `fs.ReadStream` are created and returned using the {@link createReadStream} function. + * @since v0.1.93 + */ + export class ReadStream extends stream.Readable { + close(callback?: (err?: NodeJS.ErrnoException | null) => void): void; + /** + * The number of bytes that have been read so far. + * @since v6.4.0 + */ + bytesRead: number; + /** + * The path to the file the stream is reading from as specified in the first + * argument to `fs.createReadStream()`. If `path` is passed as a string, then`readStream.path` will be a string. If `path` is passed as a `Buffer`, then`readStream.path` will be a + * `Buffer`. If `fd` is specified, then`readStream.path` will be `undefined`. + * @since v0.1.93 + */ + path: string | Buffer; + /** + * This property is `true` if the underlying file has not been opened yet, + * i.e. before the `'ready'` event is emitted. + * @since v11.2.0, v10.16.0 + */ + pending: boolean; + /** + * events.EventEmitter + * 1. open + * 2. close + * 3. ready + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: Buffer | string) => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "open", listener: (fd: number) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "ready", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: Buffer | string) => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "open", listener: (fd: number) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "readable", listener: () => void): this; + on(event: "ready", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: Buffer | string) => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "open", listener: (fd: number) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "readable", listener: () => void): this; + once(event: "ready", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "open", listener: (fd: number) => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "ready", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "open", listener: (fd: number) => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "ready", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * * Extends `stream.Writable` + * + * Instances of `fs.WriteStream` are created and returned using the {@link createWriteStream} function. + * @since v0.1.93 + */ + export class WriteStream extends stream.Writable { + /** + * Closes `writeStream`. Optionally accepts a + * callback that will be executed once the `writeStream`is closed. + * @since v0.9.4 + */ + close(callback?: (err?: NodeJS.ErrnoException | null) => void): void; + /** + * The number of bytes written so far. Does not include data that is still queued + * for writing. + * @since v0.4.7 + */ + bytesWritten: number; + /** + * The path to the file the stream is writing to as specified in the first + * argument to {@link createWriteStream}. If `path` is passed as a string, then`writeStream.path` will be a string. If `path` is passed as a `Buffer`, then`writeStream.path` will be a + * `Buffer`. + * @since v0.1.93 + */ + path: string | Buffer; + /** + * This property is `true` if the underlying file has not been opened yet, + * i.e. before the `'ready'` event is emitted. + * @since v11.2.0 + */ + pending: boolean; + /** + * events.EventEmitter + * 1. open + * 2. close + * 3. ready + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "open", listener: (fd: number) => void): this; + addListener(event: "pipe", listener: (src: stream.Readable) => void): this; + addListener(event: "ready", listener: () => void): this; + addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "open", listener: (fd: number) => void): this; + on(event: "pipe", listener: (src: stream.Readable) => void): this; + on(event: "ready", listener: () => void): this; + on(event: "unpipe", listener: (src: stream.Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "open", listener: (fd: number) => void): this; + once(event: "pipe", listener: (src: stream.Readable) => void): this; + once(event: "ready", listener: () => void): this; + once(event: "unpipe", listener: (src: stream.Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "open", listener: (fd: number) => void): this; + prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "ready", listener: () => void): this; + prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "open", listener: (fd: number) => void): this; + prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "ready", listener: () => void): this; + prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * Asynchronously rename file at `oldPath` to the pathname provided + * as `newPath`. In the case that `newPath` already exists, it will + * be overwritten. If there is a directory at `newPath`, an error will + * be raised instead. No arguments other than a possible exception are + * given to the completion callback. + * + * See also: [`rename(2)`](http://man7.org/linux/man-pages/man2/rename.2.html). + * + * ```js + * import { rename } from 'fs'; + * + * rename('oldFile.txt', 'newFile.txt', (err) => { + * if (err) throw err; + * console.log('Rename complete!'); + * }); + * ``` + * @since v0.0.2 + */ + export function rename(oldPath: PathLike, newPath: PathLike, callback: NoParamCallback): void; + export namespace rename { + /** + * Asynchronous rename(2) - Change the name or location of a file or directory. + * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(oldPath: PathLike, newPath: PathLike): Promise; + } + /** + * Renames the file from `oldPath` to `newPath`. Returns `undefined`. + * + * See the POSIX [`rename(2)`](http://man7.org/linux/man-pages/man2/rename.2.html) documentation for more details. + * @since v0.1.21 + */ + export function renameSync(oldPath: PathLike, newPath: PathLike): void; + /** + * Truncates the file. No arguments other than a possible exception are + * given to the completion callback. A file descriptor can also be passed as the + * first argument. In this case, `fs.ftruncate()` is called. + * + * ```js + * import { truncate } from 'fs'; + * // Assuming that 'path/file.txt' is a regular file. + * truncate('path/file.txt', (err) => { + * if (err) throw err; + * console.log('path/file.txt was truncated'); + * }); + * ``` + * + * Passing a file descriptor is deprecated and may result in an error being thrown + * in the future. + * + * See the POSIX [`truncate(2)`](http://man7.org/linux/man-pages/man2/truncate.2.html) documentation for more details. + * @since v0.8.6 + * @param [len=0] + */ + export function truncate(path: PathLike, len: number | undefined | null, callback: NoParamCallback): void; + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function truncate(path: PathLike, callback: NoParamCallback): void; + export namespace truncate { + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param len If not specified, defaults to `0`. + */ + function __promisify__(path: PathLike, len?: number | null): Promise; + } + /** + * Truncates the file. Returns `undefined`. A file descriptor can also be + * passed as the first argument. In this case, `fs.ftruncateSync()` is called. + * + * Passing a file descriptor is deprecated and may result in an error being thrown + * in the future. + * @since v0.8.6 + * @param [len=0] + */ + export function truncateSync(path: PathLike, len?: number | null): void; + /** + * Truncates the file descriptor. No arguments other than a possible exception are + * given to the completion callback. + * + * See the POSIX [`ftruncate(2)`](http://man7.org/linux/man-pages/man2/ftruncate.2.html) documentation for more detail. + * + * If the file referred to by the file descriptor was larger than `len` bytes, only + * the first `len` bytes will be retained in the file. + * + * For example, the following program retains only the first four bytes of the + * file: + * + * ```js + * import { open, close, ftruncate } from 'fs'; + * + * function closeFd(fd) { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * + * open('temp.txt', 'r+', (err, fd) => { + * if (err) throw err; + * + * try { + * ftruncate(fd, 4, (err) => { + * closeFd(fd); + * if (err) throw err; + * }); + * } catch (err) { + * closeFd(fd); + * if (err) throw err; + * } + * }); + * ``` + * + * If the file previously was shorter than `len` bytes, it is extended, and the + * extended part is filled with null bytes (`'\0'`): + * + * If `len` is negative then `0` will be used. + * @since v0.8.6 + * @param [len=0] + */ + export function ftruncate(fd: number, len: number | undefined | null, callback: NoParamCallback): void; + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + */ + export function ftruncate(fd: number, callback: NoParamCallback): void; + export namespace ftruncate { + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + * @param len If not specified, defaults to `0`. + */ + function __promisify__(fd: number, len?: number | null): Promise; + } + /** + * Truncates the file descriptor. Returns `undefined`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link ftruncate}. + * @since v0.8.6 + * @param [len=0] + */ + export function ftruncateSync(fd: number, len?: number | null): void; + /** + * Asynchronously changes owner and group of a file. No arguments other than a + * possible exception are given to the completion callback. + * + * See the POSIX [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html) documentation for more detail. + * @since v0.1.97 + */ + export function chown(path: PathLike, uid: number, gid: number, callback: NoParamCallback): void; + export namespace chown { + /** + * Asynchronous chown(2) - Change ownership of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, uid: number, gid: number): Promise; + } + /** + * Synchronously changes owner and group of a file. Returns `undefined`. + * This is the synchronous version of {@link chown}. + * + * See the POSIX [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html) documentation for more detail. + * @since v0.1.97 + */ + export function chownSync(path: PathLike, uid: number, gid: number): void; + /** + * Sets the owner of the file. No arguments other than a possible exception are + * given to the completion callback. + * + * See the POSIX [`fchown(2)`](http://man7.org/linux/man-pages/man2/fchown.2.html) documentation for more detail. + * @since v0.4.7 + */ + export function fchown(fd: number, uid: number, gid: number, callback: NoParamCallback): void; + export namespace fchown { + /** + * Asynchronous fchown(2) - Change ownership of a file. + * @param fd A file descriptor. + */ + function __promisify__(fd: number, uid: number, gid: number): Promise; + } + /** + * Sets the owner of the file. Returns `undefined`. + * + * See the POSIX [`fchown(2)`](http://man7.org/linux/man-pages/man2/fchown.2.html) documentation for more detail. + * @since v0.4.7 + * @param uid The file's new owner's user id. + * @param gid The file's new group's group id. + */ + export function fchownSync(fd: number, uid: number, gid: number): void; + /** + * Set the owner of the symbolic link. No arguments other than a possible + * exception are given to the completion callback. + * + * See the POSIX [`lchown(2)`](http://man7.org/linux/man-pages/man2/lchown.2.html) documentation for more detail. + */ + export function lchown(path: PathLike, uid: number, gid: number, callback: NoParamCallback): void; + export namespace lchown { + /** + * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, uid: number, gid: number): Promise; + } + /** + * Set the owner for the path. Returns `undefined`. + * + * See the POSIX [`lchown(2)`](http://man7.org/linux/man-pages/man2/lchown.2.html) documentation for more details. + * @param uid The file's new owner's user id. + * @param gid The file's new group's group id. + */ + export function lchownSync(path: PathLike, uid: number, gid: number): void; + /** + * Changes the access and modification times of a file in the same way as {@link utimes}, with the difference that if the path refers to a symbolic + * link, then the link is not dereferenced: instead, the timestamps of the + * symbolic link itself are changed. + * + * No arguments other than a possible exception are given to the completion + * callback. + * @since v14.5.0, v12.19.0 + */ + export function lutimes(path: PathLike, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; + export namespace lutimes { + /** + * Changes the access and modification times of a file in the same way as `fsPromises.utimes()`, + * with the difference that if the path refers to a symbolic link, then the link is not + * dereferenced: instead, the timestamps of the symbolic link itself are changed. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; + } + /** + * Change the file system timestamps of the symbolic link referenced by `path`. + * Returns `undefined`, or throws an exception when parameters are incorrect or + * the operation fails. This is the synchronous version of {@link lutimes}. + * @since v14.5.0, v12.19.0 + */ + export function lutimesSync(path: PathLike, atime: TimeLike, mtime: TimeLike): void; + /** + * Asynchronously changes the permissions of a file. No arguments other than a + * possible exception are given to the completion callback. + * + * See the POSIX [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html) documentation for more detail. + * + * ```js + * import { chmod } from 'fs'; + * + * chmod('my_file.txt', 0o775, (err) => { + * if (err) throw err; + * console.log('The permissions for file "my_file.txt" have been changed!'); + * }); + * ``` + * @since v0.1.30 + */ + export function chmod(path: PathLike, mode: Mode, callback: NoParamCallback): void; + export namespace chmod { + /** + * Asynchronous chmod(2) - Change permissions of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(path: PathLike, mode: Mode): Promise; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link chmod}. + * + * See the POSIX [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html) documentation for more detail. + * @since v0.6.7 + */ + export function chmodSync(path: PathLike, mode: Mode): void; + /** + * Sets the permissions on the file. No arguments other than a possible exception + * are given to the completion callback. + * + * See the POSIX [`fchmod(2)`](http://man7.org/linux/man-pages/man2/fchmod.2.html) documentation for more detail. + * @since v0.4.7 + */ + export function fchmod(fd: number, mode: Mode, callback: NoParamCallback): void; + export namespace fchmod { + /** + * Asynchronous fchmod(2) - Change permissions of a file. + * @param fd A file descriptor. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(fd: number, mode: Mode): Promise; + } + /** + * Sets the permissions on the file. Returns `undefined`. + * + * See the POSIX [`fchmod(2)`](http://man7.org/linux/man-pages/man2/fchmod.2.html) documentation for more detail. + * @since v0.4.7 + */ + export function fchmodSync(fd: number, mode: Mode): void; + /** + * Changes the permissions on a symbolic link. No arguments other than a possible + * exception are given to the completion callback. + * + * This method is only implemented on macOS. + * + * See the POSIX [`lchmod(2)`](https://www.freebsd.org/cgi/man.cgi?query=lchmod&sektion=2) documentation for more detail. + * @deprecated Since v0.4.7 + */ + export function lchmod(path: PathLike, mode: Mode, callback: NoParamCallback): void; + /** @deprecated */ + export namespace lchmod { + /** + * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(path: PathLike, mode: Mode): Promise; + } + /** + * Changes the permissions on a symbolic link. Returns `undefined`. + * + * This method is only implemented on macOS. + * + * See the POSIX [`lchmod(2)`](https://www.freebsd.org/cgi/man.cgi?query=lchmod&sektion=2) documentation for more detail. + * @deprecated Since v0.4.7 + */ + export function lchmodSync(path: PathLike, mode: Mode): void; + /** + * Asynchronous [`stat(2)`](http://man7.org/linux/man-pages/man2/stat.2.html). The callback gets two arguments `(err, stats)` where`stats` is an `fs.Stats` object. + * + * In case of an error, the `err.code` will be one of `Common System Errors`. + * + * Using `fs.stat()` to check for the existence of a file before calling`fs.open()`, `fs.readFile()` or `fs.writeFile()` is not recommended. + * Instead, user code should open/read/write the file directly and handle the + * error raised if the file is not available. + * + * To check if a file exists without manipulating it afterwards, {@link access} is recommended. + * + * For example, given the following directory structure: + * + * ```text + * - txtDir + * -- file.txt + * - app.js + * ``` + * + * The next program will check for the stats of the given paths: + * + * ```js + * import { stat } from 'fs'; + * + * const pathsToCheck = ['./txtDir', './txtDir/file.txt']; + * + * for (let i = 0; i < pathsToCheck.length; i++) { + * stat(pathsToCheck[i], (err, stats) => { + * console.log(stats.isDirectory()); + * console.log(stats); + * }); + * } + * ``` + * + * The resulting output will resemble: + * + * ```console + * true + * Stats { + * dev: 16777220, + * mode: 16877, + * nlink: 3, + * uid: 501, + * gid: 20, + * rdev: 0, + * blksize: 4096, + * ino: 14214262, + * size: 96, + * blocks: 0, + * atimeMs: 1561174653071.963, + * mtimeMs: 1561174614583.3518, + * ctimeMs: 1561174626623.5366, + * birthtimeMs: 1561174126937.2893, + * atime: 2019-06-22T03:37:33.072Z, + * mtime: 2019-06-22T03:36:54.583Z, + * ctime: 2019-06-22T03:37:06.624Z, + * birthtime: 2019-06-22T03:28:46.937Z + * } + * false + * Stats { + * dev: 16777220, + * mode: 33188, + * nlink: 1, + * uid: 501, + * gid: 20, + * rdev: 0, + * blksize: 4096, + * ino: 14214074, + * size: 8, + * blocks: 8, + * atimeMs: 1561174616618.8555, + * mtimeMs: 1561174614584, + * ctimeMs: 1561174614583.8145, + * birthtimeMs: 1561174007710.7478, + * atime: 2019-06-22T03:36:56.619Z, + * mtime: 2019-06-22T03:36:54.584Z, + * ctime: 2019-06-22T03:36:54.584Z, + * birthtime: 2019-06-22T03:26:47.711Z + * } + * ``` + * @since v0.0.2 + */ + export function stat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + export function stat( + path: PathLike, + options: + | (StatOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void, + ): void; + export function stat( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void, + ): void; + export function stat( + path: PathLike, + options: StatOptions | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void, + ): void; + export namespace stat { + /** + * Asynchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__( + path: PathLike, + options?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + function __promisify__( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + ): Promise; + function __promisify__(path: PathLike, options?: StatOptions): Promise; + } + export interface StatSyncFn extends Function { + (path: PathLike, options?: undefined): Stats; + ( + path: PathLike, + options?: StatSyncOptions & { + bigint?: false | undefined; + throwIfNoEntry: false; + }, + ): Stats | undefined; + ( + path: PathLike, + options: StatSyncOptions & { + bigint: true; + throwIfNoEntry: false; + }, + ): BigIntStats | undefined; + ( + path: PathLike, + options?: StatSyncOptions & { + bigint?: false | undefined; + }, + ): Stats; + ( + path: PathLike, + options: StatSyncOptions & { + bigint: true; + }, + ): BigIntStats; + ( + path: PathLike, + options: StatSyncOptions & { + bigint: boolean; + throwIfNoEntry?: false | undefined; + }, + ): Stats | BigIntStats; + (path: PathLike, options?: StatSyncOptions): Stats | BigIntStats | undefined; + } + /** + * Synchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export const statSync: StatSyncFn; + /** + * Invokes the callback with the `fs.Stats` for the file descriptor. + * + * See the POSIX [`fstat(2)`](http://man7.org/linux/man-pages/man2/fstat.2.html) documentation for more detail. + * @since v0.1.95 + */ + export function fstat(fd: number, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + export function fstat( + fd: number, + options: + | (StatOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void, + ): void; + export function fstat( + fd: number, + options: StatOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void, + ): void; + export function fstat( + fd: number, + options: StatOptions | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void, + ): void; + export namespace fstat { + /** + * Asynchronous fstat(2) - Get file status. + * @param fd A file descriptor. + */ + function __promisify__( + fd: number, + options?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + function __promisify__( + fd: number, + options: StatOptions & { + bigint: true; + }, + ): Promise; + function __promisify__(fd: number, options?: StatOptions): Promise; + } + /** + * Retrieves the `fs.Stats` for the file descriptor. + * + * See the POSIX [`fstat(2)`](http://man7.org/linux/man-pages/man2/fstat.2.html) documentation for more detail. + * @since v0.1.95 + */ + export function fstatSync( + fd: number, + options?: StatOptions & { + bigint?: false | undefined; + }, + ): Stats; + export function fstatSync( + fd: number, + options: StatOptions & { + bigint: true; + }, + ): BigIntStats; + export function fstatSync(fd: number, options?: StatOptions): Stats | BigIntStats; + /** + * Retrieves the `fs.Stats` for the symbolic link referred to by the path. + * The callback gets two arguments `(err, stats)` where `stats` is a `fs.Stats` object. `lstat()` is identical to `stat()`, except that if `path` is a symbolic + * link, then the link itself is stat-ed, not the file that it refers to. + * + * See the POSIX [`lstat(2)`](http://man7.org/linux/man-pages/man2/lstat.2.html) documentation for more details. + * @since v0.1.30 + */ + export function lstat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + export function lstat( + path: PathLike, + options: + | (StatOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void, + ): void; + export function lstat( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void, + ): void; + export function lstat( + path: PathLike, + options: StatOptions | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void, + ): void; + export namespace lstat { + /** + * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__( + path: PathLike, + options?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + function __promisify__( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + ): Promise; + function __promisify__(path: PathLike, options?: StatOptions): Promise; + } + /** + * Asynchronous statfs(2). Returns information about the mounted file system which contains path. The callback gets two arguments (err, stats) where stats is an object. + * In case of an error, the err.code will be one of Common System Errors. + * @param path A path to an existing file or directory on the file system to be queried. + * @param callback + */ + export function statfs(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: StatsFs) => void): void; + export function statfs( + path: PathLike, + options: + | (StatFsOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: StatsFs) => void, + ): void; + export function statfs( + path: PathLike, + options: StatFsOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStatsFs) => void, + ): void; + export function statfs( + path: PathLike, + options: StatFsOptions | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: StatsFs | BigIntStatsFs) => void, + ): void; + export namespace statfs { + /** + * Asynchronous statfs(2) - Returns information about the mounted file system which contains path. The callback gets two arguments (err, stats) where stats is an object. + * @param path A path to an existing file or directory on the file system to be queried. + */ + function __promisify__( + path: PathLike, + options?: StatFsOptions & { + bigint?: false | undefined; + }, + ): Promise; + function __promisify__( + path: PathLike, + options: StatFsOptions & { + bigint: true; + }, + ): Promise; + function __promisify__(path: PathLike, options?: StatFsOptions): Promise; + } + + /** + * Synchronous statfs(2). Returns information about the mounted file system which contains path. The callback gets two arguments (err, stats) where stats is an object. + * In case of an error, the err.code will be one of Common System Errors. + * @param path A path to an existing file or directory on the file system to be queried. + * @param callback + */ + export function statfsSync( + path: PathLike, + options?: StatFsOptions & { + bigint?: false | undefined; + }, + ): StatsFs; + export function statfsSync( + path: PathLike, + options: StatFsOptions & { + bigint: true; + }, + ): BigIntStatsFs; + + export function statfsSync(path: PathLike, options?: StatFsOptions): StatsFs | BigIntStatsFs; + /** + * Synchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export const lstatSync: StatSyncFn; + /** + * Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. No arguments other than + * a possible + * exception are given to the completion callback. + * @since v0.1.31 + */ + export function link(existingPath: PathLike, newPath: PathLike, callback: NoParamCallback): void; + export namespace link { + /** + * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. + * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(existingPath: PathLike, newPath: PathLike): Promise; + } + /** + * Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. Returns `undefined`. + * @since v0.1.31 + */ + export function linkSync(existingPath: PathLike, newPath: PathLike): void; + /** + * Creates the link called `path` pointing to `target`. No arguments other than a + * possible exception are given to the completion callback. + * + * See the POSIX [`symlink(2)`](http://man7.org/linux/man-pages/man2/symlink.2.html) documentation for more details. + * + * The `type` argument is only available on Windows and ignored on other platforms. + * It can be set to `'dir'`, `'file'`, or `'junction'`. If the `type` argument is + * not set, Node.js will autodetect `target` type and use `'file'` or `'dir'`. If + * the `target` does not exist, `'file'` will be used. Windows junction points + * require the destination path to be absolute. When using `'junction'`, the`target` argument will automatically be normalized to absolute path. + * + * Relative targets are relative to the link’s parent directory. + * + * ```js + * import { symlink } from 'fs'; + * + * symlink('./mew', './mewtwo', callback); + * ``` + * + * The above example creates a symbolic link `mewtwo` which points to `mew` in the + * same directory: + * + * ```bash + * $ tree . + * . + * ├── mew + * └── mewtwo -> ./mew + * ``` + * @since v0.1.31 + */ + export function symlink( + target: PathLike, + path: PathLike, + type: symlink.Type | undefined | null, + callback: NoParamCallback, + ): void; + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + */ + export function symlink(target: PathLike, path: PathLike, callback: NoParamCallback): void; + export namespace symlink { + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). + * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. + */ + function __promisify__(target: PathLike, path: PathLike, type?: string | null): Promise; + type Type = "dir" | "file" | "junction"; + } + /** + * Returns `undefined`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link symlink}. + * @since v0.1.31 + */ + export function symlinkSync(target: PathLike, path: PathLike, type?: symlink.Type | null): void; + /** + * Reads the contents of the symbolic link referred to by `path`. The callback gets + * two arguments `(err, linkString)`. + * + * See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the link path passed to the callback. If the `encoding` is set to `'buffer'`, + * the link path returned will be passed as a `Buffer` object. + * @since v0.1.31 + */ + export function readlink( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, linkString: string) => void, + ): void; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlink( + path: PathLike, + options: BufferEncodingOption, + callback: (err: NodeJS.ErrnoException | null, linkString: Buffer) => void, + ): void; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlink( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, linkString: string | Buffer) => void, + ): void; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function readlink( + path: PathLike, + callback: (err: NodeJS.ErrnoException | null, linkString: string) => void, + ): void; + export namespace readlink { + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + } + /** + * Returns the symbolic link's string value. + * + * See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the link path returned. If the `encoding` is set to `'buffer'`, + * the link path returned will be passed as a `Buffer` object. + * @since v0.1.31 + */ + export function readlinkSync(path: PathLike, options?: EncodingOption): string; + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlinkSync(path: PathLike, options: BufferEncodingOption): Buffer; + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlinkSync(path: PathLike, options?: EncodingOption): string | Buffer; + /** + * Asynchronously computes the canonical pathname by resolving `.`, `..` and + * symbolic links. + * + * A canonical pathname is not necessarily unique. Hard links and bind mounts can + * expose a file system entity through many pathnames. + * + * This function behaves like [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html), with some exceptions: + * + * 1. No case conversion is performed on case-insensitive file systems. + * 2. The maximum number of symbolic links is platform-independent and generally + * (much) higher than what the native [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html) implementation supports. + * + * The `callback` gets two arguments `(err, resolvedPath)`. May use `process.cwd`to resolve relative paths. + * + * Only paths that can be converted to UTF8 strings are supported. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the path passed to the callback. If the `encoding` is set to `'buffer'`, + * the path returned will be passed as a `Buffer` object. + * + * If `path` resolves to a socket or a pipe, the function will return a system + * dependent name for that object. + * @since v0.1.31 + */ + export function realpath( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void, + ): void; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpath( + path: PathLike, + options: BufferEncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void, + ): void; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpath( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | Buffer) => void, + ): void; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function realpath( + path: PathLike, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void, + ): void; + export namespace realpath { + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + /** + * Asynchronous [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html). + * + * The `callback` gets two arguments `(err, resolvedPath)`. + * + * Only paths that can be converted to UTF8 strings are supported. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the path passed to the callback. If the `encoding` is set to `'buffer'`, + * the path returned will be passed as a `Buffer` object. + * + * On Linux, when Node.js is linked against musl libc, the procfs file system must + * be mounted on `/proc` in order for this function to work. Glibc does not have + * this restriction. + * @since v9.2.0 + */ + function native( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void, + ): void; + function native( + path: PathLike, + options: BufferEncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void, + ): void; + function native( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | Buffer) => void, + ): void; + function native( + path: PathLike, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void, + ): void; + } + /** + * Returns the resolved pathname. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link realpath}. + * @since v0.1.31 + */ + export function realpathSync(path: PathLike, options?: EncodingOption): string; + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpathSync(path: PathLike, options: BufferEncodingOption): Buffer; + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpathSync(path: PathLike, options?: EncodingOption): string | Buffer; + export namespace realpathSync { + function native(path: PathLike, options?: EncodingOption): string; + function native(path: PathLike, options: BufferEncodingOption): Buffer; + function native(path: PathLike, options?: EncodingOption): string | Buffer; + } + /** + * Asynchronously removes a file or symbolic link. No arguments other than a + * possible exception are given to the completion callback. + * + * ```js + * import { unlink } from 'fs'; + * // Assuming that 'path/file.txt' is a regular file. + * unlink('path/file.txt', (err) => { + * if (err) throw err; + * console.log('path/file.txt was deleted'); + * }); + * ``` + * + * `fs.unlink()` will not work on a directory, empty or otherwise. To remove a + * directory, use {@link rmdir}. + * + * See the POSIX [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html) documentation for more details. + * @since v0.0.2 + */ + export function unlink(path: PathLike, callback: NoParamCallback): void; + export namespace unlink { + /** + * Asynchronous unlink(2) - delete a name and possibly the file it refers to. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike): Promise; + } + /** + * Synchronous [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html). Returns `undefined`. + * @since v0.1.21 + */ + export function unlinkSync(path: PathLike): void; + export interface RmDirOptions { + /** + * If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or + * `EPERM` error is encountered, Node.js will retry the operation with a linear + * backoff wait of `retryDelay` ms longer on each try. This option represents the + * number of retries. This option is ignored if the `recursive` option is not + * `true`. + * @default 0 + */ + maxRetries?: number | undefined; + /** + * @deprecated since v14.14.0 In future versions of Node.js and will trigger a warning + * `fs.rmdir(path, { recursive: true })` will throw if `path` does not exist or is a file. + * Use `fs.rm(path, { recursive: true, force: true })` instead. + * + * If `true`, perform a recursive directory removal. In + * recursive mode, operations are retried on failure. + * @default false + */ + recursive?: boolean | undefined; + /** + * The amount of time in milliseconds to wait between retries. + * This option is ignored if the `recursive` option is not `true`. + * @default 100 + */ + retryDelay?: number | undefined; + } + /** + * Asynchronous [`rmdir(2)`](http://man7.org/linux/man-pages/man2/rmdir.2.html). No arguments other than a possible exception are given + * to the completion callback. + * + * Using `fs.rmdir()` on a file (not a directory) results in an `ENOENT` error on + * Windows and an `ENOTDIR` error on POSIX. + * + * To get a behavior similar to the `rm -rf` Unix command, use {@link rm} with options `{ recursive: true, force: true }`. + * @since v0.0.2 + */ + export function rmdir(path: PathLike, callback: NoParamCallback): void; + export function rmdir(path: PathLike, options: RmDirOptions, callback: NoParamCallback): void; + export namespace rmdir { + /** + * Asynchronous rmdir(2) - delete a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, options?: RmDirOptions): Promise; + } + /** + * Synchronous [`rmdir(2)`](http://man7.org/linux/man-pages/man2/rmdir.2.html). Returns `undefined`. + * + * Using `fs.rmdirSync()` on a file (not a directory) results in an `ENOENT` error + * on Windows and an `ENOTDIR` error on POSIX. + * + * To get a behavior similar to the `rm -rf` Unix command, use {@link rmSync} with options `{ recursive: true, force: true }`. + * @since v0.1.21 + */ + export function rmdirSync(path: PathLike, options?: RmDirOptions): void; + export interface RmOptions { + /** + * When `true`, exceptions will be ignored if `path` does not exist. + * @default false + */ + force?: boolean | undefined; + /** + * If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or + * `EPERM` error is encountered, Node.js will retry the operation with a linear + * backoff wait of `retryDelay` ms longer on each try. This option represents the + * number of retries. This option is ignored if the `recursive` option is not + * `true`. + * @default 0 + */ + maxRetries?: number | undefined; + /** + * If `true`, perform a recursive directory removal. In + * recursive mode, operations are retried on failure. + * @default false + */ + recursive?: boolean | undefined; + /** + * The amount of time in milliseconds to wait between retries. + * This option is ignored if the `recursive` option is not `true`. + * @default 100 + */ + retryDelay?: number | undefined; + } + /** + * Asynchronously removes files and directories (modeled on the standard POSIX `rm`utility). No arguments other than a possible exception are given to the + * completion callback. + * @since v14.14.0 + */ + export function rm(path: PathLike, callback: NoParamCallback): void; + export function rm(path: PathLike, options: RmOptions, callback: NoParamCallback): void; + export namespace rm { + /** + * Asynchronously removes files and directories (modeled on the standard POSIX `rm` utility). + */ + function __promisify__(path: PathLike, options?: RmOptions): Promise; + } + /** + * Synchronously removes files and directories (modeled on the standard POSIX `rm`utility). Returns `undefined`. + * @since v14.14.0 + */ + export function rmSync(path: PathLike, options?: RmOptions): void; + export interface MakeDirectoryOptions { + /** + * Indicates whether parent folders should be created. + * If a folder was created, the path to the first created folder will be returned. + * @default false + */ + recursive?: boolean | undefined; + /** + * A file mode. If a string is passed, it is parsed as an octal integer. If not specified + * @default 0o777 + */ + mode?: Mode | undefined; + } + /** + * Asynchronously creates a directory. + * + * The callback is given a possible exception and, if `recursive` is `true`, the + * first directory path created, `(err[, path])`.`path` can still be `undefined` when `recursive` is `true`, if no directory was + * created. + * + * The optional `options` argument can be an integer specifying `mode` (permission + * and sticky bits), or an object with a `mode` property and a `recursive`property indicating whether parent directories should be created. Calling`fs.mkdir()` when `path` is a directory that + * exists results in an error only + * when `recursive` is false. + * + * ```js + * import { mkdir } from 'fs'; + * + * // Creates /tmp/a/apple, regardless of whether `/tmp` and /tmp/a exist. + * mkdir('/tmp/a/apple', { recursive: true }, (err) => { + * if (err) throw err; + * }); + * ``` + * + * On Windows, using `fs.mkdir()` on the root directory even with recursion will + * result in an error: + * + * ```js + * import { mkdir } from 'fs'; + * + * mkdir('/', { recursive: true }, (err) => { + * // => [Error: EPERM: operation not permitted, mkdir 'C:\'] + * }); + * ``` + * + * See the POSIX [`mkdir(2)`](http://man7.org/linux/man-pages/man2/mkdir.2.html) documentation for more details. + * @since v0.1.8 + */ + export function mkdir( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + }, + callback: (err: NodeJS.ErrnoException | null, path?: string) => void, + ): void; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdir( + path: PathLike, + options: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null + | undefined, + callback: NoParamCallback, + ): void; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdir( + path: PathLike, + options: Mode | MakeDirectoryOptions | null | undefined, + callback: (err: NodeJS.ErrnoException | null, path?: string) => void, + ): void; + /** + * Asynchronous mkdir(2) - create a directory with a mode of `0o777`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function mkdir(path: PathLike, callback: NoParamCallback): void; + export namespace mkdir { + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + }, + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__( + path: PathLike, + options?: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null, + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__( + path: PathLike, + options?: Mode | MakeDirectoryOptions | null, + ): Promise; + } + /** + * Synchronously creates a directory. Returns `undefined`, or if `recursive` is`true`, the first directory path created. + * This is the synchronous version of {@link mkdir}. + * + * See the POSIX [`mkdir(2)`](http://man7.org/linux/man-pages/man2/mkdir.2.html) documentation for more details. + * @since v0.1.21 + */ + export function mkdirSync( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + }, + ): string | undefined; + /** + * Synchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdirSync( + path: PathLike, + options?: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null, + ): void; + /** + * Synchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdirSync(path: PathLike, options?: Mode | MakeDirectoryOptions | null): string | undefined; + /** + * Creates a unique temporary directory. + * + * Generates six random characters to be appended behind a required`prefix` to create a unique temporary directory. Due to platform + * inconsistencies, avoid trailing `X` characters in `prefix`. Some platforms, + * notably the BSDs, can return more than six random characters, and replace + * trailing `X` characters in `prefix` with random characters. + * + * The created directory path is passed as a string to the callback's second + * parameter. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use. + * + * ```js + * import { mkdtemp } from 'fs'; + * + * mkdtemp(path.join(os.tmpdir(), 'foo-'), (err, directory) => { + * if (err) throw err; + * console.log(directory); + * // Prints: /tmp/foo-itXde2 or C:\Users\...\AppData\Local\Temp\foo-itXde2 + * }); + * ``` + * + * The `fs.mkdtemp()` method will append the six randomly selected characters + * directly to the `prefix` string. For instance, given a directory `/tmp`, if the + * intention is to create a temporary directory _within_`/tmp`, the `prefix`must end with a trailing platform-specific path separator + * (`require('path').sep`). + * + * ```js + * import { tmpdir } from 'os'; + * import { mkdtemp } from 'fs'; + * + * // The parent directory for the new temporary directory + * const tmpDir = tmpdir(); + * + * // This method is *INCORRECT*: + * mkdtemp(tmpDir, (err, directory) => { + * if (err) throw err; + * console.log(directory); + * // Will print something similar to `/tmpabc123`. + * // A new temporary directory is created at the file system root + * // rather than *within* the /tmp directory. + * }); + * + * // This method is *CORRECT*: + * import { sep } from 'path'; + * mkdtemp(`${tmpDir}${sep}`, (err, directory) => { + * if (err) throw err; + * console.log(directory); + * // Will print something similar to `/tmp/abc123`. + * // A new temporary directory is created within + * // the /tmp directory. + * }); + * ``` + * @since v5.10.0 + */ + export function mkdtemp( + prefix: string, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, folder: string) => void, + ): void; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtemp( + prefix: string, + options: + | "buffer" + | { + encoding: "buffer"; + }, + callback: (err: NodeJS.ErrnoException | null, folder: Buffer) => void, + ): void; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtemp( + prefix: string, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, folder: string | Buffer) => void, + ): void; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + */ + export function mkdtemp( + prefix: string, + callback: (err: NodeJS.ErrnoException | null, folder: string) => void, + ): void; + export namespace mkdtemp { + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options?: EncodingOption): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options: BufferEncodingOption): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options?: EncodingOption): Promise; + } + /** + * Returns the created directory path. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link mkdtemp}. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use. + * @since v5.10.0 + */ + export function mkdtempSync(prefix: string, options?: EncodingOption): string; + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtempSync(prefix: string, options: BufferEncodingOption): Buffer; + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtempSync(prefix: string, options?: EncodingOption): string | Buffer; + /** + * Reads the contents of a directory. The callback gets two arguments `(err, files)`where `files` is an array of the names of the files in the directory excluding`'.'` and `'..'`. + * + * See the POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the filenames passed to the callback. If the `encoding` is set to `'buffer'`, + * the filenames returned will be passed as `Buffer` objects. + * + * If `options.withFileTypes` is set to `true`, the `files` array will contain `fs.Dirent` objects. + * @since v0.1.8 + */ + export function readdir( + path: PathLike, + options: + | { + encoding: BufferEncoding | null; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | BufferEncoding + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, files: string[]) => void, + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdir( + path: PathLike, + options: + | { + encoding: "buffer"; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | "buffer", + callback: (err: NodeJS.ErrnoException | null, files: Buffer[]) => void, + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdir( + path: PathLike, + options: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, files: string[] | Buffer[]) => void, + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function readdir( + path: PathLike, + callback: (err: NodeJS.ErrnoException | null, files: string[]) => void, + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + export function readdir( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + recursive?: boolean | undefined; + }, + callback: (err: NodeJS.ErrnoException | null, files: Dirent[]) => void, + ): void; + export namespace readdir { + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__( + path: PathLike, + options?: + | { + encoding: BufferEncoding | null; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__( + path: PathLike, + options: + | "buffer" + | { + encoding: "buffer"; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent + */ + function __promisify__( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Promise; + } + /** + * Reads the contents of the directory. + * + * See the POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the filenames returned. If the `encoding` is set to `'buffer'`, + * the filenames returned will be passed as `Buffer` objects. + * + * If `options.withFileTypes` is set to `true`, the result will contain `fs.Dirent` objects. + * @since v0.1.21 + */ + export function readdirSync( + path: PathLike, + options?: + | { + encoding: BufferEncoding | null; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | BufferEncoding + | null, + ): string[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdirSync( + path: PathLike, + options: + | { + encoding: "buffer"; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | "buffer", + ): Buffer[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdirSync( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | null, + ): string[] | Buffer[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + export function readdirSync( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Dirent[]; + /** + * Closes the file descriptor. No arguments other than a possible exception are + * given to the completion callback. + * + * Calling `fs.close()` on any file descriptor (`fd`) that is currently in use + * through any other `fs` operation may lead to undefined behavior. + * + * See the POSIX [`close(2)`](http://man7.org/linux/man-pages/man2/close.2.html) documentation for more detail. + * @since v0.0.2 + */ + export function close(fd: number, callback?: NoParamCallback): void; + export namespace close { + /** + * Asynchronous close(2) - close a file descriptor. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + /** + * Closes the file descriptor. Returns `undefined`. + * + * Calling `fs.closeSync()` on any file descriptor (`fd`) that is currently in use + * through any other `fs` operation may lead to undefined behavior. + * + * See the POSIX [`close(2)`](http://man7.org/linux/man-pages/man2/close.2.html) documentation for more detail. + * @since v0.1.21 + */ + export function closeSync(fd: number): void; + /** + * Asynchronous file open. See the POSIX [`open(2)`](http://man7.org/linux/man-pages/man2/open.2.html) documentation for more details. + * + * `mode` sets the file mode (permission and sticky bits), but only if the file was + * created. On Windows, only the write permission can be manipulated; see {@link chmod}. + * + * The callback gets two arguments `(err, fd)`. + * + * Some characters (`< > : " / \ | ? *`) are reserved under Windows as documented + * by [Naming Files, Paths, and Namespaces](https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file). Under NTFS, if the filename contains + * a colon, Node.js will open a file system stream, as described by [this MSDN page](https://docs.microsoft.com/en-us/windows/desktop/FileIO/using-streams). + * + * Functions based on `fs.open()` exhibit this behavior as well:`fs.writeFile()`, `fs.readFile()`, etc. + * @since v0.0.2 + * @param [flags='r'] See `support of file system `flags``. + * @param [mode=0o666] + */ + export function open( + path: PathLike, + flags: OpenMode | undefined, + mode: Mode | undefined | null, + callback: (err: NodeJS.ErrnoException | null, fd: number) => void, + ): void; + /** + * Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be `0o666`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param [flags='r'] See `support of file system `flags``. + */ + export function open( + path: PathLike, + flags: OpenMode | undefined, + callback: (err: NodeJS.ErrnoException | null, fd: number) => void, + ): void; + /** + * Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be `0o666`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function open(path: PathLike, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; + + export namespace open { + /** + * Asynchronous open(2) - open and possibly create a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. + */ + function __promisify__(path: PathLike, flags: OpenMode, mode?: Mode | null): Promise; + } + /** + * Returns an integer representing the file descriptor. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link open}. + * @since v0.1.21 + * @param [flags='r'] + * @param [mode=0o666] + */ + export function openSync(path: PathLike, flags: OpenMode, mode?: Mode | null): number; + /** + * Change the file system timestamps of the object referenced by `path`. + * + * The `atime` and `mtime` arguments follow these rules: + * + * * Values can be either numbers representing Unix epoch time in seconds,`Date`s, or a numeric string like `'123456789.0'`. + * * If the value can not be converted to a number, or is `NaN`, `Infinity` or`-Infinity`, an `Error` will be thrown. + * @since v0.4.2 + */ + export function utimes(path: PathLike, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; + export namespace utimes { + /** + * Asynchronously change file timestamps of the file referenced by the supplied path. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; + } + /** + * Returns `undefined`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link utimes}. + * @since v0.4.2 + */ + export function utimesSync(path: PathLike, atime: TimeLike, mtime: TimeLike): void; + /** + * Change the file system timestamps of the object referenced by the supplied file + * descriptor. See {@link utimes}. + * @since v0.4.2 + */ + export function futimes(fd: number, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; + export namespace futimes { + /** + * Asynchronously change file timestamps of the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(fd: number, atime: TimeLike, mtime: TimeLike): Promise; + } + /** + * Synchronous version of {@link futimes}. Returns `undefined`. + * @since v0.4.2 + */ + export function futimesSync(fd: number, atime: TimeLike, mtime: TimeLike): void; + /** + * Request that all data for the open file descriptor is flushed to the storage + * device. The specific implementation is operating system and device specific. + * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. No arguments other + * than a possible exception are given to the completion callback. + * @since v0.1.96 + */ + export function fsync(fd: number, callback: NoParamCallback): void; + export namespace fsync { + /** + * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + /** + * Request that all data for the open file descriptor is flushed to the storage + * device. The specific implementation is operating system and device specific. + * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. Returns `undefined`. + * @since v0.1.96 + */ + export function fsyncSync(fd: number): void; + /** + * Write `buffer` to the file specified by `fd`. + * + * `offset` determines the part of the buffer to be written, and `length` is + * an integer specifying the number of bytes to write. + * + * `position` refers to the offset from the beginning of the file where this data + * should be written. If `typeof position !== 'number'`, the data will be written + * at the current position. See [`pwrite(2)`](http://man7.org/linux/man-pages/man2/pwrite.2.html). + * + * The callback will be given three arguments `(err, bytesWritten, buffer)` where`bytesWritten` specifies how many _bytes_ were written from `buffer`. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a promise for an `Object` with `bytesWritten` and `buffer` properties. + * + * It is unsafe to use `fs.write()` multiple times on the same file without waiting + * for the callback. For this scenario, {@link createWriteStream} is + * recommended. + * + * On Linux, positional writes don't work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v0.0.2 + */ + export function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + length: number | undefined | null, + position: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + */ + export function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + length: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + */ + export function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + */ + export function write( + fd: number, + buffer: TBuffer, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + export function write( + fd: number, + string: string, + position: number | undefined | null, + encoding: BufferEncoding | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void, + ): void; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + export function write( + fd: number, + string: string, + position: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void, + ): void; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + */ + export function write( + fd: number, + string: string, + callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void, + ): void; + export namespace write { + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function __promisify__( + fd: number, + buffer?: TBuffer, + offset?: number, + length?: number, + position?: number | null, + ): Promise<{ + bytesWritten: number; + buffer: TBuffer; + }>; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + function __promisify__( + fd: number, + string: string, + position?: number | null, + encoding?: BufferEncoding | null, + ): Promise<{ + bytesWritten: number; + buffer: string; + }>; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link write}. + * @since v0.1.21 + * @return The number of bytes written. + */ + export function writeSync( + fd: number, + buffer: NodeJS.ArrayBufferView, + offset?: number | null, + length?: number | null, + position?: number | null, + ): number; + /** + * Synchronously writes `string` to the file referenced by the supplied file descriptor, returning the number of bytes written. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + export function writeSync( + fd: number, + string: string, + position?: number | null, + encoding?: BufferEncoding | null, + ): number; + export type ReadPosition = number | bigint; + export interface ReadSyncOptions { + /** + * @default 0 + */ + offset?: number | undefined; + /** + * @default `length of buffer` + */ + length?: number | undefined; + /** + * @default null + */ + position?: ReadPosition | null | undefined; + } + export interface ReadAsyncOptions extends ReadSyncOptions { + buffer?: TBuffer; + } + /** + * Read data from the file specified by `fd`. + * + * The callback is given the three arguments, `(err, bytesRead, buffer)`. + * + * If the file is not modified concurrently, the end-of-file is reached when the + * number of bytes read is zero. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a promise for an `Object` with `bytesRead` and `buffer` properties. + * @since v0.0.2 + * @param buffer The buffer that the data will be written to. + * @param offset The position in `buffer` to write the data to. + * @param length The number of bytes to read. + * @param position Specifies where to begin reading from in the file. If `position` is `null` or `-1 `, data will be read from the current file position, and the file position will be updated. If + * `position` is an integer, the file position will be unchanged. + */ + export function read( + fd: number, + buffer: TBuffer, + offset: number, + length: number, + position: ReadPosition | null, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void, + ): void; + /** + * Similar to the above `fs.read` function, this version takes an optional `options` object. + * If not otherwise specified in an `options` object, + * `buffer` defaults to `Buffer.alloc(16384)`, + * `offset` defaults to `0`, + * `length` defaults to `buffer.byteLength`, `- offset` as of Node 17.6.0 + * `position` defaults to `null` + * @since v12.17.0, 13.11.0 + */ + export function read( + fd: number, + options: ReadAsyncOptions, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void, + ): void; + export function read( + fd: number, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: NodeJS.ArrayBufferView) => void, + ): void; + export namespace read { + /** + * @param fd A file descriptor. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. + */ + function __promisify__( + fd: number, + buffer: TBuffer, + offset: number, + length: number, + position: number | null, + ): Promise<{ + bytesRead: number; + buffer: TBuffer; + }>; + function __promisify__( + fd: number, + options: ReadAsyncOptions, + ): Promise<{ + bytesRead: number; + buffer: TBuffer; + }>; + function __promisify__(fd: number): Promise<{ + bytesRead: number; + buffer: NodeJS.ArrayBufferView; + }>; + } + /** + * Returns the number of `bytesRead`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link read}. + * @since v0.1.21 + */ + export function readSync( + fd: number, + buffer: NodeJS.ArrayBufferView, + offset: number, + length: number, + position: ReadPosition | null, + ): number; + /** + * Similar to the above `fs.readSync` function, this version takes an optional `options` object. + * If no `options` object is specified, it will default with the above values. + */ + export function readSync(fd: number, buffer: NodeJS.ArrayBufferView, opts?: ReadSyncOptions): number; + /** + * Asynchronously reads the entire contents of a file. + * + * ```js + * import { readFile } from 'fs'; + * + * readFile('/etc/passwd', (err, data) => { + * if (err) throw err; + * console.log(data); + * }); + * ``` + * + * The callback is passed two arguments `(err, data)`, where `data` is the + * contents of the file. + * + * If no encoding is specified, then the raw buffer is returned. + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { readFile } from 'fs'; + * + * readFile('/etc/passwd', 'utf8', callback); + * ``` + * + * When the path is a directory, the behavior of `fs.readFile()` and {@link readFileSync} is platform-specific. On macOS, Linux, and Windows, an + * error will be returned. On FreeBSD, a representation of the directory's contents + * will be returned. + * + * ```js + * import { readFile } from 'fs'; + * + * // macOS, Linux, and Windows + * readFile('', (err, data) => { + * // => [Error: EISDIR: illegal operation on a directory, read ] + * }); + * + * // FreeBSD + * readFile('', (err, data) => { + * // => null, + * }); + * ``` + * + * It is possible to abort an ongoing request using an `AbortSignal`. If a + * request is aborted the callback is called with an `AbortError`: + * + * ```js + * import { readFile } from 'fs'; + * + * const controller = new AbortController(); + * const signal = controller.signal; + * readFile(fileInfo[0].name, { signal }, (err, buf) => { + * // ... + * }); + * // When you want to abort the request + * controller.abort(); + * ``` + * + * The `fs.readFile()` function buffers the entire file. To minimize memory costs, + * when possible prefer streaming via `fs.createReadStream()`. + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.readFile` performs. + * @since v0.1.29 + * @param path filename or file descriptor + */ + export function readFile( + path: PathOrFileDescriptor, + options: + | ({ + encoding?: null | undefined; + flag?: string | undefined; + } & Abortable) + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void, + ): void; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFile( + path: PathOrFileDescriptor, + options: + | ({ + encoding: BufferEncoding; + flag?: string | undefined; + } & Abortable) + | BufferEncoding, + callback: (err: NodeJS.ErrnoException | null, data: string) => void, + ): void; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFile( + path: PathOrFileDescriptor, + options: + | (ObjectEncodingOptions & { + flag?: string | undefined; + } & Abortable) + | BufferEncoding + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, data: string | Buffer) => void, + ): void; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + */ + export function readFile( + path: PathOrFileDescriptor, + callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void, + ): void; + export namespace readFile { + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__( + path: PathOrFileDescriptor, + options?: { + encoding?: null | undefined; + flag?: string | undefined; + } | null, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__( + path: PathOrFileDescriptor, + options: + | { + encoding: BufferEncoding; + flag?: string | undefined; + } + | BufferEncoding, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__( + path: PathOrFileDescriptor, + options?: + | (ObjectEncodingOptions & { + flag?: string | undefined; + }) + | BufferEncoding + | null, + ): Promise; + } + /** + * Returns the contents of the `path`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link readFile}. + * + * If the `encoding` option is specified then this function returns a + * string. Otherwise it returns a buffer. + * + * Similar to {@link readFile}, when the path is a directory, the behavior of`fs.readFileSync()` is platform-specific. + * + * ```js + * import { readFileSync } from 'fs'; + * + * // macOS, Linux, and Windows + * readFileSync(''); + * // => [Error: EISDIR: illegal operation on a directory, read ] + * + * // FreeBSD + * readFileSync(''); // => + * ``` + * @since v0.1.8 + * @param path filename or file descriptor + */ + export function readFileSync( + path: PathOrFileDescriptor, + options?: { + encoding?: null | undefined; + flag?: string | undefined; + } | null, + ): Buffer; + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFileSync( + path: PathOrFileDescriptor, + options: + | { + encoding: BufferEncoding; + flag?: string | undefined; + } + | BufferEncoding, + ): string; + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFileSync( + path: PathOrFileDescriptor, + options?: + | (ObjectEncodingOptions & { + flag?: string | undefined; + }) + | BufferEncoding + | null, + ): string | Buffer; + export type WriteFileOptions = + | ( + & ObjectEncodingOptions + & Abortable + & { + mode?: Mode | undefined; + flag?: string | undefined; + } + ) + | BufferEncoding + | null; + /** + * When `file` is a filename, asynchronously writes data to the file, replacing the + * file if it already exists. `data` can be a string or a buffer. + * + * When `file` is a file descriptor, the behavior is similar to calling`fs.write()` directly (which is recommended). See the notes below on using + * a file descriptor. + * + * The `encoding` option is ignored if `data` is a buffer. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * ```js + * import { writeFile } from 'fs'; + * import { Buffer } from 'buffer'; + * + * const data = new Uint8Array(Buffer.from('Hello Node.js')); + * writeFile('message.txt', data, (err) => { + * if (err) throw err; + * console.log('The file has been saved!'); + * }); + * ``` + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { writeFile } from 'fs'; + * + * writeFile('message.txt', 'Hello Node.js', 'utf8', callback); + * ``` + * + * It is unsafe to use `fs.writeFile()` multiple times on the same file without + * waiting for the callback. For this scenario, {@link createWriteStream} is + * recommended. + * + * Similarly to `fs.readFile` \- `fs.writeFile` is a convenience method that + * performs multiple `write` calls internally to write the buffer passed to it. + * For performance sensitive code consider using {@link createWriteStream}. + * + * It is possible to use an `AbortSignal` to cancel an `fs.writeFile()`. + * Cancelation is "best effort", and some amount of data is likely still + * to be written. + * + * ```js + * import { writeFile } from 'fs'; + * import { Buffer } from 'buffer'; + * + * const controller = new AbortController(); + * const { signal } = controller; + * const data = new Uint8Array(Buffer.from('Hello Node.js')); + * writeFile('message.txt', data, { signal }, (err) => { + * // When a request is aborted - the callback is called with an AbortError + * }); + * // When the request should be aborted + * controller.abort(); + * ``` + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.writeFile` performs. + * @since v0.1.29 + * @param file filename or file descriptor + */ + export function writeFile( + file: PathOrFileDescriptor, + data: string | NodeJS.ArrayBufferView, + options: WriteFileOptions, + callback: NoParamCallback, + ): void; + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + */ + export function writeFile( + path: PathOrFileDescriptor, + data: string | NodeJS.ArrayBufferView, + callback: NoParamCallback, + ): void; + export namespace writeFile { + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + function __promisify__( + path: PathOrFileDescriptor, + data: string | NodeJS.ArrayBufferView, + options?: WriteFileOptions, + ): Promise; + } + /** + * Returns `undefined`. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link writeFile}. + * @since v0.1.29 + * @param file filename or file descriptor + */ + export function writeFileSync( + file: PathOrFileDescriptor, + data: string | NodeJS.ArrayBufferView, + options?: WriteFileOptions, + ): void; + /** + * Asynchronously append data to a file, creating the file if it does not yet + * exist. `data` can be a string or a `Buffer`. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * ```js + * import { appendFile } from 'fs'; + * + * appendFile('message.txt', 'data to append', (err) => { + * if (err) throw err; + * console.log('The "data to append" was appended to file!'); + * }); + * ``` + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { appendFile } from 'fs'; + * + * appendFile('message.txt', 'data to append', 'utf8', callback); + * ``` + * + * The `path` may be specified as a numeric file descriptor that has been opened + * for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will + * not be closed automatically. + * + * ```js + * import { open, close, appendFile } from 'fs'; + * + * function closeFd(fd) { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * + * open('message.txt', 'a', (err, fd) => { + * if (err) throw err; + * + * try { + * appendFile(fd, 'data to append', 'utf8', (err) => { + * closeFd(fd); + * if (err) throw err; + * }); + * } catch (err) { + * closeFd(fd); + * throw err; + * } + * }); + * ``` + * @since v0.6.7 + * @param path filename or file descriptor + */ + export function appendFile( + path: PathOrFileDescriptor, + data: string | Uint8Array, + options: WriteFileOptions, + callback: NoParamCallback, + ): void; + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + */ + export function appendFile(file: PathOrFileDescriptor, data: string | Uint8Array, callback: NoParamCallback): void; + export namespace appendFile { + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + function __promisify__( + file: PathOrFileDescriptor, + data: string | Uint8Array, + options?: WriteFileOptions, + ): Promise; + } + /** + * Synchronously append data to a file, creating the file if it does not yet + * exist. `data` can be a string or a `Buffer`. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * ```js + * import { appendFileSync } from 'fs'; + * + * try { + * appendFileSync('message.txt', 'data to append'); + * console.log('The "data to append" was appended to file!'); + * } catch (err) { + * // Handle the error + * } + * ``` + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { appendFileSync } from 'fs'; + * + * appendFileSync('message.txt', 'data to append', 'utf8'); + * ``` + * + * The `path` may be specified as a numeric file descriptor that has been opened + * for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will + * not be closed automatically. + * + * ```js + * import { openSync, closeSync, appendFileSync } from 'fs'; + * + * let fd; + * + * try { + * fd = openSync('message.txt', 'a'); + * appendFileSync(fd, 'data to append', 'utf8'); + * } catch (err) { + * // Handle the error + * } finally { + * if (fd !== undefined) + * closeSync(fd); + * } + * ``` + * @since v0.6.7 + * @param path filename or file descriptor + */ + export function appendFileSync( + path: PathOrFileDescriptor, + data: string | Uint8Array, + options?: WriteFileOptions, + ): void; + /** + * Watch for changes on `filename`. The callback `listener` will be called each + * time the file is accessed. + * + * The `options` argument may be omitted. If provided, it should be an object. The`options` object may contain a boolean named `persistent` that indicates + * whether the process should continue to run as long as files are being watched. + * The `options` object may specify an `interval` property indicating how often the + * target should be polled in milliseconds. + * + * The `listener` gets two arguments the current stat object and the previous + * stat object: + * + * ```js + * import { watchFile } from 'fs'; + * + * watchFile('message.text', (curr, prev) => { + * console.log(`the current mtime is: ${curr.mtime}`); + * console.log(`the previous mtime was: ${prev.mtime}`); + * }); + * ``` + * + * These stat objects are instances of `fs.Stat`. If the `bigint` option is `true`, + * the numeric values in these objects are specified as `BigInt`s. + * + * To be notified when the file was modified, not just accessed, it is necessary + * to compare `curr.mtimeMs` and `prev.mtimeMs`. + * + * When an `fs.watchFile` operation results in an `ENOENT` error, it + * will invoke the listener once, with all the fields zeroed (or, for dates, the + * Unix Epoch). If the file is created later on, the listener will be called + * again, with the latest stat objects. This is a change in functionality since + * v0.10. + * + * Using {@link watch} is more efficient than `fs.watchFile` and`fs.unwatchFile`. `fs.watch` should be used instead of `fs.watchFile` and`fs.unwatchFile` when possible. + * + * When a file being watched by `fs.watchFile()` disappears and reappears, + * then the contents of `previous` in the second callback event (the file's + * reappearance) will be the same as the contents of `previous` in the first + * callback event (its disappearance). + * + * This happens when: + * + * * the file is deleted, followed by a restore + * * the file is renamed and then renamed a second time back to its original name + * @since v0.1.31 + */ + export interface WatchFileOptions { + bigint?: boolean | undefined; + persistent?: boolean | undefined; + interval?: number | undefined; + } + /** + * Watch for changes on `filename`. The callback `listener` will be called each + * time the file is accessed. + * + * The `options` argument may be omitted. If provided, it should be an object. The`options` object may contain a boolean named `persistent` that indicates + * whether the process should continue to run as long as files are being watched. + * The `options` object may specify an `interval` property indicating how often the + * target should be polled in milliseconds. + * + * The `listener` gets two arguments the current stat object and the previous + * stat object: + * + * ```js + * import { watchFile } from 'fs'; + * + * watchFile('message.text', (curr, prev) => { + * console.log(`the current mtime is: ${curr.mtime}`); + * console.log(`the previous mtime was: ${prev.mtime}`); + * }); + * ``` + * + * These stat objects are instances of `fs.Stat`. If the `bigint` option is `true`, + * the numeric values in these objects are specified as `BigInt`s. + * + * To be notified when the file was modified, not just accessed, it is necessary + * to compare `curr.mtimeMs` and `prev.mtimeMs`. + * + * When an `fs.watchFile` operation results in an `ENOENT` error, it + * will invoke the listener once, with all the fields zeroed (or, for dates, the + * Unix Epoch). If the file is created later on, the listener will be called + * again, with the latest stat objects. This is a change in functionality since + * v0.10. + * + * Using {@link watch} is more efficient than `fs.watchFile` and`fs.unwatchFile`. `fs.watch` should be used instead of `fs.watchFile` and`fs.unwatchFile` when possible. + * + * When a file being watched by `fs.watchFile()` disappears and reappears, + * then the contents of `previous` in the second callback event (the file's + * reappearance) will be the same as the contents of `previous` in the first + * callback event (its disappearance). + * + * This happens when: + * + * * the file is deleted, followed by a restore + * * the file is renamed and then renamed a second time back to its original name + * @since v0.1.31 + */ + export function watchFile( + filename: PathLike, + options: + | (WatchFileOptions & { + bigint?: false | undefined; + }) + | undefined, + listener: StatsListener, + ): StatWatcher; + export function watchFile( + filename: PathLike, + options: + | (WatchFileOptions & { + bigint: true; + }) + | undefined, + listener: BigIntStatsListener, + ): StatWatcher; + /** + * Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * @param listener The callback listener will be called each time the file is accessed. + */ + export function watchFile(filename: PathLike, listener: StatsListener): StatWatcher; + /** + * Stop watching for changes on `filename`. If `listener` is specified, only that + * particular listener is removed. Otherwise, _all_ listeners are removed, + * effectively stopping watching of `filename`. + * + * Calling `fs.unwatchFile()` with a filename that is not being watched is a + * no-op, not an error. + * + * Using {@link watch} is more efficient than `fs.watchFile()` and`fs.unwatchFile()`. `fs.watch()` should be used instead of `fs.watchFile()`and `fs.unwatchFile()` when possible. + * @since v0.1.31 + * @param listener Optional, a listener previously attached using `fs.watchFile()` + */ + export function unwatchFile(filename: PathLike, listener?: StatsListener): void; + export function unwatchFile(filename: PathLike, listener?: BigIntStatsListener): void; + export interface WatchOptions extends Abortable { + encoding?: BufferEncoding | "buffer" | undefined; + persistent?: boolean | undefined; + recursive?: boolean | undefined; + } + export type WatchEventType = "rename" | "change"; + export type WatchListener = (event: WatchEventType, filename: T | null) => void; + export type StatsListener = (curr: Stats, prev: Stats) => void; + export type BigIntStatsListener = (curr: BigIntStats, prev: BigIntStats) => void; + /** + * Watch for changes on `filename`, where `filename` is either a file or a + * directory. + * + * The second argument is optional. If `options` is provided as a string, it + * specifies the `encoding`. Otherwise `options` should be passed as an object. + * + * The listener callback gets two arguments `(eventType, filename)`. `eventType`is either `'rename'` or `'change'`, and `filename` is the name of the file + * which triggered the event. + * + * On most platforms, `'rename'` is emitted whenever a filename appears or + * disappears in the directory. + * + * The listener callback is attached to the `'change'` event fired by `fs.FSWatcher`, but it is not the same thing as the `'change'` value of`eventType`. + * + * If a `signal` is passed, aborting the corresponding AbortController will close + * the returned `fs.FSWatcher`. + * @since v0.5.10 + * @param listener + */ + export function watch( + filename: PathLike, + options: + | (WatchOptions & { + encoding: "buffer"; + }) + | "buffer", + listener?: WatchListener, + ): FSWatcher; + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + export function watch( + filename: PathLike, + options?: WatchOptions | BufferEncoding | null, + listener?: WatchListener, + ): FSWatcher; + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + export function watch( + filename: PathLike, + options: WatchOptions | string, + listener?: WatchListener, + ): FSWatcher; + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + */ + export function watch(filename: PathLike, listener?: WatchListener): FSWatcher; + /** + * Test whether or not the given path exists by checking with the file system. + * Then call the `callback` argument with either true or false: + * + * ```js + * import { exists } from 'fs'; + * + * exists('/etc/passwd', (e) => { + * console.log(e ? 'it exists' : 'no passwd!'); + * }); + * ``` + * + * **The parameters for this callback are not consistent with other Node.js** + * **callbacks.** Normally, the first parameter to a Node.js callback is an `err`parameter, optionally followed by other parameters. The `fs.exists()` callback + * has only one boolean parameter. This is one reason `fs.access()` is recommended + * instead of `fs.exists()`. + * + * Using `fs.exists()` to check for the existence of a file before calling`fs.open()`, `fs.readFile()` or `fs.writeFile()` is not recommended. Doing + * so introduces a race condition, since other processes may change the file's + * state between the two calls. Instead, user code should open/read/write the + * file directly and handle the error raised if the file does not exist. + * + * **write (NOT RECOMMENDED)** + * + * ```js + * import { exists, open, close } from 'fs'; + * + * exists('myfile', (e) => { + * if (e) { + * console.error('myfile already exists'); + * } else { + * open('myfile', 'wx', (err, fd) => { + * if (err) throw err; + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * } + * }); + * ``` + * + * **write (RECOMMENDED)** + * + * ```js + * import { open, close } from 'fs'; + * open('myfile', 'wx', (err, fd) => { + * if (err) { + * if (err.code === 'EEXIST') { + * console.error('myfile already exists'); + * return; + * } + * + * throw err; + * } + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * **read (NOT RECOMMENDED)** + * + * ```js + * import { open, close, exists } from 'fs'; + * + * exists('myfile', (e) => { + * if (e) { + * open('myfile', 'r', (err, fd) => { + * if (err) throw err; + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * } else { + * console.error('myfile does not exist'); + * } + * }); + * ``` + * + * **read (RECOMMENDED)** + * + * ```js + * import { open, close } from 'fs'; + * + * open('myfile', 'r', (err, fd) => { + * if (err) { + * if (err.code === 'ENOENT') { + * console.error('myfile does not exist'); + * return; + * } + * + * throw err; + * } + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * The "not recommended" examples above check for existence and then use the + * file; the "recommended" examples are better because they use the file directly + * and handle the error, if any. + * + * In general, check for the existence of a file only if the file won’t be + * used directly, for example when its existence is a signal from another + * process. + * @since v0.0.2 + * @deprecated Since v1.0.0 - Use {@link stat} or {@link access} instead. + */ + export function exists(path: PathLike, callback: (exists: boolean) => void): void; + /** @deprecated */ + export namespace exists { + /** + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(path: PathLike): Promise; + } + /** + * Returns `true` if the path exists, `false` otherwise. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link exists}. + * + * `fs.exists()` is deprecated, but `fs.existsSync()` is not. The `callback`parameter to `fs.exists()` accepts parameters that are inconsistent with other + * Node.js callbacks. `fs.existsSync()` does not use a callback. + * + * ```js + * import { existsSync } from 'fs'; + * + * if (existsSync('/etc/passwd')) + * console.log('The path exists.'); + * ``` + * @since v0.1.21 + */ + export function existsSync(path: PathLike): boolean; + export namespace constants { + // File Access Constants + /** Constant for fs.access(). File is visible to the calling process. */ + const F_OK: number; + /** Constant for fs.access(). File can be read by the calling process. */ + const R_OK: number; + /** Constant for fs.access(). File can be written by the calling process. */ + const W_OK: number; + /** Constant for fs.access(). File can be executed by the calling process. */ + const X_OK: number; + // File Copy Constants + /** Constant for fs.copyFile. Flag indicating the destination file should not be overwritten if it already exists. */ + const COPYFILE_EXCL: number; + /** + * Constant for fs.copyFile. copy operation will attempt to create a copy-on-write reflink. + * If the underlying platform does not support copy-on-write, then a fallback copy mechanism is used. + */ + const COPYFILE_FICLONE: number; + /** + * Constant for fs.copyFile. Copy operation will attempt to create a copy-on-write reflink. + * If the underlying platform does not support copy-on-write, then the operation will fail with an error. + */ + const COPYFILE_FICLONE_FORCE: number; + // File Open Constants + /** Constant for fs.open(). Flag indicating to open a file for read-only access. */ + const O_RDONLY: number; + /** Constant for fs.open(). Flag indicating to open a file for write-only access. */ + const O_WRONLY: number; + /** Constant for fs.open(). Flag indicating to open a file for read-write access. */ + const O_RDWR: number; + /** Constant for fs.open(). Flag indicating to create the file if it does not already exist. */ + const O_CREAT: number; + /** Constant for fs.open(). Flag indicating that opening a file should fail if the O_CREAT flag is set and the file already exists. */ + const O_EXCL: number; + /** + * Constant for fs.open(). Flag indicating that if path identifies a terminal device, + * opening the path shall not cause that terminal to become the controlling terminal for the process + * (if the process does not already have one). + */ + const O_NOCTTY: number; + /** Constant for fs.open(). Flag indicating that if the file exists and is a regular file, and the file is opened successfully for write access, its length shall be truncated to zero. */ + const O_TRUNC: number; + /** Constant for fs.open(). Flag indicating that data will be appended to the end of the file. */ + const O_APPEND: number; + /** Constant for fs.open(). Flag indicating that the open should fail if the path is not a directory. */ + const O_DIRECTORY: number; + /** + * constant for fs.open(). + * Flag indicating reading accesses to the file system will no longer result in + * an update to the atime information associated with the file. + * This flag is available on Linux operating systems only. + */ + const O_NOATIME: number; + /** Constant for fs.open(). Flag indicating that the open should fail if the path is a symbolic link. */ + const O_NOFOLLOW: number; + /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O. */ + const O_SYNC: number; + /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O with write operations waiting for data integrity. */ + const O_DSYNC: number; + /** Constant for fs.open(). Flag indicating to open the symbolic link itself rather than the resource it is pointing to. */ + const O_SYMLINK: number; + /** Constant for fs.open(). When set, an attempt will be made to minimize caching effects of file I/O. */ + const O_DIRECT: number; + /** Constant for fs.open(). Flag indicating to open the file in nonblocking mode when possible. */ + const O_NONBLOCK: number; + // File Type Constants + /** Constant for fs.Stats mode property for determining a file's type. Bit mask used to extract the file type code. */ + const S_IFMT: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a regular file. */ + const S_IFREG: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a directory. */ + const S_IFDIR: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a character-oriented device file. */ + const S_IFCHR: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a block-oriented device file. */ + const S_IFBLK: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a FIFO/pipe. */ + const S_IFIFO: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a symbolic link. */ + const S_IFLNK: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a socket. */ + const S_IFSOCK: number; + // File Mode Constants + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by owner. */ + const S_IRWXU: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by owner. */ + const S_IRUSR: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by owner. */ + const S_IWUSR: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by owner. */ + const S_IXUSR: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by group. */ + const S_IRWXG: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by group. */ + const S_IRGRP: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by group. */ + const S_IWGRP: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by group. */ + const S_IXGRP: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by others. */ + const S_IRWXO: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by others. */ + const S_IROTH: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by others. */ + const S_IWOTH: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by others. */ + const S_IXOTH: number; + /** + * When set, a memory file mapping is used to access the file. This flag + * is available on Windows operating systems only. On other operating systems, + * this flag is ignored. + */ + const UV_FS_O_FILEMAP: number; + } + /** + * Tests a user's permissions for the file or directory specified by `path`. + * The `mode` argument is an optional integer that specifies the accessibility + * checks to be performed. `mode` should be either the value `fs.constants.F_OK`or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`,`fs.constants.W_OK`, and `fs.constants.X_OK` + * (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for + * possible values of `mode`. + * + * The final argument, `callback`, is a callback function that is invoked with + * a possible error argument. If any of the accessibility checks fail, the error + * argument will be an `Error` object. The following examples check if`package.json` exists, and if it is readable or writable. + * + * ```js + * import { access, constants } from 'fs'; + * + * const file = 'package.json'; + * + * // Check if the file exists in the current directory. + * access(file, constants.F_OK, (err) => { + * console.log(`${file} ${err ? 'does not exist' : 'exists'}`); + * }); + * + * // Check if the file is readable. + * access(file, constants.R_OK, (err) => { + * console.log(`${file} ${err ? 'is not readable' : 'is readable'}`); + * }); + * + * // Check if the file is writable. + * access(file, constants.W_OK, (err) => { + * console.log(`${file} ${err ? 'is not writable' : 'is writable'}`); + * }); + * + * // Check if the file is readable and writable. + * access(file, constants.R_OK | constants.W_OK, (err) => { + * console.log(`${file} ${err ? 'is not' : 'is'} readable and writable`); + * }); + * ``` + * + * Do not use `fs.access()` to check for the accessibility of a file before calling`fs.open()`, `fs.readFile()` or `fs.writeFile()`. Doing + * so introduces a race condition, since other processes may change the file's + * state between the two calls. Instead, user code should open/read/write the + * file directly and handle the error raised if the file is not accessible. + * + * **write (NOT RECOMMENDED)** + * + * ```js + * import { access, open, close } from 'fs'; + * + * access('myfile', (err) => { + * if (!err) { + * console.error('myfile already exists'); + * return; + * } + * + * open('myfile', 'wx', (err, fd) => { + * if (err) throw err; + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * }); + * ``` + * + * **write (RECOMMENDED)** + * + * ```js + * import { open, close } from 'fs'; + * + * open('myfile', 'wx', (err, fd) => { + * if (err) { + * if (err.code === 'EEXIST') { + * console.error('myfile already exists'); + * return; + * } + * + * throw err; + * } + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * **read (NOT RECOMMENDED)** + * + * ```js + * import { access, open, close } from 'fs'; + * access('myfile', (err) => { + * if (err) { + * if (err.code === 'ENOENT') { + * console.error('myfile does not exist'); + * return; + * } + * + * throw err; + * } + * + * open('myfile', 'r', (err, fd) => { + * if (err) throw err; + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * }); + * ``` + * + * **read (RECOMMENDED)** + * + * ```js + * import { open, close } from 'fs'; + * + * open('myfile', 'r', (err, fd) => { + * if (err) { + * if (err.code === 'ENOENT') { + * console.error('myfile does not exist'); + * return; + * } + * + * throw err; + * } + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * The "not recommended" examples above check for accessibility and then use the + * file; the "recommended" examples are better because they use the file directly + * and handle the error, if any. + * + * In general, check for the accessibility of a file only if the file will not be + * used directly, for example when its accessibility is a signal from another + * process. + * + * On Windows, access-control policies (ACLs) on a directory may limit access to + * a file or directory. The `fs.access()` function, however, does not check the + * ACL and therefore may report that a path is accessible even if the ACL restricts + * the user from reading or writing to it. + * @since v0.11.15 + * @param [mode=fs.constants.F_OK] + */ + export function access(path: PathLike, mode: number | undefined, callback: NoParamCallback): void; + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + */ + export function access(path: PathLike, callback: NoParamCallback): void; + export namespace access { + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(path: PathLike, mode?: number): Promise; + } + /** + * Synchronously tests a user's permissions for the file or directory specified + * by `path`. The `mode` argument is an optional integer that specifies the + * accessibility checks to be performed. `mode` should be either the value`fs.constants.F_OK` or a mask consisting of the bitwise OR of any of`fs.constants.R_OK`, `fs.constants.W_OK`, and + * `fs.constants.X_OK` (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for + * possible values of `mode`. + * + * If any of the accessibility checks fail, an `Error` will be thrown. Otherwise, + * the method will return `undefined`. + * + * ```js + * import { accessSync, constants } from 'fs'; + * + * try { + * accessSync('etc/passwd', constants.R_OK | constants.W_OK); + * console.log('can read/write'); + * } catch (err) { + * console.error('no access!'); + * } + * ``` + * @since v0.11.15 + * @param [mode=fs.constants.F_OK] + */ + export function accessSync(path: PathLike, mode?: number): void; + interface StreamOptions { + flags?: string | undefined; + encoding?: BufferEncoding | undefined; + fd?: number | promises.FileHandle | undefined; + mode?: number | undefined; + autoClose?: boolean | undefined; + emitClose?: boolean | undefined; + start?: number | undefined; + highWaterMark?: number | undefined; + } + interface FSImplementation { + open?: (...args: any[]) => any; + close?: (...args: any[]) => any; + } + interface CreateReadStreamFSImplementation extends FSImplementation { + read: (...args: any[]) => any; + } + interface CreateWriteStreamFSImplementation extends FSImplementation { + write: (...args: any[]) => any; + writev?: (...args: any[]) => any; + } + interface ReadStreamOptions extends StreamOptions { + fs?: CreateReadStreamFSImplementation | null | undefined; + end?: number | undefined; + } + interface WriteStreamOptions extends StreamOptions { + fs?: CreateWriteStreamFSImplementation | null | undefined; + } + /** + * Unlike the 16 kb default `highWaterMark` for a `stream.Readable`, the stream + * returned by this method has a default `highWaterMark` of 64 kb. + * + * `options` can include `start` and `end` values to read a range of bytes from + * the file instead of the entire file. Both `start` and `end` are inclusive and + * start counting at 0, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. If `fd` is specified and `start` is + * omitted or `undefined`, `fs.createReadStream()` reads sequentially from the + * current file position. The `encoding` can be any one of those accepted by `Buffer`. + * + * If `fd` is specified, `ReadStream` will ignore the `path` argument and will use + * the specified file descriptor. This means that no `'open'` event will be + * emitted. `fd` should be blocking; non-blocking `fd`s should be passed to `net.Socket`. + * + * If `fd` points to a character device that only supports blocking reads + * (such as keyboard or sound card), read operations do not finish until data is + * available. This can prevent the process from exiting and the stream from + * closing naturally. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * + * By providing the `fs` option, it is possible to override the corresponding `fs`implementations for `open`, `read`, and `close`. When providing the `fs` option, + * an override for `read` is required. If no `fd` is provided, an override for`open` is also required. If `autoClose` is `true`, an override for `close` is + * also required. + * + * ```js + * import { createReadStream } from 'fs'; + * + * // Create a stream from some character device. + * const stream = createReadStream('/dev/input/event0'); + * setTimeout(() => { + * stream.close(); // This may not close the stream. + * // Artificially marking end-of-stream, as if the underlying resource had + * // indicated end-of-file by itself, allows the stream to close. + * // This does not cancel pending read operations, and if there is such an + * // operation, the process may still not be able to exit successfully + * // until it finishes. + * stream.push(null); + * stream.read(0); + * }, 100); + * ``` + * + * If `autoClose` is false, then the file descriptor won't be closed, even if + * there's an error. It is the application's responsibility to close it and make + * sure there's no file descriptor leak. If `autoClose` is set to true (default + * behavior), on `'error'` or `'end'` the file descriptor will be closed + * automatically. + * + * `mode` sets the file mode (permission and sticky bits), but only if the + * file was created. + * + * An example to read the last 10 bytes of a file which is 100 bytes long: + * + * ```js + * import { createReadStream } from 'fs'; + * + * createReadStream('sample.txt', { start: 90, end: 99 }); + * ``` + * + * If `options` is a string, then it specifies the encoding. + * @since v0.1.31 + */ + export function createReadStream(path: PathLike, options?: BufferEncoding | ReadStreamOptions): ReadStream; + /** + * `options` may also include a `start` option to allow writing data at some + * position past the beginning of the file, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. Modifying a file rather than + * replacing it may require the `flags` option to be set to `r+` rather than the + * default `w`. The `encoding` can be any one of those accepted by `Buffer`. + * + * If `autoClose` is set to true (default behavior) on `'error'` or `'finish'`the file descriptor will be closed automatically. If `autoClose` is false, + * then the file descriptor won't be closed, even if there's an error. + * It is the application's responsibility to close it and make sure there's no + * file descriptor leak. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * + * By providing the `fs` option it is possible to override the corresponding `fs`implementations for `open`, `write`, `writev` and `close`. Overriding `write()`without `writev()` can reduce + * performance as some optimizations (`_writev()`) + * will be disabled. When providing the `fs` option, overrides for at least one of`write` and `writev` are required. If no `fd` option is supplied, an override + * for `open` is also required. If `autoClose` is `true`, an override for `close`is also required. + * + * Like `fs.ReadStream`, if `fd` is specified, `fs.WriteStream` will ignore the`path` argument and will use the specified file descriptor. This means that no`'open'` event will be + * emitted. `fd` should be blocking; non-blocking `fd`s + * should be passed to `net.Socket`. + * + * If `options` is a string, then it specifies the encoding. + * @since v0.1.31 + */ + export function createWriteStream(path: PathLike, options?: BufferEncoding | WriteStreamOptions): WriteStream; + /** + * Forces all currently queued I/O operations associated with the file to the + * operating system's synchronized I/O completion state. Refer to the POSIX [`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. No arguments other + * than a possible + * exception are given to the completion callback. + * @since v0.1.96 + */ + export function fdatasync(fd: number, callback: NoParamCallback): void; + export namespace fdatasync { + /** + * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + /** + * Forces all currently queued I/O operations associated with the file to the + * operating system's synchronized I/O completion state. Refer to the POSIX [`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. Returns `undefined`. + * @since v0.1.96 + */ + export function fdatasyncSync(fd: number): void; + /** + * Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it + * already exists. No arguments other than a possible exception are given to the + * callback function. Node.js makes no guarantees about the atomicity of the copy + * operation. If an error occurs after the destination file has been opened for + * writing, Node.js will attempt to remove the destination. + * + * `mode` is an optional integer that specifies the behavior + * of the copy operation. It is possible to create a mask consisting of the bitwise + * OR of two or more values (e.g.`fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`). + * + * * `fs.constants.COPYFILE_EXCL`: The copy operation will fail if `dest` already + * exists. + * * `fs.constants.COPYFILE_FICLONE`: The copy operation will attempt to create a + * copy-on-write reflink. If the platform does not support copy-on-write, then a + * fallback copy mechanism is used. + * * `fs.constants.COPYFILE_FICLONE_FORCE`: The copy operation will attempt to + * create a copy-on-write reflink. If the platform does not support + * copy-on-write, then the operation will fail. + * + * ```js + * import { copyFile, constants } from 'fs'; + * + * function callback(err) { + * if (err) throw err; + * console.log('source.txt was copied to destination.txt'); + * } + * + * // destination.txt will be created or overwritten by default. + * copyFile('source.txt', 'destination.txt', callback); + * + * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. + * copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL, callback); + * ``` + * @since v8.5.0 + * @param src source filename to copy + * @param dest destination filename of the copy operation + * @param [mode=0] modifiers for copy operation. + */ + export function copyFile(src: PathLike, dest: PathLike, callback: NoParamCallback): void; + export function copyFile(src: PathLike, dest: PathLike, mode: number, callback: NoParamCallback): void; + export namespace copyFile { + function __promisify__(src: PathLike, dst: PathLike, mode?: number): Promise; + } + /** + * Synchronously copies `src` to `dest`. By default, `dest` is overwritten if it + * already exists. Returns `undefined`. Node.js makes no guarantees about the + * atomicity of the copy operation. If an error occurs after the destination file + * has been opened for writing, Node.js will attempt to remove the destination. + * + * `mode` is an optional integer that specifies the behavior + * of the copy operation. It is possible to create a mask consisting of the bitwise + * OR of two or more values (e.g.`fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`). + * + * * `fs.constants.COPYFILE_EXCL`: The copy operation will fail if `dest` already + * exists. + * * `fs.constants.COPYFILE_FICLONE`: The copy operation will attempt to create a + * copy-on-write reflink. If the platform does not support copy-on-write, then a + * fallback copy mechanism is used. + * * `fs.constants.COPYFILE_FICLONE_FORCE`: The copy operation will attempt to + * create a copy-on-write reflink. If the platform does not support + * copy-on-write, then the operation will fail. + * + * ```js + * import { copyFileSync, constants } from 'fs'; + * + * // destination.txt will be created or overwritten by default. + * copyFileSync('source.txt', 'destination.txt'); + * console.log('source.txt was copied to destination.txt'); + * + * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. + * copyFileSync('source.txt', 'destination.txt', constants.COPYFILE_EXCL); + * ``` + * @since v8.5.0 + * @param src source filename to copy + * @param dest destination filename of the copy operation + * @param [mode=0] modifiers for copy operation. + */ + export function copyFileSync(src: PathLike, dest: PathLike, mode?: number): void; + /** + * Write an array of `ArrayBufferView`s to the file specified by `fd` using`writev()`. + * + * `position` is the offset from the beginning of the file where this data + * should be written. If `typeof position !== 'number'`, the data will be written + * at the current position. + * + * The callback will be given three arguments: `err`, `bytesWritten`, and`buffers`. `bytesWritten` is how many bytes were written from `buffers`. + * + * If this method is `util.promisify()` ed, it returns a promise for an`Object` with `bytesWritten` and `buffers` properties. + * + * It is unsafe to use `fs.writev()` multiple times on the same file without + * waiting for the callback. For this scenario, use {@link createWriteStream}. + * + * On Linux, positional writes don't work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v12.9.0 + */ + export function writev( + fd: number, + buffers: readonly NodeJS.ArrayBufferView[], + cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => void, + ): void; + export function writev( + fd: number, + buffers: readonly NodeJS.ArrayBufferView[], + position: number, + cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => void, + ): void; + export interface WriteVResult { + bytesWritten: number; + buffers: NodeJS.ArrayBufferView[]; + } + export namespace writev { + function __promisify__( + fd: number, + buffers: readonly NodeJS.ArrayBufferView[], + position?: number, + ): Promise; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link writev}. + * @since v12.9.0 + * @return The number of bytes written. + */ + export function writevSync(fd: number, buffers: readonly NodeJS.ArrayBufferView[], position?: number): number; + /** + * Read from a file specified by `fd` and write to an array of `ArrayBufferView`s + * using `readv()`. + * + * `position` is the offset from the beginning of the file from where data + * should be read. If `typeof position !== 'number'`, the data will be read + * from the current position. + * + * The callback will be given three arguments: `err`, `bytesRead`, and`buffers`. `bytesRead` is how many bytes were read from the file. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a promise for an `Object` with `bytesRead` and `buffers` properties. + * @since v13.13.0, v12.17.0 + */ + export function readv( + fd: number, + buffers: readonly NodeJS.ArrayBufferView[], + cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: NodeJS.ArrayBufferView[]) => void, + ): void; + export function readv( + fd: number, + buffers: readonly NodeJS.ArrayBufferView[], + position: number, + cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: NodeJS.ArrayBufferView[]) => void, + ): void; + export interface ReadVResult { + bytesRead: number; + buffers: NodeJS.ArrayBufferView[]; + } + export namespace readv { + function __promisify__( + fd: number, + buffers: readonly NodeJS.ArrayBufferView[], + position?: number, + ): Promise; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link readv}. + * @since v13.13.0, v12.17.0 + * @return The number of bytes read. + */ + export function readvSync(fd: number, buffers: readonly NodeJS.ArrayBufferView[], position?: number): number; + export interface OpenDirOptions { + encoding?: BufferEncoding | undefined; + /** + * Number of directory entries that are buffered + * internally when reading from the directory. Higher values lead to better + * performance but higher memory usage. + * @default 32 + */ + bufferSize?: number | undefined; + } + /** + * Synchronously open a directory. See [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html). + * + * Creates an `fs.Dir`, which contains all further functions for reading from + * and cleaning up the directory. + * + * The `encoding` option sets the encoding for the `path` while opening the + * directory and subsequent read operations. + * @since v12.12.0 + */ + export function opendirSync(path: PathLike, options?: OpenDirOptions): Dir; + /** + * Asynchronously open a directory. See the POSIX [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html) documentation for + * more details. + * + * Creates an `fs.Dir`, which contains all further functions for reading from + * and cleaning up the directory. + * + * The `encoding` option sets the encoding for the `path` while opening the + * directory and subsequent read operations. + * @since v12.12.0 + */ + export function opendir(path: PathLike, cb: (err: NodeJS.ErrnoException | null, dir: Dir) => void): void; + export function opendir( + path: PathLike, + options: OpenDirOptions, + cb: (err: NodeJS.ErrnoException | null, dir: Dir) => void, + ): void; + export namespace opendir { + function __promisify__(path: PathLike, options?: OpenDirOptions): Promise; + } + export interface BigIntStats extends StatsBase { + atimeNs: bigint; + mtimeNs: bigint; + ctimeNs: bigint; + birthtimeNs: bigint; + } + export interface BigIntOptions { + bigint: true; + } + export interface StatOptions { + bigint?: boolean | undefined; + } + export interface StatSyncOptions extends StatOptions { + throwIfNoEntry?: boolean | undefined; + } + interface CopyOptionsBase { + /** + * Dereference symlinks + * @default false + */ + dereference?: boolean; + /** + * When `force` is `false`, and the destination + * exists, throw an error. + * @default false + */ + errorOnExist?: boolean; + /** + * Overwrite existing file or directory. _The copy + * operation will ignore errors if you set this to false and the destination + * exists. Use the `errorOnExist` option to change this behavior. + * @default true + */ + force?: boolean; + /** + * Modifiers for copy operation. See `mode` flag of {@link copyFileSync()} + */ + mode?: number; + /** + * When `true` timestamps from `src` will + * be preserved. + * @default false + */ + preserveTimestamps?: boolean; + /** + * Copy directories recursively. + * @default false + */ + recursive?: boolean; + /** + * When true, path resolution for symlinks will be skipped + * @default false + */ + verbatimSymlinks?: boolean; + } + export interface CopyOptions extends CopyOptionsBase { + /** + * Function to filter copied files/directories. Return + * `true` to copy the item, `false` to ignore it. + */ + filter?(source: string, destination: string): boolean | Promise; + } + export interface CopySyncOptions extends CopyOptionsBase { + /** + * Function to filter copied files/directories. Return + * `true` to copy the item, `false` to ignore it. + */ + filter?(source: string, destination: string): boolean; + } + /** + * Asynchronously copies the entire directory structure from `src` to `dest`, + * including subdirectories and files. + * + * When copying a directory to another directory, globs are not supported and + * behavior is similar to `cp dir1/ dir2/`. + * @since v16.7.0 + * @experimental + * @param src source path to copy. + * @param dest destination path to copy to. + */ + export function cp( + source: string | URL, + destination: string | URL, + callback: (err: NodeJS.ErrnoException | null) => void, + ): void; + export function cp( + source: string | URL, + destination: string | URL, + opts: CopyOptions, + callback: (err: NodeJS.ErrnoException | null) => void, + ): void; + /** + * Synchronously copies the entire directory structure from `src` to `dest`, + * including subdirectories and files. + * + * When copying a directory to another directory, globs are not supported and + * behavior is similar to `cp dir1/ dir2/`. + * @since v16.7.0 + * @experimental + * @param src source path to copy. + * @param dest destination path to copy to. + */ + export function cpSync(source: string | URL, destination: string | URL, opts?: CopySyncOptions): void; +} +declare module "node:fs" { + export * from "fs"; +} diff --git a/backend/node_modules/@types/node/fs/promises.d.ts b/backend/node_modules/@types/node/fs/promises.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7e55f894f03bd542422c234a119b4108cc338b9b --- /dev/null +++ b/backend/node_modules/@types/node/fs/promises.d.ts @@ -0,0 +1,1205 @@ +/** + * The `fs/promises` API provides asynchronous file system methods that return + * promises. + * + * The promise APIs use the underlying Node.js threadpool to perform file + * system operations off the event loop thread. These operations are not + * synchronized or threadsafe. Care must be taken when performing multiple + * concurrent modifications on the same file or data corruption may occur. + * @since v10.0.0 + */ +declare module "fs/promises" { + import { Abortable } from "node:events"; + import { Stream } from "node:stream"; + import { ReadableStream } from "node:stream/web"; + import { + BigIntStats, + BigIntStatsFs, + BufferEncodingOption, + constants as fsConstants, + CopyOptions, + Dir, + Dirent, + MakeDirectoryOptions, + Mode, + ObjectEncodingOptions, + OpenDirOptions, + OpenMode, + PathLike, + ReadStream, + ReadVResult, + RmDirOptions, + RmOptions, + StatFsOptions, + StatOptions, + Stats, + StatsFs, + TimeLike, + WatchEventType, + WatchOptions, + WriteStream, + WriteVResult, + } from "node:fs"; + import { Interface as ReadlineInterface } from "node:readline"; + + interface FileChangeInfo { + eventType: WatchEventType; + filename: T | null; + } + interface FlagAndOpenMode { + mode?: Mode | undefined; + flag?: OpenMode | undefined; + } + interface FileReadResult { + bytesRead: number; + buffer: T; + } + interface FileReadOptions { + /** + * @default `Buffer.alloc(0xffff)` + */ + buffer?: T; + /** + * @default 0 + */ + offset?: number | null; + /** + * @default `buffer.byteLength` + */ + length?: number | null; + position?: number | null; + } + interface CreateReadStreamOptions { + encoding?: BufferEncoding | null | undefined; + autoClose?: boolean | undefined; + emitClose?: boolean | undefined; + start?: number | undefined; + end?: number | undefined; + highWaterMark?: number | undefined; + } + interface CreateWriteStreamOptions { + encoding?: BufferEncoding | null | undefined; + autoClose?: boolean | undefined; + emitClose?: boolean | undefined; + start?: number | undefined; + highWaterMark?: number | undefined; + } + interface ReadableWebStreamOptions { + /** + * Whether to open a normal or a `'bytes'` stream. + * @since v18.17.0 + */ + type?: "bytes" | undefined; + } + // TODO: Add `EventEmitter` close + interface FileHandle { + /** + * The numeric file descriptor managed by the {FileHandle} object. + * @since v10.0.0 + */ + readonly fd: number; + /** + * Alias of `filehandle.writeFile()`. + * + * When operating on file handles, the mode cannot be changed from what it was set + * to with `fsPromises.open()`. Therefore, this is equivalent to `filehandle.writeFile()`. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + appendFile( + data: string | Uint8Array, + options?: (ObjectEncodingOptions & FlagAndOpenMode) | BufferEncoding | null, + ): Promise; + /** + * Changes the ownership of the file. A wrapper for [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html). + * @since v10.0.0 + * @param uid The file's new owner's user id. + * @param gid The file's new group's group id. + * @return Fulfills with `undefined` upon success. + */ + chown(uid: number, gid: number): Promise; + /** + * Modifies the permissions on the file. See [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html). + * @since v10.0.0 + * @param mode the file mode bit mask. + * @return Fulfills with `undefined` upon success. + */ + chmod(mode: Mode): Promise; + /** + * Unlike the 16 kb default `highWaterMark` for a `stream.Readable`, the stream + * returned by this method has a default `highWaterMark` of 64 kb. + * + * `options` can include `start` and `end` values to read a range of bytes from + * the file instead of the entire file. Both `start` and `end` are inclusive and + * start counting at 0, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. If `start` is + * omitted or `undefined`, `filehandle.createReadStream()` reads sequentially from + * the current file position. The `encoding` can be any one of those accepted by `Buffer`. + * + * If the `FileHandle` points to a character device that only supports blocking + * reads (such as keyboard or sound card), read operations do not finish until data + * is available. This can prevent the process from exiting and the stream from + * closing naturally. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * + * ```js + * import { open } from 'fs/promises'; + * + * const fd = await open('/dev/input/event0'); + * // Create a stream from some character device. + * const stream = fd.createReadStream(); + * setTimeout(() => { + * stream.close(); // This may not close the stream. + * // Artificially marking end-of-stream, as if the underlying resource had + * // indicated end-of-file by itself, allows the stream to close. + * // This does not cancel pending read operations, and if there is such an + * // operation, the process may still not be able to exit successfully + * // until it finishes. + * stream.push(null); + * stream.read(0); + * }, 100); + * ``` + * + * If `autoClose` is false, then the file descriptor won't be closed, even if + * there's an error. It is the application's responsibility to close it and make + * sure there's no file descriptor leak. If `autoClose` is set to true (default + * behavior), on `'error'` or `'end'` the file descriptor will be closed + * automatically. + * + * An example to read the last 10 bytes of a file which is 100 bytes long: + * + * ```js + * import { open } from 'fs/promises'; + * + * const fd = await open('sample.txt'); + * fd.createReadStream({ start: 90, end: 99 }); + * ``` + * @since v16.11.0 + */ + createReadStream(options?: CreateReadStreamOptions): ReadStream; + /** + * `options` may also include a `start` option to allow writing data at some + * position past the beginning of the file, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. Modifying a file rather than + * replacing it may require the `flags` `open` option to be set to `r+` rather than + * the default `r`. The `encoding` can be any one of those accepted by `Buffer`. + * + * If `autoClose` is set to true (default behavior) on `'error'` or `'finish'`the file descriptor will be closed automatically. If `autoClose` is false, + * then the file descriptor won't be closed, even if there's an error. + * It is the application's responsibility to close it and make sure there's no + * file descriptor leak. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * @since v16.11.0 + */ + createWriteStream(options?: CreateWriteStreamOptions): WriteStream; + /** + * Forces all currently queued I/O operations associated with the file to the + * operating system's synchronized I/O completion state. Refer to the POSIX [`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. + * + * Unlike `filehandle.sync` this method does not flush modified metadata. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + datasync(): Promise; + /** + * Request that all data for the open file descriptor is flushed to the storage + * device. The specific implementation is operating system and device specific. + * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. + * @since v10.0.0 + * @return Fufills with `undefined` upon success. + */ + sync(): Promise; + /** + * Reads data from the file and stores that in the given buffer. + * + * If the file is not modified concurrently, the end-of-file is reached when the + * number of bytes read is zero. + * @since v10.0.0 + * @param buffer A buffer that will be filled with the file data read. + * @param offset The location in the buffer at which to start filling. + * @param length The number of bytes to read. + * @param position The location where to begin reading data from the file. If `null`, data will be read from the current file position, and the position will be updated. If `position` is an + * integer, the current file position will remain unchanged. + * @return Fulfills upon success with an object with two properties: + */ + read( + buffer: T, + offset?: number | null, + length?: number | null, + position?: number | null, + ): Promise>; + read(options?: FileReadOptions): Promise>; + /** + * Returns a `ReadableStream` that may be used to read the files data. + * + * An error will be thrown if this method is called more than once or is called after the `FileHandle` is closed + * or closing. + * + * ```js + * import { open } from 'node:fs/promises'; + * + * const file = await open('./some/file/to/read'); + * + * for await (const chunk of file.readableWebStream()) + * console.log(chunk); + * + * await file.close(); + * ``` + * + * While the `ReadableStream` will read the file to completion, it will not close the `FileHandle` automatically. User code must still call the `fileHandle.close()` method. + * + * @since v17.0.0 + * @experimental + */ + readableWebStream(options?: ReadableWebStreamOptions): ReadableStream; + /** + * Asynchronously reads the entire contents of a file. + * + * If `options` is a string, then it specifies the `encoding`. + * + * The `FileHandle` has to support reading. + * + * If one or more `filehandle.read()` calls are made on a file handle and then a`filehandle.readFile()` call is made, the data will be read from the current + * position till the end of the file. It doesn't always read from the beginning + * of the file. + * @since v10.0.0 + * @return Fulfills upon a successful read with the contents of the file. If no encoding is specified (using `options.encoding`), the data is returned as a {Buffer} object. Otherwise, the + * data will be a string. + */ + readFile( + options?: { + encoding?: null | undefined; + flag?: OpenMode | undefined; + } | null, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for reading. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + readFile( + options: + | { + encoding: BufferEncoding; + flag?: OpenMode | undefined; + } + | BufferEncoding, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for reading. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + readFile( + options?: + | (ObjectEncodingOptions & { + flag?: OpenMode | undefined; + }) + | BufferEncoding + | null, + ): Promise; + /** + * Convenience method to create a `readline` interface and stream over the file. For example: + * + * ```js + * import { open } from 'node:fs/promises'; + * + * const file = await open('./some/file/to/read'); + * + * for await (const line of file.readLines()) { + * console.log(line); + * } + * ``` + * + * @since v18.11.0 + * @param options See `filehandle.createReadStream()` for the options. + */ + readLines(options?: CreateReadStreamOptions): ReadlineInterface; + /** + * @since v10.0.0 + * @return Fulfills with an {fs.Stats} for the file. + */ + stat( + opts?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + stat( + opts: StatOptions & { + bigint: true; + }, + ): Promise; + stat(opts?: StatOptions): Promise; + /** + * Truncates the file. + * + * If the file was larger than `len` bytes, only the first `len` bytes will be + * retained in the file. + * + * The following example retains only the first four bytes of the file: + * + * ```js + * import { open } from 'fs/promises'; + * + * let filehandle = null; + * try { + * filehandle = await open('temp.txt', 'r+'); + * await filehandle.truncate(4); + * } finally { + * await filehandle?.close(); + * } + * ``` + * + * If the file previously was shorter than `len` bytes, it is extended, and the + * extended part is filled with null bytes (`'\0'`): + * + * If `len` is negative then `0` will be used. + * @since v10.0.0 + * @param [len=0] + * @return Fulfills with `undefined` upon success. + */ + truncate(len?: number): Promise; + /** + * Change the file system timestamps of the object referenced by the `FileHandle` then resolves the promise with no arguments upon success. + * @since v10.0.0 + */ + utimes(atime: TimeLike, mtime: TimeLike): Promise; + /** + * Asynchronously writes data to a file, replacing the file if it already exists.`data` can be a string, a buffer, an + * [AsyncIterable](https://tc39.github.io/ecma262/#sec-asynciterable-interface) or + * [Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) object. + * The promise is resolved with no arguments upon success. + * + * If `options` is a string, then it specifies the `encoding`. + * + * The `FileHandle` has to support writing. + * + * It is unsafe to use `filehandle.writeFile()` multiple times on the same file + * without waiting for the promise to be resolved (or rejected). + * + * If one or more `filehandle.write()` calls are made on a file handle and then a`filehandle.writeFile()` call is made, the data will be written from the + * current position till the end of the file. It doesn't always write from the + * beginning of the file. + * @since v10.0.0 + */ + writeFile( + data: string | Uint8Array, + options?: (ObjectEncodingOptions & FlagAndOpenMode & Abortable) | BufferEncoding | null, + ): Promise; + /** + * Write `buffer` to the file. + * + * The promise is resolved with an object containing two properties: + * + * It is unsafe to use `filehandle.write()` multiple times on the same file + * without waiting for the promise to be resolved (or rejected). For this + * scenario, use `filehandle.createWriteStream()`. + * + * On Linux, positional writes do not work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v10.0.0 + * @param [offset=0] The start position from within `buffer` where the data to write begins. + * @param [length=buffer.byteLength - offset] The number of bytes from `buffer` to write. + * @param position The offset from the beginning of the file where the data from `buffer` should be written. If `position` is not a `number`, the data will be written at the current position. + * See the POSIX pwrite(2) documentation for more detail. + */ + write( + buffer: TBuffer, + offset?: number | null, + length?: number | null, + position?: number | null, + ): Promise<{ + bytesWritten: number; + buffer: TBuffer; + }>; + write( + data: string, + position?: number | null, + encoding?: BufferEncoding | null, + ): Promise<{ + bytesWritten: number; + buffer: string; + }>; + /** + * Write an array of [ArrayBufferView](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView) s to the file. + * + * The promise is resolved with an object containing a two properties: + * + * It is unsafe to call `writev()` multiple times on the same file without waiting + * for the promise to be resolved (or rejected). + * + * On Linux, positional writes don't work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v12.9.0 + * @param position The offset from the beginning of the file where the data from `buffers` should be written. If `position` is not a `number`, the data will be written at the current + * position. + */ + writev(buffers: readonly NodeJS.ArrayBufferView[], position?: number): Promise; + /** + * Read from a file and write to an array of [ArrayBufferView](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView) s + * @since v13.13.0, v12.17.0 + * @param position The offset from the beginning of the file where the data should be read from. If `position` is not a `number`, the data will be read from the current position. + * @return Fulfills upon success an object containing two properties: + */ + readv(buffers: readonly NodeJS.ArrayBufferView[], position?: number): Promise; + /** + * Closes the file handle after waiting for any pending operation on the handle to + * complete. + * + * ```js + * import { open } from 'fs/promises'; + * + * let filehandle; + * try { + * filehandle = await open('thefile.txt', 'r'); + * } finally { + * await filehandle?.close(); + * } + * ``` + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + close(): Promise; + /** + * An alias for {@link FileHandle.close()}. + * @since v18.18.0 + */ + [Symbol.asyncDispose](): Promise; + } + + const constants: typeof fsConstants; + + /** + * Tests a user's permissions for the file or directory specified by `path`. + * The `mode` argument is an optional integer that specifies the accessibility + * checks to be performed. `mode` should be either the value `fs.constants.F_OK`or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`,`fs.constants.W_OK`, and `fs.constants.X_OK` + * (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for + * possible values of `mode`. + * + * If the accessibility check is successful, the promise is resolved with no + * value. If any of the accessibility checks fail, the promise is rejected + * with an [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object. The following example checks if the file`/etc/passwd` can be read and + * written by the current process. + * + * ```js + * import { access } from 'fs/promises'; + * import { constants } from 'fs'; + * + * try { + * await access('/etc/passwd', constants.R_OK | constants.W_OK); + * console.log('can access'); + * } catch { + * console.error('cannot access'); + * } + * ``` + * + * Using `fsPromises.access()` to check for the accessibility of a file before + * calling `fsPromises.open()` is not recommended. Doing so introduces a race + * condition, since other processes may change the file's state between the two + * calls. Instead, user code should open/read/write the file directly and handle + * the error raised if the file is not accessible. + * @since v10.0.0 + * @param [mode=fs.constants.F_OK] + * @return Fulfills with `undefined` upon success. + */ + function access(path: PathLike, mode?: number): Promise; + /** + * Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it + * already exists. + * + * No guarantees are made about the atomicity of the copy operation. If an + * error occurs after the destination file has been opened for writing, an attempt + * will be made to remove the destination. + * + * ```js + * import { constants } from 'fs'; + * import { copyFile } from 'fs/promises'; + * + * try { + * await copyFile('source.txt', 'destination.txt'); + * console.log('source.txt was copied to destination.txt'); + * } catch { + * console.log('The file could not be copied'); + * } + * + * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. + * try { + * await copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL); + * console.log('source.txt was copied to destination.txt'); + * } catch { + * console.log('The file could not be copied'); + * } + * ``` + * @since v10.0.0 + * @param src source filename to copy + * @param dest destination filename of the copy operation + * @param [mode=0] Optional modifiers that specify the behavior of the copy operation. It is possible to create a mask consisting of the bitwise OR of two or more values (e.g. + * `fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`) + * @return Fulfills with `undefined` upon success. + */ + function copyFile(src: PathLike, dest: PathLike, mode?: number): Promise; + /** + * Opens a `FileHandle`. + * + * Refer to the POSIX [`open(2)`](http://man7.org/linux/man-pages/man2/open.2.html) documentation for more detail. + * + * Some characters (`< > : " / \ | ? *`) are reserved under Windows as documented + * by [Naming Files, Paths, and Namespaces](https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file). Under NTFS, if the filename contains + * a colon, Node.js will open a file system stream, as described by [this MSDN page](https://docs.microsoft.com/en-us/windows/desktop/FileIO/using-streams). + * @since v10.0.0 + * @param [flags='r'] See `support of file system `flags``. + * @param [mode=0o666] Sets the file mode (permission and sticky bits) if the file is created. + * @return Fulfills with a {FileHandle} object. + */ + function open(path: PathLike, flags?: string | number, mode?: Mode): Promise; + /** + * Renames `oldPath` to `newPath`. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function rename(oldPath: PathLike, newPath: PathLike): Promise; + /** + * Truncates (shortens or extends the length) of the content at `path` to `len`bytes. + * @since v10.0.0 + * @param [len=0] + * @return Fulfills with `undefined` upon success. + */ + function truncate(path: PathLike, len?: number): Promise; + /** + * Removes the directory identified by `path`. + * + * Using `fsPromises.rmdir()` on a file (not a directory) results in the + * promise being rejected with an `ENOENT` error on Windows and an `ENOTDIR`error on POSIX. + * + * To get a behavior similar to the `rm -rf` Unix command, use `fsPromises.rm()` with options `{ recursive: true, force: true }`. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function rmdir(path: PathLike, options?: RmDirOptions): Promise; + /** + * Removes files and directories (modeled on the standard POSIX `rm` utility). + * @since v14.14.0 + * @return Fulfills with `undefined` upon success. + */ + function rm(path: PathLike, options?: RmOptions): Promise; + /** + * Asynchronously creates a directory. + * + * The optional `options` argument can be an integer specifying `mode` (permission + * and sticky bits), or an object with a `mode` property and a `recursive`property indicating whether parent directories should be created. Calling`fsPromises.mkdir()` when `path` is a directory + * that exists results in a + * rejection only when `recursive` is false. + * @since v10.0.0 + * @return Upon success, fulfills with `undefined` if `recursive` is `false`, or the first directory path created if `recursive` is `true`. + */ + function mkdir( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + }, + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir( + path: PathLike, + options?: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null, + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir(path: PathLike, options?: Mode | MakeDirectoryOptions | null): Promise; + /** + * Reads the contents of a directory. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the filenames. If the `encoding` is set to `'buffer'`, the filenames returned + * will be passed as `Buffer` objects. + * + * If `options.withFileTypes` is set to `true`, the resolved array will contain `fs.Dirent` objects. + * + * ```js + * import { readdir } from 'fs/promises'; + * + * try { + * const files = await readdir(path); + * for (const file of files) + * console.log(file); + * } catch (err) { + * console.error(err); + * } + * ``` + * @since v10.0.0 + * @return Fulfills with an array of the names of the files in the directory excluding `'.'` and `'..'`. + */ + function readdir( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir( + path: PathLike, + options: + | { + encoding: "buffer"; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | "buffer", + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + function readdir( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Promise; + /** + * Reads the contents of the symbolic link referred to by `path`. See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more detail. The promise is + * resolved with the`linkString` upon success. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the link path returned. If the `encoding` is set to `'buffer'`, the link path + * returned will be passed as a `Buffer` object. + * @since v10.0.0 + * @return Fulfills with the `linkString` upon success. + */ + function readlink(path: PathLike, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options?: ObjectEncodingOptions | string | null): Promise; + /** + * Creates a symbolic link. + * + * The `type` argument is only used on Windows platforms and can be one of `'dir'`,`'file'`, or `'junction'`. Windows junction points require the destination path + * to be absolute. When using `'junction'`, the `target` argument will + * automatically be normalized to absolute path. + * @since v10.0.0 + * @param [type='file'] + * @return Fulfills with `undefined` upon success. + */ + function symlink(target: PathLike, path: PathLike, type?: string | null): Promise; + /** + * Equivalent to `fsPromises.stat()` unless `path` refers to a symbolic link, + * in which case the link itself is stat-ed, not the file that it refers to. + * Refer to the POSIX [`lstat(2)`](http://man7.org/linux/man-pages/man2/lstat.2.html) document for more detail. + * @since v10.0.0 + * @return Fulfills with the {fs.Stats} object for the given symbolic link `path`. + */ + function lstat( + path: PathLike, + opts?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + function lstat( + path: PathLike, + opts: StatOptions & { + bigint: true; + }, + ): Promise; + function lstat(path: PathLike, opts?: StatOptions): Promise; + /** + * @since v10.0.0 + * @return Fulfills with the {fs.Stats} object for the given `path`. + */ + function stat( + path: PathLike, + opts?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + function stat( + path: PathLike, + opts: StatOptions & { + bigint: true; + }, + ): Promise; + function stat(path: PathLike, opts?: StatOptions): Promise; + /** + * @since v18.15.0 + * @return Fulfills with an {fs.StatFs} for the file system. + */ + function statfs( + path: PathLike, + opts?: StatFsOptions & { + bigint?: false | undefined; + }, + ): Promise; + function statfs( + path: PathLike, + opts: StatFsOptions & { + bigint: true; + }, + ): Promise; + function statfs(path: PathLike, opts?: StatFsOptions): Promise; + + /** + * Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function link(existingPath: PathLike, newPath: PathLike): Promise; + /** + * If `path` refers to a symbolic link, then the link is removed without affecting + * the file or directory to which that link refers. If the `path` refers to a file + * path that is not a symbolic link, the file is deleted. See the POSIX [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html) documentation for more detail. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function unlink(path: PathLike): Promise; + /** + * Changes the permissions of a file. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function chmod(path: PathLike, mode: Mode): Promise; + /** + * Changes the permissions on a symbolic link. + * + * This method is only implemented on macOS. + * @deprecated Since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function lchmod(path: PathLike, mode: Mode): Promise; + /** + * Changes the ownership on a symbolic link. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function lchown(path: PathLike, uid: number, gid: number): Promise; + /** + * Changes the access and modification times of a file in the same way as `fsPromises.utimes()`, with the difference that if the path refers to a + * symbolic link, then the link is not dereferenced: instead, the timestamps of + * the symbolic link itself are changed. + * @since v14.5.0, v12.19.0 + * @return Fulfills with `undefined` upon success. + */ + function lutimes(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; + /** + * Changes the ownership of a file. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function chown(path: PathLike, uid: number, gid: number): Promise; + /** + * Change the file system timestamps of the object referenced by `path`. + * + * The `atime` and `mtime` arguments follow these rules: + * + * * Values can be either numbers representing Unix epoch time, `Date`s, or a + * numeric string like `'123456789.0'`. + * * If the value can not be converted to a number, or is `NaN`, `Infinity` or`-Infinity`, an `Error` will be thrown. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function utimes(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; + /** + * Determines the actual location of `path` using the same semantics as the`fs.realpath.native()` function. + * + * Only paths that can be converted to UTF8 strings are supported. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the path. If the `encoding` is set to `'buffer'`, the path returned will be + * passed as a `Buffer` object. + * + * On Linux, when Node.js is linked against musl libc, the procfs file system must + * be mounted on `/proc` in order for this function to work. Glibc does not have + * this restriction. + * @since v10.0.0 + * @return Fulfills with the resolved path upon success. + */ + function realpath(path: PathLike, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath( + path: PathLike, + options?: ObjectEncodingOptions | BufferEncoding | null, + ): Promise; + /** + * Creates a unique temporary directory. A unique directory name is generated by + * appending six random characters to the end of the provided `prefix`. Due to + * platform inconsistencies, avoid trailing `X` characters in `prefix`. Some + * platforms, notably the BSDs, can return more than six random characters, and + * replace trailing `X` characters in `prefix` with random characters. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use. + * + * ```js + * import { mkdtemp } from 'fs/promises'; + * + * try { + * await mkdtemp(path.join(os.tmpdir(), 'foo-')); + * } catch (err) { + * console.error(err); + * } + * ``` + * + * The `fsPromises.mkdtemp()` method will append the six randomly selected + * characters directly to the `prefix` string. For instance, given a directory`/tmp`, if the intention is to create a temporary directory _within_`/tmp`, the`prefix` must end with a trailing + * platform-specific path separator + * (`require('path').sep`). + * @since v10.0.0 + * @return Fulfills with a string containing the filesystem path of the newly created temporary directory. + */ + function mkdtemp(prefix: string, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options: BufferEncodingOption): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronously writes data to a file, replacing the file if it already exists.`data` can be a string, a buffer, an + * [AsyncIterable](https://tc39.github.io/ecma262/#sec-asynciterable-interface) or + * [Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) object. + * + * The `encoding` option is ignored if `data` is a buffer. + * + * If `options` is a string, then it specifies the encoding. + * + * The `mode` option only affects the newly created file. See `fs.open()` for more details. + * + * Any specified `FileHandle` has to support writing. + * + * It is unsafe to use `fsPromises.writeFile()` multiple times on the same file + * without waiting for the promise to be settled. + * + * Similarly to `fsPromises.readFile` \- `fsPromises.writeFile` is a convenience + * method that performs multiple `write` calls internally to write the buffer + * passed to it. For performance sensitive code consider using `fs.createWriteStream()` or `filehandle.createWriteStream()`. + * + * It is possible to use an `AbortSignal` to cancel an `fsPromises.writeFile()`. + * Cancelation is "best effort", and some amount of data is likely still + * to be written. + * + * ```js + * import { writeFile } from 'fs/promises'; + * import { Buffer } from 'buffer'; + * + * try { + * const controller = new AbortController(); + * const { signal } = controller; + * const data = new Uint8Array(Buffer.from('Hello Node.js')); + * const promise = writeFile('message.txt', data, { signal }); + * + * // Abort the request before the promise settles. + * controller.abort(); + * + * await promise; + * } catch (err) { + * // When a request is aborted - err is an AbortError + * console.error(err); + * } + * ``` + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.writeFile` performs. + * @since v10.0.0 + * @param file filename or `FileHandle` + * @return Fulfills with `undefined` upon success. + */ + function writeFile( + file: PathLike | FileHandle, + data: + | string + | NodeJS.ArrayBufferView + | Iterable + | AsyncIterable + | Stream, + options?: + | (ObjectEncodingOptions & { + mode?: Mode | undefined; + flag?: OpenMode | undefined; + } & Abortable) + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronously append data to a file, creating the file if it does not yet + * exist. `data` can be a string or a `Buffer`. + * + * If `options` is a string, then it specifies the `encoding`. + * + * The `mode` option only affects the newly created file. See `fs.open()` for more details. + * + * The `path` may be specified as a `FileHandle` that has been opened + * for appending (using `fsPromises.open()`). + * @since v10.0.0 + * @param path filename or {FileHandle} + * @return Fulfills with `undefined` upon success. + */ + function appendFile( + path: PathLike | FileHandle, + data: string | Uint8Array, + options?: (ObjectEncodingOptions & FlagAndOpenMode) | BufferEncoding | null, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * + * If no encoding is specified (using `options.encoding`), the data is returned + * as a `Buffer` object. Otherwise, the data will be a string. + * + * If `options` is a string, then it specifies the encoding. + * + * When the `path` is a directory, the behavior of `fsPromises.readFile()` is + * platform-specific. On macOS, Linux, and Windows, the promise will be rejected + * with an error. On FreeBSD, a representation of the directory's contents will be + * returned. + * + * It is possible to abort an ongoing `readFile` using an `AbortSignal`. If a + * request is aborted the promise returned is rejected with an `AbortError`: + * + * ```js + * import { readFile } from 'fs/promises'; + * + * try { + * const controller = new AbortController(); + * const { signal } = controller; + * const promise = readFile(fileName, { signal }); + * + * // Abort the request before the promise settles. + * controller.abort(); + * + * await promise; + * } catch (err) { + * // When a request is aborted - err is an AbortError + * console.error(err); + * } + * ``` + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.readFile` performs. + * + * Any specified `FileHandle` has to support reading. + * @since v10.0.0 + * @param path filename or `FileHandle` + * @return Fulfills with the contents of the file. + */ + function readFile( + path: PathLike | FileHandle, + options?: + | ({ + encoding?: null | undefined; + flag?: OpenMode | undefined; + } & Abortable) + | null, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile( + path: PathLike | FileHandle, + options: + | ({ + encoding: BufferEncoding; + flag?: OpenMode | undefined; + } & Abortable) + | BufferEncoding, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile( + path: PathLike | FileHandle, + options?: + | ( + & ObjectEncodingOptions + & Abortable + & { + flag?: OpenMode | undefined; + } + ) + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronously open a directory for iterative scanning. See the POSIX [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html) documentation for more detail. + * + * Creates an `fs.Dir`, which contains all further functions for reading from + * and cleaning up the directory. + * + * The `encoding` option sets the encoding for the `path` while opening the + * directory and subsequent read operations. + * + * Example using async iteration: + * + * ```js + * import { opendir } from 'fs/promises'; + * + * try { + * const dir = await opendir('./'); + * for await (const dirent of dir) + * console.log(dirent.name); + * } catch (err) { + * console.error(err); + * } + * ``` + * + * When using the async iterator, the `fs.Dir` object will be automatically + * closed after the iterator exits. + * @since v12.12.0 + * @return Fulfills with an {fs.Dir}. + */ + function opendir(path: PathLike, options?: OpenDirOptions): Promise; + /** + * Returns an async iterator that watches for changes on `filename`, where `filename`is either a file or a directory. + * + * ```js + * const { watch } = require('fs/promises'); + * + * const ac = new AbortController(); + * const { signal } = ac; + * setTimeout(() => ac.abort(), 10000); + * + * (async () => { + * try { + * const watcher = watch(__filename, { signal }); + * for await (const event of watcher) + * console.log(event); + * } catch (err) { + * if (err.name === 'AbortError') + * return; + * throw err; + * } + * })(); + * ``` + * + * On most platforms, `'rename'` is emitted whenever a filename appears or + * disappears in the directory. + * + * All the `caveats` for `fs.watch()` also apply to `fsPromises.watch()`. + * @since v15.9.0, v14.18.0 + * @return of objects with the properties: + */ + function watch( + filename: PathLike, + options: + | (WatchOptions & { + encoding: "buffer"; + }) + | "buffer", + ): AsyncIterable>; + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + function watch(filename: PathLike, options?: WatchOptions | BufferEncoding): AsyncIterable>; + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + function watch( + filename: PathLike, + options: WatchOptions | string, + ): AsyncIterable> | AsyncIterable>; + /** + * Asynchronously copies the entire directory structure from `src` to `dest`, + * including subdirectories and files. + * + * When copying a directory to another directory, globs are not supported and + * behavior is similar to `cp dir1/ dir2/`. + * @since v16.7.0 + * @experimental + * @param src source path to copy. + * @param dest destination path to copy to. + * @return Fulfills with `undefined` upon success. + */ + function cp(source: string | URL, destination: string | URL, opts?: CopyOptions): Promise; +} +declare module "node:fs/promises" { + export * from "fs/promises"; +} diff --git a/backend/node_modules/@types/node/globals.d.ts b/backend/node_modules/@types/node/globals.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f6c95e9f266c69bb79671f8f76497563b00f3ecd --- /dev/null +++ b/backend/node_modules/@types/node/globals.d.ts @@ -0,0 +1,377 @@ +export {}; // Make this a module + +// #region Fetch and friends +// Conditional type aliases, used at the end of this file. +// Will either be empty if lib-dom is included, or the undici version otherwise. +type _Request = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").Request; +type _Response = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").Response; +type _FormData = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").FormData; +type _Headers = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").Headers; +type _RequestInit = typeof globalThis extends { onmessage: any } ? {} + : import("undici-types").RequestInit; +type _ResponseInit = typeof globalThis extends { onmessage: any } ? {} + : import("undici-types").ResponseInit; +// #endregion Fetch and friends + +declare global { + // Declare "static" methods in Error + interface ErrorConstructor { + /** Create .stack property on a target object */ + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + + /** + * Optional override for formatting stack traces + * + * @see https://v8.dev/docs/stack-trace-api#customizing-stack-traces + */ + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + + stackTraceLimit: number; + } + + /*-----------------------------------------------* + * * + * GLOBAL * + * * + ------------------------------------------------*/ + + // For backwards compability + interface NodeRequire extends NodeJS.Require {} + interface RequireResolve extends NodeJS.RequireResolve {} + interface NodeModule extends NodeJS.Module {} + + var process: NodeJS.Process; + var console: Console; + + var __filename: string; + var __dirname: string; + + var require: NodeRequire; + var module: NodeModule; + + // Same as module.exports + var exports: any; + + /** + * Only available if `--expose-gc` is passed to the process. + */ + var gc: undefined | (() => void); + + // #region borrowed + // from https://github.com/microsoft/TypeScript/blob/38da7c600c83e7b31193a62495239a0fe478cb67/lib/lib.webworker.d.ts#L633 until moved to separate lib + /** A controller object that allows you to abort one or more DOM requests as and when desired. */ + interface AbortController { + /** + * Returns the AbortSignal object associated with this object. + */ + + readonly signal: AbortSignal; + /** + * Invoking this method will set this object's AbortSignal's aborted flag and signal to any observers that the associated activity is to be aborted. + */ + abort(reason?: any): void; + } + + /** A signal object that allows you to communicate with a DOM request (such as a Fetch) and abort it if required via an AbortController object. */ + interface AbortSignal extends EventTarget { + /** + * Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise. + */ + readonly aborted: boolean; + readonly reason: any; + onabort: null | ((this: AbortSignal, event: Event) => any); + throwIfAborted(): void; + } + + var AbortController: typeof globalThis extends { onmessage: any; AbortController: infer T } ? T + : { + prototype: AbortController; + new(): AbortController; + }; + + var AbortSignal: typeof globalThis extends { onmessage: any; AbortSignal: infer T } ? T + : { + prototype: AbortSignal; + new(): AbortSignal; + abort(reason?: any): AbortSignal; + timeout(milliseconds: number): AbortSignal; + }; + // #endregion borrowed + + // #region Disposable + interface SymbolConstructor { + /** + * A method that is used to release resources held by an object. Called by the semantics of the `using` statement. + */ + readonly dispose: unique symbol; + + /** + * A method that is used to asynchronously release resources held by an object. Called by the semantics of the `await using` statement. + */ + readonly asyncDispose: unique symbol; + } + + interface Disposable { + [Symbol.dispose](): void; + } + + interface AsyncDisposable { + [Symbol.asyncDispose](): PromiseLike; + } + // #endregion Disposable + + // #region ArrayLike.at() + interface RelativeIndexable { + /** + * Takes an integer value and returns the item at that index, + * allowing for positive and negative integers. + * Negative integers count back from the last item in the array. + */ + at(index: number): T | undefined; + } + interface String extends RelativeIndexable {} + interface Array extends RelativeIndexable {} + interface ReadonlyArray extends RelativeIndexable {} + interface Int8Array extends RelativeIndexable {} + interface Uint8Array extends RelativeIndexable {} + interface Uint8ClampedArray extends RelativeIndexable {} + interface Int16Array extends RelativeIndexable {} + interface Uint16Array extends RelativeIndexable {} + interface Int32Array extends RelativeIndexable {} + interface Uint32Array extends RelativeIndexable {} + interface Float32Array extends RelativeIndexable {} + interface Float64Array extends RelativeIndexable {} + interface BigInt64Array extends RelativeIndexable {} + interface BigUint64Array extends RelativeIndexable {} + // #endregion ArrayLike.at() end + + /** + * @since v17.0.0 + * + * Creates a deep clone of an object. + */ + function structuredClone( + value: T, + transfer?: { transfer: ReadonlyArray }, + ): T; + + /*----------------------------------------------* + * * + * GLOBAL INTERFACES * + * * + *-----------------------------------------------*/ + namespace NodeJS { + interface CallSite { + /** + * Value of "this" + */ + getThis(): unknown; + + /** + * Type of "this" as a string. + * This is the name of the function stored in the constructor field of + * "this", if available. Otherwise the object's [[Class]] internal + * property. + */ + getTypeName(): string | null; + + /** + * Current function + */ + getFunction(): Function | undefined; + + /** + * Name of the current function, typically its name property. + * If a name property is not available an attempt will be made to try + * to infer a name from the function's context. + */ + getFunctionName(): string | null; + + /** + * Name of the property [of "this" or one of its prototypes] that holds + * the current function + */ + getMethodName(): string | null; + + /** + * Name of the script [if this function was defined in a script] + */ + getFileName(): string | undefined; + + /** + * Current line number [if this function was defined in a script] + */ + getLineNumber(): number | null; + + /** + * Current column number [if this function was defined in a script] + */ + getColumnNumber(): number | null; + + /** + * A call site object representing the location where eval was called + * [if this function was created using a call to eval] + */ + getEvalOrigin(): string | undefined; + + /** + * Is this a toplevel invocation, that is, is "this" the global object? + */ + isToplevel(): boolean; + + /** + * Does this call take place in code defined by a call to eval? + */ + isEval(): boolean; + + /** + * Is this call in native V8 code? + */ + isNative(): boolean; + + /** + * Is this a constructor call? + */ + isConstructor(): boolean; + } + + interface ErrnoException extends Error { + errno?: number | undefined; + code?: string | undefined; + path?: string | undefined; + syscall?: string | undefined; + } + + interface ReadableStream extends EventEmitter { + readable: boolean; + read(size?: number): string | Buffer; + setEncoding(encoding: BufferEncoding): this; + pause(): this; + resume(): this; + isPaused(): boolean; + pipe(destination: T, options?: { end?: boolean | undefined }): T; + unpipe(destination?: WritableStream): this; + unshift(chunk: string | Uint8Array, encoding?: BufferEncoding): void; + wrap(oldStream: ReadableStream): this; + [Symbol.asyncIterator](): AsyncIterableIterator; + } + + interface WritableStream extends EventEmitter { + writable: boolean; + write(buffer: Uint8Array | string, cb?: (err?: Error | null) => void): boolean; + write(str: string, encoding?: BufferEncoding, cb?: (err?: Error | null) => void): boolean; + end(cb?: () => void): this; + end(data: string | Uint8Array, cb?: () => void): this; + end(str: string, encoding?: BufferEncoding, cb?: () => void): this; + } + + interface ReadWriteStream extends ReadableStream, WritableStream {} + + interface RefCounted { + ref(): this; + unref(): this; + } + + type TypedArray = + | Uint8Array + | Uint8ClampedArray + | Uint16Array + | Uint32Array + | Int8Array + | Int16Array + | Int32Array + | BigUint64Array + | BigInt64Array + | Float32Array + | Float64Array; + type ArrayBufferView = TypedArray | DataView; + + interface Require { + (id: string): any; + resolve: RequireResolve; + cache: Dict; + /** + * @deprecated + */ + extensions: RequireExtensions; + main: Module | undefined; + } + + interface RequireResolve { + (id: string, options?: { paths?: string[] | undefined }): string; + paths(request: string): string[] | null; + } + + interface RequireExtensions extends Dict<(m: Module, filename: string) => any> { + ".js": (m: Module, filename: string) => any; + ".json": (m: Module, filename: string) => any; + ".node": (m: Module, filename: string) => any; + } + interface Module { + /** + * `true` if the module is running during the Node.js preload + */ + isPreloading: boolean; + exports: any; + require: Require; + id: string; + filename: string; + loaded: boolean; + /** @deprecated since v14.6.0 Please use `require.main` and `module.children` instead. */ + parent: Module | null | undefined; + children: Module[]; + /** + * @since v11.14.0 + * + * The directory name of the module. This is usually the same as the path.dirname() of the module.id. + */ + path: string; + paths: string[]; + } + + interface Dict { + [key: string]: T | undefined; + } + + interface ReadOnlyDict { + readonly [key: string]: T | undefined; + } + } + + interface RequestInit extends _RequestInit {} + + function fetch( + input: string | URL | Request, + init?: RequestInit, + ): Promise; + + interface Request extends _Request {} + var Request: typeof globalThis extends { + onmessage: any; + Request: infer T; + } ? T + : typeof import("undici-types").Request; + + interface ResponseInit extends _ResponseInit {} + + interface Response extends _Response {} + var Response: typeof globalThis extends { + onmessage: any; + Response: infer T; + } ? T + : typeof import("undici-types").Response; + + interface FormData extends _FormData {} + var FormData: typeof globalThis extends { + onmessage: any; + FormData: infer T; + } ? T + : typeof import("undici-types").FormData; + + interface Headers extends _Headers {} + var Headers: typeof globalThis extends { + onmessage: any; + Headers: infer T; + } ? T + : typeof import("undici-types").Headers; +} diff --git a/backend/node_modules/@types/node/globals.global.d.ts b/backend/node_modules/@types/node/globals.global.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ef1198c05024940c44e3c1a6429c26091fe2a94f --- /dev/null +++ b/backend/node_modules/@types/node/globals.global.d.ts @@ -0,0 +1 @@ +declare var global: typeof globalThis; diff --git a/backend/node_modules/@types/node/http.d.ts b/backend/node_modules/@types/node/http.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cc49f23274a62da7e5ab13010e8dd78489364167 --- /dev/null +++ b/backend/node_modules/@types/node/http.d.ts @@ -0,0 +1,1803 @@ +/** + * To use the HTTP server and client one must `require('http')`. + * + * The HTTP interfaces in Node.js are designed to support many features + * of the protocol which have been traditionally difficult to use. + * In particular, large, possibly chunk-encoded, messages. The interface is + * careful to never buffer entire requests or responses, so the + * user is able to stream data. + * + * HTTP message headers are represented by an object like this: + * + * ```js + * { 'content-length': '123', + * 'content-type': 'text/plain', + * 'connection': 'keep-alive', + * 'host': 'example.com', + * 'accept': '*' } + * ``` + * + * Keys are lowercased. Values are not modified. + * + * In order to support the full spectrum of possible HTTP applications, the Node.js + * HTTP API is very low-level. It deals with stream handling and message + * parsing only. It parses a message into headers and body but it does not + * parse the actual headers or the body. + * + * See `message.headers` for details on how duplicate headers are handled. + * + * The raw headers as they were received are retained in the `rawHeaders`property, which is an array of `[key, value, key2, value2, ...]`. For + * example, the previous message header object might have a `rawHeaders`list like the following: + * + * ```js + * [ 'ConTent-Length', '123456', + * 'content-LENGTH', '123', + * 'content-type', 'text/plain', + * 'CONNECTION', 'keep-alive', + * 'Host', 'example.com', + * 'accepT', '*' ] + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/http.js) + */ +declare module "http" { + import * as stream from "node:stream"; + import { URL } from "node:url"; + import { EventEmitter } from "node:events"; + import { LookupOptions } from "node:dns"; + import { LookupFunction, Server as NetServer, Socket, TcpSocketConnectOpts } from "node:net"; + // incoming headers will never contain number + interface IncomingHttpHeaders extends NodeJS.Dict { + accept?: string | undefined; + "accept-language"?: string | undefined; + "accept-patch"?: string | undefined; + "accept-ranges"?: string | undefined; + "access-control-allow-credentials"?: string | undefined; + "access-control-allow-headers"?: string | undefined; + "access-control-allow-methods"?: string | undefined; + "access-control-allow-origin"?: string | undefined; + "access-control-expose-headers"?: string | undefined; + "access-control-max-age"?: string | undefined; + "access-control-request-headers"?: string | undefined; + "access-control-request-method"?: string | undefined; + age?: string | undefined; + allow?: string | undefined; + "alt-svc"?: string | undefined; + authorization?: string | undefined; + "cache-control"?: string | undefined; + connection?: string | undefined; + "content-disposition"?: string | undefined; + "content-encoding"?: string | undefined; + "content-language"?: string | undefined; + "content-length"?: string | undefined; + "content-location"?: string | undefined; + "content-range"?: string | undefined; + "content-type"?: string | undefined; + cookie?: string | undefined; + date?: string | undefined; + etag?: string | undefined; + expect?: string | undefined; + expires?: string | undefined; + forwarded?: string | undefined; + from?: string | undefined; + host?: string | undefined; + "if-match"?: string | undefined; + "if-modified-since"?: string | undefined; + "if-none-match"?: string | undefined; + "if-unmodified-since"?: string | undefined; + "last-modified"?: string | undefined; + location?: string | undefined; + origin?: string | undefined; + pragma?: string | undefined; + "proxy-authenticate"?: string | undefined; + "proxy-authorization"?: string | undefined; + "public-key-pins"?: string | undefined; + range?: string | undefined; + referer?: string | undefined; + "retry-after"?: string | undefined; + "sec-websocket-accept"?: string | undefined; + "sec-websocket-extensions"?: string | undefined; + "sec-websocket-key"?: string | undefined; + "sec-websocket-protocol"?: string | undefined; + "sec-websocket-version"?: string | undefined; + "set-cookie"?: string[] | undefined; + "strict-transport-security"?: string | undefined; + tk?: string | undefined; + trailer?: string | undefined; + "transfer-encoding"?: string | undefined; + upgrade?: string | undefined; + "user-agent"?: string | undefined; + vary?: string | undefined; + via?: string | undefined; + warning?: string | undefined; + "www-authenticate"?: string | undefined; + } + // outgoing headers allows numbers (as they are converted internally to strings) + type OutgoingHttpHeader = number | string | string[]; + interface OutgoingHttpHeaders extends NodeJS.Dict { + accept?: string | string[] | undefined; + "accept-charset"?: string | string[] | undefined; + "accept-encoding"?: string | string[] | undefined; + "accept-language"?: string | string[] | undefined; + "accept-ranges"?: string | undefined; + "access-control-allow-credentials"?: string | undefined; + "access-control-allow-headers"?: string | undefined; + "access-control-allow-methods"?: string | undefined; + "access-control-allow-origin"?: string | undefined; + "access-control-expose-headers"?: string | undefined; + "access-control-max-age"?: string | undefined; + "access-control-request-headers"?: string | undefined; + "access-control-request-method"?: string | undefined; + age?: string | undefined; + allow?: string | undefined; + authorization?: string | undefined; + "cache-control"?: string | undefined; + "cdn-cache-control"?: string | undefined; + connection?: string | string[] | undefined; + "content-disposition"?: string | undefined; + "content-encoding"?: string | undefined; + "content-language"?: string | undefined; + "content-length"?: string | number | undefined; + "content-location"?: string | undefined; + "content-range"?: string | undefined; + "content-security-policy"?: string | undefined; + "content-security-policy-report-only"?: string | undefined; + cookie?: string | string[] | undefined; + dav?: string | string[] | undefined; + dnt?: string | undefined; + date?: string | undefined; + etag?: string | undefined; + expect?: string | undefined; + expires?: string | undefined; + forwarded?: string | undefined; + from?: string | undefined; + host?: string | undefined; + "if-match"?: string | undefined; + "if-modified-since"?: string | undefined; + "if-none-match"?: string | undefined; + "if-range"?: string | undefined; + "if-unmodified-since"?: string | undefined; + "last-modified"?: string | undefined; + link?: string | string[] | undefined; + location?: string | undefined; + "max-forwards"?: string | undefined; + origin?: string | undefined; + prgama?: string | string[] | undefined; + "proxy-authenticate"?: string | string[] | undefined; + "proxy-authorization"?: string | undefined; + "public-key-pins"?: string | undefined; + "public-key-pins-report-only"?: string | undefined; + range?: string | undefined; + referer?: string | undefined; + "referrer-policy"?: string | undefined; + refresh?: string | undefined; + "retry-after"?: string | undefined; + "sec-websocket-accept"?: string | undefined; + "sec-websocket-extensions"?: string | string[] | undefined; + "sec-websocket-key"?: string | undefined; + "sec-websocket-protocol"?: string | string[] | undefined; + "sec-websocket-version"?: string | undefined; + server?: string | undefined; + "set-cookie"?: string | string[] | undefined; + "strict-transport-security"?: string | undefined; + te?: string | undefined; + trailer?: string | undefined; + "transfer-encoding"?: string | undefined; + "user-agent"?: string | undefined; + upgrade?: string | undefined; + "upgrade-insecure-requests"?: string | undefined; + vary?: string | undefined; + via?: string | string[] | undefined; + warning?: string | undefined; + "www-authenticate"?: string | string[] | undefined; + "x-content-type-options"?: string | undefined; + "x-dns-prefetch-control"?: string | undefined; + "x-frame-options"?: string | undefined; + "x-xss-protection"?: string | undefined; + } + interface ClientRequestArgs { + _defaultAgent?: Agent | undefined; + agent?: Agent | boolean | undefined; + auth?: string | null | undefined; + createConnection?: + | (( + options: ClientRequestArgs, + oncreate: (err: Error | null, socket: stream.Duplex) => void, + ) => stream.Duplex | null | undefined) + | undefined; + defaultPort?: number | string | undefined; + family?: number | undefined; + headers?: OutgoingHttpHeaders | undefined; + hints?: LookupOptions["hints"]; + host?: string | null | undefined; + hostname?: string | null | undefined; + insecureHTTPParser?: boolean | undefined; + localAddress?: string | undefined; + localPort?: number | undefined; + lookup?: LookupFunction | undefined; + /** + * @default 16384 + */ + maxHeaderSize?: number | undefined; + method?: string | undefined; + path?: string | null | undefined; + port?: number | string | null | undefined; + protocol?: string | null | undefined; + setHost?: boolean | undefined; + signal?: AbortSignal | undefined; + socketPath?: string | undefined; + timeout?: number | undefined; + uniqueHeaders?: Array | undefined; + joinDuplicateHeaders?: boolean; + } + interface ServerOptions< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse = typeof ServerResponse, + > { + /** + * Specifies the `IncomingMessage` class to be used. Useful for extending the original `IncomingMessage`. + */ + IncomingMessage?: Request | undefined; + /** + * Specifies the `ServerResponse` class to be used. Useful for extending the original `ServerResponse`. + */ + ServerResponse?: Response | undefined; + /** + * Sets the timeout value in milliseconds for receiving the entire request from the client. + * @see Server.requestTimeout for more information. + * @default 300000 + * @since v18.0.0 + */ + requestTimeout?: number | undefined; + /** + * It joins the field line values of multiple headers in a request with `, ` instead of discarding the duplicates. + * @default false + * @since v18.14.0 + */ + joinDuplicateHeaders?: boolean; + /** + * The number of milliseconds of inactivity a server needs to wait for additional incoming data, + * after it has finished writing the last response, before a socket will be destroyed. + * @see Server.keepAliveTimeout for more information. + * @default 5000 + * @since v18.0.0 + */ + keepAliveTimeout?: number | undefined; + /** + * Sets the interval value in milliseconds to check for request and headers timeout in incomplete requests. + * @default 30000 + */ + connectionsCheckingInterval?: number | undefined; + /** + * Optionally overrides all `socket`s' `readableHighWaterMark` and `writableHighWaterMark`. + * This affects `highWaterMark` property of both `IncomingMessage` and `ServerResponse`. + * Default: @see stream.getDefaultHighWaterMark(). + * @since v18.17.0 + */ + highWaterMark?: number | undefined; + /** + * Use an insecure HTTP parser that accepts invalid HTTP headers when `true`. + * Using the insecure parser should be avoided. + * See --insecure-http-parser for more information. + * @default false + */ + insecureHTTPParser?: boolean | undefined; + /** + * Optionally overrides the value of + * `--max-http-header-size` for requests received by this server, i.e. + * the maximum length of request headers in bytes. + * @default 16384 + * @since v13.3.0 + */ + maxHeaderSize?: number | undefined; + /** + * If set to `true`, it disables the use of Nagle's algorithm immediately after a new incoming connection is received. + * @default true + * @since v16.5.0 + */ + noDelay?: boolean | undefined; + /** + * If set to `true`, it enables keep-alive functionality on the socket immediately after a new incoming connection is received, + * similarly on what is done in `socket.setKeepAlive([enable][, initialDelay])`. + * @default false + * @since v16.5.0 + */ + keepAlive?: boolean | undefined; + /** + * If set to a positive number, it sets the initial delay before the first keepalive probe is sent on an idle socket. + * @default 0 + * @since v16.5.0 + */ + keepAliveInitialDelay?: number | undefined; + /** + * A list of response headers that should be sent only once. + * If the header's value is an array, the items will be joined using `; `. + */ + uniqueHeaders?: Array | undefined; + } + type RequestListener< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse = typeof ServerResponse, + > = (req: InstanceType, res: InstanceType & { req: InstanceType }) => void; + /** + * @since v0.1.17 + */ + class Server< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse = typeof ServerResponse, + > extends NetServer { + constructor(requestListener?: RequestListener); + constructor(options: ServerOptions, requestListener?: RequestListener); + /** + * Sets the timeout value for sockets, and emits a `'timeout'` event on + * the Server object, passing the socket as an argument, if a timeout + * occurs. + * + * If there is a `'timeout'` event listener on the Server object, then it + * will be called with the timed-out socket as an argument. + * + * By default, the Server does not timeout sockets. However, if a callback + * is assigned to the Server's `'timeout'` event, timeouts must be handled + * explicitly. + * @since v0.9.12 + * @param [msecs=0 (no timeout)] + */ + setTimeout(msecs?: number, callback?: () => void): this; + setTimeout(callback: () => void): this; + /** + * Limits maximum incoming headers count. If set to 0, no limit will be applied. + * @since v0.7.0 + */ + maxHeadersCount: number | null; + /** + * The maximum number of requests socket can handle + * before closing keep alive connection. + * + * A value of `0` will disable the limit. + * + * When the limit is reached it will set the `Connection` header value to `close`, + * but will not actually close the connection, subsequent requests sent + * after the limit is reached will get `503 Service Unavailable` as a response. + * @since v16.10.0 + */ + maxRequestsPerSocket: number | null; + /** + * The number of milliseconds of inactivity before a socket is presumed + * to have timed out. + * + * A value of `0` will disable the timeout behavior on incoming connections. + * + * The socket timeout logic is set up on connection, so changing this + * value only affects new connections to the server, not any existing connections. + * @since v0.9.12 + */ + timeout: number; + /** + * Limit the amount of time the parser will wait to receive the complete HTTP + * headers. + * + * If the timeout expires, the server responds with status 408 without + * forwarding the request to the request listener and then closes the connection. + * + * It must be set to a non-zero value (e.g. 120 seconds) to protect against + * potential Denial-of-Service attacks in case the server is deployed without a + * reverse proxy in front. + * @since v11.3.0, v10.14.0 + */ + headersTimeout: number; + /** + * The number of milliseconds of inactivity a server needs to wait for additional + * incoming data, after it has finished writing the last response, before a socket + * will be destroyed. If the server receives new data before the keep-alive + * timeout has fired, it will reset the regular inactivity timeout, i.e.,`server.timeout`. + * + * A value of `0` will disable the keep-alive timeout behavior on incoming + * connections. + * A value of `0` makes the http server behave similarly to Node.js versions prior + * to 8.0.0, which did not have a keep-alive timeout. + * + * The socket timeout logic is set up on connection, so changing this value only + * affects new connections to the server, not any existing connections. + * @since v8.0.0 + */ + keepAliveTimeout: number; + /** + * Sets the timeout value in milliseconds for receiving the entire request from + * the client. + * + * If the timeout expires, the server responds with status 408 without + * forwarding the request to the request listener and then closes the connection. + * + * It must be set to a non-zero value (e.g. 120 seconds) to protect against + * potential Denial-of-Service attacks in case the server is deployed without a + * reverse proxy in front. + * @since v14.11.0 + */ + requestTimeout: number; + /** + * Closes all connections connected to this server. + * @since v18.2.0 + */ + closeAllConnections(): void; + /** + * Closes all connections connected to this server which are not sending a request or waiting for a response. + * @since v18.2.0 + */ + closeIdleConnections(): void; + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "connection", listener: (socket: Socket) => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + addListener(event: "checkContinue", listener: RequestListener): this; + addListener(event: "checkExpectation", listener: RequestListener): this; + addListener(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; + addListener( + event: "connect", + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + addListener(event: "dropRequest", listener: (req: InstanceType, socket: stream.Duplex) => void): this; + addListener(event: "request", listener: RequestListener): this; + addListener( + event: "upgrade", + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + emit(event: string, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "connection", socket: Socket): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + emit( + event: "checkContinue", + req: InstanceType, + res: InstanceType & { req: InstanceType }, + ): boolean; + emit( + event: "checkExpectation", + req: InstanceType, + res: InstanceType & { req: InstanceType }, + ): boolean; + emit(event: "clientError", err: Error, socket: stream.Duplex): boolean; + emit(event: "connect", req: InstanceType, socket: stream.Duplex, head: Buffer): boolean; + emit(event: "dropRequest", req: InstanceType, socket: stream.Duplex): boolean; + emit( + event: "request", + req: InstanceType, + res: InstanceType & { req: InstanceType }, + ): boolean; + emit(event: "upgrade", req: InstanceType, socket: stream.Duplex, head: Buffer): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "connection", listener: (socket: Socket) => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + on(event: "checkContinue", listener: RequestListener): this; + on(event: "checkExpectation", listener: RequestListener): this; + on(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; + on(event: "connect", listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void): this; + on(event: "dropRequest", listener: (req: InstanceType, socket: stream.Duplex) => void): this; + on(event: "request", listener: RequestListener): this; + on(event: "upgrade", listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "connection", listener: (socket: Socket) => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + once(event: "checkContinue", listener: RequestListener): this; + once(event: "checkExpectation", listener: RequestListener): this; + once(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; + once( + event: "connect", + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + once(event: "dropRequest", listener: (req: InstanceType, socket: stream.Duplex) => void): this; + once(event: "request", listener: RequestListener): this; + once( + event: "upgrade", + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "connection", listener: (socket: Socket) => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + prependListener(event: "checkContinue", listener: RequestListener): this; + prependListener(event: "checkExpectation", listener: RequestListener): this; + prependListener(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; + prependListener( + event: "connect", + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + prependListener( + event: "dropRequest", + listener: (req: InstanceType, socket: stream.Duplex) => void, + ): this; + prependListener(event: "request", listener: RequestListener): this; + prependListener( + event: "upgrade", + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "connection", listener: (socket: Socket) => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + prependOnceListener(event: "checkContinue", listener: RequestListener): this; + prependOnceListener(event: "checkExpectation", listener: RequestListener): this; + prependOnceListener(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; + prependOnceListener( + event: "connect", + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + prependOnceListener( + event: "dropRequest", + listener: (req: InstanceType, socket: stream.Duplex) => void, + ): this; + prependOnceListener(event: "request", listener: RequestListener): this; + prependOnceListener( + event: "upgrade", + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + } + /** + * This class serves as the parent class of {@link ClientRequest} and {@link ServerResponse}. It is an abstract of outgoing message from + * the perspective of the participants of HTTP transaction. + * @since v0.1.17 + */ + class OutgoingMessage extends stream.Writable { + readonly req: Request; + chunkedEncoding: boolean; + shouldKeepAlive: boolean; + useChunkedEncodingByDefault: boolean; + sendDate: boolean; + /** + * @deprecated Use `writableEnded` instead. + */ + finished: boolean; + /** + * Read-only. `true` if the headers were sent, otherwise `false`. + * @since v0.9.3 + */ + readonly headersSent: boolean; + /** + * Aliases of `outgoingMessage.socket` + * @since v0.3.0 + * @deprecated Since v15.12.0,v14.17.1 - Use `socket` instead. + */ + readonly connection: Socket | null; + /** + * Reference to the underlying socket. Usually, users will not want to access + * this property. + * + * After calling `outgoingMessage.end()`, this property will be nulled. + * @since v0.3.0 + */ + readonly socket: Socket | null; + constructor(); + /** + * Once a socket is associated with the message and is connected,`socket.setTimeout()` will be called with `msecs` as the first parameter. + * @since v0.9.12 + * @param callback Optional function to be called when a timeout occurs. Same as binding to the `timeout` event. + */ + setTimeout(msecs: number, callback?: () => void): this; + /** + * Sets a single header value for the header object. + * If the header already exists in the to-be-sent headers, its value will be replaced. Use an array of strings to send multiple headers with the same name. + * @since v0.4.0 + * @param name Header name + * @param value Header value + */ + setHeader(name: string, value: number | string | readonly string[]): this; + /** + * Append a single header value for the header object. + * + * If the value is an array, this is equivalent of calling this method multiple times. + * + * If there were no previous value for the header, this is equivalent of calling `outgoingMessage.setHeader(name, value)`. + * + * Depending of the value of `options.uniqueHeaders` when the client request or the server were created, + * this will end up in the header being sent multiple times or a single time with values joined using `; `. + * @since v18.3.0, v16.17.0 + * @param name Header name + * @param value Header value + */ + appendHeader(name: string, value: string | readonly string[]): this; + /** + * Gets the value of HTTP header with the given name. If such a name doesn't + * exist in message, it will be `undefined`. + * @since v0.4.0 + * @param name Name of header + */ + getHeader(name: string): number | string | string[] | undefined; + /** + * Returns a shallow copy of the current outgoing headers. Since a shallow + * copy is used, array values may be mutated without additional calls to + * various header-related HTTP module methods. The keys of the returned + * object are the header names and the values are the respective header + * values. All header names are lowercase. + * + * The object returned by the `outgoingMessage.getHeaders()` method does + * not prototypically inherit from the JavaScript Object. This means that + * typical Object methods such as `obj.toString()`, `obj.hasOwnProperty()`, + * and others are not defined and will not work. + * + * ```js + * outgoingMessage.setHeader('Foo', 'bar'); + * outgoingMessage.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headers = outgoingMessage.getHeaders(); + * // headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] } + * ``` + * @since v7.7.0 + */ + getHeaders(): OutgoingHttpHeaders; + /** + * Returns an array of names of headers of the outgoing outgoingMessage. All + * names are lowercase. + * @since v7.7.0 + */ + getHeaderNames(): string[]; + /** + * Returns `true` if the header identified by `name` is currently set in the + * outgoing headers. The header name is case-insensitive. + * + * ```js + * const hasContentType = outgoingMessage.hasHeader('content-type'); + * ``` + * @since v7.7.0 + */ + hasHeader(name: string): boolean; + /** + * Removes a header that is queued for implicit sending. + * + * ```js + * outgoingMessage.removeHeader('Content-Encoding'); + * ``` + * @since v0.4.0 + * @param name Header name + */ + removeHeader(name: string): void; + /** + * Adds HTTP trailers (headers but at the end of the message) to the message. + * + * Trailers are **only** be emitted if the message is chunked encoded. If not, + * the trailer will be silently discarded. + * + * HTTP requires the `Trailer` header to be sent to emit trailers, + * with a list of header fields in its value, e.g. + * + * ```js + * message.writeHead(200, { 'Content-Type': 'text/plain', + * 'Trailer': 'Content-MD5' }); + * message.write(fileData); + * message.addTrailers({ 'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667' }); + * message.end(); + * ``` + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v0.3.0 + */ + addTrailers(headers: OutgoingHttpHeaders | ReadonlyArray<[string, string]>): void; + /** + * Compulsorily flushes the message headers + * + * For efficiency reason, Node.js normally buffers the message headers + * until `outgoingMessage.end()` is called or the first chunk of message data + * is written. It then tries to pack the headers and data into a single TCP + * packet. + * + * It is usually desired (it saves a TCP round-trip), but not when the first + * data is not sent until possibly much later. `outgoingMessage.flushHeaders()`bypasses the optimization and kickstarts the request. + * @since v1.6.0 + */ + flushHeaders(): void; + } + /** + * This object is created internally by an HTTP server, not by the user. It is + * passed as the second parameter to the `'request'` event. + * @since v0.1.17 + */ + class ServerResponse extends OutgoingMessage { + /** + * When using implicit headers (not calling `response.writeHead()` explicitly), + * this property controls the status code that will be sent to the client when + * the headers get flushed. + * + * ```js + * response.statusCode = 404; + * ``` + * + * After response header was sent to the client, this property indicates the + * status code which was sent out. + * @since v0.4.0 + */ + statusCode: number; + /** + * When using implicit headers (not calling `response.writeHead()` explicitly), + * this property controls the status message that will be sent to the client when + * the headers get flushed. If this is left as `undefined` then the standard + * message for the status code will be used. + * + * ```js + * response.statusMessage = 'Not found'; + * ``` + * + * After response header was sent to the client, this property indicates the + * status message which was sent out. + * @since v0.11.8 + */ + statusMessage: string; + /** + * If set to `true`, Node.js will check whether the `Content-Length` header value + * and the size of the body, in bytes, are equal. Mismatching the + * `Content-Length` header value will result in an `Error` being thrown, + * identified by `code: 'ERR_HTTP_CONTENT_LENGTH_MISMATCH'`. + * @since v18.10.0, v16.18.0 + */ + strictContentLength: boolean; + constructor(req: Request); + assignSocket(socket: Socket): void; + detachSocket(socket: Socket): void; + /** + * Sends an HTTP/1.1 100 Continue message to the client, indicating that + * the request body should be sent. See the `'checkContinue'` event on`Server`. + * @since v0.3.0 + */ + writeContinue(callback?: () => void): void; + /** + * Sends an HTTP/1.1 103 Early Hints message to the client with a Link header, + * indicating that the user agent can preload/preconnect the linked resources. + * The `hints` is an object containing the values of headers to be sent with + * early hints message. The optional `callback` argument will be called when + * the response message has been written. + * + * Example: + * + * ```js + * const earlyHintsLink = '; rel=preload; as=style'; + * response.writeEarlyHints({ + * 'link': earlyHintsLink, + * }); + * + * const earlyHintsLinks = [ + * '; rel=preload; as=style', + * '; rel=preload; as=script', + * ]; + * response.writeEarlyHints({ + * 'link': earlyHintsLinks, + * 'x-trace-id': 'id for diagnostics' + * }); + * + * const earlyHintsCallback = () => console.log('early hints message sent'); + * response.writeEarlyHints({ + * 'link': earlyHintsLinks + * }, earlyHintsCallback); + * ``` + * + * @since v18.11.0 + * @param hints An object containing the values of headers + * @param callback Will be called when the response message has been written + */ + writeEarlyHints(hints: Record, callback?: () => void): void; + /** + * Sends a response header to the request. The status code is a 3-digit HTTP + * status code, like `404`. The last argument, `headers`, are the response headers. + * Optionally one can give a human-readable `statusMessage` as the second + * argument. + * + * `headers` may be an `Array` where the keys and values are in the same list. + * It is _not_ a list of tuples. So, the even-numbered offsets are key values, + * and the odd-numbered offsets are the associated values. The array is in the same + * format as `request.rawHeaders`. + * + * Returns a reference to the `ServerResponse`, so that calls can be chained. + * + * ```js + * const body = 'hello world'; + * response + * .writeHead(200, { + * 'Content-Length': Buffer.byteLength(body), + * 'Content-Type': 'text/plain' + * }) + * .end(body); + * ``` + * + * This method must only be called once on a message and it must + * be called before `response.end()` is called. + * + * If `response.write()` or `response.end()` are called before calling + * this, the implicit/mutable headers will be calculated and call this function. + * + * When headers have been set with `response.setHeader()`, they will be merged + * with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * If this method is called and `response.setHeader()` has not been called, + * it will directly write the supplied header values onto the network channel + * without caching internally, and the `response.getHeader()` on the header + * will not yield the expected result. If progressive population of headers is + * desired with potential future retrieval and modification, use `response.setHeader()` instead. + * + * ```js + * // Returns content-type = text/plain + * const server = http.createServer((req, res) => { + * res.setHeader('Content-Type', 'text/html'); + * res.setHeader('X-Foo', 'bar'); + * res.writeHead(200, { 'Content-Type': 'text/plain' }); + * res.end('ok'); + * }); + * ``` + * + * `Content-Length` is given in bytes, not characters. Use `Buffer.byteLength()` to determine the length of the body in bytes. Node.js + * does not check whether `Content-Length` and the length of the body which has + * been transmitted are equal or not. + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v0.1.30 + */ + writeHead( + statusCode: number, + statusMessage?: string, + headers?: OutgoingHttpHeaders | OutgoingHttpHeader[], + ): this; + writeHead(statusCode: number, headers?: OutgoingHttpHeaders | OutgoingHttpHeader[]): this; + /** + * Sends an HTTP/1.1 102 Processing message to the client, indicating that + * the request body should be sent. + * @since v10.0.0 + */ + writeProcessing(): void; + } + interface InformationEvent { + statusCode: number; + statusMessage: string; + httpVersion: string; + httpVersionMajor: number; + httpVersionMinor: number; + headers: IncomingHttpHeaders; + rawHeaders: string[]; + } + /** + * This object is created internally and returned from {@link request}. It + * represents an _in-progress_ request whose header has already been queued. The + * header is still mutable using the `setHeader(name, value)`,`getHeader(name)`, `removeHeader(name)` API. The actual header will + * be sent along with the first data chunk or when calling `request.end()`. + * + * To get the response, add a listener for `'response'` to the request object.`'response'` will be emitted from the request object when the response + * headers have been received. The `'response'` event is executed with one + * argument which is an instance of {@link IncomingMessage}. + * + * During the `'response'` event, one can add listeners to the + * response object; particularly to listen for the `'data'` event. + * + * If no `'response'` handler is added, then the response will be + * entirely discarded. However, if a `'response'` event handler is added, + * then the data from the response object **must** be consumed, either by + * calling `response.read()` whenever there is a `'readable'` event, or + * by adding a `'data'` handler, or by calling the `.resume()` method. + * Until the data is consumed, the `'end'` event will not fire. Also, until + * the data is read it will consume memory that can eventually lead to a + * 'process out of memory' error. + * + * For backward compatibility, `res` will only emit `'error'` if there is an`'error'` listener registered. + * + * Node.js does not check whether Content-Length and the length of the + * body which has been transmitted are equal or not. + * @since v0.1.17 + */ + class ClientRequest extends OutgoingMessage { + /** + * The `request.aborted` property will be `true` if the request has + * been aborted. + * @since v0.11.14 + * @deprecated Since v17.0.0,v16.12.0 - Check `destroyed` instead. + */ + aborted: boolean; + /** + * The request host. + * @since v14.5.0, v12.19.0 + */ + host: string; + /** + * The request protocol. + * @since v14.5.0, v12.19.0 + */ + protocol: string; + /** + * When sending request through a keep-alive enabled agent, the underlying socket + * might be reused. But if server closes connection at unfortunate time, client + * may run into a 'ECONNRESET' error. + * + * ```js + * const http = require('http'); + * + * // Server has a 5 seconds keep-alive timeout by default + * http + * .createServer((req, res) => { + * res.write('hello\n'); + * res.end(); + * }) + * .listen(3000); + * + * setInterval(() => { + * // Adapting a keep-alive agent + * http.get('http://localhost:3000', { agent }, (res) => { + * res.on('data', (data) => { + * // Do nothing + * }); + * }); + * }, 5000); // Sending request on 5s interval so it's easy to hit idle timeout + * ``` + * + * By marking a request whether it reused socket or not, we can do + * automatic error retry base on it. + * + * ```js + * const http = require('http'); + * const agent = new http.Agent({ keepAlive: true }); + * + * function retriableRequest() { + * const req = http + * .get('http://localhost:3000', { agent }, (res) => { + * // ... + * }) + * .on('error', (err) => { + * // Check if retry is needed + * if (req.reusedSocket && err.code === 'ECONNRESET') { + * retriableRequest(); + * } + * }); + * } + * + * retriableRequest(); + * ``` + * @since v13.0.0, v12.16.0 + */ + reusedSocket: boolean; + /** + * Limits maximum response headers count. If set to 0, no limit will be applied. + */ + maxHeadersCount: number; + constructor(url: string | URL | ClientRequestArgs, cb?: (res: IncomingMessage) => void); + /** + * The request method. + * @since v0.1.97 + */ + method: string; + /** + * The request path. + * @since v0.4.0 + */ + path: string; + /** + * Marks the request as aborting. Calling this will cause remaining data + * in the response to be dropped and the socket to be destroyed. + * @since v0.3.8 + * @deprecated Since v14.1.0,v13.14.0 - Use `destroy` instead. + */ + abort(): void; + onSocket(socket: Socket): void; + /** + * Once a socket is assigned to this request and is connected `socket.setTimeout()` will be called. + * @since v0.5.9 + * @param timeout Milliseconds before a request times out. + * @param callback Optional function to be called when a timeout occurs. Same as binding to the `'timeout'` event. + */ + setTimeout(timeout: number, callback?: () => void): this; + /** + * Once a socket is assigned to this request and is connected `socket.setNoDelay()` will be called. + * @since v0.5.9 + */ + setNoDelay(noDelay?: boolean): void; + /** + * Once a socket is assigned to this request and is connected `socket.setKeepAlive()` will be called. + * @since v0.5.9 + */ + setSocketKeepAlive(enable?: boolean, initialDelay?: number): void; + /** + * Returns an array containing the unique names of the current outgoing raw + * headers. Header names are returned with their exact casing being set. + * + * ```js + * request.setHeader('Foo', 'bar'); + * request.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headerNames = request.getRawHeaderNames(); + * // headerNames === ['Foo', 'Set-Cookie'] + * ``` + * @since v15.13.0, v14.17.0 + */ + getRawHeaderNames(): string[]; + /** + * @deprecated + */ + addListener(event: "abort", listener: () => void): this; + addListener( + event: "connect", + listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, + ): this; + addListener(event: "continue", listener: () => void): this; + addListener(event: "information", listener: (info: InformationEvent) => void): this; + addListener(event: "response", listener: (response: IncomingMessage) => void): this; + addListener(event: "socket", listener: (socket: Socket) => void): this; + addListener(event: "timeout", listener: () => void): this; + addListener( + event: "upgrade", + listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, + ): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "pipe", listener: (src: stream.Readable) => void): this; + addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + /** + * @deprecated + */ + on(event: "abort", listener: () => void): this; + on(event: "connect", listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + on(event: "continue", listener: () => void): this; + on(event: "information", listener: (info: InformationEvent) => void): this; + on(event: "response", listener: (response: IncomingMessage) => void): this; + on(event: "socket", listener: (socket: Socket) => void): this; + on(event: "timeout", listener: () => void): this; + on(event: "upgrade", listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pipe", listener: (src: stream.Readable) => void): this; + on(event: "unpipe", listener: (src: stream.Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + /** + * @deprecated + */ + once(event: "abort", listener: () => void): this; + once(event: "connect", listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + once(event: "continue", listener: () => void): this; + once(event: "information", listener: (info: InformationEvent) => void): this; + once(event: "response", listener: (response: IncomingMessage) => void): this; + once(event: "socket", listener: (socket: Socket) => void): this; + once(event: "timeout", listener: () => void): this; + once(event: "upgrade", listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pipe", listener: (src: stream.Readable) => void): this; + once(event: "unpipe", listener: (src: stream.Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + /** + * @deprecated + */ + prependListener(event: "abort", listener: () => void): this; + prependListener( + event: "connect", + listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, + ): this; + prependListener(event: "continue", listener: () => void): this; + prependListener(event: "information", listener: (info: InformationEvent) => void): this; + prependListener(event: "response", listener: (response: IncomingMessage) => void): this; + prependListener(event: "socket", listener: (socket: Socket) => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener( + event: "upgrade", + listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, + ): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + /** + * @deprecated + */ + prependOnceListener(event: "abort", listener: () => void): this; + prependOnceListener( + event: "connect", + listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, + ): this; + prependOnceListener(event: "continue", listener: () => void): this; + prependOnceListener(event: "information", listener: (info: InformationEvent) => void): this; + prependOnceListener(event: "response", listener: (response: IncomingMessage) => void): this; + prependOnceListener(event: "socket", listener: (socket: Socket) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener( + event: "upgrade", + listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, + ): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * An `IncomingMessage` object is created by {@link Server} or {@link ClientRequest} and passed as the first argument to the `'request'` and `'response'` event respectively. It may be used to + * access response + * status, headers and data. + * + * Different from its `socket` value which is a subclass of `stream.Duplex`, the`IncomingMessage` itself extends `stream.Readable` and is created separately to + * parse and emit the incoming HTTP headers and payload, as the underlying socket + * may be reused multiple times in case of keep-alive. + * @since v0.1.17 + */ + class IncomingMessage extends stream.Readable { + constructor(socket: Socket); + /** + * The `message.aborted` property will be `true` if the request has + * been aborted. + * @since v10.1.0 + * @deprecated Since v17.0.0,v16.12.0 - Check `message.destroyed` from stream.Readable. + */ + aborted: boolean; + /** + * In case of server request, the HTTP version sent by the client. In the case of + * client response, the HTTP version of the connected-to server. + * Probably either `'1.1'` or `'1.0'`. + * + * Also `message.httpVersionMajor` is the first integer and`message.httpVersionMinor` is the second. + * @since v0.1.1 + */ + httpVersion: string; + httpVersionMajor: number; + httpVersionMinor: number; + /** + * The `message.complete` property will be `true` if a complete HTTP message has + * been received and successfully parsed. + * + * This property is particularly useful as a means of determining if a client or + * server fully transmitted a message before a connection was terminated: + * + * ```js + * const req = http.request({ + * host: '127.0.0.1', + * port: 8080, + * method: 'POST' + * }, (res) => { + * res.resume(); + * res.on('end', () => { + * if (!res.complete) + * console.error( + * 'The connection was terminated while the message was still being sent'); + * }); + * }); + * ``` + * @since v0.3.0 + */ + complete: boolean; + /** + * Alias for `message.socket`. + * @since v0.1.90 + * @deprecated Since v16.0.0 - Use `socket`. + */ + connection: Socket; + /** + * The `net.Socket` object associated with the connection. + * + * With HTTPS support, use `request.socket.getPeerCertificate()` to obtain the + * client's authentication details. + * + * This property is guaranteed to be an instance of the `net.Socket` class, + * a subclass of `stream.Duplex`, unless the user specified a socket + * type other than `net.Socket` or internally nulled. + * @since v0.3.0 + */ + socket: Socket; + /** + * The request/response headers object. + * + * Key-value pairs of header names and values. Header names are lower-cased. + * + * ```js + * // Prints something like: + * // + * // { 'user-agent': 'curl/7.22.0', + * // host: '127.0.0.1:8000', + * // accept: '*' } + * console.log(request.getHeaders()); + * ``` + * + * Duplicates in raw headers are handled in the following ways, depending on the + * header name: + * + * * Duplicates of `age`, `authorization`, `content-length`, `content-type`,`etag`, `expires`, `from`, `host`, `if-modified-since`, `if-unmodified-since`,`last-modified`, `location`, + * `max-forwards`, `proxy-authorization`, `referer`,`retry-after`, `server`, or `user-agent` are discarded. + * * `set-cookie` is always an array. Duplicates are added to the array. + * * For duplicate `cookie` headers, the values are joined together with '; '. + * * For all other headers, the values are joined together with ', '. + * @since v0.1.5 + */ + headers: IncomingHttpHeaders; + /** + * Similar to `message.headers`, but there is no join logic and the values are always arrays of strings, even for headers received just once. + * + * ```js + * // Prints something like: + * // + * // { 'user-agent': ['curl/7.22.0'], + * // host: ['127.0.0.1:8000'], + * // accept: ['*'] } + * console.log(request.headersDistinct); + * ``` + * @since v18.3.0, v16.17.0 + */ + headersDistinct: NodeJS.Dict; + /** + * The raw request/response headers list exactly as they were received. + * + * The keys and values are in the same list. It is _not_ a + * list of tuples. So, the even-numbered offsets are key values, and the + * odd-numbered offsets are the associated values. + * + * Header names are not lowercased, and duplicates are not merged. + * + * ```js + * // Prints something like: + * // + * // [ 'user-agent', + * // 'this is invalid because there can be only one', + * // 'User-Agent', + * // 'curl/7.22.0', + * // 'Host', + * // '127.0.0.1:8000', + * // 'ACCEPT', + * // '*' ] + * console.log(request.rawHeaders); + * ``` + * @since v0.11.6 + */ + rawHeaders: string[]; + /** + * The request/response trailers object. Only populated at the `'end'` event. + * @since v0.3.0 + */ + trailers: NodeJS.Dict; + /** + * Similar to `message.trailers`, but there is no join logic and the values are always arrays of strings, even for headers received just once. + * Only populated at the `'end'` event. + * @since v18.3.0, v16.17.0 + */ + trailersDistinct: NodeJS.Dict; + /** + * The raw request/response trailer keys and values exactly as they were + * received. Only populated at the `'end'` event. + * @since v0.11.6 + */ + rawTrailers: string[]; + /** + * Calls `message.socket.setTimeout(msecs, callback)`. + * @since v0.5.9 + */ + setTimeout(msecs: number, callback?: () => void): this; + /** + * **Only valid for request obtained from {@link Server}.** + * + * The request method as a string. Read only. Examples: `'GET'`, `'DELETE'`. + * @since v0.1.1 + */ + method?: string | undefined; + /** + * **Only valid for request obtained from {@link Server}.** + * + * Request URL string. This contains only the URL that is present in the actual + * HTTP request. Take the following request: + * + * ```http + * GET /status?name=ryan HTTP/1.1 + * Accept: text/plain + * ``` + * + * To parse the URL into its parts: + * + * ```js + * new URL(request.url, `http://${request.getHeaders().host}`); + * ``` + * + * When `request.url` is `'/status?name=ryan'` and`request.getHeaders().host` is `'localhost:3000'`: + * + * ```console + * $ node + * > new URL(request.url, `http://${request.getHeaders().host}`) + * URL { + * href: 'http://localhost:3000/status?name=ryan', + * origin: 'http://localhost:3000', + * protocol: 'http:', + * username: '', + * password: '', + * host: 'localhost:3000', + * hostname: 'localhost', + * port: '3000', + * pathname: '/status', + * search: '?name=ryan', + * searchParams: URLSearchParams { 'name' => 'ryan' }, + * hash: '' + * } + * ``` + * @since v0.1.90 + */ + url?: string | undefined; + /** + * **Only valid for response obtained from {@link ClientRequest}.** + * + * The 3-digit HTTP response status code. E.G. `404`. + * @since v0.1.1 + */ + statusCode?: number | undefined; + /** + * **Only valid for response obtained from {@link ClientRequest}.** + * + * The HTTP response status message (reason phrase). E.G. `OK` or `Internal Server Error`. + * @since v0.11.10 + */ + statusMessage?: string | undefined; + /** + * Calls `destroy()` on the socket that received the `IncomingMessage`. If `error`is provided, an `'error'` event is emitted on the socket and `error` is passed + * as an argument to any listeners on the event. + * @since v0.3.0 + */ + destroy(error?: Error): this; + } + interface AgentOptions extends Partial { + /** + * Keep sockets around in a pool to be used by other requests in the future. Default = false + */ + keepAlive?: boolean | undefined; + /** + * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. + * Only relevant if keepAlive is set to true. + */ + keepAliveMsecs?: number | undefined; + /** + * Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity + */ + maxSockets?: number | undefined; + /** + * Maximum number of sockets allowed for all hosts in total. Each request will use a new socket until the maximum is reached. Default: Infinity. + */ + maxTotalSockets?: number | undefined; + /** + * Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256. + */ + maxFreeSockets?: number | undefined; + /** + * Socket timeout in milliseconds. This will set the timeout after the socket is connected. + */ + timeout?: number | undefined; + /** + * Scheduling strategy to apply when picking the next free socket to use. + * @default `lifo` + */ + scheduling?: "fifo" | "lifo" | undefined; + } + /** + * An `Agent` is responsible for managing connection persistence + * and reuse for HTTP clients. It maintains a queue of pending requests + * for a given host and port, reusing a single socket connection for each + * until the queue is empty, at which time the socket is either destroyed + * or put into a pool where it is kept to be used again for requests to the + * same host and port. Whether it is destroyed or pooled depends on the`keepAlive` `option`. + * + * Pooled connections have TCP Keep-Alive enabled for them, but servers may + * still close idle connections, in which case they will be removed from the + * pool and a new connection will be made when a new HTTP request is made for + * that host and port. Servers may also refuse to allow multiple requests + * over the same connection, in which case the connection will have to be + * remade for every request and cannot be pooled. The `Agent` will still make + * the requests to that server, but each one will occur over a new connection. + * + * When a connection is closed by the client or the server, it is removed + * from the pool. Any unused sockets in the pool will be unrefed so as not + * to keep the Node.js process running when there are no outstanding requests. + * (see `socket.unref()`). + * + * It is good practice, to `destroy()` an `Agent` instance when it is no + * longer in use, because unused sockets consume OS resources. + * + * Sockets are removed from an agent when the socket emits either + * a `'close'` event or an `'agentRemove'` event. When intending to keep one + * HTTP request open for a long time without keeping it in the agent, something + * like the following may be done: + * + * ```js + * http.get(options, (res) => { + * // Do stuff + * }).on('socket', (socket) => { + * socket.emit('agentRemove'); + * }); + * ``` + * + * An agent may also be used for an individual request. By providing`{agent: false}` as an option to the `http.get()` or `http.request()`functions, a one-time use `Agent` with default options + * will be used + * for the client connection. + * + * `agent:false`: + * + * ```js + * http.get({ + * hostname: 'localhost', + * port: 80, + * path: '/', + * agent: false // Create a new agent just for this one request + * }, (res) => { + * // Do stuff with response + * }); + * ``` + * @since v0.3.4 + */ + class Agent extends EventEmitter { + /** + * By default set to 256. For agents with `keepAlive` enabled, this + * sets the maximum number of sockets that will be left open in the free + * state. + * @since v0.11.7 + */ + maxFreeSockets: number; + /** + * By default set to `Infinity`. Determines how many concurrent sockets the agent + * can have open per origin. Origin is the returned value of `agent.getName()`. + * @since v0.3.6 + */ + maxSockets: number; + /** + * By default set to `Infinity`. Determines how many concurrent sockets the agent + * can have open. Unlike `maxSockets`, this parameter applies across all origins. + * @since v14.5.0, v12.19.0 + */ + maxTotalSockets: number; + /** + * An object which contains arrays of sockets currently awaiting use by + * the agent when `keepAlive` is enabled. Do not modify. + * + * Sockets in the `freeSockets` list will be automatically destroyed and + * removed from the array on `'timeout'`. + * @since v0.11.4 + */ + readonly freeSockets: NodeJS.ReadOnlyDict; + /** + * An object which contains arrays of sockets currently in use by the + * agent. Do not modify. + * @since v0.3.6 + */ + readonly sockets: NodeJS.ReadOnlyDict; + /** + * An object which contains queues of requests that have not yet been assigned to + * sockets. Do not modify. + * @since v0.5.9 + */ + readonly requests: NodeJS.ReadOnlyDict; + constructor(opts?: AgentOptions); + /** + * Destroy any sockets that are currently in use by the agent. + * + * It is usually not necessary to do this. However, if using an + * agent with `keepAlive` enabled, then it is best to explicitly shut down + * the agent when it is no longer needed. Otherwise, + * sockets might stay open for quite a long time before the server + * terminates them. + * @since v0.11.4 + */ + destroy(): void; + } + const METHODS: string[]; + const STATUS_CODES: { + [errorCode: number]: string | undefined; + [errorCode: string]: string | undefined; + }; + /** + * Returns a new instance of {@link Server}. + * + * The `requestListener` is a function which is automatically + * added to the `'request'` event. + * @since v0.1.13 + */ + function createServer< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse = typeof ServerResponse, + >(requestListener?: RequestListener): Server; + function createServer< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse = typeof ServerResponse, + >( + options: ServerOptions, + requestListener?: RequestListener, + ): Server; + // although RequestOptions are passed as ClientRequestArgs to ClientRequest directly, + // create interface RequestOptions would make the naming more clear to developers + interface RequestOptions extends ClientRequestArgs {} + /** + * `options` in `socket.connect()` are also supported. + * + * Node.js maintains several connections per server to make HTTP requests. + * This function allows one to transparently issue requests. + * + * `url` can be a string or a `URL` object. If `url` is a + * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. + * + * If both `url` and `options` are specified, the objects are merged, with the`options` properties taking precedence. + * + * The optional `callback` parameter will be added as a one-time listener for + * the `'response'` event. + * + * `http.request()` returns an instance of the {@link ClientRequest} class. The `ClientRequest` instance is a writable stream. If one needs to + * upload a file with a POST request, then write to the `ClientRequest` object. + * + * ```js + * const http = require('http'); + * + * const postData = JSON.stringify({ + * 'msg': 'Hello World!' + * }); + * + * const options = { + * hostname: 'www.google.com', + * port: 80, + * path: '/upload', + * method: 'POST', + * headers: { + * 'Content-Type': 'application/json', + * 'Content-Length': Buffer.byteLength(postData) + * } + * }; + * + * const req = http.request(options, (res) => { + * console.log(`STATUS: ${res.statusCode}`); + * console.log(`HEADERS: ${JSON.stringify(res.headers)}`); + * res.setEncoding('utf8'); + * res.on('data', (chunk) => { + * console.log(`BODY: ${chunk}`); + * }); + * res.on('end', () => { + * console.log('No more data in response.'); + * }); + * }); + * + * req.on('error', (e) => { + * console.error(`problem with request: ${e.message}`); + * }); + * + * // Write data to request body + * req.write(postData); + * req.end(); + * ``` + * + * In the example `req.end()` was called. With `http.request()` one + * must always call `req.end()` to signify the end of the request - + * even if there is no data being written to the request body. + * + * If any error is encountered during the request (be that with DNS resolution, + * TCP level errors, or actual HTTP parse errors) an `'error'` event is emitted + * on the returned request object. As with all `'error'` events, if no listeners + * are registered the error will be thrown. + * + * There are a few special headers that should be noted. + * + * * Sending a 'Connection: keep-alive' will notify Node.js that the connection to + * the server should be persisted until the next request. + * * Sending a 'Content-Length' header will disable the default chunked encoding. + * * Sending an 'Expect' header will immediately send the request headers. + * Usually, when sending 'Expect: 100-continue', both a timeout and a listener + * for the `'continue'` event should be set. See RFC 2616 Section 8.2.3 for more + * information. + * * Sending an Authorization header will override using the `auth` option + * to compute basic authentication. + * + * Example using a `URL` as `options`: + * + * ```js + * const options = new URL('http://abc:xyz@example.com'); + * + * const req = http.request(options, (res) => { + * // ... + * }); + * ``` + * + * In a successful request, the following events will be emitted in the following + * order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * (`'data'` will not be emitted at all if the response body is empty, for + * instance, in most redirects) + * * `'end'` on the `res` object + * * `'close'` + * + * In the case of a connection error, the following events will be emitted: + * + * * `'socket'` + * * `'error'` + * * `'close'` + * + * In the case of a premature connection close before the response is received, + * the following events will be emitted in the following order: + * + * * `'socket'` + * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'` + * * `'close'` + * + * In the case of a premature connection close after the response is received, + * the following events will be emitted in the following order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * * (connection closed here) + * * `'aborted'` on the `res` object + * * `'error'` on the `res` object with an error with message`'Error: aborted'` and code `'ECONNRESET'`. + * * `'close'` + * * `'close'` on the `res` object + * + * If `req.destroy()` is called before a socket is assigned, the following + * events will be emitted in the following order: + * + * * (`req.destroy()` called here) + * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'` + * * `'close'` + * + * If `req.destroy()` is called before the connection succeeds, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * (`req.destroy()` called here) + * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'` + * * `'close'` + * + * If `req.destroy()` is called after the response is received, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * * (`req.destroy()` called here) + * * `'aborted'` on the `res` object + * * `'error'` on the `res` object with an error with message`'Error: aborted'` and code `'ECONNRESET'`. + * * `'close'` + * * `'close'` on the `res` object + * + * If `req.abort()` is called before a socket is assigned, the following + * events will be emitted in the following order: + * + * * (`req.abort()` called here) + * * `'abort'` + * * `'close'` + * + * If `req.abort()` is called before the connection succeeds, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * (`req.abort()` called here) + * * `'abort'` + * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'` + * * `'close'` + * + * If `req.abort()` is called after the response is received, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * * (`req.abort()` called here) + * * `'abort'` + * * `'aborted'` on the `res` object + * * `'error'` on the `res` object with an error with message`'Error: aborted'` and code `'ECONNRESET'`. + * * `'close'` + * * `'close'` on the `res` object + * + * Setting the `timeout` option or using the `setTimeout()` function will + * not abort the request or do anything besides add a `'timeout'` event. + * + * Passing an `AbortSignal` and then calling `abort` on the corresponding`AbortController` will behave the same way as calling `.destroy()` on the + * request itself. + * @since v0.3.6 + */ + function request(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; + function request( + url: string | URL, + options: RequestOptions, + callback?: (res: IncomingMessage) => void, + ): ClientRequest; + /** + * Since most requests are GET requests without bodies, Node.js provides this + * convenience method. The only difference between this method and {@link request} is that it sets the method to GET and calls `req.end()`automatically. The callback must take care to consume the + * response + * data for reasons stated in {@link ClientRequest} section. + * + * The `callback` is invoked with a single argument that is an instance of {@link IncomingMessage}. + * + * JSON fetching example: + * + * ```js + * http.get('http://localhost:8000/', (res) => { + * const { statusCode } = res; + * const contentType = res.headers['content-type']; + * + * let error; + * // Any 2xx status code signals a successful response but + * // here we're only checking for 200. + * if (statusCode !== 200) { + * error = new Error('Request Failed.\n' + + * `Status Code: ${statusCode}`); + * } else if (!/^application\/json/.test(contentType)) { + * error = new Error('Invalid content-type.\n' + + * `Expected application/json but received ${contentType}`); + * } + * if (error) { + * console.error(error.message); + * // Consume response data to free up memory + * res.resume(); + * return; + * } + * + * res.setEncoding('utf8'); + * let rawData = ''; + * res.on('data', (chunk) => { rawData += chunk; }); + * res.on('end', () => { + * try { + * const parsedData = JSON.parse(rawData); + * console.log(parsedData); + * } catch (e) { + * console.error(e.message); + * } + * }); + * }).on('error', (e) => { + * console.error(`Got error: ${e.message}`); + * }); + * + * // Create a local server to receive data from + * const server = http.createServer((req, res) => { + * res.writeHead(200, { 'Content-Type': 'application/json' }); + * res.end(JSON.stringify({ + * data: 'Hello World!' + * })); + * }); + * + * server.listen(8000); + * ``` + * @since v0.3.6 + * @param options Accepts the same `options` as {@link request}, with the `method` always set to `GET`. Properties that are inherited from the prototype are ignored. + */ + function get(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; + function get(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; + + /** + * Performs the low-level validations on the provided name that are done when `res.setHeader(name, value)` is called. + * Passing illegal value as name will result in a TypeError being thrown, identified by `code: 'ERR_INVALID_HTTP_TOKEN'`. + * @param name Header name + * @since v14.3.0 + */ + function validateHeaderName(name: string): void; + /** + * Performs the low-level validations on the provided value that are done when `res.setHeader(name, value)` is called. + * Passing illegal value as value will result in a TypeError being thrown. + * - Undefined value error is identified by `code: 'ERR_HTTP_INVALID_HEADER_VALUE'`. + * - Invalid value character error is identified by `code: 'ERR_INVALID_CHAR'`. + * @param name Header name + * @param value Header value + * @since v14.3.0 + */ + function validateHeaderValue(name: string, value: string): void; + + /** + * Set the maximum number of idle HTTP parsers. Default: 1000. + * @param count + * @since v18.8.0, v16.18.0 + */ + function setMaxIdleHTTPParsers(count: number): void; + + let globalAgent: Agent; + /** + * Read-only property specifying the maximum allowed size of HTTP headers in bytes. + * Defaults to 16KB. Configurable using the `--max-http-header-size` CLI option. + */ + const maxHeaderSize: number; +} +declare module "node:http" { + export * from "http"; +} diff --git a/backend/node_modules/@types/node/http2.d.ts b/backend/node_modules/@types/node/http2.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..05cd9fd9921691fd180663312ffdda8f9d91ace1 --- /dev/null +++ b/backend/node_modules/@types/node/http2.d.ts @@ -0,0 +1,2392 @@ +/** + * The `http2` module provides an implementation of the [HTTP/2](https://tools.ietf.org/html/rfc7540) protocol. It + * can be accessed using: + * + * ```js + * const http2 = require('http2'); + * ``` + * @since v8.4.0 + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/http2.js) + */ +declare module "http2" { + import EventEmitter = require("node:events"); + import * as fs from "node:fs"; + import * as net from "node:net"; + import * as stream from "node:stream"; + import * as tls from "node:tls"; + import * as url from "node:url"; + import { + IncomingHttpHeaders as Http1IncomingHttpHeaders, + IncomingMessage, + OutgoingHttpHeaders, + ServerResponse, + } from "node:http"; + export { OutgoingHttpHeaders } from "node:http"; + export interface IncomingHttpStatusHeader { + ":status"?: number | undefined; + } + export interface IncomingHttpHeaders extends Http1IncomingHttpHeaders { + ":path"?: string | undefined; + ":method"?: string | undefined; + ":authority"?: string | undefined; + ":scheme"?: string | undefined; + } + // Http2Stream + export interface StreamPriorityOptions { + exclusive?: boolean | undefined; + parent?: number | undefined; + weight?: number | undefined; + silent?: boolean | undefined; + } + export interface StreamState { + localWindowSize?: number | undefined; + state?: number | undefined; + localClose?: number | undefined; + remoteClose?: number | undefined; + sumDependencyWeight?: number | undefined; + weight?: number | undefined; + } + export interface ServerStreamResponseOptions { + endStream?: boolean | undefined; + waitForTrailers?: boolean | undefined; + } + export interface StatOptions { + offset: number; + length: number; + } + export interface ServerStreamFileResponseOptions { + // eslint-disable-next-line @typescript-eslint/no-invalid-void-type + statCheck?(stats: fs.Stats, headers: OutgoingHttpHeaders, statOptions: StatOptions): void | boolean; + waitForTrailers?: boolean | undefined; + offset?: number | undefined; + length?: number | undefined; + } + export interface ServerStreamFileResponseOptionsWithError extends ServerStreamFileResponseOptions { + onError?(err: NodeJS.ErrnoException): void; + } + export interface Http2Stream extends stream.Duplex { + /** + * Set to `true` if the `Http2Stream` instance was aborted abnormally. When set, + * the `'aborted'` event will have been emitted. + * @since v8.4.0 + */ + readonly aborted: boolean; + /** + * This property shows the number of characters currently buffered to be written. + * See `net.Socket.bufferSize` for details. + * @since v11.2.0, v10.16.0 + */ + readonly bufferSize: number; + /** + * Set to `true` if the `Http2Stream` instance has been closed. + * @since v9.4.0 + */ + readonly closed: boolean; + /** + * Set to `true` if the `Http2Stream` instance has been destroyed and is no longer + * usable. + * @since v8.4.0 + */ + readonly destroyed: boolean; + /** + * Set to `true` if the `END_STREAM` flag was set in the request or response + * HEADERS frame received, indicating that no additional data should be received + * and the readable side of the `Http2Stream` will be closed. + * @since v10.11.0 + */ + readonly endAfterHeaders: boolean; + /** + * The numeric stream identifier of this `Http2Stream` instance. Set to `undefined`if the stream identifier has not yet been assigned. + * @since v8.4.0 + */ + readonly id?: number | undefined; + /** + * Set to `true` if the `Http2Stream` instance has not yet been assigned a + * numeric stream identifier. + * @since v9.4.0 + */ + readonly pending: boolean; + /** + * Set to the `RST_STREAM` `error code` reported when the `Http2Stream` is + * destroyed after either receiving an `RST_STREAM` frame from the connected peer, + * calling `http2stream.close()`, or `http2stream.destroy()`. Will be`undefined` if the `Http2Stream` has not been closed. + * @since v8.4.0 + */ + readonly rstCode: number; + /** + * An object containing the outbound headers sent for this `Http2Stream`. + * @since v9.5.0 + */ + readonly sentHeaders: OutgoingHttpHeaders; + /** + * An array of objects containing the outbound informational (additional) headers + * sent for this `Http2Stream`. + * @since v9.5.0 + */ + readonly sentInfoHeaders?: OutgoingHttpHeaders[] | undefined; + /** + * An object containing the outbound trailers sent for this `HttpStream`. + * @since v9.5.0 + */ + readonly sentTrailers?: OutgoingHttpHeaders | undefined; + /** + * A reference to the `Http2Session` instance that owns this `Http2Stream`. The + * value will be `undefined` after the `Http2Stream` instance is destroyed. + * @since v8.4.0 + */ + readonly session: Http2Session | undefined; + /** + * Provides miscellaneous information about the current state of the`Http2Stream`. + * + * A current state of this `Http2Stream`. + * @since v8.4.0 + */ + readonly state: StreamState; + /** + * Closes the `Http2Stream` instance by sending an `RST_STREAM` frame to the + * connected HTTP/2 peer. + * @since v8.4.0 + * @param [code=http2.constants.NGHTTP2_NO_ERROR] Unsigned 32-bit integer identifying the error code. + * @param callback An optional function registered to listen for the `'close'` event. + */ + close(code?: number, callback?: () => void): void; + /** + * Updates the priority for this `Http2Stream` instance. + * @since v8.4.0 + */ + priority(options: StreamPriorityOptions): void; + /** + * ```js + * const http2 = require('http2'); + * const client = http2.connect('http://example.org:8000'); + * const { NGHTTP2_CANCEL } = http2.constants; + * const req = client.request({ ':path': '/' }); + * + * // Cancel the stream if there's no activity after 5 seconds + * req.setTimeout(5000, () => req.close(NGHTTP2_CANCEL)); + * ``` + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + /** + * Sends a trailing `HEADERS` frame to the connected HTTP/2 peer. This method + * will cause the `Http2Stream` to be immediately closed and must only be + * called after the `'wantTrailers'` event has been emitted. When sending a + * request or sending a response, the `options.waitForTrailers` option must be set + * in order to keep the `Http2Stream` open after the final `DATA` frame so that + * trailers can be sent. + * + * ```js + * const http2 = require('http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond(undefined, { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ xyz: 'abc' }); + * }); + * stream.end('Hello World'); + * }); + * ``` + * + * The HTTP/1 specification forbids trailers from containing HTTP/2 pseudo-header + * fields (e.g. `':method'`, `':path'`, etc). + * @since v10.0.0 + */ + sendTrailers(headers: OutgoingHttpHeaders): void; + addListener(event: "aborted", listener: () => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: Buffer | string) => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + addListener(event: "pipe", listener: (src: stream.Readable) => void): this; + addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + addListener(event: "streamClosed", listener: (code: number) => void): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: "wantTrailers", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "aborted"): boolean; + emit(event: "close"): boolean; + emit(event: "data", chunk: Buffer | string): boolean; + emit(event: "drain"): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "frameError", frameType: number, errorCode: number): boolean; + emit(event: "pipe", src: stream.Readable): boolean; + emit(event: "unpipe", src: stream.Readable): boolean; + emit(event: "streamClosed", code: number): boolean; + emit(event: "timeout"): boolean; + emit(event: "trailers", trailers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "wantTrailers"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "aborted", listener: () => void): this; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: Buffer | string) => void): this; + on(event: "drain", listener: () => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + on(event: "pipe", listener: (src: stream.Readable) => void): this; + on(event: "unpipe", listener: (src: stream.Readable) => void): this; + on(event: "streamClosed", listener: (code: number) => void): this; + on(event: "timeout", listener: () => void): this; + on(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + on(event: "wantTrailers", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "aborted", listener: () => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: Buffer | string) => void): this; + once(event: "drain", listener: () => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + once(event: "pipe", listener: (src: stream.Readable) => void): this; + once(event: "unpipe", listener: (src: stream.Readable) => void): this; + once(event: "streamClosed", listener: (code: number) => void): this; + once(event: "timeout", listener: () => void): this; + once(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + once(event: "wantTrailers", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "aborted", listener: () => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "streamClosed", listener: (code: number) => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: "wantTrailers", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "aborted", listener: () => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "streamClosed", listener: (code: number) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: "wantTrailers", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface ClientHttp2Stream extends Http2Stream { + addListener(event: "continue", listener: () => {}): this; + addListener( + event: "headers", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + addListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + addListener( + event: "response", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "continue"): boolean; + emit(event: "headers", headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; + emit(event: "push", headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "response", headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "continue", listener: () => {}): this; + on( + event: "headers", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + on(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + on( + event: "response", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "continue", listener: () => {}): this; + once( + event: "headers", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + once(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + once( + event: "response", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "continue", listener: () => {}): this; + prependListener( + event: "headers", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + prependListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + prependListener( + event: "response", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "continue", listener: () => {}): this; + prependOnceListener( + event: "headers", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + prependOnceListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener( + event: "response", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface ServerHttp2Stream extends Http2Stream { + /** + * True if headers were sent, false otherwise (read-only). + * @since v8.4.0 + */ + readonly headersSent: boolean; + /** + * Read-only property mapped to the `SETTINGS_ENABLE_PUSH` flag of the remote + * client's most recent `SETTINGS` frame. Will be `true` if the remote peer + * accepts push streams, `false` otherwise. Settings are the same for every`Http2Stream` in the same `Http2Session`. + * @since v8.4.0 + */ + readonly pushAllowed: boolean; + /** + * Sends an additional informational `HEADERS` frame to the connected HTTP/2 peer. + * @since v8.4.0 + */ + additionalHeaders(headers: OutgoingHttpHeaders): void; + /** + * Initiates a push stream. The callback is invoked with the new `Http2Stream`instance created for the push stream passed as the second argument, or an`Error` passed as the first argument. + * + * ```js + * const http2 = require('http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond({ ':status': 200 }); + * stream.pushStream({ ':path': '/' }, (err, pushStream, headers) => { + * if (err) throw err; + * pushStream.respond({ ':status': 200 }); + * pushStream.end('some pushed data'); + * }); + * stream.end('some data'); + * }); + * ``` + * + * Setting the weight of a push stream is not allowed in the `HEADERS` frame. Pass + * a `weight` value to `http2stream.priority` with the `silent` option set to`true` to enable server-side bandwidth balancing between concurrent streams. + * + * Calling `http2stream.pushStream()` from within a pushed stream is not permitted + * and will throw an error. + * @since v8.4.0 + * @param callback Callback that is called once the push stream has been initiated. + */ + pushStream( + headers: OutgoingHttpHeaders, + callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void, + ): void; + pushStream( + headers: OutgoingHttpHeaders, + options?: StreamPriorityOptions, + callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void, + ): void; + /** + * ```js + * const http2 = require('http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond({ ':status': 200 }); + * stream.end('some data'); + * }); + * ``` + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * will be emitted immediately after queuing the last chunk of payload data to be + * sent. The `http2stream.sendTrailers()` method can then be used to sent trailing + * header fields to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code must call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. + * + * ```js + * const http2 = require('http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond({ ':status': 200 }, { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ ABC: 'some value to send' }); + * }); + * stream.end('some data'); + * }); + * ``` + * @since v8.4.0 + */ + respond(headers?: OutgoingHttpHeaders, options?: ServerStreamResponseOptions): void; + /** + * Initiates a response whose data is read from the given file descriptor. No + * validation is performed on the given file descriptor. If an error occurs while + * attempting to read data using the file descriptor, the `Http2Stream` will be + * closed using an `RST_STREAM` frame using the standard `INTERNAL_ERROR` code. + * + * When used, the `Http2Stream` object's `Duplex` interface will be closed + * automatically. + * + * ```js + * const http2 = require('http2'); + * const fs = require('fs'); + * + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * const fd = fs.openSync('/some/file', 'r'); + * + * const stat = fs.fstatSync(fd); + * const headers = { + * 'content-length': stat.size, + * 'last-modified': stat.mtime.toUTCString(), + * 'content-type': 'text/plain; charset=utf-8' + * }; + * stream.respondWithFD(fd, headers); + * stream.on('close', () => fs.closeSync(fd)); + * }); + * ``` + * + * The optional `options.statCheck` function may be specified to give user code + * an opportunity to set additional content headers based on the `fs.Stat` details + * of the given fd. If the `statCheck` function is provided, the`http2stream.respondWithFD()` method will perform an `fs.fstat()` call to + * collect details on the provided file descriptor. + * + * The `offset` and `length` options may be used to limit the response to a + * specific range subset. This can be used, for instance, to support HTTP Range + * requests. + * + * The file descriptor or `FileHandle` is not closed when the stream is closed, + * so it will need to be closed manually once it is no longer needed. + * Using the same file descriptor concurrently for multiple streams + * is not supported and may result in data loss. Re-using a file descriptor + * after a stream has finished is supported. + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * will be emitted immediately after queuing the last chunk of payload data to be + * sent. The `http2stream.sendTrailers()` method can then be used to sent trailing + * header fields to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code _must_ call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. + * + * ```js + * const http2 = require('http2'); + * const fs = require('fs'); + * + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * const fd = fs.openSync('/some/file', 'r'); + * + * const stat = fs.fstatSync(fd); + * const headers = { + * 'content-length': stat.size, + * 'last-modified': stat.mtime.toUTCString(), + * 'content-type': 'text/plain; charset=utf-8' + * }; + * stream.respondWithFD(fd, headers, { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ ABC: 'some value to send' }); + * }); + * + * stream.on('close', () => fs.closeSync(fd)); + * }); + * ``` + * @since v8.4.0 + * @param fd A readable file descriptor. + */ + respondWithFD( + fd: number | fs.promises.FileHandle, + headers?: OutgoingHttpHeaders, + options?: ServerStreamFileResponseOptions, + ): void; + /** + * Sends a regular file as the response. The `path` must specify a regular file + * or an `'error'` event will be emitted on the `Http2Stream` object. + * + * When used, the `Http2Stream` object's `Duplex` interface will be closed + * automatically. + * + * The optional `options.statCheck` function may be specified to give user code + * an opportunity to set additional content headers based on the `fs.Stat` details + * of the given file: + * + * If an error occurs while attempting to read the file data, the `Http2Stream`will be closed using an `RST_STREAM` frame using the standard `INTERNAL_ERROR`code. If the `onError` callback is + * defined, then it will be called. Otherwise + * the stream will be destroyed. + * + * Example using a file path: + * + * ```js + * const http2 = require('http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * function statCheck(stat, headers) { + * headers['last-modified'] = stat.mtime.toUTCString(); + * } + * + * function onError(err) { + * // stream.respond() can throw if the stream has been destroyed by + * // the other side. + * try { + * if (err.code === 'ENOENT') { + * stream.respond({ ':status': 404 }); + * } else { + * stream.respond({ ':status': 500 }); + * } + * } catch (err) { + * // Perform actual error handling. + * console.log(err); + * } + * stream.end(); + * } + * + * stream.respondWithFile('/some/file', + * { 'content-type': 'text/plain; charset=utf-8' }, + * { statCheck, onError }); + * }); + * ``` + * + * The `options.statCheck` function may also be used to cancel the send operation + * by returning `false`. For instance, a conditional request may check the stat + * results to determine if the file has been modified to return an appropriate`304` response: + * + * ```js + * const http2 = require('http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * function statCheck(stat, headers) { + * // Check the stat here... + * stream.respond({ ':status': 304 }); + * return false; // Cancel the send operation + * } + * stream.respondWithFile('/some/file', + * { 'content-type': 'text/plain; charset=utf-8' }, + * { statCheck }); + * }); + * ``` + * + * The `content-length` header field will be automatically set. + * + * The `offset` and `length` options may be used to limit the response to a + * specific range subset. This can be used, for instance, to support HTTP Range + * requests. + * + * The `options.onError` function may also be used to handle all the errors + * that could happen before the delivery of the file is initiated. The + * default behavior is to destroy the stream. + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * will be emitted immediately after queuing the last chunk of payload data to be + * sent. The `http2stream.sendTrailers()` method can then be used to sent trailing + * header fields to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code must call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. + * + * ```js + * const http2 = require('http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respondWithFile('/some/file', + * { 'content-type': 'text/plain; charset=utf-8' }, + * { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ ABC: 'some value to send' }); + * }); + * }); + * ``` + * @since v8.4.0 + */ + respondWithFile( + path: string, + headers?: OutgoingHttpHeaders, + options?: ServerStreamFileResponseOptionsWithError, + ): void; + } + // Http2Session + export interface Settings { + headerTableSize?: number | undefined; + enablePush?: boolean | undefined; + initialWindowSize?: number | undefined; + maxFrameSize?: number | undefined; + maxConcurrentStreams?: number | undefined; + maxHeaderListSize?: number | undefined; + enableConnectProtocol?: boolean | undefined; + } + export interface ClientSessionRequestOptions { + endStream?: boolean | undefined; + exclusive?: boolean | undefined; + parent?: number | undefined; + weight?: number | undefined; + waitForTrailers?: boolean | undefined; + signal?: AbortSignal | undefined; + } + export interface SessionState { + effectiveLocalWindowSize?: number | undefined; + effectiveRecvDataLength?: number | undefined; + nextStreamID?: number | undefined; + localWindowSize?: number | undefined; + lastProcStreamID?: number | undefined; + remoteWindowSize?: number | undefined; + outboundQueueSize?: number | undefined; + deflateDynamicTableSize?: number | undefined; + inflateDynamicTableSize?: number | undefined; + } + export interface Http2Session extends EventEmitter { + /** + * Value will be `undefined` if the `Http2Session` is not yet connected to a + * socket, `h2c` if the `Http2Session` is not connected to a `TLSSocket`, or + * will return the value of the connected `TLSSocket`'s own `alpnProtocol`property. + * @since v9.4.0 + */ + readonly alpnProtocol?: string | undefined; + /** + * Will be `true` if this `Http2Session` instance has been closed, otherwise`false`. + * @since v9.4.0 + */ + readonly closed: boolean; + /** + * Will be `true` if this `Http2Session` instance is still connecting, will be set + * to `false` before emitting `connect` event and/or calling the `http2.connect`callback. + * @since v10.0.0 + */ + readonly connecting: boolean; + /** + * Will be `true` if this `Http2Session` instance has been destroyed and must no + * longer be used, otherwise `false`. + * @since v8.4.0 + */ + readonly destroyed: boolean; + /** + * Value is `undefined` if the `Http2Session` session socket has not yet been + * connected, `true` if the `Http2Session` is connected with a `TLSSocket`, + * and `false` if the `Http2Session` is connected to any other kind of socket + * or stream. + * @since v9.4.0 + */ + readonly encrypted?: boolean | undefined; + /** + * A prototype-less object describing the current local settings of this`Http2Session`. The local settings are local to _this_`Http2Session` instance. + * @since v8.4.0 + */ + readonly localSettings: Settings; + /** + * If the `Http2Session` is connected to a `TLSSocket`, the `originSet` property + * will return an `Array` of origins for which the `Http2Session` may be + * considered authoritative. + * + * The `originSet` property is only available when using a secure TLS connection. + * @since v9.4.0 + */ + readonly originSet?: string[] | undefined; + /** + * Indicates whether the `Http2Session` is currently waiting for acknowledgment of + * a sent `SETTINGS` frame. Will be `true` after calling the`http2session.settings()` method. Will be `false` once all sent `SETTINGS`frames have been acknowledged. + * @since v8.4.0 + */ + readonly pendingSettingsAck: boolean; + /** + * A prototype-less object describing the current remote settings of this`Http2Session`. The remote settings are set by the _connected_ HTTP/2 peer. + * @since v8.4.0 + */ + readonly remoteSettings: Settings; + /** + * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but + * limits available methods to ones safe to use with HTTP/2. + * + * `destroy`, `emit`, `end`, `pause`, `read`, `resume`, and `write` will throw + * an error with code `ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for more information. + * + * `setTimeout` method will be called on this `Http2Session`. + * + * All other interactions will be routed directly to the socket. + * @since v8.4.0 + */ + readonly socket: net.Socket | tls.TLSSocket; + /** + * Provides miscellaneous information about the current state of the`Http2Session`. + * + * An object describing the current status of this `Http2Session`. + * @since v8.4.0 + */ + readonly state: SessionState; + /** + * The `http2session.type` will be equal to`http2.constants.NGHTTP2_SESSION_SERVER` if this `Http2Session` instance is a + * server, and `http2.constants.NGHTTP2_SESSION_CLIENT` if the instance is a + * client. + * @since v8.4.0 + */ + readonly type: number; + /** + * Gracefully closes the `Http2Session`, allowing any existing streams to + * complete on their own and preventing new `Http2Stream` instances from being + * created. Once closed, `http2session.destroy()`_might_ be called if there + * are no open `Http2Stream` instances. + * + * If specified, the `callback` function is registered as a handler for the`'close'` event. + * @since v9.4.0 + */ + close(callback?: () => void): void; + /** + * Immediately terminates the `Http2Session` and the associated `net.Socket` or`tls.TLSSocket`. + * + * Once destroyed, the `Http2Session` will emit the `'close'` event. If `error`is not undefined, an `'error'` event will be emitted immediately before the`'close'` event. + * + * If there are any remaining open `Http2Streams` associated with the`Http2Session`, those will also be destroyed. + * @since v8.4.0 + * @param error An `Error` object if the `Http2Session` is being destroyed due to an error. + * @param code The HTTP/2 error code to send in the final `GOAWAY` frame. If unspecified, and `error` is not undefined, the default is `INTERNAL_ERROR`, otherwise defaults to `NO_ERROR`. + */ + destroy(error?: Error, code?: number): void; + /** + * Transmits a `GOAWAY` frame to the connected peer _without_ shutting down the`Http2Session`. + * @since v9.4.0 + * @param code An HTTP/2 error code + * @param lastStreamID The numeric ID of the last processed `Http2Stream` + * @param opaqueData A `TypedArray` or `DataView` instance containing additional data to be carried within the `GOAWAY` frame. + */ + goaway(code?: number, lastStreamID?: number, opaqueData?: NodeJS.ArrayBufferView): void; + /** + * Sends a `PING` frame to the connected HTTP/2 peer. A `callback` function must + * be provided. The method will return `true` if the `PING` was sent, `false`otherwise. + * + * The maximum number of outstanding (unacknowledged) pings is determined by the`maxOutstandingPings` configuration option. The default maximum is 10. + * + * If provided, the `payload` must be a `Buffer`, `TypedArray`, or `DataView`containing 8 bytes of data that will be transmitted with the `PING` and + * returned with the ping acknowledgment. + * + * The callback will be invoked with three arguments: an error argument that will + * be `null` if the `PING` was successfully acknowledged, a `duration` argument + * that reports the number of milliseconds elapsed since the ping was sent and the + * acknowledgment was received, and a `Buffer` containing the 8-byte `PING`payload. + * + * ```js + * session.ping(Buffer.from('abcdefgh'), (err, duration, payload) => { + * if (!err) { + * console.log(`Ping acknowledged in ${duration} milliseconds`); + * console.log(`With payload '${payload.toString()}'`); + * } + * }); + * ``` + * + * If the `payload` argument is not specified, the default payload will be the + * 64-bit timestamp (little endian) marking the start of the `PING` duration. + * @since v8.9.3 + * @param payload Optional ping payload. + */ + ping(callback: (err: Error | null, duration: number, payload: Buffer) => void): boolean; + ping( + payload: NodeJS.ArrayBufferView, + callback: (err: Error | null, duration: number, payload: Buffer) => void, + ): boolean; + /** + * Calls `ref()` on this `Http2Session`instance's underlying `net.Socket`. + * @since v9.4.0 + */ + ref(): void; + /** + * Sets the local endpoint's window size. + * The `windowSize` is the total window size to set, not + * the delta. + * + * ```js + * const http2 = require('http2'); + * + * const server = http2.createServer(); + * const expectedWindowSize = 2 ** 20; + * server.on('connect', (session) => { + * + * // Set local window size to be 2 ** 20 + * session.setLocalWindowSize(expectedWindowSize); + * }); + * ``` + * @since v15.3.0, v14.18.0 + */ + setLocalWindowSize(windowSize: number): void; + /** + * Used to set a callback function that is called when there is no activity on + * the `Http2Session` after `msecs` milliseconds. The given `callback` is + * registered as a listener on the `'timeout'` event. + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + /** + * Updates the current local settings for this `Http2Session` and sends a new`SETTINGS` frame to the connected HTTP/2 peer. + * + * Once called, the `http2session.pendingSettingsAck` property will be `true`while the session is waiting for the remote peer to acknowledge the new + * settings. + * + * The new settings will not become effective until the `SETTINGS` acknowledgment + * is received and the `'localSettings'` event is emitted. It is possible to send + * multiple `SETTINGS` frames while acknowledgment is still pending. + * @since v8.4.0 + * @param callback Callback that is called once the session is connected or right away if the session is already connected. + */ + settings( + settings: Settings, + callback?: (err: Error | null, settings: Settings, duration: number) => void, + ): void; + /** + * Calls `unref()` on this `Http2Session`instance's underlying `net.Socket`. + * @since v9.4.0 + */ + unref(): void; + addListener(event: "close", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener( + event: "frameError", + listener: (frameType: number, errorCode: number, streamID: number) => void, + ): this; + addListener( + event: "goaway", + listener: (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => void, + ): this; + addListener(event: "localSettings", listener: (settings: Settings) => void): this; + addListener(event: "ping", listener: () => void): this; + addListener(event: "remoteSettings", listener: (settings: Settings) => void): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "close"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "frameError", frameType: number, errorCode: number, streamID: number): boolean; + emit(event: "goaway", errorCode: number, lastStreamID: number, opaqueData?: Buffer): boolean; + emit(event: "localSettings", settings: Settings): boolean; + emit(event: "ping"): boolean; + emit(event: "remoteSettings", settings: Settings): boolean; + emit(event: "timeout"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "close", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; + on(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => void): this; + on(event: "localSettings", listener: (settings: Settings) => void): this; + on(event: "ping", listener: () => void): this; + on(event: "remoteSettings", listener: (settings: Settings) => void): this; + on(event: "timeout", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; + once(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => void): this; + once(event: "localSettings", listener: (settings: Settings) => void): this; + once(event: "ping", listener: () => void): this; + once(event: "remoteSettings", listener: (settings: Settings) => void): this; + once(event: "timeout", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener( + event: "frameError", + listener: (frameType: number, errorCode: number, streamID: number) => void, + ): this; + prependListener( + event: "goaway", + listener: (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => void, + ): this; + prependListener(event: "localSettings", listener: (settings: Settings) => void): this; + prependListener(event: "ping", listener: () => void): this; + prependListener(event: "remoteSettings", listener: (settings: Settings) => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener( + event: "frameError", + listener: (frameType: number, errorCode: number, streamID: number) => void, + ): this; + prependOnceListener( + event: "goaway", + listener: (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => void, + ): this; + prependOnceListener(event: "localSettings", listener: (settings: Settings) => void): this; + prependOnceListener(event: "ping", listener: () => void): this; + prependOnceListener(event: "remoteSettings", listener: (settings: Settings) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface ClientHttp2Session extends Http2Session { + /** + * For HTTP/2 Client `Http2Session` instances only, the `http2session.request()`creates and returns an `Http2Stream` instance that can be used to send an + * HTTP/2 request to the connected server. + * + * When a `ClientHttp2Session` is first created, the socket may not yet be + * connected. if `clienthttp2session.request()` is called during this time, the + * actual request will be deferred until the socket is ready to go. + * If the `session` is closed before the actual request be executed, an`ERR_HTTP2_GOAWAY_SESSION` is thrown. + * + * This method is only available if `http2session.type` is equal to`http2.constants.NGHTTP2_SESSION_CLIENT`. + * + * ```js + * const http2 = require('http2'); + * const clientSession = http2.connect('https://localhost:1234'); + * const { + * HTTP2_HEADER_PATH, + * HTTP2_HEADER_STATUS + * } = http2.constants; + * + * const req = clientSession.request({ [HTTP2_HEADER_PATH]: '/' }); + * req.on('response', (headers) => { + * console.log(headers[HTTP2_HEADER_STATUS]); + * req.on('data', (chunk) => { // .. }); + * req.on('end', () => { // .. }); + * }); + * ``` + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * is emitted immediately after queuing the last chunk of payload data to be sent. + * The `http2stream.sendTrailers()` method can then be called to send trailing + * headers to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code must call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. + * + * When `options.signal` is set with an `AbortSignal` and then `abort` on the + * corresponding `AbortController` is called, the request will emit an `'error'`event with an `AbortError` error. + * + * The `:method` and `:path` pseudo-headers are not specified within `headers`, + * they respectively default to: + * + * * `:method` \= `'GET'` + * * `:path` \= `/` + * @since v8.4.0 + */ + request(headers?: OutgoingHttpHeaders, options?: ClientSessionRequestOptions): ClientHttp2Stream; + addListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + addListener(event: "origin", listener: (origins: string[]) => void): this; + addListener( + event: "connect", + listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + addListener( + event: "stream", + listener: ( + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + ) => void, + ): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "altsvc", alt: string, origin: string, stream: number): boolean; + emit(event: "origin", origins: readonly string[]): boolean; + emit(event: "connect", session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket): boolean; + emit( + event: "stream", + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + ): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + on(event: "origin", listener: (origins: string[]) => void): this; + on(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + on( + event: "stream", + listener: ( + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + ) => void, + ): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + once(event: "origin", listener: (origins: string[]) => void): this; + once( + event: "connect", + listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + once( + event: "stream", + listener: ( + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + ) => void, + ): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + prependListener(event: "origin", listener: (origins: string[]) => void): this; + prependListener( + event: "connect", + listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + prependListener( + event: "stream", + listener: ( + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + ) => void, + ): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + prependOnceListener(event: "origin", listener: (origins: string[]) => void): this; + prependOnceListener( + event: "connect", + listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + prependOnceListener( + event: "stream", + listener: ( + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + ) => void, + ): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface AlternativeServiceOptions { + origin: number | string | url.URL; + } + export interface ServerHttp2Session extends Http2Session { + readonly server: Http2Server | Http2SecureServer; + /** + * Submits an `ALTSVC` frame (as defined by [RFC 7838](https://tools.ietf.org/html/rfc7838)) to the connected client. + * + * ```js + * const http2 = require('http2'); + * + * const server = http2.createServer(); + * server.on('session', (session) => { + * // Set altsvc for origin https://example.org:80 + * session.altsvc('h2=":8000"', 'https://example.org:80'); + * }); + * + * server.on('stream', (stream) => { + * // Set altsvc for a specific stream + * stream.session.altsvc('h2=":8000"', stream.id); + * }); + * ``` + * + * Sending an `ALTSVC` frame with a specific stream ID indicates that the alternate + * service is associated with the origin of the given `Http2Stream`. + * + * The `alt` and origin string _must_ contain only ASCII bytes and are + * strictly interpreted as a sequence of ASCII bytes. The special value `'clear'`may be passed to clear any previously set alternative service for a given + * domain. + * + * When a string is passed for the `originOrStream` argument, it will be parsed as + * a URL and the origin will be derived. For instance, the origin for the + * HTTP URL `'https://example.org/foo/bar'` is the ASCII string`'https://example.org'`. An error will be thrown if either the given string + * cannot be parsed as a URL or if a valid origin cannot be derived. + * + * A `URL` object, or any object with an `origin` property, may be passed as`originOrStream`, in which case the value of the `origin` property will be + * used. The value of the `origin` property _must_ be a properly serialized + * ASCII origin. + * @since v9.4.0 + * @param alt A description of the alternative service configuration as defined by `RFC 7838`. + * @param originOrStream Either a URL string specifying the origin (or an `Object` with an `origin` property) or the numeric identifier of an active `Http2Stream` as given by the + * `http2stream.id` property. + */ + altsvc(alt: string, originOrStream: number | string | url.URL | AlternativeServiceOptions): void; + /** + * Submits an `ORIGIN` frame (as defined by [RFC 8336](https://tools.ietf.org/html/rfc8336)) to the connected client + * to advertise the set of origins for which the server is capable of providing + * authoritative responses. + * + * ```js + * const http2 = require('http2'); + * const options = getSecureOptionsSomehow(); + * const server = http2.createSecureServer(options); + * server.on('stream', (stream) => { + * stream.respond(); + * stream.end('ok'); + * }); + * server.on('session', (session) => { + * session.origin('https://example.com', 'https://example.org'); + * }); + * ``` + * + * When a string is passed as an `origin`, it will be parsed as a URL and the + * origin will be derived. For instance, the origin for the HTTP URL`'https://example.org/foo/bar'` is the ASCII string`'https://example.org'`. An error will be thrown if either the given + * string + * cannot be parsed as a URL or if a valid origin cannot be derived. + * + * A `URL` object, or any object with an `origin` property, may be passed as + * an `origin`, in which case the value of the `origin` property will be + * used. The value of the `origin` property _must_ be a properly serialized + * ASCII origin. + * + * Alternatively, the `origins` option may be used when creating a new HTTP/2 + * server using the `http2.createSecureServer()` method: + * + * ```js + * const http2 = require('http2'); + * const options = getSecureOptionsSomehow(); + * options.origins = ['https://example.com', 'https://example.org']; + * const server = http2.createSecureServer(options); + * server.on('stream', (stream) => { + * stream.respond(); + * stream.end('ok'); + * }); + * ``` + * @since v10.12.0 + * @param origins One or more URL Strings passed as separate arguments. + */ + origin( + ...origins: Array< + | string + | url.URL + | { + origin: string; + } + > + ): void; + addListener( + event: "connect", + listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + addListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "connect", session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket): boolean; + emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + on( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once( + event: "connect", + listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + once( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + event: "connect", + listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + prependListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + event: "connect", + listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + prependOnceListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + // Http2Server + export interface SessionOptions { + maxDeflateDynamicTableSize?: number | undefined; + maxSessionMemory?: number | undefined; + maxHeaderListPairs?: number | undefined; + maxOutstandingPings?: number | undefined; + maxSendHeaderBlockLength?: number | undefined; + paddingStrategy?: number | undefined; + peerMaxConcurrentStreams?: number | undefined; + settings?: Settings | undefined; + /** + * Specifies a timeout in milliseconds that + * a server should wait when an [`'unknownProtocol'`][] is emitted. If the + * socket has not been destroyed by that time the server will destroy it. + * @default 100000 + */ + unknownProtocolTimeout?: number | undefined; + selectPadding?(frameLen: number, maxFrameLen: number): number; + } + export interface ClientSessionOptions extends SessionOptions { + maxReservedRemoteStreams?: number | undefined; + createConnection?: ((authority: url.URL, option: SessionOptions) => stream.Duplex) | undefined; + protocol?: "http:" | "https:" | undefined; + } + export interface ServerSessionOptions extends SessionOptions { + Http1IncomingMessage?: typeof IncomingMessage | undefined; + Http1ServerResponse?: typeof ServerResponse | undefined; + Http2ServerRequest?: typeof Http2ServerRequest | undefined; + Http2ServerResponse?: typeof Http2ServerResponse | undefined; + } + export interface SecureClientSessionOptions extends ClientSessionOptions, tls.ConnectionOptions {} + export interface SecureServerSessionOptions extends ServerSessionOptions, tls.TlsOptions {} + export interface ServerOptions extends ServerSessionOptions {} + export interface SecureServerOptions extends SecureServerSessionOptions { + allowHTTP1?: boolean | undefined; + origins?: string[] | undefined; + } + interface HTTP2ServerCommon { + setTimeout(msec?: number, callback?: () => void): this; + /** + * Throws ERR_HTTP2_INVALID_SETTING_VALUE for invalid settings values. + * Throws ERR_INVALID_ARG_TYPE for invalid settings argument. + */ + updateSettings(settings: Settings): void; + } + export interface Http2Server extends net.Server, HTTP2ServerCommon { + addListener( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + addListener( + event: "request", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + addListener(event: "session", listener: (session: ServerHttp2Session) => void): this; + addListener(event: "sessionError", listener: (err: Error) => void): this; + addListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "checkContinue", request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: "request", request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: "session", session: ServerHttp2Session): boolean; + emit(event: "sessionError", err: Error): boolean; + emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "timeout"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + on(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: "session", listener: (session: ServerHttp2Session) => void): this; + on(event: "sessionError", listener: (err: Error) => void): this; + on( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + on(event: "timeout", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + once(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: "session", listener: (session: ServerHttp2Session) => void): this; + once(event: "sessionError", listener: (err: Error) => void): this; + once( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + once(event: "timeout", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + prependListener( + event: "request", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + prependListener(event: "session", listener: (session: ServerHttp2Session) => void): this; + prependListener(event: "sessionError", listener: (err: Error) => void): this; + prependListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + prependOnceListener( + event: "request", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + prependOnceListener(event: "session", listener: (session: ServerHttp2Session) => void): this; + prependOnceListener(event: "sessionError", listener: (err: Error) => void): this; + prependOnceListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface Http2SecureServer extends tls.Server, HTTP2ServerCommon { + addListener( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + addListener( + event: "request", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + addListener(event: "session", listener: (session: ServerHttp2Session) => void): this; + addListener(event: "sessionError", listener: (err: Error) => void): this; + addListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "checkContinue", request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: "request", request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: "session", session: ServerHttp2Session): boolean; + emit(event: "sessionError", err: Error): boolean; + emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "timeout"): boolean; + emit(event: "unknownProtocol", socket: tls.TLSSocket): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + on(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: "session", listener: (session: ServerHttp2Session) => void): this; + on(event: "sessionError", listener: (err: Error) => void): this; + on( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + on(event: "timeout", listener: () => void): this; + on(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + once(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: "session", listener: (session: ServerHttp2Session) => void): this; + once(event: "sessionError", listener: (err: Error) => void): this; + once( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + once(event: "timeout", listener: () => void): this; + once(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + prependListener( + event: "request", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + prependListener(event: "session", listener: (session: ServerHttp2Session) => void): this; + prependListener(event: "sessionError", listener: (err: Error) => void): this; + prependListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + prependOnceListener( + event: "request", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + prependOnceListener(event: "session", listener: (session: ServerHttp2Session) => void): this; + prependOnceListener(event: "sessionError", listener: (err: Error) => void): this; + prependOnceListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * A `Http2ServerRequest` object is created by {@link Server} or {@link SecureServer} and passed as the first argument to the `'request'` event. It may be used to access a request status, + * headers, and + * data. + * @since v8.4.0 + */ + export class Http2ServerRequest extends stream.Readable { + constructor( + stream: ServerHttp2Stream, + headers: IncomingHttpHeaders, + options: stream.ReadableOptions, + rawHeaders: readonly string[], + ); + /** + * The `request.aborted` property will be `true` if the request has + * been aborted. + * @since v10.1.0 + */ + readonly aborted: boolean; + /** + * The request authority pseudo header field. Because HTTP/2 allows requests + * to set either `:authority` or `host`, this value is derived from`req.headers[':authority']` if present. Otherwise, it is derived from`req.headers['host']`. + * @since v8.4.0 + */ + readonly authority: string; + /** + * See `request.socket`. + * @since v8.4.0 + * @deprecated Since v13.0.0 - Use `socket`. + */ + readonly connection: net.Socket | tls.TLSSocket; + /** + * The `request.complete` property will be `true` if the request has + * been completed, aborted, or destroyed. + * @since v12.10.0 + */ + readonly complete: boolean; + /** + * The request/response headers object. + * + * Key-value pairs of header names and values. Header names are lower-cased. + * + * ```js + * // Prints something like: + * // + * // { 'user-agent': 'curl/7.22.0', + * // host: '127.0.0.1:8000', + * // accept: '*' } + * console.log(request.headers); + * ``` + * + * See `HTTP/2 Headers Object`. + * + * In HTTP/2, the request path, host name, protocol, and method are represented as + * special headers prefixed with the `:` character (e.g. `':path'`). These special + * headers will be included in the `request.headers` object. Care must be taken not + * to inadvertently modify these special headers or errors may occur. For instance, + * removing all headers from the request will cause errors to occur: + * + * ```js + * removeAllHeaders(request.headers); + * assert(request.url); // Fails because the :path header has been removed + * ``` + * @since v8.4.0 + */ + readonly headers: IncomingHttpHeaders; + /** + * In case of server request, the HTTP version sent by the client. In the case of + * client response, the HTTP version of the connected-to server. Returns`'2.0'`. + * + * Also `message.httpVersionMajor` is the first integer and`message.httpVersionMinor` is the second. + * @since v8.4.0 + */ + readonly httpVersion: string; + readonly httpVersionMinor: number; + readonly httpVersionMajor: number; + /** + * The request method as a string. Read-only. Examples: `'GET'`, `'DELETE'`. + * @since v8.4.0 + */ + readonly method: string; + /** + * The raw request/response headers list exactly as they were received. + * + * The keys and values are in the same list. It is _not_ a + * list of tuples. So, the even-numbered offsets are key values, and the + * odd-numbered offsets are the associated values. + * + * Header names are not lowercased, and duplicates are not merged. + * + * ```js + * // Prints something like: + * // + * // [ 'user-agent', + * // 'this is invalid because there can be only one', + * // 'User-Agent', + * // 'curl/7.22.0', + * // 'Host', + * // '127.0.0.1:8000', + * // 'ACCEPT', + * // '*' ] + * console.log(request.rawHeaders); + * ``` + * @since v8.4.0 + */ + readonly rawHeaders: string[]; + /** + * The raw request/response trailer keys and values exactly as they were + * received. Only populated at the `'end'` event. + * @since v8.4.0 + */ + readonly rawTrailers: string[]; + /** + * The request scheme pseudo header field indicating the scheme + * portion of the target URL. + * @since v8.4.0 + */ + readonly scheme: string; + /** + * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but + * applies getters, setters, and methods based on HTTP/2 logic. + * + * `destroyed`, `readable`, and `writable` properties will be retrieved from and + * set on `request.stream`. + * + * `destroy`, `emit`, `end`, `on` and `once` methods will be called on`request.stream`. + * + * `setTimeout` method will be called on `request.stream.session`. + * + * `pause`, `read`, `resume`, and `write` will throw an error with code`ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for + * more information. + * + * All other interactions will be routed directly to the socket. With TLS support, + * use `request.socket.getPeerCertificate()` to obtain the client's + * authentication details. + * @since v8.4.0 + */ + readonly socket: net.Socket | tls.TLSSocket; + /** + * The `Http2Stream` object backing the request. + * @since v8.4.0 + */ + readonly stream: ServerHttp2Stream; + /** + * The request/response trailers object. Only populated at the `'end'` event. + * @since v8.4.0 + */ + readonly trailers: IncomingHttpHeaders; + /** + * Request URL string. This contains only the URL that is present in the actual + * HTTP request. If the request is: + * + * ```http + * GET /status?name=ryan HTTP/1.1 + * Accept: text/plain + * ``` + * + * Then `request.url` will be: + * + * ```js + * '/status?name=ryan' + * ``` + * + * To parse the url into its parts, `new URL()` can be used: + * + * ```console + * $ node + * > new URL('/status?name=ryan', 'http://example.com') + * URL { + * href: 'http://example.com/status?name=ryan', + * origin: 'http://example.com', + * protocol: 'http:', + * username: '', + * password: '', + * host: 'example.com', + * hostname: 'example.com', + * port: '', + * pathname: '/status', + * search: '?name=ryan', + * searchParams: URLSearchParams { 'name' => 'ryan' }, + * hash: '' + * } + * ``` + * @since v8.4.0 + */ + url: string; + /** + * Sets the `Http2Stream`'s timeout value to `msecs`. If a callback is + * provided, then it is added as a listener on the `'timeout'` event on + * the response object. + * + * If no `'timeout'` listener is added to the request, the response, or + * the server, then `Http2Stream` s are destroyed when they time out. If a + * handler is assigned to the request, the response, or the server's `'timeout'`events, timed out sockets must be handled explicitly. + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + read(size?: number): Buffer | string | null; + addListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: Buffer | string) => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "aborted", hadError: boolean, code: number): boolean; + emit(event: "close"): boolean; + emit(event: "data", chunk: Buffer | string): boolean; + emit(event: "end"): boolean; + emit(event: "readable"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: Buffer | string) => void): this; + on(event: "end", listener: () => void): this; + on(event: "readable", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: Buffer | string) => void): this; + once(event: "end", listener: () => void): this; + once(event: "readable", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * This object is created internally by an HTTP server, not by the user. It is + * passed as the second parameter to the `'request'` event. + * @since v8.4.0 + */ + export class Http2ServerResponse extends stream.Writable { + constructor(stream: ServerHttp2Stream); + /** + * See `response.socket`. + * @since v8.4.0 + * @deprecated Since v13.0.0 - Use `socket`. + */ + readonly connection: net.Socket | tls.TLSSocket; + /** + * Boolean value that indicates whether the response has completed. Starts + * as `false`. After `response.end()` executes, the value will be `true`. + * @since v8.4.0 + * @deprecated Since v13.4.0,v12.16.0 - Use `writableEnded`. + */ + readonly finished: boolean; + /** + * True if headers were sent, false otherwise (read-only). + * @since v8.4.0 + */ + readonly headersSent: boolean; + /** + * A reference to the original HTTP2 request object. + * @since v15.7.0 + */ + readonly req: Http2ServerRequest; + /** + * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but + * applies getters, setters, and methods based on HTTP/2 logic. + * + * `destroyed`, `readable`, and `writable` properties will be retrieved from and + * set on `response.stream`. + * + * `destroy`, `emit`, `end`, `on` and `once` methods will be called on`response.stream`. + * + * `setTimeout` method will be called on `response.stream.session`. + * + * `pause`, `read`, `resume`, and `write` will throw an error with code`ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for + * more information. + * + * All other interactions will be routed directly to the socket. + * + * ```js + * const http2 = require('http2'); + * const server = http2.createServer((req, res) => { + * const ip = req.socket.remoteAddress; + * const port = req.socket.remotePort; + * res.end(`Your IP address is ${ip} and your source port is ${port}.`); + * }).listen(3000); + * ``` + * @since v8.4.0 + */ + readonly socket: net.Socket | tls.TLSSocket; + /** + * The `Http2Stream` object backing the response. + * @since v8.4.0 + */ + readonly stream: ServerHttp2Stream; + /** + * When true, the Date header will be automatically generated and sent in + * the response if it is not already present in the headers. Defaults to true. + * + * This should only be disabled for testing; HTTP requires the Date header + * in responses. + * @since v8.4.0 + */ + sendDate: boolean; + /** + * When using implicit headers (not calling `response.writeHead()` explicitly), + * this property controls the status code that will be sent to the client when + * the headers get flushed. + * + * ```js + * response.statusCode = 404; + * ``` + * + * After response header was sent to the client, this property indicates the + * status code which was sent out. + * @since v8.4.0 + */ + statusCode: number; + /** + * Status message is not supported by HTTP/2 (RFC 7540 8.1.2.4). It returns + * an empty string. + * @since v8.4.0 + */ + statusMessage: ""; + /** + * This method adds HTTP trailing headers (a header but at the end of the + * message) to the response. + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v8.4.0 + */ + addTrailers(trailers: OutgoingHttpHeaders): void; + /** + * This method signals to the server that all of the response headers and body + * have been sent; that server should consider this message complete. + * The method, `response.end()`, MUST be called on each response. + * + * If `data` is specified, it is equivalent to calling `response.write(data, encoding)` followed by `response.end(callback)`. + * + * If `callback` is specified, it will be called when the response stream + * is finished. + * @since v8.4.0 + */ + end(callback?: () => void): this; + end(data: string | Uint8Array, callback?: () => void): this; + end(data: string | Uint8Array, encoding: BufferEncoding, callback?: () => void): this; + /** + * Reads out a header that has already been queued but not sent to the client. + * The name is case-insensitive. + * + * ```js + * const contentType = response.getHeader('content-type'); + * ``` + * @since v8.4.0 + */ + getHeader(name: string): string; + /** + * Returns an array containing the unique names of the current outgoing headers. + * All header names are lowercase. + * + * ```js + * response.setHeader('Foo', 'bar'); + * response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headerNames = response.getHeaderNames(); + * // headerNames === ['foo', 'set-cookie'] + * ``` + * @since v8.4.0 + */ + getHeaderNames(): string[]; + /** + * Returns a shallow copy of the current outgoing headers. Since a shallow copy + * is used, array values may be mutated without additional calls to various + * header-related http module methods. The keys of the returned object are the + * header names and the values are the respective header values. All header names + * are lowercase. + * + * The object returned by the `response.getHeaders()` method _does not_prototypically inherit from the JavaScript `Object`. This means that typical`Object` methods such as `obj.toString()`, + * `obj.hasOwnProperty()`, and others + * are not defined and _will not work_. + * + * ```js + * response.setHeader('Foo', 'bar'); + * response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headers = response.getHeaders(); + * // headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] } + * ``` + * @since v8.4.0 + */ + getHeaders(): OutgoingHttpHeaders; + /** + * Returns `true` if the header identified by `name` is currently set in the + * outgoing headers. The header name matching is case-insensitive. + * + * ```js + * const hasContentType = response.hasHeader('content-type'); + * ``` + * @since v8.4.0 + */ + hasHeader(name: string): boolean; + /** + * Removes a header that has been queued for implicit sending. + * + * ```js + * response.removeHeader('Content-Encoding'); + * ``` + * @since v8.4.0 + */ + removeHeader(name: string): void; + /** + * Sets a single header value for implicit headers. If this header already exists + * in the to-be-sent headers, its value will be replaced. Use an array of strings + * here to send multiple headers with the same name. + * + * ```js + * response.setHeader('Content-Type', 'text/html; charset=utf-8'); + * ``` + * + * or + * + * ```js + * response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']); + * ``` + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * + * When headers have been set with `response.setHeader()`, they will be merged + * with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * ```js + * // Returns content-type = text/plain + * const server = http2.createServer((req, res) => { + * res.setHeader('Content-Type', 'text/html; charset=utf-8'); + * res.setHeader('X-Foo', 'bar'); + * res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); + * res.end('ok'); + * }); + * ``` + * @since v8.4.0 + */ + setHeader(name: string, value: number | string | readonly string[]): void; + /** + * Sets the `Http2Stream`'s timeout value to `msecs`. If a callback is + * provided, then it is added as a listener on the `'timeout'` event on + * the response object. + * + * If no `'timeout'` listener is added to the request, the response, or + * the server, then `Http2Stream` s are destroyed when they time out. If a + * handler is assigned to the request, the response, or the server's `'timeout'`events, timed out sockets must be handled explicitly. + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + /** + * If this method is called and `response.writeHead()` has not been called, + * it will switch to implicit header mode and flush the implicit headers. + * + * This sends a chunk of the response body. This method may + * be called multiple times to provide successive parts of the body. + * + * In the `http` module, the response body is omitted when the + * request is a HEAD request. Similarly, the `204` and `304` responses _must not_ include a message body. + * + * `chunk` can be a string or a buffer. If `chunk` is a string, + * the second parameter specifies how to encode it into a byte stream. + * By default the `encoding` is `'utf8'`. `callback` will be called when this chunk + * of data is flushed. + * + * This is the raw HTTP body and has nothing to do with higher-level multi-part + * body encodings that may be used. + * + * The first time `response.write()` is called, it will send the buffered + * header information and the first chunk of the body to the client. The second + * time `response.write()` is called, Node.js assumes data will be streamed, + * and sends the new data separately. That is, the response is buffered up to the + * first chunk of the body. + * + * Returns `true` if the entire data was flushed successfully to the kernel + * buffer. Returns `false` if all or part of the data was queued in user memory.`'drain'` will be emitted when the buffer is free again. + * @since v8.4.0 + */ + write(chunk: string | Uint8Array, callback?: (err: Error) => void): boolean; + write(chunk: string | Uint8Array, encoding: BufferEncoding, callback?: (err: Error) => void): boolean; + /** + * Sends a status `100 Continue` to the client, indicating that the request body + * should be sent. See the `'checkContinue'` event on `Http2Server` and`Http2SecureServer`. + * @since v8.4.0 + */ + writeContinue(): void; + /** + * Sends a status `103 Early Hints` to the client with a Link header, + * indicating that the user agent can preload/preconnect the linked resources. + * The `hints` is an object containing the values of headers to be sent with + * early hints message. + * + * Example: + * + * ```js + * const earlyHintsLink = '; rel=preload; as=style'; + * response.writeEarlyHints({ + * 'link': earlyHintsLink, + * }); + * + * const earlyHintsLinks = [ + * '; rel=preload; as=style', + * '; rel=preload; as=script', + * ]; + * response.writeEarlyHints({ + * 'link': earlyHintsLinks, + * 'x-trace-id': 'id for diagnostics' + * }); + * ``` + * + * @since v18.11.0 + * @param hints An object containing the values of headers + */ + writeEarlyHints(hints: Record): void; + /** + * Sends a response header to the request. The status code is a 3-digit HTTP + * status code, like `404`. The last argument, `headers`, are the response headers. + * + * Returns a reference to the `Http2ServerResponse`, so that calls can be chained. + * + * For compatibility with `HTTP/1`, a human-readable `statusMessage` may be + * passed as the second argument. However, because the `statusMessage` has no + * meaning within HTTP/2, the argument will have no effect and a process warning + * will be emitted. + * + * ```js + * const body = 'hello world'; + * response.writeHead(200, { + * 'Content-Length': Buffer.byteLength(body), + * 'Content-Type': 'text/plain; charset=utf-8', + * }); + * ``` + * + * `Content-Length` is given in bytes not characters. The`Buffer.byteLength()` API may be used to determine the number of bytes in a + * given encoding. On outbound messages, Node.js does not check if Content-Length + * and the length of the body being transmitted are equal or not. However, when + * receiving messages, Node.js will automatically reject messages when the`Content-Length` does not match the actual payload size. + * + * This method may be called at most one time on a message before `response.end()` is called. + * + * If `response.write()` or `response.end()` are called before calling + * this, the implicit/mutable headers will be calculated and call this function. + * + * When headers have been set with `response.setHeader()`, they will be merged + * with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * ```js + * // Returns content-type = text/plain + * const server = http2.createServer((req, res) => { + * res.setHeader('Content-Type', 'text/html; charset=utf-8'); + * res.setHeader('X-Foo', 'bar'); + * res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); + * res.end('ok'); + * }); + * ``` + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v8.4.0 + */ + writeHead(statusCode: number, headers?: OutgoingHttpHeaders): this; + writeHead(statusCode: number, statusMessage: string, headers?: OutgoingHttpHeaders): this; + /** + * Call `http2stream.pushStream()` with the given headers, and wrap the + * given `Http2Stream` on a newly created `Http2ServerResponse` as the callback + * parameter if successful. When `Http2ServerRequest` is closed, the callback is + * called with an error `ERR_HTTP2_INVALID_STREAM`. + * @since v8.4.0 + * @param headers An object describing the headers + * @param callback Called once `http2stream.pushStream()` is finished, or either when the attempt to create the pushed `Http2Stream` has failed or has been rejected, or the state of + * `Http2ServerRequest` is closed prior to calling the `http2stream.pushStream()` method + */ + createPushResponse( + headers: OutgoingHttpHeaders, + callback: (err: Error | null, res: Http2ServerResponse) => void, + ): void; + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (error: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "pipe", listener: (src: stream.Readable) => void): this; + addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "close"): boolean; + emit(event: "drain"): boolean; + emit(event: "error", error: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "pipe", src: stream.Readable): boolean; + emit(event: "unpipe", src: stream.Readable): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (error: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pipe", listener: (src: stream.Readable) => void): this; + on(event: "unpipe", listener: (src: stream.Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (error: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pipe", listener: (src: stream.Readable) => void): this; + once(event: "unpipe", listener: (src: stream.Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (error: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (error: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export namespace constants { + const NGHTTP2_SESSION_SERVER: number; + const NGHTTP2_SESSION_CLIENT: number; + const NGHTTP2_STREAM_STATE_IDLE: number; + const NGHTTP2_STREAM_STATE_OPEN: number; + const NGHTTP2_STREAM_STATE_RESERVED_LOCAL: number; + const NGHTTP2_STREAM_STATE_RESERVED_REMOTE: number; + const NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL: number; + const NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE: number; + const NGHTTP2_STREAM_STATE_CLOSED: number; + const NGHTTP2_NO_ERROR: number; + const NGHTTP2_PROTOCOL_ERROR: number; + const NGHTTP2_INTERNAL_ERROR: number; + const NGHTTP2_FLOW_CONTROL_ERROR: number; + const NGHTTP2_SETTINGS_TIMEOUT: number; + const NGHTTP2_STREAM_CLOSED: number; + const NGHTTP2_FRAME_SIZE_ERROR: number; + const NGHTTP2_REFUSED_STREAM: number; + const NGHTTP2_CANCEL: number; + const NGHTTP2_COMPRESSION_ERROR: number; + const NGHTTP2_CONNECT_ERROR: number; + const NGHTTP2_ENHANCE_YOUR_CALM: number; + const NGHTTP2_INADEQUATE_SECURITY: number; + const NGHTTP2_HTTP_1_1_REQUIRED: number; + const NGHTTP2_ERR_FRAME_SIZE_ERROR: number; + const NGHTTP2_FLAG_NONE: number; + const NGHTTP2_FLAG_END_STREAM: number; + const NGHTTP2_FLAG_END_HEADERS: number; + const NGHTTP2_FLAG_ACK: number; + const NGHTTP2_FLAG_PADDED: number; + const NGHTTP2_FLAG_PRIORITY: number; + const DEFAULT_SETTINGS_HEADER_TABLE_SIZE: number; + const DEFAULT_SETTINGS_ENABLE_PUSH: number; + const DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE: number; + const DEFAULT_SETTINGS_MAX_FRAME_SIZE: number; + const MAX_MAX_FRAME_SIZE: number; + const MIN_MAX_FRAME_SIZE: number; + const MAX_INITIAL_WINDOW_SIZE: number; + const NGHTTP2_DEFAULT_WEIGHT: number; + const NGHTTP2_SETTINGS_HEADER_TABLE_SIZE: number; + const NGHTTP2_SETTINGS_ENABLE_PUSH: number; + const NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS: number; + const NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE: number; + const NGHTTP2_SETTINGS_MAX_FRAME_SIZE: number; + const NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE: number; + const PADDING_STRATEGY_NONE: number; + const PADDING_STRATEGY_MAX: number; + const PADDING_STRATEGY_CALLBACK: number; + const HTTP2_HEADER_STATUS: string; + const HTTP2_HEADER_METHOD: string; + const HTTP2_HEADER_AUTHORITY: string; + const HTTP2_HEADER_SCHEME: string; + const HTTP2_HEADER_PATH: string; + const HTTP2_HEADER_ACCEPT_CHARSET: string; + const HTTP2_HEADER_ACCEPT_ENCODING: string; + const HTTP2_HEADER_ACCEPT_LANGUAGE: string; + const HTTP2_HEADER_ACCEPT_RANGES: string; + const HTTP2_HEADER_ACCEPT: string; + const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_CREDENTIALS: string; + const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_HEADERS: string; + const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_METHODS: string; + const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN: string; + const HTTP2_HEADER_ACCESS_CONTROL_EXPOSE_HEADERS: string; + const HTTP2_HEADER_ACCESS_CONTROL_REQUEST_HEADERS: string; + const HTTP2_HEADER_ACCESS_CONTROL_REQUEST_METHOD: string; + const HTTP2_HEADER_AGE: string; + const HTTP2_HEADER_ALLOW: string; + const HTTP2_HEADER_AUTHORIZATION: string; + const HTTP2_HEADER_CACHE_CONTROL: string; + const HTTP2_HEADER_CONNECTION: string; + const HTTP2_HEADER_CONTENT_DISPOSITION: string; + const HTTP2_HEADER_CONTENT_ENCODING: string; + const HTTP2_HEADER_CONTENT_LANGUAGE: string; + const HTTP2_HEADER_CONTENT_LENGTH: string; + const HTTP2_HEADER_CONTENT_LOCATION: string; + const HTTP2_HEADER_CONTENT_MD5: string; + const HTTP2_HEADER_CONTENT_RANGE: string; + const HTTP2_HEADER_CONTENT_TYPE: string; + const HTTP2_HEADER_COOKIE: string; + const HTTP2_HEADER_DATE: string; + const HTTP2_HEADER_ETAG: string; + const HTTP2_HEADER_EXPECT: string; + const HTTP2_HEADER_EXPIRES: string; + const HTTP2_HEADER_FROM: string; + const HTTP2_HEADER_HOST: string; + const HTTP2_HEADER_IF_MATCH: string; + const HTTP2_HEADER_IF_MODIFIED_SINCE: string; + const HTTP2_HEADER_IF_NONE_MATCH: string; + const HTTP2_HEADER_IF_RANGE: string; + const HTTP2_HEADER_IF_UNMODIFIED_SINCE: string; + const HTTP2_HEADER_LAST_MODIFIED: string; + const HTTP2_HEADER_LINK: string; + const HTTP2_HEADER_LOCATION: string; + const HTTP2_HEADER_MAX_FORWARDS: string; + const HTTP2_HEADER_PREFER: string; + const HTTP2_HEADER_PROXY_AUTHENTICATE: string; + const HTTP2_HEADER_PROXY_AUTHORIZATION: string; + const HTTP2_HEADER_RANGE: string; + const HTTP2_HEADER_REFERER: string; + const HTTP2_HEADER_REFRESH: string; + const HTTP2_HEADER_RETRY_AFTER: string; + const HTTP2_HEADER_SERVER: string; + const HTTP2_HEADER_SET_COOKIE: string; + const HTTP2_HEADER_STRICT_TRANSPORT_SECURITY: string; + const HTTP2_HEADER_TRANSFER_ENCODING: string; + const HTTP2_HEADER_TE: string; + const HTTP2_HEADER_UPGRADE: string; + const HTTP2_HEADER_USER_AGENT: string; + const HTTP2_HEADER_VARY: string; + const HTTP2_HEADER_VIA: string; + const HTTP2_HEADER_WWW_AUTHENTICATE: string; + const HTTP2_HEADER_HTTP2_SETTINGS: string; + const HTTP2_HEADER_KEEP_ALIVE: string; + const HTTP2_HEADER_PROXY_CONNECTION: string; + const HTTP2_METHOD_ACL: string; + const HTTP2_METHOD_BASELINE_CONTROL: string; + const HTTP2_METHOD_BIND: string; + const HTTP2_METHOD_CHECKIN: string; + const HTTP2_METHOD_CHECKOUT: string; + const HTTP2_METHOD_CONNECT: string; + const HTTP2_METHOD_COPY: string; + const HTTP2_METHOD_DELETE: string; + const HTTP2_METHOD_GET: string; + const HTTP2_METHOD_HEAD: string; + const HTTP2_METHOD_LABEL: string; + const HTTP2_METHOD_LINK: string; + const HTTP2_METHOD_LOCK: string; + const HTTP2_METHOD_MERGE: string; + const HTTP2_METHOD_MKACTIVITY: string; + const HTTP2_METHOD_MKCALENDAR: string; + const HTTP2_METHOD_MKCOL: string; + const HTTP2_METHOD_MKREDIRECTREF: string; + const HTTP2_METHOD_MKWORKSPACE: string; + const HTTP2_METHOD_MOVE: string; + const HTTP2_METHOD_OPTIONS: string; + const HTTP2_METHOD_ORDERPATCH: string; + const HTTP2_METHOD_PATCH: string; + const HTTP2_METHOD_POST: string; + const HTTP2_METHOD_PRI: string; + const HTTP2_METHOD_PROPFIND: string; + const HTTP2_METHOD_PROPPATCH: string; + const HTTP2_METHOD_PUT: string; + const HTTP2_METHOD_REBIND: string; + const HTTP2_METHOD_REPORT: string; + const HTTP2_METHOD_SEARCH: string; + const HTTP2_METHOD_TRACE: string; + const HTTP2_METHOD_UNBIND: string; + const HTTP2_METHOD_UNCHECKOUT: string; + const HTTP2_METHOD_UNLINK: string; + const HTTP2_METHOD_UNLOCK: string; + const HTTP2_METHOD_UPDATE: string; + const HTTP2_METHOD_UPDATEREDIRECTREF: string; + const HTTP2_METHOD_VERSION_CONTROL: string; + const HTTP_STATUS_CONTINUE: number; + const HTTP_STATUS_SWITCHING_PROTOCOLS: number; + const HTTP_STATUS_PROCESSING: number; + const HTTP_STATUS_OK: number; + const HTTP_STATUS_CREATED: number; + const HTTP_STATUS_ACCEPTED: number; + const HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION: number; + const HTTP_STATUS_NO_CONTENT: number; + const HTTP_STATUS_RESET_CONTENT: number; + const HTTP_STATUS_PARTIAL_CONTENT: number; + const HTTP_STATUS_MULTI_STATUS: number; + const HTTP_STATUS_ALREADY_REPORTED: number; + const HTTP_STATUS_IM_USED: number; + const HTTP_STATUS_MULTIPLE_CHOICES: number; + const HTTP_STATUS_MOVED_PERMANENTLY: number; + const HTTP_STATUS_FOUND: number; + const HTTP_STATUS_SEE_OTHER: number; + const HTTP_STATUS_NOT_MODIFIED: number; + const HTTP_STATUS_USE_PROXY: number; + const HTTP_STATUS_TEMPORARY_REDIRECT: number; + const HTTP_STATUS_PERMANENT_REDIRECT: number; + const HTTP_STATUS_BAD_REQUEST: number; + const HTTP_STATUS_UNAUTHORIZED: number; + const HTTP_STATUS_PAYMENT_REQUIRED: number; + const HTTP_STATUS_FORBIDDEN: number; + const HTTP_STATUS_NOT_FOUND: number; + const HTTP_STATUS_METHOD_NOT_ALLOWED: number; + const HTTP_STATUS_NOT_ACCEPTABLE: number; + const HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED: number; + const HTTP_STATUS_REQUEST_TIMEOUT: number; + const HTTP_STATUS_CONFLICT: number; + const HTTP_STATUS_GONE: number; + const HTTP_STATUS_LENGTH_REQUIRED: number; + const HTTP_STATUS_PRECONDITION_FAILED: number; + const HTTP_STATUS_PAYLOAD_TOO_LARGE: number; + const HTTP_STATUS_URI_TOO_LONG: number; + const HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE: number; + const HTTP_STATUS_RANGE_NOT_SATISFIABLE: number; + const HTTP_STATUS_EXPECTATION_FAILED: number; + const HTTP_STATUS_TEAPOT: number; + const HTTP_STATUS_MISDIRECTED_REQUEST: number; + const HTTP_STATUS_UNPROCESSABLE_ENTITY: number; + const HTTP_STATUS_LOCKED: number; + const HTTP_STATUS_FAILED_DEPENDENCY: number; + const HTTP_STATUS_UNORDERED_COLLECTION: number; + const HTTP_STATUS_UPGRADE_REQUIRED: number; + const HTTP_STATUS_PRECONDITION_REQUIRED: number; + const HTTP_STATUS_TOO_MANY_REQUESTS: number; + const HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE: number; + const HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS: number; + const HTTP_STATUS_INTERNAL_SERVER_ERROR: number; + const HTTP_STATUS_NOT_IMPLEMENTED: number; + const HTTP_STATUS_BAD_GATEWAY: number; + const HTTP_STATUS_SERVICE_UNAVAILABLE: number; + const HTTP_STATUS_GATEWAY_TIMEOUT: number; + const HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED: number; + const HTTP_STATUS_VARIANT_ALSO_NEGOTIATES: number; + const HTTP_STATUS_INSUFFICIENT_STORAGE: number; + const HTTP_STATUS_LOOP_DETECTED: number; + const HTTP_STATUS_BANDWIDTH_LIMIT_EXCEEDED: number; + const HTTP_STATUS_NOT_EXTENDED: number; + const HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED: number; + } + /** + * This symbol can be set as a property on the HTTP/2 headers object with + * an array value in order to provide a list of headers considered sensitive. + */ + export const sensitiveHeaders: symbol; + /** + * Returns an object containing the default settings for an `Http2Session`instance. This method returns a new object instance every time it is called + * so instances returned may be safely modified for use. + * @since v8.4.0 + */ + export function getDefaultSettings(): Settings; + /** + * Returns a `Buffer` instance containing serialized representation of the given + * HTTP/2 settings as specified in the [HTTP/2](https://tools.ietf.org/html/rfc7540) specification. This is intended + * for use with the `HTTP2-Settings` header field. + * + * ```js + * const http2 = require('http2'); + * + * const packed = http2.getPackedSettings({ enablePush: false }); + * + * console.log(packed.toString('base64')); + * // Prints: AAIAAAAA + * ``` + * @since v8.4.0 + */ + export function getPackedSettings(settings: Settings): Buffer; + /** + * Returns a `HTTP/2 Settings Object` containing the deserialized settings from + * the given `Buffer` as generated by `http2.getPackedSettings()`. + * @since v8.4.0 + * @param buf The packed settings. + */ + export function getUnpackedSettings(buf: Uint8Array): Settings; + /** + * Returns a `net.Server` instance that creates and manages `Http2Session`instances. + * + * Since there are no browsers known that support [unencrypted HTTP/2](https://http2.github.io/faq/#does-http2-require-encryption), the use of {@link createSecureServer} is necessary when + * communicating + * with browser clients. + * + * ```js + * const http2 = require('http2'); + * + * // Create an unencrypted HTTP/2 server. + * // Since there are no browsers known that support + * // unencrypted HTTP/2, the use of `http2.createSecureServer()` + * // is necessary when communicating with browser clients. + * const server = http2.createServer(); + * + * server.on('stream', (stream, headers) => { + * stream.respond({ + * 'content-type': 'text/html; charset=utf-8', + * ':status': 200 + * }); + * stream.end('

Hello World

'); + * }); + * + * server.listen(80); + * ``` + * @since v8.4.0 + * @param onRequestHandler See `Compatibility API` + */ + export function createServer( + onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): Http2Server; + export function createServer( + options: ServerOptions, + onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): Http2Server; + /** + * Returns a `tls.Server` instance that creates and manages `Http2Session`instances. + * + * ```js + * const http2 = require('http2'); + * const fs = require('fs'); + * + * const options = { + * key: fs.readFileSync('server-key.pem'), + * cert: fs.readFileSync('server-cert.pem') + * }; + * + * // Create a secure HTTP/2 server + * const server = http2.createSecureServer(options); + * + * server.on('stream', (stream, headers) => { + * stream.respond({ + * 'content-type': 'text/html; charset=utf-8', + * ':status': 200 + * }); + * stream.end('

Hello World

'); + * }); + * + * server.listen(80); + * ``` + * @since v8.4.0 + * @param onRequestHandler See `Compatibility API` + */ + export function createSecureServer( + onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): Http2SecureServer; + export function createSecureServer( + options: SecureServerOptions, + onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): Http2SecureServer; + /** + * Returns a `ClientHttp2Session` instance. + * + * ```js + * const http2 = require('http2'); + * const client = http2.connect('https://localhost:1234'); + * + * // Use the client + * + * client.close(); + * ``` + * @since v8.4.0 + * @param authority The remote HTTP/2 server to connect to. This must be in the form of a minimal, valid URL with the `http://` or `https://` prefix, host name, and IP port (if a non-default port + * is used). Userinfo (user ID and password), path, querystring, and fragment details in the URL will be ignored. + * @param listener Will be registered as a one-time listener of the {@link 'connect'} event. + */ + export function connect( + authority: string | url.URL, + listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): ClientHttp2Session; + export function connect( + authority: string | url.URL, + options?: ClientSessionOptions | SecureClientSessionOptions, + listener?: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): ClientHttp2Session; +} +declare module "node:http2" { + export * from "http2"; +} diff --git a/backend/node_modules/@types/node/https.d.ts b/backend/node_modules/@types/node/https.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2f069282a05890625b7b6efb6ac3c151e26695fe --- /dev/null +++ b/backend/node_modules/@types/node/https.d.ts @@ -0,0 +1,544 @@ +/** + * HTTPS is the HTTP protocol over TLS/SSL. In Node.js this is implemented as a + * separate module. + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/https.js) + */ +declare module "https" { + import { Duplex } from "node:stream"; + import * as tls from "node:tls"; + import * as http from "node:http"; + import { URL } from "node:url"; + type ServerOptions< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse = typeof http.ServerResponse, + > = tls.SecureContextOptions & tls.TlsOptions & http.ServerOptions; + type RequestOptions = + & http.RequestOptions + & tls.SecureContextOptions + & { + checkServerIdentity?: typeof tls.checkServerIdentity | undefined; + rejectUnauthorized?: boolean | undefined; // Defaults to true + servername?: string | undefined; // SNI TLS Extension + }; + interface AgentOptions extends http.AgentOptions, tls.ConnectionOptions { + rejectUnauthorized?: boolean | undefined; + maxCachedSessions?: number | undefined; + } + /** + * An `Agent` object for HTTPS similar to `http.Agent`. See {@link request} for more information. + * @since v0.4.5 + */ + class Agent extends http.Agent { + constructor(options?: AgentOptions); + options: AgentOptions; + } + interface Server< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse = typeof http.ServerResponse, + > extends http.Server {} + /** + * See `http.Server` for more information. + * @since v0.3.4 + */ + class Server< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse = typeof http.ServerResponse, + > extends tls.Server { + constructor(requestListener?: http.RequestListener); + constructor( + options: ServerOptions, + requestListener?: http.RequestListener, + ); + /** + * Closes all connections connected to this server. + * @since v18.2.0 + */ + closeAllConnections(): void; + /** + * Closes all connections connected to this server which are not sending a request or waiting for a response. + * @since v18.2.0 + */ + closeIdleConnections(): void; + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + addListener( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, + ): this; + addListener( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + addListener( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, + ): this; + addListener(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; + addListener(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "connection", listener: (socket: Duplex) => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + addListener(event: "checkContinue", listener: http.RequestListener): this; + addListener(event: "checkExpectation", listener: http.RequestListener): this; + addListener(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; + addListener( + event: "connect", + listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, + ): this; + addListener(event: "request", listener: http.RequestListener): this; + addListener( + event: "upgrade", + listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, + ): this; + emit(event: string, ...args: any[]): boolean; + emit(event: "keylog", line: Buffer, tlsSocket: tls.TLSSocket): boolean; + emit( + event: "newSession", + sessionId: Buffer, + sessionData: Buffer, + callback: (err: Error, resp: Buffer) => void, + ): boolean; + emit( + event: "OCSPRequest", + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ): boolean; + emit(event: "resumeSession", sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void): boolean; + emit(event: "secureConnection", tlsSocket: tls.TLSSocket): boolean; + emit(event: "tlsClientError", err: Error, tlsSocket: tls.TLSSocket): boolean; + emit(event: "close"): boolean; + emit(event: "connection", socket: Duplex): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + emit( + event: "checkContinue", + req: InstanceType, + res: InstanceType & { req: InstanceType }, + ): boolean; + emit( + event: "checkExpectation", + req: InstanceType, + res: InstanceType & { req: InstanceType }, + ): boolean; + emit(event: "clientError", err: Error, socket: Duplex): boolean; + emit(event: "connect", req: InstanceType, socket: Duplex, head: Buffer): boolean; + emit( + event: "request", + req: InstanceType, + res: InstanceType & { req: InstanceType }, + ): boolean; + emit(event: "upgrade", req: InstanceType, socket: Duplex, head: Buffer): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + on( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, + ): this; + on( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + on( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, + ): this; + on(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; + on(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + on(event: "close", listener: () => void): this; + on(event: "connection", listener: (socket: Duplex) => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + on(event: "checkContinue", listener: http.RequestListener): this; + on(event: "checkExpectation", listener: http.RequestListener): this; + on(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; + on(event: "connect", listener: (req: InstanceType, socket: Duplex, head: Buffer) => void): this; + on(event: "request", listener: http.RequestListener): this; + on(event: "upgrade", listener: (req: InstanceType, socket: Duplex, head: Buffer) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + once( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, + ): this; + once( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + once( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, + ): this; + once(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; + once(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + once(event: "close", listener: () => void): this; + once(event: "connection", listener: (socket: Duplex) => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + once(event: "checkContinue", listener: http.RequestListener): this; + once(event: "checkExpectation", listener: http.RequestListener): this; + once(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; + once(event: "connect", listener: (req: InstanceType, socket: Duplex, head: Buffer) => void): this; + once(event: "request", listener: http.RequestListener): this; + once(event: "upgrade", listener: (req: InstanceType, socket: Duplex, head: Buffer) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + prependListener( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, + ): this; + prependListener( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + prependListener( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, + ): this; + prependListener(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; + prependListener(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "connection", listener: (socket: Duplex) => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + prependListener(event: "checkContinue", listener: http.RequestListener): this; + prependListener(event: "checkExpectation", listener: http.RequestListener): this; + prependListener(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; + prependListener( + event: "connect", + listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, + ): this; + prependListener(event: "request", listener: http.RequestListener): this; + prependListener( + event: "upgrade", + listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, + ): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + prependOnceListener( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, + ): this; + prependOnceListener( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + prependOnceListener( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, + ): this; + prependOnceListener(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; + prependOnceListener(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "connection", listener: (socket: Duplex) => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + prependOnceListener(event: "checkContinue", listener: http.RequestListener): this; + prependOnceListener(event: "checkExpectation", listener: http.RequestListener): this; + prependOnceListener(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; + prependOnceListener( + event: "connect", + listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, + ): this; + prependOnceListener(event: "request", listener: http.RequestListener): this; + prependOnceListener( + event: "upgrade", + listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, + ): this; + } + /** + * ```js + * // curl -k https://localhost:8000/ + * const https = require('https'); + * const fs = require('fs'); + * + * const options = { + * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), + * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem') + * }; + * + * https.createServer(options, (req, res) => { + * res.writeHead(200); + * res.end('hello world\n'); + * }).listen(8000); + * ``` + * + * Or + * + * ```js + * const https = require('https'); + * const fs = require('fs'); + * + * const options = { + * pfx: fs.readFileSync('test/fixtures/test_cert.pfx'), + * passphrase: 'sample' + * }; + * + * https.createServer(options, (req, res) => { + * res.writeHead(200); + * res.end('hello world\n'); + * }).listen(8000); + * ``` + * @since v0.3.4 + * @param options Accepts `options` from `createServer`, `createSecureContext` and `createServer`. + * @param requestListener A listener to be added to the `'request'` event. + */ + function createServer< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse = typeof http.ServerResponse, + >(requestListener?: http.RequestListener): Server; + function createServer< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse = typeof http.ServerResponse, + >( + options: ServerOptions, + requestListener?: http.RequestListener, + ): Server; + /** + * Makes a request to a secure web server. + * + * The following additional `options` from `tls.connect()` are also accepted:`ca`, `cert`, `ciphers`, `clientCertEngine`, `crl`, `dhparam`, `ecdhCurve`,`honorCipherOrder`, `key`, `passphrase`, + * `pfx`, `rejectUnauthorized`,`secureOptions`, `secureProtocol`, `servername`, `sessionIdContext`,`highWaterMark`. + * + * `options` can be an object, a string, or a `URL` object. If `options` is a + * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. + * + * `https.request()` returns an instance of the `http.ClientRequest` class. The `ClientRequest` instance is a writable stream. If one needs to + * upload a file with a POST request, then write to the `ClientRequest` object. + * + * ```js + * const https = require('https'); + * + * const options = { + * hostname: 'encrypted.google.com', + * port: 443, + * path: '/', + * method: 'GET' + * }; + * + * const req = https.request(options, (res) => { + * console.log('statusCode:', res.statusCode); + * console.log('headers:', res.headers); + * + * res.on('data', (d) => { + * process.stdout.write(d); + * }); + * }); + * + * req.on('error', (e) => { + * console.error(e); + * }); + * req.end(); + * ``` + * + * Example using options from `tls.connect()`: + * + * ```js + * const options = { + * hostname: 'encrypted.google.com', + * port: 443, + * path: '/', + * method: 'GET', + * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), + * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem') + * }; + * options.agent = new https.Agent(options); + * + * const req = https.request(options, (res) => { + * // ... + * }); + * ``` + * + * Alternatively, opt out of connection pooling by not using an `Agent`. + * + * ```js + * const options = { + * hostname: 'encrypted.google.com', + * port: 443, + * path: '/', + * method: 'GET', + * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), + * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'), + * agent: false + * }; + * + * const req = https.request(options, (res) => { + * // ... + * }); + * ``` + * + * Example using a `URL` as `options`: + * + * ```js + * const options = new URL('https://abc:xyz@example.com'); + * + * const req = https.request(options, (res) => { + * // ... + * }); + * ``` + * + * Example pinning on certificate fingerprint, or the public key (similar to`pin-sha256`): + * + * ```js + * const tls = require('tls'); + * const https = require('https'); + * const crypto = require('crypto'); + * + * function sha256(s) { + * return crypto.createHash('sha256').update(s).digest('base64'); + * } + * const options = { + * hostname: 'github.com', + * port: 443, + * path: '/', + * method: 'GET', + * checkServerIdentity: function(host, cert) { + * // Make sure the certificate is issued to the host we are connected to + * const err = tls.checkServerIdentity(host, cert); + * if (err) { + * return err; + * } + * + * // Pin the public key, similar to HPKP pin-sha25 pinning + * const pubkey256 = 'pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU='; + * if (sha256(cert.pubkey) !== pubkey256) { + * const msg = 'Certificate verification error: ' + + * `The public key of '${cert.subject.CN}' ` + + * 'does not match our pinned fingerprint'; + * return new Error(msg); + * } + * + * // Pin the exact certificate, rather than the pub key + * const cert256 = '25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:' + + * 'D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16'; + * if (cert.fingerprint256 !== cert256) { + * const msg = 'Certificate verification error: ' + + * `The certificate of '${cert.subject.CN}' ` + + * 'does not match our pinned fingerprint'; + * return new Error(msg); + * } + * + * // This loop is informational only. + * // Print the certificate and public key fingerprints of all certs in the + * // chain. Its common to pin the public key of the issuer on the public + * // internet, while pinning the public key of the service in sensitive + * // environments. + * do { + * console.log('Subject Common Name:', cert.subject.CN); + * console.log(' Certificate SHA256 fingerprint:', cert.fingerprint256); + * + * hash = crypto.createHash('sha256'); + * console.log(' Public key ping-sha256:', sha256(cert.pubkey)); + * + * lastprint256 = cert.fingerprint256; + * cert = cert.issuerCertificate; + * } while (cert.fingerprint256 !== lastprint256); + * + * }, + * }; + * + * options.agent = new https.Agent(options); + * const req = https.request(options, (res) => { + * console.log('All OK. Server matched our pinned cert or public key'); + * console.log('statusCode:', res.statusCode); + * // Print the HPKP values + * console.log('headers:', res.headers['public-key-pins']); + * + * res.on('data', (d) => {}); + * }); + * + * req.on('error', (e) => { + * console.error(e.message); + * }); + * req.end(); + * ``` + * + * Outputs for example: + * + * ```text + * Subject Common Name: github.com + * Certificate SHA256 fingerprint: 25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16 + * Public key ping-sha256: pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU= + * Subject Common Name: DigiCert SHA2 Extended Validation Server CA + * Certificate SHA256 fingerprint: 40:3E:06:2A:26:53:05:91:13:28:5B:AF:80:A0:D4:AE:42:2C:84:8C:9F:78:FA:D0:1F:C9:4B:C5:B8:7F:EF:1A + * Public key ping-sha256: RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho= + * Subject Common Name: DigiCert High Assurance EV Root CA + * Certificate SHA256 fingerprint: 74:31:E5:F4:C3:C1:CE:46:90:77:4F:0B:61:E0:54:40:88:3B:A9:A0:1E:D0:0B:A6:AB:D7:80:6E:D3:B1:18:CF + * Public key ping-sha256: WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18= + * All OK. Server matched our pinned cert or public key + * statusCode: 200 + * headers: max-age=0; pin-sha256="WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18="; pin-sha256="RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho="; + * pin-sha256="k2v657xBsOVe1PQRwOsHsw3bsGT2VzIqz5K+59sNQws="; pin-sha256="K87oWBWM9UZfyddvDfoxL+8lpNyoUB2ptGtn0fv6G2Q="; pin-sha256="IQBnNBEiFuhj+8x6X8XLgh01V9Ic5/V3IRQLNFFc7v4="; + * pin-sha256="iie1VXtL7HzAMF+/PVPR9xzT80kQxdZeJ+zduCB3uj0="; pin-sha256="LvRiGEjRqfzurezaWuj8Wie2gyHMrW5Q06LspMnox7A="; includeSubDomains + * ``` + * @since v0.3.6 + * @param options Accepts all `options` from `request`, with some differences in default values: + */ + function request( + options: RequestOptions | string | URL, + callback?: (res: http.IncomingMessage) => void, + ): http.ClientRequest; + function request( + url: string | URL, + options: RequestOptions, + callback?: (res: http.IncomingMessage) => void, + ): http.ClientRequest; + /** + * Like `http.get()` but for HTTPS. + * + * `options` can be an object, a string, or a `URL` object. If `options` is a + * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. + * + * ```js + * const https = require('https'); + * + * https.get('https://encrypted.google.com/', (res) => { + * console.log('statusCode:', res.statusCode); + * console.log('headers:', res.headers); + * + * res.on('data', (d) => { + * process.stdout.write(d); + * }); + * + * }).on('error', (e) => { + * console.error(e); + * }); + * ``` + * @since v0.3.6 + * @param options Accepts the same `options` as {@link request}, with the `method` always set to `GET`. + */ + function get( + options: RequestOptions | string | URL, + callback?: (res: http.IncomingMessage) => void, + ): http.ClientRequest; + function get( + url: string | URL, + options: RequestOptions, + callback?: (res: http.IncomingMessage) => void, + ): http.ClientRequest; + let globalAgent: Agent; +} +declare module "node:https" { + export * from "https"; +} diff --git a/backend/node_modules/@types/node/index.d.ts b/backend/node_modules/@types/node/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a596cad0219b59bd4a762eec62f85818b94409dd --- /dev/null +++ b/backend/node_modules/@types/node/index.d.ts @@ -0,0 +1,88 @@ +/** + * License for programmatically and manually incorporated + * documentation aka. `JSDoc` from https://github.com/nodejs/node/tree/master/doc + * + * Copyright Node.js contributors. 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. + */ + +// NOTE: These definitions support NodeJS and TypeScript 4.9+. + +// Reference required types from the default lib: +/// +/// +/// +/// + +// Base definitions for all NodeJS modules that are not specific to any version of TypeScript: +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// + +/// diff --git a/backend/node_modules/@types/node/inspector.d.ts b/backend/node_modules/@types/node/inspector.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3b292494d5d19613b4e80800d843bde507b87cff --- /dev/null +++ b/backend/node_modules/@types/node/inspector.d.ts @@ -0,0 +1,2738 @@ +// Type definitions for inspector + +// These definitions are auto-generated. +// Please see https://github.com/DefinitelyTyped/DefinitelyTyped/pull/19330 +// for more information. + + +/** + * The `inspector` module provides an API for interacting with the V8 inspector. + * + * It can be accessed using: + * + * ```js + * const inspector = require('inspector'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/inspector.js) + */ +declare module 'inspector' { + import EventEmitter = require('node:events'); + interface InspectorNotification { + method: string; + params: T; + } + namespace Schema { + /** + * Description of the protocol domain. + */ + interface Domain { + /** + * Domain name. + */ + name: string; + /** + * Domain version. + */ + version: string; + } + interface GetDomainsReturnType { + /** + * List of supported domains. + */ + domains: Domain[]; + } + } + namespace Runtime { + /** + * Unique script identifier. + */ + type ScriptId = string; + /** + * Unique object identifier. + */ + type RemoteObjectId = string; + /** + * Primitive value which cannot be JSON-stringified. + */ + type UnserializableValue = string; + /** + * Mirror object referencing original JavaScript object. + */ + interface RemoteObject { + /** + * Object type. + */ + type: string; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string | undefined; + /** + * Object class (constructor) name. Specified for object type values only. + */ + className?: string | undefined; + /** + * Remote object value in case of primitive values or JSON values (if it was requested). + */ + value?: any; + /** + * Primitive value which can not be JSON-stringified does not have value, but gets this property. + */ + unserializableValue?: UnserializableValue | undefined; + /** + * String representation of the object. + */ + description?: string | undefined; + /** + * Unique object identifier (for non-primitive values). + */ + objectId?: RemoteObjectId | undefined; + /** + * Preview containing abbreviated property values. Specified for object type values only. + * @experimental + */ + preview?: ObjectPreview | undefined; + /** + * @experimental + */ + customPreview?: CustomPreview | undefined; + } + /** + * @experimental + */ + interface CustomPreview { + header: string; + hasBody: boolean; + formatterObjectId: RemoteObjectId; + bindRemoteObjectFunctionId: RemoteObjectId; + configObjectId?: RemoteObjectId | undefined; + } + /** + * Object containing abbreviated remote object value. + * @experimental + */ + interface ObjectPreview { + /** + * Object type. + */ + type: string; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string | undefined; + /** + * String representation of the object. + */ + description?: string | undefined; + /** + * True iff some of the properties or entries of the original object did not fit. + */ + overflow: boolean; + /** + * List of the properties. + */ + properties: PropertyPreview[]; + /** + * List of the entries. Specified for map and set subtype values only. + */ + entries?: EntryPreview[] | undefined; + } + /** + * @experimental + */ + interface PropertyPreview { + /** + * Property name. + */ + name: string; + /** + * Object type. Accessor means that the property itself is an accessor property. + */ + type: string; + /** + * User-friendly property value string. + */ + value?: string | undefined; + /** + * Nested value preview. + */ + valuePreview?: ObjectPreview | undefined; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string | undefined; + } + /** + * @experimental + */ + interface EntryPreview { + /** + * Preview of the key. Specified for map-like collection entries. + */ + key?: ObjectPreview | undefined; + /** + * Preview of the value. + */ + value: ObjectPreview; + } + /** + * Object property descriptor. + */ + interface PropertyDescriptor { + /** + * Property name or symbol description. + */ + name: string; + /** + * The value associated with the property. + */ + value?: RemoteObject | undefined; + /** + * True if the value associated with the property may be changed (data descriptors only). + */ + writable?: boolean | undefined; + /** + * A function which serves as a getter for the property, or undefined if there is no getter (accessor descriptors only). + */ + get?: RemoteObject | undefined; + /** + * A function which serves as a setter for the property, or undefined if there is no setter (accessor descriptors only). + */ + set?: RemoteObject | undefined; + /** + * True if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. + */ + configurable: boolean; + /** + * True if this property shows up during enumeration of the properties on the corresponding object. + */ + enumerable: boolean; + /** + * True if the result was thrown during the evaluation. + */ + wasThrown?: boolean | undefined; + /** + * True if the property is owned for the object. + */ + isOwn?: boolean | undefined; + /** + * Property symbol object, if the property is of the symbol type. + */ + symbol?: RemoteObject | undefined; + } + /** + * Object internal property descriptor. This property isn't normally visible in JavaScript code. + */ + interface InternalPropertyDescriptor { + /** + * Conventional property name. + */ + name: string; + /** + * The value associated with the property. + */ + value?: RemoteObject | undefined; + } + /** + * Represents function call argument. Either remote object id objectId, primitive value, unserializable primitive value or neither of (for undefined) them should be specified. + */ + interface CallArgument { + /** + * Primitive value or serializable javascript object. + */ + value?: any; + /** + * Primitive value which can not be JSON-stringified. + */ + unserializableValue?: UnserializableValue | undefined; + /** + * Remote object handle. + */ + objectId?: RemoteObjectId | undefined; + } + /** + * Id of an execution context. + */ + type ExecutionContextId = number; + /** + * Description of an isolated world. + */ + interface ExecutionContextDescription { + /** + * Unique id of the execution context. It can be used to specify in which execution context script evaluation should be performed. + */ + id: ExecutionContextId; + /** + * Execution context origin. + */ + origin: string; + /** + * Human readable name describing given context. + */ + name: string; + /** + * Embedder-specific auxiliary data. + */ + auxData?: {} | undefined; + } + /** + * Detailed information about exception (or error) that was thrown during script compilation or execution. + */ + interface ExceptionDetails { + /** + * Exception id. + */ + exceptionId: number; + /** + * Exception text, which should be used together with exception object when available. + */ + text: string; + /** + * Line number of the exception location (0-based). + */ + lineNumber: number; + /** + * Column number of the exception location (0-based). + */ + columnNumber: number; + /** + * Script ID of the exception location. + */ + scriptId?: ScriptId | undefined; + /** + * URL of the exception location, to be used when the script was not reported. + */ + url?: string | undefined; + /** + * JavaScript stack trace if available. + */ + stackTrace?: StackTrace | undefined; + /** + * Exception object if available. + */ + exception?: RemoteObject | undefined; + /** + * Identifier of the context where exception happened. + */ + executionContextId?: ExecutionContextId | undefined; + } + /** + * Number of milliseconds since epoch. + */ + type Timestamp = number; + /** + * Stack entry for runtime errors and assertions. + */ + interface CallFrame { + /** + * JavaScript function name. + */ + functionName: string; + /** + * JavaScript script id. + */ + scriptId: ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * JavaScript script line number (0-based). + */ + lineNumber: number; + /** + * JavaScript script column number (0-based). + */ + columnNumber: number; + } + /** + * Call frames for assertions or error messages. + */ + interface StackTrace { + /** + * String label of this stack trace. For async traces this may be a name of the function that initiated the async call. + */ + description?: string | undefined; + /** + * JavaScript function name. + */ + callFrames: CallFrame[]; + /** + * Asynchronous JavaScript stack trace that preceded this stack, if available. + */ + parent?: StackTrace | undefined; + /** + * Asynchronous JavaScript stack trace that preceded this stack, if available. + * @experimental + */ + parentId?: StackTraceId | undefined; + } + /** + * Unique identifier of current debugger. + * @experimental + */ + type UniqueDebuggerId = string; + /** + * If debuggerId is set stack trace comes from another debugger and can be resolved there. This allows to track cross-debugger calls. See Runtime.StackTrace and Debugger.paused for usages. + * @experimental + */ + interface StackTraceId { + id: string; + debuggerId?: UniqueDebuggerId | undefined; + } + interface EvaluateParameterType { + /** + * Expression to evaluate. + */ + expression: string; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + /** + * Determines whether Command Line API should be available during the evaluation. + */ + includeCommandLineAPI?: boolean | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Specifies in which execution context to perform evaluation. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + contextId?: ExecutionContextId | undefined; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean | undefined; + /** + * Whether execution should be treated as initiated by user in the UI. + */ + userGesture?: boolean | undefined; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean | undefined; + } + interface AwaitPromiseParameterType { + /** + * Identifier of the promise. + */ + promiseObjectId: RemoteObjectId; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + */ + generatePreview?: boolean | undefined; + } + interface CallFunctionOnParameterType { + /** + * Declaration of the function to call. + */ + functionDeclaration: string; + /** + * Identifier of the object to call function on. Either objectId or executionContextId should be specified. + */ + objectId?: RemoteObjectId | undefined; + /** + * Call arguments. All call arguments must belong to the same JavaScript world as the target object. + */ + arguments?: CallArgument[] | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Whether the result is expected to be a JSON object which should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean | undefined; + /** + * Whether execution should be treated as initiated by user in the UI. + */ + userGesture?: boolean | undefined; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean | undefined; + /** + * Specifies execution context which global object will be used to call function on. Either executionContextId or objectId should be specified. + */ + executionContextId?: ExecutionContextId | undefined; + /** + * Symbolic group name that can be used to release multiple objects. If objectGroup is not specified and objectId is, objectGroup will be inherited from object. + */ + objectGroup?: string | undefined; + } + interface GetPropertiesParameterType { + /** + * Identifier of the object to return properties for. + */ + objectId: RemoteObjectId; + /** + * If true, returns properties belonging only to the element itself, not to its prototype chain. + */ + ownProperties?: boolean | undefined; + /** + * If true, returns accessor properties (with getter/setter) only; internal properties are not returned either. + * @experimental + */ + accessorPropertiesOnly?: boolean | undefined; + /** + * Whether preview should be generated for the results. + * @experimental + */ + generatePreview?: boolean | undefined; + } + interface ReleaseObjectParameterType { + /** + * Identifier of the object to release. + */ + objectId: RemoteObjectId; + } + interface ReleaseObjectGroupParameterType { + /** + * Symbolic object group name. + */ + objectGroup: string; + } + interface SetCustomObjectFormatterEnabledParameterType { + enabled: boolean; + } + interface CompileScriptParameterType { + /** + * Expression to compile. + */ + expression: string; + /** + * Source url to be set for the script. + */ + sourceURL: string; + /** + * Specifies whether the compiled script should be persisted. + */ + persistScript: boolean; + /** + * Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + executionContextId?: ExecutionContextId | undefined; + } + interface RunScriptParameterType { + /** + * Id of the script to run. + */ + scriptId: ScriptId; + /** + * Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + executionContextId?: ExecutionContextId | undefined; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Determines whether Command Line API should be available during the evaluation. + */ + includeCommandLineAPI?: boolean | undefined; + /** + * Whether the result is expected to be a JSON object which should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + */ + generatePreview?: boolean | undefined; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean | undefined; + } + interface QueryObjectsParameterType { + /** + * Identifier of the prototype to return objects for. + */ + prototypeObjectId: RemoteObjectId; + } + interface GlobalLexicalScopeNamesParameterType { + /** + * Specifies in which execution context to lookup global scope variables. + */ + executionContextId?: ExecutionContextId | undefined; + } + interface EvaluateReturnType { + /** + * Evaluation result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface AwaitPromiseReturnType { + /** + * Promise result. Will contain rejected value if promise was rejected. + */ + result: RemoteObject; + /** + * Exception details if stack strace is available. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface CallFunctionOnReturnType { + /** + * Call result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface GetPropertiesReturnType { + /** + * Object properties. + */ + result: PropertyDescriptor[]; + /** + * Internal object properties (only of the element itself). + */ + internalProperties?: InternalPropertyDescriptor[] | undefined; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface CompileScriptReturnType { + /** + * Id of the script. + */ + scriptId?: ScriptId | undefined; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface RunScriptReturnType { + /** + * Run result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface QueryObjectsReturnType { + /** + * Array with objects. + */ + objects: RemoteObject; + } + interface GlobalLexicalScopeNamesReturnType { + names: string[]; + } + interface ExecutionContextCreatedEventDataType { + /** + * A newly created execution context. + */ + context: ExecutionContextDescription; + } + interface ExecutionContextDestroyedEventDataType { + /** + * Id of the destroyed context + */ + executionContextId: ExecutionContextId; + } + interface ExceptionThrownEventDataType { + /** + * Timestamp of the exception. + */ + timestamp: Timestamp; + exceptionDetails: ExceptionDetails; + } + interface ExceptionRevokedEventDataType { + /** + * Reason describing why exception was revoked. + */ + reason: string; + /** + * The id of revoked exception, as reported in exceptionThrown. + */ + exceptionId: number; + } + interface ConsoleAPICalledEventDataType { + /** + * Type of the call. + */ + type: string; + /** + * Call arguments. + */ + args: RemoteObject[]; + /** + * Identifier of the context where the call was made. + */ + executionContextId: ExecutionContextId; + /** + * Call timestamp. + */ + timestamp: Timestamp; + /** + * Stack trace captured when the call was made. + */ + stackTrace?: StackTrace | undefined; + /** + * Console context descriptor for calls on non-default console context (not console.*): 'anonymous#unique-logger-id' for call on unnamed context, 'name#unique-logger-id' for call on named context. + * @experimental + */ + context?: string | undefined; + } + interface InspectRequestedEventDataType { + object: RemoteObject; + hints: {}; + } + } + namespace Debugger { + /** + * Breakpoint identifier. + */ + type BreakpointId = string; + /** + * Call frame identifier. + */ + type CallFrameId = string; + /** + * Location in the source code. + */ + interface Location { + /** + * Script identifier as reported in the Debugger.scriptParsed. + */ + scriptId: Runtime.ScriptId; + /** + * Line number in the script (0-based). + */ + lineNumber: number; + /** + * Column number in the script (0-based). + */ + columnNumber?: number | undefined; + } + /** + * Location in the source code. + * @experimental + */ + interface ScriptPosition { + lineNumber: number; + columnNumber: number; + } + /** + * JavaScript call frame. Array of call frames form the call stack. + */ + interface CallFrame { + /** + * Call frame identifier. This identifier is only valid while the virtual machine is paused. + */ + callFrameId: CallFrameId; + /** + * Name of the JavaScript function called on this call frame. + */ + functionName: string; + /** + * Location in the source code. + */ + functionLocation?: Location | undefined; + /** + * Location in the source code. + */ + location: Location; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Scope chain for this call frame. + */ + scopeChain: Scope[]; + /** + * this object for this call frame. + */ + this: Runtime.RemoteObject; + /** + * The value being returned, if the function is at return point. + */ + returnValue?: Runtime.RemoteObject | undefined; + } + /** + * Scope description. + */ + interface Scope { + /** + * Scope type. + */ + type: string; + /** + * Object representing the scope. For global and with scopes it represents the actual object; for the rest of the scopes, it is artificial transient object enumerating scope variables as its properties. + */ + object: Runtime.RemoteObject; + name?: string | undefined; + /** + * Location in the source code where scope starts + */ + startLocation?: Location | undefined; + /** + * Location in the source code where scope ends + */ + endLocation?: Location | undefined; + } + /** + * Search match for resource. + */ + interface SearchMatch { + /** + * Line number in resource content. + */ + lineNumber: number; + /** + * Line with match content. + */ + lineContent: string; + } + interface BreakLocation { + /** + * Script identifier as reported in the Debugger.scriptParsed. + */ + scriptId: Runtime.ScriptId; + /** + * Line number in the script (0-based). + */ + lineNumber: number; + /** + * Column number in the script (0-based). + */ + columnNumber?: number | undefined; + type?: string | undefined; + } + interface SetBreakpointsActiveParameterType { + /** + * New value for breakpoints active state. + */ + active: boolean; + } + interface SetSkipAllPausesParameterType { + /** + * New value for skip pauses state. + */ + skip: boolean; + } + interface SetBreakpointByUrlParameterType { + /** + * Line number to set breakpoint at. + */ + lineNumber: number; + /** + * URL of the resources to set breakpoint on. + */ + url?: string | undefined; + /** + * Regex pattern for the URLs of the resources to set breakpoints on. Either url or urlRegex must be specified. + */ + urlRegex?: string | undefined; + /** + * Script hash of the resources to set breakpoint on. + */ + scriptHash?: string | undefined; + /** + * Offset in the line to set breakpoint at. + */ + columnNumber?: number | undefined; + /** + * Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true. + */ + condition?: string | undefined; + } + interface SetBreakpointParameterType { + /** + * Location to set breakpoint in. + */ + location: Location; + /** + * Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true. + */ + condition?: string | undefined; + } + interface RemoveBreakpointParameterType { + breakpointId: BreakpointId; + } + interface GetPossibleBreakpointsParameterType { + /** + * Start of range to search possible breakpoint locations in. + */ + start: Location; + /** + * End of range to search possible breakpoint locations in (excluding). When not specified, end of scripts is used as end of range. + */ + end?: Location | undefined; + /** + * Only consider locations which are in the same (non-nested) function as start. + */ + restrictToFunction?: boolean | undefined; + } + interface ContinueToLocationParameterType { + /** + * Location to continue to. + */ + location: Location; + targetCallFrames?: string | undefined; + } + interface PauseOnAsyncCallParameterType { + /** + * Debugger will pause when async call with given stack trace is started. + */ + parentStackTraceId: Runtime.StackTraceId; + } + interface StepIntoParameterType { + /** + * Debugger will issue additional Debugger.paused notification if any async task is scheduled before next pause. + * @experimental + */ + breakOnAsyncCall?: boolean | undefined; + } + interface GetStackTraceParameterType { + stackTraceId: Runtime.StackTraceId; + } + interface SearchInContentParameterType { + /** + * Id of the script to search in. + */ + scriptId: Runtime.ScriptId; + /** + * String to search for. + */ + query: string; + /** + * If true, search is case sensitive. + */ + caseSensitive?: boolean | undefined; + /** + * If true, treats string parameter as regex. + */ + isRegex?: boolean | undefined; + } + interface SetScriptSourceParameterType { + /** + * Id of the script to edit. + */ + scriptId: Runtime.ScriptId; + /** + * New content of the script. + */ + scriptSource: string; + /** + * If true the change will not actually be applied. Dry run may be used to get result description without actually modifying the code. + */ + dryRun?: boolean | undefined; + } + interface RestartFrameParameterType { + /** + * Call frame identifier to evaluate on. + */ + callFrameId: CallFrameId; + } + interface GetScriptSourceParameterType { + /** + * Id of the script to get source for. + */ + scriptId: Runtime.ScriptId; + } + interface SetPauseOnExceptionsParameterType { + /** + * Pause on exceptions mode. + */ + state: string; + } + interface EvaluateOnCallFrameParameterType { + /** + * Call frame identifier to evaluate on. + */ + callFrameId: CallFrameId; + /** + * Expression to evaluate. + */ + expression: string; + /** + * String object group name to put result into (allows rapid releasing resulting object handles using releaseObjectGroup). + */ + objectGroup?: string | undefined; + /** + * Specifies whether command line API should be available to the evaluated expression, defaults to false. + */ + includeCommandLineAPI?: boolean | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean | undefined; + /** + * Whether to throw an exception if side effect cannot be ruled out during evaluation. + */ + throwOnSideEffect?: boolean | undefined; + } + interface SetVariableValueParameterType { + /** + * 0-based number of scope as was listed in scope chain. Only 'local', 'closure' and 'catch' scope types are allowed. Other scopes could be manipulated manually. + */ + scopeNumber: number; + /** + * Variable name. + */ + variableName: string; + /** + * New variable value. + */ + newValue: Runtime.CallArgument; + /** + * Id of callframe that holds variable. + */ + callFrameId: CallFrameId; + } + interface SetReturnValueParameterType { + /** + * New return value. + */ + newValue: Runtime.CallArgument; + } + interface SetAsyncCallStackDepthParameterType { + /** + * Maximum depth of async call stacks. Setting to 0 will effectively disable collecting async call stacks (default). + */ + maxDepth: number; + } + interface SetBlackboxPatternsParameterType { + /** + * Array of regexps that will be used to check script url for blackbox state. + */ + patterns: string[]; + } + interface SetBlackboxedRangesParameterType { + /** + * Id of the script. + */ + scriptId: Runtime.ScriptId; + positions: ScriptPosition[]; + } + interface EnableReturnType { + /** + * Unique identifier of the debugger. + * @experimental + */ + debuggerId: Runtime.UniqueDebuggerId; + } + interface SetBreakpointByUrlReturnType { + /** + * Id of the created breakpoint for further reference. + */ + breakpointId: BreakpointId; + /** + * List of the locations this breakpoint resolved into upon addition. + */ + locations: Location[]; + } + interface SetBreakpointReturnType { + /** + * Id of the created breakpoint for further reference. + */ + breakpointId: BreakpointId; + /** + * Location this breakpoint resolved into. + */ + actualLocation: Location; + } + interface GetPossibleBreakpointsReturnType { + /** + * List of the possible breakpoint locations. + */ + locations: BreakLocation[]; + } + interface GetStackTraceReturnType { + stackTrace: Runtime.StackTrace; + } + interface SearchInContentReturnType { + /** + * List of search matches. + */ + result: SearchMatch[]; + } + interface SetScriptSourceReturnType { + /** + * New stack trace in case editing has happened while VM was stopped. + */ + callFrames?: CallFrame[] | undefined; + /** + * Whether current call stack was modified after applying the changes. + */ + stackChanged?: boolean | undefined; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace | undefined; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId | undefined; + /** + * Exception details if any. + */ + exceptionDetails?: Runtime.ExceptionDetails | undefined; + } + interface RestartFrameReturnType { + /** + * New stack trace. + */ + callFrames: CallFrame[]; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace | undefined; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId | undefined; + } + interface GetScriptSourceReturnType { + /** + * Script source. + */ + scriptSource: string; + } + interface EvaluateOnCallFrameReturnType { + /** + * Object wrapper for the evaluation result. + */ + result: Runtime.RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: Runtime.ExceptionDetails | undefined; + } + interface ScriptParsedEventDataType { + /** + * Identifier of the script parsed. + */ + scriptId: Runtime.ScriptId; + /** + * URL or name of the script parsed (if any). + */ + url: string; + /** + * Line offset of the script within the resource with given URL (for script tags). + */ + startLine: number; + /** + * Column offset of the script within the resource with given URL. + */ + startColumn: number; + /** + * Last line of the script. + */ + endLine: number; + /** + * Length of the last line of the script. + */ + endColumn: number; + /** + * Specifies script creation context. + */ + executionContextId: Runtime.ExecutionContextId; + /** + * Content hash of the script. + */ + hash: string; + /** + * Embedder-specific auxiliary data. + */ + executionContextAuxData?: {} | undefined; + /** + * True, if this script is generated as a result of the live edit operation. + * @experimental + */ + isLiveEdit?: boolean | undefined; + /** + * URL of source map associated with script (if any). + */ + sourceMapURL?: string | undefined; + /** + * True, if this script has sourceURL. + */ + hasSourceURL?: boolean | undefined; + /** + * True, if this script is ES6 module. + */ + isModule?: boolean | undefined; + /** + * This script length. + */ + length?: number | undefined; + /** + * JavaScript top stack frame of where the script parsed event was triggered if available. + * @experimental + */ + stackTrace?: Runtime.StackTrace | undefined; + } + interface ScriptFailedToParseEventDataType { + /** + * Identifier of the script parsed. + */ + scriptId: Runtime.ScriptId; + /** + * URL or name of the script parsed (if any). + */ + url: string; + /** + * Line offset of the script within the resource with given URL (for script tags). + */ + startLine: number; + /** + * Column offset of the script within the resource with given URL. + */ + startColumn: number; + /** + * Last line of the script. + */ + endLine: number; + /** + * Length of the last line of the script. + */ + endColumn: number; + /** + * Specifies script creation context. + */ + executionContextId: Runtime.ExecutionContextId; + /** + * Content hash of the script. + */ + hash: string; + /** + * Embedder-specific auxiliary data. + */ + executionContextAuxData?: {} | undefined; + /** + * URL of source map associated with script (if any). + */ + sourceMapURL?: string | undefined; + /** + * True, if this script has sourceURL. + */ + hasSourceURL?: boolean | undefined; + /** + * True, if this script is ES6 module. + */ + isModule?: boolean | undefined; + /** + * This script length. + */ + length?: number | undefined; + /** + * JavaScript top stack frame of where the script parsed event was triggered if available. + * @experimental + */ + stackTrace?: Runtime.StackTrace | undefined; + } + interface BreakpointResolvedEventDataType { + /** + * Breakpoint unique identifier. + */ + breakpointId: BreakpointId; + /** + * Actual breakpoint location. + */ + location: Location; + } + interface PausedEventDataType { + /** + * Call stack the virtual machine stopped on. + */ + callFrames: CallFrame[]; + /** + * Pause reason. + */ + reason: string; + /** + * Object containing break-specific auxiliary properties. + */ + data?: {} | undefined; + /** + * Hit breakpoints IDs + */ + hitBreakpoints?: string[] | undefined; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace | undefined; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId | undefined; + /** + * Just scheduled async call will have this stack trace as parent stack during async execution. This field is available only after Debugger.stepInto call with breakOnAsynCall flag. + * @experimental + */ + asyncCallStackTraceId?: Runtime.StackTraceId | undefined; + } + } + namespace Console { + /** + * Console message. + */ + interface ConsoleMessage { + /** + * Message source. + */ + source: string; + /** + * Message severity. + */ + level: string; + /** + * Message text. + */ + text: string; + /** + * URL of the message origin. + */ + url?: string | undefined; + /** + * Line number in the resource that generated this message (1-based). + */ + line?: number | undefined; + /** + * Column number in the resource that generated this message (1-based). + */ + column?: number | undefined; + } + interface MessageAddedEventDataType { + /** + * Console message that has been added. + */ + message: ConsoleMessage; + } + } + namespace Profiler { + /** + * Profile node. Holds callsite information, execution statistics and child nodes. + */ + interface ProfileNode { + /** + * Unique id of the node. + */ + id: number; + /** + * Function location. + */ + callFrame: Runtime.CallFrame; + /** + * Number of samples where this node was on top of the call stack. + */ + hitCount?: number | undefined; + /** + * Child node ids. + */ + children?: number[] | undefined; + /** + * The reason of being not optimized. The function may be deoptimized or marked as don't optimize. + */ + deoptReason?: string | undefined; + /** + * An array of source position ticks. + */ + positionTicks?: PositionTickInfo[] | undefined; + } + /** + * Profile. + */ + interface Profile { + /** + * The list of profile nodes. First item is the root node. + */ + nodes: ProfileNode[]; + /** + * Profiling start timestamp in microseconds. + */ + startTime: number; + /** + * Profiling end timestamp in microseconds. + */ + endTime: number; + /** + * Ids of samples top nodes. + */ + samples?: number[] | undefined; + /** + * Time intervals between adjacent samples in microseconds. The first delta is relative to the profile startTime. + */ + timeDeltas?: number[] | undefined; + } + /** + * Specifies a number of samples attributed to a certain source position. + */ + interface PositionTickInfo { + /** + * Source line number (1-based). + */ + line: number; + /** + * Number of samples attributed to the source line. + */ + ticks: number; + } + /** + * Coverage data for a source range. + */ + interface CoverageRange { + /** + * JavaScript script source offset for the range start. + */ + startOffset: number; + /** + * JavaScript script source offset for the range end. + */ + endOffset: number; + /** + * Collected execution count of the source range. + */ + count: number; + } + /** + * Coverage data for a JavaScript function. + */ + interface FunctionCoverage { + /** + * JavaScript function name. + */ + functionName: string; + /** + * Source ranges inside the function with coverage data. + */ + ranges: CoverageRange[]; + /** + * Whether coverage data for this function has block granularity. + */ + isBlockCoverage: boolean; + } + /** + * Coverage data for a JavaScript script. + */ + interface ScriptCoverage { + /** + * JavaScript script id. + */ + scriptId: Runtime.ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Functions contained in the script that has coverage data. + */ + functions: FunctionCoverage[]; + } + /** + * Describes a type collected during runtime. + * @experimental + */ + interface TypeObject { + /** + * Name of a type collected with type profiling. + */ + name: string; + } + /** + * Source offset and types for a parameter or return value. + * @experimental + */ + interface TypeProfileEntry { + /** + * Source offset of the parameter or end of function for return values. + */ + offset: number; + /** + * The types for this parameter or return value. + */ + types: TypeObject[]; + } + /** + * Type profile data collected during runtime for a JavaScript script. + * @experimental + */ + interface ScriptTypeProfile { + /** + * JavaScript script id. + */ + scriptId: Runtime.ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Type profile entries for parameters and return values of the functions in the script. + */ + entries: TypeProfileEntry[]; + } + interface SetSamplingIntervalParameterType { + /** + * New sampling interval in microseconds. + */ + interval: number; + } + interface StartPreciseCoverageParameterType { + /** + * Collect accurate call counts beyond simple 'covered' or 'not covered'. + */ + callCount?: boolean | undefined; + /** + * Collect block-based coverage. + */ + detailed?: boolean | undefined; + } + interface StopReturnType { + /** + * Recorded profile. + */ + profile: Profile; + } + interface TakePreciseCoverageReturnType { + /** + * Coverage data for the current isolate. + */ + result: ScriptCoverage[]; + } + interface GetBestEffortCoverageReturnType { + /** + * Coverage data for the current isolate. + */ + result: ScriptCoverage[]; + } + interface TakeTypeProfileReturnType { + /** + * Type profile for all scripts since startTypeProfile() was turned on. + */ + result: ScriptTypeProfile[]; + } + interface ConsoleProfileStartedEventDataType { + id: string; + /** + * Location of console.profile(). + */ + location: Debugger.Location; + /** + * Profile title passed as an argument to console.profile(). + */ + title?: string | undefined; + } + interface ConsoleProfileFinishedEventDataType { + id: string; + /** + * Location of console.profileEnd(). + */ + location: Debugger.Location; + profile: Profile; + /** + * Profile title passed as an argument to console.profile(). + */ + title?: string | undefined; + } + } + namespace HeapProfiler { + /** + * Heap snapshot object id. + */ + type HeapSnapshotObjectId = string; + /** + * Sampling Heap Profile node. Holds callsite information, allocation statistics and child nodes. + */ + interface SamplingHeapProfileNode { + /** + * Function location. + */ + callFrame: Runtime.CallFrame; + /** + * Allocations size in bytes for the node excluding children. + */ + selfSize: number; + /** + * Child nodes. + */ + children: SamplingHeapProfileNode[]; + } + /** + * Profile. + */ + interface SamplingHeapProfile { + head: SamplingHeapProfileNode; + } + interface StartTrackingHeapObjectsParameterType { + trackAllocations?: boolean | undefined; + } + interface StopTrackingHeapObjectsParameterType { + /** + * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken when the tracking is stopped. + */ + reportProgress?: boolean | undefined; + } + interface TakeHeapSnapshotParameterType { + /** + * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken. + */ + reportProgress?: boolean | undefined; + } + interface GetObjectByHeapObjectIdParameterType { + objectId: HeapSnapshotObjectId; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + } + interface AddInspectedHeapObjectParameterType { + /** + * Heap snapshot object id to be accessible by means of $x command line API. + */ + heapObjectId: HeapSnapshotObjectId; + } + interface GetHeapObjectIdParameterType { + /** + * Identifier of the object to get heap object id for. + */ + objectId: Runtime.RemoteObjectId; + } + interface StartSamplingParameterType { + /** + * Average sample interval in bytes. Poisson distribution is used for the intervals. The default value is 32768 bytes. + */ + samplingInterval?: number | undefined; + } + interface GetObjectByHeapObjectIdReturnType { + /** + * Evaluation result. + */ + result: Runtime.RemoteObject; + } + interface GetHeapObjectIdReturnType { + /** + * Id of the heap snapshot object corresponding to the passed remote object id. + */ + heapSnapshotObjectId: HeapSnapshotObjectId; + } + interface StopSamplingReturnType { + /** + * Recorded sampling heap profile. + */ + profile: SamplingHeapProfile; + } + interface GetSamplingProfileReturnType { + /** + * Return the sampling profile being collected. + */ + profile: SamplingHeapProfile; + } + interface AddHeapSnapshotChunkEventDataType { + chunk: string; + } + interface ReportHeapSnapshotProgressEventDataType { + done: number; + total: number; + finished?: boolean | undefined; + } + interface LastSeenObjectIdEventDataType { + lastSeenObjectId: number; + timestamp: number; + } + interface HeapStatsUpdateEventDataType { + /** + * An array of triplets. Each triplet describes a fragment. The first integer is the fragment index, the second integer is a total count of objects for the fragment, the third integer is a total size of the objects for the fragment. + */ + statsUpdate: number[]; + } + } + namespace NodeTracing { + interface TraceConfig { + /** + * Controls how the trace buffer stores data. + */ + recordMode?: string | undefined; + /** + * Included category filters. + */ + includedCategories: string[]; + } + interface StartParameterType { + traceConfig: TraceConfig; + } + interface GetCategoriesReturnType { + /** + * A list of supported tracing categories. + */ + categories: string[]; + } + interface DataCollectedEventDataType { + value: Array<{}>; + } + } + namespace NodeWorker { + type WorkerID = string; + /** + * Unique identifier of attached debugging session. + */ + type SessionID = string; + interface WorkerInfo { + workerId: WorkerID; + type: string; + title: string; + url: string; + } + interface SendMessageToWorkerParameterType { + message: string; + /** + * Identifier of the session. + */ + sessionId: SessionID; + } + interface EnableParameterType { + /** + * Whether to new workers should be paused until the frontend sends `Runtime.runIfWaitingForDebugger` + * message to run them. + */ + waitForDebuggerOnStart: boolean; + } + interface DetachParameterType { + sessionId: SessionID; + } + interface AttachedToWorkerEventDataType { + /** + * Identifier assigned to the session used to send/receive messages. + */ + sessionId: SessionID; + workerInfo: WorkerInfo; + waitingForDebugger: boolean; + } + interface DetachedFromWorkerEventDataType { + /** + * Detached session identifier. + */ + sessionId: SessionID; + } + interface ReceivedMessageFromWorkerEventDataType { + /** + * Identifier of a session which sends a message. + */ + sessionId: SessionID; + message: string; + } + } + namespace NodeRuntime { + interface NotifyWhenWaitingForDisconnectParameterType { + enabled: boolean; + } + } + /** + * The `inspector.Session` is used for dispatching messages to the V8 inspector + * back-end and receiving message responses and notifications. + */ + class Session extends EventEmitter { + /** + * Create a new instance of the inspector.Session class. + * The inspector session needs to be connected through session.connect() before the messages can be dispatched to the inspector backend. + */ + constructor(); + /** + * Connects a session to the inspector back-end. + * @since v8.0.0 + */ + connect(): void; + /** + * Immediately close the session. All pending message callbacks will be called + * with an error. `session.connect()` will need to be called to be able to send + * messages again. Reconnected session will lose all inspector state, such as + * enabled agents or configured breakpoints. + * @since v8.0.0 + */ + disconnect(): void; + /** + * Posts a message to the inspector back-end. `callback` will be notified when + * a response is received. `callback` is a function that accepts two optional + * arguments: error and message-specific result. + * + * ```js + * session.post('Runtime.evaluate', { expression: '2 + 2' }, + * (error, { result }) => console.log(result)); + * // Output: { type: 'number', value: 4, description: '4' } + * ``` + * + * The latest version of the V8 inspector protocol is published on the [Chrome DevTools Protocol Viewer](https://chromedevtools.github.io/devtools-protocol/v8/). + * + * Node.js inspector supports all the Chrome DevTools Protocol domains declared + * by V8\. Chrome DevTools Protocol domain provides an interface for interacting + * with one of the runtime agents used to inspect the application state and listen + * to the run-time events. + * + * ## Example usage + * + * Apart from the debugger, various V8 Profilers are available through the DevTools + * protocol. + * @since v8.0.0 + */ + post(method: string, params?: {}, callback?: (err: Error | null, params?: {}) => void): void; + post(method: string, callback?: (err: Error | null, params?: {}) => void): void; + /** + * Returns supported domains. + */ + post(method: 'Schema.getDomains', callback?: (err: Error | null, params: Schema.GetDomainsReturnType) => void): void; + /** + * Evaluates expression on global object. + */ + post(method: 'Runtime.evaluate', params?: Runtime.EvaluateParameterType, callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void): void; + post(method: 'Runtime.evaluate', callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void): void; + /** + * Add handler to promise with given promise object id. + */ + post(method: 'Runtime.awaitPromise', params?: Runtime.AwaitPromiseParameterType, callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void): void; + post(method: 'Runtime.awaitPromise', callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void): void; + /** + * Calls function with given declaration on the given object. Object group of the result is inherited from the target object. + */ + post(method: 'Runtime.callFunctionOn', params?: Runtime.CallFunctionOnParameterType, callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void): void; + post(method: 'Runtime.callFunctionOn', callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void): void; + /** + * Returns properties of a given object. Object group of the result is inherited from the target object. + */ + post(method: 'Runtime.getProperties', params?: Runtime.GetPropertiesParameterType, callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void): void; + post(method: 'Runtime.getProperties', callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void): void; + /** + * Releases remote object with given id. + */ + post(method: 'Runtime.releaseObject', params?: Runtime.ReleaseObjectParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Runtime.releaseObject', callback?: (err: Error | null) => void): void; + /** + * Releases all remote objects that belong to a given group. + */ + post(method: 'Runtime.releaseObjectGroup', params?: Runtime.ReleaseObjectGroupParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Runtime.releaseObjectGroup', callback?: (err: Error | null) => void): void; + /** + * Tells inspected instance to run if it was waiting for debugger to attach. + */ + post(method: 'Runtime.runIfWaitingForDebugger', callback?: (err: Error | null) => void): void; + /** + * Enables reporting of execution contexts creation by means of executionContextCreated event. When the reporting gets enabled the event will be sent immediately for each existing execution context. + */ + post(method: 'Runtime.enable', callback?: (err: Error | null) => void): void; + /** + * Disables reporting of execution contexts creation. + */ + post(method: 'Runtime.disable', callback?: (err: Error | null) => void): void; + /** + * Discards collected exceptions and console API calls. + */ + post(method: 'Runtime.discardConsoleEntries', callback?: (err: Error | null) => void): void; + /** + * @experimental + */ + post(method: 'Runtime.setCustomObjectFormatterEnabled', params?: Runtime.SetCustomObjectFormatterEnabledParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Runtime.setCustomObjectFormatterEnabled', callback?: (err: Error | null) => void): void; + /** + * Compiles expression. + */ + post(method: 'Runtime.compileScript', params?: Runtime.CompileScriptParameterType, callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void): void; + post(method: 'Runtime.compileScript', callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void): void; + /** + * Runs script with given id in a given context. + */ + post(method: 'Runtime.runScript', params?: Runtime.RunScriptParameterType, callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void): void; + post(method: 'Runtime.runScript', callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void): void; + post(method: 'Runtime.queryObjects', params?: Runtime.QueryObjectsParameterType, callback?: (err: Error | null, params: Runtime.QueryObjectsReturnType) => void): void; + post(method: 'Runtime.queryObjects', callback?: (err: Error | null, params: Runtime.QueryObjectsReturnType) => void): void; + /** + * Returns all let, const and class variables from global scope. + */ + post( + method: 'Runtime.globalLexicalScopeNames', + params?: Runtime.GlobalLexicalScopeNamesParameterType, + callback?: (err: Error | null, params: Runtime.GlobalLexicalScopeNamesReturnType) => void + ): void; + post(method: 'Runtime.globalLexicalScopeNames', callback?: (err: Error | null, params: Runtime.GlobalLexicalScopeNamesReturnType) => void): void; + /** + * Enables debugger for the given page. Clients should not assume that the debugging has been enabled until the result for this command is received. + */ + post(method: 'Debugger.enable', callback?: (err: Error | null, params: Debugger.EnableReturnType) => void): void; + /** + * Disables debugger for given page. + */ + post(method: 'Debugger.disable', callback?: (err: Error | null) => void): void; + /** + * Activates / deactivates all breakpoints on the page. + */ + post(method: 'Debugger.setBreakpointsActive', params?: Debugger.SetBreakpointsActiveParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setBreakpointsActive', callback?: (err: Error | null) => void): void; + /** + * Makes page not interrupt on any pauses (breakpoint, exception, dom exception etc). + */ + post(method: 'Debugger.setSkipAllPauses', params?: Debugger.SetSkipAllPausesParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setSkipAllPauses', callback?: (err: Error | null) => void): void; + /** + * Sets JavaScript breakpoint at given location specified either by URL or URL regex. Once this command is issued, all existing parsed scripts will have breakpoints resolved and returned in locations property. Further matching script parsing will result in subsequent breakpointResolved events issued. This logical breakpoint will survive page reloads. + */ + post(method: 'Debugger.setBreakpointByUrl', params?: Debugger.SetBreakpointByUrlParameterType, callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void): void; + post(method: 'Debugger.setBreakpointByUrl', callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void): void; + /** + * Sets JavaScript breakpoint at a given location. + */ + post(method: 'Debugger.setBreakpoint', params?: Debugger.SetBreakpointParameterType, callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void): void; + post(method: 'Debugger.setBreakpoint', callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void): void; + /** + * Removes JavaScript breakpoint. + */ + post(method: 'Debugger.removeBreakpoint', params?: Debugger.RemoveBreakpointParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.removeBreakpoint', callback?: (err: Error | null) => void): void; + /** + * Returns possible locations for breakpoint. scriptId in start and end range locations should be the same. + */ + post( + method: 'Debugger.getPossibleBreakpoints', + params?: Debugger.GetPossibleBreakpointsParameterType, + callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void + ): void; + post(method: 'Debugger.getPossibleBreakpoints', callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void): void; + /** + * Continues execution until specific location is reached. + */ + post(method: 'Debugger.continueToLocation', params?: Debugger.ContinueToLocationParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.continueToLocation', callback?: (err: Error | null) => void): void; + /** + * @experimental + */ + post(method: 'Debugger.pauseOnAsyncCall', params?: Debugger.PauseOnAsyncCallParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.pauseOnAsyncCall', callback?: (err: Error | null) => void): void; + /** + * Steps over the statement. + */ + post(method: 'Debugger.stepOver', callback?: (err: Error | null) => void): void; + /** + * Steps into the function call. + */ + post(method: 'Debugger.stepInto', params?: Debugger.StepIntoParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.stepInto', callback?: (err: Error | null) => void): void; + /** + * Steps out of the function call. + */ + post(method: 'Debugger.stepOut', callback?: (err: Error | null) => void): void; + /** + * Stops on the next JavaScript statement. + */ + post(method: 'Debugger.pause', callback?: (err: Error | null) => void): void; + /** + * This method is deprecated - use Debugger.stepInto with breakOnAsyncCall and Debugger.pauseOnAsyncTask instead. Steps into next scheduled async task if any is scheduled before next pause. Returns success when async task is actually scheduled, returns error if no task were scheduled or another scheduleStepIntoAsync was called. + * @experimental + */ + post(method: 'Debugger.scheduleStepIntoAsync', callback?: (err: Error | null) => void): void; + /** + * Resumes JavaScript execution. + */ + post(method: 'Debugger.resume', callback?: (err: Error | null) => void): void; + /** + * Returns stack trace with given stackTraceId. + * @experimental + */ + post(method: 'Debugger.getStackTrace', params?: Debugger.GetStackTraceParameterType, callback?: (err: Error | null, params: Debugger.GetStackTraceReturnType) => void): void; + post(method: 'Debugger.getStackTrace', callback?: (err: Error | null, params: Debugger.GetStackTraceReturnType) => void): void; + /** + * Searches for given string in script content. + */ + post(method: 'Debugger.searchInContent', params?: Debugger.SearchInContentParameterType, callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void): void; + post(method: 'Debugger.searchInContent', callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void): void; + /** + * Edits JavaScript source live. + */ + post(method: 'Debugger.setScriptSource', params?: Debugger.SetScriptSourceParameterType, callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void): void; + post(method: 'Debugger.setScriptSource', callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void): void; + /** + * Restarts particular call frame from the beginning. + */ + post(method: 'Debugger.restartFrame', params?: Debugger.RestartFrameParameterType, callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void): void; + post(method: 'Debugger.restartFrame', callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void): void; + /** + * Returns source for the script with given id. + */ + post(method: 'Debugger.getScriptSource', params?: Debugger.GetScriptSourceParameterType, callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void): void; + post(method: 'Debugger.getScriptSource', callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void): void; + /** + * Defines pause on exceptions state. Can be set to stop on all exceptions, uncaught exceptions or no exceptions. Initial pause on exceptions state is none. + */ + post(method: 'Debugger.setPauseOnExceptions', params?: Debugger.SetPauseOnExceptionsParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setPauseOnExceptions', callback?: (err: Error | null) => void): void; + /** + * Evaluates expression on a given call frame. + */ + post(method: 'Debugger.evaluateOnCallFrame', params?: Debugger.EvaluateOnCallFrameParameterType, callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void): void; + post(method: 'Debugger.evaluateOnCallFrame', callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void): void; + /** + * Changes value of variable in a callframe. Object-based scopes are not supported and must be mutated manually. + */ + post(method: 'Debugger.setVariableValue', params?: Debugger.SetVariableValueParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setVariableValue', callback?: (err: Error | null) => void): void; + /** + * Changes return value in top frame. Available only at return break position. + * @experimental + */ + post(method: 'Debugger.setReturnValue', params?: Debugger.SetReturnValueParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setReturnValue', callback?: (err: Error | null) => void): void; + /** + * Enables or disables async call stacks tracking. + */ + post(method: 'Debugger.setAsyncCallStackDepth', params?: Debugger.SetAsyncCallStackDepthParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setAsyncCallStackDepth', callback?: (err: Error | null) => void): void; + /** + * Replace previous blackbox patterns with passed ones. Forces backend to skip stepping/pausing in scripts with url matching one of the patterns. VM will try to leave blackboxed script by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. + * @experimental + */ + post(method: 'Debugger.setBlackboxPatterns', params?: Debugger.SetBlackboxPatternsParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setBlackboxPatterns', callback?: (err: Error | null) => void): void; + /** + * Makes backend skip steps in the script in blackboxed ranges. VM will try leave blacklisted scripts by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. Positions array contains positions where blackbox state is changed. First interval isn't blackboxed. Array should be sorted. + * @experimental + */ + post(method: 'Debugger.setBlackboxedRanges', params?: Debugger.SetBlackboxedRangesParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setBlackboxedRanges', callback?: (err: Error | null) => void): void; + /** + * Enables console domain, sends the messages collected so far to the client by means of the messageAdded notification. + */ + post(method: 'Console.enable', callback?: (err: Error | null) => void): void; + /** + * Disables console domain, prevents further console messages from being reported to the client. + */ + post(method: 'Console.disable', callback?: (err: Error | null) => void): void; + /** + * Does nothing. + */ + post(method: 'Console.clearMessages', callback?: (err: Error | null) => void): void; + post(method: 'Profiler.enable', callback?: (err: Error | null) => void): void; + post(method: 'Profiler.disable', callback?: (err: Error | null) => void): void; + /** + * Changes CPU profiler sampling interval. Must be called before CPU profiles recording started. + */ + post(method: 'Profiler.setSamplingInterval', params?: Profiler.SetSamplingIntervalParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Profiler.setSamplingInterval', callback?: (err: Error | null) => void): void; + post(method: 'Profiler.start', callback?: (err: Error | null) => void): void; + post(method: 'Profiler.stop', callback?: (err: Error | null, params: Profiler.StopReturnType) => void): void; + /** + * Enable precise code coverage. Coverage data for JavaScript executed before enabling precise code coverage may be incomplete. Enabling prevents running optimized code and resets execution counters. + */ + post(method: 'Profiler.startPreciseCoverage', params?: Profiler.StartPreciseCoverageParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Profiler.startPreciseCoverage', callback?: (err: Error | null) => void): void; + /** + * Disable precise code coverage. Disabling releases unnecessary execution count records and allows executing optimized code. + */ + post(method: 'Profiler.stopPreciseCoverage', callback?: (err: Error | null) => void): void; + /** + * Collect coverage data for the current isolate, and resets execution counters. Precise code coverage needs to have started. + */ + post(method: 'Profiler.takePreciseCoverage', callback?: (err: Error | null, params: Profiler.TakePreciseCoverageReturnType) => void): void; + /** + * Collect coverage data for the current isolate. The coverage data may be incomplete due to garbage collection. + */ + post(method: 'Profiler.getBestEffortCoverage', callback?: (err: Error | null, params: Profiler.GetBestEffortCoverageReturnType) => void): void; + /** + * Enable type profile. + * @experimental + */ + post(method: 'Profiler.startTypeProfile', callback?: (err: Error | null) => void): void; + /** + * Disable type profile. Disabling releases type profile data collected so far. + * @experimental + */ + post(method: 'Profiler.stopTypeProfile', callback?: (err: Error | null) => void): void; + /** + * Collect type profile. + * @experimental + */ + post(method: 'Profiler.takeTypeProfile', callback?: (err: Error | null, params: Profiler.TakeTypeProfileReturnType) => void): void; + post(method: 'HeapProfiler.enable', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.disable', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.startTrackingHeapObjects', params?: HeapProfiler.StartTrackingHeapObjectsParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.startTrackingHeapObjects', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.stopTrackingHeapObjects', params?: HeapProfiler.StopTrackingHeapObjectsParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.stopTrackingHeapObjects', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.takeHeapSnapshot', params?: HeapProfiler.TakeHeapSnapshotParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.takeHeapSnapshot', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.collectGarbage', callback?: (err: Error | null) => void): void; + post( + method: 'HeapProfiler.getObjectByHeapObjectId', + params?: HeapProfiler.GetObjectByHeapObjectIdParameterType, + callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void + ): void; + post(method: 'HeapProfiler.getObjectByHeapObjectId', callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void): void; + /** + * Enables console to refer to the node with given id via $x (see Command Line API for more details $x functions). + */ + post(method: 'HeapProfiler.addInspectedHeapObject', params?: HeapProfiler.AddInspectedHeapObjectParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.addInspectedHeapObject', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.getHeapObjectId', params?: HeapProfiler.GetHeapObjectIdParameterType, callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void): void; + post(method: 'HeapProfiler.getHeapObjectId', callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void): void; + post(method: 'HeapProfiler.startSampling', params?: HeapProfiler.StartSamplingParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.startSampling', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.stopSampling', callback?: (err: Error | null, params: HeapProfiler.StopSamplingReturnType) => void): void; + post(method: 'HeapProfiler.getSamplingProfile', callback?: (err: Error | null, params: HeapProfiler.GetSamplingProfileReturnType) => void): void; + /** + * Gets supported tracing categories. + */ + post(method: 'NodeTracing.getCategories', callback?: (err: Error | null, params: NodeTracing.GetCategoriesReturnType) => void): void; + /** + * Start trace events collection. + */ + post(method: 'NodeTracing.start', params?: NodeTracing.StartParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeTracing.start', callback?: (err: Error | null) => void): void; + /** + * Stop trace events collection. Remaining collected events will be sent as a sequence of + * dataCollected events followed by tracingComplete event. + */ + post(method: 'NodeTracing.stop', callback?: (err: Error | null) => void): void; + /** + * Sends protocol message over session with given id. + */ + post(method: 'NodeWorker.sendMessageToWorker', params?: NodeWorker.SendMessageToWorkerParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeWorker.sendMessageToWorker', callback?: (err: Error | null) => void): void; + /** + * Instructs the inspector to attach to running workers. Will also attach to new workers + * as they start + */ + post(method: 'NodeWorker.enable', params?: NodeWorker.EnableParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeWorker.enable', callback?: (err: Error | null) => void): void; + /** + * Detaches from all running workers and disables attaching to new workers as they are started. + */ + post(method: 'NodeWorker.disable', callback?: (err: Error | null) => void): void; + /** + * Detached from the worker with given sessionId. + */ + post(method: 'NodeWorker.detach', params?: NodeWorker.DetachParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeWorker.detach', callback?: (err: Error | null) => void): void; + /** + * Enable the `NodeRuntime.waitingForDisconnect`. + */ + post(method: 'NodeRuntime.notifyWhenWaitingForDisconnect', params?: NodeRuntime.NotifyWhenWaitingForDisconnectParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeRuntime.notifyWhenWaitingForDisconnect', callback?: (err: Error | null) => void): void; + // Events + addListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + addListener(event: 'inspectorNotification', listener: (message: InspectorNotification<{}>) => void): this; + /** + * Issued when new execution context is created. + */ + addListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + addListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + addListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + addListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + addListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + addListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + addListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + addListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + addListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + addListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + addListener(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + addListener(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + addListener(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + addListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + addListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + addListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + addListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + addListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + addListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + addListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + addListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + addListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + addListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + addListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + addListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + addListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'inspectorNotification', message: InspectorNotification<{}>): boolean; + emit(event: 'Runtime.executionContextCreated', message: InspectorNotification): boolean; + emit(event: 'Runtime.executionContextDestroyed', message: InspectorNotification): boolean; + emit(event: 'Runtime.executionContextsCleared'): boolean; + emit(event: 'Runtime.exceptionThrown', message: InspectorNotification): boolean; + emit(event: 'Runtime.exceptionRevoked', message: InspectorNotification): boolean; + emit(event: 'Runtime.consoleAPICalled', message: InspectorNotification): boolean; + emit(event: 'Runtime.inspectRequested', message: InspectorNotification): boolean; + emit(event: 'Debugger.scriptParsed', message: InspectorNotification): boolean; + emit(event: 'Debugger.scriptFailedToParse', message: InspectorNotification): boolean; + emit(event: 'Debugger.breakpointResolved', message: InspectorNotification): boolean; + emit(event: 'Debugger.paused', message: InspectorNotification): boolean; + emit(event: 'Debugger.resumed'): boolean; + emit(event: 'Console.messageAdded', message: InspectorNotification): boolean; + emit(event: 'Profiler.consoleProfileStarted', message: InspectorNotification): boolean; + emit(event: 'Profiler.consoleProfileFinished', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.addHeapSnapshotChunk', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.resetProfiles'): boolean; + emit(event: 'HeapProfiler.reportHeapSnapshotProgress', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.lastSeenObjectId', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.heapStatsUpdate', message: InspectorNotification): boolean; + emit(event: 'NodeTracing.dataCollected', message: InspectorNotification): boolean; + emit(event: 'NodeTracing.tracingComplete'): boolean; + emit(event: 'NodeWorker.attachedToWorker', message: InspectorNotification): boolean; + emit(event: 'NodeWorker.detachedFromWorker', message: InspectorNotification): boolean; + emit(event: 'NodeWorker.receivedMessageFromWorker', message: InspectorNotification): boolean; + emit(event: 'NodeRuntime.waitingForDisconnect'): boolean; + on(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + on(event: 'inspectorNotification', listener: (message: InspectorNotification<{}>) => void): this; + /** + * Issued when new execution context is created. + */ + on(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + on(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + on(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + on(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + on(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + on(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + on(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + on(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + on(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + on(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + on(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + on(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + on(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + on(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + on(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + on(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + on(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + on(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + on(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + on(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + on(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + on(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + on(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + on(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + on(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + on(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + once(event: 'inspectorNotification', listener: (message: InspectorNotification<{}>) => void): this; + /** + * Issued when new execution context is created. + */ + once(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + once(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + once(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + once(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + once(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + once(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + once(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + once(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + once(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + once(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + once(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + once(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + once(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + once(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + once(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + once(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + once(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + once(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + once(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + once(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + once(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + once(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + once(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + once(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + once(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + once(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependListener(event: 'inspectorNotification', listener: (message: InspectorNotification<{}>) => void): this; + /** + * Issued when new execution context is created. + */ + prependListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + prependListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + prependListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + prependListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + prependListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + prependListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + prependListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependListener(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + prependListener(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + prependListener(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + prependListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + prependListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + prependListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + prependListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependOnceListener(event: 'inspectorNotification', listener: (message: InspectorNotification<{}>) => void): this; + /** + * Issued when new execution context is created. + */ + prependOnceListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + prependOnceListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + prependOnceListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + prependOnceListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + prependOnceListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + prependOnceListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependOnceListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependOnceListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + prependOnceListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependOnceListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependOnceListener(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + prependOnceListener(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + prependOnceListener(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependOnceListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + prependOnceListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependOnceListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependOnceListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + prependOnceListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependOnceListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + prependOnceListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + prependOnceListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependOnceListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependOnceListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + } + /** + * Activate inspector on host and port. Equivalent to`node --inspect=[[host:]port]`, but can be done programmatically after node has + * started. + * + * If wait is `true`, will block until a client has connected to the inspect port + * and flow control has been passed to the debugger client. + * + * See the `security warning` regarding the `host`parameter usage. + * @param [port='what was specified on the CLI'] Port to listen on for inspector connections. Optional. + * @param [host='what was specified on the CLI'] Host to listen on for inspector connections. Optional. + * @param [wait=false] Block until a client has connected. Optional. + */ + function open(port?: number, host?: string, wait?: boolean): void; + /** + * Deactivate the inspector. Blocks until there are no active connections. + */ + function close(): void; + /** + * Return the URL of the active inspector, or `undefined` if there is none. + * + * ```console + * $ node --inspect -p 'inspector.url()' + * Debugger listening on ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34 + * For help, see: https://nodejs.org/en/docs/inspector + * ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34 + * + * $ node --inspect=localhost:3000 -p 'inspector.url()' + * Debugger listening on ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a + * For help, see: https://nodejs.org/en/docs/inspector + * ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a + * + * $ node -p 'inspector.url()' + * undefined + * ``` + */ + function url(): string | undefined; + /** + * Blocks until a client (existing or connected later) has sent`Runtime.runIfWaitingForDebugger` command. + * + * An exception will be thrown if there is no active inspector. + * @since v12.7.0 + */ + function waitForDebugger(): void; +} +/** + * The inspector module provides an API for interacting with the V8 inspector. + */ +declare module 'node:inspector' { + export * from 'inspector'; +} diff --git a/backend/node_modules/@types/node/module.d.ts b/backend/node_modules/@types/node/module.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3a08656e8ba4ac2ccd87e4a94d114985d8e2cd8a --- /dev/null +++ b/backend/node_modules/@types/node/module.d.ts @@ -0,0 +1,298 @@ +/** + * @since v0.3.7 + */ +declare module "module" { + import { URL } from "node:url"; + import { MessagePort } from "node:worker_threads"; + namespace Module { + /** + * The `module.syncBuiltinESMExports()` method updates all the live bindings for + * builtin `ES Modules` to match the properties of the `CommonJS` exports. It + * does not add or remove exported names from the `ES Modules`. + * + * ```js + * const fs = require('fs'); + * const assert = require('assert'); + * const { syncBuiltinESMExports } = require('module'); + * + * fs.readFile = newAPI; + * + * delete fs.readFileSync; + * + * function newAPI() { + * // ... + * } + * + * fs.newAPI = newAPI; + * + * syncBuiltinESMExports(); + * + * import('fs').then((esmFS) => { + * // It syncs the existing readFile property with the new value + * assert.strictEqual(esmFS.readFile, newAPI); + * // readFileSync has been deleted from the required fs + * assert.strictEqual('readFileSync' in fs, false); + * // syncBuiltinESMExports() does not remove readFileSync from esmFS + * assert.strictEqual('readFileSync' in esmFS, true); + * // syncBuiltinESMExports() does not add names + * assert.strictEqual(esmFS.newAPI, undefined); + * }); + * ``` + * @since v12.12.0 + */ + function syncBuiltinESMExports(): void; + /** + * `path` is the resolved path for the file for which a corresponding source map + * should be fetched. + * @since v13.7.0, v12.17.0 + */ + function findSourceMap(path: string, error?: Error): SourceMap; + interface SourceMapPayload { + file: string; + version: number; + sources: string[]; + sourcesContent: string[]; + names: string[]; + mappings: string; + sourceRoot: string; + } + interface SourceMapping { + generatedLine: number; + generatedColumn: number; + originalSource: string; + originalLine: number; + originalColumn: number; + } + interface SourceOrigin { + /** + * The name of the range in the source map, if one was provided + */ + name?: string; + /** + * The file name of the original source, as reported in the SourceMap + */ + fileName: string; + /** + * The 1-indexed lineNumber of the corresponding call site in the original source + */ + lineNumber: number; + /** + * The 1-indexed columnNumber of the corresponding call site in the original source + */ + columnNumber: number; + } + /** + * @since v13.7.0, v12.17.0 + */ + class SourceMap { + /** + * Getter for the payload used to construct the `SourceMap` instance. + */ + readonly payload: SourceMapPayload; + constructor(payload: SourceMapPayload); + /** + * Given a line offset and column offset in the generated source + * file, returns an object representing the SourceMap range in the + * original file if found, or an empty object if not. + * + * The object returned contains the following keys: + * + * The returned value represents the raw range as it appears in the + * SourceMap, based on zero-indexed offsets, _not_ 1-indexed line and + * column numbers as they appear in Error messages and CallSite + * objects. + * + * To get the corresponding 1-indexed line and column numbers from a + * lineNumber and columnNumber as they are reported by Error stacks + * and CallSite objects, use `sourceMap.findOrigin(lineNumber, columnNumber)` + * @param lineOffset The zero-indexed line number offset in the generated source + * @param columnOffset The zero-indexed column number offset in the generated source + */ + findEntry(lineOffset: number, columnOffset: number): SourceMapping; + /** + * Given a 1-indexed `lineNumber` and `columnNumber` from a call site in the generated source, + * find the corresponding call site location in the original source. + * + * If the `lineNumber` and `columnNumber` provided are not found in any source map, + * then an empty object is returned. + * @param lineNumber The 1-indexed line number of the call site in the generated source + * @param columnNumber The 1-indexed column number of the call site in the generated source + */ + findOrigin(lineNumber: number, columnNumber: number): SourceOrigin | {}; + } + /** @deprecated Use `ImportAttributes` instead */ + interface ImportAssertions extends ImportAttributes {} + interface ImportAttributes extends NodeJS.Dict { + type?: string | undefined; + } + type ModuleFormat = "builtin" | "commonjs" | "json" | "module" | "wasm"; + type ModuleSource = string | ArrayBuffer | NodeJS.TypedArray; + interface GlobalPreloadContext { + port: MessagePort; + } + /** + * @deprecated This hook will be removed in a future version. + * Use `initialize` instead. When a loader has an `initialize` export, `globalPreload` will be ignored. + * + * Sometimes it might be necessary to run some code inside of the same global scope that the application runs in. + * This hook allows the return of a string that is run as a sloppy-mode script on startup. + * + * @param context Information to assist the preload code + * @return Code to run before application startup + */ + type GlobalPreloadHook = (context: GlobalPreloadContext) => string; + /** + * The `initialize` hook provides a way to define a custom function that runs in the hooks thread + * when the hooks module is initialized. Initialization happens when the hooks module is registered via `register`. + * + * This hook can receive data from a `register` invocation, including ports and other transferrable objects. + * The return value of `initialize` can be a `Promise`, in which case it will be awaited before the main application thread execution resumes. + */ + type InitializeHook = (data: Data) => void | Promise; + interface ResolveHookContext { + /** + * Export conditions of the relevant `package.json` + */ + conditions: string[]; + /** + * @deprecated Use `importAttributes` instead + */ + importAssertions: ImportAttributes; + /** + * An object whose key-value pairs represent the assertions for the module to import + */ + importAttributes: ImportAttributes; + /** + * The module importing this one, or undefined if this is the Node.js entry point + */ + parentURL: string | undefined; + } + interface ResolveFnOutput { + /** + * A hint to the load hook (it might be ignored) + */ + format?: ModuleFormat | null | undefined; + /** + * @deprecated Use `importAttributes` instead + */ + importAssertions?: ImportAttributes | undefined; + /** + * The import attributes to use when caching the module (optional; if excluded the input will be used) + */ + importAttributes?: ImportAttributes | undefined; + /** + * A signal that this hook intends to terminate the chain of `resolve` hooks. + * @default false + */ + shortCircuit?: boolean | undefined; + /** + * The absolute URL to which this input resolves + */ + url: string; + } + /** + * The `resolve` hook chain is responsible for resolving file URL for a given module specifier and parent URL, and optionally its format (such as `'module'`) as a hint to the `load` hook. + * If a format is specified, the load hook is ultimately responsible for providing the final `format` value (and it is free to ignore the hint provided by `resolve`); + * if `resolve` provides a format, a custom `load` hook is required even if only to pass the value to the Node.js default `load` hook. + * + * @param specifier The specified URL path of the module to be resolved + * @param context + * @param nextResolve The subsequent `resolve` hook in the chain, or the Node.js default `resolve` hook after the last user-supplied resolve hook + */ + type ResolveHook = ( + specifier: string, + context: ResolveHookContext, + nextResolve: ( + specifier: string, + context?: ResolveHookContext, + ) => ResolveFnOutput | Promise, + ) => ResolveFnOutput | Promise; + interface LoadHookContext { + /** + * Export conditions of the relevant `package.json` + */ + conditions: string[]; + /** + * The format optionally supplied by the `resolve` hook chain + */ + format: ModuleFormat; + /** + * @deprecated Use `importAttributes` instead + */ + importAssertions: ImportAttributes; + /** + * An object whose key-value pairs represent the assertions for the module to import + */ + importAttributes: ImportAttributes; + } + interface LoadFnOutput { + format: ModuleFormat; + /** + * A signal that this hook intends to terminate the chain of `resolve` hooks. + * @default false + */ + shortCircuit?: boolean | undefined; + /** + * The source for Node.js to evaluate + */ + source?: ModuleSource; + } + /** + * The `load` hook provides a way to define a custom method of determining how a URL should be interpreted, retrieved, and parsed. + * It is also in charge of validating the import assertion. + * + * @param url The URL/path of the module to be loaded + * @param context Metadata about the module + * @param nextLoad The subsequent `load` hook in the chain, or the Node.js default `load` hook after the last user-supplied `load` hook + */ + type LoadHook = ( + url: string, + context: LoadHookContext, + nextLoad: (url: string, context?: LoadHookContext) => LoadFnOutput | Promise, + ) => LoadFnOutput | Promise; + } + interface RegisterOptions { + parentURL: string | URL; + data?: Data | undefined; + transferList?: any[] | undefined; + } + interface Module extends NodeModule {} + class Module { + static runMain(): void; + static wrap(code: string): string; + static createRequire(path: string | URL): NodeRequire; + static builtinModules: string[]; + static isBuiltin(moduleName: string): boolean; + static Module: typeof Module; + static register( + specifier: string | URL, + parentURL?: string | URL, + options?: RegisterOptions, + ): void; + static register(specifier: string | URL, options?: RegisterOptions): void; + constructor(id: string, parent?: Module); + } + global { + interface ImportMeta { + url: string; + /** + * @experimental + * This feature is only available with the `--experimental-import-meta-resolve` + * command flag enabled. + * + * Provides a module-relative resolution function scoped to each module, returning + * the URL string. + * + * @param specified The module specifier to resolve relative to `parent`. + * @param parent The absolute parent module URL to resolve from. If none + * is specified, the value of `import.meta.url` is used as the default. + */ + resolve?(specified: string, parent?: string | URL): Promise; + } + } + export = Module; +} +declare module "node:module" { + import module = require("module"); + export = module; +} diff --git a/backend/node_modules/@types/node/net.d.ts b/backend/node_modules/@types/node/net.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c959b8924632faea9808081eafb15fc9ae7298d0 --- /dev/null +++ b/backend/node_modules/@types/node/net.d.ts @@ -0,0 +1,918 @@ +/** + * > Stability: 2 - Stable + * + * The `net` module provides an asynchronous network API for creating stream-based + * TCP or `IPC` servers ({@link createServer}) and clients + * ({@link createConnection}). + * + * It can be accessed using: + * + * ```js + * const net = require('net'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/net.js) + */ +declare module "net" { + import * as stream from "node:stream"; + import { Abortable, EventEmitter } from "node:events"; + import * as dns from "node:dns"; + type LookupFunction = ( + hostname: string, + options: dns.LookupOptions, + callback: (err: NodeJS.ErrnoException | null, address: string | dns.LookupAddress[], family?: number) => void, + ) => void; + interface AddressInfo { + address: string; + family: string; + port: number; + } + interface SocketConstructorOpts { + fd?: number | undefined; + allowHalfOpen?: boolean | undefined; + readable?: boolean | undefined; + writable?: boolean | undefined; + signal?: AbortSignal; + } + interface OnReadOpts { + buffer: Uint8Array | (() => Uint8Array); + /** + * This function is called for every chunk of incoming data. + * Two arguments are passed to it: the number of bytes written to buffer and a reference to buffer. + * Return false from this function to implicitly pause() the socket. + */ + callback(bytesWritten: number, buf: Uint8Array): boolean; + } + interface ConnectOpts { + /** + * If specified, incoming data is stored in a single buffer and passed to the supplied callback when data arrives on the socket. + * Note: this will cause the streaming functionality to not provide any data, however events like 'error', 'end', and 'close' will + * still be emitted as normal and methods like pause() and resume() will also behave as expected. + */ + onread?: OnReadOpts | undefined; + } + interface TcpSocketConnectOpts extends ConnectOpts { + port: number; + host?: string | undefined; + localAddress?: string | undefined; + localPort?: number | undefined; + hints?: number | undefined; + family?: number | undefined; + lookup?: LookupFunction | undefined; + noDelay?: boolean | undefined; + keepAlive?: boolean | undefined; + keepAliveInitialDelay?: number | undefined; + /** + * @since v18.13.0 + */ + autoSelectFamily?: boolean | undefined; + /** + * @since v18.13.0 + */ + autoSelectFamilyAttemptTimeout?: number | undefined; + } + interface IpcSocketConnectOpts extends ConnectOpts { + path: string; + } + type SocketConnectOpts = TcpSocketConnectOpts | IpcSocketConnectOpts; + type SocketReadyState = "opening" | "open" | "readOnly" | "writeOnly" | "closed"; + /** + * This class is an abstraction of a TCP socket or a streaming `IPC` endpoint + * (uses named pipes on Windows, and Unix domain sockets otherwise). It is also + * an `EventEmitter`. + * + * A `net.Socket` can be created by the user and used directly to interact with + * a server. For example, it is returned by {@link createConnection}, + * so the user can use it to talk to the server. + * + * It can also be created by Node.js and passed to the user when a connection + * is received. For example, it is passed to the listeners of a `'connection'` event emitted on a {@link Server}, so the user can use + * it to interact with the client. + * @since v0.3.4 + */ + class Socket extends stream.Duplex { + constructor(options?: SocketConstructorOpts); + /** + * Destroys the socket after all data is written. If the `finish` event was already emitted the socket is destroyed immediately. + * If the socket is still writable it implicitly calls `socket.end()`. + * @since v0.3.4 + */ + destroySoon(): void; + /** + * Sends data on the socket. The second parameter specifies the encoding in the + * case of a string. It defaults to UTF8 encoding. + * + * Returns `true` if the entire data was flushed successfully to the kernel + * buffer. Returns `false` if all or part of the data was queued in user memory.`'drain'` will be emitted when the buffer is again free. + * + * The optional `callback` parameter will be executed when the data is finally + * written out, which may not be immediately. + * + * See `Writable` stream `write()` method for more + * information. + * @since v0.1.90 + * @param [encoding='utf8'] Only used when data is `string`. + */ + write(buffer: Uint8Array | string, cb?: (err?: Error) => void): boolean; + write(str: Uint8Array | string, encoding?: BufferEncoding, cb?: (err?: Error) => void): boolean; + /** + * Initiate a connection on a given socket. + * + * Possible signatures: + * + * * `socket.connect(options[, connectListener])` + * * `socket.connect(path[, connectListener])` for `IPC` connections. + * * `socket.connect(port[, host][, connectListener])` for TCP connections. + * * Returns: `net.Socket` The socket itself. + * + * This function is asynchronous. When the connection is established, the `'connect'` event will be emitted. If there is a problem connecting, + * instead of a `'connect'` event, an `'error'` event will be emitted with + * the error passed to the `'error'` listener. + * The last parameter `connectListener`, if supplied, will be added as a listener + * for the `'connect'` event **once**. + * + * This function should only be used for reconnecting a socket after`'close'` has been emitted or otherwise it may lead to undefined + * behavior. + */ + connect(options: SocketConnectOpts, connectionListener?: () => void): this; + connect(port: number, host: string, connectionListener?: () => void): this; + connect(port: number, connectionListener?: () => void): this; + connect(path: string, connectionListener?: () => void): this; + /** + * Set the encoding for the socket as a `Readable Stream`. See `readable.setEncoding()` for more information. + * @since v0.1.90 + * @return The socket itself. + */ + setEncoding(encoding?: BufferEncoding): this; + /** + * Pauses the reading of data. That is, `'data'` events will not be emitted. + * Useful to throttle back an upload. + * @return The socket itself. + */ + pause(): this; + /** + * Close the TCP connection by sending an RST packet and destroy the stream. + * If this TCP socket is in connecting status, it will send an RST packet + * and destroy this TCP socket once it is connected. Otherwise, it will call + * `socket.destroy` with an `ERR_SOCKET_CLOSED` Error. If this is not a TCP socket + * (for example, a pipe), calling this method will immediately throw + * an `ERR_INVALID_HANDLE_TYPE` Error. + * @since v18.3.0 + * @return The socket itself. + */ + resetAndDestroy(): this; + /** + * Resumes reading after a call to `socket.pause()`. + * @return The socket itself. + */ + resume(): this; + /** + * Sets the socket to timeout after `timeout` milliseconds of inactivity on + * the socket. By default `net.Socket` do not have a timeout. + * + * When an idle timeout is triggered the socket will receive a `'timeout'` event but the connection will not be severed. The user must manually call `socket.end()` or `socket.destroy()` to + * end the connection. + * + * ```js + * socket.setTimeout(3000); + * socket.on('timeout', () => { + * console.log('socket timeout'); + * socket.end(); + * }); + * ``` + * + * If `timeout` is 0, then the existing idle timeout is disabled. + * + * The optional `callback` parameter will be added as a one-time listener for the `'timeout'` event. + * @since v0.1.90 + * @return The socket itself. + */ + setTimeout(timeout: number, callback?: () => void): this; + /** + * Enable/disable the use of Nagle's algorithm. + * + * When a TCP connection is created, it will have Nagle's algorithm enabled. + * + * Nagle's algorithm delays data before it is sent via the network. It attempts + * to optimize throughput at the expense of latency. + * + * Passing `true` for `noDelay` or not passing an argument will disable Nagle's + * algorithm for the socket. Passing `false` for `noDelay` will enable Nagle's + * algorithm. + * @since v0.1.90 + * @param [noDelay=true] + * @return The socket itself. + */ + setNoDelay(noDelay?: boolean): this; + /** + * Enable/disable keep-alive functionality, and optionally set the initial + * delay before the first keepalive probe is sent on an idle socket. + * + * Set `initialDelay` (in milliseconds) to set the delay between the last + * data packet received and the first keepalive probe. Setting `0` for`initialDelay` will leave the value unchanged from the default + * (or previous) setting. + * + * Enabling the keep-alive functionality will set the following socket options: + * + * * `SO_KEEPALIVE=1` + * * `TCP_KEEPIDLE=initialDelay` + * * `TCP_KEEPCNT=10` + * * `TCP_KEEPINTVL=1` + * @since v0.1.92 + * @param [enable=false] + * @param [initialDelay=0] + * @return The socket itself. + */ + setKeepAlive(enable?: boolean, initialDelay?: number): this; + /** + * Returns the bound `address`, the address `family` name and `port` of the + * socket as reported by the operating system:`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }` + * @since v0.1.90 + */ + address(): AddressInfo | {}; + /** + * Calling `unref()` on a socket will allow the program to exit if this is the only + * active socket in the event system. If the socket is already `unref`ed calling`unref()` again will have no effect. + * @since v0.9.1 + * @return The socket itself. + */ + unref(): this; + /** + * Opposite of `unref()`, calling `ref()` on a previously `unref`ed socket will _not_ let the program exit if it's the only socket left (the default behavior). + * If the socket is `ref`ed calling `ref` again will have no effect. + * @since v0.9.1 + * @return The socket itself. + */ + ref(): this; + /** + * This property shows the number of characters buffered for writing. The buffer + * may contain strings whose length after encoding is not yet known. So this number + * is only an approximation of the number of bytes in the buffer. + * + * `net.Socket` has the property that `socket.write()` always works. This is to + * help users get up and running quickly. The computer cannot always keep up + * with the amount of data that is written to a socket. The network connection + * simply might be too slow. Node.js will internally queue up the data written to a + * socket and send it out over the wire when it is possible. + * + * The consequence of this internal buffering is that memory may grow. + * Users who experience large or growing `bufferSize` should attempt to + * "throttle" the data flows in their program with `socket.pause()` and `socket.resume()`. + * @since v0.3.8 + * @deprecated Since v14.6.0 - Use `writableLength` instead. + */ + readonly bufferSize: number; + /** + * The amount of received bytes. + * @since v0.5.3 + */ + readonly bytesRead: number; + /** + * The amount of bytes sent. + * @since v0.5.3 + */ + readonly bytesWritten: number; + /** + * If `true`,`socket.connect(options[, connectListener])` was + * called and has not yet finished. It will stay `true` until the socket becomes + * connected, then it is set to `false` and the `'connect'` event is emitted. Note + * that the `socket.connect(options[, connectListener])` callback is a listener for the `'connect'` event. + * @since v6.1.0 + */ + readonly connecting: boolean; + /** + * This is `true` if the socket is not connected yet, either because `.connect()` + * has not yet been called or because it is still in the process of connecting (see `socket.connecting`). + * @since v10.16.0 + */ + readonly pending: boolean; + /** + * See `writable.destroyed` for further details. + */ + readonly destroyed: boolean; + /** + * The string representation of the local IP address the remote client is + * connecting on. For example, in a server listening on `'0.0.0.0'`, if a client + * connects on `'192.168.1.1'`, the value of `socket.localAddress` would be`'192.168.1.1'`. + * @since v0.9.6 + */ + readonly localAddress?: string; + /** + * The numeric representation of the local port. For example, `80` or `21`. + * @since v0.9.6 + */ + readonly localPort?: number; + /** + * The string representation of the local IP family. `'IPv4'` or `'IPv6'`. + * @since v18.8.0 + */ + readonly localFamily?: string; + /** + * This property represents the state of the connection as a string. + * @see {https://nodejs.org/api/net.html#socketreadystate} + * @since v0.5.0 + */ + readonly readyState: SocketReadyState; + /** + * The string representation of the remote IP address. For example,`'74.125.127.100'` or `'2001:4860:a005::68'`. Value may be `undefined` if + * the socket is destroyed (for example, if the client disconnected). + * @since v0.5.10 + */ + readonly remoteAddress?: string | undefined; + /** + * The string representation of the remote IP family. `'IPv4'` or `'IPv6'`. + * @since v0.11.14 + */ + readonly remoteFamily?: string | undefined; + /** + * The numeric representation of the remote port. For example, `80` or `21`. + * @since v0.5.10 + */ + readonly remotePort?: number | undefined; + /** + * The socket timeout in milliseconds as set by socket.setTimeout(). It is undefined if a timeout has not been set. + * @since v10.7.0 + */ + readonly timeout?: number | undefined; + /** + * Half-closes the socket. i.e., it sends a FIN packet. It is possible the + * server will still send some data. + * + * See `writable.end()` for further details. + * @since v0.1.90 + * @param [encoding='utf8'] Only used when data is `string`. + * @param callback Optional callback for when the socket is finished. + * @return The socket itself. + */ + end(callback?: () => void): this; + end(buffer: Uint8Array | string, callback?: () => void): this; + end(str: Uint8Array | string, encoding?: BufferEncoding, callback?: () => void): this; + /** + * events.EventEmitter + * 1. close + * 2. connect + * 3. data + * 4. drain + * 5. end + * 6. error + * 7. lookup + * 8. ready + * 9. timeout + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: (hadError: boolean) => void): this; + addListener(event: "connect", listener: () => void): this; + addListener(event: "data", listener: (data: Buffer) => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener( + event: "lookup", + listener: (err: Error, address: string, family: string | number, host: string) => void, + ): this; + addListener(event: "ready", listener: () => void): this; + addListener(event: "timeout", listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close", hadError: boolean): boolean; + emit(event: "connect"): boolean; + emit(event: "data", data: Buffer): boolean; + emit(event: "drain"): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "lookup", err: Error, address: string, family: string | number, host: string): boolean; + emit(event: "ready"): boolean; + emit(event: "timeout"): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: (hadError: boolean) => void): this; + on(event: "connect", listener: () => void): this; + on(event: "data", listener: (data: Buffer) => void): this; + on(event: "drain", listener: () => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on( + event: "lookup", + listener: (err: Error, address: string, family: string | number, host: string) => void, + ): this; + on(event: "ready", listener: () => void): this; + on(event: "timeout", listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: (hadError: boolean) => void): this; + once(event: "connect", listener: () => void): this; + once(event: "data", listener: (data: Buffer) => void): this; + once(event: "drain", listener: () => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once( + event: "lookup", + listener: (err: Error, address: string, family: string | number, host: string) => void, + ): this; + once(event: "ready", listener: () => void): this; + once(event: "timeout", listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: (hadError: boolean) => void): this; + prependListener(event: "connect", listener: () => void): this; + prependListener(event: "data", listener: (data: Buffer) => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener( + event: "lookup", + listener: (err: Error, address: string, family: string | number, host: string) => void, + ): this; + prependListener(event: "ready", listener: () => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: (hadError: boolean) => void): this; + prependOnceListener(event: "connect", listener: () => void): this; + prependOnceListener(event: "data", listener: (data: Buffer) => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener( + event: "lookup", + listener: (err: Error, address: string, family: string | number, host: string) => void, + ): this; + prependOnceListener(event: "ready", listener: () => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + } + interface ListenOptions extends Abortable { + port?: number | undefined; + host?: string | undefined; + backlog?: number | undefined; + path?: string | undefined; + exclusive?: boolean | undefined; + readableAll?: boolean | undefined; + writableAll?: boolean | undefined; + /** + * @default false + */ + ipv6Only?: boolean | undefined; + } + interface ServerOpts { + /** + * Indicates whether half-opened TCP connections are allowed. + * @default false + */ + allowHalfOpen?: boolean | undefined; + /** + * Indicates whether the socket should be paused on incoming connections. + * @default false + */ + pauseOnConnect?: boolean | undefined; + /** + * If set to `true`, it disables the use of Nagle's algorithm immediately after a new incoming connection is received. + * @default false + * @since v16.5.0 + */ + noDelay?: boolean | undefined; + /** + * If set to `true`, it enables keep-alive functionality on the socket immediately after a new incoming connection is received, + * similarly on what is done in `socket.setKeepAlive([enable][, initialDelay])`. + * @default false + * @since v16.5.0 + */ + keepAlive?: boolean | undefined; + /** + * If set to a positive number, it sets the initial delay before the first keepalive probe is sent on an idle socket. + * @default 0 + * @since v16.5.0 + */ + keepAliveInitialDelay?: number | undefined; + } + interface DropArgument { + localAddress?: string; + localPort?: number; + localFamily?: string; + remoteAddress?: string; + remotePort?: number; + remoteFamily?: string; + } + /** + * This class is used to create a TCP or `IPC` server. + * @since v0.1.90 + */ + class Server extends EventEmitter { + constructor(connectionListener?: (socket: Socket) => void); + constructor(options?: ServerOpts, connectionListener?: (socket: Socket) => void); + /** + * Start a server listening for connections. A `net.Server` can be a TCP or + * an `IPC` server depending on what it listens to. + * + * Possible signatures: + * + * * `server.listen(handle[, backlog][, callback])` + * * `server.listen(options[, callback])` + * * `server.listen(path[, backlog][, callback])` for `IPC` servers + * * `server.listen([port[, host[, backlog]]][, callback])` for TCP servers + * + * This function is asynchronous. When the server starts listening, the `'listening'` event will be emitted. The last parameter `callback`will be added as a listener for the `'listening'` + * event. + * + * All `listen()` methods can take a `backlog` parameter to specify the maximum + * length of the queue of pending connections. The actual length will be determined + * by the OS through sysctl settings such as `tcp_max_syn_backlog` and `somaxconn`on Linux. The default value of this parameter is 511 (not 512). + * + * All {@link Socket} are set to `SO_REUSEADDR` (see [`socket(7)`](https://man7.org/linux/man-pages/man7/socket.7.html) for + * details). + * + * The `server.listen()` method can be called again if and only if there was an + * error during the first `server.listen()` call or `server.close()` has been + * called. Otherwise, an `ERR_SERVER_ALREADY_LISTEN` error will be thrown. + * + * One of the most common errors raised when listening is `EADDRINUSE`. + * This happens when another server is already listening on the requested`port`/`path`/`handle`. One way to handle this would be to retry + * after a certain amount of time: + * + * ```js + * server.on('error', (e) => { + * if (e.code === 'EADDRINUSE') { + * console.log('Address in use, retrying...'); + * setTimeout(() => { + * server.close(); + * server.listen(PORT, HOST); + * }, 1000); + * } + * }); + * ``` + */ + listen(port?: number, hostname?: string, backlog?: number, listeningListener?: () => void): this; + listen(port?: number, hostname?: string, listeningListener?: () => void): this; + listen(port?: number, backlog?: number, listeningListener?: () => void): this; + listen(port?: number, listeningListener?: () => void): this; + listen(path: string, backlog?: number, listeningListener?: () => void): this; + listen(path: string, listeningListener?: () => void): this; + listen(options: ListenOptions, listeningListener?: () => void): this; + listen(handle: any, backlog?: number, listeningListener?: () => void): this; + listen(handle: any, listeningListener?: () => void): this; + /** + * Stops the server from accepting new connections and keeps existing + * connections. This function is asynchronous, the server is finally closed + * when all connections are ended and the server emits a `'close'` event. + * The optional `callback` will be called once the `'close'` event occurs. Unlike + * that event, it will be called with an `Error` as its only argument if the server + * was not open when it was closed. + * @since v0.1.90 + * @param callback Called when the server is closed. + */ + close(callback?: (err?: Error) => void): this; + /** + * Returns the bound `address`, the address `family` name, and `port` of the server + * as reported by the operating system if listening on an IP socket + * (useful to find which port was assigned when getting an OS-assigned address):`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`. + * + * For a server listening on a pipe or Unix domain socket, the name is returned + * as a string. + * + * ```js + * const server = net.createServer((socket) => { + * socket.end('goodbye\n'); + * }).on('error', (err) => { + * // Handle errors here. + * throw err; + * }); + * + * // Grab an arbitrary unused port. + * server.listen(() => { + * console.log('opened server on', server.address()); + * }); + * ``` + * + * `server.address()` returns `null` before the `'listening'` event has been + * emitted or after calling `server.close()`. + * @since v0.1.90 + */ + address(): AddressInfo | string | null; + /** + * Asynchronously get the number of concurrent connections on the server. Works + * when sockets were sent to forks. + * + * Callback should take two arguments `err` and `count`. + * @since v0.9.7 + */ + getConnections(cb: (error: Error | null, count: number) => void): void; + /** + * Opposite of `unref()`, calling `ref()` on a previously `unref`ed server will _not_ let the program exit if it's the only server left (the default behavior). + * If the server is `ref`ed calling `ref()` again will have no effect. + * @since v0.9.1 + */ + ref(): this; + /** + * Calling `unref()` on a server will allow the program to exit if this is the only + * active server in the event system. If the server is already `unref`ed calling`unref()` again will have no effect. + * @since v0.9.1 + */ + unref(): this; + /** + * Set this property to reject connections when the server's connection count gets + * high. + * + * It is not recommended to use this option once a socket has been sent to a child + * with `child_process.fork()`. + * @since v0.2.0 + */ + maxConnections: number; + connections: number; + /** + * Indicates whether or not the server is listening for connections. + * @since v5.7.0 + */ + listening: boolean; + /** + * events.EventEmitter + * 1. close + * 2. connection + * 3. error + * 4. listening + * 5. drop + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "connection", listener: (socket: Socket) => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + addListener(event: "drop", listener: (data?: DropArgument) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "connection", socket: Socket): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + emit(event: "drop", data?: DropArgument): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "connection", listener: (socket: Socket) => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + on(event: "drop", listener: (data?: DropArgument) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "connection", listener: (socket: Socket) => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + once(event: "drop", listener: (data?: DropArgument) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "connection", listener: (socket: Socket) => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + prependListener(event: "drop", listener: (data?: DropArgument) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "connection", listener: (socket: Socket) => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + prependOnceListener(event: "drop", listener: (data?: DropArgument) => void): this; + /** + * Calls {@link Server.close()} and returns a promise that fulfills when the server has closed. + * @since v18.18.0 + */ + [Symbol.asyncDispose](): Promise; + } + type IPVersion = "ipv4" | "ipv6"; + /** + * The `BlockList` object can be used with some network APIs to specify rules for + * disabling inbound or outbound access to specific IP addresses, IP ranges, or + * IP subnets. + * @since v15.0.0, v14.18.0 + */ + class BlockList { + /** + * Adds a rule to block the given IP address. + * @since v15.0.0, v14.18.0 + * @param address An IPv4 or IPv6 address. + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + addAddress(address: string, type?: IPVersion): void; + addAddress(address: SocketAddress): void; + /** + * Adds a rule to block a range of IP addresses from `start` (inclusive) to`end` (inclusive). + * @since v15.0.0, v14.18.0 + * @param start The starting IPv4 or IPv6 address in the range. + * @param end The ending IPv4 or IPv6 address in the range. + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + addRange(start: string, end: string, type?: IPVersion): void; + addRange(start: SocketAddress, end: SocketAddress): void; + /** + * Adds a rule to block a range of IP addresses specified as a subnet mask. + * @since v15.0.0, v14.18.0 + * @param net The network IPv4 or IPv6 address. + * @param prefix The number of CIDR prefix bits. For IPv4, this must be a value between `0` and `32`. For IPv6, this must be between `0` and `128`. + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + addSubnet(net: SocketAddress, prefix: number): void; + addSubnet(net: string, prefix: number, type?: IPVersion): void; + /** + * Returns `true` if the given IP address matches any of the rules added to the`BlockList`. + * + * ```js + * const blockList = new net.BlockList(); + * blockList.addAddress('123.123.123.123'); + * blockList.addRange('10.0.0.1', '10.0.0.10'); + * blockList.addSubnet('8592:757c:efae:4e45::', 64, 'ipv6'); + * + * console.log(blockList.check('123.123.123.123')); // Prints: true + * console.log(blockList.check('10.0.0.3')); // Prints: true + * console.log(blockList.check('222.111.111.222')); // Prints: false + * + * // IPv6 notation for IPv4 addresses works: + * console.log(blockList.check('::ffff:7b7b:7b7b', 'ipv6')); // Prints: true + * console.log(blockList.check('::ffff:123.123.123.123', 'ipv6')); // Prints: true + * ``` + * @since v15.0.0, v14.18.0 + * @param address The IP address to check + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + check(address: SocketAddress): boolean; + check(address: string, type?: IPVersion): boolean; + /** + * The list of rules added to the blocklist. + * @since v15.0.0, v14.18.0 + */ + rules: readonly string[]; + } + interface TcpNetConnectOpts extends TcpSocketConnectOpts, SocketConstructorOpts { + timeout?: number | undefined; + } + interface IpcNetConnectOpts extends IpcSocketConnectOpts, SocketConstructorOpts { + timeout?: number | undefined; + } + type NetConnectOpts = TcpNetConnectOpts | IpcNetConnectOpts; + /** + * Creates a new TCP or `IPC` server. + * + * If `allowHalfOpen` is set to `true`, when the other end of the socket + * signals the end of transmission, the server will only send back the end of + * transmission when `socket.end()` is explicitly called. For example, in the + * context of TCP, when a FIN packed is received, a FIN packed is sent + * back only when `socket.end()` is explicitly called. Until then the + * connection is half-closed (non-readable but still writable). See `'end'` event and [RFC 1122](https://tools.ietf.org/html/rfc1122) (section 4.2.2.13) for more information. + * + * If `pauseOnConnect` is set to `true`, then the socket associated with each + * incoming connection will be paused, and no data will be read from its handle. + * This allows connections to be passed between processes without any data being + * read by the original process. To begin reading data from a paused socket, call `socket.resume()`. + * + * The server can be a TCP server or an `IPC` server, depending on what it `listen()` to. + * + * Here is an example of a TCP echo server which listens for connections + * on port 8124: + * + * ```js + * const net = require('net'); + * const server = net.createServer((c) => { + * // 'connection' listener. + * console.log('client connected'); + * c.on('end', () => { + * console.log('client disconnected'); + * }); + * c.write('hello\r\n'); + * c.pipe(c); + * }); + * server.on('error', (err) => { + * throw err; + * }); + * server.listen(8124, () => { + * console.log('server bound'); + * }); + * ``` + * + * Test this by using `telnet`: + * + * ```console + * $ telnet localhost 8124 + * ``` + * + * To listen on the socket `/tmp/echo.sock`: + * + * ```js + * server.listen('/tmp/echo.sock', () => { + * console.log('server bound'); + * }); + * ``` + * + * Use `nc` to connect to a Unix domain socket server: + * + * ```console + * $ nc -U /tmp/echo.sock + * ``` + * @since v0.5.0 + * @param connectionListener Automatically set as a listener for the {@link 'connection'} event. + */ + function createServer(connectionListener?: (socket: Socket) => void): Server; + function createServer(options?: ServerOpts, connectionListener?: (socket: Socket) => void): Server; + /** + * Aliases to {@link createConnection}. + * + * Possible signatures: + * + * * {@link connect} + * * {@link connect} for `IPC` connections. + * * {@link connect} for TCP connections. + */ + function connect(options: NetConnectOpts, connectionListener?: () => void): Socket; + function connect(port: number, host?: string, connectionListener?: () => void): Socket; + function connect(path: string, connectionListener?: () => void): Socket; + /** + * A factory function, which creates a new {@link Socket}, + * immediately initiates connection with `socket.connect()`, + * then returns the `net.Socket` that starts the connection. + * + * When the connection is established, a `'connect'` event will be emitted + * on the returned socket. The last parameter `connectListener`, if supplied, + * will be added as a listener for the `'connect'` event **once**. + * + * Possible signatures: + * + * * {@link createConnection} + * * {@link createConnection} for `IPC` connections. + * * {@link createConnection} for TCP connections. + * + * The {@link connect} function is an alias to this function. + */ + function createConnection(options: NetConnectOpts, connectionListener?: () => void): Socket; + function createConnection(port: number, host?: string, connectionListener?: () => void): Socket; + function createConnection(path: string, connectionListener?: () => void): Socket; + /** + * Returns `6` if `input` is an IPv6 address. Returns `4` if `input` is an IPv4 + * address in [dot-decimal notation](https://en.wikipedia.org/wiki/Dot-decimal_notation) with no leading zeroes. Otherwise, returns`0`. + * + * ```js + * net.isIP('::1'); // returns 6 + * net.isIP('127.0.0.1'); // returns 4 + * net.isIP('127.000.000.001'); // returns 0 + * net.isIP('127.0.0.1/24'); // returns 0 + * net.isIP('fhqwhgads'); // returns 0 + * ``` + * @since v0.3.0 + */ + function isIP(input: string): number; + /** + * Returns `true` if `input` is an IPv4 address in [dot-decimal notation](https://en.wikipedia.org/wiki/Dot-decimal_notation) with no + * leading zeroes. Otherwise, returns `false`. + * + * ```js + * net.isIPv4('127.0.0.1'); // returns true + * net.isIPv4('127.000.000.001'); // returns false + * net.isIPv4('127.0.0.1/24'); // returns false + * net.isIPv4('fhqwhgads'); // returns false + * ``` + * @since v0.3.0 + */ + function isIPv4(input: string): boolean; + /** + * Returns `true` if `input` is an IPv6 address. Otherwise, returns `false`. + * + * ```js + * net.isIPv6('::1'); // returns true + * net.isIPv6('fhqwhgads'); // returns false + * ``` + * @since v0.3.0 + */ + function isIPv6(input: string): boolean; + interface SocketAddressInitOptions { + /** + * The network address as either an IPv4 or IPv6 string. + * @default 127.0.0.1 + */ + address?: string | undefined; + /** + * @default `'ipv4'` + */ + family?: IPVersion | undefined; + /** + * An IPv6 flow-label used only if `family` is `'ipv6'`. + * @default 0 + */ + flowlabel?: number | undefined; + /** + * An IP port. + * @default 0 + */ + port?: number | undefined; + } + /** + * @since v15.14.0, v14.18.0 + */ + class SocketAddress { + constructor(options: SocketAddressInitOptions); + /** + * @since v15.14.0, v14.18.0 + */ + readonly address: string; + /** + * Either \`'ipv4'\` or \`'ipv6'\`. + * @since v15.14.0, v14.18.0 + */ + readonly family: IPVersion; + /** + * @since v15.14.0, v14.18.0 + */ + readonly port: number; + /** + * @since v15.14.0, v14.18.0 + */ + readonly flowlabel: number; + } +} +declare module "node:net" { + export * from "net"; +} diff --git a/backend/node_modules/@types/node/os.d.ts b/backend/node_modules/@types/node/os.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..00d0373233dea9e3552fef7a7afc72bcd0903f9e --- /dev/null +++ b/backend/node_modules/@types/node/os.d.ts @@ -0,0 +1,473 @@ +/** + * The `os` module provides operating system-related utility methods and + * properties. It can be accessed using: + * + * ```js + * const os = require('os'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/os.js) + */ +declare module "os" { + interface CpuInfo { + model: string; + speed: number; + times: { + user: number; + nice: number; + sys: number; + idle: number; + irq: number; + }; + } + interface NetworkInterfaceBase { + address: string; + netmask: string; + mac: string; + internal: boolean; + cidr: string | null; + } + interface NetworkInterfaceInfoIPv4 extends NetworkInterfaceBase { + family: "IPv4"; + scopeid?: undefined; + } + interface NetworkInterfaceInfoIPv6 extends NetworkInterfaceBase { + family: "IPv6"; + scopeid: number; + } + interface UserInfo { + username: T; + uid: number; + gid: number; + shell: T | null; + homedir: T; + } + type NetworkInterfaceInfo = NetworkInterfaceInfoIPv4 | NetworkInterfaceInfoIPv6; + /** + * Returns the host name of the operating system as a string. + * @since v0.3.3 + */ + function hostname(): string; + /** + * Returns an array containing the 1, 5, and 15 minute load averages. + * + * The load average is a measure of system activity calculated by the operating + * system and expressed as a fractional number. + * + * The load average is a Unix-specific concept. On Windows, the return value is + * always `[0, 0, 0]`. + * @since v0.3.3 + */ + function loadavg(): number[]; + /** + * Returns the system uptime in number of seconds. + * @since v0.3.3 + */ + function uptime(): number; + /** + * Returns the amount of free system memory in bytes as an integer. + * @since v0.3.3 + */ + function freemem(): number; + /** + * Returns the total amount of system memory in bytes as an integer. + * @since v0.3.3 + */ + function totalmem(): number; + /** + * Returns an array of objects containing information about each logical CPU core. + * + * The properties included on each object include: + * + * ```js + * [ + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 252020, + * nice: 0, + * sys: 30340, + * idle: 1070356870, + * irq: 0 + * } + * }, + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 306960, + * nice: 0, + * sys: 26980, + * idle: 1071569080, + * irq: 0 + * } + * }, + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 248450, + * nice: 0, + * sys: 21750, + * idle: 1070919370, + * irq: 0 + * } + * }, + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 256880, + * nice: 0, + * sys: 19430, + * idle: 1070905480, + * irq: 20 + * } + * }, + * ] + * ``` + * + * `nice` values are POSIX-only. On Windows, the `nice` values of all processors + * are always 0. + * @since v0.3.3 + */ + function cpus(): CpuInfo[]; + /** + * Returns an estimate of the default amount of parallelism a program should use. Always returns a value greater than zero. + * + * This function is a small wrapper about libuv's [`uv_available_parallelism()`](https://docs.libuv.org/en/v1.x/misc.html#c.uv_available_parallelism). + * @since 18.4.0 + */ + function availableParallelism(): number; + /** + * Returns the operating system name as returned by [`uname(3)`](https://linux.die.net/man/3/uname). For example, it + * returns `'Linux'` on Linux, `'Darwin'` on macOS, and `'Windows_NT'` on Windows. + * + * See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for additional information + * about the output of running [`uname(3)`](https://linux.die.net/man/3/uname) on various operating systems. + * @since v0.3.3 + */ + function type(): string; + /** + * Returns the operating system as a string. + * + * On POSIX systems, the operating system release is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `GetVersionExW()` is used. See + * [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information. + * @since v0.3.3 + */ + function release(): string; + /** + * Returns an object containing network interfaces that have been assigned a + * network address. + * + * Each key on the returned object identifies a network interface. The associated + * value is an array of objects that each describe an assigned network address. + * + * The properties available on the assigned network address object include: + * + * ```js + * { + * lo: [ + * { + * address: '127.0.0.1', + * netmask: '255.0.0.0', + * family: 'IPv4', + * mac: '00:00:00:00:00:00', + * internal: true, + * cidr: '127.0.0.1/8' + * }, + * { + * address: '::1', + * netmask: 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', + * family: 'IPv6', + * mac: '00:00:00:00:00:00', + * scopeid: 0, + * internal: true, + * cidr: '::1/128' + * } + * ], + * eth0: [ + * { + * address: '192.168.1.108', + * netmask: '255.255.255.0', + * family: 'IPv4', + * mac: '01:02:03:0a:0b:0c', + * internal: false, + * cidr: '192.168.1.108/24' + * }, + * { + * address: 'fe80::a00:27ff:fe4e:66a1', + * netmask: 'ffff:ffff:ffff:ffff::', + * family: 'IPv6', + * mac: '01:02:03:0a:0b:0c', + * scopeid: 1, + * internal: false, + * cidr: 'fe80::a00:27ff:fe4e:66a1/64' + * } + * ] + * } + * ``` + * @since v0.6.0 + */ + function networkInterfaces(): NodeJS.Dict; + /** + * Returns the string path of the current user's home directory. + * + * On POSIX, it uses the `$HOME` environment variable if defined. Otherwise it + * uses the [effective UID](https://en.wikipedia.org/wiki/User_identifier#Effective_user_ID) to look up the user's home directory. + * + * On Windows, it uses the `USERPROFILE` environment variable if defined. + * Otherwise it uses the path to the profile directory of the current user. + * @since v2.3.0 + */ + function homedir(): string; + /** + * Returns information about the currently effective user. On POSIX platforms, + * this is typically a subset of the password file. The returned object includes + * the `username`, `uid`, `gid`, `shell`, and `homedir`. On Windows, the `uid` and`gid` fields are `-1`, and `shell` is `null`. + * + * The value of `homedir` returned by `os.userInfo()` is provided by the operating + * system. This differs from the result of `os.homedir()`, which queries + * environment variables for the home directory before falling back to the + * operating system response. + * + * Throws a `SystemError` if a user has no `username` or `homedir`. + * @since v6.0.0 + */ + function userInfo(options: { encoding: "buffer" }): UserInfo; + function userInfo(options?: { encoding: BufferEncoding }): UserInfo; + type SignalConstants = { + [key in NodeJS.Signals]: number; + }; + namespace constants { + const UV_UDP_REUSEADDR: number; + namespace signals {} + const signals: SignalConstants; + namespace errno { + const E2BIG: number; + const EACCES: number; + const EADDRINUSE: number; + const EADDRNOTAVAIL: number; + const EAFNOSUPPORT: number; + const EAGAIN: number; + const EALREADY: number; + const EBADF: number; + const EBADMSG: number; + const EBUSY: number; + const ECANCELED: number; + const ECHILD: number; + const ECONNABORTED: number; + const ECONNREFUSED: number; + const ECONNRESET: number; + const EDEADLK: number; + const EDESTADDRREQ: number; + const EDOM: number; + const EDQUOT: number; + const EEXIST: number; + const EFAULT: number; + const EFBIG: number; + const EHOSTUNREACH: number; + const EIDRM: number; + const EILSEQ: number; + const EINPROGRESS: number; + const EINTR: number; + const EINVAL: number; + const EIO: number; + const EISCONN: number; + const EISDIR: number; + const ELOOP: number; + const EMFILE: number; + const EMLINK: number; + const EMSGSIZE: number; + const EMULTIHOP: number; + const ENAMETOOLONG: number; + const ENETDOWN: number; + const ENETRESET: number; + const ENETUNREACH: number; + const ENFILE: number; + const ENOBUFS: number; + const ENODATA: number; + const ENODEV: number; + const ENOENT: number; + const ENOEXEC: number; + const ENOLCK: number; + const ENOLINK: number; + const ENOMEM: number; + const ENOMSG: number; + const ENOPROTOOPT: number; + const ENOSPC: number; + const ENOSR: number; + const ENOSTR: number; + const ENOSYS: number; + const ENOTCONN: number; + const ENOTDIR: number; + const ENOTEMPTY: number; + const ENOTSOCK: number; + const ENOTSUP: number; + const ENOTTY: number; + const ENXIO: number; + const EOPNOTSUPP: number; + const EOVERFLOW: number; + const EPERM: number; + const EPIPE: number; + const EPROTO: number; + const EPROTONOSUPPORT: number; + const EPROTOTYPE: number; + const ERANGE: number; + const EROFS: number; + const ESPIPE: number; + const ESRCH: number; + const ESTALE: number; + const ETIME: number; + const ETIMEDOUT: number; + const ETXTBSY: number; + const EWOULDBLOCK: number; + const EXDEV: number; + const WSAEINTR: number; + const WSAEBADF: number; + const WSAEACCES: number; + const WSAEFAULT: number; + const WSAEINVAL: number; + const WSAEMFILE: number; + const WSAEWOULDBLOCK: number; + const WSAEINPROGRESS: number; + const WSAEALREADY: number; + const WSAENOTSOCK: number; + const WSAEDESTADDRREQ: number; + const WSAEMSGSIZE: number; + const WSAEPROTOTYPE: number; + const WSAENOPROTOOPT: number; + const WSAEPROTONOSUPPORT: number; + const WSAESOCKTNOSUPPORT: number; + const WSAEOPNOTSUPP: number; + const WSAEPFNOSUPPORT: number; + const WSAEAFNOSUPPORT: number; + const WSAEADDRINUSE: number; + const WSAEADDRNOTAVAIL: number; + const WSAENETDOWN: number; + const WSAENETUNREACH: number; + const WSAENETRESET: number; + const WSAECONNABORTED: number; + const WSAECONNRESET: number; + const WSAENOBUFS: number; + const WSAEISCONN: number; + const WSAENOTCONN: number; + const WSAESHUTDOWN: number; + const WSAETOOMANYREFS: number; + const WSAETIMEDOUT: number; + const WSAECONNREFUSED: number; + const WSAELOOP: number; + const WSAENAMETOOLONG: number; + const WSAEHOSTDOWN: number; + const WSAEHOSTUNREACH: number; + const WSAENOTEMPTY: number; + const WSAEPROCLIM: number; + const WSAEUSERS: number; + const WSAEDQUOT: number; + const WSAESTALE: number; + const WSAEREMOTE: number; + const WSASYSNOTREADY: number; + const WSAVERNOTSUPPORTED: number; + const WSANOTINITIALISED: number; + const WSAEDISCON: number; + const WSAENOMORE: number; + const WSAECANCELLED: number; + const WSAEINVALIDPROCTABLE: number; + const WSAEINVALIDPROVIDER: number; + const WSAEPROVIDERFAILEDINIT: number; + const WSASYSCALLFAILURE: number; + const WSASERVICE_NOT_FOUND: number; + const WSATYPE_NOT_FOUND: number; + const WSA_E_NO_MORE: number; + const WSA_E_CANCELLED: number; + const WSAEREFUSED: number; + } + namespace priority { + const PRIORITY_LOW: number; + const PRIORITY_BELOW_NORMAL: number; + const PRIORITY_NORMAL: number; + const PRIORITY_ABOVE_NORMAL: number; + const PRIORITY_HIGH: number; + const PRIORITY_HIGHEST: number; + } + } + const devNull: string; + const EOL: string; + /** + * Returns the operating system CPU architecture for which the Node.js binary was + * compiled. Possible values are `'arm'`, `'arm64'`, `'ia32'`, `'mips'`,`'mipsel'`, `'ppc'`, `'ppc64'`, `'s390'`, `'s390x'`, and `'x64'`. + * + * The return value is equivalent to `process.arch`. + * @since v0.5.0 + */ + function arch(): string; + /** + * Returns a string identifying the kernel version. + * + * On POSIX systems, the operating system release is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `RtlGetVersion()` is used, and if it is not + * available, `GetVersionExW()` will be used. See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information. + * @since v13.11.0, v12.17.0 + */ + function version(): string; + /** + * Returns a string identifying the operating system platform for which + * the Node.js binary was compiled. The value is set at compile time. + * Possible values are `'aix'`, `'darwin'`, `'freebsd'`,`'linux'`,`'openbsd'`, `'sunos'`, and `'win32'`. + * + * The return value is equivalent to `process.platform`. + * + * The value `'android'` may also be returned if Node.js is built on the Android + * operating system. [Android support is experimental](https://github.com/nodejs/node/blob/HEAD/BUILDING.md#androidandroid-based-devices-eg-firefox-os). + * @since v0.5.0 + */ + function platform(): NodeJS.Platform; + /** + * Returns the machine type as a string, such as arm, aarch64, mips, mips64, ppc64, ppc64le, s390, s390x, i386, i686, x86_64. + * + * On POSIX systems, the machine type is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). + * On Windows, `RtlGetVersion()` is used, and if it is not available, `GetVersionExW()` will be used. + * See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information. + * @since v18.9.0 + */ + function machine(): string; + /** + * Returns the operating system's default directory for temporary files as a + * string. + * @since v0.9.9 + */ + function tmpdir(): string; + /** + * Returns a string identifying the endianness of the CPU for which the Node.js + * binary was compiled. + * + * Possible values are `'BE'` for big endian and `'LE'` for little endian. + * @since v0.9.4 + */ + function endianness(): "BE" | "LE"; + /** + * Returns the scheduling priority for the process specified by `pid`. If `pid` is + * not provided or is `0`, the priority of the current process is returned. + * @since v10.10.0 + * @param [pid=0] The process ID to retrieve scheduling priority for. + */ + function getPriority(pid?: number): number; + /** + * Attempts to set the scheduling priority for the process specified by `pid`. If`pid` is not provided or is `0`, the process ID of the current process is used. + * + * The `priority` input must be an integer between `-20` (high priority) and `19`(low priority). Due to differences between Unix priority levels and Windows + * priority classes, `priority` is mapped to one of six priority constants in`os.constants.priority`. When retrieving a process priority level, this range + * mapping may cause the return value to be slightly different on Windows. To avoid + * confusion, set `priority` to one of the priority constants. + * + * On Windows, setting priority to `PRIORITY_HIGHEST` requires elevated user + * privileges. Otherwise the set priority will be silently reduced to`PRIORITY_HIGH`. + * @since v10.10.0 + * @param [pid=0] The process ID to set scheduling priority for. + * @param priority The scheduling priority to assign to the process. + */ + function setPriority(priority: number): void; + function setPriority(pid: number, priority: number): void; +} +declare module "node:os" { + export * from "os"; +} diff --git a/backend/node_modules/@types/node/package.json b/backend/node_modules/@types/node/package.json new file mode 100644 index 0000000000000000000000000000000000000000..367f2ad2fb1be8341902f09736570e241c65c301 --- /dev/null +++ b/backend/node_modules/@types/node/package.json @@ -0,0 +1,222 @@ +{ + "name": "@types/node", + "version": "18.19.31", + "description": "TypeScript definitions for node", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node", + "license": "MIT", + "contributors": [ + { + "name": "Microsoft TypeScript", + "githubUsername": "Microsoft", + "url": "https://github.com/Microsoft" + }, + { + "name": "Alberto Schiabel", + "githubUsername": "jkomyno", + "url": "https://github.com/jkomyno" + }, + { + "name": "Alvis HT Tang", + "githubUsername": "alvis", + "url": "https://github.com/alvis" + }, + { + "name": "Andrew Makarov", + "githubUsername": "r3nya", + "url": "https://github.com/r3nya" + }, + { + "name": "Benjamin Toueg", + "githubUsername": "btoueg", + "url": "https://github.com/btoueg" + }, + { + "name": "Chigozirim C.", + "githubUsername": "smac89", + "url": "https://github.com/smac89" + }, + { + "name": "David Junger", + "githubUsername": "touffy", + "url": "https://github.com/touffy" + }, + { + "name": "Deividas Bakanas", + "githubUsername": "DeividasBakanas", + "url": "https://github.com/DeividasBakanas" + }, + { + "name": "Eugene Y. Q. Shen", + "githubUsername": "eyqs", + "url": "https://github.com/eyqs" + }, + { + "name": "Hannes Magnusson", + "githubUsername": "Hannes-Magnusson-CK", + "url": "https://github.com/Hannes-Magnusson-CK" + }, + { + "name": "Huw", + "githubUsername": "hoo29", + "url": "https://github.com/hoo29" + }, + { + "name": "Kelvin Jin", + "githubUsername": "kjin", + "url": "https://github.com/kjin" + }, + { + "name": "Klaus Meinhardt", + "githubUsername": "ajafff", + "url": "https://github.com/ajafff" + }, + { + "name": "Lishude", + "githubUsername": "islishude", + "url": "https://github.com/islishude" + }, + { + "name": "Mariusz Wiktorczyk", + "githubUsername": "mwiktorczyk", + "url": "https://github.com/mwiktorczyk" + }, + { + "name": "Mohsen Azimi", + "githubUsername": "mohsen1", + "url": "https://github.com/mohsen1" + }, + { + "name": "Nikita Galkin", + "githubUsername": "galkin", + "url": "https://github.com/galkin" + }, + { + "name": "Parambir Singh", + "githubUsername": "parambirs", + "url": "https://github.com/parambirs" + }, + { + "name": "Sebastian Silbermann", + "githubUsername": "eps1lon", + "url": "https://github.com/eps1lon" + }, + { + "name": "Simon Schick", + "githubUsername": "SimonSchick", + "url": "https://github.com/SimonSchick" + }, + { + "name": "Thomas den Hollander", + "githubUsername": "ThomasdenH", + "url": "https://github.com/ThomasdenH" + }, + { + "name": "Wilco Bakker", + "githubUsername": "WilcoBakker", + "url": "https://github.com/WilcoBakker" + }, + { + "name": "wwwy3y3", + "githubUsername": "wwwy3y3", + "url": "https://github.com/wwwy3y3" + }, + { + "name": "Samuel Ainsworth", + "githubUsername": "samuela", + "url": "https://github.com/samuela" + }, + { + "name": "Kyle Uehlein", + "githubUsername": "kuehlein", + "url": "https://github.com/kuehlein" + }, + { + "name": "Thanik Bhongbhibhat", + "githubUsername": "bhongy", + "url": "https://github.com/bhongy" + }, + { + "name": "Marcin Kopacz", + "githubUsername": "chyzwar", + "url": "https://github.com/chyzwar" + }, + { + "name": "Trivikram Kamat", + "githubUsername": "trivikr", + "url": "https://github.com/trivikr" + }, + { + "name": "Junxiao Shi", + "githubUsername": "yoursunny", + "url": "https://github.com/yoursunny" + }, + { + "name": "Ilia Baryshnikov", + "githubUsername": "qwelias", + "url": "https://github.com/qwelias" + }, + { + "name": "ExE Boss", + "githubUsername": "ExE-Boss", + "url": "https://github.com/ExE-Boss" + }, + { + "name": "Piotr Błażejewicz", + "githubUsername": "peterblazejewicz", + "url": "https://github.com/peterblazejewicz" + }, + { + "name": "Anna Henningsen", + "githubUsername": "addaleax", + "url": "https://github.com/addaleax" + }, + { + "name": "Victor Perin", + "githubUsername": "victorperin", + "url": "https://github.com/victorperin" + }, + { + "name": "Yongsheng Zhang", + "githubUsername": "ZYSzys", + "url": "https://github.com/ZYSzys" + }, + { + "name": "NodeJS Contributors", + "githubUsername": "NodeJS", + "url": "https://github.com/NodeJS" + }, + { + "name": "Linus Unnebäck", + "githubUsername": "LinusU", + "url": "https://github.com/LinusU" + }, + { + "name": "wafuwafu13", + "githubUsername": "wafuwafu13", + "url": "https://github.com/wafuwafu13" + }, + { + "name": "Matteo Collina", + "githubUsername": "mcollina", + "url": "https://github.com/mcollina" + }, + { + "name": "Dmitry Semigradsky", + "githubUsername": "Semigradsky", + "url": "https://github.com/Semigradsky" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/node" + }, + "scripts": {}, + "dependencies": { + "undici-types": "~5.26.4" + }, + "typesPublisherContentHash": "7348694678b514716d29b96928bb8211a9ac6af108f4217c3e3b06aa1d1cfc57", + "typeScriptVersion": "4.7" +} \ No newline at end of file diff --git a/backend/node_modules/@types/node/path.d.ts b/backend/node_modules/@types/node/path.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1465c38e3d362c3fa2a0f006c7c775a59561545c --- /dev/null +++ b/backend/node_modules/@types/node/path.d.ts @@ -0,0 +1,191 @@ +declare module "path/posix" { + import path = require("path"); + export = path; +} +declare module "path/win32" { + import path = require("path"); + export = path; +} +/** + * The `path` module provides utilities for working with file and directory paths. + * It can be accessed using: + * + * ```js + * const path = require('path'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/path.js) + */ +declare module "path" { + namespace path { + /** + * A parsed path object generated by path.parse() or consumed by path.format(). + */ + interface ParsedPath { + /** + * The root of the path such as '/' or 'c:\' + */ + root: string; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir: string; + /** + * The file name including extension (if any) such as 'index.html' + */ + base: string; + /** + * The file extension (if any) such as '.html' + */ + ext: string; + /** + * The file name without extension (if any) such as 'index' + */ + name: string; + } + interface FormatInputPathObject { + /** + * The root of the path such as '/' or 'c:\' + */ + root?: string | undefined; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir?: string | undefined; + /** + * The file name including extension (if any) such as 'index.html' + */ + base?: string | undefined; + /** + * The file extension (if any) such as '.html' + */ + ext?: string | undefined; + /** + * The file name without extension (if any) such as 'index' + */ + name?: string | undefined; + } + interface PlatformPath { + /** + * Normalize a string path, reducing '..' and '.' parts. + * When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used. + * + * @param path string path to normalize. + * @throws {TypeError} if `path` is not a string. + */ + normalize(path: string): string; + /** + * Join all arguments together and normalize the resulting path. + * + * @param paths paths to join. + * @throws {TypeError} if any of the path segments is not a string. + */ + join(...paths: string[]): string; + /** + * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. + * + * Starting from leftmost {from} parameter, resolves {to} to an absolute path. + * + * If {to} isn't already absolute, {from} arguments are prepended in right to left order, + * until an absolute path is found. If after using all {from} paths still no absolute path is found, + * the current working directory is used as well. The resulting path is normalized, + * and trailing slashes are removed unless the path gets resolved to the root directory. + * + * @param paths A sequence of paths or path segments. + * @throws {TypeError} if any of the arguments is not a string. + */ + resolve(...paths: string[]): string; + /** + * Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory. + * + * If the given {path} is a zero-length string, `false` will be returned. + * + * @param path path to test. + * @throws {TypeError} if `path` is not a string. + */ + isAbsolute(path: string): boolean; + /** + * Solve the relative path from {from} to {to} based on the current working directory. + * At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve. + * + * @throws {TypeError} if either `from` or `to` is not a string. + */ + relative(from: string, to: string): string; + /** + * Return the directory name of a path. Similar to the Unix dirname command. + * + * @param path the path to evaluate. + * @throws {TypeError} if `path` is not a string. + */ + dirname(path: string): string; + /** + * Return the last portion of a path. Similar to the Unix basename command. + * Often used to extract the file name from a fully qualified path. + * + * @param path the path to evaluate. + * @param suffix optionally, an extension to remove from the result. + * @throws {TypeError} if `path` is not a string or if `ext` is given and is not a string. + */ + basename(path: string, suffix?: string): string; + /** + * Return the extension of the path, from the last '.' to end of string in the last portion of the path. + * If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string. + * + * @param path the path to evaluate. + * @throws {TypeError} if `path` is not a string. + */ + extname(path: string): string; + /** + * The platform-specific file separator. '\\' or '/'. + */ + readonly sep: "\\" | "/"; + /** + * The platform-specific file delimiter. ';' or ':'. + */ + readonly delimiter: ";" | ":"; + /** + * Returns an object from a path string - the opposite of format(). + * + * @param path path to evaluate. + * @throws {TypeError} if `path` is not a string. + */ + parse(path: string): ParsedPath; + /** + * Returns a path string from an object - the opposite of parse(). + * + * @param pathObject path to evaluate. + */ + format(pathObject: FormatInputPathObject): string; + /** + * On Windows systems only, returns an equivalent namespace-prefixed path for the given path. + * If path is not a string, path will be returned without modifications. + * This method is meaningful only on Windows system. + * On POSIX systems, the method is non-operational and always returns path without modifications. + */ + toNamespacedPath(path: string): string; + /** + * Posix specific pathing. + * Same as parent object on posix. + */ + readonly posix: PlatformPath; + /** + * Windows specific pathing. + * Same as parent object on windows + */ + readonly win32: PlatformPath; + } + } + const path: path.PlatformPath; + export = path; +} +declare module "node:path" { + import path = require("path"); + export = path; +} +declare module "node:path/posix" { + import path = require("path/posix"); + export = path; +} +declare module "node:path/win32" { + import path = require("path/win32"); + export = path; +} diff --git a/backend/node_modules/@types/node/perf_hooks.d.ts b/backend/node_modules/@types/node/perf_hooks.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9ad41b90a8fd769c18d1be42435cb029221c4d21 --- /dev/null +++ b/backend/node_modules/@types/node/perf_hooks.d.ts @@ -0,0 +1,626 @@ +/** + * This module provides an implementation of a subset of the W3C [Web Performance APIs](https://w3c.github.io/perf-timing-primer/) as well as additional APIs for + * Node.js-specific performance measurements. + * + * Node.js supports the following [Web Performance APIs](https://w3c.github.io/perf-timing-primer/): + * + * * [High Resolution Time](https://www.w3.org/TR/hr-time-2) + * * [Performance Timeline](https://w3c.github.io/performance-timeline/) + * * [User Timing](https://www.w3.org/TR/user-timing/) + * + * ```js + * const { PerformanceObserver, performance } = require('perf_hooks'); + * + * const obs = new PerformanceObserver((items) => { + * console.log(items.getEntries()[0].duration); + * performance.clearMarks(); + * }); + * obs.observe({ type: 'measure' }); + * performance.measure('Start to Now'); + * + * performance.mark('A'); + * doSomeLongRunningProcess(() => { + * performance.measure('A to Now', 'A'); + * + * performance.mark('B'); + * performance.measure('A to B', 'A', 'B'); + * }); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/perf_hooks.js) + */ +declare module "perf_hooks" { + import { AsyncResource } from "node:async_hooks"; + type EntryType = "node" | "mark" | "measure" | "gc" | "function" | "http2" | "http" | "dns"; + interface NodeGCPerformanceDetail { + /** + * When `performanceEntry.entryType` is equal to 'gc', `the performance.kind` property identifies + * the type of garbage collection operation that occurred. + * See perf_hooks.constants for valid values. + */ + readonly kind?: number | undefined; + /** + * When `performanceEntry.entryType` is equal to 'gc', the `performance.flags` + * property contains additional information about garbage collection operation. + * See perf_hooks.constants for valid values. + */ + readonly flags?: number | undefined; + } + /** + * @since v8.5.0 + */ + class PerformanceEntry { + protected constructor(); + /** + * The total number of milliseconds elapsed for this entry. This value will not + * be meaningful for all Performance Entry types. + * @since v8.5.0 + */ + readonly duration: number; + /** + * The name of the performance entry. + * @since v8.5.0 + */ + readonly name: string; + /** + * The high resolution millisecond timestamp marking the starting time of the + * Performance Entry. + * @since v8.5.0 + */ + readonly startTime: number; + /** + * The type of the performance entry. It may be one of: + * + * * `'node'` (Node.js only) + * * `'mark'` (available on the Web) + * * `'measure'` (available on the Web) + * * `'gc'` (Node.js only) + * * `'function'` (Node.js only) + * * `'http2'` (Node.js only) + * * `'http'` (Node.js only) + * @since v8.5.0 + */ + readonly entryType: EntryType; + /** + * Additional detail specific to the `entryType`. + * @since v16.0.0 + */ + readonly detail?: NodeGCPerformanceDetail | unknown | undefined; // TODO: Narrow this based on entry type. + toJSON(): any; + } + class PerformanceMark extends PerformanceEntry { + readonly duration: 0; + readonly entryType: "mark"; + } + class PerformanceMeasure extends PerformanceEntry { + readonly entryType: "measure"; + } + /** + * _This property is an extension by Node.js. It is not available in Web browsers._ + * + * Provides timing details for Node.js itself. The constructor of this class + * is not exposed to users. + * @since v8.5.0 + */ + class PerformanceNodeTiming extends PerformanceEntry { + /** + * The high resolution millisecond timestamp at which the Node.js process + * completed bootstrapping. If bootstrapping has not yet finished, the property + * has the value of -1. + * @since v8.5.0 + */ + readonly bootstrapComplete: number; + /** + * The high resolution millisecond timestamp at which the Node.js environment was + * initialized. + * @since v8.5.0 + */ + readonly environment: number; + /** + * The high resolution millisecond timestamp of the amount of time the event loop + * has been idle within the event loop's event provider (e.g. `epoll_wait`). This + * does not take CPU usage into consideration. If the event loop has not yet + * started (e.g., in the first tick of the main script), the property has the + * value of 0. + * @since v14.10.0, v12.19.0 + */ + readonly idleTime: number; + /** + * The high resolution millisecond timestamp at which the Node.js event loop + * exited. If the event loop has not yet exited, the property has the value of -1\. + * It can only have a value of not -1 in a handler of the `'exit'` event. + * @since v8.5.0 + */ + readonly loopExit: number; + /** + * The high resolution millisecond timestamp at which the Node.js event loop + * started. If the event loop has not yet started (e.g., in the first tick of the + * main script), the property has the value of -1. + * @since v8.5.0 + */ + readonly loopStart: number; + /** + * The high resolution millisecond timestamp at which the V8 platform was + * initialized. + * @since v8.5.0 + */ + readonly v8Start: number; + } + interface EventLoopUtilization { + idle: number; + active: number; + utilization: number; + } + /** + * @param util1 The result of a previous call to eventLoopUtilization() + * @param util2 The result of a previous call to eventLoopUtilization() prior to util1 + */ + type EventLoopUtilityFunction = ( + util1?: EventLoopUtilization, + util2?: EventLoopUtilization, + ) => EventLoopUtilization; + interface MarkOptions { + /** + * Additional optional detail to include with the mark. + */ + detail?: unknown | undefined; + /** + * An optional timestamp to be used as the mark time. + * @default `performance.now()`. + */ + startTime?: number | undefined; + } + interface MeasureOptions { + /** + * Additional optional detail to include with the mark. + */ + detail?: unknown | undefined; + /** + * Duration between start and end times. + */ + duration?: number | undefined; + /** + * Timestamp to be used as the end time, or a string identifying a previously recorded mark. + */ + end?: number | string | undefined; + /** + * Timestamp to be used as the start time, or a string identifying a previously recorded mark. + */ + start?: number | string | undefined; + } + interface TimerifyOptions { + /** + * A histogram object created using + * `perf_hooks.createHistogram()` that will record runtime durations in + * nanoseconds. + */ + histogram?: RecordableHistogram | undefined; + } + interface Performance { + /** + * If name is not provided, removes all PerformanceMark objects from the Performance Timeline. + * If name is provided, removes only the named mark. + * @param name + */ + clearMarks(name?: string): void; + /** + * If name is not provided, removes all PerformanceMeasure objects from the Performance Timeline. + * If name is provided, removes only the named measure. + * @param name + * @since v16.7.0 + */ + clearMeasures(name?: string): void; + /** + * Returns a list of `PerformanceEntry` objects in chronological order with respect to `performanceEntry.startTime`. + * If you are only interested in performance entries of certain types or that have certain names, see + * `performance.getEntriesByType()` and `performance.getEntriesByName()`. + * @since v16.7.0 + */ + getEntries(): PerformanceEntry[]; + /** + * Returns a list of `PerformanceEntry` objects in chronological order with respect to `performanceEntry.startTime` + * whose `performanceEntry.name` is equal to `name`, and optionally, whose `performanceEntry.entryType` is equal to `type`. + * @param name + * @param type + * @since v16.7.0 + */ + getEntriesByName(name: string, type?: EntryType): PerformanceEntry[]; + /** + * Returns a list of `PerformanceEntry` objects in chronological order with respect to `performanceEntry.startTime` + * whose `performanceEntry.entryType` is equal to `type`. + * @param type + * @since v16.7.0 + */ + getEntriesByType(type: EntryType): PerformanceEntry[]; + /** + * Creates a new PerformanceMark entry in the Performance Timeline. + * A PerformanceMark is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'mark', + * and whose performanceEntry.duration is always 0. + * Performance marks are used to mark specific significant moments in the Performance Timeline. + * @param name + * @return The PerformanceMark entry that was created + */ + mark(name?: string, options?: MarkOptions): PerformanceMark; + /** + * Creates a new PerformanceMeasure entry in the Performance Timeline. + * A PerformanceMeasure is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'measure', + * and whose performanceEntry.duration measures the number of milliseconds elapsed since startMark and endMark. + * + * The startMark argument may identify any existing PerformanceMark in the the Performance Timeline, or may identify + * any of the timestamp properties provided by the PerformanceNodeTiming class. If the named startMark does not exist, + * then startMark is set to timeOrigin by default. + * + * The endMark argument must identify any existing PerformanceMark in the the Performance Timeline or any of the timestamp + * properties provided by the PerformanceNodeTiming class. If the named endMark does not exist, an error will be thrown. + * @param name + * @param startMark + * @param endMark + * @return The PerformanceMeasure entry that was created + */ + measure(name: string, startMark?: string, endMark?: string): PerformanceMeasure; + measure(name: string, options: MeasureOptions): PerformanceMeasure; + /** + * An instance of the PerformanceNodeTiming class that provides performance metrics for specific Node.js operational milestones. + */ + readonly nodeTiming: PerformanceNodeTiming; + /** + * @return the current high resolution millisecond timestamp + */ + now(): number; + /** + * The timeOrigin specifies the high resolution millisecond timestamp from which all performance metric durations are measured. + */ + readonly timeOrigin: number; + /** + * Wraps a function within a new function that measures the running time of the wrapped function. + * A PerformanceObserver must be subscribed to the 'function' event type in order for the timing details to be accessed. + * @param fn + */ + timerify any>(fn: T, options?: TimerifyOptions): T; + /** + * eventLoopUtilization is similar to CPU utilization except that it is calculated using high precision wall-clock time. + * It represents the percentage of time the event loop has spent outside the event loop's event provider (e.g. epoll_wait). + * No other CPU idle time is taken into consideration. + */ + eventLoopUtilization: EventLoopUtilityFunction; + } + interface PerformanceObserverEntryList { + /** + * Returns a list of `PerformanceEntry` objects in chronological order + * with respect to `performanceEntry.startTime`. + * + * ```js + * const { + * performance, + * PerformanceObserver + * } = require('perf_hooks'); + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntries()); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 81.465639, + * * duration: 0 + * * }, + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 81.860064, + * * duration: 0 + * * } + * * ] + * + * performance.clearMarks(); + * performance.clearMeasures(); + * observer.disconnect(); + * }); + * obs.observe({ type: 'mark' }); + * + * performance.mark('test'); + * performance.mark('meow'); + * ``` + * @since v8.5.0 + */ + getEntries(): PerformanceEntry[]; + /** + * Returns a list of `PerformanceEntry` objects in chronological order + * with respect to `performanceEntry.startTime` whose `performanceEntry.name` is + * equal to `name`, and optionally, whose `performanceEntry.entryType` is equal to`type`. + * + * ```js + * const { + * performance, + * PerformanceObserver + * } = require('perf_hooks'); + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntriesByName('meow')); + * + * * [ + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 98.545991, + * * duration: 0 + * * } + * * ] + * + * console.log(perfObserverList.getEntriesByName('nope')); // [] + * + * console.log(perfObserverList.getEntriesByName('test', 'mark')); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 63.518931, + * * duration: 0 + * * } + * * ] + * + * console.log(perfObserverList.getEntriesByName('test', 'measure')); // [] + * + * performance.clearMarks(); + * performance.clearMeasures(); + * observer.disconnect(); + * }); + * obs.observe({ entryTypes: ['mark', 'measure'] }); + * + * performance.mark('test'); + * performance.mark('meow'); + * ``` + * @since v8.5.0 + */ + getEntriesByName(name: string, type?: EntryType): PerformanceEntry[]; + /** + * Returns a list of `PerformanceEntry` objects in chronological order + * with respect to `performanceEntry.startTime` whose `performanceEntry.entryType`is equal to `type`. + * + * ```js + * const { + * performance, + * PerformanceObserver + * } = require('perf_hooks'); + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntriesByType('mark')); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 55.897834, + * * duration: 0 + * * }, + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 56.350146, + * * duration: 0 + * * } + * * ] + * + * performance.clearMarks(); + * performance.clearMeasures(); + * observer.disconnect(); + * }); + * obs.observe({ type: 'mark' }); + * + * performance.mark('test'); + * performance.mark('meow'); + * ``` + * @since v8.5.0 + */ + getEntriesByType(type: EntryType): PerformanceEntry[]; + } + type PerformanceObserverCallback = (list: PerformanceObserverEntryList, observer: PerformanceObserver) => void; + class PerformanceObserver extends AsyncResource { + constructor(callback: PerformanceObserverCallback); + /** + * Disconnects the `PerformanceObserver` instance from all notifications. + * @since v8.5.0 + */ + disconnect(): void; + /** + * Subscribes the `PerformanceObserver` instance to notifications of new `PerformanceEntry` instances identified either by `options.entryTypes`or `options.type`: + * + * ```js + * const { + * performance, + * PerformanceObserver + * } = require('perf_hooks'); + * + * const obs = new PerformanceObserver((list, observer) => { + * // Called once asynchronously. `list` contains three items. + * }); + * obs.observe({ type: 'mark' }); + * + * for (let n = 0; n < 3; n++) + * performance.mark(`test${n}`); + * ``` + * @since v8.5.0 + */ + observe( + options: + | { + entryTypes: readonly EntryType[]; + buffered?: boolean | undefined; + } + | { + type: EntryType; + buffered?: boolean | undefined; + }, + ): void; + } + namespace constants { + const NODE_PERFORMANCE_GC_MAJOR: number; + const NODE_PERFORMANCE_GC_MINOR: number; + const NODE_PERFORMANCE_GC_INCREMENTAL: number; + const NODE_PERFORMANCE_GC_WEAKCB: number; + const NODE_PERFORMANCE_GC_FLAGS_NO: number; + const NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINED: number; + const NODE_PERFORMANCE_GC_FLAGS_FORCED: number; + const NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSING: number; + const NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGE: number; + const NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORY: number; + const NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE: number; + } + const performance: Performance; + interface EventLoopMonitorOptions { + /** + * The sampling rate in milliseconds. + * Must be greater than zero. + * @default 10 + */ + resolution?: number | undefined; + } + interface Histogram { + /** + * Returns a `Map` object detailing the accumulated percentile distribution. + * @since v11.10.0 + */ + readonly percentiles: Map; + /** + * The number of times the event loop delay exceeded the maximum 1 hour event + * loop delay threshold. + * @since v11.10.0 + */ + readonly exceeds: number; + /** + * The minimum recorded event loop delay. + * @since v11.10.0 + */ + readonly min: number; + /** + * The maximum recorded event loop delay. + * @since v11.10.0 + */ + readonly max: number; + /** + * The mean of the recorded event loop delays. + * @since v11.10.0 + */ + readonly mean: number; + /** + * The standard deviation of the recorded event loop delays. + * @since v11.10.0 + */ + readonly stddev: number; + /** + * Resets the collected histogram data. + * @since v11.10.0 + */ + reset(): void; + /** + * Returns the value at the given percentile. + * @since v11.10.0 + * @param percentile A percentile value in the range (0, 100]. + */ + percentile(percentile: number): number; + } + interface IntervalHistogram extends Histogram { + /** + * Enables the update interval timer. Returns `true` if the timer was + * started, `false` if it was already started. + * @since v11.10.0 + */ + enable(): boolean; + /** + * Disables the update interval timer. Returns `true` if the timer was + * stopped, `false` if it was already stopped. + * @since v11.10.0 + */ + disable(): boolean; + } + interface RecordableHistogram extends Histogram { + /** + * @since v15.9.0, v14.18.0 + * @param val The amount to record in the histogram. + */ + record(val: number | bigint): void; + /** + * Calculates the amount of time (in nanoseconds) that has passed since the + * previous call to `recordDelta()` and records that amount in the histogram. + * + * ## Examples + * @since v15.9.0, v14.18.0 + */ + recordDelta(): void; + /** + * Adds the values from other to this histogram. + * @since v17.4.0, v16.14.0 + * @param other Recordable Histogram to combine with + */ + add(other: RecordableHistogram): void; + } + /** + * _This property is an extension by Node.js. It is not available in Web browsers._ + * + * Creates an `IntervalHistogram` object that samples and reports the event loop + * delay over time. The delays will be reported in nanoseconds. + * + * Using a timer to detect approximate event loop delay works because the + * execution of timers is tied specifically to the lifecycle of the libuv + * event loop. That is, a delay in the loop will cause a delay in the execution + * of the timer, and those delays are specifically what this API is intended to + * detect. + * + * ```js + * const { monitorEventLoopDelay } = require('perf_hooks'); + * const h = monitorEventLoopDelay({ resolution: 20 }); + * h.enable(); + * // Do something. + * h.disable(); + * console.log(h.min); + * console.log(h.max); + * console.log(h.mean); + * console.log(h.stddev); + * console.log(h.percentiles); + * console.log(h.percentile(50)); + * console.log(h.percentile(99)); + * ``` + * @since v11.10.0 + */ + function monitorEventLoopDelay(options?: EventLoopMonitorOptions): IntervalHistogram; + interface CreateHistogramOptions { + /** + * The minimum recordable value. Must be an integer value greater than 0. + * @default 1 + */ + min?: number | bigint | undefined; + /** + * The maximum recordable value. Must be an integer value greater than min. + * @default Number.MAX_SAFE_INTEGER + */ + max?: number | bigint | undefined; + /** + * The number of accuracy digits. Must be a number between 1 and 5. + * @default 3 + */ + figures?: number | undefined; + } + /** + * Returns a `RecordableHistogram`. + * @since v15.9.0, v14.18.0 + */ + function createHistogram(options?: CreateHistogramOptions): RecordableHistogram; + + import { performance as _performance } from "perf_hooks"; + global { + /** + * `performance` is a global reference for `require('perf_hooks').performance` + * https://nodejs.org/api/globals.html#performance + * @since v16.0.0 + */ + var performance: typeof globalThis extends { + onmessage: any; + performance: infer T; + } ? T + : typeof _performance; + } +} +declare module "node:perf_hooks" { + export * from "perf_hooks"; +} diff --git a/backend/node_modules/@types/node/process.d.ts b/backend/node_modules/@types/node/process.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c5d6f8711ad6421a4fb5c1d4e37bdd6d94b7a8f4 --- /dev/null +++ b/backend/node_modules/@types/node/process.d.ts @@ -0,0 +1,1548 @@ +declare module "process" { + import * as tty from "node:tty"; + import { Worker } from "node:worker_threads"; + global { + var process: NodeJS.Process; + namespace NodeJS { + // this namespace merge is here because these are specifically used + // as the type for process.stdin, process.stdout, and process.stderr. + // they can't live in tty.d.ts because we need to disambiguate the imported name. + interface ReadStream extends tty.ReadStream {} + interface WriteStream extends tty.WriteStream {} + interface MemoryUsageFn { + /** + * The `process.memoryUsage()` method iterate over each page to gather informations about memory + * usage which can be slow depending on the program memory allocations. + */ + (): MemoryUsage; + /** + * method returns an integer representing the Resident Set Size (RSS) in bytes. + */ + rss(): number; + } + interface MemoryUsage { + rss: number; + heapTotal: number; + heapUsed: number; + external: number; + arrayBuffers: number; + } + interface CpuUsage { + user: number; + system: number; + } + interface ProcessRelease { + name: string; + sourceUrl?: string | undefined; + headersUrl?: string | undefined; + libUrl?: string | undefined; + lts?: string | undefined; + } + interface ProcessVersions extends Dict { + http_parser: string; + node: string; + v8: string; + ares: string; + uv: string; + zlib: string; + modules: string; + openssl: string; + } + type Platform = + | "aix" + | "android" + | "darwin" + | "freebsd" + | "haiku" + | "linux" + | "openbsd" + | "sunos" + | "win32" + | "cygwin" + | "netbsd"; + type Architecture = + | "arm" + | "arm64" + | "ia32" + | "mips" + | "mipsel" + | "ppc" + | "ppc64" + | "s390" + | "s390x" + | "x64"; + type Signals = + | "SIGABRT" + | "SIGALRM" + | "SIGBUS" + | "SIGCHLD" + | "SIGCONT" + | "SIGFPE" + | "SIGHUP" + | "SIGILL" + | "SIGINT" + | "SIGIO" + | "SIGIOT" + | "SIGKILL" + | "SIGPIPE" + | "SIGPOLL" + | "SIGPROF" + | "SIGPWR" + | "SIGQUIT" + | "SIGSEGV" + | "SIGSTKFLT" + | "SIGSTOP" + | "SIGSYS" + | "SIGTERM" + | "SIGTRAP" + | "SIGTSTP" + | "SIGTTIN" + | "SIGTTOU" + | "SIGUNUSED" + | "SIGURG" + | "SIGUSR1" + | "SIGUSR2" + | "SIGVTALRM" + | "SIGWINCH" + | "SIGXCPU" + | "SIGXFSZ" + | "SIGBREAK" + | "SIGLOST" + | "SIGINFO"; + type UncaughtExceptionOrigin = "uncaughtException" | "unhandledRejection"; + type MultipleResolveType = "resolve" | "reject"; + type BeforeExitListener = (code: number) => void; + type DisconnectListener = () => void; + type ExitListener = (code: number) => void; + type RejectionHandledListener = (promise: Promise) => void; + type UncaughtExceptionListener = (error: Error, origin: UncaughtExceptionOrigin) => void; + /** + * Most of the time the unhandledRejection will be an Error, but this should not be relied upon + * as *anything* can be thrown/rejected, it is therefore unsafe to assume that the value is an Error. + */ + type UnhandledRejectionListener = (reason: unknown, promise: Promise) => void; + type WarningListener = (warning: Error) => void; + type MessageListener = (message: unknown, sendHandle: unknown) => void; + type SignalsListener = (signal: Signals) => void; + type MultipleResolveListener = ( + type: MultipleResolveType, + promise: Promise, + value: unknown, + ) => void; + type WorkerListener = (worker: Worker) => void; + interface Socket extends ReadWriteStream { + isTTY?: true | undefined; + } + // Alias for compatibility + interface ProcessEnv extends Dict { + /** + * Can be used to change the default timezone at runtime + */ + TZ?: string; + } + interface HRTime { + (time?: [number, number]): [number, number]; + bigint(): bigint; + } + interface ProcessReport { + /** + * Directory where the report is written. + * working directory of the Node.js process. + * @default '' indicating that reports are written to the current + */ + directory: string; + /** + * Filename where the report is written. + * The default value is the empty string. + * @default '' the output filename will be comprised of a timestamp, + * PID, and sequence number. + */ + filename: string; + /** + * Returns a JSON-formatted diagnostic report for the running process. + * The report's JavaScript stack trace is taken from err, if present. + */ + getReport(err?: Error): string; + /** + * If true, a diagnostic report is generated on fatal errors, + * such as out of memory errors or failed C++ assertions. + * @default false + */ + reportOnFatalError: boolean; + /** + * If true, a diagnostic report is generated when the process + * receives the signal specified by process.report.signal. + * @default false + */ + reportOnSignal: boolean; + /** + * If true, a diagnostic report is generated on uncaught exception. + * @default false + */ + reportOnUncaughtException: boolean; + /** + * The signal used to trigger the creation of a diagnostic report. + * @default 'SIGUSR2' + */ + signal: Signals; + /** + * Writes a diagnostic report to a file. If filename is not provided, the default filename + * includes the date, time, PID, and a sequence number. + * The report's JavaScript stack trace is taken from err, if present. + * + * @param fileName Name of the file where the report is written. + * This should be a relative path, that will be appended to the directory specified in + * `process.report.directory`, or the current working directory of the Node.js process, + * if unspecified. + * @param error A custom error used for reporting the JavaScript stack. + * @return Filename of the generated report. + */ + writeReport(fileName?: string): string; + writeReport(error?: Error): string; + writeReport(fileName?: string, err?: Error): string; + } + interface ResourceUsage { + fsRead: number; + fsWrite: number; + involuntaryContextSwitches: number; + ipcReceived: number; + ipcSent: number; + majorPageFault: number; + maxRSS: number; + minorPageFault: number; + sharedMemorySize: number; + signalsCount: number; + swappedOut: number; + systemCPUTime: number; + unsharedDataSize: number; + unsharedStackSize: number; + userCPUTime: number; + voluntaryContextSwitches: number; + } + interface EmitWarningOptions { + /** + * When `warning` is a `string`, `type` is the name to use for the _type_ of warning being emitted. + * + * @default 'Warning' + */ + type?: string | undefined; + /** + * A unique identifier for the warning instance being emitted. + */ + code?: string | undefined; + /** + * When `warning` is a `string`, `ctor` is an optional function used to limit the generated stack trace. + * + * @default process.emitWarning + */ + ctor?: Function | undefined; + /** + * Additional text to include with the error. + */ + detail?: string | undefined; + } + interface ProcessConfig { + readonly target_defaults: { + readonly cflags: any[]; + readonly default_configuration: string; + readonly defines: string[]; + readonly include_dirs: string[]; + readonly libraries: string[]; + }; + readonly variables: { + readonly clang: number; + readonly host_arch: string; + readonly node_install_npm: boolean; + readonly node_install_waf: boolean; + readonly node_prefix: string; + readonly node_shared_openssl: boolean; + readonly node_shared_v8: boolean; + readonly node_shared_zlib: boolean; + readonly node_use_dtrace: boolean; + readonly node_use_etw: boolean; + readonly node_use_openssl: boolean; + readonly target_arch: string; + readonly v8_no_strict_aliasing: number; + readonly v8_use_snapshot: boolean; + readonly visibility: string; + }; + } + interface Process extends EventEmitter { + /** + * The `process.stdout` property returns a stream connected to`stdout` (fd `1`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `1` refers to a file, in which case it is + * a `Writable` stream. + * + * For example, to copy `process.stdin` to `process.stdout`: + * + * ```js + * import { stdin, stdout } from 'process'; + * + * stdin.pipe(stdout); + * ``` + * + * `process.stdout` differs from other Node.js streams in important ways. See `note on process I/O` for more information. + */ + stdout: WriteStream & { + fd: 1; + }; + /** + * The `process.stderr` property returns a stream connected to`stderr` (fd `2`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `2` refers to a file, in which case it is + * a `Writable` stream. + * + * `process.stderr` differs from other Node.js streams in important ways. See `note on process I/O` for more information. + */ + stderr: WriteStream & { + fd: 2; + }; + /** + * The `process.stdin` property returns a stream connected to`stdin` (fd `0`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `0` refers to a file, in which case it is + * a `Readable` stream. + * + * For details of how to read from `stdin` see `readable.read()`. + * + * As a `Duplex` stream, `process.stdin` can also be used in "old" mode that + * is compatible with scripts written for Node.js prior to v0.10\. + * For more information see `Stream compatibility`. + * + * In "old" streams mode the `stdin` stream is paused by default, so one + * must call `process.stdin.resume()` to read from it. Note also that calling`process.stdin.resume()` itself would switch stream to "old" mode. + */ + stdin: ReadStream & { + fd: 0; + }; + openStdin(): Socket; + /** + * The `process.argv` property returns an array containing the command-line + * arguments passed when the Node.js process was launched. The first element will + * be {@link execPath}. See `process.argv0` if access to the original value + * of `argv[0]` is needed. The second element will be the path to the JavaScript + * file being executed. The remaining elements will be any additional command-line + * arguments. + * + * For example, assuming the following script for `process-args.js`: + * + * ```js + * import { argv } from 'process'; + * + * // print process.argv + * argv.forEach((val, index) => { + * console.log(`${index}: ${val}`); + * }); + * ``` + * + * Launching the Node.js process as: + * + * ```console + * $ node process-args.js one two=three four + * ``` + * + * Would generate the output: + * + * ```text + * 0: /usr/local/bin/node + * 1: /Users/mjr/work/node/process-args.js + * 2: one + * 3: two=three + * 4: four + * ``` + * @since v0.1.27 + */ + argv: string[]; + /** + * The `process.argv0` property stores a read-only copy of the original value of`argv[0]` passed when Node.js starts. + * + * ```console + * $ bash -c 'exec -a customArgv0 ./node' + * > process.argv[0] + * '/Volumes/code/external/node/out/Release/node' + * > process.argv0 + * 'customArgv0' + * ``` + * @since v6.4.0 + */ + argv0: string; + /** + * The `process.execArgv` property returns the set of Node.js-specific command-line + * options passed when the Node.js process was launched. These options do not + * appear in the array returned by the {@link argv} property, and do not + * include the Node.js executable, the name of the script, or any options following + * the script name. These options are useful in order to spawn child processes with + * the same execution environment as the parent. + * + * ```console + * $ node --harmony script.js --version + * ``` + * + * Results in `process.execArgv`: + * + * ```js + * ['--harmony'] + * ``` + * + * And `process.argv`: + * + * ```js + * ['/usr/local/bin/node', 'script.js', '--version'] + * ``` + * + * Refer to `Worker constructor` for the detailed behavior of worker + * threads with this property. + * @since v0.7.7 + */ + execArgv: string[]; + /** + * The `process.execPath` property returns the absolute pathname of the executable + * that started the Node.js process. Symbolic links, if any, are resolved. + * + * ```js + * '/usr/local/bin/node' + * ``` + * @since v0.1.100 + */ + execPath: string; + /** + * The `process.abort()` method causes the Node.js process to exit immediately and + * generate a core file. + * + * This feature is not available in `Worker` threads. + * @since v0.7.0 + */ + abort(): never; + /** + * The `process.chdir()` method changes the current working directory of the + * Node.js process or throws an exception if doing so fails (for instance, if + * the specified `directory` does not exist). + * + * ```js + * import { chdir, cwd } from 'process'; + * + * console.log(`Starting directory: ${cwd()}`); + * try { + * chdir('/tmp'); + * console.log(`New directory: ${cwd()}`); + * } catch (err) { + * console.error(`chdir: ${err}`); + * } + * ``` + * + * This feature is not available in `Worker` threads. + * @since v0.1.17 + */ + chdir(directory: string): void; + /** + * The `process.cwd()` method returns the current working directory of the Node.js + * process. + * + * ```js + * import { cwd } from 'process'; + * + * console.log(`Current directory: ${cwd()}`); + * ``` + * @since v0.1.8 + */ + cwd(): string; + /** + * The port used by the Node.js debugger when enabled. + * + * ```js + * import process from 'process'; + * + * process.debugPort = 5858; + * ``` + * @since v0.7.2 + */ + debugPort: number; + /** + * The `process.emitWarning()` method can be used to emit custom or application + * specific process warnings. These can be listened for by adding a handler to the `'warning'` event. + * + * ```js + * import { emitWarning } from 'process'; + * + * // Emit a warning with a code and additional detail. + * emitWarning('Something happened!', { + * code: 'MY_WARNING', + * detail: 'This is some additional information' + * }); + * // Emits: + * // (node:56338) [MY_WARNING] Warning: Something happened! + * // This is some additional information + * ``` + * + * In this example, an `Error` object is generated internally by`process.emitWarning()` and passed through to the `'warning'` handler. + * + * ```js + * import process from 'process'; + * + * process.on('warning', (warning) => { + * console.warn(warning.name); // 'Warning' + * console.warn(warning.message); // 'Something happened!' + * console.warn(warning.code); // 'MY_WARNING' + * console.warn(warning.stack); // Stack trace + * console.warn(warning.detail); // 'This is some additional information' + * }); + * ``` + * + * If `warning` is passed as an `Error` object, the `options` argument is ignored. + * @since v8.0.0 + * @param warning The warning to emit. + */ + emitWarning(warning: string | Error, ctor?: Function): void; + emitWarning(warning: string | Error, type?: string, ctor?: Function): void; + emitWarning(warning: string | Error, type?: string, code?: string, ctor?: Function): void; + emitWarning(warning: string | Error, options?: EmitWarningOptions): void; + /** + * The `process.env` property returns an object containing the user environment. + * See [`environ(7)`](http://man7.org/linux/man-pages/man7/environ.7.html). + * + * An example of this object looks like: + * + * ```js + * { + * TERM: 'xterm-256color', + * SHELL: '/usr/local/bin/bash', + * USER: 'maciej', + * PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin', + * PWD: '/Users/maciej', + * EDITOR: 'vim', + * SHLVL: '1', + * HOME: '/Users/maciej', + * LOGNAME: 'maciej', + * _: '/usr/local/bin/node' + * } + * ``` + * + * It is possible to modify this object, but such modifications will not be + * reflected outside the Node.js process, or (unless explicitly requested) + * to other `Worker` threads. + * In other words, the following example would not work: + * + * ```console + * $ node -e 'process.env.foo = "bar"' && echo $foo + * ``` + * + * While the following will: + * + * ```js + * import { env } from 'process'; + * + * env.foo = 'bar'; + * console.log(env.foo); + * ``` + * + * Assigning a property on `process.env` will implicitly convert the value + * to a string. **This behavior is deprecated.** Future versions of Node.js may + * throw an error when the value is not a string, number, or boolean. + * + * ```js + * import { env } from 'process'; + * + * env.test = null; + * console.log(env.test); + * // => 'null' + * env.test = undefined; + * console.log(env.test); + * // => 'undefined' + * ``` + * + * Use `delete` to delete a property from `process.env`. + * + * ```js + * import { env } from 'process'; + * + * env.TEST = 1; + * delete env.TEST; + * console.log(env.TEST); + * // => undefined + * ``` + * + * On Windows operating systems, environment variables are case-insensitive. + * + * ```js + * import { env } from 'process'; + * + * env.TEST = 1; + * console.log(env.test); + * // => 1 + * ``` + * + * Unless explicitly specified when creating a `Worker` instance, + * each `Worker` thread has its own copy of `process.env`, based on its + * parent thread’s `process.env`, or whatever was specified as the `env` option + * to the `Worker` constructor. Changes to `process.env` will not be visible + * across `Worker` threads, and only the main thread can make changes that + * are visible to the operating system or to native add-ons. + * @since v0.1.27 + */ + env: ProcessEnv; + /** + * The `process.exit()` method instructs Node.js to terminate the process + * synchronously with an exit status of `code`. If `code` is omitted, exit uses + * either the 'success' code `0` or the value of `process.exitCode` if it has been + * set. Node.js will not terminate until all the `'exit'` event listeners are + * called. + * + * To exit with a 'failure' code: + * + * ```js + * import { exit } from 'process'; + * + * exit(1); + * ``` + * + * The shell that executed Node.js should see the exit code as `1`. + * + * Calling `process.exit()` will force the process to exit as quickly as possible + * even if there are still asynchronous operations pending that have not yet + * completed fully, including I/O operations to `process.stdout` and`process.stderr`. + * + * In most situations, it is not actually necessary to call `process.exit()`explicitly. The Node.js process will exit on its own _if there is no additional_ + * _work pending_ in the event loop. The `process.exitCode` property can be set to + * tell the process which exit code to use when the process exits gracefully. + * + * For instance, the following example illustrates a _misuse_ of the`process.exit()` method that could lead to data printed to stdout being + * truncated and lost: + * + * ```js + * import { exit } from 'process'; + * + * // This is an example of what *not* to do: + * if (someConditionNotMet()) { + * printUsageToStdout(); + * exit(1); + * } + * ``` + * + * The reason this is problematic is because writes to `process.stdout` in Node.js + * are sometimes _asynchronous_ and may occur over multiple ticks of the Node.js + * event loop. Calling `process.exit()`, however, forces the process to exit _before_ those additional writes to `stdout` can be performed. + * + * Rather than calling `process.exit()` directly, the code _should_ set the`process.exitCode` and allow the process to exit naturally by avoiding + * scheduling any additional work for the event loop: + * + * ```js + * import process from 'process'; + * + * // How to properly set the exit code while letting + * // the process exit gracefully. + * if (someConditionNotMet()) { + * printUsageToStdout(); + * process.exitCode = 1; + * } + * ``` + * + * If it is necessary to terminate the Node.js process due to an error condition, + * throwing an _uncaught_ error and allowing the process to terminate accordingly + * is safer than calling `process.exit()`. + * + * In `Worker` threads, this function stops the current thread rather + * than the current process. + * @since v0.1.13 + * @param [code=0] The exit code. + */ + exit(code?: number): never; + /** + * A number which will be the process exit code, when the process either + * exits gracefully, or is exited via {@link exit} without specifying + * a code. + * + * Specifying a code to {@link exit} will override any + * previous setting of `process.exitCode`. + * @since v0.11.8 + */ + exitCode?: number | undefined; + /** + * The `process.getgid()` method returns the numerical group identity of the + * process. (See [`getgid(2)`](http://man7.org/linux/man-pages/man2/getgid.2.html).) + * + * ```js + * import process from 'process'; + * + * if (process.getgid) { + * console.log(`Current gid: ${process.getgid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v0.1.31 + */ + getgid?: () => number; + /** + * The `process.setgid()` method sets the group identity of the process. (See [`setgid(2)`](http://man7.org/linux/man-pages/man2/setgid.2.html).) The `id` can be passed as either a + * numeric ID or a group name + * string. If a group name is specified, this method blocks while resolving the + * associated numeric ID. + * + * ```js + * import process from 'process'; + * + * if (process.getgid && process.setgid) { + * console.log(`Current gid: ${process.getgid()}`); + * try { + * process.setgid(501); + * console.log(`New gid: ${process.getgid()}`); + * } catch (err) { + * console.log(`Failed to set gid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v0.1.31 + * @param id The group name or ID + */ + setgid?: (id: number | string) => void; + /** + * The `process.getuid()` method returns the numeric user identity of the process. + * (See [`getuid(2)`](http://man7.org/linux/man-pages/man2/getuid.2.html).) + * + * ```js + * import process from 'process'; + * + * if (process.getuid) { + * console.log(`Current uid: ${process.getuid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v0.1.28 + */ + getuid?: () => number; + /** + * The `process.setuid(id)` method sets the user identity of the process. (See [`setuid(2)`](http://man7.org/linux/man-pages/man2/setuid.2.html).) The `id` can be passed as either a + * numeric ID or a username string. + * If a username is specified, the method blocks while resolving the associated + * numeric ID. + * + * ```js + * import process from 'process'; + * + * if (process.getuid && process.setuid) { + * console.log(`Current uid: ${process.getuid()}`); + * try { + * process.setuid(501); + * console.log(`New uid: ${process.getuid()}`); + * } catch (err) { + * console.log(`Failed to set uid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v0.1.28 + */ + setuid?: (id: number | string) => void; + /** + * The `process.geteuid()` method returns the numerical effective user identity of + * the process. (See [`geteuid(2)`](http://man7.org/linux/man-pages/man2/geteuid.2.html).) + * + * ```js + * import process from 'process'; + * + * if (process.geteuid) { + * console.log(`Current uid: ${process.geteuid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v2.0.0 + */ + geteuid?: () => number; + /** + * The `process.seteuid()` method sets the effective user identity of the process. + * (See [`seteuid(2)`](http://man7.org/linux/man-pages/man2/seteuid.2.html).) The `id` can be passed as either a numeric ID or a username + * string. If a username is specified, the method blocks while resolving the + * associated numeric ID. + * + * ```js + * import process from 'process'; + * + * if (process.geteuid && process.seteuid) { + * console.log(`Current uid: ${process.geteuid()}`); + * try { + * process.seteuid(501); + * console.log(`New uid: ${process.geteuid()}`); + * } catch (err) { + * console.log(`Failed to set uid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v2.0.0 + * @param id A user name or ID + */ + seteuid?: (id: number | string) => void; + /** + * The `process.getegid()` method returns the numerical effective group identity + * of the Node.js process. (See [`getegid(2)`](http://man7.org/linux/man-pages/man2/getegid.2.html).) + * + * ```js + * import process from 'process'; + * + * if (process.getegid) { + * console.log(`Current gid: ${process.getegid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v2.0.0 + */ + getegid?: () => number; + /** + * The `process.setegid()` method sets the effective group identity of the process. + * (See [`setegid(2)`](http://man7.org/linux/man-pages/man2/setegid.2.html).) The `id` can be passed as either a numeric ID or a group + * name string. If a group name is specified, this method blocks while resolving + * the associated a numeric ID. + * + * ```js + * import process from 'process'; + * + * if (process.getegid && process.setegid) { + * console.log(`Current gid: ${process.getegid()}`); + * try { + * process.setegid(501); + * console.log(`New gid: ${process.getegid()}`); + * } catch (err) { + * console.log(`Failed to set gid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v2.0.0 + * @param id A group name or ID + */ + setegid?: (id: number | string) => void; + /** + * The `process.getgroups()` method returns an array with the supplementary group + * IDs. POSIX leaves it unspecified if the effective group ID is included but + * Node.js ensures it always is. + * + * ```js + * import process from 'process'; + * + * if (process.getgroups) { + * console.log(process.getgroups()); // [ 16, 21, 297 ] + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v0.9.4 + */ + getgroups?: () => number[]; + /** + * The `process.setgroups()` method sets the supplementary group IDs for the + * Node.js process. This is a privileged operation that requires the Node.js + * process to have `root` or the `CAP_SETGID` capability. + * + * The `groups` array can contain numeric group IDs, group names, or both. + * + * ```js + * import process from 'process'; + * + * if (process.getgroups && process.setgroups) { + * try { + * process.setgroups([501]); + * console.log(process.getgroups()); // new groups + * } catch (err) { + * console.log(`Failed to set groups: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v0.9.4 + */ + setgroups?: (groups: ReadonlyArray) => void; + /** + * The `process.setUncaughtExceptionCaptureCallback()` function sets a function + * that will be invoked when an uncaught exception occurs, which will receive the + * exception value itself as its first argument. + * + * If such a function is set, the `'uncaughtException'` event will + * not be emitted. If `--abort-on-uncaught-exception` was passed from the + * command line or set through `v8.setFlagsFromString()`, the process will + * not abort. Actions configured to take place on exceptions such as report + * generations will be affected too + * + * To unset the capture function,`process.setUncaughtExceptionCaptureCallback(null)` may be used. Calling this + * method with a non-`null` argument while another capture function is set will + * throw an error. + * + * Using this function is mutually exclusive with using the deprecated `domain` built-in module. + * @since v9.3.0 + */ + setUncaughtExceptionCaptureCallback(cb: ((err: Error) => void) | null): void; + /** + * Indicates whether a callback has been set using {@link setUncaughtExceptionCaptureCallback}. + * @since v9.3.0 + */ + hasUncaughtExceptionCaptureCallback(): boolean; + /** + * This function enables or disables the Source Map v3 support for stack traces. + * It provides same features as launching Node.js process with commandline options --enable-source-maps. + * @since v16.6.0 + * @experimental + */ + setSourceMapsEnabled(value: boolean): void; + /** + * The `process.sourceMapsEnabled` property returns whether the [Source Map v3](https://sourcemaps.info/spec.html) support for stack traces is enabled. + * @since v18.19.0 + * @experimental + */ + readonly sourceMapsEnabled: boolean; + /** + * The `process.version` property contains the Node.js version string. + * + * ```js + * import { version } from 'process'; + * + * console.log(`Version: ${version}`); + * // Version: v14.8.0 + * ``` + * + * To get the version string without the prepended _v_, use`process.versions.node`. + * @since v0.1.3 + */ + readonly version: string; + /** + * The `process.versions` property returns an object listing the version strings of + * Node.js and its dependencies. `process.versions.modules` indicates the current + * ABI version, which is increased whenever a C++ API changes. Node.js will refuse + * to load modules that were compiled against a different module ABI version. + * + * ```js + * import { versions } from 'process'; + * + * console.log(versions); + * ``` + * + * Will generate an object similar to: + * + * ```console + * { node: '11.13.0', + * v8: '7.0.276.38-node.18', + * uv: '1.27.0', + * zlib: '1.2.11', + * brotli: '1.0.7', + * ares: '1.15.0', + * modules: '67', + * nghttp2: '1.34.0', + * napi: '4', + * llhttp: '1.1.1', + * openssl: '1.1.1b', + * cldr: '34.0', + * icu: '63.1', + * tz: '2018e', + * unicode: '11.0' } + * ``` + * @since v0.2.0 + */ + readonly versions: ProcessVersions; + /** + * The `process.config` property returns an `Object` containing the JavaScript + * representation of the configure options used to compile the current Node.js + * executable. This is the same as the `config.gypi` file that was produced when + * running the `./configure` script. + * + * An example of the possible output looks like: + * + * ```js + * { + * target_defaults: + * { cflags: [], + * default_configuration: 'Release', + * defines: [], + * include_dirs: [], + * libraries: [] }, + * variables: + * { + * host_arch: 'x64', + * napi_build_version: 5, + * node_install_npm: 'true', + * node_prefix: '', + * node_shared_cares: 'false', + * node_shared_http_parser: 'false', + * node_shared_libuv: 'false', + * node_shared_zlib: 'false', + * node_use_dtrace: 'false', + * node_use_openssl: 'true', + * node_shared_openssl: 'false', + * strict_aliasing: 'true', + * target_arch: 'x64', + * v8_use_snapshot: 1 + * } + * } + * ``` + * + * The `process.config` property is **not** read-only and there are existing + * modules in the ecosystem that are known to extend, modify, or entirely replace + * the value of `process.config`. + * + * Modifying the `process.config` property, or any child-property of the`process.config` object has been deprecated. The `process.config` will be made + * read-only in a future release. + * @since v0.7.7 + */ + readonly config: ProcessConfig; + /** + * The `process.kill()` method sends the `signal` to the process identified by`pid`. + * + * Signal names are strings such as `'SIGINT'` or `'SIGHUP'`. See `Signal Events` and [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) for more information. + * + * This method will throw an error if the target `pid` does not exist. As a special + * case, a signal of `0` can be used to test for the existence of a process. + * Windows platforms will throw an error if the `pid` is used to kill a process + * group. + * + * Even though the name of this function is `process.kill()`, it is really just a + * signal sender, like the `kill` system call. The signal sent may do something + * other than kill the target process. + * + * ```js + * import process, { kill } from 'process'; + * + * process.on('SIGHUP', () => { + * console.log('Got SIGHUP signal.'); + * }); + * + * setTimeout(() => { + * console.log('Exiting.'); + * process.exit(0); + * }, 100); + * + * kill(process.pid, 'SIGHUP'); + * ``` + * + * When `SIGUSR1` is received by a Node.js process, Node.js will start the + * debugger. See `Signal Events`. + * @since v0.0.6 + * @param pid A process ID + * @param [signal='SIGTERM'] The signal to send, either as a string or number. + */ + kill(pid: number, signal?: string | number): true; + /** + * The `process.pid` property returns the PID of the process. + * + * ```js + * import { pid } from 'process'; + * + * console.log(`This process is pid ${pid}`); + * ``` + * @since v0.1.15 + */ + readonly pid: number; + /** + * The `process.ppid` property returns the PID of the parent of the + * current process. + * + * ```js + * import { ppid } from 'process'; + * + * console.log(`The parent process is pid ${ppid}`); + * ``` + * @since v9.2.0, v8.10.0, v6.13.0 + */ + readonly ppid: number; + /** + * The `process.title` property returns the current process title (i.e. returns + * the current value of `ps`). Assigning a new value to `process.title` modifies + * the current value of `ps`. + * + * When a new value is assigned, different platforms will impose different maximum + * length restrictions on the title. Usually such restrictions are quite limited. + * For instance, on Linux and macOS, `process.title` is limited to the size of the + * binary name plus the length of the command-line arguments because setting the`process.title` overwrites the `argv` memory of the process. Node.js v0.8 + * allowed for longer process title strings by also overwriting the `environ`memory but that was potentially insecure and confusing in some (rather obscure) + * cases. + * + * Assigning a value to `process.title` might not result in an accurate label + * within process manager applications such as macOS Activity Monitor or Windows + * Services Manager. + * @since v0.1.104 + */ + title: string; + /** + * The operating system CPU architecture for which the Node.js binary was compiled. + * Possible values are: `'arm'`, `'arm64'`, `'ia32'`, `'mips'`,`'mipsel'`, `'ppc'`,`'ppc64'`, `'s390'`, `'s390x'`, and `'x64'`. + * + * ```js + * import { arch } from 'process'; + * + * console.log(`This processor architecture is ${arch}`); + * ``` + * @since v0.5.0 + */ + readonly arch: Architecture; + /** + * The `process.platform` property returns a string identifying the operating + * system platform for which the Node.js binary was compiled. + * + * Currently possible values are: + * + * * `'aix'` + * * `'darwin'` + * * `'freebsd'` + * * `'linux'` + * * `'openbsd'` + * * `'sunos'` + * * `'win32'` + * + * ```js + * import { platform } from 'process'; + * + * console.log(`This platform is ${platform}`); + * ``` + * + * The value `'android'` may also be returned if the Node.js is built on the + * Android operating system. However, Android support in Node.js [is experimental](https://github.com/nodejs/node/blob/HEAD/BUILDING.md#androidandroid-based-devices-eg-firefox-os). + * @since v0.1.16 + */ + readonly platform: Platform; + /** + * The `process.mainModule` property provides an alternative way of retrieving `require.main`. The difference is that if the main module changes at + * runtime, `require.main` may still refer to the original main module in + * modules that were required before the change occurred. Generally, it's + * safe to assume that the two refer to the same module. + * + * As with `require.main`, `process.mainModule` will be `undefined` if there + * is no entry script. + * @since v0.1.17 + * @deprecated Since v14.0.0 - Use `main` instead. + */ + mainModule?: Module | undefined; + memoryUsage: MemoryUsageFn; + /** + * Gets the amount of memory available to the process (in bytes) based on + * limits imposed by the OS. If there is no such constraint, or the constraint + * is unknown, `undefined` is returned. + */ + constrainedMemory(): number | undefined; + /** + * The `process.cpuUsage()` method returns the user and system CPU time usage of + * the current process, in an object with properties `user` and `system`, whose + * values are microsecond values (millionth of a second). These values measure time + * spent in user and system code respectively, and may end up being greater than + * actual elapsed time if multiple CPU cores are performing work for this process. + * + * The result of a previous call to `process.cpuUsage()` can be passed as the + * argument to the function, to get a diff reading. + * + * ```js + * import { cpuUsage } from 'process'; + * + * const startUsage = cpuUsage(); + * // { user: 38579, system: 6986 } + * + * // spin the CPU for 500 milliseconds + * const now = Date.now(); + * while (Date.now() - now < 500); + * + * console.log(cpuUsage(startUsage)); + * // { user: 514883, system: 11226 } + * ``` + * @since v6.1.0 + * @param previousValue A previous return value from calling `process.cpuUsage()` + */ + cpuUsage(previousValue?: CpuUsage): CpuUsage; + /** + * `process.nextTick()` adds `callback` to the "next tick queue". This queue is + * fully drained after the current operation on the JavaScript stack runs to + * completion and before the event loop is allowed to continue. It's possible to + * create an infinite loop if one were to recursively call `process.nextTick()`. + * See the [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#process-nexttick) guide for more background. + * + * ```js + * import { nextTick } from 'process'; + * + * console.log('start'); + * nextTick(() => { + * console.log('nextTick callback'); + * }); + * console.log('scheduled'); + * // Output: + * // start + * // scheduled + * // nextTick callback + * ``` + * + * This is important when developing APIs in order to give users the opportunity + * to assign event handlers _after_ an object has been constructed but before any + * I/O has occurred: + * + * ```js + * import { nextTick } from 'process'; + * + * function MyThing(options) { + * this.setupOptions(options); + * + * nextTick(() => { + * this.startDoingStuff(); + * }); + * } + * + * const thing = new MyThing(); + * thing.getReadyForStuff(); + * + * // thing.startDoingStuff() gets called now, not before. + * ``` + * + * It is very important for APIs to be either 100% synchronous or 100% + * asynchronous. Consider this example: + * + * ```js + * // WARNING! DO NOT USE! BAD UNSAFE HAZARD! + * function maybeSync(arg, cb) { + * if (arg) { + * cb(); + * return; + * } + * + * fs.stat('file', cb); + * } + * ``` + * + * This API is hazardous because in the following case: + * + * ```js + * const maybeTrue = Math.random() > 0.5; + * + * maybeSync(maybeTrue, () => { + * foo(); + * }); + * + * bar(); + * ``` + * + * It is not clear whether `foo()` or `bar()` will be called first. + * + * The following approach is much better: + * + * ```js + * import { nextTick } from 'process'; + * + * function definitelyAsync(arg, cb) { + * if (arg) { + * nextTick(cb); + * return; + * } + * + * fs.stat('file', cb); + * } + * ``` + * @since v0.1.26 + * @param args Additional arguments to pass when invoking the `callback` + */ + nextTick(callback: Function, ...args: any[]): void; + /** + * The `process.release` property returns an `Object` containing metadata related + * to the current release, including URLs for the source tarball and headers-only + * tarball. + * + * `process.release` contains the following properties: + * + * ```js + * { + * name: 'node', + * lts: 'Erbium', + * sourceUrl: 'https://nodejs.org/download/release/v12.18.1/node-v12.18.1.tar.gz', + * headersUrl: 'https://nodejs.org/download/release/v12.18.1/node-v12.18.1-headers.tar.gz', + * libUrl: 'https://nodejs.org/download/release/v12.18.1/win-x64/node.lib' + * } + * ``` + * + * In custom builds from non-release versions of the source tree, only the`name` property may be present. The additional properties should not be + * relied upon to exist. + * @since v3.0.0 + */ + readonly release: ProcessRelease; + features: { + inspector: boolean; + debug: boolean; + uv: boolean; + ipv6: boolean; + tls_alpn: boolean; + tls_sni: boolean; + tls_ocsp: boolean; + tls: boolean; + }; + /** + * `process.umask()` returns the Node.js process's file mode creation mask. Child + * processes inherit the mask from the parent process. + * @since v0.1.19 + * @deprecated Calling `process.umask()` with no argument causes the process-wide umask to be written twice. This introduces a race condition between threads, and is a potential * + * security vulnerability. There is no safe, cross-platform alternative API. + */ + umask(): number; + /** + * Can only be set if not in worker thread. + */ + umask(mask: string | number): number; + /** + * The `process.uptime()` method returns the number of seconds the current Node.js + * process has been running. + * + * The return value includes fractions of a second. Use `Math.floor()` to get whole + * seconds. + * @since v0.5.0 + */ + uptime(): number; + hrtime: HRTime; + /** + * If the Node.js process was spawned with an IPC channel, the process.channel property is a reference to the IPC channel. + * If no IPC channel exists, this property is undefined. + * @since v7.1.0 + */ + channel?: { + /** + * This method makes the IPC channel keep the event loop of the process running if .unref() has been called before. + * @since v7.1.0 + */ + ref(): void; + /** + * This method makes the IPC channel not keep the event loop of the process running, and lets it finish even while the channel is open. + * @since v7.1.0 + */ + unref(): void; + }; + /** + * If Node.js is spawned with an IPC channel, the `process.send()` method can be + * used to send messages to the parent process. Messages will be received as a `'message'` event on the parent's `ChildProcess` object. + * + * If Node.js was not spawned with an IPC channel, `process.send` will be `undefined`. + * + * The message goes through serialization and parsing. The resulting message might + * not be the same as what is originally sent. + * @since v0.5.9 + * @param options used to parameterize the sending of certain types of handles.`options` supports the following properties: + */ + send?( + message: any, + sendHandle?: any, + options?: { + swallowErrors?: boolean | undefined; + }, + callback?: (error: Error | null) => void, + ): boolean; + /** + * If the Node.js process is spawned with an IPC channel (see the `Child Process` and `Cluster` documentation), the `process.disconnect()` method will close the + * IPC channel to the parent process, allowing the child process to exit gracefully + * once there are no other connections keeping it alive. + * + * The effect of calling `process.disconnect()` is the same as calling `ChildProcess.disconnect()` from the parent process. + * + * If the Node.js process was not spawned with an IPC channel,`process.disconnect()` will be `undefined`. + * @since v0.7.2 + */ + disconnect(): void; + /** + * If the Node.js process is spawned with an IPC channel (see the `Child Process` and `Cluster` documentation), the `process.connected` property will return`true` so long as the IPC + * channel is connected and will return `false` after`process.disconnect()` is called. + * + * Once `process.connected` is `false`, it is no longer possible to send messages + * over the IPC channel using `process.send()`. + * @since v0.7.2 + */ + connected: boolean; + /** + * The `process.allowedNodeEnvironmentFlags` property is a special, + * read-only `Set` of flags allowable within the `NODE_OPTIONS` environment variable. + * + * `process.allowedNodeEnvironmentFlags` extends `Set`, but overrides`Set.prototype.has` to recognize several different possible flag + * representations. `process.allowedNodeEnvironmentFlags.has()` will + * return `true` in the following cases: + * + * * Flags may omit leading single (`-`) or double (`--`) dashes; e.g.,`inspect-brk` for `--inspect-brk`, or `r` for `-r`. + * * Flags passed through to V8 (as listed in `--v8-options`) may replace + * one or more _non-leading_ dashes for an underscore, or vice-versa; + * e.g., `--perf_basic_prof`, `--perf-basic-prof`, `--perf_basic-prof`, + * etc. + * * Flags may contain one or more equals (`=`) characters; all + * characters after and including the first equals will be ignored; + * e.g., `--stack-trace-limit=100`. + * * Flags _must_ be allowable within `NODE_OPTIONS`. + * + * When iterating over `process.allowedNodeEnvironmentFlags`, flags will + * appear only _once_; each will begin with one or more dashes. Flags + * passed through to V8 will contain underscores instead of non-leading + * dashes: + * + * ```js + * import { allowedNodeEnvironmentFlags } from 'process'; + * + * allowedNodeEnvironmentFlags.forEach((flag) => { + * // -r + * // --inspect-brk + * // --abort_on_uncaught_exception + * // ... + * }); + * ``` + * + * The methods `add()`, `clear()`, and `delete()` of`process.allowedNodeEnvironmentFlags` do nothing, and will fail + * silently. + * + * If Node.js was compiled _without_ `NODE_OPTIONS` support (shown in {@link config}), `process.allowedNodeEnvironmentFlags` will + * contain what _would have_ been allowable. + * @since v10.10.0 + */ + allowedNodeEnvironmentFlags: ReadonlySet; + /** + * `process.report` is an object whose methods are used to generate diagnostic + * reports for the current process. Additional documentation is available in the `report documentation`. + * @since v11.8.0 + */ + report?: ProcessReport | undefined; + /** + * ```js + * import { resourceUsage } from 'process'; + * + * console.log(resourceUsage()); + * /* + * Will output: + * { + * userCPUTime: 82872, + * systemCPUTime: 4143, + * maxRSS: 33164, + * sharedMemorySize: 0, + * unsharedDataSize: 0, + * unsharedStackSize: 0, + * minorPageFault: 2469, + * majorPageFault: 0, + * swappedOut: 0, + * fsRead: 0, + * fsWrite: 8, + * ipcSent: 0, + * ipcReceived: 0, + * signalsCount: 0, + * voluntaryContextSwitches: 79, + * involuntaryContextSwitches: 1 + * } + * + * ``` + * @since v12.6.0 + * @return the resource usage for the current process. All of these values come from the `uv_getrusage` call which returns a [`uv_rusage_t` struct][uv_rusage_t]. + */ + resourceUsage(): ResourceUsage; + /** + * The `process.traceDeprecation` property indicates whether the`--trace-deprecation` flag is set on the current Node.js process. See the + * documentation for the `'warning' event` and the `emitWarning() method` for more information about this + * flag's behavior. + * @since v0.8.0 + */ + traceDeprecation: boolean; + /* EventEmitter */ + addListener(event: "beforeExit", listener: BeforeExitListener): this; + addListener(event: "disconnect", listener: DisconnectListener): this; + addListener(event: "exit", listener: ExitListener): this; + addListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + addListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + addListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + addListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + addListener(event: "warning", listener: WarningListener): this; + addListener(event: "message", listener: MessageListener): this; + addListener(event: Signals, listener: SignalsListener): this; + addListener(event: "multipleResolves", listener: MultipleResolveListener): this; + addListener(event: "worker", listener: WorkerListener): this; + emit(event: "beforeExit", code: number): boolean; + emit(event: "disconnect"): boolean; + emit(event: "exit", code: number): boolean; + emit(event: "rejectionHandled", promise: Promise): boolean; + emit(event: "uncaughtException", error: Error): boolean; + emit(event: "uncaughtExceptionMonitor", error: Error): boolean; + emit(event: "unhandledRejection", reason: unknown, promise: Promise): boolean; + emit(event: "warning", warning: Error): boolean; + emit(event: "message", message: unknown, sendHandle: unknown): this; + emit(event: Signals, signal?: Signals): boolean; + emit( + event: "multipleResolves", + type: MultipleResolveType, + promise: Promise, + value: unknown, + ): this; + emit(event: "worker", listener: WorkerListener): this; + on(event: "beforeExit", listener: BeforeExitListener): this; + on(event: "disconnect", listener: DisconnectListener): this; + on(event: "exit", listener: ExitListener): this; + on(event: "rejectionHandled", listener: RejectionHandledListener): this; + on(event: "uncaughtException", listener: UncaughtExceptionListener): this; + on(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + on(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + on(event: "warning", listener: WarningListener): this; + on(event: "message", listener: MessageListener): this; + on(event: Signals, listener: SignalsListener): this; + on(event: "multipleResolves", listener: MultipleResolveListener): this; + on(event: "worker", listener: WorkerListener): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "beforeExit", listener: BeforeExitListener): this; + once(event: "disconnect", listener: DisconnectListener): this; + once(event: "exit", listener: ExitListener): this; + once(event: "rejectionHandled", listener: RejectionHandledListener): this; + once(event: "uncaughtException", listener: UncaughtExceptionListener): this; + once(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + once(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + once(event: "warning", listener: WarningListener): this; + once(event: "message", listener: MessageListener): this; + once(event: Signals, listener: SignalsListener): this; + once(event: "multipleResolves", listener: MultipleResolveListener): this; + once(event: "worker", listener: WorkerListener): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "beforeExit", listener: BeforeExitListener): this; + prependListener(event: "disconnect", listener: DisconnectListener): this; + prependListener(event: "exit", listener: ExitListener): this; + prependListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + prependListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + prependListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + prependListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + prependListener(event: "warning", listener: WarningListener): this; + prependListener(event: "message", listener: MessageListener): this; + prependListener(event: Signals, listener: SignalsListener): this; + prependListener(event: "multipleResolves", listener: MultipleResolveListener): this; + prependListener(event: "worker", listener: WorkerListener): this; + prependOnceListener(event: "beforeExit", listener: BeforeExitListener): this; + prependOnceListener(event: "disconnect", listener: DisconnectListener): this; + prependOnceListener(event: "exit", listener: ExitListener): this; + prependOnceListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + prependOnceListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + prependOnceListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + prependOnceListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + prependOnceListener(event: "warning", listener: WarningListener): this; + prependOnceListener(event: "message", listener: MessageListener): this; + prependOnceListener(event: Signals, listener: SignalsListener): this; + prependOnceListener(event: "multipleResolves", listener: MultipleResolveListener): this; + prependOnceListener(event: "worker", listener: WorkerListener): this; + listeners(event: "beforeExit"): BeforeExitListener[]; + listeners(event: "disconnect"): DisconnectListener[]; + listeners(event: "exit"): ExitListener[]; + listeners(event: "rejectionHandled"): RejectionHandledListener[]; + listeners(event: "uncaughtException"): UncaughtExceptionListener[]; + listeners(event: "uncaughtExceptionMonitor"): UncaughtExceptionListener[]; + listeners(event: "unhandledRejection"): UnhandledRejectionListener[]; + listeners(event: "warning"): WarningListener[]; + listeners(event: "message"): MessageListener[]; + listeners(event: Signals): SignalsListener[]; + listeners(event: "multipleResolves"): MultipleResolveListener[]; + listeners(event: "worker"): WorkerListener[]; + } + } + } + export = process; +} +declare module "node:process" { + import process = require("process"); + export = process; +} diff --git a/backend/node_modules/@types/node/punycode.d.ts b/backend/node_modules/@types/node/punycode.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cfe559b4424fc5d8b661d711dbfbc1efcd003789 --- /dev/null +++ b/backend/node_modules/@types/node/punycode.d.ts @@ -0,0 +1,117 @@ +/** + * **The version of the punycode module bundled in Node.js is being deprecated.**In a future major version of Node.js this module will be removed. Users + * currently depending on the `punycode` module should switch to using the + * userland-provided [Punycode.js](https://github.com/bestiejs/punycode.js) module instead. For punycode-based URL + * encoding, see `url.domainToASCII` or, more generally, the `WHATWG URL API`. + * + * The `punycode` module is a bundled version of the [Punycode.js](https://github.com/bestiejs/punycode.js) module. It + * can be accessed using: + * + * ```js + * const punycode = require('punycode'); + * ``` + * + * [Punycode](https://tools.ietf.org/html/rfc3492) is a character encoding scheme defined by RFC 3492 that is + * primarily intended for use in Internationalized Domain Names. Because host + * names in URLs are limited to ASCII characters only, Domain Names that contain + * non-ASCII characters must be converted into ASCII using the Punycode scheme. + * For instance, the Japanese character that translates into the English word,`'example'` is `'例'`. The Internationalized Domain Name, `'例.com'` (equivalent + * to `'example.com'`) is represented by Punycode as the ASCII string`'xn--fsq.com'`. + * + * The `punycode` module provides a simple implementation of the Punycode standard. + * + * The `punycode` module is a third-party dependency used by Node.js and + * made available to developers as a convenience. Fixes or other modifications to + * the module must be directed to the [Punycode.js](https://github.com/bestiejs/punycode.js) project. + * @deprecated Since v7.0.0 - Deprecated + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/punycode.js) + */ +declare module "punycode" { + /** + * The `punycode.decode()` method converts a [Punycode](https://tools.ietf.org/html/rfc3492) string of ASCII-only + * characters to the equivalent string of Unicode codepoints. + * + * ```js + * punycode.decode('maana-pta'); // 'mañana' + * punycode.decode('--dqo34k'); // '☃-⌘' + * ``` + * @since v0.5.1 + */ + function decode(string: string): string; + /** + * The `punycode.encode()` method converts a string of Unicode codepoints to a [Punycode](https://tools.ietf.org/html/rfc3492) string of ASCII-only characters. + * + * ```js + * punycode.encode('mañana'); // 'maana-pta' + * punycode.encode('☃-⌘'); // '--dqo34k' + * ``` + * @since v0.5.1 + */ + function encode(string: string): string; + /** + * The `punycode.toUnicode()` method converts a string representing a domain name + * containing [Punycode](https://tools.ietf.org/html/rfc3492) encoded characters into Unicode. Only the [Punycode](https://tools.ietf.org/html/rfc3492) encoded parts of the domain name are be + * converted. + * + * ```js + * // decode domain names + * punycode.toUnicode('xn--maana-pta.com'); // 'mañana.com' + * punycode.toUnicode('xn----dqo34k.com'); // '☃-⌘.com' + * punycode.toUnicode('example.com'); // 'example.com' + * ``` + * @since v0.6.1 + */ + function toUnicode(domain: string): string; + /** + * The `punycode.toASCII()` method converts a Unicode string representing an + * Internationalized Domain Name to [Punycode](https://tools.ietf.org/html/rfc3492). Only the non-ASCII parts of the + * domain name will be converted. Calling `punycode.toASCII()` on a string that + * already only contains ASCII characters will have no effect. + * + * ```js + * // encode domain names + * punycode.toASCII('mañana.com'); // 'xn--maana-pta.com' + * punycode.toASCII('☃-⌘.com'); // 'xn----dqo34k.com' + * punycode.toASCII('example.com'); // 'example.com' + * ``` + * @since v0.6.1 + */ + function toASCII(domain: string): string; + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + const ucs2: ucs2; + interface ucs2 { + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + decode(string: string): number[]; + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + encode(codePoints: readonly number[]): string; + } + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + const version: string; +} +declare module "node:punycode" { + export * from "punycode"; +} diff --git a/backend/node_modules/@types/node/querystring.d.ts b/backend/node_modules/@types/node/querystring.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1837171d80a24bbdb3338c5f01e22ee7dd43e992 --- /dev/null +++ b/backend/node_modules/@types/node/querystring.d.ts @@ -0,0 +1,141 @@ +/** + * The `querystring` module provides utilities for parsing and formatting URL + * query strings. It can be accessed using: + * + * ```js + * const querystring = require('querystring'); + * ``` + * + * `querystring` is more performant than `URLSearchParams` but is not a + * standardized API. Use `URLSearchParams` when performance is not critical + * or when compatibility with browser code is desirable. + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/querystring.js) + */ +declare module "querystring" { + interface StringifyOptions { + encodeURIComponent?: ((str: string) => string) | undefined; + } + interface ParseOptions { + maxKeys?: number | undefined; + decodeURIComponent?: ((str: string) => string) | undefined; + } + interface ParsedUrlQuery extends NodeJS.Dict {} + interface ParsedUrlQueryInput extends + NodeJS.Dict< + | string + | number + | boolean + | readonly string[] + | readonly number[] + | readonly boolean[] + | null + > + {} + /** + * The `querystring.stringify()` method produces a URL query string from a + * given `obj` by iterating through the object's "own properties". + * + * It serializes the following types of values passed in `obj`:[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | + * [number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | + * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) | + * [boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) | + * [string\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | + * [number\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | + * [bigint\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) | + * [boolean\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) The numeric values must be finite. Any other input values will be coerced to + * empty strings. + * + * ```js + * querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' }); + * // Returns 'foo=bar&baz=qux&baz=quux&corge=' + * + * querystring.stringify({ foo: 'bar', baz: 'qux' }, ';', ':'); + * // Returns 'foo:bar;baz:qux' + * ``` + * + * By default, characters requiring percent-encoding within the query string will + * be encoded as UTF-8\. If an alternative encoding is required, then an alternative`encodeURIComponent` option will need to be specified: + * + * ```js + * // Assuming gbkEncodeURIComponent function already exists, + * + * querystring.stringify({ w: '中文', foo: 'bar' }, null, null, + * { encodeURIComponent: gbkEncodeURIComponent }); + * ``` + * @since v0.1.25 + * @param obj The object to serialize into a URL query string + * @param [sep='&'] The substring used to delimit key and value pairs in the query string. + * @param [eq='='] . The substring used to delimit keys and values in the query string. + */ + function stringify(obj?: ParsedUrlQueryInput, sep?: string, eq?: string, options?: StringifyOptions): string; + /** + * The `querystring.parse()` method parses a URL query string (`str`) into a + * collection of key and value pairs. + * + * For example, the query string `'foo=bar&abc=xyz&abc=123'` is parsed into: + * + * ```js + * { + * foo: 'bar', + * abc: ['xyz', '123'] + * } + * ``` + * + * The object returned by the `querystring.parse()` method _does not_prototypically inherit from the JavaScript `Object`. This means that typical`Object` methods such as `obj.toString()`, + * `obj.hasOwnProperty()`, and others + * are not defined and _will not work_. + * + * By default, percent-encoded characters within the query string will be assumed + * to use UTF-8 encoding. If an alternative character encoding is used, then an + * alternative `decodeURIComponent` option will need to be specified: + * + * ```js + * // Assuming gbkDecodeURIComponent function already exists... + * + * querystring.parse('w=%D6%D0%CE%C4&foo=bar', null, null, + * { decodeURIComponent: gbkDecodeURIComponent }); + * ``` + * @since v0.1.25 + * @param str The URL query string to parse + * @param [sep='&'] The substring used to delimit key and value pairs in the query string. + * @param [eq='='] . The substring used to delimit keys and values in the query string. + */ + function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): ParsedUrlQuery; + /** + * The querystring.encode() function is an alias for querystring.stringify(). + */ + const encode: typeof stringify; + /** + * The querystring.decode() function is an alias for querystring.parse(). + */ + const decode: typeof parse; + /** + * The `querystring.escape()` method performs URL percent-encoding on the given`str` in a manner that is optimized for the specific requirements of URL + * query strings. + * + * The `querystring.escape()` method is used by `querystring.stringify()` and is + * generally not expected to be used directly. It is exported primarily to allow + * application code to provide a replacement percent-encoding implementation if + * necessary by assigning `querystring.escape` to an alternative function. + * @since v0.1.25 + */ + function escape(str: string): string; + /** + * The `querystring.unescape()` method performs decoding of URL percent-encoded + * characters on the given `str`. + * + * The `querystring.unescape()` method is used by `querystring.parse()` and is + * generally not expected to be used directly. It is exported primarily to allow + * application code to provide a replacement decoding implementation if + * necessary by assigning `querystring.unescape` to an alternative function. + * + * By default, the `querystring.unescape()` method will attempt to use the + * JavaScript built-in `decodeURIComponent()` method to decode. If that fails, + * a safer equivalent that does not throw on malformed URLs will be used. + * @since v0.1.25 + */ + function unescape(str: string): string; +} +declare module "node:querystring" { + export * from "querystring"; +} diff --git a/backend/node_modules/@types/node/readline.d.ts b/backend/node_modules/@types/node/readline.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..60ccb8e9ff1ddc1373a662aa5d6dd3ffb99acc72 --- /dev/null +++ b/backend/node_modules/@types/node/readline.d.ts @@ -0,0 +1,666 @@ +/** + * The `readline` module provides an interface for reading data from a `Readable` stream (such as `process.stdin`) one line at a time. + * + * To use the promise-based APIs: + * + * ```js + * import * as readline from 'node:readline/promises'; + * ``` + * + * To use the callback and sync APIs: + * + * ```js + * import * as readline from 'node:readline'; + * ``` + * + * The following simple example illustrates the basic use of the `readline` module. + * + * ```js + * import * as readline from 'node:readline/promises'; + * import { stdin as input, stdout as output } from 'node:process'; + * + * const rl = readline.createInterface({ input, output }); + * + * const answer = await rl.question('What do you think of Node.js? '); + * + * console.log(`Thank you for your valuable feedback: ${answer}`); + * + * rl.close(); + * ``` + * + * Once this code is invoked, the Node.js application will not terminate until the`readline.Interface` is closed because the interface waits for data to be + * received on the `input` stream. + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/readline.js) + */ +declare module "readline" { + import { Abortable, EventEmitter } from "node:events"; + import * as promises from "node:readline/promises"; + + export { promises }; + export interface Key { + sequence?: string | undefined; + name?: string | undefined; + ctrl?: boolean | undefined; + meta?: boolean | undefined; + shift?: boolean | undefined; + } + /** + * Instances of the `readline.Interface` class are constructed using the`readline.createInterface()` method. Every instance is associated with a + * single `input` `Readable` stream and a single `output` `Writable` stream. + * The `output` stream is used to print prompts for user input that arrives on, + * and is read from, the `input` stream. + * @since v0.1.104 + */ + export class Interface extends EventEmitter { + readonly terminal: boolean; + /** + * The current input data being processed by node. + * + * This can be used when collecting input from a TTY stream to retrieve the + * current value that has been processed thus far, prior to the `line` event + * being emitted. Once the `line` event has been emitted, this property will + * be an empty string. + * + * Be aware that modifying the value during the instance runtime may have + * unintended consequences if `rl.cursor` is not also controlled. + * + * **If not using a TTY stream for input, use the `'line'` event.** + * + * One possible use case would be as follows: + * + * ```js + * const values = ['lorem ipsum', 'dolor sit amet']; + * const rl = readline.createInterface(process.stdin); + * const showResults = debounce(() => { + * console.log( + * '\n', + * values.filter((val) => val.startsWith(rl.line)).join(' ') + * ); + * }, 300); + * process.stdin.on('keypress', (c, k) => { + * showResults(); + * }); + * ``` + * @since v0.1.98 + */ + readonly line: string; + /** + * The cursor position relative to `rl.line`. + * + * This will track where the current cursor lands in the input string, when + * reading input from a TTY stream. The position of cursor determines the + * portion of the input string that will be modified as input is processed, + * as well as the column where the terminal caret will be rendered. + * @since v0.1.98 + */ + readonly cursor: number; + /** + * NOTE: According to the documentation: + * + * > Instances of the `readline.Interface` class are constructed using the + * > `readline.createInterface()` method. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/readline.html#readline_class_interface + */ + protected constructor( + input: NodeJS.ReadableStream, + output?: NodeJS.WritableStream, + completer?: Completer | AsyncCompleter, + terminal?: boolean, + ); + /** + * NOTE: According to the documentation: + * + * > Instances of the `readline.Interface` class are constructed using the + * > `readline.createInterface()` method. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/readline.html#readline_class_interface + */ + protected constructor(options: ReadLineOptions); + /** + * The `rl.getPrompt()` method returns the current prompt used by `rl.prompt()`. + * @since v15.3.0 + * @return the current prompt string + */ + getPrompt(): string; + /** + * The `rl.setPrompt()` method sets the prompt that will be written to `output`whenever `rl.prompt()` is called. + * @since v0.1.98 + */ + setPrompt(prompt: string): void; + /** + * The `rl.prompt()` method writes the `readline.Interface` instances configured`prompt` to a new line in `output` in order to provide a user with a new + * location at which to provide input. + * + * When called, `rl.prompt()` will resume the `input` stream if it has been + * paused. + * + * If the `readline.Interface` was created with `output` set to `null` or`undefined` the prompt is not written. + * @since v0.1.98 + * @param preserveCursor If `true`, prevents the cursor placement from being reset to `0`. + */ + prompt(preserveCursor?: boolean): void; + /** + * The `rl.question()` method displays the `query` by writing it to the `output`, + * waits for user input to be provided on `input`, then invokes the `callback`function passing the provided input as the first argument. + * + * When called, `rl.question()` will resume the `input` stream if it has been + * paused. + * + * If the `readline.Interface` was created with `output` set to `null` or`undefined` the `query` is not written. + * + * The `callback` function passed to `rl.question()` does not follow the typical + * pattern of accepting an `Error` object or `null` as the first argument. + * The `callback` is called with the provided answer as the only argument. + * + * Example usage: + * + * ```js + * rl.question('What is your favorite food? ', (answer) => { + * console.log(`Oh, so your favorite food is ${answer}`); + * }); + * ``` + * + * Using an `AbortController` to cancel a question. + * + * ```js + * const ac = new AbortController(); + * const signal = ac.signal; + * + * rl.question('What is your favorite food? ', { signal }, (answer) => { + * console.log(`Oh, so your favorite food is ${answer}`); + * }); + * + * signal.addEventListener('abort', () => { + * console.log('The food question timed out'); + * }, { once: true }); + * + * setTimeout(() => ac.abort(), 10000); + * ``` + * + * If this method is invoked as it's util.promisify()ed version, it returns a + * Promise that fulfills with the answer. If the question is canceled using + * an `AbortController` it will reject with an `AbortError`. + * + * ```js + * const util = require('util'); + * const question = util.promisify(rl.question).bind(rl); + * + * async function questionExample() { + * try { + * const answer = await question('What is you favorite food? '); + * console.log(`Oh, so your favorite food is ${answer}`); + * } catch (err) { + * console.error('Question rejected', err); + * } + * } + * questionExample(); + * ``` + * @since v0.3.3 + * @param query A statement or query to write to `output`, prepended to the prompt. + * @param callback A callback function that is invoked with the user's input in response to the `query`. + */ + question(query: string, callback: (answer: string) => void): void; + question(query: string, options: Abortable, callback: (answer: string) => void): void; + /** + * The `rl.pause()` method pauses the `input` stream, allowing it to be resumed + * later if necessary. + * + * Calling `rl.pause()` does not immediately pause other events (including`'line'`) from being emitted by the `readline.Interface` instance. + * @since v0.3.4 + */ + pause(): this; + /** + * The `rl.resume()` method resumes the `input` stream if it has been paused. + * @since v0.3.4 + */ + resume(): this; + /** + * The `rl.close()` method closes the `readline.Interface` instance and + * relinquishes control over the `input` and `output` streams. When called, + * the `'close'` event will be emitted. + * + * Calling `rl.close()` does not immediately stop other events (including `'line'`) + * from being emitted by the `readline.Interface` instance. + * @since v0.1.98 + */ + close(): void; + /** + * The `rl.write()` method will write either `data` or a key sequence identified + * by `key` to the `output`. The `key` argument is supported only if `output` is + * a `TTY` text terminal. See `TTY keybindings` for a list of key + * combinations. + * + * If `key` is specified, `data` is ignored. + * + * When called, `rl.write()` will resume the `input` stream if it has been + * paused. + * + * If the `readline.Interface` was created with `output` set to `null` or`undefined` the `data` and `key` are not written. + * + * ```js + * rl.write('Delete this!'); + * // Simulate Ctrl+U to delete the line written previously + * rl.write(null, { ctrl: true, name: 'u' }); + * ``` + * + * The `rl.write()` method will write the data to the `readline` `Interface`'s`input`_as if it were provided by the user_. + * @since v0.1.98 + */ + write(data: string | Buffer, key?: Key): void; + write(data: undefined | null | string | Buffer, key: Key): void; + /** + * Returns the real position of the cursor in relation to the input + * prompt + string. Long input (wrapping) strings, as well as multiple + * line prompts are included in the calculations. + * @since v13.5.0, v12.16.0 + */ + getCursorPos(): CursorPos; + /** + * events.EventEmitter + * 1. close + * 2. line + * 3. pause + * 4. resume + * 5. SIGCONT + * 6. SIGINT + * 7. SIGTSTP + * 8. history + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "line", listener: (input: string) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: "SIGCONT", listener: () => void): this; + addListener(event: "SIGINT", listener: () => void): this; + addListener(event: "SIGTSTP", listener: () => void): this; + addListener(event: "history", listener: (history: string[]) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "line", input: string): boolean; + emit(event: "pause"): boolean; + emit(event: "resume"): boolean; + emit(event: "SIGCONT"): boolean; + emit(event: "SIGINT"): boolean; + emit(event: "SIGTSTP"): boolean; + emit(event: "history", history: string[]): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "line", listener: (input: string) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: "SIGCONT", listener: () => void): this; + on(event: "SIGINT", listener: () => void): this; + on(event: "SIGTSTP", listener: () => void): this; + on(event: "history", listener: (history: string[]) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "line", listener: (input: string) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: "SIGCONT", listener: () => void): this; + once(event: "SIGINT", listener: () => void): this; + once(event: "SIGTSTP", listener: () => void): this; + once(event: "history", listener: (history: string[]) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "line", listener: (input: string) => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: "SIGCONT", listener: () => void): this; + prependListener(event: "SIGINT", listener: () => void): this; + prependListener(event: "SIGTSTP", listener: () => void): this; + prependListener(event: "history", listener: (history: string[]) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "line", listener: (input: string) => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: "SIGCONT", listener: () => void): this; + prependOnceListener(event: "SIGINT", listener: () => void): this; + prependOnceListener(event: "SIGTSTP", listener: () => void): this; + prependOnceListener(event: "history", listener: (history: string[]) => void): this; + [Symbol.asyncIterator](): AsyncIterableIterator; + } + export type ReadLine = Interface; // type forwarded for backwards compatibility + export type Completer = (line: string) => CompleterResult; + export type AsyncCompleter = ( + line: string, + callback: (err?: null | Error, result?: CompleterResult) => void, + ) => void; + export type CompleterResult = [string[], string]; + export interface ReadLineOptions { + input: NodeJS.ReadableStream; + output?: NodeJS.WritableStream | undefined; + completer?: Completer | AsyncCompleter | undefined; + terminal?: boolean | undefined; + /** + * Initial list of history lines. This option makes sense + * only if `terminal` is set to `true` by the user or by an internal `output` + * check, otherwise the history caching mechanism is not initialized at all. + * @default [] + */ + history?: string[] | undefined; + historySize?: number | undefined; + prompt?: string | undefined; + crlfDelay?: number | undefined; + /** + * If `true`, when a new input line added + * to the history list duplicates an older one, this removes the older line + * from the list. + * @default false + */ + removeHistoryDuplicates?: boolean | undefined; + escapeCodeTimeout?: number | undefined; + tabSize?: number | undefined; + } + /** + * The `readline.createInterface()` method creates a new `readline.Interface`instance. + * + * ```js + * const readline = require('readline'); + * const rl = readline.createInterface({ + * input: process.stdin, + * output: process.stdout + * }); + * ``` + * + * Once the `readline.Interface` instance is created, the most common case is to + * listen for the `'line'` event: + * + * ```js + * rl.on('line', (line) => { + * console.log(`Received: ${line}`); + * }); + * ``` + * + * If `terminal` is `true` for this instance then the `output` stream will get + * the best compatibility if it defines an `output.columns` property and emits + * a `'resize'` event on the `output` if or when the columns ever change + * (`process.stdout` does this automatically when it is a TTY). + * + * When creating a `readline.Interface` using `stdin` as input, the program + * will not terminate until it receives `EOF` (Ctrl+D on + * Linux/macOS, Ctrl+Z followed by Return on + * Windows). + * If you want your application to exit without waiting for user input, you can `unref()` the standard input stream: + * + * ```js + * process.stdin.unref(); + * ``` + * @since v0.1.98 + */ + export function createInterface( + input: NodeJS.ReadableStream, + output?: NodeJS.WritableStream, + completer?: Completer | AsyncCompleter, + terminal?: boolean, + ): Interface; + export function createInterface(options: ReadLineOptions): Interface; + /** + * The `readline.emitKeypressEvents()` method causes the given `Readable` stream to begin emitting `'keypress'` events corresponding to received input. + * + * Optionally, `interface` specifies a `readline.Interface` instance for which + * autocompletion is disabled when copy-pasted input is detected. + * + * If the `stream` is a `TTY`, then it must be in raw mode. + * + * This is automatically called by any readline instance on its `input` if the`input` is a terminal. Closing the `readline` instance does not stop + * the `input` from emitting `'keypress'` events. + * + * ```js + * readline.emitKeypressEvents(process.stdin); + * if (process.stdin.isTTY) + * process.stdin.setRawMode(true); + * ``` + * + * ## Example: Tiny CLI + * + * The following example illustrates the use of `readline.Interface` class to + * implement a small command-line interface: + * + * ```js + * const readline = require('readline'); + * const rl = readline.createInterface({ + * input: process.stdin, + * output: process.stdout, + * prompt: 'OHAI> ' + * }); + * + * rl.prompt(); + * + * rl.on('line', (line) => { + * switch (line.trim()) { + * case 'hello': + * console.log('world!'); + * break; + * default: + * console.log(`Say what? I might have heard '${line.trim()}'`); + * break; + * } + * rl.prompt(); + * }).on('close', () => { + * console.log('Have a great day!'); + * process.exit(0); + * }); + * ``` + * + * ## Example: Read file stream line-by-Line + * + * A common use case for `readline` is to consume an input file one line at a + * time. The easiest way to do so is leveraging the `fs.ReadStream` API as + * well as a `for await...of` loop: + * + * ```js + * const fs = require('fs'); + * const readline = require('readline'); + * + * async function processLineByLine() { + * const fileStream = fs.createReadStream('input.txt'); + * + * const rl = readline.createInterface({ + * input: fileStream, + * crlfDelay: Infinity + * }); + * // Note: we use the crlfDelay option to recognize all instances of CR LF + * // ('\r\n') in input.txt as a single line break. + * + * for await (const line of rl) { + * // Each line in input.txt will be successively available here as `line`. + * console.log(`Line from file: ${line}`); + * } + * } + * + * processLineByLine(); + * ``` + * + * Alternatively, one could use the `'line'` event: + * + * ```js + * const fs = require('fs'); + * const readline = require('readline'); + * + * const rl = readline.createInterface({ + * input: fs.createReadStream('sample.txt'), + * crlfDelay: Infinity + * }); + * + * rl.on('line', (line) => { + * console.log(`Line from file: ${line}`); + * }); + * ``` + * + * Currently, `for await...of` loop can be a bit slower. If `async` / `await`flow and speed are both essential, a mixed approach can be applied: + * + * ```js + * const { once } = require('events'); + * const { createReadStream } = require('fs'); + * const { createInterface } = require('readline'); + * + * (async function processLineByLine() { + * try { + * const rl = createInterface({ + * input: createReadStream('big-file.txt'), + * crlfDelay: Infinity + * }); + * + * rl.on('line', (line) => { + * // Process the line. + * }); + * + * await once(rl, 'close'); + * + * console.log('File processed.'); + * } catch (err) { + * console.error(err); + * } + * })(); + * ``` + * @since v0.7.7 + */ + export function emitKeypressEvents(stream: NodeJS.ReadableStream, readlineInterface?: Interface): void; + export type Direction = -1 | 0 | 1; + export interface CursorPos { + rows: number; + cols: number; + } + /** + * The `readline.clearLine()` method clears current line of given `TTY` stream + * in a specified direction identified by `dir`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + export function clearLine(stream: NodeJS.WritableStream, dir: Direction, callback?: () => void): boolean; + /** + * The `readline.clearScreenDown()` method clears the given `TTY` stream from + * the current position of the cursor down. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + export function clearScreenDown(stream: NodeJS.WritableStream, callback?: () => void): boolean; + /** + * The `readline.cursorTo()` method moves cursor to the specified position in a + * given `TTY` `stream`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + export function cursorTo(stream: NodeJS.WritableStream, x: number, y?: number, callback?: () => void): boolean; + /** + * The `readline.moveCursor()` method moves the cursor _relative_ to its current + * position in a given `TTY` `stream`. + * + * ## Example: Tiny CLI + * + * The following example illustrates the use of `readline.Interface` class to + * implement a small command-line interface: + * + * ```js + * const readline = require('readline'); + * const rl = readline.createInterface({ + * input: process.stdin, + * output: process.stdout, + * prompt: 'OHAI> ' + * }); + * + * rl.prompt(); + * + * rl.on('line', (line) => { + * switch (line.trim()) { + * case 'hello': + * console.log('world!'); + * break; + * default: + * console.log(`Say what? I might have heard '${line.trim()}'`); + * break; + * } + * rl.prompt(); + * }).on('close', () => { + * console.log('Have a great day!'); + * process.exit(0); + * }); + * ``` + * + * ## Example: Read file stream line-by-Line + * + * A common use case for `readline` is to consume an input file one line at a + * time. The easiest way to do so is leveraging the `fs.ReadStream` API as + * well as a `for await...of` loop: + * + * ```js + * const fs = require('fs'); + * const readline = require('readline'); + * + * async function processLineByLine() { + * const fileStream = fs.createReadStream('input.txt'); + * + * const rl = readline.createInterface({ + * input: fileStream, + * crlfDelay: Infinity + * }); + * // Note: we use the crlfDelay option to recognize all instances of CR LF + * // ('\r\n') in input.txt as a single line break. + * + * for await (const line of rl) { + * // Each line in input.txt will be successively available here as `line`. + * console.log(`Line from file: ${line}`); + * } + * } + * + * processLineByLine(); + * ``` + * + * Alternatively, one could use the `'line'` event: + * + * ```js + * const fs = require('fs'); + * const readline = require('readline'); + * + * const rl = readline.createInterface({ + * input: fs.createReadStream('sample.txt'), + * crlfDelay: Infinity + * }); + * + * rl.on('line', (line) => { + * console.log(`Line from file: ${line}`); + * }); + * ``` + * + * Currently, `for await...of` loop can be a bit slower. If `async` / `await`flow and speed are both essential, a mixed approach can be applied: + * + * ```js + * const { once } = require('events'); + * const { createReadStream } = require('fs'); + * const { createInterface } = require('readline'); + * + * (async function processLineByLine() { + * try { + * const rl = createInterface({ + * input: createReadStream('big-file.txt'), + * crlfDelay: Infinity + * }); + * + * rl.on('line', (line) => { + * // Process the line. + * }); + * + * await once(rl, 'close'); + * + * console.log('File processed.'); + * } catch (err) { + * console.error(err); + * } + * })(); + * ``` + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + export function moveCursor(stream: NodeJS.WritableStream, dx: number, dy: number, callback?: () => void): boolean; +} +declare module "node:readline" { + export * from "readline"; +} diff --git a/backend/node_modules/@types/node/readline/promises.d.ts b/backend/node_modules/@types/node/readline/promises.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ba603ef4b574ee058f7e2dd307a2b2c0c009ad87 --- /dev/null +++ b/backend/node_modules/@types/node/readline/promises.d.ts @@ -0,0 +1,143 @@ +/** + * The `readline/promise` module provides an API for reading lines of input from a Readable stream one line at a time. + * + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/readline/promises.js) + * @since v17.0.0 + */ +declare module "readline/promises" { + import { AsyncCompleter, Completer, Direction, Interface as _Interface, ReadLineOptions } from "node:readline"; + import { Abortable } from "node:events"; + + class Interface extends _Interface { + /** + * The rl.question() method displays the query by writing it to the output, waits for user input to be provided on input, + * then invokes the callback function passing the provided input as the first argument. + * + * When called, rl.question() will resume the input stream if it has been paused. + * + * If the readlinePromises.Interface was created with output set to null or undefined the query is not written. + * + * If the question is called after rl.close(), it returns a rejected promise. + * + * Example usage: + * + * ```js + * const answer = await rl.question('What is your favorite food? '); + * console.log(`Oh, so your favorite food is ${answer}`); + * ``` + * + * Using an AbortSignal to cancel a question. + * + * ```js + * const signal = AbortSignal.timeout(10_000); + * + * signal.addEventListener('abort', () => { + * console.log('The food question timed out'); + * }, { once: true }); + * + * const answer = await rl.question('What is your favorite food? ', { signal }); + * console.log(`Oh, so your favorite food is ${answer}`); + * ``` + * + * @since v17.0.0 + * @param query A statement or query to write to output, prepended to the prompt. + */ + question(query: string): Promise; + question(query: string, options: Abortable): Promise; + } + + class Readline { + /** + * @param stream A TTY stream. + */ + constructor(stream: NodeJS.WritableStream, options?: { autoCommit?: boolean }); + /** + * The `rl.clearLine()` method adds to the internal list of pending action an action that clears current line of the associated `stream` in a specified direction identified by `dir`. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + */ + clearLine(dir: Direction): this; + /** + * The `rl.clearScreenDown()` method adds to the internal list of pending action an action that clears the associated `stream` from the current position of the cursor down. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + */ + clearScreenDown(): this; + /** + * The `rl.commit()` method sends all the pending actions to the associated `stream` and clears the internal list of pending actions. + */ + commit(): Promise; + /** + * The `rl.cursorTo()` method adds to the internal list of pending action an action that moves cursor to the specified position in the associated `stream`. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + */ + cursorTo(x: number, y?: number): this; + /** + * The `rl.moveCursor()` method adds to the internal list of pending action an action that moves the cursor relative to its current position in the associated `stream`. + * Call `rl.commit()` to see the effect of this method, unless autoCommit: true was passed to the constructor. + */ + moveCursor(dx: number, dy: number): this; + /** + * The `rl.rollback()` method clears the internal list of pending actions without sending it to the associated `stream`. + */ + rollback(): this; + } + + /** + * The `readlinePromises.createInterface()` method creates a new `readlinePromises.Interface` instance. + * + * ```js + * const readlinePromises = require('node:readline/promises'); + * const rl = readlinePromises.createInterface({ + * input: process.stdin, + * output: process.stdout + * }); + * ``` + * + * Once the `readlinePromises.Interface` instance is created, the most common case is to listen for the `'line'` event: + * + * ```js + * rl.on('line', (line) => { + * console.log(`Received: ${line}`); + * }); + * ``` + * + * If `terminal` is `true` for this instance then the `output` stream will get the best compatibility if it defines an `output.columns` property, + * and emits a `'resize'` event on the `output`, if or when the columns ever change (`process.stdout` does this automatically when it is a TTY). + * + * ## Use of the `completer` function + * + * The `completer` function takes the current line entered by the user as an argument, and returns an `Array` with 2 entries: + * + * - An Array with matching entries for the completion. + * - The substring that was used for the matching. + * + * For instance: `[[substr1, substr2, ...], originalsubstring]`. + * + * ```js + * function completer(line) { + * const completions = '.help .error .exit .quit .q'.split(' '); + * const hits = completions.filter((c) => c.startsWith(line)); + * // Show all completions if none found + * return [hits.length ? hits : completions, line]; + * } + * ``` + * + * The `completer` function can also returns a `Promise`, or be asynchronous: + * + * ```js + * async function completer(linePartial) { + * await someAsyncWork(); + * return [['123'], linePartial]; + * } + * ``` + */ + function createInterface( + input: NodeJS.ReadableStream, + output?: NodeJS.WritableStream, + completer?: Completer | AsyncCompleter, + terminal?: boolean, + ): Interface; + function createInterface(options: ReadLineOptions): Interface; +} +declare module "node:readline/promises" { + export * from "readline/promises"; +} diff --git a/backend/node_modules/@types/node/repl.d.ts b/backend/node_modules/@types/node/repl.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7ed370b63377fec6c28d7e9db8a3a86e660c1639 --- /dev/null +++ b/backend/node_modules/@types/node/repl.d.ts @@ -0,0 +1,430 @@ +/** + * The `repl` module provides a Read-Eval-Print-Loop (REPL) implementation that + * is available both as a standalone program or includible in other applications. + * It can be accessed using: + * + * ```js + * const repl = require('repl'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/repl.js) + */ +declare module "repl" { + import { AsyncCompleter, Completer, Interface } from "node:readline"; + import { Context } from "node:vm"; + import { InspectOptions } from "node:util"; + interface ReplOptions { + /** + * The input prompt to display. + * @default "> " + */ + prompt?: string | undefined; + /** + * The `Readable` stream from which REPL input will be read. + * @default process.stdin + */ + input?: NodeJS.ReadableStream | undefined; + /** + * The `Writable` stream to which REPL output will be written. + * @default process.stdout + */ + output?: NodeJS.WritableStream | undefined; + /** + * If `true`, specifies that the output should be treated as a TTY terminal, and have + * ANSI/VT100 escape codes written to it. + * Default: checking the value of the `isTTY` property on the output stream upon + * instantiation. + */ + terminal?: boolean | undefined; + /** + * The function to be used when evaluating each given line of input. + * Default: an async wrapper for the JavaScript `eval()` function. An `eval` function can + * error with `repl.Recoverable` to indicate the input was incomplete and prompt for + * additional lines. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_default_evaluation + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_custom_evaluation_functions + */ + eval?: REPLEval | undefined; + /** + * Defines if the repl prints output previews or not. + * @default `true` Always `false` in case `terminal` is falsy. + */ + preview?: boolean | undefined; + /** + * If `true`, specifies that the default `writer` function should include ANSI color + * styling to REPL output. If a custom `writer` function is provided then this has no + * effect. + * Default: the REPL instance's `terminal` value. + */ + useColors?: boolean | undefined; + /** + * If `true`, specifies that the default evaluation function will use the JavaScript + * `global` as the context as opposed to creating a new separate context for the REPL + * instance. The node CLI REPL sets this value to `true`. + * Default: `false`. + */ + useGlobal?: boolean | undefined; + /** + * If `true`, specifies that the default writer will not output the return value of a + * command if it evaluates to `undefined`. + * Default: `false`. + */ + ignoreUndefined?: boolean | undefined; + /** + * The function to invoke to format the output of each command before writing to `output`. + * Default: a wrapper for `util.inspect`. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_customizing_repl_output + */ + writer?: REPLWriter | undefined; + /** + * An optional function used for custom Tab auto completion. + * + * @see https://nodejs.org/dist/latest-v11.x/docs/api/readline.html#readline_use_of_the_completer_function + */ + completer?: Completer | AsyncCompleter | undefined; + /** + * A flag that specifies whether the default evaluator executes all JavaScript commands in + * strict mode or default (sloppy) mode. + * Accepted values are: + * - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode. + * - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to + * prefacing every repl statement with `'use strict'`. + */ + replMode?: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT | undefined; + /** + * Stop evaluating the current piece of code when `SIGINT` is received, i.e. `Ctrl+C` is + * pressed. This cannot be used together with a custom `eval` function. + * Default: `false`. + */ + breakEvalOnSigint?: boolean | undefined; + } + type REPLEval = ( + this: REPLServer, + evalCmd: string, + context: Context, + file: string, + cb: (err: Error | null, result: any) => void, + ) => void; + type REPLWriter = (this: REPLServer, obj: any) => string; + /** + * This is the default "writer" value, if none is passed in the REPL options, + * and it can be overridden by custom print functions. + */ + const writer: REPLWriter & { + options: InspectOptions; + }; + type REPLCommandAction = (this: REPLServer, text: string) => void; + interface REPLCommand { + /** + * Help text to be displayed when `.help` is entered. + */ + help?: string | undefined; + /** + * The function to execute, optionally accepting a single string argument. + */ + action: REPLCommandAction; + } + /** + * Instances of `repl.REPLServer` are created using the {@link start} method + * or directly using the JavaScript `new` keyword. + * + * ```js + * const repl = require('repl'); + * + * const options = { useColors: true }; + * + * const firstInstance = repl.start(options); + * const secondInstance = new repl.REPLServer(options); + * ``` + * @since v0.1.91 + */ + class REPLServer extends Interface { + /** + * The `vm.Context` provided to the `eval` function to be used for JavaScript + * evaluation. + */ + readonly context: Context; + /** + * @deprecated since v14.3.0 - Use `input` instead. + */ + readonly inputStream: NodeJS.ReadableStream; + /** + * @deprecated since v14.3.0 - Use `output` instead. + */ + readonly outputStream: NodeJS.WritableStream; + /** + * The `Readable` stream from which REPL input will be read. + */ + readonly input: NodeJS.ReadableStream; + /** + * The `Writable` stream to which REPL output will be written. + */ + readonly output: NodeJS.WritableStream; + /** + * The commands registered via `replServer.defineCommand()`. + */ + readonly commands: NodeJS.ReadOnlyDict; + /** + * A value indicating whether the REPL is currently in "editor mode". + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_commands_and_special_keys + */ + readonly editorMode: boolean; + /** + * A value indicating whether the `_` variable has been assigned. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly underscoreAssigned: boolean; + /** + * The last evaluation result from the REPL (assigned to the `_` variable inside of the REPL). + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly last: any; + /** + * A value indicating whether the `_error` variable has been assigned. + * + * @since v9.8.0 + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly underscoreErrAssigned: boolean; + /** + * The last error raised inside the REPL (assigned to the `_error` variable inside of the REPL). + * + * @since v9.8.0 + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly lastError: any; + /** + * Specified in the REPL options, this is the function to be used when evaluating each + * given line of input. If not specified in the REPL options, this is an async wrapper + * for the JavaScript `eval()` function. + */ + readonly eval: REPLEval; + /** + * Specified in the REPL options, this is a value indicating whether the default + * `writer` function should include ANSI color styling to REPL output. + */ + readonly useColors: boolean; + /** + * Specified in the REPL options, this is a value indicating whether the default `eval` + * function will use the JavaScript `global` as the context as opposed to creating a new + * separate context for the REPL instance. + */ + readonly useGlobal: boolean; + /** + * Specified in the REPL options, this is a value indicating whether the default `writer` + * function should output the result of a command if it evaluates to `undefined`. + */ + readonly ignoreUndefined: boolean; + /** + * Specified in the REPL options, this is the function to invoke to format the output of + * each command before writing to `outputStream`. If not specified in the REPL options, + * this will be a wrapper for `util.inspect`. + */ + readonly writer: REPLWriter; + /** + * Specified in the REPL options, this is the function to use for custom Tab auto-completion. + */ + readonly completer: Completer | AsyncCompleter; + /** + * Specified in the REPL options, this is a flag that specifies whether the default `eval` + * function should execute all JavaScript commands in strict mode or default (sloppy) mode. + * Possible values are: + * - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode. + * - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to + * prefacing every repl statement with `'use strict'`. + */ + readonly replMode: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT; + /** + * NOTE: According to the documentation: + * + * > Instances of `repl.REPLServer` are created using the `repl.start()` method and + * > _should not_ be created directly using the JavaScript `new` keyword. + * + * `REPLServer` cannot be subclassed due to implementation specifics in NodeJS. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_class_replserver + */ + private constructor(); + /** + * The `replServer.defineCommand()` method is used to add new `.`\-prefixed commands + * to the REPL instance. Such commands are invoked by typing a `.` followed by the`keyword`. The `cmd` is either a `Function` or an `Object` with the following + * properties: + * + * The following example shows two new commands added to the REPL instance: + * + * ```js + * const repl = require('repl'); + * + * const replServer = repl.start({ prompt: '> ' }); + * replServer.defineCommand('sayhello', { + * help: 'Say hello', + * action(name) { + * this.clearBufferedCommand(); + * console.log(`Hello, ${name}!`); + * this.displayPrompt(); + * } + * }); + * replServer.defineCommand('saybye', function saybye() { + * console.log('Goodbye!'); + * this.close(); + * }); + * ``` + * + * The new commands can then be used from within the REPL instance: + * + * ```console + * > .sayhello Node.js User + * Hello, Node.js User! + * > .saybye + * Goodbye! + * ``` + * @since v0.3.0 + * @param keyword The command keyword (_without_ a leading `.` character). + * @param cmd The function to invoke when the command is processed. + */ + defineCommand(keyword: string, cmd: REPLCommandAction | REPLCommand): void; + /** + * The `replServer.displayPrompt()` method readies the REPL instance for input + * from the user, printing the configured `prompt` to a new line in the `output`and resuming the `input` to accept new input. + * + * When multi-line input is being entered, an ellipsis is printed rather than the + * 'prompt'. + * + * When `preserveCursor` is `true`, the cursor placement will not be reset to `0`. + * + * The `replServer.displayPrompt` method is primarily intended to be called from + * within the action function for commands registered using the`replServer.defineCommand()` method. + * @since v0.1.91 + */ + displayPrompt(preserveCursor?: boolean): void; + /** + * The `replServer.clearBufferedCommand()` method clears any command that has been + * buffered but not yet executed. This method is primarily intended to be + * called from within the action function for commands registered using the`replServer.defineCommand()` method. + * @since v9.0.0 + */ + clearBufferedCommand(): void; + /** + * Initializes a history log file for the REPL instance. When executing the + * Node.js binary and using the command-line REPL, a history file is initialized + * by default. However, this is not the case when creating a REPL + * programmatically. Use this method to initialize a history log file when working + * with REPL instances programmatically. + * @since v11.10.0 + * @param historyPath the path to the history file + * @param callback called when history writes are ready or upon error + */ + setupHistory(path: string, callback: (err: Error | null, repl: this) => void): void; + /** + * events.EventEmitter + * 1. close - inherited from `readline.Interface` + * 2. line - inherited from `readline.Interface` + * 3. pause - inherited from `readline.Interface` + * 4. resume - inherited from `readline.Interface` + * 5. SIGCONT - inherited from `readline.Interface` + * 6. SIGINT - inherited from `readline.Interface` + * 7. SIGTSTP - inherited from `readline.Interface` + * 8. exit + * 9. reset + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "line", listener: (input: string) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: "SIGCONT", listener: () => void): this; + addListener(event: "SIGINT", listener: () => void): this; + addListener(event: "SIGTSTP", listener: () => void): this; + addListener(event: "exit", listener: () => void): this; + addListener(event: "reset", listener: (context: Context) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "line", input: string): boolean; + emit(event: "pause"): boolean; + emit(event: "resume"): boolean; + emit(event: "SIGCONT"): boolean; + emit(event: "SIGINT"): boolean; + emit(event: "SIGTSTP"): boolean; + emit(event: "exit"): boolean; + emit(event: "reset", context: Context): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "line", listener: (input: string) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: "SIGCONT", listener: () => void): this; + on(event: "SIGINT", listener: () => void): this; + on(event: "SIGTSTP", listener: () => void): this; + on(event: "exit", listener: () => void): this; + on(event: "reset", listener: (context: Context) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "line", listener: (input: string) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: "SIGCONT", listener: () => void): this; + once(event: "SIGINT", listener: () => void): this; + once(event: "SIGTSTP", listener: () => void): this; + once(event: "exit", listener: () => void): this; + once(event: "reset", listener: (context: Context) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "line", listener: (input: string) => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: "SIGCONT", listener: () => void): this; + prependListener(event: "SIGINT", listener: () => void): this; + prependListener(event: "SIGTSTP", listener: () => void): this; + prependListener(event: "exit", listener: () => void): this; + prependListener(event: "reset", listener: (context: Context) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "line", listener: (input: string) => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: "SIGCONT", listener: () => void): this; + prependOnceListener(event: "SIGINT", listener: () => void): this; + prependOnceListener(event: "SIGTSTP", listener: () => void): this; + prependOnceListener(event: "exit", listener: () => void): this; + prependOnceListener(event: "reset", listener: (context: Context) => void): this; + } + /** + * A flag passed in the REPL options. Evaluates expressions in sloppy mode. + */ + const REPL_MODE_SLOPPY: unique symbol; + /** + * A flag passed in the REPL options. Evaluates expressions in strict mode. + * This is equivalent to prefacing every repl statement with `'use strict'`. + */ + const REPL_MODE_STRICT: unique symbol; + /** + * The `repl.start()` method creates and starts a {@link REPLServer} instance. + * + * If `options` is a string, then it specifies the input prompt: + * + * ```js + * const repl = require('repl'); + * + * // a Unix style prompt + * repl.start('$ '); + * ``` + * @since v0.1.91 + */ + function start(options?: string | ReplOptions): REPLServer; + /** + * Indicates a recoverable error that a `REPLServer` can use to support multi-line input. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_recoverable_errors + */ + class Recoverable extends SyntaxError { + err: Error; + constructor(err: Error); + } +} +declare module "node:repl" { + export * from "repl"; +} diff --git a/backend/node_modules/@types/node/stream.d.ts b/backend/node_modules/@types/node/stream.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f7d2afb53c00524e1499e7d4a1b45770999208a1 --- /dev/null +++ b/backend/node_modules/@types/node/stream.d.ts @@ -0,0 +1,1731 @@ +/** + * A stream is an abstract interface for working with streaming data in Node.js. + * The `stream` module provides an API for implementing the stream interface. + * + * There are many stream objects provided by Node.js. For instance, a `request to an HTTP server` and `process.stdout` are both stream instances. + * + * Streams can be readable, writable, or both. All streams are instances of `EventEmitter`. + * + * To access the `stream` module: + * + * ```js + * const stream = require('stream'); + * ``` + * + * The `stream` module is useful for creating new types of stream instances. It is + * usually not necessary to use the `stream` module to consume streams. + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/stream.js) + */ +declare module "stream" { + import { Abortable, EventEmitter } from "node:events"; + import { Blob as NodeBlob } from "node:buffer"; + import * as streamPromises from "node:stream/promises"; + import * as streamConsumers from "node:stream/consumers"; + import * as streamWeb from "node:stream/web"; + + type ComposeFnParam = (source: any) => void; + + class internal extends EventEmitter { + pipe( + destination: T, + options?: { + end?: boolean | undefined; + }, + ): T; + compose( + stream: T | ComposeFnParam | Iterable | AsyncIterable, + options?: { signal: AbortSignal }, + ): T; + } + namespace internal { + class Stream extends internal { + constructor(opts?: ReadableOptions); + } + interface StreamOptions extends Abortable { + emitClose?: boolean | undefined; + highWaterMark?: number | undefined; + objectMode?: boolean | undefined; + construct?(this: T, callback: (error?: Error | null) => void): void; + destroy?(this: T, error: Error | null, callback: (error?: Error | null) => void): void; + autoDestroy?: boolean | undefined; + } + interface ReadableOptions extends StreamOptions { + encoding?: BufferEncoding | undefined; + read?(this: Readable, size: number): void; + } + interface ArrayOptions { + /** the maximum concurrent invocations of `fn` to call on the stream at once. **Default: 1**. */ + concurrency?: number; + /** allows destroying the stream if the signal is aborted. */ + signal?: AbortSignal; + } + /** + * @since v0.9.4 + */ + class Readable extends Stream implements NodeJS.ReadableStream { + /** + * A utility method for creating Readable Streams out of iterators. + */ + static from(iterable: Iterable | AsyncIterable, options?: ReadableOptions): Readable; + /** + * A utility method for creating a `Readable` from a web `ReadableStream`. + * @since v17.0.0 + * @experimental + */ + static fromWeb( + readableStream: streamWeb.ReadableStream, + options?: Pick, + ): Readable; + /** + * Returns whether the stream has been read from or cancelled. + * @since v16.8.0 + */ + static isDisturbed(stream: Readable | NodeJS.ReadableStream): boolean; + /** + * A utility method for creating a web `ReadableStream` from a `Readable`. + * @since v17.0.0 + * @experimental + */ + static toWeb(streamReadable: Readable): streamWeb.ReadableStream; + /** + * Returns whether the stream was destroyed or errored before emitting `'end'`. + * @since v16.8.0 + * @experimental + */ + readonly readableAborted: boolean; + /** + * Is `true` if it is safe to call `readable.read()`, which means + * the stream has not been destroyed or emitted `'error'` or `'end'`. + * @since v11.4.0 + */ + readable: boolean; + /** + * Returns whether `'data'` has been emitted. + * @since v16.7.0, v14.18.0 + * @experimental + */ + readonly readableDidRead: boolean; + /** + * Getter for the property `encoding` of a given `Readable` stream. The `encoding`property can be set using the `readable.setEncoding()` method. + * @since v12.7.0 + */ + readonly readableEncoding: BufferEncoding | null; + /** + * Becomes `true` when `'end'` event is emitted. + * @since v12.9.0 + */ + readonly readableEnded: boolean; + /** + * This property reflects the current state of a `Readable` stream as described + * in the `Three states` section. + * @since v9.4.0 + */ + readonly readableFlowing: boolean | null; + /** + * Returns the value of `highWaterMark` passed when creating this `Readable`. + * @since v9.3.0 + */ + readonly readableHighWaterMark: number; + /** + * This property contains the number of bytes (or objects) in the queue + * ready to be read. The value provides introspection data regarding + * the status of the `highWaterMark`. + * @since v9.4.0 + */ + readonly readableLength: number; + /** + * Getter for the property `objectMode` of a given `Readable` stream. + * @since v12.3.0 + */ + readonly readableObjectMode: boolean; + /** + * Is `true` after `readable.destroy()` has been called. + * @since v8.0.0 + */ + destroyed: boolean; + /** + * Is true after 'close' has been emitted. + * @since v18.0.0 + */ + readonly closed: boolean; + /** + * Returns error if the stream has been destroyed with an error. + * @since v18.0.0 + */ + readonly errored: Error | null; + constructor(opts?: ReadableOptions); + _construct?(callback: (error?: Error | null) => void): void; + _read(size: number): void; + /** + * The `readable.read()` method reads data out of the internal buffer and + * returns it. If no data is available to be read, `null` is returned. By default, + * the data is returned as a `Buffer` object unless an encoding has been + * specified using the `readable.setEncoding()` method or the stream is operating + * in object mode. + * + * The optional `size` argument specifies a specific number of bytes to read. If`size` bytes are not available to be read, `null` will be returned _unless_the stream has ended, in which + * case all of the data remaining in the internal + * buffer will be returned. + * + * If the `size` argument is not specified, all of the data contained in the + * internal buffer will be returned. + * + * The `size` argument must be less than or equal to 1 GiB. + * + * The `readable.read()` method should only be called on `Readable` streams + * operating in paused mode. In flowing mode, `readable.read()` is called + * automatically until the internal buffer is fully drained. + * + * ```js + * const readable = getReadableStreamSomehow(); + * + * // 'readable' may be triggered multiple times as data is buffered in + * readable.on('readable', () => { + * let chunk; + * console.log('Stream is readable (new data received in buffer)'); + * // Use a loop to make sure we read all currently available data + * while (null !== (chunk = readable.read())) { + * console.log(`Read ${chunk.length} bytes of data...`); + * } + * }); + * + * // 'end' will be triggered once when there is no more data available + * readable.on('end', () => { + * console.log('Reached end of stream.'); + * }); + * ``` + * + * Each call to `readable.read()` returns a chunk of data, or `null`. The chunks + * are not concatenated. A `while` loop is necessary to consume all data + * currently in the buffer. When reading a large file `.read()` may return `null`, + * having consumed all buffered content so far, but there is still more data to + * come not yet buffered. In this case a new `'readable'` event will be emitted + * when there is more data in the buffer. Finally the `'end'` event will be + * emitted when there is no more data to come. + * + * Therefore to read a file's whole contents from a `readable`, it is necessary + * to collect chunks across multiple `'readable'` events: + * + * ```js + * const chunks = []; + * + * readable.on('readable', () => { + * let chunk; + * while (null !== (chunk = readable.read())) { + * chunks.push(chunk); + * } + * }); + * + * readable.on('end', () => { + * const content = chunks.join(''); + * }); + * ``` + * + * A `Readable` stream in object mode will always return a single item from + * a call to `readable.read(size)`, regardless of the value of the`size` argument. + * + * If the `readable.read()` method returns a chunk of data, a `'data'` event will + * also be emitted. + * + * Calling {@link read} after the `'end'` event has + * been emitted will return `null`. No runtime error will be raised. + * @since v0.9.4 + * @param size Optional argument to specify how much data to read. + */ + read(size?: number): any; + /** + * The `readable.setEncoding()` method sets the character encoding for + * data read from the `Readable` stream. + * + * By default, no encoding is assigned and stream data will be returned as`Buffer` objects. Setting an encoding causes the stream data + * to be returned as strings of the specified encoding rather than as `Buffer`objects. For instance, calling `readable.setEncoding('utf8')` will cause the + * output data to be interpreted as UTF-8 data, and passed as strings. Calling`readable.setEncoding('hex')` will cause the data to be encoded in hexadecimal + * string format. + * + * The `Readable` stream will properly handle multi-byte characters delivered + * through the stream that would otherwise become improperly decoded if simply + * pulled from the stream as `Buffer` objects. + * + * ```js + * const readable = getReadableStreamSomehow(); + * readable.setEncoding('utf8'); + * readable.on('data', (chunk) => { + * assert.equal(typeof chunk, 'string'); + * console.log('Got %d characters of string data:', chunk.length); + * }); + * ``` + * @since v0.9.4 + * @param encoding The encoding to use. + */ + setEncoding(encoding: BufferEncoding): this; + /** + * The `readable.pause()` method will cause a stream in flowing mode to stop + * emitting `'data'` events, switching out of flowing mode. Any data that + * becomes available will remain in the internal buffer. + * + * ```js + * const readable = getReadableStreamSomehow(); + * readable.on('data', (chunk) => { + * console.log(`Received ${chunk.length} bytes of data.`); + * readable.pause(); + * console.log('There will be no additional data for 1 second.'); + * setTimeout(() => { + * console.log('Now data will start flowing again.'); + * readable.resume(); + * }, 1000); + * }); + * ``` + * + * The `readable.pause()` method has no effect if there is a `'readable'`event listener. + * @since v0.9.4 + */ + pause(): this; + /** + * The `readable.resume()` method causes an explicitly paused `Readable` stream to + * resume emitting `'data'` events, switching the stream into flowing mode. + * + * The `readable.resume()` method can be used to fully consume the data from a + * stream without actually processing any of that data: + * + * ```js + * getReadableStreamSomehow() + * .resume() + * .on('end', () => { + * console.log('Reached the end, but did not read anything.'); + * }); + * ``` + * + * The `readable.resume()` method has no effect if there is a `'readable'`event listener. + * @since v0.9.4 + */ + resume(): this; + /** + * The `readable.isPaused()` method returns the current operating state of the`Readable`. This is used primarily by the mechanism that underlies the`readable.pipe()` method. In most + * typical cases, there will be no reason to + * use this method directly. + * + * ```js + * const readable = new stream.Readable(); + * + * readable.isPaused(); // === false + * readable.pause(); + * readable.isPaused(); // === true + * readable.resume(); + * readable.isPaused(); // === false + * ``` + * @since v0.11.14 + */ + isPaused(): boolean; + /** + * The `readable.unpipe()` method detaches a `Writable` stream previously attached + * using the {@link pipe} method. + * + * If the `destination` is not specified, then _all_ pipes are detached. + * + * If the `destination` is specified, but no pipe is set up for it, then + * the method does nothing. + * + * ```js + * const fs = require('fs'); + * const readable = getReadableStreamSomehow(); + * const writable = fs.createWriteStream('file.txt'); + * // All the data from readable goes into 'file.txt', + * // but only for the first second. + * readable.pipe(writable); + * setTimeout(() => { + * console.log('Stop writing to file.txt.'); + * readable.unpipe(writable); + * console.log('Manually close the file stream.'); + * writable.end(); + * }, 1000); + * ``` + * @since v0.9.4 + * @param destination Optional specific stream to unpipe + */ + unpipe(destination?: NodeJS.WritableStream): this; + /** + * Passing `chunk` as `null` signals the end of the stream (EOF) and behaves the + * same as `readable.push(null)`, after which no more data can be written. The EOF + * signal is put at the end of the buffer and any buffered data will still be + * flushed. + * + * The `readable.unshift()` method pushes a chunk of data back into the internal + * buffer. This is useful in certain situations where a stream is being consumed by + * code that needs to "un-consume" some amount of data that it has optimistically + * pulled out of the source, so that the data can be passed on to some other party. + * + * The `stream.unshift(chunk)` method cannot be called after the `'end'` event + * has been emitted or a runtime error will be thrown. + * + * Developers using `stream.unshift()` often should consider switching to + * use of a `Transform` stream instead. See the `API for stream implementers` section for more information. + * + * ```js + * // Pull off a header delimited by \n\n. + * // Use unshift() if we get too much. + * // Call the callback with (error, header, stream). + * const { StringDecoder } = require('string_decoder'); + * function parseHeader(stream, callback) { + * stream.on('error', callback); + * stream.on('readable', onReadable); + * const decoder = new StringDecoder('utf8'); + * let header = ''; + * function onReadable() { + * let chunk; + * while (null !== (chunk = stream.read())) { + * const str = decoder.write(chunk); + * if (str.includes('\n\n')) { + * // Found the header boundary. + * const split = str.split(/\n\n/); + * header += split.shift(); + * const remaining = split.join('\n\n'); + * const buf = Buffer.from(remaining, 'utf8'); + * stream.removeListener('error', callback); + * // Remove the 'readable' listener before unshifting. + * stream.removeListener('readable', onReadable); + * if (buf.length) + * stream.unshift(buf); + * // Now the body of the message can be read from the stream. + * callback(null, header, stream); + * return; + * } + * // Still reading the header. + * header += str; + * } + * } + * } + * ``` + * + * Unlike {@link push}, `stream.unshift(chunk)` will not + * end the reading process by resetting the internal reading state of the stream. + * This can cause unexpected results if `readable.unshift()` is called during a + * read (i.e. from within a {@link _read} implementation on a + * custom stream). Following the call to `readable.unshift()` with an immediate {@link push} will reset the reading state appropriately, + * however it is best to simply avoid calling `readable.unshift()` while in the + * process of performing a read. + * @since v0.9.11 + * @param chunk Chunk of data to unshift onto the read queue. For streams not operating in object mode, `chunk` must be a string, `Buffer`, `Uint8Array` or `null`. For object mode + * streams, `chunk` may be any JavaScript value. + * @param encoding Encoding of string chunks. Must be a valid `Buffer` encoding, such as `'utf8'` or `'ascii'`. + */ + unshift(chunk: any, encoding?: BufferEncoding): void; + /** + * Prior to Node.js 0.10, streams did not implement the entire `stream` module API + * as it is currently defined. (See `Compatibility` for more information.) + * + * When using an older Node.js library that emits `'data'` events and has a {@link pause} method that is advisory only, the`readable.wrap()` method can be used to create a `Readable` + * stream that uses + * the old stream as its data source. + * + * It will rarely be necessary to use `readable.wrap()` but the method has been + * provided as a convenience for interacting with older Node.js applications and + * libraries. + * + * ```js + * const { OldReader } = require('./old-api-module.js'); + * const { Readable } = require('stream'); + * const oreader = new OldReader(); + * const myReader = new Readable().wrap(oreader); + * + * myReader.on('readable', () => { + * myReader.read(); // etc. + * }); + * ``` + * @since v0.9.4 + * @param stream An "old style" readable stream + */ + wrap(stream: NodeJS.ReadableStream): this; + push(chunk: any, encoding?: BufferEncoding): boolean; + /** + * The iterator created by this method gives users the option to cancel the destruction + * of the stream if the `for await...of` loop is exited by `return`, `break`, or `throw`, + * or if the iterator should destroy the stream if the stream emitted an error during iteration. + * @since v16.3.0 + * @param options.destroyOnReturn When set to `false`, calling `return` on the async iterator, + * or exiting a `for await...of` iteration using a `break`, `return`, or `throw` will not destroy the stream. + * **Default: `true`**. + */ + iterator(options?: { destroyOnReturn?: boolean }): AsyncIterableIterator; + /** + * This method allows mapping over the stream. The *fn* function will be called for every chunk in the stream. + * If the *fn* function returns a promise - that promise will be `await`ed before being passed to the result stream. + * @since v17.4.0, v16.14.0 + * @param fn a function to map over every chunk in the stream. Async or not. + * @returns a stream mapped with the function *fn*. + */ + map(fn: (data: any, options?: Pick) => any, options?: ArrayOptions): Readable; + /** + * This method allows filtering the stream. For each chunk in the stream the *fn* function will be called + * and if it returns a truthy value, the chunk will be passed to the result stream. + * If the *fn* function returns a promise - that promise will be `await`ed. + * @since v17.4.0, v16.14.0 + * @param fn a function to filter chunks from the stream. Async or not. + * @returns a stream filtered with the predicate *fn*. + */ + filter( + fn: (data: any, options?: Pick) => boolean | Promise, + options?: ArrayOptions, + ): Readable; + /** + * This method allows iterating a stream. For each chunk in the stream the *fn* function will be called. + * If the *fn* function returns a promise - that promise will be `await`ed. + * + * This method is different from `for await...of` loops in that it can optionally process chunks concurrently. + * In addition, a `forEach` iteration can only be stopped by having passed a `signal` option + * and aborting the related AbortController while `for await...of` can be stopped with `break` or `return`. + * In either case the stream will be destroyed. + * + * This method is different from listening to the `'data'` event in that it uses the `readable` event + * in the underlying machinary and can limit the number of concurrent *fn* calls. + * @since v17.5.0 + * @param fn a function to call on each chunk of the stream. Async or not. + * @returns a promise for when the stream has finished. + */ + forEach( + fn: (data: any, options?: Pick) => void | Promise, + options?: ArrayOptions, + ): Promise; + /** + * This method allows easily obtaining the contents of a stream. + * + * As this method reads the entire stream into memory, it negates the benefits of streams. It's intended + * for interoperability and convenience, not as the primary way to consume streams. + * @since v17.5.0 + * @returns a promise containing an array with the contents of the stream. + */ + toArray(options?: Pick): Promise; + /** + * This method is similar to `Array.prototype.some` and calls *fn* on each chunk in the stream + * until the awaited return value is `true` (or any truthy value). Once an *fn* call on a chunk + * `await`ed return value is truthy, the stream is destroyed and the promise is fulfilled with `true`. + * If none of the *fn* calls on the chunks return a truthy value, the promise is fulfilled with `false`. + * @since v17.5.0 + * @param fn a function to call on each chunk of the stream. Async or not. + * @returns a promise evaluating to `true` if *fn* returned a truthy value for at least one of the chunks. + */ + some( + fn: (data: any, options?: Pick) => boolean | Promise, + options?: ArrayOptions, + ): Promise; + /** + * This method is similar to `Array.prototype.find` and calls *fn* on each chunk in the stream + * to find a chunk with a truthy value for *fn*. Once an *fn* call's awaited return value is truthy, + * the stream is destroyed and the promise is fulfilled with value for which *fn* returned a truthy value. + * If all of the *fn* calls on the chunks return a falsy value, the promise is fulfilled with `undefined`. + * @since v17.5.0 + * @param fn a function to call on each chunk of the stream. Async or not. + * @returns a promise evaluating to the first chunk for which *fn* evaluated with a truthy value, + * or `undefined` if no element was found. + */ + find( + fn: (data: any, options?: Pick) => data is T, + options?: ArrayOptions, + ): Promise; + find( + fn: (data: any, options?: Pick) => boolean | Promise, + options?: ArrayOptions, + ): Promise; + /** + * This method is similar to `Array.prototype.every` and calls *fn* on each chunk in the stream + * to check if all awaited return values are truthy value for *fn*. Once an *fn* call on a chunk + * `await`ed return value is falsy, the stream is destroyed and the promise is fulfilled with `false`. + * If all of the *fn* calls on the chunks return a truthy value, the promise is fulfilled with `true`. + * @since v17.5.0 + * @param fn a function to call on each chunk of the stream. Async or not. + * @returns a promise evaluating to `true` if *fn* returned a truthy value for every one of the chunks. + */ + every( + fn: (data: any, options?: Pick) => boolean | Promise, + options?: ArrayOptions, + ): Promise; + /** + * This method returns a new stream by applying the given callback to each chunk of the stream + * and then flattening the result. + * + * It is possible to return a stream or another iterable or async iterable from *fn* and the result streams + * will be merged (flattened) into the returned stream. + * @since v17.5.0 + * @param fn a function to map over every chunk in the stream. May be async. May be a stream or generator. + * @returns a stream flat-mapped with the function *fn*. + */ + flatMap(fn: (data: any, options?: Pick) => any, options?: ArrayOptions): Readable; + /** + * This method returns a new stream with the first *limit* chunks dropped from the start. + * @since v17.5.0 + * @param limit the number of chunks to drop from the readable. + * @returns a stream with *limit* chunks dropped from the start. + */ + drop(limit: number, options?: Pick): Readable; + /** + * This method returns a new stream with the first *limit* chunks. + * @since v17.5.0 + * @param limit the number of chunks to take from the readable. + * @returns a stream with *limit* chunks taken. + */ + take(limit: number, options?: Pick): Readable; + /** + * This method returns a new stream with chunks of the underlying stream paired with a counter + * in the form `[index, chunk]`. The first index value is `0` and it increases by 1 for each chunk produced. + * @since v17.5.0 + * @returns a stream of indexed pairs. + */ + asIndexedPairs(options?: Pick): Readable; + /** + * This method calls *fn* on each chunk of the stream in order, passing it the result from the calculation + * on the previous element. It returns a promise for the final value of the reduction. + * + * If no *initial* value is supplied the first chunk of the stream is used as the initial value. + * If the stream is empty, the promise is rejected with a `TypeError` with the `ERR_INVALID_ARGS` code property. + * + * The reducer function iterates the stream element-by-element which means that there is no *concurrency* parameter + * or parallelism. To perform a reduce concurrently, you can extract the async function to `readable.map` method. + * @since v17.5.0 + * @param fn a reducer function to call over every chunk in the stream. Async or not. + * @param initial the initial value to use in the reduction. + * @returns a promise for the final value of the reduction. + */ + reduce( + fn: (previous: any, data: any, options?: Pick) => T, + initial?: undefined, + options?: Pick, + ): Promise; + reduce( + fn: (previous: T, data: any, options?: Pick) => T, + initial: T, + options?: Pick, + ): Promise; + _destroy(error: Error | null, callback: (error?: Error | null) => void): void; + /** + * Destroy the stream. Optionally emit an `'error'` event, and emit a `'close'`event (unless `emitClose` is set to `false`). After this call, the readable + * stream will release any internal resources and subsequent calls to `push()`will be ignored. + * + * Once `destroy()` has been called any further calls will be a no-op and no + * further errors except from `_destroy()` may be emitted as `'error'`. + * + * Implementors should not override this method, but instead implement `readable._destroy()`. + * @since v8.0.0 + * @param error Error which will be passed as payload in `'error'` event + */ + destroy(error?: Error): this; + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. data + * 3. end + * 4. error + * 5. pause + * 6. readable + * 7. resume + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: any) => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "close"): boolean; + emit(event: "data", chunk: any): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "pause"): boolean; + emit(event: "readable"): boolean; + emit(event: "resume"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: any) => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "readable", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: any) => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "readable", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: any) => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: any) => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: "close", listener: () => void): this; + removeListener(event: "data", listener: (chunk: any) => void): this; + removeListener(event: "end", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: "pause", listener: () => void): this; + removeListener(event: "readable", listener: () => void): this; + removeListener(event: "resume", listener: () => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + [Symbol.asyncIterator](): AsyncIterableIterator; + /** + * Calls `readable.destroy()` with an `AbortError` and returns a promise that fulfills when the stream is finished. + * @since v18.18.0 + */ + [Symbol.asyncDispose](): Promise; + } + interface WritableOptions extends StreamOptions { + decodeStrings?: boolean | undefined; + defaultEncoding?: BufferEncoding | undefined; + write?( + this: Writable, + chunk: any, + encoding: BufferEncoding, + callback: (error?: Error | null) => void, + ): void; + writev?( + this: Writable, + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void, + ): void; + final?(this: Writable, callback: (error?: Error | null) => void): void; + } + /** + * @since v0.9.4 + */ + class Writable extends Stream implements NodeJS.WritableStream { + /** + * A utility method for creating a `Writable` from a web `WritableStream`. + * @since v17.0.0 + * @experimental + */ + static fromWeb( + writableStream: streamWeb.WritableStream, + options?: Pick, + ): Writable; + /** + * A utility method for creating a web `WritableStream` from a `Writable`. + * @since v17.0.0 + * @experimental + */ + static toWeb(streamWritable: Writable): streamWeb.WritableStream; + /** + * Is `true` if it is safe to call `writable.write()`, which means + * the stream has not been destroyed, errored or ended. + * @since v11.4.0 + */ + readonly writable: boolean; + /** + * Is `true` after `writable.end()` has been called. This property + * does not indicate whether the data has been flushed, for this use `writable.writableFinished` instead. + * @since v12.9.0 + */ + readonly writableEnded: boolean; + /** + * Is set to `true` immediately before the `'finish'` event is emitted. + * @since v12.6.0 + */ + readonly writableFinished: boolean; + /** + * Return the value of `highWaterMark` passed when creating this `Writable`. + * @since v9.3.0 + */ + readonly writableHighWaterMark: number; + /** + * This property contains the number of bytes (or objects) in the queue + * ready to be written. The value provides introspection data regarding + * the status of the `highWaterMark`. + * @since v9.4.0 + */ + readonly writableLength: number; + /** + * Getter for the property `objectMode` of a given `Writable` stream. + * @since v12.3.0 + */ + readonly writableObjectMode: boolean; + /** + * Number of times `writable.uncork()` needs to be + * called in order to fully uncork the stream. + * @since v13.2.0, v12.16.0 + */ + readonly writableCorked: number; + /** + * Is `true` after `writable.destroy()` has been called. + * @since v8.0.0 + */ + destroyed: boolean; + /** + * Is true after 'close' has been emitted. + * @since v18.0.0 + */ + readonly closed: boolean; + /** + * Returns error if the stream has been destroyed with an error. + * @since v18.0.0 + */ + readonly errored: Error | null; + /** + * Is `true` if the stream's buffer has been full and stream will emit 'drain'. + * @since v15.2.0, v14.17.0 + */ + readonly writableNeedDrain: boolean; + constructor(opts?: WritableOptions); + _write(chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; + _writev?( + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void, + ): void; + _construct?(callback: (error?: Error | null) => void): void; + _destroy(error: Error | null, callback: (error?: Error | null) => void): void; + _final(callback: (error?: Error | null) => void): void; + /** + * The `writable.write()` method writes some data to the stream, and calls the + * supplied `callback` once the data has been fully handled. If an error + * occurs, the `callback` will be called with the error as its + * first argument. The `callback` is called asynchronously and before `'error'` is + * emitted. + * + * The return value is `true` if the internal buffer is less than the`highWaterMark` configured when the stream was created after admitting `chunk`. + * If `false` is returned, further attempts to write data to the stream should + * stop until the `'drain'` event is emitted. + * + * While a stream is not draining, calls to `write()` will buffer `chunk`, and + * return false. Once all currently buffered chunks are drained (accepted for + * delivery by the operating system), the `'drain'` event will be emitted. + * Once `write()` returns false, do not write more chunks + * until the `'drain'` event is emitted. While calling `write()` on a stream that + * is not draining is allowed, Node.js will buffer all written chunks until + * maximum memory usage occurs, at which point it will abort unconditionally. + * Even before it aborts, high memory usage will cause poor garbage collector + * performance and high RSS (which is not typically released back to the system, + * even after the memory is no longer required). Since TCP sockets may never + * drain if the remote peer does not read the data, writing a socket that is + * not draining may lead to a remotely exploitable vulnerability. + * + * Writing data while the stream is not draining is particularly + * problematic for a `Transform`, because the `Transform` streams are paused + * by default until they are piped or a `'data'` or `'readable'` event handler + * is added. + * + * If the data to be written can be generated or fetched on demand, it is + * recommended to encapsulate the logic into a `Readable` and use {@link pipe}. However, if calling `write()` is preferred, it is + * possible to respect backpressure and avoid memory issues using the `'drain'` event: + * + * ```js + * function write(data, cb) { + * if (!stream.write(data)) { + * stream.once('drain', cb); + * } else { + * process.nextTick(cb); + * } + * } + * + * // Wait for cb to be called before doing any other write. + * write('hello', () => { + * console.log('Write completed, do more writes now.'); + * }); + * ``` + * + * A `Writable` stream in object mode will always ignore the `encoding` argument. + * @since v0.9.4 + * @param chunk Optional data to write. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any + * JavaScript value other than `null`. + * @param [encoding='utf8'] The encoding, if `chunk` is a string. + * @param callback Callback for when this chunk of data is flushed. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + write(chunk: any, callback?: (error: Error | null | undefined) => void): boolean; + write(chunk: any, encoding: BufferEncoding, callback?: (error: Error | null | undefined) => void): boolean; + /** + * The `writable.setDefaultEncoding()` method sets the default `encoding` for a `Writable` stream. + * @since v0.11.15 + * @param encoding The new default encoding + */ + setDefaultEncoding(encoding: BufferEncoding): this; + /** + * Calling the `writable.end()` method signals that no more data will be written + * to the `Writable`. The optional `chunk` and `encoding` arguments allow one + * final additional chunk of data to be written immediately before closing the + * stream. + * + * Calling the {@link write} method after calling {@link end} will raise an error. + * + * ```js + * // Write 'hello, ' and then end with 'world!'. + * const fs = require('fs'); + * const file = fs.createWriteStream('example.txt'); + * file.write('hello, '); + * file.end('world!'); + * // Writing more now is not allowed! + * ``` + * @since v0.9.4 + * @param chunk Optional data to write. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any + * JavaScript value other than `null`. + * @param encoding The encoding if `chunk` is a string + * @param callback Callback for when the stream is finished. + */ + end(cb?: () => void): this; + end(chunk: any, cb?: () => void): this; + end(chunk: any, encoding: BufferEncoding, cb?: () => void): this; + /** + * The `writable.cork()` method forces all written data to be buffered in memory. + * The buffered data will be flushed when either the {@link uncork} or {@link end} methods are called. + * + * The primary intent of `writable.cork()` is to accommodate a situation in which + * several small chunks are written to the stream in rapid succession. Instead of + * immediately forwarding them to the underlying destination, `writable.cork()`buffers all the chunks until `writable.uncork()` is called, which will pass them + * all to `writable._writev()`, if present. This prevents a head-of-line blocking + * situation where data is being buffered while waiting for the first small chunk + * to be processed. However, use of `writable.cork()` without implementing`writable._writev()` may have an adverse effect on throughput. + * + * See also: `writable.uncork()`, `writable._writev()`. + * @since v0.11.2 + */ + cork(): void; + /** + * The `writable.uncork()` method flushes all data buffered since {@link cork} was called. + * + * When using `writable.cork()` and `writable.uncork()` to manage the buffering + * of writes to a stream, defer calls to `writable.uncork()` using`process.nextTick()`. Doing so allows batching of all`writable.write()` calls that occur within a given Node.js event + * loop phase. + * + * ```js + * stream.cork(); + * stream.write('some '); + * stream.write('data '); + * process.nextTick(() => stream.uncork()); + * ``` + * + * If the `writable.cork()` method is called multiple times on a stream, the + * same number of calls to `writable.uncork()` must be called to flush the buffered + * data. + * + * ```js + * stream.cork(); + * stream.write('some '); + * stream.cork(); + * stream.write('data '); + * process.nextTick(() => { + * stream.uncork(); + * // The data will not be flushed until uncork() is called a second time. + * stream.uncork(); + * }); + * ``` + * + * See also: `writable.cork()`. + * @since v0.11.2 + */ + uncork(): void; + /** + * Destroy the stream. Optionally emit an `'error'` event, and emit a `'close'`event (unless `emitClose` is set to `false`). After this call, the writable + * stream has ended and subsequent calls to `write()` or `end()` will result in + * an `ERR_STREAM_DESTROYED` error. + * This is a destructive and immediate way to destroy a stream. Previous calls to`write()` may not have drained, and may trigger an `ERR_STREAM_DESTROYED` error. + * Use `end()` instead of destroy if data should flush before close, or wait for + * the `'drain'` event before destroying the stream. + * + * Once `destroy()` has been called any further calls will be a no-op and no + * further errors except from `_destroy()` may be emitted as `'error'`. + * + * Implementors should not override this method, + * but instead implement `writable._destroy()`. + * @since v8.0.0 + * @param error Optional, an error to emit with `'error'` event. + */ + destroy(error?: Error): this; + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. drain + * 3. error + * 4. finish + * 5. pipe + * 6. unpipe + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "pipe", listener: (src: Readable) => void): this; + addListener(event: "unpipe", listener: (src: Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "close"): boolean; + emit(event: "drain"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "pipe", src: Readable): boolean; + emit(event: "unpipe", src: Readable): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pipe", listener: (src: Readable) => void): this; + on(event: "unpipe", listener: (src: Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pipe", listener: (src: Readable) => void): this; + once(event: "unpipe", listener: (src: Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "pipe", listener: (src: Readable) => void): this; + prependListener(event: "unpipe", listener: (src: Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "pipe", listener: (src: Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: "close", listener: () => void): this; + removeListener(event: "drain", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: "finish", listener: () => void): this; + removeListener(event: "pipe", listener: (src: Readable) => void): this; + removeListener(event: "unpipe", listener: (src: Readable) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + interface DuplexOptions extends ReadableOptions, WritableOptions { + allowHalfOpen?: boolean | undefined; + readableObjectMode?: boolean | undefined; + writableObjectMode?: boolean | undefined; + readableHighWaterMark?: number | undefined; + writableHighWaterMark?: number | undefined; + writableCorked?: number | undefined; + construct?(this: Duplex, callback: (error?: Error | null) => void): void; + read?(this: Duplex, size: number): void; + write?(this: Duplex, chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; + writev?( + this: Duplex, + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void, + ): void; + final?(this: Duplex, callback: (error?: Error | null) => void): void; + destroy?(this: Duplex, error: Error | null, callback: (error?: Error | null) => void): void; + } + /** + * Duplex streams are streams that implement both the `Readable` and `Writable` interfaces. + * + * Examples of `Duplex` streams include: + * + * * `TCP sockets` + * * `zlib streams` + * * `crypto streams` + * @since v0.9.4 + */ + class Duplex extends Readable implements Writable { + readonly writable: boolean; + readonly writableEnded: boolean; + readonly writableFinished: boolean; + readonly writableHighWaterMark: number; + readonly writableLength: number; + readonly writableObjectMode: boolean; + readonly writableCorked: number; + readonly writableNeedDrain: boolean; + readonly closed: boolean; + readonly errored: Error | null; + /** + * If `false` then the stream will automatically end the writable side when the + * readable side ends. Set initially by the `allowHalfOpen` constructor option, + * which defaults to `false`. + * + * This can be changed manually to change the half-open behavior of an existing`Duplex` stream instance, but must be changed before the `'end'` event is + * emitted. + * @since v0.9.4 + */ + allowHalfOpen: boolean; + constructor(opts?: DuplexOptions); + /** + * A utility method for creating duplex streams. + * + * - `Stream` converts writable stream into writable `Duplex` and readable stream + * to `Duplex`. + * - `Blob` converts into readable `Duplex`. + * - `string` converts into readable `Duplex`. + * - `ArrayBuffer` converts into readable `Duplex`. + * - `AsyncIterable` converts into a readable `Duplex`. Cannot yield `null`. + * - `AsyncGeneratorFunction` converts into a readable/writable transform + * `Duplex`. Must take a source `AsyncIterable` as first parameter. Cannot yield + * `null`. + * - `AsyncFunction` converts into a writable `Duplex`. Must return + * either `null` or `undefined` + * - `Object ({ writable, readable })` converts `readable` and + * `writable` into `Stream` and then combines them into `Duplex` where the + * `Duplex` will write to the `writable` and read from the `readable`. + * - `Promise` converts into readable `Duplex`. Value `null` is ignored. + * + * @since v16.8.0 + */ + static from( + src: + | Stream + | NodeBlob + | ArrayBuffer + | string + | Iterable + | AsyncIterable + | AsyncGeneratorFunction + | Promise + | Object, + ): Duplex; + _write(chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; + _writev?( + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void, + ): void; + _destroy(error: Error | null, callback: (error?: Error | null) => void): void; + _final(callback: (error?: Error | null) => void): void; + write(chunk: any, encoding?: BufferEncoding, cb?: (error: Error | null | undefined) => void): boolean; + write(chunk: any, cb?: (error: Error | null | undefined) => void): boolean; + setDefaultEncoding(encoding: BufferEncoding): this; + end(cb?: () => void): this; + end(chunk: any, cb?: () => void): this; + end(chunk: any, encoding?: BufferEncoding, cb?: () => void): this; + cork(): void; + uncork(): void; + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. data + * 3. drain + * 4. end + * 5. error + * 6. finish + * 7. pause + * 8. pipe + * 9. readable + * 10. resume + * 11. unpipe + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: any) => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "pipe", listener: (src: Readable) => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: "unpipe", listener: (src: Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "close"): boolean; + emit(event: "data", chunk: any): boolean; + emit(event: "drain"): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "pause"): boolean; + emit(event: "pipe", src: Readable): boolean; + emit(event: "readable"): boolean; + emit(event: "resume"): boolean; + emit(event: "unpipe", src: Readable): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: any) => void): this; + on(event: "drain", listener: () => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pause", listener: () => void): this; + on(event: "pipe", listener: (src: Readable) => void): this; + on(event: "readable", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: "unpipe", listener: (src: Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: any) => void): this; + once(event: "drain", listener: () => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pause", listener: () => void): this; + once(event: "pipe", listener: (src: Readable) => void): this; + once(event: "readable", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: "unpipe", listener: (src: Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: any) => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "pipe", listener: (src: Readable) => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: "unpipe", listener: (src: Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: any) => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "pipe", listener: (src: Readable) => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: "unpipe", listener: (src: Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: "close", listener: () => void): this; + removeListener(event: "data", listener: (chunk: any) => void): this; + removeListener(event: "drain", listener: () => void): this; + removeListener(event: "end", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: "finish", listener: () => void): this; + removeListener(event: "pause", listener: () => void): this; + removeListener(event: "pipe", listener: (src: Readable) => void): this; + removeListener(event: "readable", listener: () => void): this; + removeListener(event: "resume", listener: () => void): this; + removeListener(event: "unpipe", listener: (src: Readable) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + type TransformCallback = (error?: Error | null, data?: any) => void; + interface TransformOptions extends DuplexOptions { + construct?(this: Transform, callback: (error?: Error | null) => void): void; + read?(this: Transform, size: number): void; + write?( + this: Transform, + chunk: any, + encoding: BufferEncoding, + callback: (error?: Error | null) => void, + ): void; + writev?( + this: Transform, + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void, + ): void; + final?(this: Transform, callback: (error?: Error | null) => void): void; + destroy?(this: Transform, error: Error | null, callback: (error?: Error | null) => void): void; + transform?(this: Transform, chunk: any, encoding: BufferEncoding, callback: TransformCallback): void; + flush?(this: Transform, callback: TransformCallback): void; + } + /** + * Transform streams are `Duplex` streams where the output is in some way + * related to the input. Like all `Duplex` streams, `Transform` streams + * implement both the `Readable` and `Writable` interfaces. + * + * Examples of `Transform` streams include: + * + * * `zlib streams` + * * `crypto streams` + * @since v0.9.4 + */ + class Transform extends Duplex { + constructor(opts?: TransformOptions); + _transform(chunk: any, encoding: BufferEncoding, callback: TransformCallback): void; + _flush(callback: TransformCallback): void; + } + /** + * The `stream.PassThrough` class is a trivial implementation of a `Transform` stream that simply passes the input bytes across to the output. Its purpose is + * primarily for examples and testing, but there are some use cases where`stream.PassThrough` is useful as a building block for novel sorts of streams. + */ + class PassThrough extends Transform {} + /** + * Attaches an AbortSignal to a readable or writeable stream. This lets code + * control stream destruction using an `AbortController`. + * + * Calling `abort` on the `AbortController` corresponding to the passed`AbortSignal` will behave the same way as calling `.destroy(new AbortError())`on the stream. + * + * ```js + * const fs = require('fs'); + * + * const controller = new AbortController(); + * const read = addAbortSignal( + * controller.signal, + * fs.createReadStream(('object.json')) + * ); + * // Later, abort the operation closing the stream + * controller.abort(); + * ``` + * + * Or using an `AbortSignal` with a readable stream as an async iterable: + * + * ```js + * const controller = new AbortController(); + * setTimeout(() => controller.abort(), 10_000); // set a timeout + * const stream = addAbortSignal( + * controller.signal, + * fs.createReadStream(('object.json')) + * ); + * (async () => { + * try { + * for await (const chunk of stream) { + * await process(chunk); + * } + * } catch (e) { + * if (e.name === 'AbortError') { + * // The operation was cancelled + * } else { + * throw e; + * } + * } + * })(); + * ``` + * @since v15.4.0 + * @param signal A signal representing possible cancellation + * @param stream a stream to attach a signal to + */ + function addAbortSignal(signal: AbortSignal, stream: T): T; + /** + * Returns the default highWaterMark used by streams. + * Defaults to `16384` (16 KiB), or `16` for `objectMode`. + * @since v18.17.0 + * @param objectMode + */ + function getDefaultHighWaterMark(objectMode: boolean): number; + /** + * Sets the default highWaterMark used by streams. + * @since v18.17.0 + * @param objectMode + * @param value highWaterMark value + */ + function setDefaultHighWaterMark(objectMode: boolean, value: number): void; + interface FinishedOptions extends Abortable { + error?: boolean | undefined; + readable?: boolean | undefined; + writable?: boolean | undefined; + } + /** + * A function to get notified when a stream is no longer readable, writable + * or has experienced an error or a premature close event. + * + * ```js + * const { finished } = require('stream'); + * + * const rs = fs.createReadStream('archive.tar'); + * + * finished(rs, (err) => { + * if (err) { + * console.error('Stream failed.', err); + * } else { + * console.log('Stream is done reading.'); + * } + * }); + * + * rs.resume(); // Drain the stream. + * ``` + * + * Especially useful in error handling scenarios where a stream is destroyed + * prematurely (like an aborted HTTP request), and will not emit `'end'`or `'finish'`. + * + * The `finished` API provides promise version: + * + * ```js + * const { finished } = require('stream/promises'); + * + * const rs = fs.createReadStream('archive.tar'); + * + * async function run() { + * await finished(rs); + * console.log('Stream is done reading.'); + * } + * + * run().catch(console.error); + * rs.resume(); // Drain the stream. + * ``` + * + * `stream.finished()` leaves dangling event listeners (in particular`'error'`, `'end'`, `'finish'` and `'close'`) after `callback` has been + * invoked. The reason for this is so that unexpected `'error'` events (due to + * incorrect stream implementations) do not cause unexpected crashes. + * If this is unwanted behavior then the returned cleanup function needs to be + * invoked in the callback: + * + * ```js + * const cleanup = finished(rs, (err) => { + * cleanup(); + * // ... + * }); + * ``` + * @since v10.0.0 + * @param stream A readable and/or writable stream. + * @param callback A callback function that takes an optional error argument. + * @return A cleanup function which removes all registered listeners. + */ + function finished( + stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, + options: FinishedOptions, + callback: (err?: NodeJS.ErrnoException | null) => void, + ): () => void; + function finished( + stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, + callback: (err?: NodeJS.ErrnoException | null) => void, + ): () => void; + namespace finished { + function __promisify__( + stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, + options?: FinishedOptions, + ): Promise; + } + type PipelineSourceFunction = () => Iterable | AsyncIterable; + type PipelineSource = Iterable | AsyncIterable | NodeJS.ReadableStream | PipelineSourceFunction; + type PipelineTransform, U> = + | NodeJS.ReadWriteStream + | (( + source: S extends (...args: any[]) => Iterable | AsyncIterable ? AsyncIterable + : S, + ) => AsyncIterable); + type PipelineTransformSource = PipelineSource | PipelineTransform; + type PipelineDestinationIterableFunction = (source: AsyncIterable) => AsyncIterable; + type PipelineDestinationPromiseFunction = (source: AsyncIterable) => Promise

; + type PipelineDestination, P> = S extends + PipelineTransformSource ? + | NodeJS.WritableStream + | PipelineDestinationIterableFunction + | PipelineDestinationPromiseFunction + : never; + type PipelineCallback> = S extends + PipelineDestinationPromiseFunction ? (err: NodeJS.ErrnoException | null, value: P) => void + : (err: NodeJS.ErrnoException | null) => void; + type PipelinePromise> = S extends + PipelineDestinationPromiseFunction ? Promise

: Promise; + interface PipelineOptions { + signal?: AbortSignal | undefined; + end?: boolean | undefined; + } + /** + * A module method to pipe between streams and generators forwarding errors and + * properly cleaning up and provide a callback when the pipeline is complete. + * + * ```js + * const { pipeline } = require('stream'); + * const fs = require('fs'); + * const zlib = require('zlib'); + * + * // Use the pipeline API to easily pipe a series of streams + * // together and get notified when the pipeline is fully done. + * + * // A pipeline to gzip a potentially huge tar file efficiently: + * + * pipeline( + * fs.createReadStream('archive.tar'), + * zlib.createGzip(), + * fs.createWriteStream('archive.tar.gz'), + * (err) => { + * if (err) { + * console.error('Pipeline failed.', err); + * } else { + * console.log('Pipeline succeeded.'); + * } + * } + * ); + * ``` + * + * The `pipeline` API provides a promise version, which can also + * receive an options argument as the last parameter with a`signal` `AbortSignal` property. When the signal is aborted,`destroy` will be called on the underlying pipeline, with + * an`AbortError`. + * + * ```js + * const { pipeline } = require('stream/promises'); + * + * async function run() { + * await pipeline( + * fs.createReadStream('archive.tar'), + * zlib.createGzip(), + * fs.createWriteStream('archive.tar.gz') + * ); + * console.log('Pipeline succeeded.'); + * } + * + * run().catch(console.error); + * ``` + * + * To use an `AbortSignal`, pass it inside an options object, + * as the last argument: + * + * ```js + * const { pipeline } = require('stream/promises'); + * + * async function run() { + * const ac = new AbortController(); + * const signal = ac.signal; + * + * setTimeout(() => ac.abort(), 1); + * await pipeline( + * fs.createReadStream('archive.tar'), + * zlib.createGzip(), + * fs.createWriteStream('archive.tar.gz'), + * { signal }, + * ); + * } + * + * run().catch(console.error); // AbortError + * ``` + * + * The `pipeline` API also supports async generators: + * + * ```js + * const { pipeline } = require('stream/promises'); + * const fs = require('fs'); + * + * async function run() { + * await pipeline( + * fs.createReadStream('lowercase.txt'), + * async function* (source, { signal }) { + * source.setEncoding('utf8'); // Work with strings rather than `Buffer`s. + * for await (const chunk of source) { + * yield await processChunk(chunk, { signal }); + * } + * }, + * fs.createWriteStream('uppercase.txt') + * ); + * console.log('Pipeline succeeded.'); + * } + * + * run().catch(console.error); + * ``` + * + * Remember to handle the `signal` argument passed into the async generator. + * Especially in the case where the async generator is the source for the + * pipeline (i.e. first argument) or the pipeline will never complete. + * + * ```js + * const { pipeline } = require('stream/promises'); + * const fs = require('fs'); + * + * async function run() { + * await pipeline( + * async function* ({ signal }) { + * await someLongRunningfn({ signal }); + * yield 'asd'; + * }, + * fs.createWriteStream('uppercase.txt') + * ); + * console.log('Pipeline succeeded.'); + * } + * + * run().catch(console.error); + * ``` + * + * `stream.pipeline()` will call `stream.destroy(err)` on all streams except: + * + * * `Readable` streams which have emitted `'end'` or `'close'`. + * * `Writable` streams which have emitted `'finish'` or `'close'`. + * + * `stream.pipeline()` leaves dangling event listeners on the streams + * after the `callback` has been invoked. In the case of reuse of streams after + * failure, this can cause event listener leaks and swallowed errors. If the last + * stream is readable, dangling event listeners will be removed so that the last + * stream can be consumed later. + * + * `stream.pipeline()` closes all the streams when an error is raised. + * The `IncomingRequest` usage with `pipeline` could lead to an unexpected behavior + * once it would destroy the socket without sending the expected response. + * See the example below: + * + * ```js + * const fs = require('fs'); + * const http = require('http'); + * const { pipeline } = require('stream'); + * + * const server = http.createServer((req, res) => { + * const fileStream = fs.createReadStream('./fileNotExist.txt'); + * pipeline(fileStream, res, (err) => { + * if (err) { + * console.log(err); // No such file + * // this message can't be sent once `pipeline` already destroyed the socket + * return res.end('error!!!'); + * } + * }); + * }); + * ``` + * @since v10.0.0 + * @param callback Called when the pipeline is fully done. + */ + function pipeline, B extends PipelineDestination>( + source: A, + destination: B, + callback?: PipelineCallback, + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + destination: B, + callback?: PipelineCallback, + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + destination: B, + callback?: PipelineCallback, + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + destination: B, + callback?: PipelineCallback, + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + T4 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + transform4: T4, + destination: B, + callback?: PipelineCallback, + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline( + streams: ReadonlyArray, + callback?: (err: NodeJS.ErrnoException | null) => void, + ): NodeJS.WritableStream; + function pipeline( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array< + NodeJS.ReadWriteStream | NodeJS.WritableStream | ((err: NodeJS.ErrnoException | null) => void) + > + ): NodeJS.WritableStream; + namespace pipeline { + function __promisify__, B extends PipelineDestination>( + source: A, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function __promisify__< + A extends PipelineSource, + T1 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function __promisify__< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function __promisify__< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function __promisify__< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + T4 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + transform4: T4, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function __promisify__( + streams: ReadonlyArray, + options?: PipelineOptions, + ): Promise; + function __promisify__( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array + ): Promise; + } + interface Pipe { + close(): void; + hasRef(): boolean; + ref(): void; + unref(): void; + } + + /** + * Returns whether the stream has encountered an error. + * @since v17.3.0 + */ + function isErrored(stream: Readable | Writable | NodeJS.ReadableStream | NodeJS.WritableStream): boolean; + + /** + * Returns whether the stream is readable. + * @since v17.4.0 + */ + function isReadable(stream: Readable | NodeJS.ReadableStream): boolean; + + const promises: typeof streamPromises; + const consumers: typeof streamConsumers; + } + export = internal; +} +declare module "node:stream" { + import stream = require("stream"); + export = stream; +} diff --git a/backend/node_modules/@types/node/stream/consumers.d.ts b/backend/node_modules/@types/node/stream/consumers.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5ad9cbab98829fd66db9effa031b885647ba251c --- /dev/null +++ b/backend/node_modules/@types/node/stream/consumers.d.ts @@ -0,0 +1,12 @@ +declare module "stream/consumers" { + import { Blob as NodeBlob } from "node:buffer"; + import { Readable } from "node:stream"; + function buffer(stream: NodeJS.ReadableStream | Readable | AsyncIterable): Promise; + function text(stream: NodeJS.ReadableStream | Readable | AsyncIterable): Promise; + function arrayBuffer(stream: NodeJS.ReadableStream | Readable | AsyncIterable): Promise; + function blob(stream: NodeJS.ReadableStream | Readable | AsyncIterable): Promise; + function json(stream: NodeJS.ReadableStream | Readable | AsyncIterable): Promise; +} +declare module "node:stream/consumers" { + export * from "stream/consumers"; +} diff --git a/backend/node_modules/@types/node/stream/promises.d.ts b/backend/node_modules/@types/node/stream/promises.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6eac5b7156a6b0cecea5c24cd8037a0a75af42eb --- /dev/null +++ b/backend/node_modules/@types/node/stream/promises.d.ts @@ -0,0 +1,83 @@ +declare module "stream/promises" { + import { + FinishedOptions, + PipelineDestination, + PipelineOptions, + PipelinePromise, + PipelineSource, + PipelineTransform, + } from "node:stream"; + function finished( + stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, + options?: FinishedOptions, + ): Promise; + function pipeline, B extends PipelineDestination>( + source: A, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + T4 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + transform4: T4, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function pipeline( + streams: ReadonlyArray, + options?: PipelineOptions, + ): Promise; + function pipeline( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array + ): Promise; +} +declare module "node:stream/promises" { + export * from "stream/promises"; +} diff --git a/backend/node_modules/@types/node/stream/web.d.ts b/backend/node_modules/@types/node/stream/web.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..aac05236fda8526cd3be1b1ae32d4518b1d3c2b0 --- /dev/null +++ b/backend/node_modules/@types/node/stream/web.d.ts @@ -0,0 +1,352 @@ +declare module "stream/web" { + // stub module, pending copy&paste from .d.ts or manual impl + // copy from lib.dom.d.ts + interface ReadableWritablePair { + readable: ReadableStream; + /** + * Provides a convenient, chainable way of piping this readable stream + * through a transform stream (or any other { writable, readable } + * pair). It simply pipes the stream into the writable side of the + * supplied pair, and returns the readable side for further use. + * + * Piping a stream will lock it for the duration of the pipe, preventing + * any other consumer from acquiring a reader. + */ + writable: WritableStream; + } + interface StreamPipeOptions { + preventAbort?: boolean; + preventCancel?: boolean; + /** + * Pipes this readable stream to a given writable stream destination. + * The way in which the piping process behaves under various error + * conditions can be customized with a number of passed options. It + * returns a promise that fulfills when the piping process completes + * successfully, or rejects if any errors were encountered. + * + * Piping a stream will lock it for the duration of the pipe, preventing + * any other consumer from acquiring a reader. + * + * Errors and closures of the source and destination streams propagate + * as follows: + * + * An error in this source readable stream will abort destination, + * unless preventAbort is truthy. The returned promise will be rejected + * with the source's error, or with any error that occurs during + * aborting the destination. + * + * An error in destination will cancel this source readable stream, + * unless preventCancel is truthy. The returned promise will be rejected + * with the destination's error, or with any error that occurs during + * canceling the source. + * + * When this source readable stream closes, destination will be closed, + * unless preventClose is truthy. The returned promise will be fulfilled + * once this process completes, unless an error is encountered while + * closing the destination, in which case it will be rejected with that + * error. + * + * If destination starts out closed or closing, this source readable + * stream will be canceled, unless preventCancel is true. The returned + * promise will be rejected with an error indicating piping to a closed + * stream failed, or with any error that occurs during canceling the + * source. + * + * The signal option can be set to an AbortSignal to allow aborting an + * ongoing pipe operation via the corresponding AbortController. In this + * case, this source readable stream will be canceled, and destination + * aborted, unless the respective options preventCancel or preventAbort + * are set. + */ + preventClose?: boolean; + signal?: AbortSignal; + } + interface ReadableStreamGenericReader { + readonly closed: Promise; + cancel(reason?: any): Promise; + } + interface ReadableStreamDefaultReadValueResult { + done: false; + value: T; + } + interface ReadableStreamDefaultReadDoneResult { + done: true; + value?: undefined; + } + type ReadableStreamController = ReadableStreamDefaultController; + type ReadableStreamDefaultReadResult = + | ReadableStreamDefaultReadValueResult + | ReadableStreamDefaultReadDoneResult; + interface ReadableByteStreamControllerCallback { + (controller: ReadableByteStreamController): void | PromiseLike; + } + interface UnderlyingSinkAbortCallback { + (reason?: any): void | PromiseLike; + } + interface UnderlyingSinkCloseCallback { + (): void | PromiseLike; + } + interface UnderlyingSinkStartCallback { + (controller: WritableStreamDefaultController): any; + } + interface UnderlyingSinkWriteCallback { + (chunk: W, controller: WritableStreamDefaultController): void | PromiseLike; + } + interface UnderlyingSourceCancelCallback { + (reason?: any): void | PromiseLike; + } + interface UnderlyingSourcePullCallback { + (controller: ReadableStreamController): void | PromiseLike; + } + interface UnderlyingSourceStartCallback { + (controller: ReadableStreamController): any; + } + interface TransformerFlushCallback { + (controller: TransformStreamDefaultController): void | PromiseLike; + } + interface TransformerStartCallback { + (controller: TransformStreamDefaultController): any; + } + interface TransformerTransformCallback { + (chunk: I, controller: TransformStreamDefaultController): void | PromiseLike; + } + interface UnderlyingByteSource { + autoAllocateChunkSize?: number; + cancel?: ReadableStreamErrorCallback; + pull?: ReadableByteStreamControllerCallback; + start?: ReadableByteStreamControllerCallback; + type: "bytes"; + } + interface UnderlyingSource { + cancel?: UnderlyingSourceCancelCallback; + pull?: UnderlyingSourcePullCallback; + start?: UnderlyingSourceStartCallback; + type?: undefined; + } + interface UnderlyingSink { + abort?: UnderlyingSinkAbortCallback; + close?: UnderlyingSinkCloseCallback; + start?: UnderlyingSinkStartCallback; + type?: undefined; + write?: UnderlyingSinkWriteCallback; + } + interface ReadableStreamErrorCallback { + (reason: any): void | PromiseLike; + } + /** This Streams API interface represents a readable stream of byte data. */ + interface ReadableStream { + readonly locked: boolean; + cancel(reason?: any): Promise; + getReader(): ReadableStreamDefaultReader; + pipeThrough(transform: ReadableWritablePair, options?: StreamPipeOptions): ReadableStream; + pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise; + tee(): [ReadableStream, ReadableStream]; + values(options?: { preventCancel?: boolean }): AsyncIterableIterator; + [Symbol.asyncIterator](): AsyncIterableIterator; + } + const ReadableStream: { + prototype: ReadableStream; + new(underlyingSource: UnderlyingByteSource, strategy?: QueuingStrategy): ReadableStream; + new(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy): ReadableStream; + }; + interface ReadableStreamDefaultReader extends ReadableStreamGenericReader { + read(): Promise>; + releaseLock(): void; + } + const ReadableStreamDefaultReader: { + prototype: ReadableStreamDefaultReader; + new(stream: ReadableStream): ReadableStreamDefaultReader; + }; + const ReadableStreamBYOBReader: any; + const ReadableStreamBYOBRequest: any; + interface ReadableByteStreamController { + readonly byobRequest: undefined; + readonly desiredSize: number | null; + close(): void; + enqueue(chunk: ArrayBufferView): void; + error(error?: any): void; + } + const ReadableByteStreamController: { + prototype: ReadableByteStreamController; + new(): ReadableByteStreamController; + }; + interface ReadableStreamDefaultController { + readonly desiredSize: number | null; + close(): void; + enqueue(chunk?: R): void; + error(e?: any): void; + } + const ReadableStreamDefaultController: { + prototype: ReadableStreamDefaultController; + new(): ReadableStreamDefaultController; + }; + interface Transformer { + flush?: TransformerFlushCallback; + readableType?: undefined; + start?: TransformerStartCallback; + transform?: TransformerTransformCallback; + writableType?: undefined; + } + interface TransformStream { + readonly readable: ReadableStream; + readonly writable: WritableStream; + } + const TransformStream: { + prototype: TransformStream; + new( + transformer?: Transformer, + writableStrategy?: QueuingStrategy, + readableStrategy?: QueuingStrategy, + ): TransformStream; + }; + interface TransformStreamDefaultController { + readonly desiredSize: number | null; + enqueue(chunk?: O): void; + error(reason?: any): void; + terminate(): void; + } + const TransformStreamDefaultController: { + prototype: TransformStreamDefaultController; + new(): TransformStreamDefaultController; + }; + /** + * This Streams API interface provides a standard abstraction for writing + * streaming data to a destination, known as a sink. This object comes with + * built-in back pressure and queuing. + */ + interface WritableStream { + readonly locked: boolean; + abort(reason?: any): Promise; + close(): Promise; + getWriter(): WritableStreamDefaultWriter; + } + const WritableStream: { + prototype: WritableStream; + new(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy): WritableStream; + }; + /** + * This Streams API interface is the object returned by + * WritableStream.getWriter() and once created locks the < writer to the + * WritableStream ensuring that no other streams can write to the underlying + * sink. + */ + interface WritableStreamDefaultWriter { + readonly closed: Promise; + readonly desiredSize: number | null; + readonly ready: Promise; + abort(reason?: any): Promise; + close(): Promise; + releaseLock(): void; + write(chunk?: W): Promise; + } + const WritableStreamDefaultWriter: { + prototype: WritableStreamDefaultWriter; + new(stream: WritableStream): WritableStreamDefaultWriter; + }; + /** + * This Streams API interface represents a controller allowing control of a + * WritableStream's state. When constructing a WritableStream, the + * underlying sink is given a corresponding WritableStreamDefaultController + * instance to manipulate. + */ + interface WritableStreamDefaultController { + error(e?: any): void; + } + const WritableStreamDefaultController: { + prototype: WritableStreamDefaultController; + new(): WritableStreamDefaultController; + }; + interface QueuingStrategy { + highWaterMark?: number; + size?: QueuingStrategySize; + } + interface QueuingStrategySize { + (chunk?: T): number; + } + interface QueuingStrategyInit { + /** + * Creates a new ByteLengthQueuingStrategy with the provided high water + * mark. + * + * Note that the provided high water mark will not be validated ahead of + * time. Instead, if it is negative, NaN, or not a number, the resulting + * ByteLengthQueuingStrategy will cause the corresponding stream + * constructor to throw. + */ + highWaterMark: number; + } + /** + * This Streams API interface provides a built-in byte length queuing + * strategy that can be used when constructing streams. + */ + interface ByteLengthQueuingStrategy extends QueuingStrategy { + readonly highWaterMark: number; + readonly size: QueuingStrategySize; + } + const ByteLengthQueuingStrategy: { + prototype: ByteLengthQueuingStrategy; + new(init: QueuingStrategyInit): ByteLengthQueuingStrategy; + }; + /** + * This Streams API interface provides a built-in byte length queuing + * strategy that can be used when constructing streams. + */ + interface CountQueuingStrategy extends QueuingStrategy { + readonly highWaterMark: number; + readonly size: QueuingStrategySize; + } + const CountQueuingStrategy: { + prototype: CountQueuingStrategy; + new(init: QueuingStrategyInit): CountQueuingStrategy; + }; + interface TextEncoderStream { + /** Returns "utf-8". */ + readonly encoding: "utf-8"; + readonly readable: ReadableStream; + readonly writable: WritableStream; + readonly [Symbol.toStringTag]: string; + } + const TextEncoderStream: { + prototype: TextEncoderStream; + new(): TextEncoderStream; + }; + interface TextDecoderOptions { + fatal?: boolean; + ignoreBOM?: boolean; + } + type BufferSource = ArrayBufferView | ArrayBuffer; + interface TextDecoderStream { + /** Returns encoding's name, lower cased. */ + readonly encoding: string; + /** Returns `true` if error mode is "fatal", and `false` otherwise. */ + readonly fatal: boolean; + /** Returns `true` if ignore BOM flag is set, and `false` otherwise. */ + readonly ignoreBOM: boolean; + readonly readable: ReadableStream; + readonly writable: WritableStream; + readonly [Symbol.toStringTag]: string; + } + const TextDecoderStream: { + prototype: TextDecoderStream; + new(encoding?: string, options?: TextDecoderOptions): TextDecoderStream; + }; + interface CompressionStream { + readonly readable: ReadableStream; + readonly writable: WritableStream; + } + const CompressionStream: { + prototype: CompressionStream; + new(format: string): CompressionStream; + }; + interface DecompressionStream { + readonly readable: ReadableStream; + readonly writable: WritableStream; + } + const DecompressionStream: { + prototype: DecompressionStream; + new(format: string): DecompressionStream; + }; +} +declare module "node:stream/web" { + export * from "stream/web"; +} diff --git a/backend/node_modules/@types/node/string_decoder.d.ts b/backend/node_modules/@types/node/string_decoder.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9e562266928f0687ded712fc3157ce3c4142e131 --- /dev/null +++ b/backend/node_modules/@types/node/string_decoder.d.ts @@ -0,0 +1,67 @@ +/** + * The `node:string_decoder` module provides an API for decoding `Buffer` objects + * into strings in a manner that preserves encoded multi-byte UTF-8 and UTF-16 + * characters. It can be accessed using: + * + * ```js + * const { StringDecoder } = require('node:string_decoder'); + * ``` + * + * The following example shows the basic use of the `StringDecoder` class. + * + * ```js + * const { StringDecoder } = require('node:string_decoder'); + * const decoder = new StringDecoder('utf8'); + * + * const cent = Buffer.from([0xC2, 0xA2]); + * console.log(decoder.write(cent)); // Prints: ¢ + * + * const euro = Buffer.from([0xE2, 0x82, 0xAC]); + * console.log(decoder.write(euro)); // Prints: € + * ``` + * + * When a `Buffer` instance is written to the `StringDecoder` instance, an + * internal buffer is used to ensure that the decoded string does not contain + * any incomplete multibyte characters. These are held in the buffer until the + * next call to `stringDecoder.write()` or until `stringDecoder.end()` is called. + * + * In the following example, the three UTF-8 encoded bytes of the European Euro + * symbol (`€`) are written over three separate operations: + * + * ```js + * const { StringDecoder } = require('node:string_decoder'); + * const decoder = new StringDecoder('utf8'); + * + * decoder.write(Buffer.from([0xE2])); + * decoder.write(Buffer.from([0x82])); + * console.log(decoder.end(Buffer.from([0xAC]))); // Prints: € + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.19.0/lib/string_decoder.js) + */ +declare module "string_decoder" { + class StringDecoder { + constructor(encoding?: BufferEncoding); + /** + * Returns a decoded string, ensuring that any incomplete multibyte characters at + * the end of the `Buffer`, or `TypedArray`, or `DataView` are omitted from the + * returned string and stored in an internal buffer for the next call to`stringDecoder.write()` or `stringDecoder.end()`. + * @since v0.1.99 + * @param buffer The bytes to decode. + */ + write(buffer: string | Buffer | NodeJS.ArrayBufferView): string; + /** + * Returns any remaining input stored in the internal buffer as a string. Bytes + * representing incomplete UTF-8 and UTF-16 characters will be replaced with + * substitution characters appropriate for the character encoding. + * + * If the `buffer` argument is provided, one final call to `stringDecoder.write()`is performed before returning the remaining input. + * After `end()` is called, the `stringDecoder` object can be reused for new input. + * @since v0.9.3 + * @param buffer The bytes to decode. + */ + end(buffer?: string | Buffer | NodeJS.ArrayBufferView): string; + } +} +declare module "node:string_decoder" { + export * from "string_decoder"; +} diff --git a/backend/node_modules/@types/node/test.d.ts b/backend/node_modules/@types/node/test.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5557822ef3a286e9de51b6de8a7f9efc07dc2c92 --- /dev/null +++ b/backend/node_modules/@types/node/test.d.ts @@ -0,0 +1,1113 @@ +/** + * The `node:test` module provides a standalone testing module. + * @see [source](https://github.com/nodejs/node/blob/v18.x/lib/test.js) + */ +declare module "node:test" { + import { AsyncResource } from "node:async_hooks"; + /** + * Programmatically start the test runner. + * @since v18.9.0 + * @param options Configuration options for running tests. + * @returns A {@link TestsStream} that emits events about the test execution. + */ + function run(options?: RunOptions): TestsStream; + /** + * The `test()` function is the value imported from the test module. Each invocation of this + * function results in reporting the test to the {@link TestsStream}. + * + * The {@link TestContext} object passed to the fn argument can be used to perform actions + * related to the current test. Examples include skipping the test, adding additional + * diagnostic information, or creating subtests. + * + * `test()` returns a {@link Promise} that resolves once the test completes. The return value + * can usually be discarded for top level tests. However, the return value from subtests should + * be used to prevent the parent test from finishing first and cancelling the subtest as shown + * in the following example. + * + * ```js + * test('top level test', async (t) => { + * // The setTimeout() in the following subtest would cause it to outlive its + * // parent test if 'await' is removed on the next line. Once the parent test + * // completes, it will cancel any outstanding subtests. + * await t.test('longer running subtest', async (t) => { + * return new Promise((resolve, reject) => { + * setTimeout(resolve, 1000); + * }); + * }); + * }); + * ``` + * @since v18.0.0 + * @param name The name of the test, which is displayed when reporting test results. + * Default: The `name` property of fn, or `''` if `fn` does not have a name. + * @param options Configuration options for the test + * @param fn The function under test. The first argument to this function is a + * {@link TestContext} object. If the test uses callbacks, the callback function is + * passed as the second argument. Default: A no-op function. + * @returns A {@link Promise} resolved with `undefined` once the test completes. + */ + function test(name?: string, fn?: TestFn): Promise; + function test(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function test(options?: TestOptions, fn?: TestFn): Promise; + function test(fn?: TestFn): Promise; + namespace test { + export { after, afterEach, before, beforeEach, describe, it, mock, only, run, skip, test, todo }; + } + /** + * @since v18.6.0 + * @param name The name of the suite, which is displayed when reporting suite results. + * Default: The `name` property of fn, or `''` if `fn` does not have a name. + * @param options Configuration options for the suite + * @param fn The function under suite. Default: A no-op function. + */ + function describe(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function describe(name?: string, fn?: SuiteFn): Promise; + function describe(options?: TestOptions, fn?: SuiteFn): Promise; + function describe(fn?: SuiteFn): Promise; + namespace describe { + /** + * Shorthand for skipping a suite, same as `describe([name], { skip: true }[, fn])`. + */ + function skip(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function skip(name?: string, fn?: SuiteFn): Promise; + function skip(options?: TestOptions, fn?: SuiteFn): Promise; + function skip(fn?: SuiteFn): Promise; + /** + * Shorthand for marking a suite as `TODO`, same as `describe([name], { todo: true }[, fn])`. + */ + function todo(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function todo(name?: string, fn?: SuiteFn): Promise; + function todo(options?: TestOptions, fn?: SuiteFn): Promise; + function todo(fn?: SuiteFn): Promise; + /** + * Shorthand for marking a suite as `only`, same as `describe([name], { only: true }[, fn])`. + * @since v18.15.0 + */ + function only(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function only(name?: string, fn?: SuiteFn): Promise; + function only(options?: TestOptions, fn?: SuiteFn): Promise; + function only(fn?: SuiteFn): Promise; + } + + /** + * @since v18.6.0 + * @param name The name of the test, which is displayed when reporting test results. + * Default: The `name` property of fn, or `''` if `fn` does not have a name. + * @param options Configuration options for the test + * @param fn The function under test. If the test uses callbacks, the callback function is + * passed as the second argument. Default: A no-op function. + */ + function it(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function it(name?: string, fn?: TestFn): Promise; + function it(options?: TestOptions, fn?: TestFn): Promise; + function it(fn?: TestFn): Promise; + namespace it { + /** + * Shorthand for skipping a test, same as `it([name], { skip: true }[, fn])`. + */ + function skip(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function skip(name?: string, fn?: TestFn): Promise; + function skip(options?: TestOptions, fn?: TestFn): Promise; + function skip(fn?: TestFn): Promise; + /** + * Shorthand for marking a test as `TODO`, same as `it([name], { todo: true }[, fn])`. + */ + function todo(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function todo(name?: string, fn?: TestFn): Promise; + function todo(options?: TestOptions, fn?: TestFn): Promise; + function todo(fn?: TestFn): Promise; + /** + * Shorthand for marking a test as `only`, same as `it([name], { only: true }[, fn])`. + * @since v18.15.0 + */ + function only(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function only(name?: string, fn?: TestFn): Promise; + function only(options?: TestOptions, fn?: TestFn): Promise; + function only(fn?: TestFn): Promise; + } + /** + * Shorthand for skipping a test, same as `test([name], { skip: true }[, fn])`. + * @since v18.17.0 + */ + function skip(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function skip(name?: string, fn?: TestFn): Promise; + function skip(options?: TestOptions, fn?: TestFn): Promise; + function skip(fn?: TestFn): Promise; + /** + * Shorthand for marking a test as `TODO`, same as `test([name], { todo: true }[, fn])`. + * @since v18.17.0 + */ + function todo(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function todo(name?: string, fn?: TestFn): Promise; + function todo(options?: TestOptions, fn?: TestFn): Promise; + function todo(fn?: TestFn): Promise; + /** + * Shorthand for marking a test as `only`, same as `test([name], { only: true }[, fn])`. + * @since v18.17.0 + */ + function only(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function only(name?: string, fn?: TestFn): Promise; + function only(options?: TestOptions, fn?: TestFn): Promise; + function only(fn?: TestFn): Promise; + /** + * The type of a function under test. The first argument to this function is a + * {@link TestContext} object. If the test uses callbacks, the callback function is passed as + * the second argument. + */ + type TestFn = (t: TestContext, done: (result?: any) => void) => any; + /** + * The type of a function under Suite. + */ + type SuiteFn = (s: SuiteContext) => void | Promise; + interface TestShard { + /** + * A positive integer between 1 and `` that specifies the index of the shard to run. + */ + index: number; + /** + * A positive integer that specifies the total number of shards to split the test files to. + */ + total: number; + } + interface RunOptions { + /** + * If a number is provided, then that many files would run in parallel. + * If truthy, it would run (number of cpu cores - 1) files in parallel. + * If falsy, it would only run one file at a time. + * If unspecified, subtests inherit this value from their parent. + * @default true + */ + concurrency?: number | boolean | undefined; + /** + * An array containing the list of files to run. + * If unspecified, the test runner execution model will be used. + */ + files?: readonly string[] | undefined; + /** + * Allows aborting an in-progress test execution. + * @default undefined + */ + signal?: AbortSignal | undefined; + /** + * A number of milliseconds the test will fail after. + * If unspecified, subtests inherit this value from their parent. + * @default Infinity + */ + timeout?: number | undefined; + /** + * Sets inspector port of test child process. + * If a nullish value is provided, each process gets its own port, + * incremented from the primary's `process.debugPort`. + */ + inspectPort?: number | (() => number) | undefined; + /** + * That can be used to only run tests whose name matches the provided pattern. + * Test name patterns are interpreted as JavaScript regular expressions. + * For each test that is executed, any corresponding test hooks, such as `beforeEach()`, are also run. + */ + testNamePatterns?: string | RegExp | string[] | RegExp[]; + /** + * If truthy, the test context will only run tests that have the `only` option set + * @since v18.19.0 + */ + only?: boolean; + /** + * A function that accepts the TestsStream instance and can be used to setup listeners before any tests are run. + */ + setup?: (root: Test) => void | Promise; + /** + * Whether to run in watch mode or not. + * @default false + */ + watch?: boolean | undefined; + /** + * Running tests in a specific shard. + * @since v18.19.0 + * @default undefined + */ + shard?: TestShard | undefined; + } + class Test extends AsyncResource { + concurrency: number; + nesting: number; + only: boolean; + reporter: TestsStream; + runOnlySubtests: boolean; + testNumber: number; + timeout: number | null; + } + + /** + * A successful call of the `run()` method will return a new `TestsStream` object, + * streaming a series of events representing the execution of the tests. + * `TestsStream` will emit events in the order of the tests' definitions. + * @since v18.9.0 + */ + interface TestsStream extends NodeJS.ReadableStream { + addListener(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this; + addListener(event: "test:fail", listener: (data: TestFail) => void): this; + addListener(event: "test:pass", listener: (data: TestPass) => void): this; + addListener(event: "test:plan", listener: (data: TestPlan) => void): this; + addListener(event: "test:start", listener: (data: TestStart) => void): this; + addListener(event: "test:stderr", listener: (data: TestStderr) => void): this; + addListener(event: "test:stdout", listener: (data: TestStdout) => void): this; + addListener(event: string, listener: (...args: any[]) => void): this; + emit(event: "test:diagnostic", data: DiagnosticData): boolean; + emit(event: "test:fail", data: TestFail): boolean; + emit(event: "test:pass", data: TestPass): boolean; + emit(event: "test:plan", data: TestPlan): boolean; + emit(event: "test:start", data: TestStart): boolean; + emit(event: "test:stderr", data: TestStderr): boolean; + emit(event: "test:stdout", data: TestStdout): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this; + on(event: "test:fail", listener: (data: TestFail) => void): this; + on(event: "test:pass", listener: (data: TestPass) => void): this; + on(event: "test:plan", listener: (data: TestPlan) => void): this; + on(event: "test:start", listener: (data: TestStart) => void): this; + on(event: "test:stderr", listener: (data: TestStderr) => void): this; + on(event: "test:stdout", listener: (data: TestStdout) => void): this; + on(event: string, listener: (...args: any[]) => void): this; + once(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this; + once(event: "test:fail", listener: (data: TestFail) => void): this; + once(event: "test:pass", listener: (data: TestPass) => void): this; + once(event: "test:plan", listener: (data: TestPlan) => void): this; + once(event: "test:start", listener: (data: TestStart) => void): this; + once(event: "test:stderr", listener: (data: TestStderr) => void): this; + once(event: "test:stdout", listener: (data: TestStdout) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this; + prependListener(event: "test:fail", listener: (data: TestFail) => void): this; + prependListener(event: "test:pass", listener: (data: TestPass) => void): this; + prependListener(event: "test:plan", listener: (data: TestPlan) => void): this; + prependListener(event: "test:start", listener: (data: TestStart) => void): this; + prependListener(event: "test:stderr", listener: (data: TestStderr) => void): this; + prependListener(event: "test:stdout", listener: (data: TestStdout) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this; + prependOnceListener(event: "test:fail", listener: (data: TestFail) => void): this; + prependOnceListener(event: "test:pass", listener: (data: TestPass) => void): this; + prependOnceListener(event: "test:plan", listener: (data: TestPlan) => void): this; + prependOnceListener(event: "test:start", listener: (data: TestStart) => void): this; + prependOnceListener(event: "test:stderr", listener: (data: TestStderr) => void): this; + prependOnceListener(event: "test:stdout", listener: (data: TestStdout) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + } + + /** + * An instance of `TestContext` is passed to each test function in order to interact with the + * test runner. However, the `TestContext` constructor is not exposed as part of the API. + * @since v18.0.0 + */ + interface TestContext { + /** + * This function is used to create a hook running before subtest of the current test. + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as + * the second argument. Default: A no-op function. + * @param options Configuration options for the hook. + * @since v18.17.0 + */ + before: typeof before; + + /** + * This function is used to create a hook running before each subtest of the current test. + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as + * the second argument. Default: A no-op function. + * @param options Configuration options for the hook. + * @since v18.8.0 + */ + beforeEach: typeof beforeEach; + + /** + * This function is used to create a hook that runs after the current test finishes. + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as + * the second argument. Default: A no-op function. + * @param options Configuration options for the hook. + * @since v18.13.0 + */ + after: typeof after; + + /** + * This function is used to create a hook running after each subtest of the current test. + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as + * the second argument. Default: A no-op function. + * @param options Configuration options for the hook. + * @since v18.8.0 + */ + afterEach: typeof afterEach; + + /** + * This function is used to write diagnostics to the output. Any diagnostic information is + * included at the end of the test's results. This function does not return a value. + * @param message Message to be reported. + * @since v18.0.0 + */ + diagnostic(message: string): void; + + /** + * The name of the test. + * @since v18.8.0 + */ + readonly name: string; + + /** + * If `shouldRunOnlyTests` is truthy, the test context will only run tests that have the `only` + * option set. Otherwise, all tests are run. If Node.js was not started with the `--test-only` + * command-line option, this function is a no-op. + * @param shouldRunOnlyTests Whether or not to run `only` tests. + * @since v18.0.0 + */ + runOnly(shouldRunOnlyTests: boolean): void; + + /** + * Can be used to abort test subtasks when the test has been aborted. + * @since v18.7.0 + */ + readonly signal: AbortSignal; + + /** + * This function causes the test's output to indicate the test as skipped. If `message` is + * provided, it is included in the output. Calling `skip()` does not terminate execution of + * the test function. This function does not return a value. + * @param message Optional skip message. + * @since v18.0.0 + */ + skip(message?: string): void; + + /** + * This function adds a `TODO` directive to the test's output. If `message` is provided, it is + * included in the output. Calling `todo()` does not terminate execution of the test + * function. This function does not return a value. + * @param message Optional `TODO` message. + * @since v18.0.0 + */ + todo(message?: string): void; + + /** + * This function is used to create subtests under the current test. This function behaves in + * the same fashion as the top level {@link test} function. + * @since v18.0.0 + * @param name The name of the test, which is displayed when reporting test results. + * Default: The `name` property of fn, or `''` if `fn` does not have a name. + * @param options Configuration options for the test + * @param fn The function under test. This first argument to this function is a + * {@link TestContext} object. If the test uses callbacks, the callback function is + * passed as the second argument. Default: A no-op function. + * @returns A {@link Promise} resolved with `undefined` once the test completes. + */ + test: typeof test; + /** + * Each test provides its own MockTracker instance. + */ + readonly mock: MockTracker; + } + + /** + * An instance of `SuiteContext` is passed to each suite function in order to + * interact with the test runner. However, the `SuiteContext` constructor is not + * exposed as part of the API. + * @since v18.7.0, v16.17.0 + */ + class SuiteContext { + /** + * The name of the suite. + * @since v18.8.0, v16.18.0 + */ + readonly name: string; + /** + * Can be used to abort test subtasks when the test has been aborted. + * @since v18.7.0, v16.17.0 + */ + readonly signal: AbortSignal; + } + interface TestOptions { + /** + * If a number is provided, then that many tests would run in parallel. + * If truthy, it would run (number of cpu cores - 1) tests in parallel. + * For subtests, it will be `Infinity` tests in parallel. + * If falsy, it would only run one test at a time. + * If unspecified, subtests inherit this value from their parent. + * @default false + */ + concurrency?: number | boolean | undefined; + + /** + * If truthy, and the test context is configured to run `only` tests, then this test will be + * run. Otherwise, the test is skipped. + * @default false + */ + only?: boolean | undefined; + + /** + * Allows aborting an in-progress test. + * @since v18.8.0 + */ + signal?: AbortSignal | undefined; + + /** + * If truthy, the test is skipped. If a string is provided, that string is displayed in the + * test results as the reason for skipping the test. + * @default false + */ + skip?: boolean | string | undefined; + + /** + * A number of milliseconds the test will fail after. If unspecified, subtests inherit this + * value from their parent. + * @default Infinity + * @since v18.7.0 + */ + timeout?: number | undefined; + + /** + * If truthy, the test marked as `TODO`. If a string is provided, that string is displayed in + * the test results as the reason why the test is `TODO`. + * @default false + */ + todo?: boolean | string | undefined; + } + + /** + * This function is used to create a hook running before running a suite. + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as + * the second argument. Default: A no-op function. + * @param options Configuration options for the hook. + * @since v18.8.0 + */ + function before(fn?: HookFn, options?: HookOptions): void; + + /** + * This function is used to create a hook running after running a suite. + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as + * the second argument. Default: A no-op function. + * @param options Configuration options for the hook. + * @since v18.8.0 + */ + function after(fn?: HookFn, options?: HookOptions): void; + + /** + * This function is used to create a hook running before each subtest of the current suite. + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as + * the second argument. Default: A no-op function. + * @param options Configuration options for the hook. + * @since v18.8.0 + */ + function beforeEach(fn?: HookFn, options?: HookOptions): void; + + /** + * This function is used to create a hook running after each subtest of the current test. + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as + * the second argument. Default: A no-op function. + * @param options Configuration options for the hook. + * @since v18.8.0 + */ + function afterEach(fn?: HookFn, options?: HookOptions): void; + + /** + * The hook function. If the hook uses callbacks, the callback function is passed as the + * second argument. + */ + type HookFn = (s: SuiteContext, done: (result?: any) => void) => any; + + /** + * Configuration options for hooks. + * @since v18.8.0 + */ + interface HookOptions { + /** + * Allows aborting an in-progress hook. + */ + signal?: AbortSignal | undefined; + + /** + * A number of milliseconds the hook will fail after. If unspecified, subtests inherit this + * value from their parent. + * @default Infinity + */ + timeout?: number | undefined; + } + + interface MockFunctionOptions { + /** + * The number of times that the mock will use the behavior of `implementation`. + * Once the mock function has been called `times` times, + * it will automatically restore the behavior of `original`. + * This value must be an integer greater than zero. + * @default Infinity + */ + times?: number | undefined; + } + + interface MockMethodOptions extends MockFunctionOptions { + /** + * If `true`, `object[methodName]` is treated as a getter. + * This option cannot be used with the `setter` option. + */ + getter?: boolean | undefined; + + /** + * If `true`, `object[methodName]` is treated as a setter. + * This option cannot be used with the `getter` option. + */ + setter?: boolean | undefined; + } + + type Mock = F & { + mock: MockFunctionContext; + }; + + type NoOpFunction = (...args: any[]) => undefined; + + type FunctionPropertyNames = { + [K in keyof T]: T[K] extends Function ? K : never; + }[keyof T]; + + interface MockTracker { + /** + * This function is used to create a mock function. + * @param original An optional function to create a mock on. + * @param implementation An optional function used as the mock implementation for `original`. + * This is useful for creating mocks that exhibit one behavior for a specified number of calls and then restore the behavior of `original`. + * @param options Optional configuration options for the mock function. + */ + fn(original?: F, options?: MockFunctionOptions): Mock; + fn( + original?: F, + implementation?: Implementation, + options?: MockFunctionOptions, + ): Mock; + /** + * This function is used to create a mock on an existing object method. + * @param object The object whose method is being mocked. + * @param methodName The identifier of the method on `object` to mock. If `object[methodName]` is not a function, an error is thrown. + * @param implementation An optional function used as the mock implementation for `object[methodName]`. + * @param options Optional configuration options for the mock method. + */ + method< + MockedObject extends object, + MethodName extends FunctionPropertyNames, + >( + object: MockedObject, + methodName: MethodName, + options?: MockFunctionOptions, + ): MockedObject[MethodName] extends Function ? Mock + : never; + method< + MockedObject extends object, + MethodName extends FunctionPropertyNames, + Implementation extends Function, + >( + object: MockedObject, + methodName: MethodName, + implementation: Implementation, + options?: MockFunctionOptions, + ): MockedObject[MethodName] extends Function ? Mock + : never; + method( + object: MockedObject, + methodName: keyof MockedObject, + options: MockMethodOptions, + ): Mock; + method( + object: MockedObject, + methodName: keyof MockedObject, + implementation: Function, + options: MockMethodOptions, + ): Mock; + /** + * This function is syntax sugar for {@link MockTracker.method} with `options.getter` set to `true`. + */ + getter< + MockedObject extends object, + MethodName extends keyof MockedObject, + >( + object: MockedObject, + methodName: MethodName, + options?: MockFunctionOptions, + ): Mock<() => MockedObject[MethodName]>; + getter< + MockedObject extends object, + MethodName extends keyof MockedObject, + Implementation extends Function, + >( + object: MockedObject, + methodName: MethodName, + implementation?: Implementation, + options?: MockFunctionOptions, + ): Mock<(() => MockedObject[MethodName]) | Implementation>; + /** + * This function is syntax sugar for {@link MockTracker.method} with `options.setter` set to `true`. + */ + setter< + MockedObject extends object, + MethodName extends keyof MockedObject, + >( + object: MockedObject, + methodName: MethodName, + options?: MockFunctionOptions, + ): Mock<(value: MockedObject[MethodName]) => void>; + setter< + MockedObject extends object, + MethodName extends keyof MockedObject, + Implementation extends Function, + >( + object: MockedObject, + methodName: MethodName, + implementation?: Implementation, + options?: MockFunctionOptions, + ): Mock<((value: MockedObject[MethodName]) => void) | Implementation>; + /** + * This function restores the default behavior of all mocks that were previously created by this `MockTracker` + * and disassociates the mocks from the `MockTracker` instance. Once disassociated, the mocks can still be used, + * but the `MockTracker` instance can no longer be used to reset their behavior or otherwise interact with them. + * + * After each test completes, this function is called on the test context's `MockTracker`. + * If the global `MockTracker` is used extensively, calling this function manually is recommended. + */ + reset(): void; + /** + * This function restores the default behavior of all mocks that were previously created by this `MockTracker`. + * Unlike `mock.reset()`, `mock.restoreAll()` does not disassociate the mocks from the `MockTracker` instance. + */ + restoreAll(): void; + timers: MockTimers; + } + + const mock: MockTracker; + + interface MockFunctionCall< + F extends Function, + ReturnType = F extends (...args: any) => infer T ? T + : F extends abstract new(...args: any) => infer T ? T + : unknown, + Args = F extends (...args: infer Y) => any ? Y + : F extends abstract new(...args: infer Y) => any ? Y + : unknown[], + > { + /** + * An array of the arguments passed to the mock function. + */ + arguments: Args; + /** + * If the mocked function threw then this property contains the thrown value. + */ + error: unknown | undefined; + /** + * The value returned by the mocked function. + * + * If the mocked function threw, it will be `undefined`. + */ + result: ReturnType | undefined; + /** + * An `Error` object whose stack can be used to determine the callsite of the mocked function invocation. + */ + stack: Error; + /** + * If the mocked function is a constructor, this field contains the class being constructed. + * Otherwise this will be `undefined`. + */ + target: F extends abstract new(...args: any) => any ? F : undefined; + /** + * The mocked function's `this` value. + */ + this: unknown; + } + + interface MockFunctionContext { + /** + * A getter that returns a copy of the internal array used to track calls to the mock. + */ + readonly calls: Array>; + + /** + * This function returns the number of times that this mock has been invoked. + * This function is more efficient than checking `ctx.calls.length` + * because `ctx.calls` is a getter that creates a copy of the internal call tracking array. + */ + callCount(): number; + + /** + * This function is used to change the behavior of an existing mock. + * @param implementation The function to be used as the mock's new implementation. + */ + mockImplementation(implementation: Function): void; + + /** + * This function is used to change the behavior of an existing mock for a single invocation. + * Once invocation `onCall` has occurred, the mock will revert to whatever behavior + * it would have used had `mockImplementationOnce()` not been called. + * @param implementation The function to be used as the mock's implementation for the invocation number specified by `onCall`. + * @param onCall The invocation number that will use `implementation`. + * If the specified invocation has already occurred then an exception is thrown. + */ + mockImplementationOnce(implementation: Function, onCall?: number): void; + + /** + * Resets the call history of the mock function. + */ + resetCalls(): void; + + /** + * Resets the implementation of the mock function to its original behavior. + * The mock can still be used after calling this function. + */ + restore(): void; + } + type Timer = "setInterval" | "clearInterval" | "setTimeout" | "clearTimeout"; + /** + * Mocking timers is a technique commonly used in software testing to simulate and + * control the behavior of timers, such as `setInterval` and `setTimeout`, + * without actually waiting for the specified time intervals. + * + * The `MockTracker` provides a top-level `timers` export + * which is a `MockTimers` instance. + * @since v18.19.0 + * @experimental + */ + class MockTimers { + /** + * Enables timer mocking for the specified timers. + * + * **Note:** When you enable mocking for a specific timer, its associated + * clear function will also be implicitly mocked. + * + * Example usage: + * + * ```js + * import { mock } from 'node:test'; + * mock.timers.enable(['setInterval']); + * ``` + * + * The above example enables mocking for the `setInterval` timer and + * implicitly mocks the `clearInterval` function. Only the `setInterval`and `clearInterval` functions from `node:timers`,`node:timers/promises`, and`globalThis` will be mocked. + * + * Alternatively, if you call `mock.timers.enable()` without any parameters: + * + * All timers (`'setInterval'`, `'clearInterval'`, `'setTimeout'`, and `'clearTimeout'`) + * will be mocked. The `setInterval`, `clearInterval`, `setTimeout`, and `clearTimeout`functions from `node:timers`, `node:timers/promises`, + * and `globalThis` will be mocked. + * @since v18.19.0 + */ + enable(timers?: Timer[]): void; + /** + * This function restores the default behavior of all mocks that were previously + * created by this `MockTimers` instance and disassociates the mocks + * from the `MockTracker` instance. + * + * **Note:** After each test completes, this function is called on + * the test context's `MockTracker`. + * + * ```js + * import { mock } from 'node:test'; + * mock.timers.reset(); + * ``` + * @since v18.19.0 + */ + reset(): void; + /** + * Advances time for all mocked timers. + * + * **Note:** This diverges from how `setTimeout` in Node.js behaves and accepts + * only positive numbers. In Node.js, `setTimeout` with negative numbers is + * only supported for web compatibility reasons. + * + * The following example mocks a `setTimeout` function and + * by using `.tick` advances in + * time triggering all pending timers. + * + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * + * test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => { + * const fn = context.mock.fn(); + * + * context.mock.timers.enable(['setTimeout']); + * + * setTimeout(fn, 9999); + * + * assert.strictEqual(fn.mock.callCount(), 0); + * + * // Advance in time + * context.mock.timers.tick(9999); + * + * assert.strictEqual(fn.mock.callCount(), 1); + * }); + * ``` + * + * Alternativelly, the `.tick` function can be called many times + * + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * + * test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => { + * const fn = context.mock.fn(); + * context.mock.timers.enable(['setTimeout']); + * const nineSecs = 9000; + * setTimeout(fn, nineSecs); + * + * const twoSeconds = 3000; + * context.mock.timers.tick(twoSeconds); + * context.mock.timers.tick(twoSeconds); + * context.mock.timers.tick(twoSeconds); + * + * assert.strictEqual(fn.mock.callCount(), 1); + * }); + * ``` + * @since v18.19.0 + */ + tick(milliseconds: number): void; + /** + * Triggers all pending mocked timers immediately. + * + * The example below triggers all pending timers immediately, + * causing them to execute without any delay. + * + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * + * test('runAll functions following the given order', (context) => { + * context.mock.timers.enable(['setTimeout']); + * const results = []; + * setTimeout(() => results.push(1), 9999); + * + * // Notice that if both timers have the same timeout, + * // the order of execution is guaranteed + * setTimeout(() => results.push(3), 8888); + * setTimeout(() => results.push(2), 8888); + * + * assert.deepStrictEqual(results, []); + * + * context.mock.timers.runAll(); + * + * assert.deepStrictEqual(results, [3, 2, 1]); + * }); + * ``` + * + * **Note:** The `runAll()` function is specifically designed for + * triggering timers in the context of timer mocking. + * It does not have any effect on real-time system + * clocks or actual timers outside of the mocking environment. + * @since v18.19.0 + */ + runAll(): void; + /** + * Calls {@link MockTimers.reset()}. + */ + [Symbol.dispose](): void; + } + + export { after, afterEach, before, beforeEach, describe, it, mock, run, test, test as default }; +} + +interface TestLocationInfo { + /** + * The column number where the test is defined, or + * `undefined` if the test was run through the REPL. + */ + column?: number; + /** + * The path of the test file, `undefined` if test is not ran through a file. + */ + file?: string; + /** + * The line number where the test is defined, or + * `undefined` if the test was run through the REPL. + */ + line?: number; +} +interface DiagnosticData extends TestLocationInfo { + /** + * The diagnostic message. + */ + message: string; + /** + * The nesting level of the test. + */ + nesting: number; +} +interface TestFail extends TestLocationInfo { + /** + * Additional execution metadata. + */ + details: { + /** + * The duration of the test in milliseconds. + */ + duration_ms: number; + /** + * The error thrown by the test. + */ + error: Error; + /** + * The type of the test, used to denote whether this is a suite. + * @since 18.17.0 + */ + type?: "suite"; + }; + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The ordinal number of the test. + */ + testNumber: number; + /** + * Present if `context.todo` is called. + */ + todo?: string | boolean; + /** + * Present if `context.skip` is called. + */ + skip?: string | boolean; +} +interface TestPass extends TestLocationInfo { + /** + * Additional execution metadata. + */ + details: { + /** + * The duration of the test in milliseconds. + */ + duration_ms: number; + /** + * The type of the test, used to denote whether this is a suite. + * @since 18.17.0 + */ + type?: "suite"; + }; + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The ordinal number of the test. + */ + testNumber: number; + /** + * Present if `context.todo` is called. + */ + todo?: string | boolean; + /** + * Present if `context.skip` is called. + */ + skip?: string | boolean; +} +interface TestPlan extends TestLocationInfo { + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The number of subtests that have ran. + */ + count: number; +} +interface TestStart extends TestLocationInfo { + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; +} +interface TestStderr extends TestLocationInfo { + /** + * The message written to `stderr` + */ + message: string; +} +interface TestStdout extends TestLocationInfo { + /** + * The message written to `stdout` + */ + message: string; +} +interface TestEnqueue extends TestLocationInfo { + /** + * The test name + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; +} +interface TestDequeue extends TestLocationInfo { + /** + * The test name + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; +} + +/** + * The `node:test/reporters` module exposes the builtin-reporters for `node:test`. + * To access it: + * + * ```js + * import test from 'node:test/reporters'; + * ``` + * + * This module is only available under the `node:` scheme. The following will not + * work: + * + * ```js + * import test from 'test/reporters'; + * ``` + * @since v18.17.0 + * @see [source](https://github.com/nodejs/node/blob/v18.17.0/lib/test/reporters.js) + */ +declare module "node:test/reporters" { + import { Transform } from "node:stream"; + + type TestEvent = + | { type: "test:diagnostic"; data: DiagnosticData } + | { type: "test:fail"; data: TestFail } + | { type: "test:pass"; data: TestPass } + | { type: "test:plan"; data: TestPlan } + | { type: "test:start"; data: TestStart } + | { type: "test:stderr"; data: TestStderr } + | { type: "test:stdout"; data: TestStdout } + | { type: "test:enqueue"; data: TestEnqueue } + | { type: "test:dequeue"; data: TestDequeue } + | { type: "test:watch:drained" }; + type TestEventGenerator = AsyncGenerator; + + /** + * The `dot` reporter outputs the test results in a compact format, + * where each passing test is represented by a `.`, + * and each failing test is represented by a `X`. + */ + function dot(source: TestEventGenerator): AsyncGenerator<"\n" | "." | "X", void>; + /** + * The `tap` reporter outputs the test results in the [TAP](https://testanything.org/) format. + */ + function tap(source: TestEventGenerator): AsyncGenerator; + /** + * The `spec` reporter outputs the test results in a human-readable format. + */ + class Spec extends Transform { + constructor(); + } + /** + * The `junit` reporter outputs test results in a jUnit XML format + */ + function junit(source: TestEventGenerator): AsyncGenerator; + export { dot, junit, Spec as spec, tap, TestEvent }; +} diff --git a/backend/node_modules/@types/node/timers.d.ts b/backend/node_modules/@types/node/timers.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0d1beedacf0500cdb57a840bdd964c898c866b5c --- /dev/null +++ b/backend/node_modules/@types/node/timers.d.ts @@ -0,0 +1,126 @@ +/** + * The `timer` module exposes a global API for scheduling functions to + * be called at some future period of time. Because the timer functions are + * globals, there is no need to call `require('timers')` to use the API. + * + * The timer functions within Node.js implement a similar API as the timers API + * provided by Web Browsers but use a different internal implementation that is + * built around the Node.js [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#setimmediate-vs-settimeout). + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/timers.js) + */ +declare module "timers" { + import { Abortable } from "node:events"; + import { + setImmediate as setImmediatePromise, + setInterval as setIntervalPromise, + setTimeout as setTimeoutPromise, + } from "node:timers/promises"; + interface TimerOptions extends Abortable { + /** + * Set to `false` to indicate that the scheduled `Timeout` + * should not require the Node.js event loop to remain active. + * @default true + */ + ref?: boolean | undefined; + } + let setTimeout: typeof global.setTimeout; + let clearTimeout: typeof global.clearTimeout; + let setInterval: typeof global.setInterval; + let clearInterval: typeof global.clearInterval; + let setImmediate: typeof global.setImmediate; + let clearImmediate: typeof global.clearImmediate; + global { + namespace NodeJS { + // compatibility with older typings + interface Timer extends RefCounted { + hasRef(): boolean; + refresh(): this; + [Symbol.toPrimitive](): number; + } + interface Immediate extends RefCounted { + /** + * If true, the `Immediate` object will keep the Node.js event loop active. + * @since v11.0.0 + */ + hasRef(): boolean; + _onImmediate: Function; // to distinguish it from the Timeout class + /** + * Cancels the immediate. This is similar to calling `clearImmediate()`. + * @since v18.18.0 + */ + [Symbol.dispose](): void; + } + interface Timeout extends Timer { + /** + * If true, the `Timeout` object will keep the Node.js event loop active. + * @since v11.0.0 + */ + hasRef(): boolean; + /** + * Sets the timer's start time to the current time, and reschedules the timer to + * call its callback at the previously specified duration adjusted to the current + * time. This is useful for refreshing a timer without allocating a new + * JavaScript object. + * + * Using this on a timer that has already called its callback will reactivate the + * timer. + * @since v10.2.0 + * @return a reference to `timeout` + */ + refresh(): this; + [Symbol.toPrimitive](): number; + /** + * Cancels the timeout. + * @since v18.18.0 + */ + [Symbol.dispose](): void; + } + } + /** + * Schedules execution of a one-time `callback` after `delay` milliseconds. The `callback` will likely not be invoked in precisely `delay` milliseconds. + * Node.js makes no guarantees about the exact timing of when callbacks will fire, nor of their ordering. The callback will be called as close as possible to the time specified. + * When `delay` is larger than `2147483647` or less than `1`, the `delay` will be set to `1`. Non-integer delays are truncated to an integer. + * If `callback` is not a function, a [TypeError](https://nodejs.org/api/errors.html#class-typeerror) will be thrown. + * @since v0.0.1 + */ + function setTimeout( + callback: (...args: TArgs) => void, + ms?: number, + ...args: TArgs + ): NodeJS.Timeout; + // util.promisify no rest args compability + // eslint-disable-next-line @typescript-eslint/no-invalid-void-type + function setTimeout(callback: (args: void) => void, ms?: number): NodeJS.Timeout; + namespace setTimeout { + const __promisify__: typeof setTimeoutPromise; + } + function clearTimeout(timeoutId: NodeJS.Timeout | string | number | undefined): void; + function setInterval( + callback: (...args: TArgs) => void, + ms?: number, + ...args: TArgs + ): NodeJS.Timeout; + // util.promisify no rest args compability + // eslint-disable-next-line @typescript-eslint/no-invalid-void-type + function setInterval(callback: (args: void) => void, ms?: number): NodeJS.Timeout; + namespace setInterval { + const __promisify__: typeof setIntervalPromise; + } + function clearInterval(intervalId: NodeJS.Timeout | string | number | undefined): void; + function setImmediate( + callback: (...args: TArgs) => void, + ...args: TArgs + ): NodeJS.Immediate; + // util.promisify no rest args compability + // eslint-disable-next-line @typescript-eslint/no-invalid-void-type + function setImmediate(callback: (args: void) => void): NodeJS.Immediate; + namespace setImmediate { + const __promisify__: typeof setImmediatePromise; + } + function clearImmediate(immediateId: NodeJS.Immediate | undefined): void; + function queueMicrotask(callback: () => void): void; + } +} +declare module "node:timers" { + export * from "timers"; +} diff --git a/backend/node_modules/@types/node/timers/promises.d.ts b/backend/node_modules/@types/node/timers/promises.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..abb5b425dda4f069b61a54331f9783e16e08c3c4 --- /dev/null +++ b/backend/node_modules/@types/node/timers/promises.d.ts @@ -0,0 +1,93 @@ +/** + * The `timers/promises` API provides an alternative set of timer functions + * that return `Promise` objects. The API is accessible via`require('timers/promises')`. + * + * ```js + * import { + * setTimeout, + * setImmediate, + * setInterval, + * } from 'timers/promises'; + * ``` + * @since v15.0.0 + */ +declare module "timers/promises" { + import { TimerOptions } from "node:timers"; + /** + * ```js + * import { + * setTimeout, + * } from 'timers/promises'; + * + * const res = await setTimeout(100, 'result'); + * + * console.log(res); // Prints 'result' + * ``` + * @since v15.0.0 + * @param [delay=1] The number of milliseconds to wait before fulfilling the promise. + * @param value A value with which the promise is fulfilled. + */ + function setTimeout(delay?: number, value?: T, options?: TimerOptions): Promise; + /** + * ```js + * import { + * setImmediate, + * } from 'timers/promises'; + * + * const res = await setImmediate('result'); + * + * console.log(res); // Prints 'result' + * ``` + * @since v15.0.0 + * @param value A value with which the promise is fulfilled. + */ + function setImmediate(value?: T, options?: TimerOptions): Promise; + /** + * Returns an async iterator that generates values in an interval of `delay` ms. + * + * ```js + * import { + * setInterval, + * } from 'timers/promises'; + * + * const interval = 100; + * for await (const startTime of setInterval(interval, Date.now())) { + * const now = Date.now(); + * console.log(now); + * if ((now - startTime) > 1000) + * break; + * } + * console.log(Date.now()); + * ``` + * @since v15.9.0 + */ + function setInterval(delay?: number, value?: T, options?: TimerOptions): AsyncIterable; + + interface Scheduler { + /** + * ```js + * import { scheduler } from 'node:timers/promises'; + * + * await scheduler.wait(1000); // Wait one second before continuing + * ``` + * An experimental API defined by the Scheduling APIs draft specification being developed as a standard Web Platform API. + * Calling timersPromises.scheduler.wait(delay, options) is roughly equivalent to calling timersPromises.setTimeout(delay, undefined, options) except that the ref option is not supported. + * @since v16.14.0 + * @experimental + * @param [delay=1] The number of milliseconds to wait before fulfilling the promise. + */ + wait: (delay?: number, options?: TimerOptions) => Promise; + /** + * An experimental API defined by the Scheduling APIs draft specification being developed as a standard Web Platform API. + * Calling timersPromises.scheduler.yield() is equivalent to calling timersPromises.setImmediate() with no arguments. + * @since v16.14.0 + * @experimental + */ + yield: () => Promise; + } + + const scheduler: Scheduler; +} +declare module "node:timers/promises" { + export * from "timers/promises"; +} diff --git a/backend/node_modules/@types/node/tls.d.ts b/backend/node_modules/@types/node/tls.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f6b872ce2afda67598e04be19fc4c9d096b31f1d --- /dev/null +++ b/backend/node_modules/@types/node/tls.d.ts @@ -0,0 +1,1203 @@ +/** + * The `tls` module provides an implementation of the Transport Layer Security + * (TLS) and Secure Socket Layer (SSL) protocols that is built on top of OpenSSL. + * The module can be accessed using: + * + * ```js + * const tls = require('tls'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/tls.js) + */ +declare module "tls" { + import { X509Certificate } from "node:crypto"; + import * as net from "node:net"; + import * as stream from "stream"; + const CLIENT_RENEG_LIMIT: number; + const CLIENT_RENEG_WINDOW: number; + interface Certificate { + /** + * Country code. + */ + C: string; + /** + * Street. + */ + ST: string; + /** + * Locality. + */ + L: string; + /** + * Organization. + */ + O: string; + /** + * Organizational unit. + */ + OU: string; + /** + * Common name. + */ + CN: string; + } + interface PeerCertificate { + /** + * `true` if a Certificate Authority (CA), `false` otherwise. + * @since v18.13.0 + */ + ca: boolean; + /** + * The DER encoded X.509 certificate data. + */ + raw: Buffer; + /** + * The certificate subject. + */ + subject: Certificate; + /** + * The certificate issuer, described in the same terms as the `subject`. + */ + issuer: Certificate; + /** + * The date-time the certificate is valid from. + */ + valid_from: string; + /** + * The date-time the certificate is valid to. + */ + valid_to: string; + /** + * The certificate serial number, as a hex string. + */ + serialNumber: string; + /** + * The SHA-1 digest of the DER encoded certificate. + * It is returned as a `:` separated hexadecimal string. + */ + fingerprint: string; + /** + * The SHA-256 digest of the DER encoded certificate. + * It is returned as a `:` separated hexadecimal string. + */ + fingerprint256: string; + /** + * The SHA-512 digest of the DER encoded certificate. + * It is returned as a `:` separated hexadecimal string. + */ + fingerprint512: string; + /** + * The extended key usage, a set of OIDs. + */ + ext_key_usage?: string[]; + /** + * A string containing concatenated names for the subject, + * an alternative to the `subject` names. + */ + subjectaltname?: string; + /** + * An array describing the AuthorityInfoAccess, used with OCSP. + */ + infoAccess?: NodeJS.Dict; + /** + * For RSA keys: The RSA bit size. + * + * For EC keys: The key size in bits. + */ + bits?: number; + /** + * The RSA exponent, as a string in hexadecimal number notation. + */ + exponent?: string; + /** + * The RSA modulus, as a hexadecimal string. + */ + modulus?: string; + /** + * The public key. + */ + pubkey?: Buffer; + /** + * The ASN.1 name of the OID of the elliptic curve. + * Well-known curves are identified by an OID. + * While it is unusual, it is possible that the curve + * is identified by its mathematical properties, + * in which case it will not have an OID. + */ + asn1Curve?: string; + /** + * The NIST name for the elliptic curve,if it has one + * (not all well-known curves have been assigned names by NIST). + */ + nistCurve?: string; + } + interface DetailedPeerCertificate extends PeerCertificate { + /** + * The issuer certificate object. + * For self-signed certificates, this may be a circular reference. + */ + issuerCertificate: DetailedPeerCertificate; + } + interface CipherNameAndProtocol { + /** + * The cipher name. + */ + name: string; + /** + * SSL/TLS protocol version. + */ + version: string; + /** + * IETF name for the cipher suite. + */ + standardName: string; + } + interface EphemeralKeyInfo { + /** + * The supported types are 'DH' and 'ECDH'. + */ + type: string; + /** + * The name property is available only when type is 'ECDH'. + */ + name?: string | undefined; + /** + * The size of parameter of an ephemeral key exchange. + */ + size: number; + } + interface KeyObject { + /** + * Private keys in PEM format. + */ + pem: string | Buffer; + /** + * Optional passphrase. + */ + passphrase?: string | undefined; + } + interface PxfObject { + /** + * PFX or PKCS12 encoded private key and certificate chain. + */ + buf: string | Buffer; + /** + * Optional passphrase. + */ + passphrase?: string | undefined; + } + interface TLSSocketOptions extends SecureContextOptions, CommonConnectionOptions { + /** + * If true the TLS socket will be instantiated in server-mode. + * Defaults to false. + */ + isServer?: boolean | undefined; + /** + * An optional net.Server instance. + */ + server?: net.Server | undefined; + /** + * An optional Buffer instance containing a TLS session. + */ + session?: Buffer | undefined; + /** + * If true, specifies that the OCSP status request extension will be + * added to the client hello and an 'OCSPResponse' event will be + * emitted on the socket before establishing a secure communication + */ + requestOCSP?: boolean | undefined; + } + /** + * Performs transparent encryption of written data and all required TLS + * negotiation. + * + * Instances of `tls.TLSSocket` implement the duplex `Stream` interface. + * + * Methods that return TLS connection metadata (e.g.{@link TLSSocket.getPeerCertificate} will only return data while the + * connection is open. + * @since v0.11.4 + */ + class TLSSocket extends net.Socket { + /** + * Construct a new tls.TLSSocket object from an existing TCP socket. + */ + constructor(socket: net.Socket | stream.Duplex, options?: TLSSocketOptions); + /** + * This property is `true` if the peer certificate was signed by one of the CAs + * specified when creating the `tls.TLSSocket` instance, otherwise `false`. + * @since v0.11.4 + */ + authorized: boolean; + /** + * Returns the reason why the peer's certificate was not been verified. This + * property is set only when `tlsSocket.authorized === false`. + * @since v0.11.4 + */ + authorizationError: Error; + /** + * Always returns `true`. This may be used to distinguish TLS sockets from regular`net.Socket` instances. + * @since v0.11.4 + */ + encrypted: true; + /** + * String containing the selected ALPN protocol. + * Before a handshake has completed, this value is always null. + * When a handshake is completed but not ALPN protocol was selected, tlsSocket.alpnProtocol equals false. + */ + alpnProtocol: string | false | null; + /** + * Returns an object representing the local certificate. The returned object has + * some properties corresponding to the fields of the certificate. + * + * See {@link TLSSocket.getPeerCertificate} for an example of the certificate + * structure. + * + * If there is no local certificate, an empty object will be returned. If the + * socket has been destroyed, `null` will be returned. + * @since v11.2.0 + */ + getCertificate(): PeerCertificate | object | null; + /** + * Returns an object containing information on the negotiated cipher suite. + * + * For example: + * + * ```json + * { + * "name": "AES128-SHA256", + * "standardName": "TLS_RSA_WITH_AES_128_CBC_SHA256", + * "version": "TLSv1.2" + * } + * ``` + * + * See [SSL\_CIPHER\_get\_name](https://www.openssl.org/docs/man1.1.1/man3/SSL_CIPHER_get_name.html) for more information. + * @since v0.11.4 + */ + getCipher(): CipherNameAndProtocol; + /** + * Returns an object representing the type, name, and size of parameter of + * an ephemeral key exchange in `perfect forward secrecy` on a client + * connection. It returns an empty object when the key exchange is not + * ephemeral. As this is only supported on a client socket; `null` is returned + * if called on a server socket. The supported types are `'DH'` and `'ECDH'`. The`name` property is available only when type is `'ECDH'`. + * + * For example: `{ type: 'ECDH', name: 'prime256v1', size: 256 }`. + * @since v5.0.0 + */ + getEphemeralKeyInfo(): EphemeralKeyInfo | object | null; + /** + * As the `Finished` messages are message digests of the complete handshake + * (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can + * be used for external authentication procedures when the authentication + * provided by SSL/TLS is not desired or is not enough. + * + * Corresponds to the `SSL_get_finished` routine in OpenSSL and may be used + * to implement the `tls-unique` channel binding from [RFC 5929](https://tools.ietf.org/html/rfc5929). + * @since v9.9.0 + * @return The latest `Finished` message that has been sent to the socket as part of a SSL/TLS handshake, or `undefined` if no `Finished` message has been sent yet. + */ + getFinished(): Buffer | undefined; + /** + * Returns an object representing the peer's certificate. If the peer does not + * provide a certificate, an empty object will be returned. If the socket has been + * destroyed, `null` will be returned. + * + * If the full certificate chain was requested, each certificate will include an`issuerCertificate` property containing an object representing its issuer's + * certificate. + * @since v0.11.4 + * @param detailed Include the full certificate chain if `true`, otherwise include just the peer's certificate. + * @return A certificate object. + */ + getPeerCertificate(detailed: true): DetailedPeerCertificate; + getPeerCertificate(detailed?: false): PeerCertificate; + getPeerCertificate(detailed?: boolean): PeerCertificate | DetailedPeerCertificate; + /** + * As the `Finished` messages are message digests of the complete handshake + * (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can + * be used for external authentication procedures when the authentication + * provided by SSL/TLS is not desired or is not enough. + * + * Corresponds to the `SSL_get_peer_finished` routine in OpenSSL and may be used + * to implement the `tls-unique` channel binding from [RFC 5929](https://tools.ietf.org/html/rfc5929). + * @since v9.9.0 + * @return The latest `Finished` message that is expected or has actually been received from the socket as part of a SSL/TLS handshake, or `undefined` if there is no `Finished` message so + * far. + */ + getPeerFinished(): Buffer | undefined; + /** + * Returns a string containing the negotiated SSL/TLS protocol version of the + * current connection. The value `'unknown'` will be returned for connected + * sockets that have not completed the handshaking process. The value `null` will + * be returned for server sockets or disconnected client sockets. + * + * Protocol versions are: + * + * * `'SSLv3'` + * * `'TLSv1'` + * * `'TLSv1.1'` + * * `'TLSv1.2'` + * * `'TLSv1.3'` + * + * See the OpenSSL [`SSL_get_version`](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_version.html) documentation for more information. + * @since v5.7.0 + */ + getProtocol(): string | null; + /** + * Returns the TLS session data or `undefined` if no session was + * negotiated. On the client, the data can be provided to the `session` option of {@link connect} to resume the connection. On the server, it may be useful + * for debugging. + * + * See `Session Resumption` for more information. + * + * Note: `getSession()` works only for TLSv1.2 and below. For TLSv1.3, applications + * must use the `'session'` event (it also works for TLSv1.2 and below). + * @since v0.11.4 + */ + getSession(): Buffer | undefined; + /** + * See [SSL\_get\_shared\_sigalgs](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_shared_sigalgs.html) for more information. + * @since v12.11.0 + * @return List of signature algorithms shared between the server and the client in the order of decreasing preference. + */ + getSharedSigalgs(): string[]; + /** + * For a client, returns the TLS session ticket if one is available, or`undefined`. For a server, always returns `undefined`. + * + * It may be useful for debugging. + * + * See `Session Resumption` for more information. + * @since v0.11.4 + */ + getTLSTicket(): Buffer | undefined; + /** + * See `Session Resumption` for more information. + * @since v0.5.6 + * @return `true` if the session was reused, `false` otherwise. + */ + isSessionReused(): boolean; + /** + * The `tlsSocket.renegotiate()` method initiates a TLS renegotiation process. + * Upon completion, the `callback` function will be passed a single argument + * that is either an `Error` (if the request failed) or `null`. + * + * This method can be used to request a peer's certificate after the secure + * connection has been established. + * + * When running as the server, the socket will be destroyed with an error after`handshakeTimeout` timeout. + * + * For TLSv1.3, renegotiation cannot be initiated, it is not supported by the + * protocol. + * @since v0.11.8 + * @param callback If `renegotiate()` returned `true`, callback is attached once to the `'secure'` event. If `renegotiate()` returned `false`, `callback` will be called in the next tick with + * an error, unless the `tlsSocket` has been destroyed, in which case `callback` will not be called at all. + * @return `true` if renegotiation was initiated, `false` otherwise. + */ + renegotiate( + options: { + rejectUnauthorized?: boolean | undefined; + requestCert?: boolean | undefined; + }, + callback: (err: Error | null) => void, + ): undefined | boolean; + /** + * The `tlsSocket.setMaxSendFragment()` method sets the maximum TLS fragment size. + * Returns `true` if setting the limit succeeded; `false` otherwise. + * + * Smaller fragment sizes decrease the buffering latency on the client: larger + * fragments are buffered by the TLS layer until the entire fragment is received + * and its integrity is verified; large fragments can span multiple roundtrips + * and their processing can be delayed due to packet loss or reordering. However, + * smaller fragments add extra TLS framing bytes and CPU overhead, which may + * decrease overall server throughput. + * @since v0.11.11 + * @param [size=16384] The maximum TLS fragment size. The maximum value is `16384`. + */ + setMaxSendFragment(size: number): boolean; + /** + * Disables TLS renegotiation for this `TLSSocket` instance. Once called, attempts + * to renegotiate will trigger an `'error'` event on the `TLSSocket`. + * @since v8.4.0 + */ + disableRenegotiation(): void; + /** + * When enabled, TLS packet trace information is written to `stderr`. This can be + * used to debug TLS connection problems. + * + * The format of the output is identical to the output of`openssl s_client -trace` or `openssl s_server -trace`. While it is produced by + * OpenSSL's `SSL_trace()` function, the format is undocumented, can change + * without notice, and should not be relied on. + * @since v12.2.0 + */ + enableTrace(): void; + /** + * Returns the peer certificate as an `X509Certificate` object. + * + * If there is no peer certificate, or the socket has been destroyed,`undefined` will be returned. + * @since v15.9.0 + */ + getPeerX509Certificate(): X509Certificate | undefined; + /** + * Returns the local certificate as an `X509Certificate` object. + * + * If there is no local certificate, or the socket has been destroyed,`undefined` will be returned. + * @since v15.9.0 + */ + getX509Certificate(): X509Certificate | undefined; + /** + * Keying material is used for validations to prevent different kind of attacks in + * network protocols, for example in the specifications of IEEE 802.1X. + * + * Example + * + * ```js + * const keyingMaterial = tlsSocket.exportKeyingMaterial( + * 128, + * 'client finished'); + * + * /* + * Example return value of keyingMaterial: + * + * + * ``` + * + * See the OpenSSL [`SSL_export_keying_material`](https://www.openssl.org/docs/man1.1.1/man3/SSL_export_keying_material.html) documentation for more + * information. + * @since v13.10.0, v12.17.0 + * @param length number of bytes to retrieve from keying material + * @param label an application specific label, typically this will be a value from the [IANA Exporter Label + * Registry](https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#exporter-labels). + * @param context Optionally provide a context. + * @return requested bytes of the keying material + */ + exportKeyingMaterial(length: number, label: string, context: Buffer): Buffer; + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + addListener(event: "secureConnect", listener: () => void): this; + addListener(event: "session", listener: (session: Buffer) => void): this; + addListener(event: "keylog", listener: (line: Buffer) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "OCSPResponse", response: Buffer): boolean; + emit(event: "secureConnect"): boolean; + emit(event: "session", session: Buffer): boolean; + emit(event: "keylog", line: Buffer): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "OCSPResponse", listener: (response: Buffer) => void): this; + on(event: "secureConnect", listener: () => void): this; + on(event: "session", listener: (session: Buffer) => void): this; + on(event: "keylog", listener: (line: Buffer) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "OCSPResponse", listener: (response: Buffer) => void): this; + once(event: "secureConnect", listener: () => void): this; + once(event: "session", listener: (session: Buffer) => void): this; + once(event: "keylog", listener: (line: Buffer) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + prependListener(event: "secureConnect", listener: () => void): this; + prependListener(event: "session", listener: (session: Buffer) => void): this; + prependListener(event: "keylog", listener: (line: Buffer) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + prependOnceListener(event: "secureConnect", listener: () => void): this; + prependOnceListener(event: "session", listener: (session: Buffer) => void): this; + prependOnceListener(event: "keylog", listener: (line: Buffer) => void): this; + } + interface CommonConnectionOptions { + /** + * An optional TLS context object from tls.createSecureContext() + */ + secureContext?: SecureContext | undefined; + /** + * When enabled, TLS packet trace information is written to `stderr`. This can be + * used to debug TLS connection problems. + * @default false + */ + enableTrace?: boolean | undefined; + /** + * If true the server will request a certificate from clients that + * connect and attempt to verify that certificate. Defaults to + * false. + */ + requestCert?: boolean | undefined; + /** + * An array of strings or a Buffer naming possible ALPN protocols. + * (Protocols should be ordered by their priority.) + */ + ALPNProtocols?: string[] | Uint8Array[] | Uint8Array | undefined; + /** + * SNICallback(servername, cb) A function that will be + * called if the client supports SNI TLS extension. Two arguments + * will be passed when called: servername and cb. SNICallback should + * invoke cb(null, ctx), where ctx is a SecureContext instance. + * (tls.createSecureContext(...) can be used to get a proper + * SecureContext.) If SNICallback wasn't provided the default callback + * with high-level API will be used (see below). + */ + SNICallback?: ((servername: string, cb: (err: Error | null, ctx?: SecureContext) => void) => void) | undefined; + /** + * If true the server will reject any connection which is not + * authorized with the list of supplied CAs. This option only has an + * effect if requestCert is true. + * @default true + */ + rejectUnauthorized?: boolean | undefined; + } + interface TlsOptions extends SecureContextOptions, CommonConnectionOptions, net.ServerOpts { + /** + * Abort the connection if the SSL/TLS handshake does not finish in the + * specified number of milliseconds. A 'tlsClientError' is emitted on + * the tls.Server object whenever a handshake times out. Default: + * 120000 (120 seconds). + */ + handshakeTimeout?: number | undefined; + /** + * The number of seconds after which a TLS session created by the + * server will no longer be resumable. See Session Resumption for more + * information. Default: 300. + */ + sessionTimeout?: number | undefined; + /** + * 48-bytes of cryptographically strong pseudo-random data. + */ + ticketKeys?: Buffer | undefined; + /** + * @param socket + * @param identity identity parameter sent from the client. + * @return pre-shared key that must either be + * a buffer or `null` to stop the negotiation process. Returned PSK must be + * compatible with the selected cipher's digest. + * + * When negotiating TLS-PSK (pre-shared keys), this function is called + * with the identity provided by the client. + * If the return value is `null` the negotiation process will stop and an + * "unknown_psk_identity" alert message will be sent to the other party. + * If the server wishes to hide the fact that the PSK identity was not known, + * the callback must provide some random data as `psk` to make the connection + * fail with "decrypt_error" before negotiation is finished. + * PSK ciphers are disabled by default, and using TLS-PSK thus + * requires explicitly specifying a cipher suite with the `ciphers` option. + * More information can be found in the RFC 4279. + */ + pskCallback?(socket: TLSSocket, identity: string): DataView | NodeJS.TypedArray | null; + /** + * hint to send to a client to help + * with selecting the identity during TLS-PSK negotiation. Will be ignored + * in TLS 1.3. Upon failing to set pskIdentityHint `tlsClientError` will be + * emitted with `ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED` code. + */ + pskIdentityHint?: string | undefined; + } + interface PSKCallbackNegotation { + psk: DataView | NodeJS.TypedArray; + identity: string; + } + interface ConnectionOptions extends SecureContextOptions, CommonConnectionOptions { + host?: string | undefined; + port?: number | undefined; + path?: string | undefined; // Creates unix socket connection to path. If this option is specified, `host` and `port` are ignored. + socket?: stream.Duplex | undefined; // Establish secure connection on a given socket rather than creating a new socket + checkServerIdentity?: typeof checkServerIdentity | undefined; + servername?: string | undefined; // SNI TLS Extension + session?: Buffer | undefined; + minDHSize?: number | undefined; + lookup?: net.LookupFunction | undefined; + timeout?: number | undefined; + /** + * When negotiating TLS-PSK (pre-shared keys), this function is called + * with optional identity `hint` provided by the server or `null` + * in case of TLS 1.3 where `hint` was removed. + * It will be necessary to provide a custom `tls.checkServerIdentity()` + * for the connection as the default one will try to check hostname/IP + * of the server against the certificate but that's not applicable for PSK + * because there won't be a certificate present. + * More information can be found in the RFC 4279. + * + * @param hint message sent from the server to help client + * decide which identity to use during negotiation. + * Always `null` if TLS 1.3 is used. + * @returns Return `null` to stop the negotiation process. `psk` must be + * compatible with the selected cipher's digest. + * `identity` must use UTF-8 encoding. + */ + pskCallback?(hint: string | null): PSKCallbackNegotation | null; + } + /** + * Accepts encrypted connections using TLS or SSL. + * @since v0.3.2 + */ + class Server extends net.Server { + constructor(secureConnectionListener?: (socket: TLSSocket) => void); + constructor(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void); + /** + * The `server.addContext()` method adds a secure context that will be used if + * the client request's SNI name matches the supplied `hostname` (or wildcard). + * + * When there are multiple matching contexts, the most recently added one is + * used. + * @since v0.5.3 + * @param hostname A SNI host name or wildcard (e.g. `'*'`) + * @param context An object containing any of the possible properties from the {@link createSecureContext} `options` arguments (e.g. `key`, `cert`, `ca`, etc). + */ + addContext(hostname: string, context: SecureContextOptions): void; + /** + * Returns the session ticket keys. + * + * See `Session Resumption` for more information. + * @since v3.0.0 + * @return A 48-byte buffer containing the session ticket keys. + */ + getTicketKeys(): Buffer; + /** + * The `server.setSecureContext()` method replaces the secure context of an + * existing server. Existing connections to the server are not interrupted. + * @since v11.0.0 + * @param options An object containing any of the possible properties from the {@link createSecureContext} `options` arguments (e.g. `key`, `cert`, `ca`, etc). + */ + setSecureContext(options: SecureContextOptions): void; + /** + * Sets the session ticket keys. + * + * Changes to the ticket keys are effective only for future server connections. + * Existing or currently pending server connections will use the previous keys. + * + * See `Session Resumption` for more information. + * @since v3.0.0 + * @param keys A 48-byte buffer containing the session ticket keys. + */ + setTicketKeys(keys: Buffer): void; + /** + * events.EventEmitter + * 1. tlsClientError + * 2. newSession + * 3. OCSPRequest + * 4. resumeSession + * 5. secureConnection + * 6. keylog + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + addListener( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void, + ): this; + addListener( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + addListener( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, + ): this; + addListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + addListener(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "tlsClientError", err: Error, tlsSocket: TLSSocket): boolean; + emit(event: "newSession", sessionId: Buffer, sessionData: Buffer, callback: () => void): boolean; + emit( + event: "OCSPRequest", + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ): boolean; + emit( + event: "resumeSession", + sessionId: Buffer, + callback: (err: Error | null, sessionData: Buffer | null) => void, + ): boolean; + emit(event: "secureConnection", tlsSocket: TLSSocket): boolean; + emit(event: "keylog", line: Buffer, tlsSocket: TLSSocket): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + on(event: "newSession", listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void): this; + on( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + on( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, + ): this; + on(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + on(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + once( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void, + ): this; + once( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + once( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, + ): this; + once(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + once(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + prependListener( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void, + ): this; + prependListener( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + prependListener( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, + ): this; + prependListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + prependListener(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + prependOnceListener( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void, + ): this; + prependOnceListener( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + prependOnceListener( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, + ): this; + prependOnceListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + prependOnceListener(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + } + /** + * @deprecated since v0.11.3 Use `tls.TLSSocket` instead. + */ + interface SecurePair { + encrypted: TLSSocket; + cleartext: TLSSocket; + } + type SecureVersion = "TLSv1.3" | "TLSv1.2" | "TLSv1.1" | "TLSv1"; + interface SecureContextOptions { + /** + * If set, this will be called when a client opens a connection using the ALPN extension. + * One argument will be passed to the callback: an object containing `servername` and `protocols` fields, + * respectively containing the server name from the SNI extension (if any) and an array of + * ALPN protocol name strings. The callback must return either one of the strings listed in `protocols`, + * which will be returned to the client as the selected ALPN protocol, or `undefined`, + * to reject the connection with a fatal alert. If a string is returned that does not match one of + * the client's ALPN protocols, an error will be thrown. + * This option cannot be used with the `ALPNProtocols` option, and setting both options will throw an error. + * @since v18.19.0 + */ + ALPNCallback?: ((arg: { servername: string; protocols: string[] }) => string | undefined) | undefined; + /** + * Optionally override the trusted CA certificates. Default is to trust + * the well-known CAs curated by Mozilla. Mozilla's CAs are completely + * replaced when CAs are explicitly specified using this option. + */ + ca?: string | Buffer | Array | undefined; + /** + * Cert chains in PEM format. One cert chain should be provided per + * private key. Each cert chain should consist of the PEM formatted + * certificate for a provided private key, followed by the PEM + * formatted intermediate certificates (if any), in order, and not + * including the root CA (the root CA must be pre-known to the peer, + * see ca). When providing multiple cert chains, they do not have to + * be in the same order as their private keys in key. If the + * intermediate certificates are not provided, the peer will not be + * able to validate the certificate, and the handshake will fail. + */ + cert?: string | Buffer | Array | undefined; + /** + * Colon-separated list of supported signature algorithms. The list + * can contain digest algorithms (SHA256, MD5 etc.), public key + * algorithms (RSA-PSS, ECDSA etc.), combination of both (e.g + * 'RSA+SHA384') or TLS v1.3 scheme names (e.g. rsa_pss_pss_sha512). + */ + sigalgs?: string | undefined; + /** + * Cipher suite specification, replacing the default. For more + * information, see modifying the default cipher suite. Permitted + * ciphers can be obtained via tls.getCiphers(). Cipher names must be + * uppercased in order for OpenSSL to accept them. + */ + ciphers?: string | undefined; + /** + * Name of an OpenSSL engine which can provide the client certificate. + */ + clientCertEngine?: string | undefined; + /** + * PEM formatted CRLs (Certificate Revocation Lists). + */ + crl?: string | Buffer | Array | undefined; + /** + * `'auto'` or custom Diffie-Hellman parameters, required for non-ECDHE perfect forward secrecy. + * If omitted or invalid, the parameters are silently discarded and DHE ciphers will not be available. + * ECDHE-based perfect forward secrecy will still be available. + */ + dhparam?: string | Buffer | undefined; + /** + * A string describing a named curve or a colon separated list of curve + * NIDs or names, for example P-521:P-384:P-256, to use for ECDH key + * agreement. Set to auto to select the curve automatically. Use + * crypto.getCurves() to obtain a list of available curve names. On + * recent releases, openssl ecparam -list_curves will also display the + * name and description of each available elliptic curve. Default: + * tls.DEFAULT_ECDH_CURVE. + */ + ecdhCurve?: string | undefined; + /** + * Attempt to use the server's cipher suite preferences instead of the + * client's. When true, causes SSL_OP_CIPHER_SERVER_PREFERENCE to be + * set in secureOptions + */ + honorCipherOrder?: boolean | undefined; + /** + * Private keys in PEM format. PEM allows the option of private keys + * being encrypted. Encrypted keys will be decrypted with + * options.passphrase. Multiple keys using different algorithms can be + * provided either as an array of unencrypted key strings or buffers, + * or an array of objects in the form {pem: [, + * passphrase: ]}. The object form can only occur in an array. + * object.passphrase is optional. Encrypted keys will be decrypted with + * object.passphrase if provided, or options.passphrase if it is not. + */ + key?: string | Buffer | Array | undefined; + /** + * Name of an OpenSSL engine to get private key from. Should be used + * together with privateKeyIdentifier. + */ + privateKeyEngine?: string | undefined; + /** + * Identifier of a private key managed by an OpenSSL engine. Should be + * used together with privateKeyEngine. Should not be set together with + * key, because both options define a private key in different ways. + */ + privateKeyIdentifier?: string | undefined; + /** + * Optionally set the maximum TLS version to allow. One + * of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the + * `secureProtocol` option, use one or the other. + * **Default:** `'TLSv1.3'`, unless changed using CLI options. Using + * `--tls-max-v1.2` sets the default to `'TLSv1.2'`. Using `--tls-max-v1.3` sets the default to + * `'TLSv1.3'`. If multiple of the options are provided, the highest maximum is used. + */ + maxVersion?: SecureVersion | undefined; + /** + * Optionally set the minimum TLS version to allow. One + * of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the + * `secureProtocol` option, use one or the other. It is not recommended to use + * less than TLSv1.2, but it may be required for interoperability. + * **Default:** `'TLSv1.2'`, unless changed using CLI options. Using + * `--tls-v1.0` sets the default to `'TLSv1'`. Using `--tls-v1.1` sets the default to + * `'TLSv1.1'`. Using `--tls-min-v1.3` sets the default to + * 'TLSv1.3'. If multiple of the options are provided, the lowest minimum is used. + */ + minVersion?: SecureVersion | undefined; + /** + * Shared passphrase used for a single private key and/or a PFX. + */ + passphrase?: string | undefined; + /** + * PFX or PKCS12 encoded private key and certificate chain. pfx is an + * alternative to providing key and cert individually. PFX is usually + * encrypted, if it is, passphrase will be used to decrypt it. Multiple + * PFX can be provided either as an array of unencrypted PFX buffers, + * or an array of objects in the form {buf: [, + * passphrase: ]}. The object form can only occur in an array. + * object.passphrase is optional. Encrypted PFX will be decrypted with + * object.passphrase if provided, or options.passphrase if it is not. + */ + pfx?: string | Buffer | Array | undefined; + /** + * Optionally affect the OpenSSL protocol behavior, which is not + * usually necessary. This should be used carefully if at all! Value is + * a numeric bitmask of the SSL_OP_* options from OpenSSL Options + */ + secureOptions?: number | undefined; // Value is a numeric bitmask of the `SSL_OP_*` options + /** + * Legacy mechanism to select the TLS protocol version to use, it does + * not support independent control of the minimum and maximum version, + * and does not support limiting the protocol to TLSv1.3. Use + * minVersion and maxVersion instead. The possible values are listed as + * SSL_METHODS, use the function names as strings. For example, use + * 'TLSv1_1_method' to force TLS version 1.1, or 'TLS_method' to allow + * any TLS protocol version up to TLSv1.3. It is not recommended to use + * TLS versions less than 1.2, but it may be required for + * interoperability. Default: none, see minVersion. + */ + secureProtocol?: string | undefined; + /** + * Opaque identifier used by servers to ensure session state is not + * shared between applications. Unused by clients. + */ + sessionIdContext?: string | undefined; + /** + * 48-bytes of cryptographically strong pseudo-random data. + * See Session Resumption for more information. + */ + ticketKeys?: Buffer | undefined; + /** + * The number of seconds after which a TLS session created by the + * server will no longer be resumable. See Session Resumption for more + * information. Default: 300. + */ + sessionTimeout?: number | undefined; + } + interface SecureContext { + context: any; + } + /** + * Verifies the certificate `cert` is issued to `hostname`. + * + * Returns [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object, populating it with `reason`, `host`, and `cert` on + * failure. On success, returns [undefined](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type). + * + * This function is intended to be used in combination with the`checkServerIdentity` option that can be passed to {@link connect} and as + * such operates on a `certificate object`. For other purposes, consider using `x509.checkHost()` instead. + * + * This function can be overwritten by providing an alternative function as the`options.checkServerIdentity` option that is passed to `tls.connect()`. The + * overwriting function can call `tls.checkServerIdentity()` of course, to augment + * the checks done with additional verification. + * + * This function is only called if the certificate passed all other checks, such as + * being issued by trusted CA (`options.ca`). + * + * Earlier versions of Node.js incorrectly accepted certificates for a given`hostname` if a matching `uniformResourceIdentifier` subject alternative name + * was present (see [CVE-2021-44531](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-44531)). Applications that wish to accept`uniformResourceIdentifier` subject alternative names can use + * a custom`options.checkServerIdentity` function that implements the desired behavior. + * @since v0.8.4 + * @param hostname The host name or IP address to verify the certificate against. + * @param cert A `certificate object` representing the peer's certificate. + */ + function checkServerIdentity(hostname: string, cert: PeerCertificate): Error | undefined; + /** + * Creates a new {@link Server}. The `secureConnectionListener`, if provided, is + * automatically set as a listener for the `'secureConnection'` event. + * + * The `ticketKeys` options is automatically shared between `cluster` module + * workers. + * + * The following illustrates a simple echo server: + * + * ```js + * const tls = require('tls'); + * const fs = require('fs'); + * + * const options = { + * key: fs.readFileSync('server-key.pem'), + * cert: fs.readFileSync('server-cert.pem'), + * + * // This is necessary only if using client certificate authentication. + * requestCert: true, + * + * // This is necessary only if the client uses a self-signed certificate. + * ca: [ fs.readFileSync('client-cert.pem') ] + * }; + * + * const server = tls.createServer(options, (socket) => { + * console.log('server connected', + * socket.authorized ? 'authorized' : 'unauthorized'); + * socket.write('welcome!\n'); + * socket.setEncoding('utf8'); + * socket.pipe(socket); + * }); + * server.listen(8000, () => { + * console.log('server bound'); + * }); + * ``` + * + * The server can be tested by connecting to it using the example client from {@link connect}. + * @since v0.3.2 + */ + function createServer(secureConnectionListener?: (socket: TLSSocket) => void): Server; + function createServer(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void): Server; + /** + * The `callback` function, if specified, will be added as a listener for the `'secureConnect'` event. + * + * `tls.connect()` returns a {@link TLSSocket} object. + * + * Unlike the `https` API, `tls.connect()` does not enable the + * SNI (Server Name Indication) extension by default, which may cause some + * servers to return an incorrect certificate or reject the connection + * altogether. To enable SNI, set the `servername` option in addition + * to `host`. + * + * The following illustrates a client for the echo server example from {@link createServer}: + * + * ```js + * // Assumes an echo server that is listening on port 8000. + * const tls = require('tls'); + * const fs = require('fs'); + * + * const options = { + * // Necessary only if the server requires client certificate authentication. + * key: fs.readFileSync('client-key.pem'), + * cert: fs.readFileSync('client-cert.pem'), + * + * // Necessary only if the server uses a self-signed certificate. + * ca: [ fs.readFileSync('server-cert.pem') ], + * + * // Necessary only if the server's cert isn't for "localhost". + * checkServerIdentity: () => { return null; }, + * }; + * + * const socket = tls.connect(8000, options, () => { + * console.log('client connected', + * socket.authorized ? 'authorized' : 'unauthorized'); + * process.stdin.pipe(socket); + * process.stdin.resume(); + * }); + * socket.setEncoding('utf8'); + * socket.on('data', (data) => { + * console.log(data); + * }); + * socket.on('end', () => { + * console.log('server ends connection'); + * }); + * ``` + * @since v0.11.3 + */ + function connect(options: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + function connect( + port: number, + host?: string, + options?: ConnectionOptions, + secureConnectListener?: () => void, + ): TLSSocket; + function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + /** + * Creates a new secure pair object with two streams, one of which reads and writes + * the encrypted data and the other of which reads and writes the cleartext data. + * Generally, the encrypted stream is piped to/from an incoming encrypted data + * stream and the cleartext one is used as a replacement for the initial encrypted + * stream. + * + * `tls.createSecurePair()` returns a `tls.SecurePair` object with `cleartext` and`encrypted` stream properties. + * + * Using `cleartext` has the same API as {@link TLSSocket}. + * + * The `tls.createSecurePair()` method is now deprecated in favor of`tls.TLSSocket()`. For example, the code: + * + * ```js + * pair = tls.createSecurePair(// ... ); + * pair.encrypted.pipe(socket); + * socket.pipe(pair.encrypted); + * ``` + * + * can be replaced by: + * + * ```js + * secureSocket = tls.TLSSocket(socket, options); + * ``` + * + * where `secureSocket` has the same API as `pair.cleartext`. + * @since v0.3.2 + * @deprecated Since v0.11.3 - Use {@link TLSSocket} instead. + * @param context A secure context object as returned by `tls.createSecureContext()` + * @param isServer `true` to specify that this TLS connection should be opened as a server. + * @param requestCert `true` to specify whether a server should request a certificate from a connecting client. Only applies when `isServer` is `true`. + * @param rejectUnauthorized If not `false` a server automatically reject clients with invalid certificates. Only applies when `isServer` is `true`. + */ + function createSecurePair( + context?: SecureContext, + isServer?: boolean, + requestCert?: boolean, + rejectUnauthorized?: boolean, + ): SecurePair; + /** + * {@link createServer} sets the default value of the `honorCipherOrder` option + * to `true`, other APIs that create secure contexts leave it unset. + * + * {@link createServer} uses a 128 bit truncated SHA1 hash value generated + * from `process.argv` as the default value of the `sessionIdContext` option, other + * APIs that create secure contexts have no default value. + * + * The `tls.createSecureContext()` method creates a `SecureContext` object. It is + * usable as an argument to several `tls` APIs, such as {@link createServer} and `server.addContext()`, but has no public methods. + * + * A key is _required_ for ciphers that use certificates. Either `key` or`pfx` can be used to provide it. + * + * If the `ca` option is not given, then Node.js will default to using [Mozilla's publicly trusted list of + * CAs](https://hg.mozilla.org/mozilla-central/raw-file/tip/security/nss/lib/ckfw/builtins/certdata.txt). + * @since v0.11.13 + */ + function createSecureContext(options?: SecureContextOptions): SecureContext; + /** + * Returns an array with the names of the supported TLS ciphers. The names are + * lower-case for historical reasons, but must be uppercased to be used in + * the `ciphers` option of {@link createSecureContext}. + * + * Not all supported ciphers are enabled by default. See `Modifying the default TLS cipher suite`. + * + * Cipher names that start with `'tls_'` are for TLSv1.3, all the others are for + * TLSv1.2 and below. + * + * ```js + * console.log(tls.getCiphers()); // ['aes128-gcm-sha256', 'aes128-sha', ...] + * ``` + * @since v0.10.2 + */ + function getCiphers(): string[]; + /** + * The default curve name to use for ECDH key agreement in a tls server. + * The default value is 'auto'. See tls.createSecureContext() for further + * information. + */ + let DEFAULT_ECDH_CURVE: string; + /** + * The default value of the maxVersion option of + * tls.createSecureContext(). It can be assigned any of the supported TLS + * protocol versions, 'TLSv1.3', 'TLSv1.2', 'TLSv1.1', or 'TLSv1'. Default: + * 'TLSv1.3', unless changed using CLI options. Using --tls-max-v1.2 sets + * the default to 'TLSv1.2'. Using --tls-max-v1.3 sets the default to + * 'TLSv1.3'. If multiple of the options are provided, the highest maximum + * is used. + */ + let DEFAULT_MAX_VERSION: SecureVersion; + /** + * The default value of the minVersion option of tls.createSecureContext(). + * It can be assigned any of the supported TLS protocol versions, + * 'TLSv1.3', 'TLSv1.2', 'TLSv1.1', or 'TLSv1'. Default: 'TLSv1.2', unless + * changed using CLI options. Using --tls-min-v1.0 sets the default to + * 'TLSv1'. Using --tls-min-v1.1 sets the default to 'TLSv1.1'. Using + * --tls-min-v1.3 sets the default to 'TLSv1.3'. If multiple of the options + * are provided, the lowest minimum is used. + */ + let DEFAULT_MIN_VERSION: SecureVersion; + /** + * The default value of the ciphers option of tls.createSecureContext(). + * It can be assigned any of the supported OpenSSL ciphers. + * Defaults to the content of crypto.constants.defaultCoreCipherList, unless + * changed using CLI options using --tls-default-ciphers. + */ + let DEFAULT_CIPHERS: string; + /** + * An immutable array of strings representing the root certificates (in PEM + * format) used for verifying peer certificates. This is the default value + * of the ca option to tls.createSecureContext(). + */ + const rootCertificates: readonly string[]; +} +declare module "node:tls" { + export * from "tls"; +} diff --git a/backend/node_modules/@types/node/trace_events.d.ts b/backend/node_modules/@types/node/trace_events.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7f0fe55a861d9bc952221f285b9edf6b9157d3db --- /dev/null +++ b/backend/node_modules/@types/node/trace_events.d.ts @@ -0,0 +1,171 @@ +/** + * The `trace_events` module provides a mechanism to centralize tracing information + * generated by V8, Node.js core, and userspace code. + * + * Tracing can be enabled with the `--trace-event-categories` command-line flag + * or by using the `trace_events` module. The `--trace-event-categories` flag + * accepts a list of comma-separated category names. + * + * The available categories are: + * + * * `node`: An empty placeholder. + * * `node.async_hooks`: Enables capture of detailed `async_hooks` trace data. + * The `async_hooks` events have a unique `asyncId` and a special `triggerId` `triggerAsyncId` property. + * * `node.bootstrap`: Enables capture of Node.js bootstrap milestones. + * * `node.console`: Enables capture of `console.time()` and `console.count()`output. + * * `node.dns.native`: Enables capture of trace data for DNS queries. + * * `node.environment`: Enables capture of Node.js Environment milestones. + * * `node.fs.sync`: Enables capture of trace data for file system sync methods. + * * `node.perf`: Enables capture of `Performance API` measurements. + * * `node.perf.usertiming`: Enables capture of only Performance API User Timing + * measures and marks. + * * `node.perf.timerify`: Enables capture of only Performance API timerify + * measurements. + * * `node.promises.rejections`: Enables capture of trace data tracking the number + * of unhandled Promise rejections and handled-after-rejections. + * * `node.vm.script`: Enables capture of trace data for the `vm` module's`runInNewContext()`, `runInContext()`, and `runInThisContext()` methods. + * * `v8`: The `V8` events are GC, compiling, and execution related. + * + * By default the `node`, `node.async_hooks`, and `v8` categories are enabled. + * + * ```bash + * node --trace-event-categories v8,node,node.async_hooks server.js + * ``` + * + * Prior versions of Node.js required the use of the `--trace-events-enabled`flag to enable trace events. This requirement has been removed. However, the`--trace-events-enabled` flag _may_ still be + * used and will enable the`node`, `node.async_hooks`, and `v8` trace event categories by default. + * + * ```bash + * node --trace-events-enabled + * + * # is equivalent to + * + * node --trace-event-categories v8,node,node.async_hooks + * ``` + * + * Alternatively, trace events may be enabled using the `trace_events` module: + * + * ```js + * const trace_events = require('trace_events'); + * const tracing = trace_events.createTracing({ categories: ['node.perf'] }); + * tracing.enable(); // Enable trace event capture for the 'node.perf' category + * + * // do work + * + * tracing.disable(); // Disable trace event capture for the 'node.perf' category + * ``` + * + * Running Node.js with tracing enabled will produce log files that can be opened + * in the [`chrome://tracing`](https://www.chromium.org/developers/how-tos/trace-event-profiling-tool) tab of Chrome. + * + * The logging file is by default called `node_trace.${rotation}.log`, where`${rotation}` is an incrementing log-rotation id. The filepath pattern can + * be specified with `--trace-event-file-pattern` that accepts a template + * string that supports `${rotation}` and `${pid}`: + * + * ```bash + * node --trace-event-categories v8 --trace-event-file-pattern '${pid}-${rotation}.log' server.js + * ``` + * + * To guarantee that the log file is properly generated after signal events like`SIGINT`, `SIGTERM`, or `SIGBREAK`, make sure to have the appropriate handlers + * in your code, such as: + * + * ```js + * process.on('SIGINT', function onSigint() { + * console.info('Received SIGINT.'); + * process.exit(130); // Or applicable exit code depending on OS and signal + * }); + * ``` + * + * The tracing system uses the same time source + * as the one used by `process.hrtime()`. + * However the trace-event timestamps are expressed in microseconds, + * unlike `process.hrtime()` which returns nanoseconds. + * + * The features from this module are not available in `Worker` threads. + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/trace_events.js) + */ +declare module "trace_events" { + /** + * The `Tracing` object is used to enable or disable tracing for sets of + * categories. Instances are created using the + * `trace_events.createTracing()` method. + * + * When created, the `Tracing` object is disabled. Calling the + * `tracing.enable()` method adds the categories to the set of enabled trace + * event categories. Calling `tracing.disable()` will remove the categories + * from the set of enabled trace event categories. + */ + interface Tracing { + /** + * A comma-separated list of the trace event categories covered by this + * `Tracing` object. + */ + readonly categories: string; + /** + * Disables this `Tracing` object. + * + * Only trace event categories _not_ covered by other enabled `Tracing` + * objects and _not_ specified by the `--trace-event-categories` flag + * will be disabled. + */ + disable(): void; + /** + * Enables this `Tracing` object for the set of categories covered by + * the `Tracing` object. + */ + enable(): void; + /** + * `true` only if the `Tracing` object has been enabled. + */ + readonly enabled: boolean; + } + interface CreateTracingOptions { + /** + * An array of trace category names. Values included in the array are + * coerced to a string when possible. An error will be thrown if the + * value cannot be coerced. + */ + categories: string[]; + } + /** + * Creates and returns a `Tracing` object for the given set of `categories`. + * + * ```js + * const trace_events = require('trace_events'); + * const categories = ['node.perf', 'node.async_hooks']; + * const tracing = trace_events.createTracing({ categories }); + * tracing.enable(); + * // do stuff + * tracing.disable(); + * ``` + * @since v10.0.0 + * @return . + */ + function createTracing(options: CreateTracingOptions): Tracing; + /** + * Returns a comma-separated list of all currently-enabled trace event + * categories. The current set of enabled trace event categories is determined + * by the _union_ of all currently-enabled `Tracing` objects and any categories + * enabled using the `--trace-event-categories` flag. + * + * Given the file `test.js` below, the command`node --trace-event-categories node.perf test.js` will print`'node.async_hooks,node.perf'` to the console. + * + * ```js + * const trace_events = require('trace_events'); + * const t1 = trace_events.createTracing({ categories: ['node.async_hooks'] }); + * const t2 = trace_events.createTracing({ categories: ['node.perf'] }); + * const t3 = trace_events.createTracing({ categories: ['v8'] }); + * + * t1.enable(); + * t2.enable(); + * + * console.log(trace_events.getEnabledCategories()); + * ``` + * @since v10.0.0 + */ + function getEnabledCategories(): string | undefined; +} +declare module "node:trace_events" { + export * from "trace_events"; +} diff --git a/backend/node_modules/@types/node/tty.d.ts b/backend/node_modules/@types/node/tty.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c0304153c5d0f1e993d839888a6a24e91f525e7a --- /dev/null +++ b/backend/node_modules/@types/node/tty.d.ts @@ -0,0 +1,206 @@ +/** + * The `tty` module provides the `tty.ReadStream` and `tty.WriteStream` classes. + * In most cases, it will not be necessary or possible to use this module directly. + * However, it can be accessed using: + * + * ```js + * const tty = require('tty'); + * ``` + * + * When Node.js detects that it is being run with a text terminal ("TTY") + * attached, `process.stdin` will, by default, be initialized as an instance of`tty.ReadStream` and both `process.stdout` and `process.stderr` will, by + * default, be instances of `tty.WriteStream`. The preferred method of determining + * whether Node.js is being run within a TTY context is to check that the value of + * the `process.stdout.isTTY` property is `true`: + * + * ```console + * $ node -p -e "Boolean(process.stdout.isTTY)" + * true + * $ node -p -e "Boolean(process.stdout.isTTY)" | cat + * false + * ``` + * + * In most cases, there should be little to no reason for an application to + * manually create instances of the `tty.ReadStream` and `tty.WriteStream`classes. + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/tty.js) + */ +declare module "tty" { + import * as net from "node:net"; + /** + * The `tty.isatty()` method returns `true` if the given `fd` is associated with + * a TTY and `false` if it is not, including whenever `fd` is not a non-negative + * integer. + * @since v0.5.8 + * @param fd A numeric file descriptor + */ + function isatty(fd: number): boolean; + /** + * Represents the readable side of a TTY. In normal circumstances `process.stdin` will be the only `tty.ReadStream` instance in a Node.js + * process and there should be no reason to create additional instances. + * @since v0.5.8 + */ + class ReadStream extends net.Socket { + constructor(fd: number, options?: net.SocketConstructorOpts); + /** + * A `boolean` that is `true` if the TTY is currently configured to operate as a + * raw device. Defaults to `false`. + * @since v0.7.7 + */ + isRaw: boolean; + /** + * Allows configuration of `tty.ReadStream` so that it operates as a raw device. + * + * When in raw mode, input is always available character-by-character, not + * including modifiers. Additionally, all special processing of characters by the + * terminal is disabled, including echoing input + * characters. Ctrl+C will no longer cause a `SIGINT` when + * in this mode. + * @since v0.7.7 + * @param mode If `true`, configures the `tty.ReadStream` to operate as a raw device. If `false`, configures the `tty.ReadStream` to operate in its default mode. The `readStream.isRaw` + * property will be set to the resulting mode. + * @return The read stream instance. + */ + setRawMode(mode: boolean): this; + /** + * A `boolean` that is always `true` for `tty.ReadStream` instances. + * @since v0.5.8 + */ + isTTY: boolean; + } + /** + * -1 - to the left from cursor + * 0 - the entire line + * 1 - to the right from cursor + */ + type Direction = -1 | 0 | 1; + /** + * Represents the writable side of a TTY. In normal circumstances,`process.stdout` and `process.stderr` will be the only`tty.WriteStream` instances created for a Node.js process and there + * should be no reason to create additional instances. + * @since v0.5.8 + */ + class WriteStream extends net.Socket { + constructor(fd: number); + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "resize", listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "resize"): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "resize", listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "resize", listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "resize", listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "resize", listener: () => void): this; + /** + * `writeStream.clearLine()` clears the current line of this `WriteStream` in a + * direction identified by `dir`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + clearLine(dir: Direction, callback?: () => void): boolean; + /** + * `writeStream.clearScreenDown()` clears this `WriteStream` from the current + * cursor down. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + clearScreenDown(callback?: () => void): boolean; + /** + * `writeStream.cursorTo()` moves this `WriteStream`'s cursor to the specified + * position. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + cursorTo(x: number, y?: number, callback?: () => void): boolean; + cursorTo(x: number, callback: () => void): boolean; + /** + * `writeStream.moveCursor()` moves this `WriteStream`'s cursor _relative_ to its + * current position. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + moveCursor(dx: number, dy: number, callback?: () => void): boolean; + /** + * Returns: + * + * * `1` for 2, + * * `4` for 16, + * * `8` for 256, + * * `24` for 16,777,216 colors supported. + * + * Use this to determine what colors the terminal supports. Due to the nature of + * colors in terminals it is possible to either have false positives or false + * negatives. It depends on process information and the environment variables that + * may lie about what terminal is used. + * It is possible to pass in an `env` object to simulate the usage of a specific + * terminal. This can be useful to check how specific environment settings behave. + * + * To enforce a specific color support, use one of the below environment settings. + * + * * 2 colors: `FORCE_COLOR = 0` (Disables colors) + * * 16 colors: `FORCE_COLOR = 1` + * * 256 colors: `FORCE_COLOR = 2` + * * 16,777,216 colors: `FORCE_COLOR = 3` + * + * Disabling color support is also possible by using the `NO_COLOR` and`NODE_DISABLE_COLORS` environment variables. + * @since v9.9.0 + * @param [env=process.env] An object containing the environment variables to check. This enables simulating the usage of a specific terminal. + */ + getColorDepth(env?: object): number; + /** + * Returns `true` if the `writeStream` supports at least as many colors as provided + * in `count`. Minimum support is 2 (black and white). + * + * This has the same false positives and negatives as described in `writeStream.getColorDepth()`. + * + * ```js + * process.stdout.hasColors(); + * // Returns true or false depending on if `stdout` supports at least 16 colors. + * process.stdout.hasColors(256); + * // Returns true or false depending on if `stdout` supports at least 256 colors. + * process.stdout.hasColors({ TMUX: '1' }); + * // Returns true. + * process.stdout.hasColors(2 ** 24, { TMUX: '1' }); + * // Returns false (the environment setting pretends to support 2 ** 8 colors). + * ``` + * @since v11.13.0, v10.16.0 + * @param [count=16] The number of colors that are requested (minimum 2). + * @param [env=process.env] An object containing the environment variables to check. This enables simulating the usage of a specific terminal. + */ + hasColors(count?: number): boolean; + hasColors(env?: object): boolean; + hasColors(count: number, env?: object): boolean; + /** + * `writeStream.getWindowSize()` returns the size of the TTY + * corresponding to this `WriteStream`. The array is of the type`[numColumns, numRows]` where `numColumns` and `numRows` represent the number + * of columns and rows in the corresponding TTY. + * @since v0.7.7 + */ + getWindowSize(): [number, number]; + /** + * A `number` specifying the number of columns the TTY currently has. This property + * is updated whenever the `'resize'` event is emitted. + * @since v0.7.7 + */ + columns: number; + /** + * A `number` specifying the number of rows the TTY currently has. This property + * is updated whenever the `'resize'` event is emitted. + * @since v0.7.7 + */ + rows: number; + /** + * A `boolean` that is always `true`. + * @since v0.5.8 + */ + isTTY: boolean; + } +} +declare module "node:tty" { + export * from "tty"; +} diff --git a/backend/node_modules/@types/node/url.d.ts b/backend/node_modules/@types/node/url.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2e5ccf84dfff2a2698d2086cbbe8e48b1e85232c --- /dev/null +++ b/backend/node_modules/@types/node/url.d.ts @@ -0,0 +1,954 @@ +/** + * The `url` module provides utilities for URL resolution and parsing. It can be + * accessed using: + * + * ```js + * import url from 'url'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.19.0/lib/url.js) + */ +declare module "url" { + import { Blob as NodeBlob } from "node:buffer"; + import { ClientRequestArgs } from "node:http"; + import { ParsedUrlQuery, ParsedUrlQueryInput } from "node:querystring"; + // Input to `url.format` + interface UrlObject { + auth?: string | null | undefined; + hash?: string | null | undefined; + host?: string | null | undefined; + hostname?: string | null | undefined; + href?: string | null | undefined; + pathname?: string | null | undefined; + protocol?: string | null | undefined; + search?: string | null | undefined; + slashes?: boolean | null | undefined; + port?: string | number | null | undefined; + query?: string | null | ParsedUrlQueryInput | undefined; + } + // Output of `url.parse` + interface Url { + auth: string | null; + hash: string | null; + host: string | null; + hostname: string | null; + href: string; + path: string | null; + pathname: string | null; + protocol: string | null; + search: string | null; + slashes: boolean | null; + port: string | null; + query: string | null | ParsedUrlQuery; + } + interface UrlWithParsedQuery extends Url { + query: ParsedUrlQuery; + } + interface UrlWithStringQuery extends Url { + query: string | null; + } + /** + * The `url.parse()` method takes a URL string, parses it, and returns a URL + * object. + * + * A `TypeError` is thrown if `urlString` is not a string. + * + * A `URIError` is thrown if the `auth` property is present but cannot be decoded. + * + * Use of the legacy `url.parse()` method is discouraged. Users should + * use the WHATWG `URL` API. Because the `url.parse()` method uses a + * lenient, non-standard algorithm for parsing URL strings, security + * issues can be introduced. Specifically, issues with [host name spoofing](https://hackerone.com/reports/678487) and + * incorrect handling of usernames and passwords have been identified. + * + * Deprecation of this API has been shelved for now primarily due to the the + * inability of the [WHATWG API to parse relative URLs](https://github.com/nodejs/node/issues/12682#issuecomment-1154492373). + * [Discussions are ongoing](https://github.com/whatwg/url/issues/531) for the best way to resolve this. + * + * @since v0.1.25 + * @param urlString The URL string to parse. + * @param [parseQueryString=false] If `true`, the `query` property will always be set to an object returned by the {@link querystring} module's `parse()` method. If `false`, the `query` property + * on the returned URL object will be an unparsed, undecoded string. + * @param [slashesDenoteHost=false] If `true`, the first token after the literal string `//` and preceding the next `/` will be interpreted as the `host`. For instance, given `//foo/bar`, the + * result would be `{host: 'foo', pathname: '/bar'}` rather than `{pathname: '//foo/bar'}`. + */ + function parse(urlString: string): UrlWithStringQuery; + function parse( + urlString: string, + parseQueryString: false | undefined, + slashesDenoteHost?: boolean, + ): UrlWithStringQuery; + function parse(urlString: string, parseQueryString: true, slashesDenoteHost?: boolean): UrlWithParsedQuery; + function parse(urlString: string, parseQueryString: boolean, slashesDenoteHost?: boolean): Url; + /** + * The `url.format()` method returns a formatted URL string derived from `urlObject`. + * + * ```js + * const url = require('node:url'); + * url.format({ + * protocol: 'https', + * hostname: 'example.com', + * pathname: '/some/path', + * query: { + * page: 1, + * format: 'json', + * }, + * }); + * + * // => 'https://example.com/some/path?page=1&format=json' + * ``` + * + * If `urlObject` is not an object or a string, `url.format()` will throw a `TypeError`. + * + * The formatting process operates as follows: + * + * * A new empty string `result` is created. + * * If `urlObject.protocol` is a string, it is appended as-is to `result`. + * * Otherwise, if `urlObject.protocol` is not `undefined` and is not a string, an `Error` is thrown. + * * For all string values of `urlObject.protocol` that _do not end_ with an ASCII + * colon (`:`) character, the literal string `:` will be appended to `result`. + * * If either of the following conditions is true, then the literal string `//` will be appended to `result`: + * * `urlObject.slashes` property is true; + * * `urlObject.protocol` begins with `http`, `https`, `ftp`, `gopher`, or `file`; + * * If the value of the `urlObject.auth` property is truthy, and either `urlObject.host` or `urlObject.hostname` are not `undefined`, the value of `urlObject.auth` will be coerced into a string + * and appended to `result` followed by the literal string `@`. + * * If the `urlObject.host` property is `undefined` then: + * * If the `urlObject.hostname` is a string, it is appended to `result`. + * * Otherwise, if `urlObject.hostname` is not `undefined` and is not a string, + * an `Error` is thrown. + * * If the `urlObject.port` property value is truthy, and `urlObject.hostname` is not `undefined`: + * * The literal string `:` is appended to `result`, and + * * The value of `urlObject.port` is coerced to a string and appended to `result`. + * * Otherwise, if the `urlObject.host` property value is truthy, the value of `urlObject.host` is coerced to a string and appended to `result`. + * * If the `urlObject.pathname` property is a string that is not an empty string: + * * If the `urlObject.pathname` _does not start_ with an ASCII forward slash + * (`/`), then the literal string `'/'` is appended to `result`. + * * The value of `urlObject.pathname` is appended to `result`. + * * Otherwise, if `urlObject.pathname` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.search` property is `undefined` and if the `urlObject.query`property is an `Object`, the literal string `?` is appended to `result` followed by the output of calling the + * `querystring` module's `stringify()` method passing the value of `urlObject.query`. + * * Otherwise, if `urlObject.search` is a string: + * * If the value of `urlObject.search` _does not start_ with the ASCII question + * mark (`?`) character, the literal string `?` is appended to `result`. + * * The value of `urlObject.search` is appended to `result`. + * * Otherwise, if `urlObject.search` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.hash` property is a string: + * * If the value of `urlObject.hash` _does not start_ with the ASCII hash (`#`) + * character, the literal string `#` is appended to `result`. + * * The value of `urlObject.hash` is appended to `result`. + * * Otherwise, if the `urlObject.hash` property is not `undefined` and is not a + * string, an `Error` is thrown. + * * `result` is returned. + * @since v0.1.25 + * @legacy Use the WHATWG URL API instead. + * @param urlObject A URL object (as returned by `url.parse()` or constructed otherwise). If a string, it is converted to an object by passing it to `url.parse()`. + */ + function format(urlObject: URL, options?: URLFormatOptions): string; + /** + * The `url.format()` method returns a formatted URL string derived from `urlObject`. + * + * ```js + * const url = require('node:url'); + * url.format({ + * protocol: 'https', + * hostname: 'example.com', + * pathname: '/some/path', + * query: { + * page: 1, + * format: 'json', + * }, + * }); + * + * // => 'https://example.com/some/path?page=1&format=json' + * ``` + * + * If `urlObject` is not an object or a string, `url.format()` will throw a `TypeError`. + * + * The formatting process operates as follows: + * + * * A new empty string `result` is created. + * * If `urlObject.protocol` is a string, it is appended as-is to `result`. + * * Otherwise, if `urlObject.protocol` is not `undefined` and is not a string, an `Error` is thrown. + * * For all string values of `urlObject.protocol` that _do not end_ with an ASCII + * colon (`:`) character, the literal string `:` will be appended to `result`. + * * If either of the following conditions is true, then the literal string `//` will be appended to `result`: + * * `urlObject.slashes` property is true; + * * `urlObject.protocol` begins with `http`, `https`, `ftp`, `gopher`, or `file`; + * * If the value of the `urlObject.auth` property is truthy, and either `urlObject.host` or `urlObject.hostname` are not `undefined`, the value of `urlObject.auth` will be coerced into a string + * and appended to `result` followed by the literal string `@`. + * * If the `urlObject.host` property is `undefined` then: + * * If the `urlObject.hostname` is a string, it is appended to `result`. + * * Otherwise, if `urlObject.hostname` is not `undefined` and is not a string, + * an `Error` is thrown. + * * If the `urlObject.port` property value is truthy, and `urlObject.hostname` is not `undefined`: + * * The literal string `:` is appended to `result`, and + * * The value of `urlObject.port` is coerced to a string and appended to `result`. + * * Otherwise, if the `urlObject.host` property value is truthy, the value of `urlObject.host` is coerced to a string and appended to `result`. + * * If the `urlObject.pathname` property is a string that is not an empty string: + * * If the `urlObject.pathname` _does not start_ with an ASCII forward slash + * (`/`), then the literal string `'/'` is appended to `result`. + * * The value of `urlObject.pathname` is appended to `result`. + * * Otherwise, if `urlObject.pathname` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.search` property is `undefined` and if the `urlObject.query`property is an `Object`, the literal string `?` is appended to `result` followed by the output of calling the + * `querystring` module's `stringify()` method passing the value of `urlObject.query`. + * * Otherwise, if `urlObject.search` is a string: + * * If the value of `urlObject.search` _does not start_ with the ASCII question + * mark (`?`) character, the literal string `?` is appended to `result`. + * * The value of `urlObject.search` is appended to `result`. + * * Otherwise, if `urlObject.search` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.hash` property is a string: + * * If the value of `urlObject.hash` _does not start_ with the ASCII hash (`#`) + * character, the literal string `#` is appended to `result`. + * * The value of `urlObject.hash` is appended to `result`. + * * Otherwise, if the `urlObject.hash` property is not `undefined` and is not a + * string, an `Error` is thrown. + * * `result` is returned. + * @since v0.1.25 + * @legacy Use the WHATWG URL API instead. + * @param urlObject A URL object (as returned by `url.parse()` or constructed otherwise). If a string, it is converted to an object by passing it to `url.parse()`. + */ + function format(urlObject: UrlObject | string): string; + /** + * The `url.resolve()` method resolves a target URL relative to a base URL in a + * manner similar to that of a web browser resolving an anchor tag. + * + * ```js + * const url = require('url'); + * url.resolve('/one/two/three', 'four'); // '/one/two/four' + * url.resolve('http://example.com/', '/one'); // 'http://example.com/one' + * url.resolve('http://example.com/one', '/two'); // 'http://example.com/two' + * ``` + * + * To achieve the same result using the WHATWG URL API: + * + * ```js + * function resolve(from, to) { + * const resolvedUrl = new URL(to, new URL(from, 'resolve://')); + * if (resolvedUrl.protocol === 'resolve:') { + * // `from` is a relative URL. + * const { pathname, search, hash } = resolvedUrl; + * return pathname + search + hash; + * } + * return resolvedUrl.toString(); + * } + * + * resolve('/one/two/three', 'four'); // '/one/two/four' + * resolve('http://example.com/', '/one'); // 'http://example.com/one' + * resolve('http://example.com/one', '/two'); // 'http://example.com/two' + * ``` + * @since v0.1.25 + * @legacy Use the WHATWG URL API instead. + * @param from The base URL to use if `to` is a relative URL. + * @param to The target URL to resolve. + */ + function resolve(from: string, to: string): string; + /** + * Returns the [Punycode](https://tools.ietf.org/html/rfc5891#section-4.4) ASCII serialization of the `domain`. If `domain` is an + * invalid domain, the empty string is returned. + * + * It performs the inverse operation to {@link domainToUnicode}. + * + * This feature is only available if the `node` executable was compiled with `ICU` enabled. If not, the domain names are passed through unchanged. + * + * ```js + * import url from 'url'; + * + * console.log(url.domainToASCII('español.com')); + * // Prints xn--espaol-zwa.com + * console.log(url.domainToASCII('中文.com')); + * // Prints xn--fiq228c.com + * console.log(url.domainToASCII('xn--iñvalid.com')); + * // Prints an empty string + * ``` + * @since v7.4.0, v6.13.0 + */ + function domainToASCII(domain: string): string; + /** + * Returns the Unicode serialization of the `domain`. If `domain` is an invalid + * domain, the empty string is returned. + * + * It performs the inverse operation to {@link domainToASCII}. + * + * This feature is only available if the `node` executable was compiled with `ICU` enabled. If not, the domain names are passed through unchanged. + * + * ```js + * import url from 'url'; + * + * console.log(url.domainToUnicode('xn--espaol-zwa.com')); + * // Prints español.com + * console.log(url.domainToUnicode('xn--fiq228c.com')); + * // Prints 中文.com + * console.log(url.domainToUnicode('xn--iñvalid.com')); + * // Prints an empty string + * ``` + * @since v7.4.0, v6.13.0 + */ + function domainToUnicode(domain: string): string; + /** + * This function ensures the correct decodings of percent-encoded characters as + * well as ensuring a cross-platform valid absolute path string. + * + * ```js + * import { fileURLToPath } from 'url'; + * + * const __filename = fileURLToPath(import.meta.url); + * + * new URL('file:///C:/path/').pathname; // Incorrect: /C:/path/ + * fileURLToPath('file:///C:/path/'); // Correct: C:\path\ (Windows) + * + * new URL('file://nas/foo.txt').pathname; // Incorrect: /foo.txt + * fileURLToPath('file://nas/foo.txt'); // Correct: \\nas\foo.txt (Windows) + * + * new URL('file:///你好.txt').pathname; // Incorrect: /%E4%BD%A0%E5%A5%BD.txt + * fileURLToPath('file:///你好.txt'); // Correct: /你好.txt (POSIX) + * + * new URL('file:///hello world').pathname; // Incorrect: /hello%20world + * fileURLToPath('file:///hello world'); // Correct: /hello world (POSIX) + * ``` + * @since v10.12.0 + * @param url The file URL string or URL object to convert to a path. + * @return The fully-resolved platform-specific Node.js file path. + */ + function fileURLToPath(url: string | URL): string; + /** + * This function ensures that `path` is resolved absolutely, and that the URL + * control characters are correctly encoded when converting into a File URL. + * + * ```js + * import { pathToFileURL } from 'url'; + * + * new URL('/foo#1', 'file:'); // Incorrect: file:///foo#1 + * pathToFileURL('/foo#1'); // Correct: file:///foo%231 (POSIX) + * + * new URL('/some/path%.c', 'file:'); // Incorrect: file:///some/path%.c + * pathToFileURL('/some/path%.c'); // Correct: file:///some/path%25.c (POSIX) + * ``` + * @since v10.12.0 + * @param path The path to convert to a File URL. + * @return The file URL object. + */ + function pathToFileURL(path: string): URL; + /** + * This utility function converts a URL object into an ordinary options object as + * expected by the `http.request()` and `https.request()` APIs. + * + * ```js + * import { urlToHttpOptions } from 'url'; + * const myURL = new URL('https://a:b@測試?abc#foo'); + * + * console.log(urlToHttpOptions(myURL)); + * /* + * { + * protocol: 'https:', + * hostname: 'xn--g6w251d', + * hash: '#foo', + * search: '?abc', + * pathname: '/', + * path: '/?abc', + * href: 'https://a:b@xn--g6w251d/?abc#foo', + * auth: 'a:b' + * } + * + * ``` + * @since v15.7.0, v14.18.0 + * @param url The `WHATWG URL` object to convert to an options object. + * @return Options object + */ + function urlToHttpOptions(url: URL): ClientRequestArgs; + interface URLFormatOptions { + /** + * `true` if the serialized URL string should include the username and password, `false` otherwise. + * @default true + */ + auth?: boolean | undefined; + /** + * `true` if the serialized URL string should include the fragment, `false` otherwise. + * @default true + */ + fragment?: boolean | undefined; + /** + * `true` if the serialized URL string should include the search query, `false` otherwise. + * @default true + */ + search?: boolean | undefined; + /** + * `true` if Unicode characters appearing in the host component of the URL string should be encoded directly as opposed to + * being Punycode encoded. + * @default false + */ + unicode?: boolean | undefined; + } + /** + * Browser-compatible `URL` class, implemented by following the WHATWG URL + * Standard. [Examples of parsed URLs](https://url.spec.whatwg.org/#example-url-parsing) may be found in the Standard itself. + * The `URL` class is also available on the global object. + * + * In accordance with browser conventions, all properties of `URL` objects + * are implemented as getters and setters on the class prototype, rather than as + * data properties on the object itself. Thus, unlike `legacy urlObject`s, + * using the `delete` keyword on any properties of `URL` objects (e.g. `delete myURL.protocol`, `delete myURL.pathname`, etc) has no effect but will still + * return `true`. + * @since v7.0.0, v6.13.0 + */ + class URL { + /** + * Creates a `'blob:nodedata:...'` URL string that represents the given `Blob` object and can be used to retrieve the `Blob` later. + * + * ```js + * const { + * Blob, + * resolveObjectURL, + * } = require('buffer'); + * + * const blob = new Blob(['hello']); + * const id = URL.createObjectURL(blob); + * + * // later... + * + * const otherBlob = resolveObjectURL(id); + * console.log(otherBlob.size); + * ``` + * + * The data stored by the registered `Blob` will be retained in memory until `URL.revokeObjectURL()` is called to remove it. + * + * `Blob` objects are registered within the current thread. If using Worker + * Threads, `Blob` objects registered within one Worker will not be available + * to other workers or the main thread. + * @since v16.7.0 + * @experimental + */ + static createObjectURL(blob: NodeBlob): string; + /** + * Removes the stored `Blob` identified by the given ID. Attempting to revoke a + * ID that isn’t registered will silently fail. + * @since v16.7.0 + * @experimental + * @param id A `'blob:nodedata:...` URL string returned by a prior call to `URL.createObjectURL()`. + */ + static revokeObjectURL(id: string): void; + /** + * Checks if an `input` relative to the `base` can be parsed to a `URL`. + * + * ```js + * const isValid = URL.canParse('/foo', 'https://example.org/'); // true + * + * const isNotValid = URL.canParse('/foo'); // false + * ``` + * @since v18.17.0 + * @param input The absolute or relative input URL to parse. If `input` is relative, then `base` is required. If `input` is absolute, the `base` is ignored. If `input` is not a string, it is + * `converted to a string` first. + * @param base The base URL to resolve against if the `input` is not absolute. If `base` is not a string, it is `converted to a string` first. + */ + static canParse(input: string, base?: string): boolean; + constructor(input: string | { toString: () => string }, base?: string | URL); + /** + * Gets and sets the fragment portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org/foo#bar'); + * console.log(myURL.hash); + * // Prints #bar + * + * myURL.hash = 'baz'; + * console.log(myURL.href); + * // Prints https://example.org/foo#baz + * ``` + * + * Invalid URL characters included in the value assigned to the `hash` property + * are `percent-encoded`. The selection of which characters to + * percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + hash: string; + /** + * Gets and sets the host portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org:81/foo'); + * console.log(myURL.host); + * // Prints example.org:81 + * + * myURL.host = 'example.com:82'; + * console.log(myURL.href); + * // Prints https://example.com:82/foo + * ``` + * + * Invalid host values assigned to the `host` property are ignored. + */ + host: string; + /** + * Gets and sets the host name portion of the URL. The key difference between`url.host` and `url.hostname` is that `url.hostname` does _not_ include the + * port. + * + * ```js + * const myURL = new URL('https://example.org:81/foo'); + * console.log(myURL.hostname); + * // Prints example.org + * + * // Setting the hostname does not change the port + * myURL.hostname = 'example.com:82'; + * console.log(myURL.href); + * // Prints https://example.com:81/foo + * + * // Use myURL.host to change the hostname and port + * myURL.host = 'example.org:82'; + * console.log(myURL.href); + * // Prints https://example.org:82/foo + * ``` + * + * Invalid host name values assigned to the `hostname` property are ignored. + */ + hostname: string; + /** + * Gets and sets the serialized URL. + * + * ```js + * const myURL = new URL('https://example.org/foo'); + * console.log(myURL.href); + * // Prints https://example.org/foo + * + * myURL.href = 'https://example.com/bar'; + * console.log(myURL.href); + * // Prints https://example.com/bar + * ``` + * + * Getting the value of the `href` property is equivalent to calling {@link toString}. + * + * Setting the value of this property to a new value is equivalent to creating a + * new `URL` object using `new URL(value)`. Each of the `URL`object's properties will be modified. + * + * If the value assigned to the `href` property is not a valid URL, a `TypeError`will be thrown. + */ + href: string; + /** + * Gets the read-only serialization of the URL's origin. + * + * ```js + * const myURL = new URL('https://example.org/foo/bar?baz'); + * console.log(myURL.origin); + * // Prints https://example.org + * ``` + * + * ```js + * const idnURL = new URL('https://測試'); + * console.log(idnURL.origin); + * // Prints https://xn--g6w251d + * + * console.log(idnURL.hostname); + * // Prints xn--g6w251d + * ``` + */ + readonly origin: string; + /** + * Gets and sets the password portion of the URL. + * + * ```js + * const myURL = new URL('https://abc:xyz@example.com'); + * console.log(myURL.password); + * // Prints xyz + * + * myURL.password = '123'; + * console.log(myURL.href); + * // Prints https://abc:123@example.com + * ``` + * + * Invalid URL characters included in the value assigned to the `password` property + * are `percent-encoded`. The selection of which characters to + * percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + password: string; + /** + * Gets and sets the path portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org/abc/xyz?123'); + * console.log(myURL.pathname); + * // Prints /abc/xyz + * + * myURL.pathname = '/abcdef'; + * console.log(myURL.href); + * // Prints https://example.org/abcdef?123 + * ``` + * + * Invalid URL characters included in the value assigned to the `pathname` property are `percent-encoded`. The selection of which characters + * to percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + pathname: string; + /** + * Gets and sets the port portion of the URL. + * + * The port value may be a number or a string containing a number in the range `0` to `65535` (inclusive). Setting the value to the default port of the `URL` objects given `protocol` will + * result in the `port` value becoming + * the empty string (`''`). + * + * The port value can be an empty string in which case the port depends on + * the protocol/scheme: + * + * + * + * Upon assigning a value to the port, the value will first be converted to a + * string using `.toString()`. + * + * If that string is invalid but it begins with a number, the leading number is + * assigned to `port`. + * If the number lies outside the range denoted above, it is ignored. + * + * ```js + * const myURL = new URL('https://example.org:8888'); + * console.log(myURL.port); + * // Prints 8888 + * + * // Default ports are automatically transformed to the empty string + * // (HTTPS protocol's default port is 443) + * myURL.port = '443'; + * console.log(myURL.port); + * // Prints the empty string + * console.log(myURL.href); + * // Prints https://example.org/ + * + * myURL.port = 1234; + * console.log(myURL.port); + * // Prints 1234 + * console.log(myURL.href); + * // Prints https://example.org:1234/ + * + * // Completely invalid port strings are ignored + * myURL.port = 'abcd'; + * console.log(myURL.port); + * // Prints 1234 + * + * // Leading numbers are treated as a port number + * myURL.port = '5678abcd'; + * console.log(myURL.port); + * // Prints 5678 + * + * // Non-integers are truncated + * myURL.port = 1234.5678; + * console.log(myURL.port); + * // Prints 1234 + * + * // Out-of-range numbers which are not represented in scientific notation + * // will be ignored. + * myURL.port = 1e10; // 10000000000, will be range-checked as described below + * console.log(myURL.port); + * // Prints 1234 + * ``` + * + * Numbers which contain a decimal point, + * such as floating-point numbers or numbers in scientific notation, + * are not an exception to this rule. + * Leading numbers up to the decimal point will be set as the URL's port, + * assuming they are valid: + * + * ```js + * myURL.port = 4.567e21; + * console.log(myURL.port); + * // Prints 4 (because it is the leading number in the string '4.567e21') + * ``` + */ + port: string; + /** + * Gets and sets the protocol portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org'); + * console.log(myURL.protocol); + * // Prints https: + * + * myURL.protocol = 'ftp'; + * console.log(myURL.href); + * // Prints ftp://example.org/ + * ``` + * + * Invalid URL protocol values assigned to the `protocol` property are ignored. + */ + protocol: string; + /** + * Gets and sets the serialized query portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org/abc?123'); + * console.log(myURL.search); + * // Prints ?123 + * + * myURL.search = 'abc=xyz'; + * console.log(myURL.href); + * // Prints https://example.org/abc?abc=xyz + * ``` + * + * Any invalid URL characters appearing in the value assigned the `search`property will be `percent-encoded`. The selection of which + * characters to percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + search: string; + /** + * Gets the `URLSearchParams` object representing the query parameters of the + * URL. This property is read-only but the `URLSearchParams` object it provides + * can be used to mutate the URL instance; to replace the entirety of query + * parameters of the URL, use the {@link search} setter. See `URLSearchParams` documentation for details. + * + * Use care when using `.searchParams` to modify the `URL` because, + * per the WHATWG specification, the `URLSearchParams` object uses + * different rules to determine which characters to percent-encode. For + * instance, the `URL` object will not percent encode the ASCII tilde (`~`) + * character, while `URLSearchParams` will always encode it: + * + * ```js + * const myUrl = new URL('https://example.org/abc?foo=~bar'); + * + * console.log(myUrl.search); // prints ?foo=~bar + * + * // Modify the URL via searchParams... + * myUrl.searchParams.sort(); + * + * console.log(myUrl.search); // prints ?foo=%7Ebar + * ``` + */ + readonly searchParams: URLSearchParams; + /** + * Gets and sets the username portion of the URL. + * + * ```js + * const myURL = new URL('https://abc:xyz@example.com'); + * console.log(myURL.username); + * // Prints abc + * + * myURL.username = '123'; + * console.log(myURL.href); + * // Prints https://123:xyz@example.com/ + * ``` + * + * Any invalid URL characters appearing in the value assigned the `username` property will be `percent-encoded`. The selection of which + * characters to percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + username: string; + /** + * The `toString()` method on the `URL` object returns the serialized URL. The + * value returned is equivalent to that of {@link href} and {@link toJSON}. + */ + toString(): string; + /** + * The `toJSON()` method on the `URL` object returns the serialized URL. The + * value returned is equivalent to that of {@link href} and {@link toString}. + * + * This method is automatically called when an `URL` object is serialized + * with [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify). + * + * ```js + * const myURLs = [ + * new URL('https://www.example.com'), + * new URL('https://test.example.org'), + * ]; + * console.log(JSON.stringify(myURLs)); + * // Prints ["https://www.example.com/","https://test.example.org/"] + * ``` + */ + toJSON(): string; + } + /** + * The `URLSearchParams` API provides read and write access to the query of a `URL`. The `URLSearchParams` class can also be used standalone with one of the + * four following constructors. + * The `URLSearchParams` class is also available on the global object. + * + * The WHATWG `URLSearchParams` interface and the `querystring` module have + * similar purpose, but the purpose of the `querystring` module is more + * general, as it allows the customization of delimiter characters (`&` and `=`). + * On the other hand, this API is designed purely for URL query strings. + * + * ```js + * const myURL = new URL('https://example.org/?abc=123'); + * console.log(myURL.searchParams.get('abc')); + * // Prints 123 + * + * myURL.searchParams.append('abc', 'xyz'); + * console.log(myURL.href); + * // Prints https://example.org/?abc=123&abc=xyz + * + * myURL.searchParams.delete('abc'); + * myURL.searchParams.set('a', 'b'); + * console.log(myURL.href); + * // Prints https://example.org/?a=b + * + * const newSearchParams = new URLSearchParams(myURL.searchParams); + * // The above is equivalent to + * // const newSearchParams = new URLSearchParams(myURL.search); + * + * newSearchParams.append('a', 'c'); + * console.log(myURL.href); + * // Prints https://example.org/?a=b + * console.log(newSearchParams.toString()); + * // Prints a=b&a=c + * + * // newSearchParams.toString() is implicitly called + * myURL.search = newSearchParams; + * console.log(myURL.href); + * // Prints https://example.org/?a=b&a=c + * newSearchParams.delete('a'); + * console.log(myURL.href); + * // Prints https://example.org/?a=b&a=c + * ``` + * @since v7.5.0, v6.13.0 + */ + class URLSearchParams implements Iterable<[string, string]> { + constructor( + init?: + | URLSearchParams + | string + | Record + | Iterable<[string, string]> + | ReadonlyArray<[string, string]>, + ); + /** + * Append a new name-value pair to the query string. + */ + append(name: string, value: string): void; + /** + * If `value` is provided, removes all name-value pairs + * where name is `name` and value is `value`. + * + * If `value` is not provided, removes all name-value pairs whose name is `name`. + */ + delete(name: string, value?: string): void; + /** + * Returns an ES6 `Iterator` over each of the name-value pairs in the query. + * Each item of the iterator is a JavaScript `Array`. The first item of the `Array` is the `name`, the second item of the `Array` is the `value`. + * + * Alias for `urlSearchParams[@@iterator]()`. + */ + entries(): IterableIterator<[string, string]>; + /** + * Iterates over each name-value pair in the query and invokes the given function. + * + * ```js + * const myURL = new URL('https://example.org/?a=b&c=d'); + * myURL.searchParams.forEach((value, name, searchParams) => { + * console.log(name, value, myURL.searchParams === searchParams); + * }); + * // Prints: + * // a b true + * // c d true + * ``` + * @param fn Invoked for each name-value pair in the query + * @param thisArg To be used as `this` value for when `fn` is called + */ + forEach( + fn: (this: TThis, value: string, name: string, searchParams: URLSearchParams) => void, + thisArg?: TThis, + ): void; + /** + * Returns the value of the first name-value pair whose name is `name`. If there + * are no such pairs, `null` is returned. + * @return or `null` if there is no name-value pair with the given `name`. + */ + get(name: string): string | null; + /** + * Returns the values of all name-value pairs whose name is `name`. If there are + * no such pairs, an empty array is returned. + */ + getAll(name: string): string[]; + /** + * Checks if the `URLSearchParams` object contains key-value pair(s) based on `name` and an optional `value` argument. + * + * If `value` is provided, returns `true` when name-value pair with + * same `name` and `value` exists. + * + * If `value` is not provided, returns `true` if there is at least one name-value + * pair whose name is `name`. + */ + has(name: string, value?: string): boolean; + /** + * Returns an ES6 `Iterator` over the names of each name-value pair. + * + * ```js + * const params = new URLSearchParams('foo=bar&foo=baz'); + * for (const name of params.keys()) { + * console.log(name); + * } + * // Prints: + * // foo + * // foo + * ``` + */ + keys(): IterableIterator; + /** + * Sets the value in the `URLSearchParams` object associated with `name` to`value`. If there are any pre-existing name-value pairs whose names are `name`, + * set the first such pair's value to `value` and remove all others. If not, + * append the name-value pair to the query string. + * + * ```js + * const params = new URLSearchParams(); + * params.append('foo', 'bar'); + * params.append('foo', 'baz'); + * params.append('abc', 'def'); + * console.log(params.toString()); + * // Prints foo=bar&foo=baz&abc=def + * + * params.set('foo', 'def'); + * params.set('xyz', 'opq'); + * console.log(params.toString()); + * // Prints foo=def&abc=def&xyz=opq + * ``` + */ + set(name: string, value: string): void; + /** + * The total number of parameter entries. + * @since v18.16.0 + */ + readonly size: number; + /** + * Sort all existing name-value pairs in-place by their names. Sorting is done + * with a [stable sorting algorithm](https://en.wikipedia.org/wiki/Sorting_algorithm#Stability), so relative order between name-value pairs + * with the same name is preserved. + * + * This method can be used, in particular, to increase cache hits. + * + * ```js + * const params = new URLSearchParams('query[]=abc&type=search&query[]=123'); + * params.sort(); + * console.log(params.toString()); + * // Prints query%5B%5D=abc&query%5B%5D=123&type=search + * ``` + * @since v7.7.0, v6.13.0 + */ + sort(): void; + /** + * Returns the search parameters serialized as a string, with characters + * percent-encoded where necessary. + */ + toString(): string; + /** + * Returns an ES6 `Iterator` over the values of each name-value pair. + */ + values(): IterableIterator; + [Symbol.iterator](): IterableIterator<[string, string]>; + } + import { URL as _URL, URLSearchParams as _URLSearchParams } from "url"; + global { + interface URLSearchParams extends _URLSearchParams {} + interface URL extends _URL {} + interface Global { + URL: typeof _URL; + URLSearchParams: typeof _URLSearchParams; + } + /** + * `URL` class is a global reference for `require('url').URL` + * https://nodejs.org/api/url.html#the-whatwg-url-api + * @since v10.0.0 + */ + var URL: typeof globalThis extends { + onmessage: any; + URL: infer T; + } ? T + : typeof _URL; + /** + * `URLSearchParams` class is a global reference for `require('url').URLSearchParams` + * https://nodejs.org/api/url.html#class-urlsearchparams + * @since v10.0.0 + */ + var URLSearchParams: typeof globalThis extends { + onmessage: any; + URLSearchParams: infer T; + } ? T + : typeof _URLSearchParams; + } +} +declare module "node:url" { + export * from "url"; +} diff --git a/backend/node_modules/@types/node/util.d.ts b/backend/node_modules/@types/node/util.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6adf5db11bd13108d81c939e1c99c491babc05d5 --- /dev/null +++ b/backend/node_modules/@types/node/util.d.ts @@ -0,0 +1,2075 @@ +/** + * The `util` module supports the needs of Node.js internal APIs. Many of the + * utilities are useful for application and module developers as well. To access + * it: + * + * ```js + * const util = require('util'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.x/lib/util.js) + */ +declare module "util" { + import * as types from "node:util/types"; + export interface InspectOptions { + /** + * If `true`, object's non-enumerable symbols and properties are included in the formatted result. + * `WeakMap` and `WeakSet` entries are also included as well as user defined prototype properties (excluding method properties). + * @default false + */ + showHidden?: boolean | undefined; + /** + * Specifies the number of times to recurse while formatting object. + * This is useful for inspecting large objects. + * To recurse up to the maximum call stack size pass `Infinity` or `null`. + * @default 2 + */ + depth?: number | null | undefined; + /** + * If `true`, the output is styled with ANSI color codes. Colors are customizable. + */ + colors?: boolean | undefined; + /** + * If `false`, `[util.inspect.custom](depth, opts, inspect)` functions are not invoked. + * @default true + */ + customInspect?: boolean | undefined; + /** + * If `true`, `Proxy` inspection includes the target and handler objects. + * @default false + */ + showProxy?: boolean | undefined; + /** + * Specifies the maximum number of `Array`, `TypedArray`, `WeakMap`, and `WeakSet` elements + * to include when formatting. Set to `null` or `Infinity` to show all elements. + * Set to `0` or negative to show no elements. + * @default 100 + */ + maxArrayLength?: number | null | undefined; + /** + * Specifies the maximum number of characters to + * include when formatting. Set to `null` or `Infinity` to show all elements. + * Set to `0` or negative to show no characters. + * @default 10000 + */ + maxStringLength?: number | null | undefined; + /** + * The length at which input values are split across multiple lines. + * Set to `Infinity` to format the input as a single line + * (in combination with `compact` set to `true` or any number >= `1`). + * @default 80 + */ + breakLength?: number | undefined; + /** + * Setting this to `false` causes each object key + * to be displayed on a new line. It will also add new lines to text that is + * longer than `breakLength`. If set to a number, the most `n` inner elements + * are united on a single line as long as all properties fit into + * `breakLength`. Short array elements are also grouped together. Note that no + * text will be reduced below 16 characters, no matter the `breakLength` size. + * For more information, see the example below. + * @default true + */ + compact?: boolean | number | undefined; + /** + * If set to `true` or a function, all properties of an object, and `Set` and `Map` + * entries are sorted in the resulting string. + * If set to `true` the default sort is used. + * If set to a function, it is used as a compare function. + */ + sorted?: boolean | ((a: string, b: string) => number) | undefined; + /** + * If set to `true`, getters are going to be + * inspected as well. If set to `'get'` only getters without setter are going + * to be inspected. If set to `'set'` only getters having a corresponding + * setter are going to be inspected. This might cause side effects depending on + * the getter function. + * @default false + */ + getters?: "get" | "set" | boolean | undefined; + /** + * If set to `true`, an underscore is used to separate every three digits in all bigints and numbers. + * @default false + */ + numericSeparator?: boolean | undefined; + } + export type Style = + | "special" + | "number" + | "bigint" + | "boolean" + | "undefined" + | "null" + | "string" + | "symbol" + | "date" + | "regexp" + | "module"; + export type CustomInspectFunction = (depth: number, options: InspectOptionsStylized) => any; // TODO: , inspect: inspect + export interface InspectOptionsStylized extends InspectOptions { + stylize(text: string, styleType: Style): string; + } + /** + * The `util.format()` method returns a formatted string using the first argument + * as a `printf`\-like format string which can contain zero or more format + * specifiers. Each specifier is replaced with the converted value from the + * corresponding argument. Supported specifiers are: + * + * If a specifier does not have a corresponding argument, it is not replaced: + * + * ```js + * util.format('%s:%s', 'foo'); + * // Returns: 'foo:%s' + * ``` + * + * Values that are not part of the format string are formatted using`util.inspect()` if their type is not `string`. + * + * If there are more arguments passed to the `util.format()` method than the + * number of specifiers, the extra arguments are concatenated to the returned + * string, separated by spaces: + * + * ```js + * util.format('%s:%s', 'foo', 'bar', 'baz'); + * // Returns: 'foo:bar baz' + * ``` + * + * If the first argument does not contain a valid format specifier, `util.format()`returns a string that is the concatenation of all arguments separated by spaces: + * + * ```js + * util.format(1, 2, 3); + * // Returns: '1 2 3' + * ``` + * + * If only one argument is passed to `util.format()`, it is returned as it is + * without any formatting: + * + * ```js + * util.format('%% %s'); + * // Returns: '%% %s' + * ``` + * + * `util.format()` is a synchronous method that is intended as a debugging tool. + * Some input values can have a significant performance overhead that can block the + * event loop. Use this function with care and never in a hot code path. + * @since v0.5.3 + * @param format A `printf`-like format string. + */ + export function format(format?: any, ...param: any[]): string; + /** + * This function is identical to {@link format}, except in that it takes + * an `inspectOptions` argument which specifies options that are passed along to {@link inspect}. + * + * ```js + * util.formatWithOptions({ colors: true }, 'See object %O', { foo: 42 }); + * // Returns 'See object { foo: 42 }', where `42` is colored as a number + * // when printed to a terminal. + * ``` + * @since v10.0.0 + */ + export function formatWithOptions(inspectOptions: InspectOptions, format?: any, ...param: any[]): string; + /** + * Returns the string name for a numeric error code that comes from a Node.js API. + * The mapping between error codes and error names is platform-dependent. + * See `Common System Errors` for the names of common errors. + * + * ```js + * fs.access('file/that/does/not/exist', (err) => { + * const name = util.getSystemErrorName(err.errno); + * console.error(name); // ENOENT + * }); + * ``` + * @since v9.7.0 + */ + export function getSystemErrorName(err: number): string; + /** + * Returns a Map of all system error codes available from the Node.js API. + * The mapping between error codes and error names is platform-dependent. + * See `Common System Errors` for the names of common errors. + * + * ```js + * fs.access('file/that/does/not/exist', (err) => { + * const errorMap = util.getSystemErrorMap(); + * const name = errorMap.get(err.errno); + * console.error(name); // ENOENT + * }); + * ``` + * @since v16.0.0, v14.17.0 + */ + export function getSystemErrorMap(): Map; + /** + * The `util.log()` method prints the given `string` to `stdout` with an included + * timestamp. + * + * ```js + * const util = require('util'); + * + * util.log('Timestamped message.'); + * ``` + * @since v0.3.0 + * @deprecated Since v6.0.0 - Use a third party module instead. + */ + export function log(string: string): void; + /** + * Returns the `string` after replacing any surrogate code points + * (or equivalently, any unpaired surrogate code units) with the + * Unicode "replacement character" U+FFFD. + * @since v16.8.0, v14.18.0 + */ + export function toUSVString(string: string): string; + /** + * Creates and returns an `AbortController` instance whose `AbortSignal` is marked + * as transferable and can be used with `structuredClone()` or `postMessage()`. + * @since v18.11.0 + * @returns A transferable AbortController + */ + export function transferableAbortController(): AbortController; + /** + * Marks the given {AbortSignal} as transferable so that it can be used with + * `structuredClone()` and `postMessage()`. + * + * ```js + * const signal = transferableAbortSignal(AbortSignal.timeout(100)); + * const channel = new MessageChannel(); + * channel.port2.postMessage(signal, [signal]); + * ``` + * @since v18.11.0 + * @param signal The AbortSignal + * @returns The same AbortSignal + */ + export function transferableAbortSignal(signal: AbortSignal): AbortSignal; + /** + * Listens to abort event on the provided `signal` and returns a promise that is fulfilled when the `signal` is aborted. + * If the passed `resource` is garbage collected before the `signal` is aborted, the returned promise shall remain pending indefinitely. + * @param resource Any non-null entity, reference to which is held weakly. + */ + export function aborted(signal: AbortSignal, resource: any): Promise; + /** + * The `util.inspect()` method returns a string representation of `object` that is + * intended for debugging. The output of `util.inspect` may change at any time + * and should not be depended upon programmatically. Additional `options` may be + * passed that alter the result.`util.inspect()` will use the constructor's name and/or `@@toStringTag` to make + * an identifiable tag for an inspected value. + * + * ```js + * class Foo { + * get [Symbol.toStringTag]() { + * return 'bar'; + * } + * } + * + * class Bar {} + * + * const baz = Object.create(null, { [Symbol.toStringTag]: { value: 'foo' } }); + * + * util.inspect(new Foo()); // 'Foo [bar] {}' + * util.inspect(new Bar()); // 'Bar {}' + * util.inspect(baz); // '[foo] {}' + * ``` + * + * Circular references point to their anchor by using a reference index: + * + * ```js + * const { inspect } = require('util'); + * + * const obj = {}; + * obj.a = [obj]; + * obj.b = {}; + * obj.b.inner = obj.b; + * obj.b.obj = obj; + * + * console.log(inspect(obj)); + * // { + * // a: [ [Circular *1] ], + * // b: { inner: [Circular *2], obj: [Circular *1] } + * // } + * ``` + * + * The following example inspects all properties of the `util` object: + * + * ```js + * const util = require('util'); + * + * console.log(util.inspect(util, { showHidden: true, depth: null })); + * ``` + * + * The following example highlights the effect of the `compact` option: + * + * ```js + * const util = require('util'); + * + * const o = { + * a: [1, 2, [[ + * 'Lorem ipsum dolor sit amet,\nconsectetur adipiscing elit, sed do ' + + * 'eiusmod \ntempor incididunt ut labore et dolore magna aliqua.', + * 'test', + * 'foo']], 4], + * b: new Map([['za', 1], ['zb', 'test']]) + * }; + * console.log(util.inspect(o, { compact: true, depth: 5, breakLength: 80 })); + * + * // { a: + * // [ 1, + * // 2, + * // [ [ 'Lorem ipsum dolor sit amet,\nconsectetur [...]', // A long line + * // 'test', + * // 'foo' ] ], + * // 4 ], + * // b: Map(2) { 'za' => 1, 'zb' => 'test' } } + * + * // Setting `compact` to false or an integer creates more reader friendly output. + * console.log(util.inspect(o, { compact: false, depth: 5, breakLength: 80 })); + * + * // { + * // a: [ + * // 1, + * // 2, + * // [ + * // [ + * // 'Lorem ipsum dolor sit amet,\n' + + * // 'consectetur adipiscing elit, sed do eiusmod \n' + + * // 'tempor incididunt ut labore et dolore magna aliqua.', + * // 'test', + * // 'foo' + * // ] + * // ], + * // 4 + * // ], + * // b: Map(2) { + * // 'za' => 1, + * // 'zb' => 'test' + * // } + * // } + * + * // Setting `breakLength` to e.g. 150 will print the "Lorem ipsum" text in a + * // single line. + * ``` + * + * The `showHidden` option allows [`WeakMap`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap) and + * [`WeakSet`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet) entries to be + * inspected. If there are more entries than `maxArrayLength`, there is no + * guarantee which entries are displayed. That means retrieving the same [`WeakSet`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet) entries twice may + * result in different output. Furthermore, entries + * with no remaining strong references may be garbage collected at any time. + * + * ```js + * const { inspect } = require('util'); + * + * const obj = { a: 1 }; + * const obj2 = { b: 2 }; + * const weakSet = new WeakSet([obj, obj2]); + * + * console.log(inspect(weakSet, { showHidden: true })); + * // WeakSet { { a: 1 }, { b: 2 } } + * ``` + * + * The `sorted` option ensures that an object's property insertion order does not + * impact the result of `util.inspect()`. + * + * ```js + * const { inspect } = require('util'); + * const assert = require('assert'); + * + * const o1 = { + * b: [2, 3, 1], + * a: '`a` comes before `b`', + * c: new Set([2, 3, 1]) + * }; + * console.log(inspect(o1, { sorted: true })); + * // { a: '`a` comes before `b`', b: [ 2, 3, 1 ], c: Set(3) { 1, 2, 3 } } + * console.log(inspect(o1, { sorted: (a, b) => b.localeCompare(a) })); + * // { c: Set(3) { 3, 2, 1 }, b: [ 2, 3, 1 ], a: '`a` comes before `b`' } + * + * const o2 = { + * c: new Set([2, 1, 3]), + * a: '`a` comes before `b`', + * b: [2, 3, 1] + * }; + * assert.strict.equal( + * inspect(o1, { sorted: true }), + * inspect(o2, { sorted: true }) + * ); + * ``` + * + * The `numericSeparator` option adds an underscore every three digits to all + * numbers. + * + * ```js + * const { inspect } = require('util'); + * + * const thousand = 1_000; + * const million = 1_000_000; + * const bigNumber = 123_456_789n; + * const bigDecimal = 1_234.123_45; + * + * console.log(thousand, million, bigNumber, bigDecimal); + * // 1_000 1_000_000 123_456_789n 1_234.123_45 + * ``` + * + * `util.inspect()` is a synchronous method intended for debugging. Its maximum + * output length is approximately 128 MB. Inputs that result in longer output will + * be truncated. + * @since v0.3.0 + * @param object Any JavaScript primitive or `Object`. + * @return The representation of `object`. + */ + export function inspect(object: any, showHidden?: boolean, depth?: number | null, color?: boolean): string; + export function inspect(object: any, options?: InspectOptions): string; + export namespace inspect { + let colors: NodeJS.Dict<[number, number]>; + let styles: { + [K in Style]: string; + }; + let defaultOptions: InspectOptions; + /** + * Allows changing inspect settings from the repl. + */ + let replDefaults: InspectOptions; + /** + * That can be used to declare custom inspect functions. + */ + const custom: unique symbol; + } + /** + * Alias for [`Array.isArray()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray). + * + * Returns `true` if the given `object` is an `Array`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isArray([]); + * // Returns: true + * util.isArray(new Array()); + * // Returns: true + * util.isArray({}); + * // Returns: false + * ``` + * @since v0.6.0 + * @deprecated Since v4.0.0 - Use `isArray` instead. + */ + export function isArray(object: unknown): object is unknown[]; + /** + * Returns `true` if the given `object` is a `RegExp`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isRegExp(/some regexp/); + * // Returns: true + * util.isRegExp(new RegExp('another regexp')); + * // Returns: true + * util.isRegExp({}); + * // Returns: false + * ``` + * @since v0.6.0 + * @deprecated Since v4.0.0 - Deprecated + */ + export function isRegExp(object: unknown): object is RegExp; + /** + * Returns `true` if the given `object` is a `Date`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isDate(new Date()); + * // Returns: true + * util.isDate(Date()); + * // false (without 'new' returns a String) + * util.isDate({}); + * // Returns: false + * ``` + * @since v0.6.0 + * @deprecated Since v4.0.0 - Use {@link types.isDate} instead. + */ + export function isDate(object: unknown): object is Date; + /** + * Returns `true` if the given `object` is an `Error`. Otherwise, returns`false`. + * + * ```js + * const util = require('util'); + * + * util.isError(new Error()); + * // Returns: true + * util.isError(new TypeError()); + * // Returns: true + * util.isError({ name: 'Error', message: 'an error occurred' }); + * // Returns: false + * ``` + * + * This method relies on `Object.prototype.toString()` behavior. It is + * possible to obtain an incorrect result when the `object` argument manipulates`@@toStringTag`. + * + * ```js + * const util = require('util'); + * const obj = { name: 'Error', message: 'an error occurred' }; + * + * util.isError(obj); + * // Returns: false + * obj[Symbol.toStringTag] = 'Error'; + * util.isError(obj); + * // Returns: true + * ``` + * @since v0.6.0 + * @deprecated Since v4.0.0 - Use {@link types.isNativeError} instead. + */ + export function isError(object: unknown): object is Error; + /** + * Usage of `util.inherits()` is discouraged. Please use the ES6 `class` and`extends` keywords to get language level inheritance support. Also note + * that the two styles are [semantically incompatible](https://github.com/nodejs/node/issues/4179). + * + * Inherit the prototype methods from one [constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor) into another. The + * prototype of `constructor` will be set to a new object created from`superConstructor`. + * + * This mainly adds some input validation on top of`Object.setPrototypeOf(constructor.prototype, superConstructor.prototype)`. + * As an additional convenience, `superConstructor` will be accessible + * through the `constructor.super_` property. + * + * ```js + * const util = require('util'); + * const EventEmitter = require('events'); + * + * function MyStream() { + * EventEmitter.call(this); + * } + * + * util.inherits(MyStream, EventEmitter); + * + * MyStream.prototype.write = function(data) { + * this.emit('data', data); + * }; + * + * const stream = new MyStream(); + * + * console.log(stream instanceof EventEmitter); // true + * console.log(MyStream.super_ === EventEmitter); // true + * + * stream.on('data', (data) => { + * console.log(`Received data: "${data}"`); + * }); + * stream.write('It works!'); // Received data: "It works!" + * ``` + * + * ES6 example using `class` and `extends`: + * + * ```js + * const EventEmitter = require('events'); + * + * class MyStream extends EventEmitter { + * write(data) { + * this.emit('data', data); + * } + * } + * + * const stream = new MyStream(); + * + * stream.on('data', (data) => { + * console.log(`Received data: "${data}"`); + * }); + * stream.write('With ES6'); + * ``` + * @since v0.3.0 + * @legacy Use ES2015 class syntax and `extends` keyword instead. + */ + export function inherits(constructor: unknown, superConstructor: unknown): void; + export type DebugLoggerFunction = (msg: string, ...param: unknown[]) => void; + export interface DebugLogger extends DebugLoggerFunction { + enabled: boolean; + } + /** + * The `util.debuglog()` method is used to create a function that conditionally + * writes debug messages to `stderr` based on the existence of the `NODE_DEBUG`environment variable. If the `section` name appears within the value of that + * environment variable, then the returned function operates similar to `console.error()`. If not, then the returned function is a no-op. + * + * ```js + * const util = require('util'); + * const debuglog = util.debuglog('foo'); + * + * debuglog('hello from foo [%d]', 123); + * ``` + * + * If this program is run with `NODE_DEBUG=foo` in the environment, then + * it will output something like: + * + * ```console + * FOO 3245: hello from foo [123] + * ``` + * + * where `3245` is the process id. If it is not run with that + * environment variable set, then it will not print anything. + * + * The `section` supports wildcard also: + * + * ```js + * const util = require('util'); + * const debuglog = util.debuglog('foo-bar'); + * + * debuglog('hi there, it\'s foo-bar [%d]', 2333); + * ``` + * + * if it is run with `NODE_DEBUG=foo*` in the environment, then it will output + * something like: + * + * ```console + * FOO-BAR 3257: hi there, it's foo-bar [2333] + * ``` + * + * Multiple comma-separated `section` names may be specified in the `NODE_DEBUG`environment variable: `NODE_DEBUG=fs,net,tls`. + * + * The optional `callback` argument can be used to replace the logging function + * with a different function that doesn't have any initialization or + * unnecessary wrapping. + * + * ```js + * const util = require('util'); + * let debuglog = util.debuglog('internals', (debug) => { + * // Replace with a logging function that optimizes out + * // testing if the section is enabled + * debuglog = debug; + * }); + * ``` + * @since v0.11.3 + * @param section A string identifying the portion of the application for which the `debuglog` function is being created. + * @param callback A callback invoked the first time the logging function is called with a function argument that is a more optimized logging function. + * @return The logging function + */ + export function debuglog(section: string, callback?: (fn: DebugLoggerFunction) => void): DebugLogger; + export const debug: typeof debuglog; + /** + * Returns `true` if the given `object` is a `Boolean`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isBoolean(1); + * // Returns: false + * util.isBoolean(0); + * // Returns: false + * util.isBoolean(false); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'boolean'` instead. + */ + export function isBoolean(object: unknown): object is boolean; + /** + * Returns `true` if the given `object` is a `Buffer`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isBuffer({ length: 0 }); + * // Returns: false + * util.isBuffer([]); + * // Returns: false + * util.isBuffer(Buffer.from('hello world')); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `isBuffer` instead. + */ + export function isBuffer(object: unknown): object is Buffer; + /** + * Returns `true` if the given `object` is a `Function`. Otherwise, returns`false`. + * + * ```js + * const util = require('util'); + * + * function Foo() {} + * const Bar = () => {}; + * + * util.isFunction({}); + * // Returns: false + * util.isFunction(Foo); + * // Returns: true + * util.isFunction(Bar); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'function'` instead. + */ + export function isFunction(object: unknown): boolean; + /** + * Returns `true` if the given `object` is strictly `null`. Otherwise, returns`false`. + * + * ```js + * const util = require('util'); + * + * util.isNull(0); + * // Returns: false + * util.isNull(undefined); + * // Returns: false + * util.isNull(null); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `value === null` instead. + */ + export function isNull(object: unknown): object is null; + /** + * Returns `true` if the given `object` is `null` or `undefined`. Otherwise, + * returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isNullOrUndefined(0); + * // Returns: false + * util.isNullOrUndefined(undefined); + * // Returns: true + * util.isNullOrUndefined(null); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `value === undefined || value === null` instead. + */ + export function isNullOrUndefined(object: unknown): object is null | undefined; + /** + * Returns `true` if the given `object` is a `Number`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isNumber(false); + * // Returns: false + * util.isNumber(Infinity); + * // Returns: true + * util.isNumber(0); + * // Returns: true + * util.isNumber(NaN); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'number'` instead. + */ + export function isNumber(object: unknown): object is number; + /** + * Returns `true` if the given `object` is strictly an `Object`**and** not a`Function` (even though functions are objects in JavaScript). + * Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isObject(5); + * // Returns: false + * util.isObject(null); + * // Returns: false + * util.isObject({}); + * // Returns: true + * util.isObject(() => {}); + * // Returns: false + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Deprecated: Use `value !== null && typeof value === 'object'` instead. + */ + export function isObject(object: unknown): boolean; + /** + * Returns `true` if the given `object` is a primitive type. Otherwise, returns`false`. + * + * ```js + * const util = require('util'); + * + * util.isPrimitive(5); + * // Returns: true + * util.isPrimitive('foo'); + * // Returns: true + * util.isPrimitive(false); + * // Returns: true + * util.isPrimitive(null); + * // Returns: true + * util.isPrimitive(undefined); + * // Returns: true + * util.isPrimitive({}); + * // Returns: false + * util.isPrimitive(() => {}); + * // Returns: false + * util.isPrimitive(/^$/); + * // Returns: false + * util.isPrimitive(new Date()); + * // Returns: false + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `(typeof value !== 'object' && typeof value !== 'function') || value === null` instead. + */ + export function isPrimitive(object: unknown): boolean; + /** + * Returns `true` if the given `object` is a `string`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isString(''); + * // Returns: true + * util.isString('foo'); + * // Returns: true + * util.isString(String('foo')); + * // Returns: true + * util.isString(5); + * // Returns: false + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'string'` instead. + */ + export function isString(object: unknown): object is string; + /** + * Returns `true` if the given `object` is a `Symbol`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isSymbol(5); + * // Returns: false + * util.isSymbol('foo'); + * // Returns: false + * util.isSymbol(Symbol('foo')); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'symbol'` instead. + */ + export function isSymbol(object: unknown): object is symbol; + /** + * Returns `true` if the given `object` is `undefined`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * const foo = undefined; + * util.isUndefined(5); + * // Returns: false + * util.isUndefined(foo); + * // Returns: true + * util.isUndefined(null); + * // Returns: false + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `value === undefined` instead. + */ + export function isUndefined(object: unknown): object is undefined; + /** + * The `util.deprecate()` method wraps `fn` (which may be a function or class) in + * such a way that it is marked as deprecated. + * + * ```js + * const util = require('util'); + * + * exports.obsoleteFunction = util.deprecate(() => { + * // Do something here. + * }, 'obsoleteFunction() is deprecated. Use newShinyFunction() instead.'); + * ``` + * + * When called, `util.deprecate()` will return a function that will emit a`DeprecationWarning` using the `'warning'` event. The warning will + * be emitted and printed to `stderr` the first time the returned function is + * called. After the warning is emitted, the wrapped function is called without + * emitting a warning. + * + * If the same optional `code` is supplied in multiple calls to `util.deprecate()`, + * the warning will be emitted only once for that `code`. + * + * ```js + * const util = require('util'); + * + * const fn1 = util.deprecate(someFunction, someMessage, 'DEP0001'); + * const fn2 = util.deprecate(someOtherFunction, someOtherMessage, 'DEP0001'); + * fn1(); // Emits a deprecation warning with code DEP0001 + * fn2(); // Does not emit a deprecation warning because it has the same code + * ``` + * + * If either the `--no-deprecation` or `--no-warnings` command-line flags are + * used, or if the `process.noDeprecation` property is set to `true`_prior_ to + * the first deprecation warning, the `util.deprecate()` method does nothing. + * + * If the `--trace-deprecation` or `--trace-warnings` command-line flags are set, + * or the `process.traceDeprecation` property is set to `true`, a warning and a + * stack trace are printed to `stderr` the first time the deprecated function is + * called. + * + * If the `--throw-deprecation` command-line flag is set, or the`process.throwDeprecation` property is set to `true`, then an exception will be + * thrown when the deprecated function is called. + * + * The `--throw-deprecation` command-line flag and `process.throwDeprecation`property take precedence over `--trace-deprecation` and`process.traceDeprecation`. + * @since v0.8.0 + * @param fn The function that is being deprecated. + * @param msg A warning message to display when the deprecated function is invoked. + * @param code A deprecation code. See the `list of deprecated APIs` for a list of codes. + * @return The deprecated function wrapped to emit a warning. + */ + export function deprecate(fn: T, msg: string, code?: string): T; + /** + * Returns `true` if there is deep strict equality between `val1` and `val2`. + * Otherwise, returns `false`. + * + * See `assert.deepStrictEqual()` for more information about deep strict + * equality. + * @since v9.0.0 + */ + export function isDeepStrictEqual(val1: unknown, val2: unknown): boolean; + /** + * Returns `str` with any ANSI escape codes removed. + * + * ```js + * console.log(util.stripVTControlCharacters('\u001B[4mvalue\u001B[0m')); + * // Prints "value" + * ``` + * @since v16.11.0 + */ + export function stripVTControlCharacters(str: string): string; + /** + * Takes an `async` function (or a function that returns a `Promise`) and returns a + * function following the error-first callback style, i.e. taking + * an `(err, value) => ...` callback as the last argument. In the callback, the + * first argument will be the rejection reason (or `null` if the `Promise`resolved), and the second argument will be the resolved value. + * + * ```js + * const util = require('util'); + * + * async function fn() { + * return 'hello world'; + * } + * const callbackFunction = util.callbackify(fn); + * + * callbackFunction((err, ret) => { + * if (err) throw err; + * console.log(ret); + * }); + * ``` + * + * Will print: + * + * ```text + * hello world + * ``` + * + * The callback is executed asynchronously, and will have a limited stack trace. + * If the callback throws, the process will emit an `'uncaughtException'` event, and if not handled will exit. + * + * Since `null` has a special meaning as the first argument to a callback, if a + * wrapped function rejects a `Promise` with a falsy value as a reason, the value + * is wrapped in an `Error` with the original value stored in a field named`reason`. + * + * ```js + * function fn() { + * return Promise.reject(null); + * } + * const callbackFunction = util.callbackify(fn); + * + * callbackFunction((err, ret) => { + * // When the Promise was rejected with `null` it is wrapped with an Error and + * // the original value is stored in `reason`. + * err && Object.hasOwn(err, 'reason') && err.reason === null; // true + * }); + * ``` + * @since v8.2.0 + * @param fn An `async` function + * @return a callback style function + */ + export function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: () => Promise, + ): (callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1) => Promise, + ): (arg1: T1, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1) => Promise, + ): (arg1: T1, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2) => Promise, + ): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2) => Promise, + ): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise, + ): ( + arg1: T1, + arg2: T2, + arg3: T3, + arg4: T4, + callback: (err: NodeJS.ErrnoException | null, result: TResult) => void, + ) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise, + ): ( + arg1: T1, + arg2: T2, + arg3: T3, + arg4: T4, + arg5: T5, + callback: (err: NodeJS.ErrnoException | null, result: TResult) => void, + ) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise, + ): ( + arg1: T1, + arg2: T2, + arg3: T3, + arg4: T4, + arg5: T5, + arg6: T6, + callback: (err: NodeJS.ErrnoException) => void, + ) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise, + ): ( + arg1: T1, + arg2: T2, + arg3: T3, + arg4: T4, + arg5: T5, + arg6: T6, + callback: (err: NodeJS.ErrnoException | null, result: TResult) => void, + ) => void; + export interface CustomPromisifyLegacy extends Function { + __promisify__: TCustom; + } + export interface CustomPromisifySymbol extends Function { + [promisify.custom]: TCustom; + } + export type CustomPromisify = + | CustomPromisifySymbol + | CustomPromisifyLegacy; + /** + * Takes a function following the common error-first callback style, i.e. taking + * an `(err, value) => ...` callback as the last argument, and returns a version + * that returns promises. + * + * ```js + * const util = require('util'); + * const fs = require('fs'); + * + * const stat = util.promisify(fs.stat); + * stat('.').then((stats) => { + * // Do something with `stats` + * }).catch((error) => { + * // Handle the error. + * }); + * ``` + * + * Or, equivalently using `async function`s: + * + * ```js + * const util = require('util'); + * const fs = require('fs'); + * + * const stat = util.promisify(fs.stat); + * + * async function callStat() { + * const stats = await stat('.'); + * console.log(`This directory is owned by ${stats.uid}`); + * } + * ``` + * + * If there is an `original[util.promisify.custom]` property present, `promisify`will return its value, see `Custom promisified functions`. + * + * `promisify()` assumes that `original` is a function taking a callback as its + * final argument in all cases. If `original` is not a function, `promisify()`will throw an error. If `original` is a function but its last argument is not + * an error-first callback, it will still be passed an error-first + * callback as its last argument. + * + * Using `promisify()` on class methods or other methods that use `this` may not + * work as expected unless handled specially: + * + * ```js + * const util = require('util'); + * + * class Foo { + * constructor() { + * this.a = 42; + * } + * + * bar(callback) { + * callback(null, this.a); + * } + * } + * + * const foo = new Foo(); + * + * const naiveBar = util.promisify(foo.bar); + * // TypeError: Cannot read property 'a' of undefined + * // naiveBar().then(a => console.log(a)); + * + * naiveBar.call(foo).then((a) => console.log(a)); // '42' + * + * const bindBar = naiveBar.bind(foo); + * bindBar().then((a) => console.log(a)); // '42' + * ``` + * @since v8.0.0 + */ + export function promisify(fn: CustomPromisify): TCustom; + export function promisify( + fn: (callback: (err: any, result: TResult) => void) => void, + ): () => Promise; + export function promisify(fn: (callback: (err?: any) => void) => void): () => Promise; + export function promisify( + fn: (arg1: T1, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1) => Promise; + export function promisify(fn: (arg1: T1, callback: (err?: any) => void) => void): (arg1: T1) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, callback: (err?: any) => void) => void, + ): (arg1: T1, arg2: T2) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err?: any) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err?: any) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err?: any) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; + export function promisify(fn: Function): Function; + export namespace promisify { + /** + * That can be used to declare custom promisified variants of functions. + */ + const custom: unique symbol; + } + /** + * An implementation of the [WHATWG Encoding Standard](https://encoding.spec.whatwg.org/) `TextDecoder` API. + * + * ```js + * const decoder = new TextDecoder(); + * const u8arr = new Uint8Array([72, 101, 108, 108, 111]); + * console.log(decoder.decode(u8arr)); // Hello + * ``` + * @since v8.3.0 + */ + export class TextDecoder { + /** + * The encoding supported by the `TextDecoder` instance. + */ + readonly encoding: string; + /** + * The value will be `true` if decoding errors result in a `TypeError` being + * thrown. + */ + readonly fatal: boolean; + /** + * The value will be `true` if the decoding result will include the byte order + * mark. + */ + readonly ignoreBOM: boolean; + constructor( + encoding?: string, + options?: { + fatal?: boolean | undefined; + ignoreBOM?: boolean | undefined; + }, + ); + /** + * Decodes the `input` and returns a string. If `options.stream` is `true`, any + * incomplete byte sequences occurring at the end of the `input` are buffered + * internally and emitted after the next call to `textDecoder.decode()`. + * + * If `textDecoder.fatal` is `true`, decoding errors that occur will result in a`TypeError` being thrown. + * @param input An `ArrayBuffer`, `DataView` or `TypedArray` instance containing the encoded data. + */ + decode( + input?: NodeJS.ArrayBufferView | ArrayBuffer | null, + options?: { + stream?: boolean | undefined; + }, + ): string; + } + export interface EncodeIntoResult { + /** + * The read Unicode code units of input. + */ + read: number; + /** + * The written UTF-8 bytes of output. + */ + written: number; + } + export { types }; + + //// TextEncoder/Decoder + /** + * An implementation of the [WHATWG Encoding Standard](https://encoding.spec.whatwg.org/) `TextEncoder` API. All + * instances of `TextEncoder` only support UTF-8 encoding. + * + * ```js + * const encoder = new TextEncoder(); + * const uint8array = encoder.encode('this is some data'); + * ``` + * + * The `TextEncoder` class is also available on the global object. + * @since v8.3.0 + */ + export class TextEncoder { + /** + * The encoding supported by the `TextEncoder` instance. Always set to `'utf-8'`. + */ + readonly encoding: string; + /** + * UTF-8 encodes the `input` string and returns a `Uint8Array` containing the + * encoded bytes. + * @param [input='an empty string'] The text to encode. + */ + encode(input?: string): Uint8Array; + /** + * UTF-8 encodes the `src` string to the `dest` Uint8Array and returns an object + * containing the read Unicode code units and written UTF-8 bytes. + * + * ```js + * const encoder = new TextEncoder(); + * const src = 'this is some data'; + * const dest = new Uint8Array(10); + * const { read, written } = encoder.encodeInto(src, dest); + * ``` + * @param src The text to encode. + * @param dest The array to hold the encode result. + */ + encodeInto(src: string, dest: Uint8Array): EncodeIntoResult; + } + + import { TextDecoder as _TextDecoder, TextEncoder as _TextEncoder } from "util"; + global { + /** + * `TextDecoder` class is a global reference for `require('util').TextDecoder` + * https://nodejs.org/api/globals.html#textdecoder + * @since v11.0.0 + */ + var TextDecoder: typeof globalThis extends { + onmessage: any; + TextDecoder: infer TextDecoder; + } ? TextDecoder + : typeof _TextDecoder; + + /** + * `TextEncoder` class is a global reference for `require('util').TextEncoder` + * https://nodejs.org/api/globals.html#textencoder + * @since v11.0.0 + */ + var TextEncoder: typeof globalThis extends { + onmessage: any; + TextEncoder: infer TextEncoder; + } ? TextEncoder + : typeof _TextEncoder; + } + + //// parseArgs + /** + * Provides a high-level API for command-line argument parsing. Takes a + * specification for the expected arguments and returns a structured object + * with the parsed values and positionals. + * + * `config` provides arguments for parsing and configures the parser. It + * supports the following properties: + * + * - `args` The array of argument strings. **Default:** `process.argv` with + * `execPath` and `filename` removed. + * - `options` Arguments known to the parser. Keys of `options` are the long + * names of options and values are objects accepting the following properties: + * + * - `type` Type of argument, which must be either `boolean` (for options + * which do not take values) or `string` (for options which do). + * - `multiple` Whether this option can be provided multiple + * times. If `true`, all values will be collected in an array. If + * `false`, values for the option are last-wins. **Default:** `false`. + * - `short` A single character alias for the option. + * - `default` The default option value when it is not set by args. It + * must be of the same type as the `type` property. When `multiple` + * is `true`, it must be an array. + * + * - `strict`: Whether an error should be thrown when unknown arguments + * are encountered, or when arguments are passed that do not match the + * `type` configured in `options`. **Default:** `true`. + * - `allowPositionals`: Whether this command accepts positional arguments. + * **Default:** `false` if `strict` is `true`, otherwise `true`. + * - `tokens`: Whether tokens {boolean} Return the parsed tokens. This is useful + * for extending the built-in behavior, from adding additional checks through + * to reprocessing the tokens in different ways. + * **Default:** `false`. + * + * @returns The parsed command line arguments: + * + * - `values` A mapping of parsed option names with their string + * or boolean values. + * - `positionals` Positional arguments. + * - `tokens` Detailed parse information (only if `tokens` was specified). + */ + export function parseArgs(config?: T): ParsedResults; + + interface ParseArgsOptionConfig { + /** + * Type of argument. + */ + type: "string" | "boolean"; + /** + * Whether this option can be provided multiple times. + * If `true`, all values will be collected in an array. + * If `false`, values for the option are last-wins. + * @default false. + */ + multiple?: boolean | undefined; + /** + * A single character alias for the option. + */ + short?: string | undefined; + /** + * The default option value when it is not set by args. + * It must be of the same type as the the `type` property. + * When `multiple` is `true`, it must be an array. + * @since v18.11.0 + */ + default?: string | boolean | string[] | boolean[] | undefined; + } + + interface ParseArgsOptionsConfig { + [longOption: string]: ParseArgsOptionConfig; + } + + export interface ParseArgsConfig { + /** + * Array of argument strings. + */ + args?: string[] | undefined; + /** + * Used to describe arguments known to the parser. + */ + options?: ParseArgsOptionsConfig | undefined; + /** + * Should an error be thrown when unknown arguments are encountered, + * or when arguments are passed that do not match the `type` configured in `options`. + * @default true + */ + strict?: boolean | undefined; + /** + * Whether this command accepts positional arguments. + */ + allowPositionals?: boolean | undefined; + /** + * Return the parsed tokens. This is useful for extending the built-in behavior, + * from adding additional checks through to reprocessing the tokens in different ways. + * @default false + */ + tokens?: boolean | undefined; + } + + /* + IfDefaultsTrue and IfDefaultsFalse are helpers to handle default values for missing boolean properties. + TypeScript does not have exact types for objects: https://github.com/microsoft/TypeScript/issues/12936 + This means it is impossible to distinguish between "field X is definitely not present" and "field X may or may not be present". + But we expect users to generally provide their config inline or `as const`, which means TS will always know whether a given field is present. + So this helper treats "not definitely present" (i.e., not `extends boolean`) as being "definitely not present", i.e. it should have its default value. + This is technically incorrect but is a much nicer UX for the common case. + The IfDefaultsTrue version is for things which default to true; the IfDefaultsFalse version is for things which default to false. + */ + type IfDefaultsTrue = T extends true ? IfTrue + : T extends false ? IfFalse + : IfTrue; + + // we put the `extends false` condition first here because `undefined` compares like `any` when `strictNullChecks: false` + type IfDefaultsFalse = T extends false ? IfFalse + : T extends true ? IfTrue + : IfFalse; + + type ExtractOptionValue = IfDefaultsTrue< + T["strict"], + O["type"] extends "string" ? string : O["type"] extends "boolean" ? boolean : string | boolean, + string | boolean + >; + + type ParsedValues = + & IfDefaultsTrue + & (T["options"] extends ParseArgsOptionsConfig ? { + -readonly [LongOption in keyof T["options"]]: IfDefaultsFalse< + T["options"][LongOption]["multiple"], + undefined | Array>, + undefined | ExtractOptionValue + >; + } + : {}); + + type ParsedPositionals = IfDefaultsTrue< + T["strict"], + IfDefaultsFalse, + IfDefaultsTrue + >; + + type PreciseTokenForOptions< + K extends string, + O extends ParseArgsOptionConfig, + > = O["type"] extends "string" ? { + kind: "option"; + index: number; + name: K; + rawName: string; + value: string; + inlineValue: boolean; + } + : O["type"] extends "boolean" ? { + kind: "option"; + index: number; + name: K; + rawName: string; + value: undefined; + inlineValue: undefined; + } + : OptionToken & { name: K }; + + type TokenForOptions< + T extends ParseArgsConfig, + K extends keyof T["options"] = keyof T["options"], + > = K extends unknown + ? T["options"] extends ParseArgsOptionsConfig ? PreciseTokenForOptions + : OptionToken + : never; + + type ParsedOptionToken = IfDefaultsTrue, OptionToken>; + + type ParsedPositionalToken = IfDefaultsTrue< + T["strict"], + IfDefaultsFalse, + IfDefaultsTrue + >; + + type ParsedTokens = Array< + ParsedOptionToken | ParsedPositionalToken | { kind: "option-terminator"; index: number } + >; + + type PreciseParsedResults = IfDefaultsFalse< + T["tokens"], + { + values: ParsedValues; + positionals: ParsedPositionals; + tokens: ParsedTokens; + }, + { + values: ParsedValues; + positionals: ParsedPositionals; + } + >; + + type OptionToken = + | { kind: "option"; index: number; name: string; rawName: string; value: string; inlineValue: boolean } + | { + kind: "option"; + index: number; + name: string; + rawName: string; + value: undefined; + inlineValue: undefined; + }; + + type Token = + | OptionToken + | { kind: "positional"; index: number; value: string } + | { kind: "option-terminator"; index: number }; + + // If ParseArgsConfig extends T, then the user passed config constructed elsewhere. + // So we can't rely on the `"not definitely present" implies "definitely not present"` assumption mentioned above. + type ParsedResults = ParseArgsConfig extends T ? { + values: { [longOption: string]: undefined | string | boolean | Array }; + positionals: string[]; + tokens?: Token[]; + } + : PreciseParsedResults; + + /** + * @since v18.13.0 + */ + export class MIMEType { + /** + * Creates a new MIMEType object by parsing the input. + * + * A `TypeError` will be thrown if the `input` is not a valid MIME. + * Note that an effort will be made to coerce the given values into strings. + * @param input The input MIME to parse. + */ + constructor(input: string | { toString: () => string }); + + /** + * Gets and sets the type portion of the MIME. + */ + type: string; + + /** + * Gets and sets the subtype portion of the MIME. + */ + subtype: string; + + /** + * Gets the essence of the MIME. + * + * Use `mime.type` or `mime.subtype` to alter the MIME. + */ + readonly essence: string; + + /** + * Gets the `MIMEParams` object representing the parameters of the MIME. + */ + readonly params: MIMEParams; + + /** + * Returns the serialized MIME. + * + * Because of the need for standard compliance, this method + * does not allow users to customize the serialization process of the MIME. + */ + toString(): string; + } + + /** + * @since v18.13.0 + */ + export class MIMEParams { + /** + * Remove all name-value pairs whose name is `name`. + */ + delete(name: string): void; + /** + * Returns an iterator over each of the name-value pairs in the parameters. + */ + entries(): IterableIterator<[name: string, value: string]>; + /** + * Returns the value of the first name-value pair whose name is `name`. + * If there are no such pairs, `null` is returned. + */ + get(name: string): string | null; + /** + * Returns `true` if there is at least one name-value pair whose name is `name`. + */ + has(name: string): boolean; + /** + * Returns an iterator over the names of each name-value pair. + */ + keys(): IterableIterator; + /** + * Sets the value in the `MIMEParams` object associated with `name` to `value`. + * If there are any pre-existing name-value pairs whose names are `name`, + * set the first such pair's value to `value`. + */ + set(name: string, value: string): void; + /** + * Returns an iterator over the values of each name-value pair. + */ + values(): IterableIterator; + /** + * Returns an iterator over each of the name-value pairs in the parameters. + */ + [Symbol.iterator]: typeof MIMEParams.prototype.entries; + } +} +declare module "util/types" { + import { KeyObject, webcrypto } from "node:crypto"; + /** + * Returns `true` if the value is a built-in [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) or + * [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instance. + * + * See also `util.types.isArrayBuffer()` and `util.types.isSharedArrayBuffer()`. + * + * ```js + * util.types.isAnyArrayBuffer(new ArrayBuffer()); // Returns true + * util.types.isAnyArrayBuffer(new SharedArrayBuffer()); // Returns true + * ``` + * @since v10.0.0 + */ + function isAnyArrayBuffer(object: unknown): object is ArrayBufferLike; + /** + * Returns `true` if the value is an `arguments` object. + * + * ```js + * function foo() { + * util.types.isArgumentsObject(arguments); // Returns true + * } + * ``` + * @since v10.0.0 + */ + function isArgumentsObject(object: unknown): object is IArguments; + /** + * Returns `true` if the value is a built-in [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) instance. + * This does _not_ include [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instances. Usually, it is + * desirable to test for both; See `util.types.isAnyArrayBuffer()` for that. + * + * ```js + * util.types.isArrayBuffer(new ArrayBuffer()); // Returns true + * util.types.isArrayBuffer(new SharedArrayBuffer()); // Returns false + * ``` + * @since v10.0.0 + */ + function isArrayBuffer(object: unknown): object is ArrayBuffer; + /** + * Returns `true` if the value is an instance of one of the [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) views, such as typed + * array objects or [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView). Equivalent to + * [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView). + * + * ```js + * util.types.isArrayBufferView(new Int8Array()); // true + * util.types.isArrayBufferView(Buffer.from('hello world')); // true + * util.types.isArrayBufferView(new DataView(new ArrayBuffer(16))); // true + * util.types.isArrayBufferView(new ArrayBuffer()); // false + * ``` + * @since v10.0.0 + */ + function isArrayBufferView(object: unknown): object is NodeJS.ArrayBufferView; + /** + * Returns `true` if the value is an [async function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function). + * This only reports back what the JavaScript engine is seeing; + * in particular, the return value may not match the original source code if + * a transpilation tool was used. + * + * ```js + * util.types.isAsyncFunction(function foo() {}); // Returns false + * util.types.isAsyncFunction(async function foo() {}); // Returns true + * ``` + * @since v10.0.0 + */ + function isAsyncFunction(object: unknown): boolean; + /** + * Returns `true` if the value is a `BigInt64Array` instance. + * + * ```js + * util.types.isBigInt64Array(new BigInt64Array()); // Returns true + * util.types.isBigInt64Array(new BigUint64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isBigInt64Array(value: unknown): value is BigInt64Array; + /** + * Returns `true` if the value is a `BigUint64Array` instance. + * + * ```js + * util.types.isBigUint64Array(new BigInt64Array()); // Returns false + * util.types.isBigUint64Array(new BigUint64Array()); // Returns true + * ``` + * @since v10.0.0 + */ + function isBigUint64Array(value: unknown): value is BigUint64Array; + /** + * Returns `true` if the value is a boolean object, e.g. created + * by `new Boolean()`. + * + * ```js + * util.types.isBooleanObject(false); // Returns false + * util.types.isBooleanObject(true); // Returns false + * util.types.isBooleanObject(new Boolean(false)); // Returns true + * util.types.isBooleanObject(new Boolean(true)); // Returns true + * util.types.isBooleanObject(Boolean(false)); // Returns false + * util.types.isBooleanObject(Boolean(true)); // Returns false + * ``` + * @since v10.0.0 + */ + function isBooleanObject(object: unknown): object is Boolean; + /** + * Returns `true` if the value is any boxed primitive object, e.g. created + * by `new Boolean()`, `new String()` or `Object(Symbol())`. + * + * For example: + * + * ```js + * util.types.isBoxedPrimitive(false); // Returns false + * util.types.isBoxedPrimitive(new Boolean(false)); // Returns true + * util.types.isBoxedPrimitive(Symbol('foo')); // Returns false + * util.types.isBoxedPrimitive(Object(Symbol('foo'))); // Returns true + * util.types.isBoxedPrimitive(Object(BigInt(5))); // Returns true + * ``` + * @since v10.11.0 + */ + function isBoxedPrimitive(object: unknown): object is String | Number | BigInt | Boolean | Symbol; + /** + * Returns `true` if the value is a built-in [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) instance. + * + * ```js + * const ab = new ArrayBuffer(20); + * util.types.isDataView(new DataView(ab)); // Returns true + * util.types.isDataView(new Float64Array()); // Returns false + * ``` + * + * See also [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView). + * @since v10.0.0 + */ + function isDataView(object: unknown): object is DataView; + /** + * Returns `true` if the value is a built-in [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) instance. + * + * ```js + * util.types.isDate(new Date()); // Returns true + * ``` + * @since v10.0.0 + */ + function isDate(object: unknown): object is Date; + /** + * Returns `true` if the value is a native `External` value. + * + * A native `External` value is a special type of object that contains a + * raw C++ pointer (`void*`) for access from native code, and has no other + * properties. Such objects are created either by Node.js internals or native + * addons. In JavaScript, they are [frozen](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze) objects with a`null` prototype. + * + * ```c + * #include + * #include + * napi_value result; + * static napi_value MyNapi(napi_env env, napi_callback_info info) { + * int* raw = (int*) malloc(1024); + * napi_status status = napi_create_external(env, (void*) raw, NULL, NULL, &result); + * if (status != napi_ok) { + * napi_throw_error(env, NULL, "napi_create_external failed"); + * return NULL; + * } + * return result; + * } + * ... + * DECLARE_NAPI_PROPERTY("myNapi", MyNapi) + * ... + * ``` + * + * ```js + * const native = require('napi_addon.node'); + * const data = native.myNapi(); + * util.types.isExternal(data); // returns true + * util.types.isExternal(0); // returns false + * util.types.isExternal(new String('foo')); // returns false + * ``` + * + * For further information on `napi_create_external`, refer to `napi_create_external()`. + * @since v10.0.0 + */ + function isExternal(object: unknown): boolean; + /** + * Returns `true` if the value is a built-in [`Float32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float32Array) instance. + * + * ```js + * util.types.isFloat32Array(new ArrayBuffer()); // Returns false + * util.types.isFloat32Array(new Float32Array()); // Returns true + * util.types.isFloat32Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isFloat32Array(object: unknown): object is Float32Array; + /** + * Returns `true` if the value is a built-in [`Float64Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float64Array) instance. + * + * ```js + * util.types.isFloat64Array(new ArrayBuffer()); // Returns false + * util.types.isFloat64Array(new Uint8Array()); // Returns false + * util.types.isFloat64Array(new Float64Array()); // Returns true + * ``` + * @since v10.0.0 + */ + function isFloat64Array(object: unknown): object is Float64Array; + /** + * Returns `true` if the value is a generator function. + * This only reports back what the JavaScript engine is seeing; + * in particular, the return value may not match the original source code if + * a transpilation tool was used. + * + * ```js + * util.types.isGeneratorFunction(function foo() {}); // Returns false + * util.types.isGeneratorFunction(function* foo() {}); // Returns true + * ``` + * @since v10.0.0 + */ + function isGeneratorFunction(object: unknown): object is GeneratorFunction; + /** + * Returns `true` if the value is a generator object as returned from a + * built-in generator function. + * This only reports back what the JavaScript engine is seeing; + * in particular, the return value may not match the original source code if + * a transpilation tool was used. + * + * ```js + * function* foo() {} + * const generator = foo(); + * util.types.isGeneratorObject(generator); // Returns true + * ``` + * @since v10.0.0 + */ + function isGeneratorObject(object: unknown): object is Generator; + /** + * Returns `true` if the value is a built-in [`Int8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int8Array) instance. + * + * ```js + * util.types.isInt8Array(new ArrayBuffer()); // Returns false + * util.types.isInt8Array(new Int8Array()); // Returns true + * util.types.isInt8Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isInt8Array(object: unknown): object is Int8Array; + /** + * Returns `true` if the value is a built-in [`Int16Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int16Array) instance. + * + * ```js + * util.types.isInt16Array(new ArrayBuffer()); // Returns false + * util.types.isInt16Array(new Int16Array()); // Returns true + * util.types.isInt16Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isInt16Array(object: unknown): object is Int16Array; + /** + * Returns `true` if the value is a built-in [`Int32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int32Array) instance. + * + * ```js + * util.types.isInt32Array(new ArrayBuffer()); // Returns false + * util.types.isInt32Array(new Int32Array()); // Returns true + * util.types.isInt32Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isInt32Array(object: unknown): object is Int32Array; + /** + * Returns `true` if the value is a built-in [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) instance. + * + * ```js + * util.types.isMap(new Map()); // Returns true + * ``` + * @since v10.0.0 + */ + function isMap( + object: T | {}, + ): object is T extends ReadonlyMap ? (unknown extends T ? never : ReadonlyMap) + : Map; + /** + * Returns `true` if the value is an iterator returned for a built-in [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) instance. + * + * ```js + * const map = new Map(); + * util.types.isMapIterator(map.keys()); // Returns true + * util.types.isMapIterator(map.values()); // Returns true + * util.types.isMapIterator(map.entries()); // Returns true + * util.types.isMapIterator(map[Symbol.iterator]()); // Returns true + * ``` + * @since v10.0.0 + */ + function isMapIterator(object: unknown): boolean; + /** + * Returns `true` if the value is an instance of a [Module Namespace Object](https://tc39.github.io/ecma262/#sec-module-namespace-exotic-objects). + * + * ```js + * import * as ns from './a.js'; + * + * util.types.isModuleNamespaceObject(ns); // Returns true + * ``` + * @since v10.0.0 + */ + function isModuleNamespaceObject(value: unknown): boolean; + /** + * Returns `true` if the value is an instance of a built-in `Error` type. + * + * ```js + * util.types.isNativeError(new Error()); // Returns true + * util.types.isNativeError(new TypeError()); // Returns true + * util.types.isNativeError(new RangeError()); // Returns true + * ``` + * @since v10.0.0 + */ + function isNativeError(object: unknown): object is Error; + /** + * Returns `true` if the value is a number object, e.g. created + * by `new Number()`. + * + * ```js + * util.types.isNumberObject(0); // Returns false + * util.types.isNumberObject(new Number(0)); // Returns true + * ``` + * @since v10.0.0 + */ + function isNumberObject(object: unknown): object is Number; + /** + * Returns `true` if the value is a built-in [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). + * + * ```js + * util.types.isPromise(Promise.resolve(42)); // Returns true + * ``` + * @since v10.0.0 + */ + function isPromise(object: unknown): object is Promise; + /** + * Returns `true` if the value is a [`Proxy`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) instance. + * + * ```js + * const target = {}; + * const proxy = new Proxy(target, {}); + * util.types.isProxy(target); // Returns false + * util.types.isProxy(proxy); // Returns true + * ``` + * @since v10.0.0 + */ + function isProxy(object: unknown): boolean; + /** + * Returns `true` if the value is a regular expression object. + * + * ```js + * util.types.isRegExp(/abc/); // Returns true + * util.types.isRegExp(new RegExp('abc')); // Returns true + * ``` + * @since v10.0.0 + */ + function isRegExp(object: unknown): object is RegExp; + /** + * Returns `true` if the value is a built-in [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) instance. + * + * ```js + * util.types.isSet(new Set()); // Returns true + * ``` + * @since v10.0.0 + */ + function isSet( + object: T | {}, + ): object is T extends ReadonlySet ? (unknown extends T ? never : ReadonlySet) : Set; + /** + * Returns `true` if the value is an iterator returned for a built-in [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) instance. + * + * ```js + * const set = new Set(); + * util.types.isSetIterator(set.keys()); // Returns true + * util.types.isSetIterator(set.values()); // Returns true + * util.types.isSetIterator(set.entries()); // Returns true + * util.types.isSetIterator(set[Symbol.iterator]()); // Returns true + * ``` + * @since v10.0.0 + */ + function isSetIterator(object: unknown): boolean; + /** + * Returns `true` if the value is a built-in [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instance. + * This does _not_ include [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) instances. Usually, it is + * desirable to test for both; See `util.types.isAnyArrayBuffer()` for that. + * + * ```js + * util.types.isSharedArrayBuffer(new ArrayBuffer()); // Returns false + * util.types.isSharedArrayBuffer(new SharedArrayBuffer()); // Returns true + * ``` + * @since v10.0.0 + */ + function isSharedArrayBuffer(object: unknown): object is SharedArrayBuffer; + /** + * Returns `true` if the value is a string object, e.g. created + * by `new String()`. + * + * ```js + * util.types.isStringObject('foo'); // Returns false + * util.types.isStringObject(new String('foo')); // Returns true + * ``` + * @since v10.0.0 + */ + function isStringObject(object: unknown): object is String; + /** + * Returns `true` if the value is a symbol object, created + * by calling `Object()` on a `Symbol` primitive. + * + * ```js + * const symbol = Symbol('foo'); + * util.types.isSymbolObject(symbol); // Returns false + * util.types.isSymbolObject(Object(symbol)); // Returns true + * ``` + * @since v10.0.0 + */ + function isSymbolObject(object: unknown): object is Symbol; + /** + * Returns `true` if the value is a built-in [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) instance. + * + * ```js + * util.types.isTypedArray(new ArrayBuffer()); // Returns false + * util.types.isTypedArray(new Uint8Array()); // Returns true + * util.types.isTypedArray(new Float64Array()); // Returns true + * ``` + * + * See also [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView). + * @since v10.0.0 + */ + function isTypedArray(object: unknown): object is NodeJS.TypedArray; + /** + * Returns `true` if the value is a built-in [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) instance. + * + * ```js + * util.types.isUint8Array(new ArrayBuffer()); // Returns false + * util.types.isUint8Array(new Uint8Array()); // Returns true + * util.types.isUint8Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint8Array(object: unknown): object is Uint8Array; + /** + * Returns `true` if the value is a built-in [`Uint8ClampedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8ClampedArray) instance. + * + * ```js + * util.types.isUint8ClampedArray(new ArrayBuffer()); // Returns false + * util.types.isUint8ClampedArray(new Uint8ClampedArray()); // Returns true + * util.types.isUint8ClampedArray(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint8ClampedArray(object: unknown): object is Uint8ClampedArray; + /** + * Returns `true` if the value is a built-in [`Uint16Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint16Array) instance. + * + * ```js + * util.types.isUint16Array(new ArrayBuffer()); // Returns false + * util.types.isUint16Array(new Uint16Array()); // Returns true + * util.types.isUint16Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint16Array(object: unknown): object is Uint16Array; + /** + * Returns `true` if the value is a built-in [`Uint32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint32Array) instance. + * + * ```js + * util.types.isUint32Array(new ArrayBuffer()); // Returns false + * util.types.isUint32Array(new Uint32Array()); // Returns true + * util.types.isUint32Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint32Array(object: unknown): object is Uint32Array; + /** + * Returns `true` if the value is a built-in [`WeakMap`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap) instance. + * + * ```js + * util.types.isWeakMap(new WeakMap()); // Returns true + * ``` + * @since v10.0.0 + */ + function isWeakMap(object: unknown): object is WeakMap; + /** + * Returns `true` if the value is a built-in [`WeakSet`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet) instance. + * + * ```js + * util.types.isWeakSet(new WeakSet()); // Returns true + * ``` + * @since v10.0.0 + */ + function isWeakSet(object: unknown): object is WeakSet; + /** + * Returns `true` if `value` is a `KeyObject`, `false` otherwise. + * @since v16.2.0 + */ + function isKeyObject(object: unknown): object is KeyObject; + /** + * Returns `true` if `value` is a `CryptoKey`, `false` otherwise. + * @since v16.2.0 + */ + function isCryptoKey(object: unknown): object is webcrypto.CryptoKey; +} +declare module "node:util" { + export * from "util"; +} +declare module "node:util/types" { + export * from "util/types"; +} diff --git a/backend/node_modules/@types/node/v8.d.ts b/backend/node_modules/@types/node/v8.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..762faabaa2a61f47073c0d7ca0afd2a55a70de15 --- /dev/null +++ b/backend/node_modules/@types/node/v8.d.ts @@ -0,0 +1,753 @@ +/** + * The `node:v8` module exposes APIs that are specific to the version of [V8](https://developers.google.com/v8/) built into the Node.js binary. It can be accessed using: + * + * ```js + * const v8 = require('node:v8'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.19.0/lib/v8.js) + */ +declare module "v8" { + import { Readable } from "node:stream"; + interface HeapSpaceInfo { + space_name: string; + space_size: number; + space_used_size: number; + space_available_size: number; + physical_space_size: number; + } + // ** Signifies if the --zap_code_space option is enabled or not. 1 == enabled, 0 == disabled. */ + type DoesZapCodeSpaceFlag = 0 | 1; + interface HeapInfo { + total_heap_size: number; + total_heap_size_executable: number; + total_physical_size: number; + total_available_size: number; + used_heap_size: number; + heap_size_limit: number; + malloced_memory: number; + peak_malloced_memory: number; + does_zap_garbage: DoesZapCodeSpaceFlag; + number_of_native_contexts: number; + number_of_detached_contexts: number; + total_global_handles_size: number; + used_global_handles_size: number; + external_memory: number; + } + interface HeapCodeStatistics { + code_and_metadata_size: number; + bytecode_and_metadata_size: number; + external_script_source_size: number; + } + /** + * Returns an integer representing a version tag derived from the V8 version, + * command-line flags, and detected CPU features. This is useful for determining + * whether a `vm.Script` `cachedData` buffer is compatible with this instance + * of V8. + * + * ```js + * console.log(v8.cachedDataVersionTag()); // 3947234607 + * // The value returned by v8.cachedDataVersionTag() is derived from the V8 + * // version, command-line flags, and detected CPU features. Test that the value + * // does indeed update when flags are toggled. + * v8.setFlagsFromString('--allow_natives_syntax'); + * console.log(v8.cachedDataVersionTag()); // 183726201 + * ``` + * @since v8.0.0 + */ + function cachedDataVersionTag(): number; + /** + * Returns an object with the following properties: + * + * `does_zap_garbage` is a 0/1 boolean, which signifies whether the`--zap_code_space` option is enabled or not. This makes V8 overwrite heap + * garbage with a bit pattern. The RSS footprint (resident set size) gets bigger + * because it continuously touches all heap pages and that makes them less likely + * to get swapped out by the operating system. + * + * `number_of_native_contexts` The value of native\_context is the number of the + * top-level contexts currently active. Increase of this number over time indicates + * a memory leak. + * + * `number_of_detached_contexts` The value of detached\_context is the number + * of contexts that were detached and not yet garbage collected. This number + * being non-zero indicates a potential memory leak. + * + * `total_global_handles_size` The value of total\_global\_handles\_size is the + * total memory size of V8 global handles. + * + * `used_global_handles_size` The value of used\_global\_handles\_size is the + * used memory size of V8 global handles. + * + * `external_memory` The value of external\_memory is the memory size of array + * buffers and external strings. + * + * ```js + * { + * total_heap_size: 7326976, + * total_heap_size_executable: 4194304, + * total_physical_size: 7326976, + * total_available_size: 1152656, + * used_heap_size: 3476208, + * heap_size_limit: 1535115264, + * malloced_memory: 16384, + * peak_malloced_memory: 1127496, + * does_zap_garbage: 0, + * number_of_native_contexts: 1, + * number_of_detached_contexts: 0, + * total_global_handles_size: 8192, + * used_global_handles_size: 3296, + * external_memory: 318824 + * } + * ``` + * @since v1.0.0 + */ + function getHeapStatistics(): HeapInfo; + /** + * Returns statistics about the V8 heap spaces, i.e. the segments which make up + * the V8 heap. Neither the ordering of heap spaces, nor the availability of a + * heap space can be guaranteed as the statistics are provided via the + * V8 [`GetHeapSpaceStatistics`](https://v8docs.nodesource.com/node-13.2/d5/dda/classv8_1_1_isolate.html#ac673576f24fdc7a33378f8f57e1d13a4) function and may change from one V8 version to the + * next. + * + * The value returned is an array of objects containing the following properties: + * + * ```json + * [ + * { + * "space_name": "new_space", + * "space_size": 2063872, + * "space_used_size": 951112, + * "space_available_size": 80824, + * "physical_space_size": 2063872 + * }, + * { + * "space_name": "old_space", + * "space_size": 3090560, + * "space_used_size": 2493792, + * "space_available_size": 0, + * "physical_space_size": 3090560 + * }, + * { + * "space_name": "code_space", + * "space_size": 1260160, + * "space_used_size": 644256, + * "space_available_size": 960, + * "physical_space_size": 1260160 + * }, + * { + * "space_name": "map_space", + * "space_size": 1094160, + * "space_used_size": 201608, + * "space_available_size": 0, + * "physical_space_size": 1094160 + * }, + * { + * "space_name": "large_object_space", + * "space_size": 0, + * "space_used_size": 0, + * "space_available_size": 1490980608, + * "physical_space_size": 0 + * } + * ] + * ``` + * @since v6.0.0 + */ + function getHeapSpaceStatistics(): HeapSpaceInfo[]; + /** + * The `v8.setFlagsFromString()` method can be used to programmatically set + * V8 command-line flags. This method should be used with care. Changing settings + * after the VM has started may result in unpredictable behavior, including + * crashes and data loss; or it may simply do nothing. + * + * The V8 options available for a version of Node.js may be determined by running`node --v8-options`. + * + * Usage: + * + * ```js + * // Print GC events to stdout for one minute. + * const v8 = require('node:v8'); + * v8.setFlagsFromString('--trace_gc'); + * setTimeout(() => { v8.setFlagsFromString('--notrace_gc'); }, 60e3); + * ``` + * @since v1.0.0 + */ + function setFlagsFromString(flags: string): void; + /** + * Generates a snapshot of the current V8 heap and returns a Readable + * Stream that may be used to read the JSON serialized representation. + * This JSON stream format is intended to be used with tools such as + * Chrome DevTools. The JSON schema is undocumented and specific to the + * V8 engine. Therefore, the schema may change from one version of V8 to the next. + * + * Creating a heap snapshot requires memory about twice the size of the heap at + * the time the snapshot is created. This results in the risk of OOM killers + * terminating the process. + * + * Generating a snapshot is a synchronous operation which blocks the event loop + * for a duration depending on the heap size. + * + * ```js + * // Print heap snapshot to the console + * const v8 = require('node:v8'); + * const stream = v8.getHeapSnapshot(); + * stream.pipe(process.stdout); + * ``` + * @since v11.13.0 + * @return A Readable Stream containing the V8 heap snapshot + */ + function getHeapSnapshot(): Readable; + /** + * Generates a snapshot of the current V8 heap and writes it to a JSON + * file. This file is intended to be used with tools such as Chrome + * DevTools. The JSON schema is undocumented and specific to the V8 + * engine, and may change from one version of V8 to the next. + * + * A heap snapshot is specific to a single V8 isolate. When using `worker threads`, a heap snapshot generated from the main thread will + * not contain any information about the workers, and vice versa. + * + * Creating a heap snapshot requires memory about twice the size of the heap at + * the time the snapshot is created. This results in the risk of OOM killers + * terminating the process. + * + * Generating a snapshot is a synchronous operation which blocks the event loop + * for a duration depending on the heap size. + * + * ```js + * const { writeHeapSnapshot } = require('node:v8'); + * const { + * Worker, + * isMainThread, + * parentPort, + * } = require('node:worker_threads'); + * + * if (isMainThread) { + * const worker = new Worker(__filename); + * + * worker.once('message', (filename) => { + * console.log(`worker heapdump: ${filename}`); + * // Now get a heapdump for the main thread. + * console.log(`main thread heapdump: ${writeHeapSnapshot()}`); + * }); + * + * // Tell the worker to create a heapdump. + * worker.postMessage('heapdump'); + * } else { + * parentPort.once('message', (message) => { + * if (message === 'heapdump') { + * // Generate a heapdump for the worker + * // and return the filename to the parent. + * parentPort.postMessage(writeHeapSnapshot()); + * } + * }); + * } + * ``` + * @since v11.13.0 + * @param filename The file path where the V8 heap snapshot is to be saved. If not specified, a file name with the pattern `'Heap-${yyyymmdd}-${hhmmss}-${pid}-${thread_id}.heapsnapshot'` will be + * generated, where `{pid}` will be the PID of the Node.js process, `{thread_id}` will be `0` when `writeHeapSnapshot()` is called from the main Node.js thread or the id of a + * worker thread. + * @return The filename where the snapshot was saved. + */ + function writeHeapSnapshot(filename?: string): string; + /** + * Get statistics about code and its metadata in the heap, see + * V8 [`GetHeapCodeAndMetadataStatistics`](https://v8docs.nodesource.com/node-13.2/d5/dda/classv8_1_1_isolate.html#a6079122af17612ef54ef3348ce170866) API. Returns an object with the + * following properties: + * + * ```js + * { + * code_and_metadata_size: 212208, + * bytecode_and_metadata_size: 161368, + * external_script_source_size: 1410794, + * cpu_profiler_metadata_size: 0, + * } + * ``` + * @since v12.8.0 + */ + function getHeapCodeStatistics(): HeapCodeStatistics; + /** + * @since v8.0.0 + */ + class Serializer { + /** + * Writes out a header, which includes the serialization format version. + */ + writeHeader(): void; + /** + * Serializes a JavaScript value and adds the serialized representation to the + * internal buffer. + * + * This throws an error if `value` cannot be serialized. + */ + writeValue(val: any): boolean; + /** + * Returns the stored internal buffer. This serializer should not be used once + * the buffer is released. Calling this method results in undefined behavior + * if a previous write has failed. + */ + releaseBuffer(): Buffer; + /** + * Marks an `ArrayBuffer` as having its contents transferred out of band. + * Pass the corresponding `ArrayBuffer` in the deserializing context to `deserializer.transferArrayBuffer()`. + * @param id A 32-bit unsigned integer. + * @param arrayBuffer An `ArrayBuffer` instance. + */ + transferArrayBuffer(id: number, arrayBuffer: ArrayBuffer): void; + /** + * Write a raw 32-bit unsigned integer. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeUint32(value: number): void; + /** + * Write a raw 64-bit unsigned integer, split into high and low 32-bit parts. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeUint64(hi: number, lo: number): void; + /** + * Write a JS `number` value. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeDouble(value: number): void; + /** + * Write raw bytes into the serializer's internal buffer. The deserializer + * will require a way to compute the length of the buffer. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeRawBytes(buffer: NodeJS.TypedArray): void; + } + /** + * A subclass of `Serializer` that serializes `TypedArray`(in particular `Buffer`) and `DataView` objects as host objects, and only + * stores the part of their underlying `ArrayBuffer`s that they are referring to. + * @since v8.0.0 + */ + class DefaultSerializer extends Serializer {} + /** + * @since v8.0.0 + */ + class Deserializer { + constructor(data: NodeJS.TypedArray); + /** + * Reads and validates a header (including the format version). + * May, for example, reject an invalid or unsupported wire format. In that case, + * an `Error` is thrown. + */ + readHeader(): boolean; + /** + * Deserializes a JavaScript value from the buffer and returns it. + */ + readValue(): any; + /** + * Marks an `ArrayBuffer` as having its contents transferred out of band. + * Pass the corresponding `ArrayBuffer` in the serializing context to `serializer.transferArrayBuffer()` (or return the `id` from `serializer._getSharedArrayBufferId()` in the case of + * `SharedArrayBuffer`s). + * @param id A 32-bit unsigned integer. + * @param arrayBuffer An `ArrayBuffer` instance. + */ + transferArrayBuffer(id: number, arrayBuffer: ArrayBuffer): void; + /** + * Reads the underlying wire format version. Likely mostly to be useful to + * legacy code reading old wire format versions. May not be called before`.readHeader()`. + */ + getWireFormatVersion(): number; + /** + * Read a raw 32-bit unsigned integer and return it. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readUint32(): number; + /** + * Read a raw 64-bit unsigned integer and return it as an array `[hi, lo]`with two 32-bit unsigned integer entries. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readUint64(): [number, number]; + /** + * Read a JS `number` value. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readDouble(): number; + /** + * Read raw bytes from the deserializer's internal buffer. The `length` parameter + * must correspond to the length of the buffer that was passed to `serializer.writeRawBytes()`. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readRawBytes(length: number): Buffer; + } + /** + * A subclass of `Deserializer` corresponding to the format written by `DefaultSerializer`. + * @since v8.0.0 + */ + class DefaultDeserializer extends Deserializer {} + /** + * Uses a `DefaultSerializer` to serialize `value` into a buffer. + * + * `ERR_BUFFER_TOO_LARGE` will be thrown when trying to + * serialize a huge object which requires buffer + * larger than `buffer.constants.MAX_LENGTH`. + * @since v8.0.0 + */ + function serialize(value: any): Buffer; + /** + * Uses a `DefaultDeserializer` with default options to read a JS value + * from a buffer. + * @since v8.0.0 + * @param buffer A buffer returned by {@link serialize}. + */ + function deserialize(buffer: NodeJS.TypedArray): any; + /** + * The `v8.takeCoverage()` method allows the user to write the coverage started by `NODE_V8_COVERAGE` to disk on demand. This method can be invoked multiple + * times during the lifetime of the process. Each time the execution counter will + * be reset and a new coverage report will be written to the directory specified + * by `NODE_V8_COVERAGE`. + * + * When the process is about to exit, one last coverage will still be written to + * disk unless {@link stopCoverage} is invoked before the process exits. + * @since v15.1.0, v14.18.0, v12.22.0 + */ + function takeCoverage(): void; + /** + * The `v8.stopCoverage()` method allows the user to stop the coverage collection + * started by `NODE_V8_COVERAGE`, so that V8 can release the execution count + * records and optimize code. This can be used in conjunction with {@link takeCoverage} if the user wants to collect the coverage on demand. + * @since v15.1.0, v14.18.0, v12.22.0 + */ + function stopCoverage(): void; + /** + * The API is a no-op if `--heapsnapshot-near-heap-limit` is already set from the command line or the API is called more than once. + * `limit` must be a positive integer. See [`--heapsnapshot-near-heap-limit`](https://nodejs.org/docs/latest-v18.x/api/cli.html#--heapsnapshot-near-heap-limitmax_count) for more information. + * @experimental + * @since v18.10.0, v16.18.0 + */ + function setHeapSnapshotNearHeapLimit(limit: number): void; + /** + * This API collects GC data in current thread. + * @since v18.15.0 + */ + class GCProfiler { + /** + * Start collecting GC data. + * @since v18.15.0 + */ + start(): void; + /** + * Stop collecting GC data and return an object.The content of object + * is as follows. + * + * ```json + * { + * "version": 1, + * "startTime": 1674059033862, + * "statistics": [ + * { + * "gcType": "Scavenge", + * "beforeGC": { + * "heapStatistics": { + * "totalHeapSize": 5005312, + * "totalHeapSizeExecutable": 524288, + * "totalPhysicalSize": 5226496, + * "totalAvailableSize": 4341325216, + * "totalGlobalHandlesSize": 8192, + * "usedGlobalHandlesSize": 2112, + * "usedHeapSize": 4883840, + * "heapSizeLimit": 4345298944, + * "mallocedMemory": 254128, + * "externalMemory": 225138, + * "peakMallocedMemory": 181760 + * }, + * "heapSpaceStatistics": [ + * { + * "spaceName": "read_only_space", + * "spaceSize": 0, + * "spaceUsedSize": 0, + * "spaceAvailableSize": 0, + * "physicalSpaceSize": 0 + * } + * ] + * }, + * "cost": 1574.14, + * "afterGC": { + * "heapStatistics": { + * "totalHeapSize": 6053888, + * "totalHeapSizeExecutable": 524288, + * "totalPhysicalSize": 5500928, + * "totalAvailableSize": 4341101384, + * "totalGlobalHandlesSize": 8192, + * "usedGlobalHandlesSize": 2112, + * "usedHeapSize": 4059096, + * "heapSizeLimit": 4345298944, + * "mallocedMemory": 254128, + * "externalMemory": 225138, + * "peakMallocedMemory": 181760 + * }, + * "heapSpaceStatistics": [ + * { + * "spaceName": "read_only_space", + * "spaceSize": 0, + * "spaceUsedSize": 0, + * "spaceAvailableSize": 0, + * "physicalSpaceSize": 0 + * } + * ] + * } + * } + * ], + * "endTime": 1674059036865 + * } + * ``` + * + * Here's an example. + * + * ```js + * const { GCProfiler } = require('v8'); + * const profiler = new GCProfiler(); + * profiler.start(); + * setTimeout(() => { + * console.log(profiler.stop()); + * }, 1000); + * ``` + * @since v18.15.0 + */ + stop(): GCProfilerResult; + } + interface GCProfilerResult { + version: number; + startTime: number; + endTime: number; + statistics: Array<{ + gcType: string; + cost: number; + beforeGC: { + heapStatistics: HeapStatistics; + heapSpaceStatistics: HeapSpaceStatistics[]; + }; + afterGC: { + heapStatistics: HeapStatistics; + heapSpaceStatistics: HeapSpaceStatistics[]; + }; + }>; + } + interface HeapStatistics { + totalHeapSize: number; + totalHeapSizeExecutable: number; + totalPhysicalSize: number; + totalAvailableSize: number; + totalGlobalHandlesSize: number; + usedGlobalHandlesSize: number; + usedHeapSize: number; + heapSizeLimit: number; + mallocedMemory: number; + externalMemory: number; + peakMallocedMemory: number; + } + interface HeapSpaceStatistics { + spaceName: string; + spaceSize: number; + spaceUsedSize: number; + spaceAvailableSize: number; + physicalSpaceSize: number; + } + /** + * Called when a promise is constructed. This does not mean that corresponding before/after events will occur, only that the possibility exists. This will + * happen if a promise is created without ever getting a continuation. + * @since v17.1.0, v16.14.0 + * @param promise The promise being created. + * @param parent The promise continued from, if applicable. + */ + interface Init { + (promise: Promise, parent: Promise): void; + } + /** + * Called before a promise continuation executes. This can be in the form of `then()`, `catch()`, or `finally()` handlers or an await resuming. + * + * The before callback will be called 0 to N times. The before callback will typically be called 0 times if no continuation was ever made for the promise. + * The before callback may be called many times in the case where many continuations have been made from the same promise. + * @since v17.1.0, v16.14.0 + */ + interface Before { + (promise: Promise): void; + } + /** + * Called immediately after a promise continuation executes. This may be after a `then()`, `catch()`, or `finally()` handler or before an await after another await. + * @since v17.1.0, v16.14.0 + */ + interface After { + (promise: Promise): void; + } + /** + * Called when the promise receives a resolution or rejection value. This may occur synchronously in the case of {@link Promise.resolve()} or + * {@link Promise.reject()}. + * @since v17.1.0, v16.14.0 + */ + interface Settled { + (promise: Promise): void; + } + /** + * Key events in the lifetime of a promise have been categorized into four areas: creation of a promise, before/after a continuation handler is called or + * around an await, and when the promise resolves or rejects. + * + * Because promises are asynchronous resources whose lifecycle is tracked via the promise hooks mechanism, the `init()`, `before()`, `after()`, and + * `settled()` callbacks must not be async functions as they create more promises which would produce an infinite loop. + * @since v17.1.0, v16.14.0 + */ + interface HookCallbacks { + init?: Init; + before?: Before; + after?: After; + settled?: Settled; + } + interface PromiseHooks { + /** + * The `init` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param init The {@link Init | `init` callback} to call when a promise is created. + * @return Call to stop the hook. + */ + onInit: (init: Init) => Function; + /** + * The `settled` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param settled The {@link Settled | `settled` callback} to call when a promise is created. + * @return Call to stop the hook. + */ + onSettled: (settled: Settled) => Function; + /** + * The `before` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param before The {@link Before | `before` callback} to call before a promise continuation executes. + * @return Call to stop the hook. + */ + onBefore: (before: Before) => Function; + /** + * The `after` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param after The {@link After | `after` callback} to call after a promise continuation executes. + * @return Call to stop the hook. + */ + onAfter: (after: After) => Function; + /** + * Registers functions to be called for different lifetime events of each promise. + * The callbacks `init()`/`before()`/`after()`/`settled()` are called for the respective events during a promise's lifetime. + * All callbacks are optional. For example, if only promise creation needs to be tracked, then only the init callback needs to be passed. + * The hook callbacks must be plain functions. Providing async functions will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param callbacks The {@link HookCallbacks | Hook Callbacks} to register + * @return Used for disabling hooks + */ + createHook: (callbacks: HookCallbacks) => Function; + } + /** + * The `promiseHooks` interface can be used to track promise lifecycle events. + * @since v17.1.0, v16.14.0 + */ + const promiseHooks: PromiseHooks; + type StartupSnapshotCallbackFn = (args: any) => any; + interface StartupSnapshot { + /** + * Add a callback that will be called when the Node.js instance is about to get serialized into a snapshot and exit. + * This can be used to release resources that should not or cannot be serialized or to convert user data into a form more suitable for serialization. + * @since v18.6.0, v16.17.0 + */ + addSerializeCallback(callback: StartupSnapshotCallbackFn, data?: any): void; + /** + * Add a callback that will be called when the Node.js instance is deserialized from a snapshot. + * The `callback` and the `data` (if provided) will be serialized into the snapshot, they can be used to re-initialize the state of the application or + * to re-acquire resources that the application needs when the application is restarted from the snapshot. + * @since v18.6.0, v16.17.0 + */ + addDeserializeCallback(callback: StartupSnapshotCallbackFn, data?: any): void; + /** + * This sets the entry point of the Node.js application when it is deserialized from a snapshot. This can be called only once in the snapshot building script. + * If called, the deserialized application no longer needs an additional entry point script to start up and will simply invoke the callback along with the deserialized + * data (if provided), otherwise an entry point script still needs to be provided to the deserialized application. + * @since v18.6.0, v16.17.0 + */ + setDeserializeMainFunction(callback: StartupSnapshotCallbackFn, data?: any): void; + /** + * Returns true if the Node.js instance is run to build a snapshot. + * @since v18.6.0, v16.17.0 + */ + isBuildingSnapshot(): boolean; + } + /** + * The `v8.startupSnapshot` interface can be used to add serialization and deserialization hooks for custom startup snapshots. + * + * ```bash + * $ node --snapshot-blob snapshot.blob --build-snapshot entry.js + * # This launches a process with the snapshot + * $ node --snapshot-blob snapshot.blob + * ``` + * + * In the example above, `entry.js` can use methods from the `v8.startupSnapshot` interface to specify how to save information for custom objects + * in the snapshot during serialization + * and how the information can be used to synchronize these objects during deserialization of the snapshot. + * For example, if the `entry.js` contains the following script: + * + * ```js + * 'use strict'; + * + * const fs = require('node:fs'); + * const zlib = require('node:zlib'); + * const path = require('node:path'); + * const assert = require('node:assert'); + * + * const v8 = require('node:v8'); + * + * class BookShelf { + * storage = new Map(); + * + * // Reading a series of files from directory and store them into storage. + * constructor(directory, books) { + * for (const book of books) { + * this.storage.set(book, fs.readFileSync(path.join(directory, book))); + * } + * } + * + * static compressAll(shelf) { + * for (const [ book, content ] of shelf.storage) { + * shelf.storage.set(book, zlib.gzipSync(content)); + * } + * } + * + * static decompressAll(shelf) { + * for (const [ book, content ] of shelf.storage) { + * shelf.storage.set(book, zlib.gunzipSync(content)); + * } + * } + * } + * + * // __dirname here is where the snapshot script is placed + * // during snapshot building time. + * const shelf = new BookShelf(__dirname, [ + * 'book1.en_US.txt', + * 'book1.es_ES.txt', + * 'book2.zh_CN.txt', + * ]); + * + * assert(v8.startupSnapshot.isBuildingSnapshot()); + * // On snapshot serialization, compress the books to reduce size. + * v8.startupSnapshot.addSerializeCallback(BookShelf.compressAll, shelf); + * // On snapshot deserialization, decompress the books. + * v8.startupSnapshot.addDeserializeCallback(BookShelf.decompressAll, shelf); + * v8.startupSnapshot.setDeserializeMainFunction((shelf) => { + * // process.env and process.argv are refreshed during snapshot + * // deserialization. + * const lang = process.env.BOOK_LANG || 'en_US'; + * const book = process.argv[1]; + * const name = `${book}.${lang}.txt`; + * console.log(shelf.storage.get(name)); + * }, shelf); + * ``` + * + * The resulted binary will get print the data deserialized from the snapshot during start up, using the refreshed `process.env` and `process.argv` of the launched process: + * + * ```bash + * $ BOOK_LANG=es_ES node --snapshot-blob snapshot.blob book1 + * # Prints content of book1.es_ES.txt deserialized from the snapshot. + * ``` + * + * Currently the application deserialized from a user-land snapshot cannot be snapshotted again, so these APIs are only available to applications that are not deserialized from a user-land snapshot. + * + * @experimental + * @since v18.6.0, v16.17.0 + */ + const startupSnapshot: StartupSnapshot; +} +declare module "node:v8" { + export * from "v8"; +} diff --git a/backend/node_modules/@types/node/vm.d.ts b/backend/node_modules/@types/node/vm.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c63d1569c4107871679660f61f14d72e83c5a266 --- /dev/null +++ b/backend/node_modules/@types/node/vm.d.ts @@ -0,0 +1,667 @@ +/** + * The `vm` module enables compiling and running code within V8 Virtual + * Machine contexts. + * + * **The `vm` module is not a security** + * **mechanism. Do not use it to run untrusted code.** + * + * JavaScript code can be compiled and run immediately or + * compiled, saved, and run later. + * + * A common use case is to run the code in a different V8 Context. This means + * invoked code has a different global object than the invoking code. + * + * One can provide the context by `contextifying` an + * object. The invoked code treats any property in the context like a + * global variable. Any changes to global variables caused by the invoked + * code are reflected in the context object. + * + * ```js + * const vm = require('vm'); + * + * const x = 1; + * + * const context = { x: 2 }; + * vm.createContext(context); // Contextify the object. + * + * const code = 'x += 40; var y = 17;'; + * // `x` and `y` are global variables in the context. + * // Initially, x has the value 2 because that is the value of context.x. + * vm.runInContext(code, context); + * + * console.log(context.x); // 42 + * console.log(context.y); // 17 + * + * console.log(x); // 1; y is not defined. + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/vm.js) + */ +declare module "vm" { + import { ImportAttributes } from "node:module"; + interface Context extends NodeJS.Dict {} + interface BaseOptions { + /** + * Specifies the filename used in stack traces produced by this script. + * Default: `''`. + */ + filename?: string | undefined; + /** + * Specifies the line number offset that is displayed in stack traces produced by this script. + * Default: `0`. + */ + lineOffset?: number | undefined; + /** + * Specifies the column number offset that is displayed in stack traces produced by this script. + * @default 0 + */ + columnOffset?: number | undefined; + } + interface ScriptOptions extends BaseOptions { + /** + * V8's code cache data for the supplied source. + */ + cachedData?: Buffer | NodeJS.ArrayBufferView | undefined; + /** @deprecated in favor of `script.createCachedData()` */ + produceCachedData?: boolean | undefined; + /** + * Called during evaluation of this module when `import()` is called. + * If this option is not specified, calls to `import()` will reject with `ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`. + */ + importModuleDynamically?: + | ((specifier: string, script: Script, importAttributes: ImportAttributes) => Module) + | undefined; + } + interface RunningScriptOptions extends BaseOptions { + /** + * When `true`, if an `Error` occurs while compiling the `code`, the line of code causing the error is attached to the stack trace. + * Default: `true`. + */ + displayErrors?: boolean | undefined; + /** + * Specifies the number of milliseconds to execute code before terminating execution. + * If execution is terminated, an `Error` will be thrown. This value must be a strictly positive integer. + */ + timeout?: number | undefined; + /** + * If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received. + * Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that. + * If execution is terminated, an `Error` will be thrown. + * Default: `false`. + */ + breakOnSigint?: boolean | undefined; + } + interface RunningScriptInNewContextOptions extends RunningScriptOptions { + /** + * Human-readable name of the newly created context. + */ + contextName?: CreateContextOptions["name"]; + /** + * Origin corresponding to the newly created context for display purposes. The origin should be formatted like a URL, + * but with only the scheme, host, and port (if necessary), like the value of the `url.origin` property of a `URL` object. + * Most notably, this string should omit the trailing slash, as that denotes a path. + */ + contextOrigin?: CreateContextOptions["origin"]; + contextCodeGeneration?: CreateContextOptions["codeGeneration"]; + /** + * If set to `afterEvaluate`, microtasks will be run immediately after the script has run. + */ + microtaskMode?: CreateContextOptions["microtaskMode"]; + } + interface RunningCodeOptions extends RunningScriptOptions { + cachedData?: ScriptOptions["cachedData"]; + importModuleDynamically?: ScriptOptions["importModuleDynamically"]; + } + interface RunningCodeInNewContextOptions extends RunningScriptInNewContextOptions { + cachedData?: ScriptOptions["cachedData"]; + importModuleDynamically?: ScriptOptions["importModuleDynamically"]; + } + interface CompileFunctionOptions extends BaseOptions { + /** + * Provides an optional data with V8's code cache data for the supplied source. + */ + cachedData?: Buffer | undefined; + /** + * Specifies whether to produce new cache data. + * Default: `false`, + */ + produceCachedData?: boolean | undefined; + /** + * The sandbox/context in which the said function should be compiled in. + */ + parsingContext?: Context | undefined; + /** + * An array containing a collection of context extensions (objects wrapping the current scope) to be applied while compiling + */ + contextExtensions?: Object[] | undefined; + } + interface CreateContextOptions { + /** + * Human-readable name of the newly created context. + * @default 'VM Context i' Where i is an ascending numerical index of the created context. + */ + name?: string | undefined; + /** + * Corresponds to the newly created context for display purposes. + * The origin should be formatted like a `URL`, but with only the scheme, host, and port (if necessary), + * like the value of the `url.origin` property of a URL object. + * Most notably, this string should omit the trailing slash, as that denotes a path. + * @default '' + */ + origin?: string | undefined; + codeGeneration?: + | { + /** + * If set to false any calls to eval or function constructors (Function, GeneratorFunction, etc) + * will throw an EvalError. + * @default true + */ + strings?: boolean | undefined; + /** + * If set to false any attempt to compile a WebAssembly module will throw a WebAssembly.CompileError. + * @default true + */ + wasm?: boolean | undefined; + } + | undefined; + /** + * If set to `afterEvaluate`, microtasks will be run immediately after the script has run. + */ + microtaskMode?: "afterEvaluate" | undefined; + } + type MeasureMemoryMode = "summary" | "detailed"; + interface MeasureMemoryOptions { + /** + * @default 'summary' + */ + mode?: MeasureMemoryMode | undefined; + /** + * @default 'default' + */ + execution?: "default" | "eager" | undefined; + } + interface MemoryMeasurement { + total: { + jsMemoryEstimate: number; + jsMemoryRange: [number, number]; + }; + } + /** + * Instances of the `vm.Script` class contain precompiled scripts that can be + * executed in specific contexts. + * @since v0.3.1 + */ + class Script { + constructor(code: string, options?: ScriptOptions | string); + /** + * Runs the compiled code contained by the `vm.Script` object within the given`contextifiedObject` and returns the result. Running code does not have access + * to local scope. + * + * The following example compiles code that increments a global variable, sets + * the value of another global variable, then execute the code multiple times. + * The globals are contained in the `context` object. + * + * ```js + * const vm = require('vm'); + * + * const context = { + * animal: 'cat', + * count: 2 + * }; + * + * const script = new vm.Script('count += 1; name = "kitty";'); + * + * vm.createContext(context); + * for (let i = 0; i < 10; ++i) { + * script.runInContext(context); + * } + * + * console.log(context); + * // Prints: { animal: 'cat', count: 12, name: 'kitty' } + * ``` + * + * Using the `timeout` or `breakOnSigint` options will result in new event loops + * and corresponding threads being started, which have a non-zero performance + * overhead. + * @since v0.3.1 + * @param contextifiedObject A `contextified` object as returned by the `vm.createContext()` method. + * @return the result of the very last statement executed in the script. + */ + runInContext(contextifiedObject: Context, options?: RunningScriptOptions): any; + /** + * First contextifies the given `contextObject`, runs the compiled code contained + * by the `vm.Script` object within the created context, and returns the result. + * Running code does not have access to local scope. + * + * The following example compiles code that sets a global variable, then executes + * the code multiple times in different contexts. The globals are set on and + * contained within each individual `context`. + * + * ```js + * const vm = require('vm'); + * + * const script = new vm.Script('globalVar = "set"'); + * + * const contexts = [{}, {}, {}]; + * contexts.forEach((context) => { + * script.runInNewContext(context); + * }); + * + * console.log(contexts); + * // Prints: [{ globalVar: 'set' }, { globalVar: 'set' }, { globalVar: 'set' }] + * ``` + * @since v0.3.1 + * @param contextObject An object that will be `contextified`. If `undefined`, a new object will be created. + * @return the result of the very last statement executed in the script. + */ + runInNewContext(contextObject?: Context, options?: RunningScriptInNewContextOptions): any; + /** + * Runs the compiled code contained by the `vm.Script` within the context of the + * current `global` object. Running code does not have access to local scope, but _does_ have access to the current `global` object. + * + * The following example compiles code that increments a `global` variable then + * executes that code multiple times: + * + * ```js + * const vm = require('vm'); + * + * global.globalVar = 0; + * + * const script = new vm.Script('globalVar += 1', { filename: 'myfile.vm' }); + * + * for (let i = 0; i < 1000; ++i) { + * script.runInThisContext(); + * } + * + * console.log(globalVar); + * + * // 1000 + * ``` + * @since v0.3.1 + * @return the result of the very last statement executed in the script. + */ + runInThisContext(options?: RunningScriptOptions): any; + /** + * Creates a code cache that can be used with the `Script` constructor's`cachedData` option. Returns a `Buffer`. This method may be called at any + * time and any number of times. + * + * ```js + * const script = new vm.Script(` + * function add(a, b) { + * return a + b; + * } + * + * const x = add(1, 2); + * `); + * + * const cacheWithoutX = script.createCachedData(); + * + * script.runInThisContext(); + * + * const cacheWithX = script.createCachedData(); + * ``` + * @since v10.6.0 + */ + createCachedData(): Buffer; + /** @deprecated in favor of `script.createCachedData()` */ + cachedDataProduced?: boolean | undefined; + cachedDataRejected?: boolean | undefined; + cachedData?: Buffer | undefined; + /** + * When the script is compiled from a source that contains a source map magic comment, this property will be set to the URL of the source map. + */ + sourceMapURL?: string | undefined; + } + /** + * If given a `contextObject`, the `vm.createContext()` method will `prepare + * that object` so that it can be used in calls to {@link runInContext} or `script.runInContext()`. Inside such scripts, + * the `contextObject` will be the global object, retaining all of its existing + * properties but also having the built-in objects and functions any standard [global object](https://es5.github.io/#x15.1) has. Outside of scripts run by the vm module, global variables + * will remain unchanged. + * + * ```js + * const vm = require('vm'); + * + * global.globalVar = 3; + * + * const context = { globalVar: 1 }; + * vm.createContext(context); + * + * vm.runInContext('globalVar *= 2;', context); + * + * console.log(context); + * // Prints: { globalVar: 2 } + * + * console.log(global.globalVar); + * // Prints: 3 + * ``` + * + * If `contextObject` is omitted (or passed explicitly as `undefined`), a new, + * empty `contextified` object will be returned. + * + * The `vm.createContext()` method is primarily useful for creating a single + * context that can be used to run multiple scripts. For instance, if emulating a + * web browser, the method can be used to create a single context representing a + * window's global object, then run all ` + + + +``` +Usage as a Node module: +```js +var streams = require("web-streams-polyfill"); +var readable = new streams.ReadableStream(); +``` +Usage as a ponyfill from within a ES2015 module: +```js +import { ReadableStream } from "web-streams-polyfill"; +const readable = new ReadableStream(); +``` +Usage as a polyfill from within an ES2015 module: +```js +import "web-streams-polyfill/polyfill"; +const readable = new ReadableStream(); +``` + +## Compatibility + +The default and `polyfill` variants work in any ES2015-compatible environment. + +The `es5` and `polyfill/es5` variants work in any ES5-compatible environment that has a global `Promise`. +If you need to support older browsers or Node versions that do not have a native `Promise` implementation +(check the [support table][promise-support]), you must first include a `Promise` polyfill +(e.g. [promise-polyfill][promise-polyfill]). + +[Async iterable support for `ReadableStream`][rs-asynciterator] is available in all variants, but requires an ES2018-compatible environment or a polyfill for `Symbol.asyncIterator`. + +[`WritableStreamDefaultController.signal`][ws-controller-signal] is available in all variants, but requires a global `AbortController` constructor. If necessary, consider using a polyfill such as [abortcontroller-polyfill]. + +## Compliance + +The polyfill implements [version `e9355ce` (18 Apr 2022)][spec-snapshot] of the streams specification. + +The polyfill is tested against the same [web platform tests][wpt] that are used by browsers to test their native implementations. +It aims to pass all tests, although it allows some exceptions for practical reasons: +* The default (ES2015) variant passes all of the tests, except for: + * The ["bad buffers and views" tests for readable byte streams][wpt-bad-buffers]. + These tests require the implementation to synchronously transfer the contents of an `ArrayBuffer`, which is not yet possible from JavaScript (although there is a [proposal][proposal-arraybuffer-transfer] to make it possible). + The reference implementation "cheats" on these tests [by making a copy instead][ref-impl-transferarraybuffer], but that is unacceptable for the polyfill's performance ([#3][issue-3]). + * The [test for the prototype of `ReadableStream`'s async iterator][wpt-async-iterator-prototype]. + Retrieving the correct `%AsyncIteratorPrototype%` requires using an async generator (`async function* () {}`), which is invalid syntax before ES2018. + Instead, the polyfill [creates its own version][stub-async-iterator-prototype] which is functionally equivalent to the real prototype. + * The tests [with patched globals][wpt-rs-patched-global] and [with `Object.prototype.then`][wpt-then-interception]. + These tests are meant for browsers to ensure user-land modifications cannot affect the internal logic of `pipeTo()` and `tee()`. + However, it's not reasonable or desirable for a user-land polyfill to try and isolate itself completely from using the global `Object`. + * Certain `pipeTo()` tests that require synchronous inspection of the stream's state ([1][wpt-pipe-sync-state-1], [2][wpt-pipe-sync-state-2]). + Because the polyfill uses the public `getReader()` and `getWriter()` API to implement `pipeTo()`, it can only *asynchronously* observe if and when a stream becomes closed or errored. + Therefore, when the readable and the writable end become errored *at the exact same time*, it's difficult for the polyfill to observe these state changes in exactly the same order. +* The ES5 variant passes the same tests as the ES2015 variant, except for various tests about specific characteristics of the constructors, properties and methods. + These test failures do not affect the run-time behavior of the polyfill. + For example: + * The `name` property of down-leveled constructors is incorrect. + * The `length` property of down-leveled constructors and methods with optional arguments is incorrect. + * Not all properties and methods are correctly marked as non-enumerable. + * Down-leveled class methods are not correctly marked as non-constructable. + +The type definitions are compatible with the built-in stream types of TypeScript 3.3 and higher. + +## Contributors + +Thanks to these people for their work on [the original polyfill][creatorrr-polyfill]: + + - Diwank Singh Tomer ([creatorrr](https://github.com/creatorrr)) + - Anders Riutta ([ariutta](https://github.com/ariutta)) + +[spec]: https://streams.spec.whatwg.org +[ref-impl]: https://github.com/whatwg/streams +[ponyfill]: https://github.com/sindresorhus/ponyfill +[amd]: https://requirejs.org/docs/whyamd.html +[migrating]: https://github.com/MattiasBuelens/web-streams-polyfill/blob/v4.0.0-beta.3/MIGRATING.md +[promise-support]: https://kangax.github.io/compat-table/es6/#test-Promise +[promise-polyfill]: https://www.npmjs.com/package/promise-polyfill +[rs-asynciterator]: https://streams.spec.whatwg.org/#rs-asynciterator +[ws-controller-signal]: https://streams.spec.whatwg.org/#ws-default-controller-signal +[abortcontroller-polyfill]: https://www.npmjs.com/package/abortcontroller-polyfill +[spec-snapshot]: https://streams.spec.whatwg.org/commit-snapshots/e9355ce79925947e8eb496563d599c329769d315/ +[wpt]: https://github.com/web-platform-tests/wpt/tree/6a46d9cb8d20c510a620141c721b81b460a4ee55/streams +[wpt-bad-buffers]: https://github.com/web-platform-tests/wpt/blob/6a46d9cb8d20c510a620141c721b81b460a4ee55/streams/readable-byte-streams/bad-buffers-and-views.any.js +[proposal-arraybuffer-transfer]: https://github.com/domenic/proposal-arraybuffer-transfer +[ref-impl-transferarraybuffer]: https://github.com/whatwg/streams/blob/e9355ce79925947e8eb496563d599c329769d315/reference-implementation/lib/abstract-ops/ecmascript.js#L16 +[issue-3]: https://github.com/MattiasBuelens/web-streams-polyfill/issues/3 +[wpt-async-iterator-prototype]: https://github.com/web-platform-tests/wpt/blob/6a46d9cb8d20c510a620141c721b81b460a4ee55/streams/readable-streams/async-iterator.any.js#L24 +[stub-async-iterator-prototype]: https://github.com/MattiasBuelens/web-streams-polyfill/blob/v4.0.0-beta.3/src/lib/readable-stream/async-iterator.ts#L126-L134 +[wpt-rs-patched-global]: https://github.com/web-platform-tests/wpt/blob/887350c2f46def5b01c4dd1f8d2eee35dfb9c5bb/streams/readable-streams/patched-global.any.js +[wpt-then-interception]: https://github.com/web-platform-tests/wpt/blob/cf33f00596af295ee0f207c88e23b5f8b0791307/streams/piping/then-interception.any.js +[wpt-pipe-sync-state-1]: https://github.com/web-platform-tests/wpt/blob/e1e713c842e54ea0a9410ddc988b63d0e1d31973/streams/piping/multiple-propagation.any.js#L30-L53 +[wpt-pipe-sync-state-2]: https://github.com/web-platform-tests/wpt/blob/e1e713c842e54ea0a9410ddc988b63d0e1d31973/streams/piping/multiple-propagation.any.js#L114-L138 +[creatorrr-polyfill]: https://github.com/creatorrr/web-streams-polyfill diff --git a/backend/node_modules/formdata-node/node_modules/web-streams-polyfill/dist/polyfill.es5.js b/backend/node_modules/formdata-node/node_modules/web-streams-polyfill/dist/polyfill.es5.js new file mode 100644 index 0000000000000000000000000000000000000000..7c6cd2430e5b6ff8df0e9497580b7e70fa1c5e0e --- /dev/null +++ b/backend/node_modules/formdata-node/node_modules/web-streams-polyfill/dist/polyfill.es5.js @@ -0,0 +1,8 @@ +/** + * @license + * web-streams-polyfill v4.0.0-beta.3 + * Copyright 2021 Mattias Buelens, Diwank Singh Tomer and other contributors. + * This code is released under the MIT license. + * SPDX-License-Identifier: MIT + */ +!function(){"use strict";var e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol:function(e){return"Symbol(".concat(e,")")};function r(){}function t(e){return"object"==typeof e&&null!==e||"function"==typeof e}var n=r;function o(e,r){try{Object.defineProperty(e,"name",{value:r,configurable:!0})}catch(e){}}var a=Promise,i=Promise.prototype.then,l=Promise.resolve.bind(a),u=Promise.reject.bind(a);function s(e){return new a(e)}function c(e){return l(e)}function d(e){return u(e)}function f(e,r,t){return i.call(e,r,t)}function b(e,r,t){f(f(e,r,t),void 0,n)}function p(e,r){b(e,r)}function h(e,r){b(e,void 0,r)}function _(e,r,t){return f(e,r,t)}function y(e){f(e,void 0,n)}var v=function(e){if("function"==typeof queueMicrotask)v=queueMicrotask;else{var r=c(void 0);v=function(e){return f(r,e)}}return v(e)};function m(e,r,t){if("function"!=typeof e)throw new TypeError("Argument is not a function");return Function.prototype.apply.call(e,r,t)}function g(e,r,t){try{return c(m(e,r,t))}catch(e){return d(e)}}var w=function(){function e(){this._cursor=0,this._size=0,this._front={_elements:[],_next:void 0},this._back=this._front,this._cursor=0,this._size=0}return Object.defineProperty(e.prototype,"length",{get:function(){return this._size},enumerable:!1,configurable:!0}),e.prototype.push=function(e){var r=this._back,t=r;16383===r._elements.length&&(t={_elements:[],_next:void 0}),r._elements.push(e),t!==r&&(this._back=t,r._next=t),++this._size},e.prototype.shift=function(){var e=this._front,r=e,t=this._cursor,n=t+1,o=e._elements,a=o[t];return 16384===n&&(r=e._next,n=0),--this._size,this._cursor=n,e!==r&&(this._front=r),o[t]=void 0,a},e.prototype.forEach=function(e){for(var r=this._cursor,t=this._front,n=t._elements;!(r===n.length&&void 0===t._next||r===n.length&&(r=0,0===(n=(t=t._next)._elements).length));)e(n[r]),++r},e.prototype.peek=function(){var e=this._front,r=this._cursor;return e._elements[r]},e}(),S=e("[[AbortSteps]]"),R=e("[[ErrorSteps]]"),T=e("[[CancelSteps]]"),q=e("[[PullSteps]]"),P=e("[[ReleaseSteps]]");function C(e,r){e._ownerReadableStream=r,r._reader=e,"readable"===r._state?k(e):"closed"===r._state?function(e){k(e),A(e)}(e):j(e,r._storedError)}function E(e,r){return at(e._ownerReadableStream,r)}function O(e){var r=e._ownerReadableStream;"readable"===r._state?B(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):function(e,r){j(e,r)}(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),r._readableStreamController[P](),r._reader=void 0,e._ownerReadableStream=void 0}function W(e){return new TypeError("Cannot "+e+" a stream using a released reader")}function k(e){e._closedPromise=s((function(r,t){e._closedPromise_resolve=r,e._closedPromise_reject=t}))}function j(e,r){k(e),B(e,r)}function B(e,r){void 0!==e._closedPromise_reject&&(y(e._closedPromise),e._closedPromise_reject(r),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}function A(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}var z=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},L=Math.trunc||function(e){return e<0?Math.ceil(e):Math.floor(e)};function F(e,r){if(void 0!==e&&("object"!=typeof(t=e)&&"function"!=typeof t))throw new TypeError("".concat(r," is not an object."));var t}function I(e,r){if("function"!=typeof e)throw new TypeError("".concat(r," is not a function."))}function D(e,r){if(!function(e){return"object"==typeof e&&null!==e||"function"==typeof e}(e))throw new TypeError("".concat(r," is not an object."))}function M(e,r,t){if(void 0===e)throw new TypeError("Parameter ".concat(r," is required in '").concat(t,"'."))}function Q(e,r,t){if(void 0===e)throw new TypeError("".concat(r," is required in '").concat(t,"'."))}function Y(e){return Number(e)}function N(e){return 0===e?0:e}function H(e,r){var t=Number.MAX_SAFE_INTEGER,n=Number(e);if(n=N(n),!z(n))throw new TypeError("".concat(r," is not a finite number"));if((n=function(e){return N(L(e))}(n))<0||n>t)throw new TypeError("".concat(r," is outside the accepted range of ").concat(0," to ").concat(t,", inclusive"));return z(n)&&0!==n?n:0}function x(e){if(!t(e))return!1;if("function"!=typeof e.getReader)return!1;try{return"boolean"==typeof e.locked}catch(e){return!1}}function V(e){if(!t(e))return!1;if("function"!=typeof e.getWriter)return!1;try{return"boolean"==typeof e.locked}catch(e){return!1}}function U(e,r){if(!nt(e))throw new TypeError("".concat(r," is not a ReadableStream."))}function G(e,r){e._reader._readRequests.push(r)}function X(e,r,t){var n=e._reader._readRequests.shift();t?n._closeSteps():n._chunkSteps(r)}function J(e){return e._reader._readRequests.length}function K(e){var r=e._reader;return void 0!==r&&!!$(r)}var Z=function(){function ReadableStreamDefaultReader(e){if(M(e,1,"ReadableStreamDefaultReader"),U(e,"First parameter"),ot(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");C(this,e),this._readRequests=new w}return Object.defineProperty(ReadableStreamDefaultReader.prototype,"closed",{get:function(){return $(this)?this._closedPromise:d(re("closed"))},enumerable:!1,configurable:!0}),ReadableStreamDefaultReader.prototype.cancel=function(e){return void 0===e&&(e=void 0),$(this)?void 0===this._ownerReadableStream?d(W("cancel")):E(this,e):d(re("cancel"))},ReadableStreamDefaultReader.prototype.read=function(){if(!$(this))return d(re("read"));if(void 0===this._ownerReadableStream)return d(W("read from"));var e,r,t=s((function(t,n){e=t,r=n}));return function(e,r){var t=e._ownerReadableStream;t._disturbed=!0,"closed"===t._state?r._closeSteps():"errored"===t._state?r._errorSteps(t._storedError):t._readableStreamController[q](r)}(this,{_chunkSteps:function(r){return e({value:r,done:!1})},_closeSteps:function(){return e({value:void 0,done:!0})},_errorSteps:function(e){return r(e)}}),t},ReadableStreamDefaultReader.prototype.releaseLock=function(){if(!$(this))throw re("releaseLock");void 0!==this._ownerReadableStream&&function(e){O(e);var r=new TypeError("Reader was released");ee(e,r)}(this)},ReadableStreamDefaultReader}();function $(e){return!!t(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readRequests")&&e instanceof Z)}function ee(e,r){var t=e._readRequests;e._readRequests=new w,t.forEach((function(e){e._errorSteps(r)}))}function re(e){return new TypeError("ReadableStreamDefaultReader.prototype.".concat(e," can only be used on a ReadableStreamDefaultReader"))}Object.defineProperties(Z.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),o(Z.prototype.cancel,"cancel"),o(Z.prototype.read,"read"),o(Z.prototype.releaseLock,"releaseLock"),"symbol"==typeof e.toStringTag&&Object.defineProperty(Z.prototype,e.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0});var te=function(){function e(e,r){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=e,this._preventCancel=r}return e.prototype.next=function(){var e=this,r=function(){return e._nextSteps()};return this._ongoingPromise=this._ongoingPromise?_(this._ongoingPromise,r,r):r(),this._ongoingPromise},e.prototype.return=function(e){var r=this,t=function(){return r._returnSteps(e)};return this._ongoingPromise?_(this._ongoingPromise,t,t):t()},e.prototype._nextSteps=function(){var e=this;if(this._isFinished)return Promise.resolve({value:void 0,done:!0});var r=this._reader;return void 0===r?d(W("iterate")):f(r.read(),(function(r){var t;return e._ongoingPromise=void 0,r.done&&(e._isFinished=!0,null===(t=e._reader)||void 0===t||t.releaseLock(),e._reader=void 0),r}),(function(r){var t;throw e._ongoingPromise=void 0,e._isFinished=!0,null===(t=e._reader)||void 0===t||t.releaseLock(),e._reader=void 0,r}))},e.prototype._returnSteps=function(e){if(this._isFinished)return Promise.resolve({value:e,done:!0});this._isFinished=!0;var r=this._reader;if(void 0===r)return d(W("finish iterating"));if(this._reader=void 0,!this._preventCancel){var t=r.cancel(e);return r.releaseLock(),_(t,(function(){return{value:e,done:!0}}))}return r.releaseLock(),c({value:e,done:!0})},e}(),ne={next:function(){return oe(this)?this._asyncIteratorImpl.next():d(ae("next"))},return:function(e){return oe(this)?this._asyncIteratorImpl.return(e):d(ae("return"))}};function oe(e){if(!t(e))return!1;if(!Object.prototype.hasOwnProperty.call(e,"_asyncIteratorImpl"))return!1;try{return e._asyncIteratorImpl instanceof te}catch(e){return!1}}function ae(e){return new TypeError("ReadableStreamAsyncIterator.".concat(e," can only be used on a ReadableSteamAsyncIterator"))}"symbol"==typeof e.asyncIterator&&Object.defineProperty(ne,e.asyncIterator,{value:function(){return this},writable:!0,configurable:!0});var ie=Number.isNaN||function(e){return e!=e};function le(e,r,t,n,o){new Uint8Array(e).set(new Uint8Array(t,n,o),r)}function ue(e){var r=function(e,r,t){if(e.slice)return e.slice(r,t);var n=t-r,o=new ArrayBuffer(n);return le(o,0,e,r,n),o}(e.buffer,e.byteOffset,e.byteOffset+e.byteLength);return new Uint8Array(r)}function se(e){var r=e._queue.shift();return e._queueTotalSize-=r.size,e._queueTotalSize<0&&(e._queueTotalSize=0),r.value}function ce(e,r,t){if("number"!=typeof(n=t)||ie(n)||n<0||t===1/0)throw new RangeError("Size must be a finite, non-NaN, non-negative number.");var n;e._queue.push({value:r,size:t}),e._queueTotalSize+=t}function de(e){e._queue=new w,e._queueTotalSize=0}var fe=function(){function ReadableStreamBYOBRequest(){throw new TypeError("Illegal constructor")}return Object.defineProperty(ReadableStreamBYOBRequest.prototype,"view",{get:function(){if(!he(this))throw ze("view");return this._view},enumerable:!1,configurable:!0}),ReadableStreamBYOBRequest.prototype.respond=function(e){if(!he(this))throw ze("respond");if(M(e,1,"respond"),e=H(e,"First parameter"),void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");this._view.buffer,function(e,r){var t=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==r)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream")}else{if(0===r)throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");if(t.bytesFilled+r>t.byteLength)throw new RangeError("bytesWritten out of range")}t.buffer=t.buffer,Ee(e,r)}(this._associatedReadableByteStreamController,e)},ReadableStreamBYOBRequest.prototype.respondWithNewView=function(e){if(!he(this))throw ze("respondWithNewView");if(M(e,1,"respondWithNewView"),!ArrayBuffer.isView(e))throw new TypeError("You can only respond with array buffer views");if(void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");e.buffer,function(e,r){var t=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==r.byteLength)throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream")}else if(0===r.byteLength)throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");if(t.byteOffset+t.bytesFilled!==r.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(t.bufferByteLength!==r.buffer.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");if(t.bytesFilled+r.byteLength>t.byteLength)throw new RangeError("The region specified by view is larger than byobRequest");var n=r.byteLength;t.buffer=r.buffer,Ee(e,n)}(this._associatedReadableByteStreamController,e)},ReadableStreamBYOBRequest}();Object.defineProperties(fe.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),o(fe.prototype.respond,"respond"),o(fe.prototype.respondWithNewView,"respondWithNewView"),"symbol"==typeof e.toStringTag&&Object.defineProperty(fe.prototype,e.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});var be=function(){function ReadableByteStreamController(){throw new TypeError("Illegal constructor")}return Object.defineProperty(ReadableByteStreamController.prototype,"byobRequest",{get:function(){if(!pe(this))throw Le("byobRequest");return function(e){if(null===e._byobRequest&&e._pendingPullIntos.length>0){var r=e._pendingPullIntos.peek(),t=new Uint8Array(r.buffer,r.byteOffset+r.bytesFilled,r.byteLength-r.bytesFilled),n=Object.create(fe.prototype);!function(e,r,t){e._associatedReadableByteStreamController=r,e._view=t}(n,e,t),e._byobRequest=n}return e._byobRequest}(this)},enumerable:!1,configurable:!0}),Object.defineProperty(ReadableByteStreamController.prototype,"desiredSize",{get:function(){if(!pe(this))throw Le("desiredSize");return Be(this)},enumerable:!1,configurable:!0}),ReadableByteStreamController.prototype.close=function(){if(!pe(this))throw Le("close");if(this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");var e=this._controlledReadableByteStream._state;if("readable"!==e)throw new TypeError("The stream (in ".concat(e," state) is not in the readable state and cannot be closed"));!function(e){var r=e._controlledReadableByteStream;if(e._closeRequested||"readable"!==r._state)return;if(e._queueTotalSize>0)return void(e._closeRequested=!0);if(e._pendingPullIntos.length>0){if(e._pendingPullIntos.peek().bytesFilled>0){var t=new TypeError("Insufficient bytes to fill elements in the given buffer");throw ke(e,t),t}}We(e),it(r)}(this)},ReadableByteStreamController.prototype.enqueue=function(e){if(!pe(this))throw Le("enqueue");if(M(e,1,"enqueue"),!ArrayBuffer.isView(e))throw new TypeError("chunk must be an array buffer view");if(0===e.byteLength)throw new TypeError("chunk must have non-zero byteLength");if(0===e.buffer.byteLength)throw new TypeError("chunk's buffer must have non-zero byteLength");if(this._closeRequested)throw new TypeError("stream is closed or draining");var r=this._controlledReadableByteStream._state;if("readable"!==r)throw new TypeError("The stream (in ".concat(r," state) is not in the readable state and cannot be enqueued to"));!function(e,r){var t=e._controlledReadableByteStream;if(e._closeRequested||"readable"!==t._state)return;var n=r.buffer,o=r.byteOffset,a=r.byteLength,i=n;if(e._pendingPullIntos.length>0){var l=e._pendingPullIntos.peek();l.buffer,0,Pe(e),l.buffer=l.buffer,"none"===l.readerType&&Se(e,l)}if(K(t)){if(function(e){var r=e._controlledReadableByteStream._reader;for(;r._readRequests.length>0;){if(0===e._queueTotalSize)return;je(e,r._readRequests.shift())}}(e),0===J(t))ge(e,i,o,a);else e._pendingPullIntos.length>0&&Oe(e),X(t,new Uint8Array(i,o,a),!1)}else De(t)?(ge(e,i,o,a),Ce(e)):ge(e,i,o,a);_e(e)}(this,e)},ReadableByteStreamController.prototype.error=function(e){if(void 0===e&&(e=void 0),!pe(this))throw Le("error");ke(this,e)},ReadableByteStreamController.prototype[T]=function(e){ye(this),de(this);var r=this._cancelAlgorithm(e);return We(this),r},ReadableByteStreamController.prototype[q]=function(e){var r=this._controlledReadableByteStream;if(this._queueTotalSize>0)je(this,e);else{var t=this._autoAllocateChunkSize;if(void 0!==t){var n=void 0;try{n=new ArrayBuffer(t)}catch(r){return void e._errorSteps(r)}var o={buffer:n,bufferByteLength:t,byteOffset:0,byteLength:t,bytesFilled:0,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(o)}G(r,e),_e(this)}},ReadableByteStreamController.prototype[P]=function(){if(this._pendingPullIntos.length>0){var e=this._pendingPullIntos.peek();e.readerType="none",this._pendingPullIntos=new w,this._pendingPullIntos.push(e)}},ReadableByteStreamController}();function pe(e){return!!t(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableByteStream")&&e instanceof be)}function he(e){return!!t(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_associatedReadableByteStreamController")&&e instanceof fe)}function _e(e){var r=function(e){var r=e._controlledReadableByteStream;if("readable"!==r._state)return!1;if(e._closeRequested)return!1;if(!e._started)return!1;if(K(r)&&J(r)>0)return!0;if(De(r)&&Ie(r)>0)return!0;if(Be(e)>0)return!0;return!1}(e);r&&(e._pulling?e._pullAgain=!0:(e._pulling=!0,b(e._pullAlgorithm(),(function(){return e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,_e(e)),null}),(function(r){return ke(e,r),null}))))}function ye(e){Pe(e),e._pendingPullIntos=new w}function ve(e,r){var t=!1;"closed"===e._state&&(t=!0);var n=me(r);"default"===r.readerType?X(e,n,t):function(e,r,t){var n=e._reader._readIntoRequests.shift();t?n._closeSteps(r):n._chunkSteps(r)}(e,n,t)}function me(e){var r=e.bytesFilled,t=e.elementSize;return new e.viewConstructor(e.buffer,e.byteOffset,r/t)}function ge(e,r,t,n){e._queue.push({buffer:r,byteOffset:t,byteLength:n}),e._queueTotalSize+=n}function we(e,r,t,n){var o;try{o=r.slice(t,t+n)}catch(r){throw ke(e,r),r}ge(e,o,0,n)}function Se(e,r){r.bytesFilled>0&&we(e,r.buffer,r.byteOffset,r.bytesFilled),Oe(e)}function Re(e,r){var t=r.elementSize,n=r.bytesFilled-r.bytesFilled%t,o=Math.min(e._queueTotalSize,r.byteLength-r.bytesFilled),a=r.bytesFilled+o,i=a-a%t,l=o,u=!1;i>n&&(l=i-r.bytesFilled,u=!0);for(var s=e._queue;l>0;){var c=s.peek(),d=Math.min(l,c.byteLength),f=r.byteOffset+r.bytesFilled;le(r.buffer,f,c.buffer,c.byteOffset,d),c.byteLength===d?s.shift():(c.byteOffset+=d,c.byteLength-=d),e._queueTotalSize-=d,Te(e,d,r),l-=d}return u}function Te(e,r,t){t.bytesFilled+=r}function qe(e){0===e._queueTotalSize&&e._closeRequested?(We(e),it(e._controlledReadableByteStream)):_e(e)}function Pe(e){null!==e._byobRequest&&(e._byobRequest._associatedReadableByteStreamController=void 0,e._byobRequest._view=null,e._byobRequest=null)}function Ce(e){for(;e._pendingPullIntos.length>0;){if(0===e._queueTotalSize)return;var r=e._pendingPullIntos.peek();Re(e,r)&&(Oe(e),ve(e._controlledReadableByteStream,r))}}function Ee(e,r){var t=e._pendingPullIntos.peek();Pe(e),"closed"===e._controlledReadableByteStream._state?function(e,r){"none"===r.readerType&&Oe(e);var t=e._controlledReadableByteStream;if(De(t))for(;Ie(t)>0;)ve(t,Oe(e))}(e,t):function(e,r,t){if(Te(0,r,t),"none"===t.readerType)return Se(e,t),void Ce(e);if(!(t.bytesFilled0){var o=t.byteOffset+t.bytesFilled;we(e,t.buffer,o-n,n)}t.bytesFilled-=n,ve(e._controlledReadableByteStream,t),Ce(e)}}(e,r,t),_e(e)}function Oe(e){return e._pendingPullIntos.shift()}function We(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0}function ke(e,r){var t=e._controlledReadableByteStream;"readable"===t._state&&(ye(e),de(e),We(e),lt(t,r))}function je(e,r){var t=e._queue.shift();e._queueTotalSize-=t.byteLength,qe(e);var n=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);r._chunkSteps(n)}function Be(e){var r=e._controlledReadableByteStream._state;return"errored"===r?null:"closed"===r?0:e._strategyHWM-e._queueTotalSize}function Ae(e,r,t){var n,o,a,i=Object.create(be.prototype);n=void 0!==r.start?function(){return r.start(i)}:function(){},o=void 0!==r.pull?function(){return r.pull(i)}:function(){return c(void 0)},a=void 0!==r.cancel?function(e){return r.cancel(e)}:function(){return c(void 0)};var l=r.autoAllocateChunkSize;if(0===l)throw new TypeError("autoAllocateChunkSize must be greater than 0");!function(e,r,t,n,o,a,i){r._controlledReadableByteStream=e,r._pullAgain=!1,r._pulling=!1,r._byobRequest=null,r._queue=r._queueTotalSize=void 0,de(r),r._closeRequested=!1,r._started=!1,r._strategyHWM=a,r._pullAlgorithm=n,r._cancelAlgorithm=o,r._autoAllocateChunkSize=i,r._pendingPullIntos=new w,e._readableStreamController=r,b(c(t()),(function(){return r._started=!0,_e(r),null}),(function(e){return ke(r,e),null}))}(e,i,n,o,a,t,l)}function ze(e){return new TypeError("ReadableStreamBYOBRequest.prototype.".concat(e," can only be used on a ReadableStreamBYOBRequest"))}function Le(e){return new TypeError("ReadableByteStreamController.prototype.".concat(e," can only be used on a ReadableByteStreamController"))}function Fe(e,r){e._reader._readIntoRequests.push(r)}function Ie(e){return e._reader._readIntoRequests.length}function De(e){var r=e._reader;return void 0!==r&&!!Qe(r)}Object.defineProperties(be.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),o(be.prototype.close,"close"),o(be.prototype.enqueue,"enqueue"),o(be.prototype.error,"error"),"symbol"==typeof e.toStringTag&&Object.defineProperty(be.prototype,e.toStringTag,{value:"ReadableByteStreamController",configurable:!0});var Me=function(){function ReadableStreamBYOBReader(e){if(M(e,1,"ReadableStreamBYOBReader"),U(e,"First parameter"),ot(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!pe(e._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");C(this,e),this._readIntoRequests=new w}return Object.defineProperty(ReadableStreamBYOBReader.prototype,"closed",{get:function(){return Qe(this)?this._closedPromise:d(Ne("closed"))},enumerable:!1,configurable:!0}),ReadableStreamBYOBReader.prototype.cancel=function(e){return void 0===e&&(e=void 0),Qe(this)?void 0===this._ownerReadableStream?d(W("cancel")):E(this,e):d(Ne("cancel"))},ReadableStreamBYOBReader.prototype.read=function(e){if(!Qe(this))return d(Ne("read"));if(!ArrayBuffer.isView(e))return d(new TypeError("view must be an array buffer view"));if(0===e.byteLength)return d(new TypeError("view must have non-zero byteLength"));if(0===e.buffer.byteLength)return d(new TypeError("view's buffer must have non-zero byteLength"));if(e.buffer,void 0===this._ownerReadableStream)return d(W("read from"));var r,t,n=s((function(e,n){r=e,t=n}));return function(e,r,t){var n=e._ownerReadableStream;n._disturbed=!0,"errored"===n._state?t._errorSteps(n._storedError):function(e,r,t){var n=e._controlledReadableByteStream,o=1;r.constructor!==DataView&&(o=r.constructor.BYTES_PER_ELEMENT);var a=r.constructor,i=r.buffer,l={buffer:i,bufferByteLength:i.byteLength,byteOffset:r.byteOffset,byteLength:r.byteLength,bytesFilled:0,elementSize:o,viewConstructor:a,readerType:"byob"};if(e._pendingPullIntos.length>0)return e._pendingPullIntos.push(l),void Fe(n,t);if("closed"!==n._state){if(e._queueTotalSize>0){if(Re(e,l)){var u=me(l);return qe(e),void t._chunkSteps(u)}if(e._closeRequested){var s=new TypeError("Insufficient bytes to fill elements in the given buffer");return ke(e,s),void t._errorSteps(s)}}e._pendingPullIntos.push(l),Fe(n,t),_e(e)}else{var c=new a(l.buffer,l.byteOffset,0);t._closeSteps(c)}}(n._readableStreamController,r,t)}(this,e,{_chunkSteps:function(e){return r({value:e,done:!1})},_closeSteps:function(e){return r({value:e,done:!0})},_errorSteps:function(e){return t(e)}}),n},ReadableStreamBYOBReader.prototype.releaseLock=function(){if(!Qe(this))throw Ne("releaseLock");void 0!==this._ownerReadableStream&&function(e){O(e);var r=new TypeError("Reader was released");Ye(e,r)}(this)},ReadableStreamBYOBReader}();function Qe(e){return!!t(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readIntoRequests")&&e instanceof Me)}function Ye(e,r){var t=e._readIntoRequests;e._readIntoRequests=new w,t.forEach((function(e){e._errorSteps(r)}))}function Ne(e){return new TypeError("ReadableStreamBYOBReader.prototype.".concat(e," can only be used on a ReadableStreamBYOBReader"))}function He(e,r){var t=e.highWaterMark;if(void 0===t)return r;if(ie(t)||t<0)throw new RangeError("Invalid highWaterMark");return t}function xe(e){var r=e.size;return r||function(){return 1}}function Ve(e,r){F(e,r);var t=null==e?void 0:e.highWaterMark,n=null==e?void 0:e.size;return{highWaterMark:void 0===t?void 0:Y(t),size:void 0===n?void 0:Ue(n,"".concat(r," has member 'size' that"))}}function Ue(e,r){return I(e,r),function(r){return Y(e(r))}}function Ge(e,r,t){return I(e,t),function(t){return g(e,r,[t])}}function Xe(e,r,t){return I(e,t),function(){return g(e,r,[])}}function Je(e,r,t){return I(e,t),function(t){return m(e,r,[t])}}function Ke(e,r,t){return I(e,t),function(t,n){return g(e,r,[t,n])}}Object.defineProperties(Me.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),o(Me.prototype.cancel,"cancel"),o(Me.prototype.read,"read"),o(Me.prototype.releaseLock,"releaseLock"),"symbol"==typeof e.toStringTag&&Object.defineProperty(Me.prototype,e.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});var Ze="function"==typeof AbortController;var $e=function(){function WritableStream(e,r){void 0===e&&(e={}),void 0===r&&(r={}),void 0===e?e=null:D(e,"First parameter");var t,n=Ve(r,"Second parameter"),o=function(e,r){F(e,r);var t=null==e?void 0:e.abort,n=null==e?void 0:e.close,o=null==e?void 0:e.start,a=null==e?void 0:e.type,i=null==e?void 0:e.write;return{abort:void 0===t?void 0:Ge(t,e,"".concat(r," has member 'abort' that")),close:void 0===n?void 0:Xe(n,e,"".concat(r," has member 'close' that")),start:void 0===o?void 0:Je(o,e,"".concat(r," has member 'start' that")),write:void 0===i?void 0:Ke(i,e,"".concat(r," has member 'write' that")),type:a}}(e,"First parameter");if((t=this)._state="writable",t._storedError=void 0,t._writer=void 0,t._writableStreamController=void 0,t._writeRequests=new w,t._inFlightWriteRequest=void 0,t._closeRequest=void 0,t._inFlightCloseRequest=void 0,t._pendingAbortRequest=void 0,t._backpressure=!1,void 0!==o.type)throw new RangeError("Invalid type is specified");var a=xe(n);!function(e,r,t,n){var o,a,i,l,u=Object.create(pr.prototype);o=void 0!==r.start?function(){return r.start(u)}:function(){};a=void 0!==r.write?function(e){return r.write(e,u)}:function(){return c(void 0)};i=void 0!==r.close?function(){return r.close()}:function(){return c(void 0)};l=void 0!==r.abort?function(e){return r.abort(e)}:function(){return c(void 0)};!function(e,r,t,n,o,a,i,l){r._controlledWritableStream=e,e._writableStreamController=r,r._queue=void 0,r._queueTotalSize=void 0,de(r),r._abortReason=void 0,r._abortController=function(){if(Ze)return new AbortController}(),r._started=!1,r._strategySizeAlgorithm=l,r._strategyHWM=i,r._writeAlgorithm=n,r._closeAlgorithm=o,r._abortAlgorithm=a;var u=gr(r);sr(e,u),b(c(t()),(function(){return r._started=!0,vr(r),null}),(function(t){return r._started=!0,or(e,t),null}))}(e,u,o,a,i,l,t,n)}(this,o,He(n,1),a)}return Object.defineProperty(WritableStream.prototype,"locked",{get:function(){if(!er(this))throw Sr("locked");return rr(this)},enumerable:!1,configurable:!0}),WritableStream.prototype.abort=function(e){return void 0===e&&(e=void 0),er(this)?rr(this)?d(new TypeError("Cannot abort a stream that already has a writer")):tr(this,e):d(Sr("abort"))},WritableStream.prototype.close=function(){return er(this)?rr(this)?d(new TypeError("Cannot close a stream that already has a writer")):lr(this)?d(new TypeError("Cannot close an already-closing stream")):nr(this):d(Sr("close"))},WritableStream.prototype.getWriter=function(){if(!er(this))throw Sr("getWriter");return new cr(this)},WritableStream}();function er(e){return!!t(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_writableStreamController")&&e instanceof $e)}function rr(e){return void 0!==e._writer}function tr(e,r){var t;if("closed"===e._state||"errored"===e._state)return c(void 0);e._writableStreamController._abortReason=r,null===(t=e._writableStreamController._abortController)||void 0===t||t.abort(r);var n=e._state;if("closed"===n||"errored"===n)return c(void 0);if(void 0!==e._pendingAbortRequest)return e._pendingAbortRequest._promise;var o=!1;"erroring"===n&&(o=!0,r=void 0);var a=s((function(t,n){e._pendingAbortRequest={_promise:void 0,_resolve:t,_reject:n,_reason:r,_wasAlreadyErroring:o}}));return e._pendingAbortRequest._promise=a,o||ar(e,r),a}function nr(e){var r=e._state;if("closed"===r||"errored"===r)return d(new TypeError("The stream (in ".concat(r," state) is not in the writable state and cannot be closed")));var t,n=s((function(r,t){var n={_resolve:r,_reject:t};e._closeRequest=n})),o=e._writer;return void 0!==o&&e._backpressure&&"writable"===r&&Ar(o),ce(t=e._writableStreamController,br,0),vr(t),n}function or(e,r){"writable"!==e._state?ir(e):ar(e,r)}function ar(e,r){var t=e._writableStreamController;e._state="erroring",e._storedError=r;var n=e._writer;void 0!==n&&fr(n,r),!function(e){if(void 0===e._inFlightWriteRequest&&void 0===e._inFlightCloseRequest)return!1;return!0}(e)&&t._started&&ir(e)}function ir(e){e._state="errored",e._writableStreamController[R]();var r=e._storedError;if(e._writeRequests.forEach((function(e){e._reject(r)})),e._writeRequests=new w,void 0!==e._pendingAbortRequest){var t=e._pendingAbortRequest;if(e._pendingAbortRequest=void 0,t._wasAlreadyErroring)return t._reject(r),void ur(e);b(e._writableStreamController[S](t._reason),(function(){return t._resolve(),ur(e),null}),(function(r){return t._reject(r),ur(e),null}))}else ur(e)}function lr(e){return void 0!==e._closeRequest||void 0!==e._inFlightCloseRequest}function ur(e){void 0!==e._closeRequest&&(e._closeRequest._reject(e._storedError),e._closeRequest=void 0);var r=e._writer;void 0!==r&&Er(r,e._storedError)}function sr(e,r){var t=e._writer;void 0!==t&&r!==e._backpressure&&(r?function(e){Wr(e)}(t):Ar(t)),e._backpressure=r}Object.defineProperties($e.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),o($e.prototype.abort,"abort"),o($e.prototype.close,"close"),o($e.prototype.getWriter,"getWriter"),"symbol"==typeof e.toStringTag&&Object.defineProperty($e.prototype,e.toStringTag,{value:"WritableStream",configurable:!0});var cr=function(){function WritableStreamDefaultWriter(e){if(M(e,1,"WritableStreamDefaultWriter"),function(e,r){if(!er(e))throw new TypeError("".concat(r," is not a WritableStream."))}(e,"First parameter"),rr(e))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=e,e._writer=this;var r,t=e._state;if("writable"===t)!lr(e)&&e._backpressure?Wr(this):jr(this),Pr(this);else if("erroring"===t)kr(this,e._storedError),Pr(this);else if("closed"===t)jr(this),Pr(r=this),Or(r);else{var n=e._storedError;kr(this,n),Cr(this,n)}}return Object.defineProperty(WritableStreamDefaultWriter.prototype,"closed",{get:function(){return dr(this)?this._closedPromise:d(Tr("closed"))},enumerable:!1,configurable:!0}),Object.defineProperty(WritableStreamDefaultWriter.prototype,"desiredSize",{get:function(){if(!dr(this))throw Tr("desiredSize");if(void 0===this._ownerWritableStream)throw qr("desiredSize");return function(e){var r=e._ownerWritableStream,t=r._state;if("errored"===t||"erroring"===t)return null;if("closed"===t)return 0;return yr(r._writableStreamController)}(this)},enumerable:!1,configurable:!0}),Object.defineProperty(WritableStreamDefaultWriter.prototype,"ready",{get:function(){return dr(this)?this._readyPromise:d(Tr("ready"))},enumerable:!1,configurable:!0}),WritableStreamDefaultWriter.prototype.abort=function(e){return void 0===e&&(e=void 0),dr(this)?void 0===this._ownerWritableStream?d(qr("abort")):function(e,r){return tr(e._ownerWritableStream,r)}(this,e):d(Tr("abort"))},WritableStreamDefaultWriter.prototype.close=function(){if(!dr(this))return d(Tr("close"));var e=this._ownerWritableStream;return void 0===e?d(qr("close")):lr(e)?d(new TypeError("Cannot close an already-closing stream")):nr(this._ownerWritableStream)},WritableStreamDefaultWriter.prototype.releaseLock=function(){if(!dr(this))throw Tr("releaseLock");void 0!==this._ownerWritableStream&&function(e){var r=e._ownerWritableStream,t=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");fr(e,t),function(e,r){"pending"===e._closedPromiseState?Er(e,r):function(e,r){Cr(e,r)}(e,r)}(e,t),r._writer=void 0,e._ownerWritableStream=void 0}(this)},WritableStreamDefaultWriter.prototype.write=function(e){return void 0===e&&(e=void 0),dr(this)?void 0===this._ownerWritableStream?d(qr("write to")):function(e,r){var t=e._ownerWritableStream,n=t._writableStreamController,o=function(e,r){try{return e._strategySizeAlgorithm(r)}catch(r){return mr(e,r),1}}(n,r);if(t!==e._ownerWritableStream)return d(qr("write to"));var a=t._state;if("errored"===a)return d(t._storedError);if(lr(t)||"closed"===a)return d(new TypeError("The stream is closing or closed and cannot be written to"));if("erroring"===a)return d(t._storedError);var i=function(e){return s((function(r,t){var n={_resolve:r,_reject:t};e._writeRequests.push(n)}))}(t);return function(e,r,t){try{ce(e,r,t)}catch(r){return void mr(e,r)}var n=e._controlledWritableStream;if(!lr(n)&&"writable"===n._state){sr(n,gr(e))}vr(e)}(n,r,o),i}(this,e):d(Tr("write"))},WritableStreamDefaultWriter}();function dr(e){return!!t(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_ownerWritableStream")&&e instanceof cr)}function fr(e,r){"pending"===e._readyPromiseState?Br(e,r):function(e,r){kr(e,r)}(e,r)}Object.defineProperties(cr.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),o(cr.prototype.abort,"abort"),o(cr.prototype.close,"close"),o(cr.prototype.releaseLock,"releaseLock"),o(cr.prototype.write,"write"),"symbol"==typeof e.toStringTag&&Object.defineProperty(cr.prototype,e.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});var br={},pr=function(){function WritableStreamDefaultController(){throw new TypeError("Illegal constructor")}return Object.defineProperty(WritableStreamDefaultController.prototype,"abortReason",{get:function(){if(!hr(this))throw Rr("abortReason");return this._abortReason},enumerable:!1,configurable:!0}),Object.defineProperty(WritableStreamDefaultController.prototype,"signal",{get:function(){if(!hr(this))throw Rr("signal");if(void 0===this._abortController)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal},enumerable:!1,configurable:!0}),WritableStreamDefaultController.prototype.error=function(e){if(void 0===e&&(e=void 0),!hr(this))throw Rr("error");"writable"===this._controlledWritableStream._state&&wr(this,e)},WritableStreamDefaultController.prototype[S]=function(e){var r=this._abortAlgorithm(e);return _r(this),r},WritableStreamDefaultController.prototype[R]=function(){de(this)},WritableStreamDefaultController}();function hr(e){return!!t(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledWritableStream")&&e instanceof pr)}function _r(e){e._writeAlgorithm=void 0,e._closeAlgorithm=void 0,e._abortAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function yr(e){return e._strategyHWM-e._queueTotalSize}function vr(e){var r=e._controlledWritableStream;if(e._started&&void 0===r._inFlightWriteRequest)if("erroring"!==r._state){if(0!==e._queue.length){var t=e._queue.peek().value;t===br?function(e){var r=e._controlledWritableStream;(function(e){e._inFlightCloseRequest=e._closeRequest,e._closeRequest=void 0})(r),se(e);var t=e._closeAlgorithm();_r(e),b(t,(function(){return function(e){e._inFlightCloseRequest._resolve(void 0),e._inFlightCloseRequest=void 0,"erroring"===e._state&&(e._storedError=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._resolve(),e._pendingAbortRequest=void 0)),e._state="closed";var r=e._writer;void 0!==r&&Or(r)}(r),null}),(function(e){return function(e,r){e._inFlightCloseRequest._reject(r),e._inFlightCloseRequest=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._reject(r),e._pendingAbortRequest=void 0),or(e,r)}(r,e),null}))}(e):function(e,r){var t=e._controlledWritableStream;(function(e){e._inFlightWriteRequest=e._writeRequests.shift()})(t),b(e._writeAlgorithm(r),(function(){!function(e){e._inFlightWriteRequest._resolve(void 0),e._inFlightWriteRequest=void 0}(t);var r=t._state;if(se(e),!lr(t)&&"writable"===r){var n=gr(e);sr(t,n)}return vr(e),null}),(function(r){return"writable"===t._state&&_r(e),function(e,r){e._inFlightWriteRequest._reject(r),e._inFlightWriteRequest=void 0,or(e,r)}(t,r),null}))}(e,t)}}else ir(r)}function mr(e,r){"writable"===e._controlledWritableStream._state&&wr(e,r)}function gr(e){return yr(e)<=0}function wr(e,r){var t=e._controlledWritableStream;_r(e),ar(t,r)}function Sr(e){return new TypeError("WritableStream.prototype.".concat(e," can only be used on a WritableStream"))}function Rr(e){return new TypeError("WritableStreamDefaultController.prototype.".concat(e," can only be used on a WritableStreamDefaultController"))}function Tr(e){return new TypeError("WritableStreamDefaultWriter.prototype.".concat(e," can only be used on a WritableStreamDefaultWriter"))}function qr(e){return new TypeError("Cannot "+e+" a stream using a released writer")}function Pr(e){e._closedPromise=s((function(r,t){e._closedPromise_resolve=r,e._closedPromise_reject=t,e._closedPromiseState="pending"}))}function Cr(e,r){Pr(e),Er(e,r)}function Er(e,r){void 0!==e._closedPromise_reject&&(y(e._closedPromise),e._closedPromise_reject(r),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="rejected")}function Or(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="resolved")}function Wr(e){e._readyPromise=s((function(r,t){e._readyPromise_resolve=r,e._readyPromise_reject=t})),e._readyPromiseState="pending"}function kr(e,r){Wr(e),Br(e,r)}function jr(e){Wr(e),Ar(e)}function Br(e,r){void 0!==e._readyPromise_reject&&(y(e._readyPromise),e._readyPromise_reject(r),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="rejected")}function Ar(e){void 0!==e._readyPromise_resolve&&(e._readyPromise_resolve(void 0),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="fulfilled")}Object.defineProperties(pr.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),"symbol"==typeof e.toStringTag&&Object.defineProperty(pr.prototype,e.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});var zr="undefined"!=typeof DOMException?DOMException:void 0;var Lr,Fr=function(e){if("function"!=typeof e&&"object"!=typeof e)return!1;try{return new e,!0}catch(e){return!1}}(zr)?zr:((Lr=function(e,r){this.message=e||"",this.name=r||"Error",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}).prototype=Object.create(Error.prototype),Object.defineProperty(Lr.prototype,"constructor",{value:Lr,writable:!0,configurable:!0}),Lr);function Ir(e,r,t,n,o,a){var i=e.getReader(),l=r.getWriter();nt(e)&&(e._disturbed=!0);var u,h,m,g=!1,w=!1,S="readable",R="writable",T=!1,q=!1,P=s((function(e){m=e})),C=Promise.resolve(void 0);return s((function(E,O){var W;function k(){if(!g){var e=s((function(e,r){!function t(n){n?e():f(function(){if(g)return c(!0);return f(l.ready,(function(){return f(i.read(),(function(e){return!!e.done||(y(C=l.write(e.value)),!1)}))}))}(),t,r)}(!1)}));y(e)}}function j(){return S="closed",t?F():L((function(){return er(r)&&(T=lr(r),R=r._state),T||"closed"===R?c(void 0):"erroring"===R||"errored"===R?d(h):(T=!0,l.close())}),!1,void 0),null}function B(e){return g||(S="errored",u=e,n?F(!0,e):L((function(){return l.abort(e)}),!0,e)),null}function A(e){return w||(R="errored",h=e,o?F(!0,e):L((function(){return i.cancel(e)}),!0,e)),null}if(void 0!==a&&(W=function(){var e=void 0!==a.reason?a.reason:new Fr("Aborted","AbortError"),r=[];n||r.push((function(){return"writable"===R?l.abort(e):c(void 0)})),o||r.push((function(){return"readable"===S?i.cancel(e):c(void 0)})),L((function(){return Promise.all(r.map((function(e){return e()})))}),!0,e)},a.aborted?W():a.addEventListener("abort",W)),nt(e)&&(S=e._state,u=e._storedError),er(r)&&(R=r._state,h=r._storedError,T=lr(r)),nt(e)&&er(r)&&(q=!0,m()),"errored"===S)B(u);else if("erroring"===R||"errored"===R)A(h);else if("closed"===S)j();else if(T||"closed"===R){var z=new TypeError("the destination writable stream closed before all data could be piped to it");o?F(!0,z):L((function(){return i.cancel(z)}),!0,z)}function L(e,r,t){function n(){var e;return"writable"!==R||T?o():p(c(function r(){if(e!==C)return e=C,_(C,r,r)}()),o),null}function o(){return e?b(e(),(function(){return I(r,t)}),(function(e){return I(!0,e)})):I(r,t),null}g||(g=!0,q?n():p(P,n))}function F(e,r){L(void 0,e,r)}function I(e,r){return w=!0,l.releaseLock(),i.releaseLock(),void 0!==a&&a.removeEventListener("abort",W),e?O(r):E(void 0),null}g||(b(i.closed,j,B),b(l.closed,(function(){return w||(R="closed"),null}),A)),q?k():v((function(){q=!0,m(),k()}))}))}function Dr(e,r){return function(e){try{return e.getReader({mode:"byob"}).releaseLock(),!0}catch(e){return!1}}(e)?function(e){var r,t,n,o,a,i=e.getReader(),l=!1,u=!1,d=!1,f=!1,p=!1,_=!1,y=s((function(e){a=e}));function v(e){h(e.closed,(function(r){return e!==i||(n.error(r),o.error(r),p&&_||a(void 0)),null}))}function m(){l&&(i.releaseLock(),v(i=e.getReader()),l=!1),b(i.read(),(function(e){var r,t;if(d=!1,f=!1,e.done)return p||n.close(),_||o.close(),null===(r=n.byobRequest)||void 0===r||r.respond(0),null===(t=o.byobRequest)||void 0===t||t.respond(0),p&&_||a(void 0),null;var l=e.value,s=l,c=l;if(!p&&!_)try{c=ue(l)}catch(e){return n.error(e),o.error(e),a(i.cancel(e)),null}return p||n.enqueue(s),_||o.enqueue(c),u=!1,d?w():f&&S(),null}),(function(){return u=!1,null}))}function g(r,t){l||(i.releaseLock(),v(i=e.getReader({mode:"byob"})),l=!0);var s=t?o:n,c=t?n:o;b(i.read(r),(function(e){var r;d=!1,f=!1;var n=t?_:p,o=t?p:_;if(e.done){n||s.close(),o||c.close();var l=e.value;return void 0!==l&&(n||s.byobRequest.respondWithNewView(l),o||null===(r=c.byobRequest)||void 0===r||r.respond(0)),n&&o||a(void 0),null}var b=e.value;if(o)n||s.byobRequest.respondWithNewView(b);else{var h=void 0;try{h=ue(b)}catch(e){return s.error(e),c.error(e),a(i.cancel(e)),null}n||s.byobRequest.respondWithNewView(b),c.enqueue(h)}return u=!1,d?w():f&&S(),null}),(function(){return u=!1,null}))}function w(){if(u)return d=!0,c(void 0);u=!0;var e=n.byobRequest;return null===e?m():g(e.view,!1),c(void 0)}function S(){if(u)return f=!0,c(void 0);u=!0;var e=o.byobRequest;return null===e?m():g(e.view,!0),c(void 0)}function R(e){if(p=!0,r=e,_){var n=[r,t],o=i.cancel(n);a(o)}return y}function T(e){if(_=!0,t=e,p){var n=[r,t],o=i.cancel(n);a(o)}return y}var q=new tt({type:"bytes",start:function(e){n=e},pull:w,cancel:R}),P=new tt({type:"bytes",start:function(e){o=e},pull:S,cancel:T});return v(i),[q,P]}(e):function(e,r){var t,n,o,a,i,l=e.getReader(),u=!1,d=!1,f=!1,p=!1,_=s((function(e){i=e}));function y(){return u?(d=!0,c(void 0)):(u=!0,b(l.read(),(function(e){if(d=!1,e.done)return f||o.close(),p||a.close(),f&&p||i(void 0),null;var r=e.value,t=r,n=r;return f||o.enqueue(t),p||a.enqueue(n),u=!1,d&&y(),null}),(function(){return u=!1,null})),c(void 0))}function v(e){if(f=!0,t=e,p){var r=[t,n],o=l.cancel(r);i(o)}return _}function m(e){if(p=!0,n=e,f){var r=[t,n],o=l.cancel(r);i(o)}return _}var g=new tt({start:function(e){o=e},pull:y,cancel:v}),w=new tt({start:function(e){a=e},pull:y,cancel:m});return h(l.closed,(function(e){return o.error(e),a.error(e),f&&p||i(void 0),null})),[g,w]}(e)}var Mr=function(){function ReadableStreamDefaultController(){throw new TypeError("Illegal constructor")}return Object.defineProperty(ReadableStreamDefaultController.prototype,"desiredSize",{get:function(){if(!Qr(this))throw Gr("desiredSize");return xr(this)},enumerable:!1,configurable:!0}),ReadableStreamDefaultController.prototype.close=function(){if(!Qr(this))throw Gr("close");if(!Vr(this))throw new TypeError("The stream is not in a state that permits close");!function(e){if(!Vr(e))return;var r=e._controlledReadableStream;e._closeRequested=!0,0===e._queue.length&&(Nr(e),it(r))}(this)},ReadableStreamDefaultController.prototype.enqueue=function(e){if(void 0===e&&(e=void 0),!Qr(this))throw Gr("enqueue");if(!Vr(this))throw new TypeError("The stream is not in a state that permits enqueue");return function(e,r){if(!Vr(e))return;var t=e._controlledReadableStream;if(ot(t)&&J(t)>0)X(t,r,!1);else{var n=void 0;try{n=e._strategySizeAlgorithm(r)}catch(r){throw Hr(e,r),r}try{ce(e,r,n)}catch(r){throw Hr(e,r),r}}Yr(e)}(this,e)},ReadableStreamDefaultController.prototype.error=function(e){if(void 0===e&&(e=void 0),!Qr(this))throw Gr("error");Hr(this,e)},ReadableStreamDefaultController.prototype[T]=function(e){de(this);var r=this._cancelAlgorithm(e);return Nr(this),r},ReadableStreamDefaultController.prototype[q]=function(e){var r=this._controlledReadableStream;if(this._queue.length>0){var t=se(this);this._closeRequested&&0===this._queue.length?(Nr(this),it(r)):Yr(this),e._chunkSteps(t)}else G(r,e),Yr(this)},ReadableStreamDefaultController.prototype[P]=function(){},ReadableStreamDefaultController}();function Qr(e){return!!t(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableStream")&&e instanceof Mr)}function Yr(e){var r=function(e){var r=e._controlledReadableStream;if(!Vr(e))return!1;if(!e._started)return!1;if(ot(r)&&J(r)>0)return!0;if(xr(e)>0)return!0;return!1}(e);r&&(e._pulling?e._pullAgain=!0:(e._pulling=!0,b(e._pullAlgorithm(),(function(){return e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,Yr(e)),null}),(function(r){return Hr(e,r),null}))))}function Nr(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function Hr(e,r){var t=e._controlledReadableStream;"readable"===t._state&&(de(e),Nr(e),lt(t,r))}function xr(e){var r=e._controlledReadableStream._state;return"errored"===r?null:"closed"===r?0:e._strategyHWM-e._queueTotalSize}function Vr(e){return!e._closeRequested&&"readable"===e._controlledReadableStream._state}function Ur(e,r,t,n){var o,a,i,l=Object.create(Mr.prototype);o=void 0!==r.start?function(){return r.start(l)}:function(){},a=void 0!==r.pull?function(){return r.pull(l)}:function(){return c(void 0)},i=void 0!==r.cancel?function(e){return r.cancel(e)}:function(){return c(void 0)},function(e,r,t,n,o,a,i){r._controlledReadableStream=e,r._queue=void 0,r._queueTotalSize=void 0,de(r),r._started=!1,r._closeRequested=!1,r._pullAgain=!1,r._pulling=!1,r._strategySizeAlgorithm=i,r._strategyHWM=a,r._pullAlgorithm=n,r._cancelAlgorithm=o,e._readableStreamController=r,b(c(t()),(function(){return r._started=!0,Yr(r),null}),(function(e){return Hr(r,e),null}))}(e,l,o,a,i,t,n)}function Gr(e){return new TypeError("ReadableStreamDefaultController.prototype.".concat(e," can only be used on a ReadableStreamDefaultController"))}function Xr(e,r,t){return I(e,t),function(t){return g(e,r,[t])}}function Jr(e,r,t){return I(e,t),function(t){return g(e,r,[t])}}function Kr(e,r,t){return I(e,t),function(t){return m(e,r,[t])}}function Zr(e,r){if("bytes"!==(e="".concat(e)))throw new TypeError("".concat(r," '").concat(e,"' is not a valid enumeration value for ReadableStreamType"));return e}function $r(e,r){if("byob"!==(e="".concat(e)))throw new TypeError("".concat(r," '").concat(e,"' is not a valid enumeration value for ReadableStreamReaderMode"));return e}function et(e,r){F(e,r);var t=null==e?void 0:e.preventAbort,n=null==e?void 0:e.preventCancel,o=null==e?void 0:e.preventClose,a=null==e?void 0:e.signal;return void 0!==a&&function(e,r){if(!function(e){if("object"!=typeof e||null===e)return!1;try{return"boolean"==typeof e.aborted}catch(e){return!1}}(e))throw new TypeError("".concat(r," is not an AbortSignal."))}(a,"".concat(r," has member 'signal' that")),{preventAbort:Boolean(t),preventCancel:Boolean(n),preventClose:Boolean(o),signal:a}}function rt(e,r){F(e,r);var t=null==e?void 0:e.readable;Q(t,"readable","ReadableWritablePair"),function(e,r){if(!x(e))throw new TypeError("".concat(r," is not a ReadableStream."))}(t,"".concat(r," has member 'readable' that"));var n=null==e?void 0:e.writable;return Q(n,"writable","ReadableWritablePair"),function(e,r){if(!V(e))throw new TypeError("".concat(r," is not a WritableStream."))}(n,"".concat(r," has member 'writable' that")),{readable:t,writable:n}}Object.defineProperties(Mr.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),o(Mr.prototype.close,"close"),o(Mr.prototype.enqueue,"enqueue"),o(Mr.prototype.error,"error"),"symbol"==typeof e.toStringTag&&Object.defineProperty(Mr.prototype,e.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});var tt=function(){function ReadableStream(e,r){void 0===e&&(e={}),void 0===r&&(r={}),void 0===e?e=null:D(e,"First parameter");var t,n=Ve(r,"Second parameter"),o=function(e,r){F(e,r);var t=e,n=null==t?void 0:t.autoAllocateChunkSize,o=null==t?void 0:t.cancel,a=null==t?void 0:t.pull,i=null==t?void 0:t.start,l=null==t?void 0:t.type;return{autoAllocateChunkSize:void 0===n?void 0:H(n,"".concat(r," has member 'autoAllocateChunkSize' that")),cancel:void 0===o?void 0:Xr(o,t,"".concat(r," has member 'cancel' that")),pull:void 0===a?void 0:Jr(a,t,"".concat(r," has member 'pull' that")),start:void 0===i?void 0:Kr(i,t,"".concat(r," has member 'start' that")),type:void 0===l?void 0:Zr(l,"".concat(r," has member 'type' that"))}}(e,"First parameter");if((t=this)._state="readable",t._reader=void 0,t._storedError=void 0,t._disturbed=!1,"bytes"===o.type){if(void 0!==n.size)throw new RangeError("The strategy for a byte stream cannot have a size function");Ae(this,o,He(n,0))}else{var a=xe(n);Ur(this,o,He(n,1),a)}}return Object.defineProperty(ReadableStream.prototype,"locked",{get:function(){if(!nt(this))throw ut("locked");return ot(this)},enumerable:!1,configurable:!0}),ReadableStream.prototype.cancel=function(e){return void 0===e&&(e=void 0),nt(this)?ot(this)?d(new TypeError("Cannot cancel a stream that already has a reader")):at(this,e):d(ut("cancel"))},ReadableStream.prototype.getReader=function(e){if(void 0===e&&(e=void 0),!nt(this))throw ut("getReader");return void 0===function(e,r){F(e,r);var t=null==e?void 0:e.mode;return{mode:void 0===t?void 0:$r(t,"".concat(r," has member 'mode' that"))}}(e,"First parameter").mode?new Z(this):function(e){return new Me(e)}(this)},ReadableStream.prototype.pipeThrough=function(e,r){if(void 0===r&&(r={}),!x(this))throw ut("pipeThrough");M(e,1,"pipeThrough");var t=rt(e,"First parameter"),n=et(r,"Second parameter");if(this.locked)throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(t.writable.locked)throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");return y(Ir(this,t.writable,n.preventClose,n.preventAbort,n.preventCancel,n.signal)),t.readable},ReadableStream.prototype.pipeTo=function(e,r){if(void 0===r&&(r={}),!x(this))return d(ut("pipeTo"));if(void 0===e)return d("Parameter 1 is required in 'pipeTo'.");if(!V(e))return d(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));var t;try{t=et(r,"Second parameter")}catch(e){return d(e)}return this.locked?d(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):e.locked?d(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):Ir(this,e,t.preventClose,t.preventAbort,t.preventCancel,t.signal)},ReadableStream.prototype.tee=function(){if(!x(this))throw ut("tee");if(this.locked)throw new TypeError("Cannot tee a stream that already has a reader");return Dr(this)},ReadableStream.prototype.values=function(e){if(void 0===e&&(e=void 0),!x(this))throw ut("values");var r,t,n,o,a,i=function(e,r){F(e,r);var t=null==e?void 0:e.preventCancel;return{preventCancel:Boolean(t)}}(e,"First parameter");return r=this,t=i.preventCancel,n=r.getReader(),o=new te(n,t),(a=Object.create(ne))._asyncIteratorImpl=o,a},ReadableStream}();function nt(e){return!!t(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readableStreamController")&&e instanceof tt)}function ot(e){return void 0!==e._reader}function at(e,t){if(e._disturbed=!0,"closed"===e._state)return c(void 0);if("errored"===e._state)return d(e._storedError);it(e);var n=e._reader;if(void 0!==n&&Qe(n)){var o=n._readIntoRequests;n._readIntoRequests=new w,o.forEach((function(e){e._closeSteps(void 0)}))}return _(e._readableStreamController[T](t),r)}function it(e){e._state="closed";var r=e._reader;if(void 0!==r&&(A(r),$(r))){var t=r._readRequests;r._readRequests=new w,t.forEach((function(e){e._closeSteps()}))}}function lt(e,r){e._state="errored",e._storedError=r;var t=e._reader;void 0!==t&&(B(t,r),$(t)?ee(t,r):Ye(t,r))}function ut(e){return new TypeError("ReadableStream.prototype.".concat(e," can only be used on a ReadableStream"))}function st(e,r){F(e,r);var t=null==e?void 0:e.highWaterMark;return Q(t,"highWaterMark","QueuingStrategyInit"),{highWaterMark:Y(t)}}Object.defineProperties(tt.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),o(tt.prototype.cancel,"cancel"),o(tt.prototype.getReader,"getReader"),o(tt.prototype.pipeThrough,"pipeThrough"),o(tt.prototype.pipeTo,"pipeTo"),o(tt.prototype.tee,"tee"),o(tt.prototype.values,"values"),"symbol"==typeof e.toStringTag&&Object.defineProperty(tt.prototype,e.toStringTag,{value:"ReadableStream",configurable:!0}),"symbol"==typeof e.asyncIterator&&Object.defineProperty(tt.prototype,e.asyncIterator,{value:tt.prototype.values,writable:!0,configurable:!0});var ct=function(e){return e.byteLength};o(ct,"size");var dt=function(){function ByteLengthQueuingStrategy(e){M(e,1,"ByteLengthQueuingStrategy"),e=st(e,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=e.highWaterMark}return Object.defineProperty(ByteLengthQueuingStrategy.prototype,"highWaterMark",{get:function(){if(!bt(this))throw ft("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark},enumerable:!1,configurable:!0}),Object.defineProperty(ByteLengthQueuingStrategy.prototype,"size",{get:function(){if(!bt(this))throw ft("size");return ct},enumerable:!1,configurable:!0}),ByteLengthQueuingStrategy}();function ft(e){return new TypeError("ByteLengthQueuingStrategy.prototype.".concat(e," can only be used on a ByteLengthQueuingStrategy"))}function bt(e){return!!t(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_byteLengthQueuingStrategyHighWaterMark")&&e instanceof dt)}Object.defineProperties(dt.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof e.toStringTag&&Object.defineProperty(dt.prototype,e.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});var pt=function(){return 1};o(pt,"size");var ht=function(){function CountQueuingStrategy(e){M(e,1,"CountQueuingStrategy"),e=st(e,"First parameter"),this._countQueuingStrategyHighWaterMark=e.highWaterMark}return Object.defineProperty(CountQueuingStrategy.prototype,"highWaterMark",{get:function(){if(!yt(this))throw _t("highWaterMark");return this._countQueuingStrategyHighWaterMark},enumerable:!1,configurable:!0}),Object.defineProperty(CountQueuingStrategy.prototype,"size",{get:function(){if(!yt(this))throw _t("size");return pt},enumerable:!1,configurable:!0}),CountQueuingStrategy}();function _t(e){return new TypeError("CountQueuingStrategy.prototype.".concat(e," can only be used on a CountQueuingStrategy"))}function yt(e){return!!t(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_countQueuingStrategyHighWaterMark")&&e instanceof ht)}function vt(e,r,t){return I(e,t),function(t){return g(e,r,[t])}}function mt(e,r,t){return I(e,t),function(t){return m(e,r,[t])}}function gt(e,r,t){return I(e,t),function(t,n){return g(e,r,[t,n])}}Object.defineProperties(ht.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof e.toStringTag&&Object.defineProperty(ht.prototype,e.toStringTag,{value:"CountQueuingStrategy",configurable:!0});var wt=function(){function TransformStream(e,r,t){void 0===e&&(e={}),void 0===r&&(r={}),void 0===t&&(t={}),void 0===e&&(e=null);var n=Ve(r,"Second parameter"),o=Ve(t,"Third parameter"),a=function(e,r){F(e,r);var t=null==e?void 0:e.flush,n=null==e?void 0:e.readableType,o=null==e?void 0:e.start,a=null==e?void 0:e.transform,i=null==e?void 0:e.writableType;return{flush:void 0===t?void 0:vt(t,e,"".concat(r," has member 'flush' that")),readableType:n,start:void 0===o?void 0:mt(o,e,"".concat(r," has member 'start' that")),transform:void 0===a?void 0:gt(a,e,"".concat(r," has member 'transform' that")),writableType:i}}(e,"First parameter");if(void 0!==a.readableType)throw new RangeError("Invalid readableType specified");if(void 0!==a.writableType)throw new RangeError("Invalid writableType specified");var i,l=He(o,0),u=xe(o),f=He(n,1),b=xe(n);!function(e,r,t,n,o,a){function i(){return r}function l(r){return function(e,r){var t=e._transformStreamController;if(e._backpressure){return _(e._backpressureChangePromise,(function(){if("erroring"===(er(e._writable)?e._writable._state:e._writableState))throw er(e._writable)?e._writable._storedError:e._writableStoredError;return Wt(t,r)}))}return Wt(t,r)}(e,r)}function u(r){return function(e,r){return Rt(e,r),c(void 0)}(e,r)}function s(){return function(e){var r=e._transformStreamController,t=r._flushAlgorithm();return Et(r),_(t,(function(){if("errored"===e._readableState)throw e._readableStoredError;Bt(e)&&At(e)}),(function(r){throw Rt(e,r),e._readableStoredError}))}(e)}function d(){return function(e){return qt(e,!1),e._backpressureChangePromise}(e)}function f(r){return Tt(e,r),c(void 0)}e._writableState="writable",e._writableStoredError=void 0,e._writableHasInFlightOperation=!1,e._writableStarted=!1,e._writable=function(e,r,t,n,o,a,i){return new $e({start:function(t){e._writableController=t;try{var n=t.signal;void 0!==n&&n.addEventListener("abort",(function(){"writable"===e._writableState&&(e._writableState="erroring",n.reason&&(e._writableStoredError=n.reason))}))}catch(e){}return _(r(),(function(){return e._writableStarted=!0,Mt(e),null}),(function(r){throw e._writableStarted=!0,Ft(e,r),r}))},write:function(r){return function(e){e._writableHasInFlightOperation=!0}(e),_(t(r),(function(){return function(e){e._writableHasInFlightOperation=!1}(e),Mt(e),null}),(function(r){throw function(e,r){e._writableHasInFlightOperation=!1,Ft(e,r)}(e,r),r}))},close:function(){return function(e){e._writableHasInFlightOperation=!0}(e),_(n(),(function(){return function(e){e._writableHasInFlightOperation=!1,"erroring"===e._writableState&&(e._writableStoredError=void 0);e._writableState="closed"}(e),null}),(function(r){throw function(e,r){e._writableHasInFlightOperation=!1,e._writableState,Ft(e,r)}(e,r),r}))},abort:function(r){return e._writableState="errored",e._writableStoredError=r,o(r)}},{highWaterMark:a,size:i})}(e,i,l,s,u,t,n),e._readableState="readable",e._readableStoredError=void 0,e._readableCloseRequested=!1,e._readablePulling=!1,e._readable=function(e,r,t,n,o,a){return new tt({start:function(t){return e._readableController=t,r().catch((function(r){zt(e,r)}))},pull:function(){return e._readablePulling=!0,t().catch((function(r){zt(e,r)}))},cancel:function(r){return e._readableState="closed",n(r)}},{highWaterMark:o,size:a})}(e,i,d,f,o,a),e._backpressure=void 0,e._backpressureChangePromise=void 0,e._backpressureChangePromise_resolve=void 0,qt(e,!0),e._transformStreamController=void 0}(this,s((function(e){i=e})),f,b,l,u),function(e,r){var t,n,o=Object.create(Pt.prototype);t=void 0!==r.transform?function(e){return r.transform(e,o)}:function(e){try{return Ot(o,e),c(void 0)}catch(e){return d(e)}};n=void 0!==r.flush?function(){return r.flush(o)}:function(){return c(void 0)};!function(e,r,t,n){r._controlledTransformStream=e,e._transformStreamController=r,r._transformAlgorithm=t,r._flushAlgorithm=n}(e,o,t,n)}(this,a),void 0!==a.start?i(a.start(this._transformStreamController)):i(void 0)}return Object.defineProperty(TransformStream.prototype,"readable",{get:function(){if(!St(this))throw jt("readable");return this._readable},enumerable:!1,configurable:!0}),Object.defineProperty(TransformStream.prototype,"writable",{get:function(){if(!St(this))throw jt("writable");return this._writable},enumerable:!1,configurable:!0}),TransformStream}();function St(e){return!!t(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_transformStreamController")&&e instanceof wt)}function Rt(e,r){zt(e,r),Tt(e,r)}function Tt(e,r){Et(e._transformStreamController),function(e,r){e._writableController.error(r),"writable"===e._writableState&&It(e,r)}(e,r),e._backpressure&&qt(e,!1)}function qt(e,r){void 0!==e._backpressureChangePromise&&e._backpressureChangePromise_resolve(),e._backpressureChangePromise=s((function(r){e._backpressureChangePromise_resolve=r})),e._backpressure=r}Object.defineProperties(wt.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),"symbol"==typeof e.toStringTag&&Object.defineProperty(wt.prototype,e.toStringTag,{value:"TransformStream",configurable:!0});var Pt=function(){function TransformStreamDefaultController(){throw new TypeError("Illegal constructor")}return Object.defineProperty(TransformStreamDefaultController.prototype,"desiredSize",{get:function(){if(!Ct(this))throw kt("desiredSize");return Lt(this._controlledTransformStream)},enumerable:!1,configurable:!0}),TransformStreamDefaultController.prototype.enqueue=function(e){if(void 0===e&&(e=void 0),!Ct(this))throw kt("enqueue");Ot(this,e)},TransformStreamDefaultController.prototype.error=function(e){if(void 0===e&&(e=void 0),!Ct(this))throw kt("error");var r;r=e,Rt(this._controlledTransformStream,r)},TransformStreamDefaultController.prototype.terminate=function(){if(!Ct(this))throw kt("terminate");!function(e){var r=e._controlledTransformStream;Bt(r)&&At(r);var t=new TypeError("TransformStream terminated");Tt(r,t)}(this)},TransformStreamDefaultController}();function Ct(e){return!!t(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledTransformStream")&&e instanceof Pt)}function Et(e){e._transformAlgorithm=void 0,e._flushAlgorithm=void 0}function Ot(e,r){var t=e._controlledTransformStream;if(!Bt(t))throw new TypeError("Readable side is not in a state that permits enqueue");try{!function(e,r){e._readablePulling=!1;try{e._readableController.enqueue(r)}catch(r){throw zt(e,r),r}}(t,r)}catch(e){throw Tt(t,e),t._readableStoredError}var n=function(e){return!function(e){if(!Bt(e))return!1;if(e._readablePulling)return!0;if(Lt(e)>0)return!0;return!1}(e)}(t);n!==t._backpressure&&qt(t,!0)}function Wt(e,r){return _(e._transformAlgorithm(r),void 0,(function(r){throw Rt(e._controlledTransformStream,r),r}))}function kt(e){return new TypeError("TransformStreamDefaultController.prototype.".concat(e," can only be used on a TransformStreamDefaultController"))}function jt(e){return new TypeError("TransformStream.prototype.".concat(e," can only be used on a TransformStream"))}function Bt(e){return!e._readableCloseRequested&&"readable"===e._readableState}function At(e){e._readableState="closed",e._readableCloseRequested=!0,e._readableController.close()}function zt(e,r){"readable"===e._readableState&&(e._readableState="errored",e._readableStoredError=r),e._readableController.error(r)}function Lt(e){return e._readableController.desiredSize}function Ft(e,r){"writable"!==e._writableState?Dt(e):It(e,r)}function It(e,r){e._writableState="erroring",e._writableStoredError=r,!function(e){return e._writableHasInFlightOperation}(e)&&e._writableStarted&&Dt(e)}function Dt(e){e._writableState="errored"}function Mt(e){"erroring"===e._writableState&&Dt(e)}Object.defineProperties(Pt.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),o(Pt.prototype.enqueue,"enqueue"),o(Pt.prototype.error,"error"),o(Pt.prototype.terminate,"terminate"),"symbol"==typeof e.toStringTag&&Object.defineProperty(Pt.prototype,e.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});var Qt="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof global?global:void 0,Yt={ReadableStream:tt,ReadableStreamDefaultController:Mr,ReadableByteStreamController:be,ReadableStreamBYOBRequest:fe,ReadableStreamDefaultReader:Z,ReadableStreamBYOBReader:Me,WritableStream:$e,WritableStreamDefaultController:pr,WritableStreamDefaultWriter:cr,ByteLengthQueuingStrategy:dt,CountQueuingStrategy:ht,TransformStream:wt,TransformStreamDefaultController:Pt};for(var Nt in Yt)Object.prototype.hasOwnProperty.call(Yt,Nt)&&Object.defineProperty(Qt,Nt,{value:Yt[Nt],writable:!0,configurable:!0})}(); diff --git a/backend/node_modules/formdata-node/node_modules/web-streams-polyfill/dist/polyfill.js b/backend/node_modules/formdata-node/node_modules/web-streams-polyfill/dist/polyfill.js new file mode 100644 index 0000000000000000000000000000000000000000..9809552c4e317b333fcf98494588d0837e77f42f --- /dev/null +++ b/backend/node_modules/formdata-node/node_modules/web-streams-polyfill/dist/polyfill.js @@ -0,0 +1,8 @@ +/** + * @license + * web-streams-polyfill v4.0.0-beta.3 + * Copyright 2021 Mattias Buelens, Diwank Singh Tomer and other contributors. + * This code is released under the MIT license. + * SPDX-License-Identifier: MIT + */ +!function(){"use strict";const e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol:e=>`Symbol(${e})`;function t(){}function r(e){return"object"==typeof e&&null!==e||"function"==typeof e}const o=t;function n(e,t){try{Object.defineProperty(e,"name",{value:t,configurable:!0})}catch(e){}}const a=Promise,i=Promise.prototype.then,l=Promise.resolve.bind(a),s=Promise.reject.bind(a);function u(e){return new a(e)}function c(e){return l(e)}function d(e){return s(e)}function f(e,t,r){return i.call(e,t,r)}function b(e,t,r){f(f(e,t,r),void 0,o)}function h(e,t){b(e,t)}function _(e,t){b(e,void 0,t)}function p(e,t,r){return f(e,t,r)}function m(e){f(e,void 0,o)}let y=e=>{if("function"==typeof queueMicrotask)y=queueMicrotask;else{const e=c(void 0);y=t=>f(e,t)}return y(e)};function g(e,t,r){if("function"!=typeof e)throw new TypeError("Argument is not a function");return Function.prototype.apply.call(e,t,r)}function S(e,t,r){try{return c(g(e,t,r))}catch(e){return d(e)}}class w{constructor(){this._cursor=0,this._size=0,this._front={_elements:[],_next:void 0},this._back=this._front,this._cursor=0,this._size=0}get length(){return this._size}push(e){const t=this._back;let r=t;16383===t._elements.length&&(r={_elements:[],_next:void 0}),t._elements.push(e),r!==t&&(this._back=r,t._next=r),++this._size}shift(){const e=this._front;let t=e;const r=this._cursor;let o=r+1;const n=e._elements,a=n[r];return 16384===o&&(t=e._next,o=0),--this._size,this._cursor=o,e!==t&&(this._front=t),n[r]=void 0,a}forEach(e){let t=this._cursor,r=this._front,o=r._elements;for(;!(t===o.length&&void 0===r._next||t===o.length&&(r=r._next,o=r._elements,t=0,0===o.length));)e(o[t]),++t}peek(){const e=this._front,t=this._cursor;return e._elements[t]}}const v=e("[[AbortSteps]]"),R=e("[[ErrorSteps]]"),T=e("[[CancelSteps]]"),q=e("[[PullSteps]]"),C=e("[[ReleaseSteps]]");function P(e,t){e._ownerReadableStream=t,t._reader=e,"readable"===t._state?k(e):"closed"===t._state?function(e){k(e),j(e)}(e):B(e,t._storedError)}function E(e,t){return Gt(e._ownerReadableStream,t)}function W(e){const t=e._ownerReadableStream;"readable"===t._state?A(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):function(e,t){B(e,t)}(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),t._readableStreamController[C](),t._reader=void 0,e._ownerReadableStream=void 0}function O(e){return new TypeError("Cannot "+e+" a stream using a released reader")}function k(e){e._closedPromise=u(((t,r)=>{e._closedPromise_resolve=t,e._closedPromise_reject=r}))}function B(e,t){k(e),A(e,t)}function A(e,t){void 0!==e._closedPromise_reject&&(m(e._closedPromise),e._closedPromise_reject(t),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}function j(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}const z=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},L=Math.trunc||function(e){return e<0?Math.ceil(e):Math.floor(e)};function F(e,t){if(void 0!==e&&("object"!=typeof(r=e)&&"function"!=typeof r))throw new TypeError(`${t} is not an object.`);var r}function D(e,t){if("function"!=typeof e)throw new TypeError(`${t} is not a function.`)}function I(e,t){if(!function(e){return"object"==typeof e&&null!==e||"function"==typeof e}(e))throw new TypeError(`${t} is not an object.`)}function $(e,t,r){if(void 0===e)throw new TypeError(`Parameter ${t} is required in '${r}'.`)}function M(e,t,r){if(void 0===e)throw new TypeError(`${t} is required in '${r}'.`)}function Y(e){return Number(e)}function Q(e){return 0===e?0:e}function N(e,t){const r=Number.MAX_SAFE_INTEGER;let o=Number(e);if(o=Q(o),!z(o))throw new TypeError(`${t} is not a finite number`);if(o=function(e){return Q(L(e))}(o),o<0||o>r)throw new TypeError(`${t} is outside the accepted range of 0 to ${r}, inclusive`);return z(o)&&0!==o?o:0}function H(e){if(!r(e))return!1;if("function"!=typeof e.getReader)return!1;try{return"boolean"==typeof e.locked}catch(e){return!1}}function x(e){if(!r(e))return!1;if("function"!=typeof e.getWriter)return!1;try{return"boolean"==typeof e.locked}catch(e){return!1}}function V(e,t){if(!Vt(e))throw new TypeError(`${t} is not a ReadableStream.`)}function U(e,t){e._reader._readRequests.push(t)}function G(e,t,r){const o=e._reader._readRequests.shift();r?o._closeSteps():o._chunkSteps(t)}function X(e){return e._reader._readRequests.length}function J(e){const t=e._reader;return void 0!==t&&!!K(t)}class ReadableStreamDefaultReader{constructor(e){if($(e,1,"ReadableStreamDefaultReader"),V(e,"First parameter"),Ut(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");P(this,e),this._readRequests=new w}get closed(){return K(this)?this._closedPromise:d(ee("closed"))}cancel(e){return K(this)?void 0===this._ownerReadableStream?d(O("cancel")):E(this,e):d(ee("cancel"))}read(){if(!K(this))return d(ee("read"));if(void 0===this._ownerReadableStream)return d(O("read from"));let e,t;const r=u(((r,o)=>{e=r,t=o}));return function(e,t){const r=e._ownerReadableStream;r._disturbed=!0,"closed"===r._state?t._closeSteps():"errored"===r._state?t._errorSteps(r._storedError):r._readableStreamController[q](t)}(this,{_chunkSteps:t=>e({value:t,done:!1}),_closeSteps:()=>e({value:void 0,done:!0}),_errorSteps:e=>t(e)}),r}releaseLock(){if(!K(this))throw ee("releaseLock");void 0!==this._ownerReadableStream&&function(e){W(e);const t=new TypeError("Reader was released");Z(e,t)}(this)}}function K(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readRequests")&&e instanceof ReadableStreamDefaultReader)}function Z(e,t){const r=e._readRequests;e._readRequests=new w,r.forEach((e=>{e._errorSteps(t)}))}function ee(e){return new TypeError(`ReadableStreamDefaultReader.prototype.${e} can only be used on a ReadableStreamDefaultReader`)}Object.defineProperties(ReadableStreamDefaultReader.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),n(ReadableStreamDefaultReader.prototype.cancel,"cancel"),n(ReadableStreamDefaultReader.prototype.read,"read"),n(ReadableStreamDefaultReader.prototype.releaseLock,"releaseLock"),"symbol"==typeof e.toStringTag&&Object.defineProperty(ReadableStreamDefaultReader.prototype,e.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0});class te{constructor(e,t){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=e,this._preventCancel=t}next(){const e=()=>this._nextSteps();return this._ongoingPromise=this._ongoingPromise?p(this._ongoingPromise,e,e):e(),this._ongoingPromise}return(e){const t=()=>this._returnSteps(e);return this._ongoingPromise?p(this._ongoingPromise,t,t):t()}_nextSteps(){if(this._isFinished)return Promise.resolve({value:void 0,done:!0});const e=this._reader;return void 0===e?d(O("iterate")):f(e.read(),(e=>{var t;return this._ongoingPromise=void 0,e.done&&(this._isFinished=!0,null===(t=this._reader)||void 0===t||t.releaseLock(),this._reader=void 0),e}),(e=>{var t;throw this._ongoingPromise=void 0,this._isFinished=!0,null===(t=this._reader)||void 0===t||t.releaseLock(),this._reader=void 0,e}))}_returnSteps(e){if(this._isFinished)return Promise.resolve({value:e,done:!0});this._isFinished=!0;const t=this._reader;if(void 0===t)return d(O("finish iterating"));if(this._reader=void 0,!this._preventCancel){const r=t.cancel(e);return t.releaseLock(),p(r,(()=>({value:e,done:!0})))}return t.releaseLock(),c({value:e,done:!0})}}const re={next(){return oe(this)?this._asyncIteratorImpl.next():d(ne("next"))},return(e){return oe(this)?this._asyncIteratorImpl.return(e):d(ne("return"))}};function oe(e){if(!r(e))return!1;if(!Object.prototype.hasOwnProperty.call(e,"_asyncIteratorImpl"))return!1;try{return e._asyncIteratorImpl instanceof te}catch(e){return!1}}function ne(e){return new TypeError(`ReadableStreamAsyncIterator.${e} can only be used on a ReadableSteamAsyncIterator`)}"symbol"==typeof e.asyncIterator&&Object.defineProperty(re,e.asyncIterator,{value(){return this},writable:!0,configurable:!0});const ae=Number.isNaN||function(e){return e!=e};function ie(e,t,r,o,n){new Uint8Array(e).set(new Uint8Array(r,o,n),t)}function le(e){const t=function(e,t,r){if(e.slice)return e.slice(t,r);const o=r-t,n=new ArrayBuffer(o);return ie(n,0,e,t,o),n}(e.buffer,e.byteOffset,e.byteOffset+e.byteLength);return new Uint8Array(t)}function se(e){const t=e._queue.shift();return e._queueTotalSize-=t.size,e._queueTotalSize<0&&(e._queueTotalSize=0),t.value}function ue(e,t,r){if("number"!=typeof(o=r)||ae(o)||o<0||r===1/0)throw new RangeError("Size must be a finite, non-NaN, non-negative number.");var o;e._queue.push({value:t,size:r}),e._queueTotalSize+=r}function ce(e){e._queue=new w,e._queueTotalSize=0}class ReadableStreamBYOBRequest{constructor(){throw new TypeError("Illegal constructor")}get view(){if(!fe(this))throw Be("view");return this._view}respond(e){if(!fe(this))throw Be("respond");if($(e,1,"respond"),e=N(e,"First parameter"),void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");this._view.buffer,function(e,t){const r=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==t)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream")}else{if(0===t)throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");if(r.bytesFilled+t>r.byteLength)throw new RangeError("bytesWritten out of range")}r.buffer=r.buffer,qe(e,t)}(this._associatedReadableByteStreamController,e)}respondWithNewView(e){if(!fe(this))throw Be("respondWithNewView");if($(e,1,"respondWithNewView"),!ArrayBuffer.isView(e))throw new TypeError("You can only respond with array buffer views");if(void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");e.buffer,function(e,t){const r=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==t.byteLength)throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream")}else if(0===t.byteLength)throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");if(r.byteOffset+r.bytesFilled!==t.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(r.bufferByteLength!==t.buffer.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");if(r.bytesFilled+t.byteLength>r.byteLength)throw new RangeError("The region specified by view is larger than byobRequest");const o=t.byteLength;r.buffer=t.buffer,qe(e,o)}(this._associatedReadableByteStreamController,e)}}Object.defineProperties(ReadableStreamBYOBRequest.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),n(ReadableStreamBYOBRequest.prototype.respond,"respond"),n(ReadableStreamBYOBRequest.prototype.respondWithNewView,"respondWithNewView"),"symbol"==typeof e.toStringTag&&Object.defineProperty(ReadableStreamBYOBRequest.prototype,e.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});class ReadableByteStreamController{constructor(){throw new TypeError("Illegal constructor")}get byobRequest(){if(!de(this))throw Ae("byobRequest");return function(e){if(null===e._byobRequest&&e._pendingPullIntos.length>0){const t=e._pendingPullIntos.peek(),r=new Uint8Array(t.buffer,t.byteOffset+t.bytesFilled,t.byteLength-t.bytesFilled),o=Object.create(ReadableStreamBYOBRequest.prototype);!function(e,t,r){e._associatedReadableByteStreamController=t,e._view=r}(o,e,r),e._byobRequest=o}return e._byobRequest}(this)}get desiredSize(){if(!de(this))throw Ae("desiredSize");return Oe(this)}close(){if(!de(this))throw Ae("close");if(this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");const e=this._controlledReadableByteStream._state;if("readable"!==e)throw new TypeError(`The stream (in ${e} state) is not in the readable state and cannot be closed`);!function(e){const t=e._controlledReadableByteStream;if(e._closeRequested||"readable"!==t._state)return;if(e._queueTotalSize>0)return void(e._closeRequested=!0);if(e._pendingPullIntos.length>0){if(e._pendingPullIntos.peek().bytesFilled>0){const t=new TypeError("Insufficient bytes to fill elements in the given buffer");throw Ee(e,t),t}}Pe(e),Xt(t)}(this)}enqueue(e){if(!de(this))throw Ae("enqueue");if($(e,1,"enqueue"),!ArrayBuffer.isView(e))throw new TypeError("chunk must be an array buffer view");if(0===e.byteLength)throw new TypeError("chunk must have non-zero byteLength");if(0===e.buffer.byteLength)throw new TypeError("chunk's buffer must have non-zero byteLength");if(this._closeRequested)throw new TypeError("stream is closed or draining");const t=this._controlledReadableByteStream._state;if("readable"!==t)throw new TypeError(`The stream (in ${t} state) is not in the readable state and cannot be enqueued to`);!function(e,t){const r=e._controlledReadableByteStream;if(e._closeRequested||"readable"!==r._state)return;const o=t.buffer,n=t.byteOffset,a=t.byteLength,i=o;if(e._pendingPullIntos.length>0){const t=e._pendingPullIntos.peek();t.buffer,0,Re(e),t.buffer=t.buffer,"none"===t.readerType&&ge(e,t)}if(J(r))if(function(e){const t=e._controlledReadableByteStream._reader;for(;t._readRequests.length>0;){if(0===e._queueTotalSize)return;We(e,t._readRequests.shift())}}(e),0===X(r))me(e,i,n,a);else{e._pendingPullIntos.length>0&&Ce(e);G(r,new Uint8Array(i,n,a),!1)}else Le(r)?(me(e,i,n,a),Te(e)):me(e,i,n,a);be(e)}(this,e)}error(e){if(!de(this))throw Ae("error");Ee(this,e)}[T](e){he(this),ce(this);const t=this._cancelAlgorithm(e);return Pe(this),t}[q](e){const t=this._controlledReadableByteStream;if(this._queueTotalSize>0)return void We(this,e);const r=this._autoAllocateChunkSize;if(void 0!==r){let t;try{t=new ArrayBuffer(r)}catch(t){return void e._errorSteps(t)}const o={buffer:t,bufferByteLength:r,byteOffset:0,byteLength:r,bytesFilled:0,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(o)}U(t,e),be(this)}[C](){if(this._pendingPullIntos.length>0){const e=this._pendingPullIntos.peek();e.readerType="none",this._pendingPullIntos=new w,this._pendingPullIntos.push(e)}}}function de(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableByteStream")&&e instanceof ReadableByteStreamController)}function fe(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_associatedReadableByteStreamController")&&e instanceof ReadableStreamBYOBRequest)}function be(e){const t=function(e){const t=e._controlledReadableByteStream;if("readable"!==t._state)return!1;if(e._closeRequested)return!1;if(!e._started)return!1;if(J(t)&&X(t)>0)return!0;if(Le(t)&&ze(t)>0)return!0;if(Oe(e)>0)return!0;return!1}(e);if(!t)return;if(e._pulling)return void(e._pullAgain=!0);e._pulling=!0;b(e._pullAlgorithm(),(()=>(e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,be(e)),null)),(t=>(Ee(e,t),null)))}function he(e){Re(e),e._pendingPullIntos=new w}function _e(e,t){let r=!1;"closed"===e._state&&(r=!0);const o=pe(t);"default"===t.readerType?G(e,o,r):function(e,t,r){const o=e._reader._readIntoRequests.shift();r?o._closeSteps(t):o._chunkSteps(t)}(e,o,r)}function pe(e){const t=e.bytesFilled,r=e.elementSize;return new e.viewConstructor(e.buffer,e.byteOffset,t/r)}function me(e,t,r,o){e._queue.push({buffer:t,byteOffset:r,byteLength:o}),e._queueTotalSize+=o}function ye(e,t,r,o){let n;try{n=t.slice(r,r+o)}catch(t){throw Ee(e,t),t}me(e,n,0,o)}function ge(e,t){t.bytesFilled>0&&ye(e,t.buffer,t.byteOffset,t.bytesFilled),Ce(e)}function Se(e,t){const r=t.elementSize,o=t.bytesFilled-t.bytesFilled%r,n=Math.min(e._queueTotalSize,t.byteLength-t.bytesFilled),a=t.bytesFilled+n,i=a-a%r;let l=n,s=!1;i>o&&(l=i-t.bytesFilled,s=!0);const u=e._queue;for(;l>0;){const r=u.peek(),o=Math.min(l,r.byteLength),n=t.byteOffset+t.bytesFilled;ie(t.buffer,n,r.buffer,r.byteOffset,o),r.byteLength===o?u.shift():(r.byteOffset+=o,r.byteLength-=o),e._queueTotalSize-=o,we(e,o,t),l-=o}return s}function we(e,t,r){r.bytesFilled+=t}function ve(e){0===e._queueTotalSize&&e._closeRequested?(Pe(e),Xt(e._controlledReadableByteStream)):be(e)}function Re(e){null!==e._byobRequest&&(e._byobRequest._associatedReadableByteStreamController=void 0,e._byobRequest._view=null,e._byobRequest=null)}function Te(e){for(;e._pendingPullIntos.length>0;){if(0===e._queueTotalSize)return;const t=e._pendingPullIntos.peek();Se(e,t)&&(Ce(e),_e(e._controlledReadableByteStream,t))}}function qe(e,t){const r=e._pendingPullIntos.peek();Re(e);"closed"===e._controlledReadableByteStream._state?function(e,t){"none"===t.readerType&&Ce(e);const r=e._controlledReadableByteStream;if(Le(r))for(;ze(r)>0;)_e(r,Ce(e))}(e,r):function(e,t,r){if(we(0,t,r),"none"===r.readerType)return ge(e,r),void Te(e);if(r.bytesFilled0){const t=r.byteOffset+r.bytesFilled;ye(e,r.buffer,t-o,o)}r.bytesFilled-=o,_e(e._controlledReadableByteStream,r),Te(e)}(e,t,r),be(e)}function Ce(e){return e._pendingPullIntos.shift()}function Pe(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0}function Ee(e,t){const r=e._controlledReadableByteStream;"readable"===r._state&&(he(e),ce(e),Pe(e),Jt(r,t))}function We(e,t){const r=e._queue.shift();e._queueTotalSize-=r.byteLength,ve(e);const o=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);t._chunkSteps(o)}function Oe(e){const t=e._controlledReadableByteStream._state;return"errored"===t?null:"closed"===t?0:e._strategyHWM-e._queueTotalSize}function ke(e,t,r){const o=Object.create(ReadableByteStreamController.prototype);let n,a,i;n=void 0!==t.start?()=>t.start(o):()=>{},a=void 0!==t.pull?()=>t.pull(o):()=>c(void 0),i=void 0!==t.cancel?e=>t.cancel(e):()=>c(void 0);const l=t.autoAllocateChunkSize;if(0===l)throw new TypeError("autoAllocateChunkSize must be greater than 0");!function(e,t,r,o,n,a,i){t._controlledReadableByteStream=e,t._pullAgain=!1,t._pulling=!1,t._byobRequest=null,t._queue=t._queueTotalSize=void 0,ce(t),t._closeRequested=!1,t._started=!1,t._strategyHWM=a,t._pullAlgorithm=o,t._cancelAlgorithm=n,t._autoAllocateChunkSize=i,t._pendingPullIntos=new w,e._readableStreamController=t,b(c(r()),(()=>(t._started=!0,be(t),null)),(e=>(Ee(t,e),null)))}(e,o,n,a,i,r,l)}function Be(e){return new TypeError(`ReadableStreamBYOBRequest.prototype.${e} can only be used on a ReadableStreamBYOBRequest`)}function Ae(e){return new TypeError(`ReadableByteStreamController.prototype.${e} can only be used on a ReadableByteStreamController`)}function je(e,t){e._reader._readIntoRequests.push(t)}function ze(e){return e._reader._readIntoRequests.length}function Le(e){const t=e._reader;return void 0!==t&&!!Fe(t)}Object.defineProperties(ReadableByteStreamController.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),n(ReadableByteStreamController.prototype.close,"close"),n(ReadableByteStreamController.prototype.enqueue,"enqueue"),n(ReadableByteStreamController.prototype.error,"error"),"symbol"==typeof e.toStringTag&&Object.defineProperty(ReadableByteStreamController.prototype,e.toStringTag,{value:"ReadableByteStreamController",configurable:!0});class ReadableStreamBYOBReader{constructor(e){if($(e,1,"ReadableStreamBYOBReader"),V(e,"First parameter"),Ut(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!de(e._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");P(this,e),this._readIntoRequests=new w}get closed(){return Fe(this)?this._closedPromise:d(Ie("closed"))}cancel(e){return Fe(this)?void 0===this._ownerReadableStream?d(O("cancel")):E(this,e):d(Ie("cancel"))}read(e){if(!Fe(this))return d(Ie("read"));if(!ArrayBuffer.isView(e))return d(new TypeError("view must be an array buffer view"));if(0===e.byteLength)return d(new TypeError("view must have non-zero byteLength"));if(0===e.buffer.byteLength)return d(new TypeError("view's buffer must have non-zero byteLength"));if(e.buffer,void 0===this._ownerReadableStream)return d(O("read from"));let t,r;const o=u(((e,o)=>{t=e,r=o}));return function(e,t,r){const o=e._ownerReadableStream;o._disturbed=!0,"errored"===o._state?r._errorSteps(o._storedError):function(e,t,r){const o=e._controlledReadableByteStream;let n=1;t.constructor!==DataView&&(n=t.constructor.BYTES_PER_ELEMENT);const a=t.constructor,i=t.buffer,l={buffer:i,bufferByteLength:i.byteLength,byteOffset:t.byteOffset,byteLength:t.byteLength,bytesFilled:0,elementSize:n,viewConstructor:a,readerType:"byob"};if(e._pendingPullIntos.length>0)return e._pendingPullIntos.push(l),void je(o,r);if("closed"!==o._state){if(e._queueTotalSize>0){if(Se(e,l)){const t=pe(l);return ve(e),void r._chunkSteps(t)}if(e._closeRequested){const t=new TypeError("Insufficient bytes to fill elements in the given buffer");return Ee(e,t),void r._errorSteps(t)}}e._pendingPullIntos.push(l),je(o,r),be(e)}else{const e=new a(l.buffer,l.byteOffset,0);r._closeSteps(e)}}(o._readableStreamController,t,r)}(this,e,{_chunkSteps:e=>t({value:e,done:!1}),_closeSteps:e=>t({value:e,done:!0}),_errorSteps:e=>r(e)}),o}releaseLock(){if(!Fe(this))throw Ie("releaseLock");void 0!==this._ownerReadableStream&&function(e){W(e);const t=new TypeError("Reader was released");De(e,t)}(this)}}function Fe(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readIntoRequests")&&e instanceof ReadableStreamBYOBReader)}function De(e,t){const r=e._readIntoRequests;e._readIntoRequests=new w,r.forEach((e=>{e._errorSteps(t)}))}function Ie(e){return new TypeError(`ReadableStreamBYOBReader.prototype.${e} can only be used on a ReadableStreamBYOBReader`)}function $e(e,t){const{highWaterMark:r}=e;if(void 0===r)return t;if(ae(r)||r<0)throw new RangeError("Invalid highWaterMark");return r}function Me(e){const{size:t}=e;return t||(()=>1)}function Ye(e,t){F(e,t);const r=null==e?void 0:e.highWaterMark,o=null==e?void 0:e.size;return{highWaterMark:void 0===r?void 0:Y(r),size:void 0===o?void 0:Qe(o,`${t} has member 'size' that`)}}function Qe(e,t){return D(e,t),t=>Y(e(t))}function Ne(e,t,r){return D(e,r),r=>S(e,t,[r])}function He(e,t,r){return D(e,r),()=>S(e,t,[])}function xe(e,t,r){return D(e,r),r=>g(e,t,[r])}function Ve(e,t,r){return D(e,r),(r,o)=>S(e,t,[r,o])}Object.defineProperties(ReadableStreamBYOBReader.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),n(ReadableStreamBYOBReader.prototype.cancel,"cancel"),n(ReadableStreamBYOBReader.prototype.read,"read"),n(ReadableStreamBYOBReader.prototype.releaseLock,"releaseLock"),"symbol"==typeof e.toStringTag&&Object.defineProperty(ReadableStreamBYOBReader.prototype,e.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});const Ue="function"==typeof AbortController;class WritableStream{constructor(e={},t={}){void 0===e?e=null:I(e,"First parameter");const r=Ye(t,"Second parameter"),o=function(e,t){F(e,t);const r=null==e?void 0:e.abort,o=null==e?void 0:e.close,n=null==e?void 0:e.start,a=null==e?void 0:e.type,i=null==e?void 0:e.write;return{abort:void 0===r?void 0:Ne(r,e,`${t} has member 'abort' that`),close:void 0===o?void 0:He(o,e,`${t} has member 'close' that`),start:void 0===n?void 0:xe(n,e,`${t} has member 'start' that`),write:void 0===i?void 0:Ve(i,e,`${t} has member 'write' that`),type:a}}(e,"First parameter");var n;(n=this)._state="writable",n._storedError=void 0,n._writer=void 0,n._writableStreamController=void 0,n._writeRequests=new w,n._inFlightWriteRequest=void 0,n._closeRequest=void 0,n._inFlightCloseRequest=void 0,n._pendingAbortRequest=void 0,n._backpressure=!1;if(void 0!==o.type)throw new RangeError("Invalid type is specified");const a=Me(r);!function(e,t,r,o){const n=Object.create(WritableStreamDefaultController.prototype);let a,i,l,s;a=void 0!==t.start?()=>t.start(n):()=>{};i=void 0!==t.write?e=>t.write(e,n):()=>c(void 0);l=void 0!==t.close?()=>t.close():()=>c(void 0);s=void 0!==t.abort?e=>t.abort(e):()=>c(void 0);!function(e,t,r,o,n,a,i,l){t._controlledWritableStream=e,e._writableStreamController=t,t._queue=void 0,t._queueTotalSize=void 0,ce(t),t._abortReason=void 0,t._abortController=function(){if(Ue)return new AbortController}(),t._started=!1,t._strategySizeAlgorithm=l,t._strategyHWM=i,t._writeAlgorithm=o,t._closeAlgorithm=n,t._abortAlgorithm=a;const s=bt(t);nt(e,s);const u=r();b(c(u),(()=>(t._started=!0,dt(t),null)),(r=>(t._started=!0,Ze(e,r),null)))}(e,n,a,i,l,s,r,o)}(this,o,$e(r,1),a)}get locked(){if(!Ge(this))throw _t("locked");return Xe(this)}abort(e){return Ge(this)?Xe(this)?d(new TypeError("Cannot abort a stream that already has a writer")):Je(this,e):d(_t("abort"))}close(){return Ge(this)?Xe(this)?d(new TypeError("Cannot close a stream that already has a writer")):rt(this)?d(new TypeError("Cannot close an already-closing stream")):Ke(this):d(_t("close"))}getWriter(){if(!Ge(this))throw _t("getWriter");return new WritableStreamDefaultWriter(this)}}function Ge(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_writableStreamController")&&e instanceof WritableStream)}function Xe(e){return void 0!==e._writer}function Je(e,t){var r;if("closed"===e._state||"errored"===e._state)return c(void 0);e._writableStreamController._abortReason=t,null===(r=e._writableStreamController._abortController)||void 0===r||r.abort(t);const o=e._state;if("closed"===o||"errored"===o)return c(void 0);if(void 0!==e._pendingAbortRequest)return e._pendingAbortRequest._promise;let n=!1;"erroring"===o&&(n=!0,t=void 0);const a=u(((r,o)=>{e._pendingAbortRequest={_promise:void 0,_resolve:r,_reject:o,_reason:t,_wasAlreadyErroring:n}}));return e._pendingAbortRequest._promise=a,n||et(e,t),a}function Ke(e){const t=e._state;if("closed"===t||"errored"===t)return d(new TypeError(`The stream (in ${t} state) is not in the writable state and cannot be closed`));const r=u(((t,r)=>{const o={_resolve:t,_reject:r};e._closeRequest=o})),o=e._writer;var n;return void 0!==o&&e._backpressure&&"writable"===t&&Pt(o),ue(n=e._writableStreamController,lt,0),dt(n),r}function Ze(e,t){"writable"!==e._state?tt(e):et(e,t)}function et(e,t){const r=e._writableStreamController;e._state="erroring",e._storedError=t;const o=e._writer;void 0!==o&&it(o,t),!function(e){if(void 0===e._inFlightWriteRequest&&void 0===e._inFlightCloseRequest)return!1;return!0}(e)&&r._started&&tt(e)}function tt(e){e._state="errored",e._writableStreamController[R]();const t=e._storedError;if(e._writeRequests.forEach((e=>{e._reject(t)})),e._writeRequests=new w,void 0===e._pendingAbortRequest)return void ot(e);const r=e._pendingAbortRequest;if(e._pendingAbortRequest=void 0,r._wasAlreadyErroring)return r._reject(t),void ot(e);b(e._writableStreamController[v](r._reason),(()=>(r._resolve(),ot(e),null)),(t=>(r._reject(t),ot(e),null)))}function rt(e){return void 0!==e._closeRequest||void 0!==e._inFlightCloseRequest}function ot(e){void 0!==e._closeRequest&&(e._closeRequest._reject(e._storedError),e._closeRequest=void 0);const t=e._writer;void 0!==t&&wt(t,e._storedError)}function nt(e,t){const r=e._writer;void 0!==r&&t!==e._backpressure&&(t?function(e){Rt(e)}(r):Pt(r)),e._backpressure=t}Object.defineProperties(WritableStream.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),n(WritableStream.prototype.abort,"abort"),n(WritableStream.prototype.close,"close"),n(WritableStream.prototype.getWriter,"getWriter"),"symbol"==typeof e.toStringTag&&Object.defineProperty(WritableStream.prototype,e.toStringTag,{value:"WritableStream",configurable:!0});class WritableStreamDefaultWriter{constructor(e){if($(e,1,"WritableStreamDefaultWriter"),function(e,t){if(!Ge(e))throw new TypeError(`${t} is not a WritableStream.`)}(e,"First parameter"),Xe(e))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=e,e._writer=this;const t=e._state;if("writable"===t)!rt(e)&&e._backpressure?Rt(this):qt(this),gt(this);else if("erroring"===t)Tt(this,e._storedError),gt(this);else if("closed"===t)qt(this),gt(r=this),vt(r);else{const t=e._storedError;Tt(this,t),St(this,t)}var r}get closed(){return at(this)?this._closedPromise:d(mt("closed"))}get desiredSize(){if(!at(this))throw mt("desiredSize");if(void 0===this._ownerWritableStream)throw yt("desiredSize");return function(e){const t=e._ownerWritableStream,r=t._state;if("errored"===r||"erroring"===r)return null;if("closed"===r)return 0;return ct(t._writableStreamController)}(this)}get ready(){return at(this)?this._readyPromise:d(mt("ready"))}abort(e){return at(this)?void 0===this._ownerWritableStream?d(yt("abort")):function(e,t){return Je(e._ownerWritableStream,t)}(this,e):d(mt("abort"))}close(){if(!at(this))return d(mt("close"));const e=this._ownerWritableStream;return void 0===e?d(yt("close")):rt(e)?d(new TypeError("Cannot close an already-closing stream")):Ke(this._ownerWritableStream)}releaseLock(){if(!at(this))throw mt("releaseLock");void 0!==this._ownerWritableStream&&function(e){const t=e._ownerWritableStream,r=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");it(e,r),function(e,t){"pending"===e._closedPromiseState?wt(e,t):function(e,t){St(e,t)}(e,t)}(e,r),t._writer=void 0,e._ownerWritableStream=void 0}(this)}write(e){return at(this)?void 0===this._ownerWritableStream?d(yt("write to")):function(e,t){const r=e._ownerWritableStream,o=r._writableStreamController,n=function(e,t){try{return e._strategySizeAlgorithm(t)}catch(t){return ft(e,t),1}}(o,t);if(r!==e._ownerWritableStream)return d(yt("write to"));const a=r._state;if("errored"===a)return d(r._storedError);if(rt(r)||"closed"===a)return d(new TypeError("The stream is closing or closed and cannot be written to"));if("erroring"===a)return d(r._storedError);const i=function(e){return u(((t,r)=>{const o={_resolve:t,_reject:r};e._writeRequests.push(o)}))}(r);return function(e,t,r){try{ue(e,t,r)}catch(t){return void ft(e,t)}const o=e._controlledWritableStream;if(!rt(o)&&"writable"===o._state){nt(o,bt(e))}dt(e)}(o,t,n),i}(this,e):d(mt("write"))}}function at(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_ownerWritableStream")&&e instanceof WritableStreamDefaultWriter)}function it(e,t){"pending"===e._readyPromiseState?Ct(e,t):function(e,t){Tt(e,t)}(e,t)}Object.defineProperties(WritableStreamDefaultWriter.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),n(WritableStreamDefaultWriter.prototype.abort,"abort"),n(WritableStreamDefaultWriter.prototype.close,"close"),n(WritableStreamDefaultWriter.prototype.releaseLock,"releaseLock"),n(WritableStreamDefaultWriter.prototype.write,"write"),"symbol"==typeof e.toStringTag&&Object.defineProperty(WritableStreamDefaultWriter.prototype,e.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});const lt={};class WritableStreamDefaultController{constructor(){throw new TypeError("Illegal constructor")}get abortReason(){if(!st(this))throw pt("abortReason");return this._abortReason}get signal(){if(!st(this))throw pt("signal");if(void 0===this._abortController)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal}error(e){if(!st(this))throw pt("error");"writable"===this._controlledWritableStream._state&&ht(this,e)}[v](e){const t=this._abortAlgorithm(e);return ut(this),t}[R](){ce(this)}}function st(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledWritableStream")&&e instanceof WritableStreamDefaultController)}function ut(e){e._writeAlgorithm=void 0,e._closeAlgorithm=void 0,e._abortAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function ct(e){return e._strategyHWM-e._queueTotalSize}function dt(e){const t=e._controlledWritableStream;if(!e._started)return;if(void 0!==t._inFlightWriteRequest)return;if("erroring"===t._state)return void tt(t);if(0===e._queue.length)return;const r=e._queue.peek().value;r===lt?function(e){const t=e._controlledWritableStream;(function(e){e._inFlightCloseRequest=e._closeRequest,e._closeRequest=void 0})(t),se(e);const r=e._closeAlgorithm();ut(e),b(r,(()=>(function(e){e._inFlightCloseRequest._resolve(void 0),e._inFlightCloseRequest=void 0,"erroring"===e._state&&(e._storedError=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._resolve(),e._pendingAbortRequest=void 0)),e._state="closed";const t=e._writer;void 0!==t&&vt(t)}(t),null)),(e=>(function(e,t){e._inFlightCloseRequest._reject(t),e._inFlightCloseRequest=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._reject(t),e._pendingAbortRequest=void 0),Ze(e,t)}(t,e),null)))}(e):function(e,t){const r=e._controlledWritableStream;!function(e){e._inFlightWriteRequest=e._writeRequests.shift()}(r);b(e._writeAlgorithm(t),(()=>{!function(e){e._inFlightWriteRequest._resolve(void 0),e._inFlightWriteRequest=void 0}(r);const t=r._state;if(se(e),!rt(r)&&"writable"===t){const t=bt(e);nt(r,t)}return dt(e),null}),(t=>("writable"===r._state&&ut(e),function(e,t){e._inFlightWriteRequest._reject(t),e._inFlightWriteRequest=void 0,Ze(e,t)}(r,t),null)))}(e,r)}function ft(e,t){"writable"===e._controlledWritableStream._state&&ht(e,t)}function bt(e){return ct(e)<=0}function ht(e,t){const r=e._controlledWritableStream;ut(e),et(r,t)}function _t(e){return new TypeError(`WritableStream.prototype.${e} can only be used on a WritableStream`)}function pt(e){return new TypeError(`WritableStreamDefaultController.prototype.${e} can only be used on a WritableStreamDefaultController`)}function mt(e){return new TypeError(`WritableStreamDefaultWriter.prototype.${e} can only be used on a WritableStreamDefaultWriter`)}function yt(e){return new TypeError("Cannot "+e+" a stream using a released writer")}function gt(e){e._closedPromise=u(((t,r)=>{e._closedPromise_resolve=t,e._closedPromise_reject=r,e._closedPromiseState="pending"}))}function St(e,t){gt(e),wt(e,t)}function wt(e,t){void 0!==e._closedPromise_reject&&(m(e._closedPromise),e._closedPromise_reject(t),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="rejected")}function vt(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="resolved")}function Rt(e){e._readyPromise=u(((t,r)=>{e._readyPromise_resolve=t,e._readyPromise_reject=r})),e._readyPromiseState="pending"}function Tt(e,t){Rt(e),Ct(e,t)}function qt(e){Rt(e),Pt(e)}function Ct(e,t){void 0!==e._readyPromise_reject&&(m(e._readyPromise),e._readyPromise_reject(t),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="rejected")}function Pt(e){void 0!==e._readyPromise_resolve&&(e._readyPromise_resolve(void 0),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="fulfilled")}Object.defineProperties(WritableStreamDefaultController.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),"symbol"==typeof e.toStringTag&&Object.defineProperty(WritableStreamDefaultController.prototype,e.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});const Et="undefined"!=typeof DOMException?DOMException:void 0;const Wt=function(e){if("function"!=typeof e&&"object"!=typeof e)return!1;try{return new e,!0}catch(e){return!1}}(Et)?Et:function(){const e=function(e,t){this.message=e||"",this.name=t||"Error",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)};return e.prototype=Object.create(Error.prototype),Object.defineProperty(e.prototype,"constructor",{value:e,writable:!0,configurable:!0}),e}();function Ot(e,t,r,o,n,a){const i=e.getReader(),l=t.getWriter();Vt(e)&&(e._disturbed=!0);let s,_,g,S=!1,w=!1,v="readable",R="writable",T=!1,q=!1;const C=u((e=>{g=e}));let P=Promise.resolve(void 0);return u(((E,W)=>{let O;function k(){if(S)return;const e=u(((e,t)=>{!function r(o){o?e():f(function(){if(S)return c(!0);return f(l.ready,(()=>f(i.read(),(e=>!!e.done||(P=l.write(e.value),m(P),!1)))))}(),r,t)}(!1)}));m(e)}function B(){return v="closed",r?L():z((()=>(Ge(t)&&(T=rt(t),R=t._state),T||"closed"===R?c(void 0):"erroring"===R||"errored"===R?d(_):(T=!0,l.close()))),!1,void 0),null}function A(e){return S||(v="errored",s=e,o?L(!0,e):z((()=>l.abort(e)),!0,e)),null}function j(e){return w||(R="errored",_=e,n?L(!0,e):z((()=>i.cancel(e)),!0,e)),null}if(void 0!==a&&(O=()=>{const e=void 0!==a.reason?a.reason:new Wt("Aborted","AbortError"),t=[];o||t.push((()=>"writable"===R?l.abort(e):c(void 0))),n||t.push((()=>"readable"===v?i.cancel(e):c(void 0))),z((()=>Promise.all(t.map((e=>e())))),!0,e)},a.aborted?O():a.addEventListener("abort",O)),Vt(e)&&(v=e._state,s=e._storedError),Ge(t)&&(R=t._state,_=t._storedError,T=rt(t)),Vt(e)&&Ge(t)&&(q=!0,g()),"errored"===v)A(s);else if("erroring"===R||"errored"===R)j(_);else if("closed"===v)B();else if(T||"closed"===R){const e=new TypeError("the destination writable stream closed before all data could be piped to it");n?L(!0,e):z((()=>i.cancel(e)),!0,e)}function z(e,t,r){function o(){return"writable"!==R||T?n():h(function(){let e;return c(function t(){if(e!==P)return e=P,p(P,t,t)}())}(),n),null}function n(){return e?b(e(),(()=>F(t,r)),(e=>F(!0,e))):F(t,r),null}S||(S=!0,q?o():h(C,o))}function L(e,t){z(void 0,e,t)}function F(e,t){return w=!0,l.releaseLock(),i.releaseLock(),void 0!==a&&a.removeEventListener("abort",O),e?W(t):E(void 0),null}S||(b(i.closed,B,A),b(l.closed,(function(){return w||(R="closed"),null}),j)),q?k():y((()=>{q=!0,g(),k()}))}))}function kt(e,t){return function(e){try{return e.getReader({mode:"byob"}).releaseLock(),!0}catch(e){return!1}}(e)?function(e){let t,r,o,n,a,i=e.getReader(),l=!1,s=!1,d=!1,f=!1,h=!1,p=!1;const m=u((e=>{a=e}));function y(e){_(e.closed,(t=>(e!==i||(o.error(t),n.error(t),h&&p||a(void 0)),null)))}function g(){l&&(i.releaseLock(),i=e.getReader(),y(i),l=!1),b(i.read(),(e=>{var t,r;if(d=!1,f=!1,e.done)return h||o.close(),p||n.close(),null===(t=o.byobRequest)||void 0===t||t.respond(0),null===(r=n.byobRequest)||void 0===r||r.respond(0),h&&p||a(void 0),null;const l=e.value,u=l;let c=l;if(!h&&!p)try{c=le(l)}catch(e){return o.error(e),n.error(e),a(i.cancel(e)),null}return h||o.enqueue(u),p||n.enqueue(c),s=!1,d?w():f&&v(),null}),(()=>(s=!1,null)))}function S(t,r){l||(i.releaseLock(),i=e.getReader({mode:"byob"}),y(i),l=!0);const u=r?n:o,c=r?o:n;b(i.read(t),(e=>{var t;d=!1,f=!1;const o=r?p:h,n=r?h:p;if(e.done){o||u.close(),n||c.close();const r=e.value;return void 0!==r&&(o||u.byobRequest.respondWithNewView(r),n||null===(t=c.byobRequest)||void 0===t||t.respond(0)),o&&n||a(void 0),null}const l=e.value;if(n)o||u.byobRequest.respondWithNewView(l);else{let e;try{e=le(l)}catch(e){return u.error(e),c.error(e),a(i.cancel(e)),null}o||u.byobRequest.respondWithNewView(l),c.enqueue(e)}return s=!1,d?w():f&&v(),null}),(()=>(s=!1,null)))}function w(){if(s)return d=!0,c(void 0);s=!0;const e=o.byobRequest;return null===e?g():S(e.view,!1),c(void 0)}function v(){if(s)return f=!0,c(void 0);s=!0;const e=n.byobRequest;return null===e?g():S(e.view,!0),c(void 0)}function R(e){if(h=!0,t=e,p){const e=[t,r],o=i.cancel(e);a(o)}return m}function T(e){if(p=!0,r=e,h){const e=[t,r],o=i.cancel(e);a(o)}return m}const q=new ReadableStream({type:"bytes",start(e){o=e},pull:w,cancel:R}),C=new ReadableStream({type:"bytes",start(e){n=e},pull:v,cancel:T});return y(i),[q,C]}(e):function(e,t){const r=e.getReader();let o,n,a,i,l,s=!1,d=!1,f=!1,h=!1;const p=u((e=>{l=e}));function m(){return s?(d=!0,c(void 0)):(s=!0,b(r.read(),(e=>{if(d=!1,e.done)return f||a.close(),h||i.close(),f&&h||l(void 0),null;const t=e.value,r=t,o=t;return f||a.enqueue(r),h||i.enqueue(o),s=!1,d&&m(),null}),(()=>(s=!1,null))),c(void 0))}function y(e){if(f=!0,o=e,h){const e=[o,n],t=r.cancel(e);l(t)}return p}function g(e){if(h=!0,n=e,f){const e=[o,n],t=r.cancel(e);l(t)}return p}const S=new ReadableStream({start(e){a=e},pull:m,cancel:y}),w=new ReadableStream({start(e){i=e},pull:m,cancel:g});return _(r.closed,(e=>(a.error(e),i.error(e),f&&h||l(void 0),null))),[S,w]}(e)}class ReadableStreamDefaultController{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Bt(this))throw It("desiredSize");return Lt(this)}close(){if(!Bt(this))throw It("close");if(!Ft(this))throw new TypeError("The stream is not in a state that permits close");!function(e){if(!Ft(e))return;const t=e._controlledReadableStream;e._closeRequested=!0,0===e._queue.length&&(jt(e),Xt(t))}(this)}enqueue(e){if(!Bt(this))throw It("enqueue");if(!Ft(this))throw new TypeError("The stream is not in a state that permits enqueue");return function(e,t){if(!Ft(e))return;const r=e._controlledReadableStream;if(Ut(r)&&X(r)>0)G(r,t,!1);else{let r;try{r=e._strategySizeAlgorithm(t)}catch(t){throw zt(e,t),t}try{ue(e,t,r)}catch(t){throw zt(e,t),t}}At(e)}(this,e)}error(e){if(!Bt(this))throw It("error");zt(this,e)}[T](e){ce(this);const t=this._cancelAlgorithm(e);return jt(this),t}[q](e){const t=this._controlledReadableStream;if(this._queue.length>0){const r=se(this);this._closeRequested&&0===this._queue.length?(jt(this),Xt(t)):At(this),e._chunkSteps(r)}else U(t,e),At(this)}[C](){}}function Bt(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableStream")&&e instanceof ReadableStreamDefaultController)}function At(e){const t=function(e){const t=e._controlledReadableStream;if(!Ft(e))return!1;if(!e._started)return!1;if(Ut(t)&&X(t)>0)return!0;if(Lt(e)>0)return!0;return!1}(e);if(!t)return;if(e._pulling)return void(e._pullAgain=!0);e._pulling=!0;b(e._pullAlgorithm(),(()=>(e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,At(e)),null)),(t=>(zt(e,t),null)))}function jt(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function zt(e,t){const r=e._controlledReadableStream;"readable"===r._state&&(ce(e),jt(e),Jt(r,t))}function Lt(e){const t=e._controlledReadableStream._state;return"errored"===t?null:"closed"===t?0:e._strategyHWM-e._queueTotalSize}function Ft(e){return!e._closeRequested&&"readable"===e._controlledReadableStream._state}function Dt(e,t,r,o){const n=Object.create(ReadableStreamDefaultController.prototype);let a,i,l;a=void 0!==t.start?()=>t.start(n):()=>{},i=void 0!==t.pull?()=>t.pull(n):()=>c(void 0),l=void 0!==t.cancel?e=>t.cancel(e):()=>c(void 0),function(e,t,r,o,n,a,i){t._controlledReadableStream=e,t._queue=void 0,t._queueTotalSize=void 0,ce(t),t._started=!1,t._closeRequested=!1,t._pullAgain=!1,t._pulling=!1,t._strategySizeAlgorithm=i,t._strategyHWM=a,t._pullAlgorithm=o,t._cancelAlgorithm=n,e._readableStreamController=t,b(c(r()),(()=>(t._started=!0,At(t),null)),(e=>(zt(t,e),null)))}(e,n,a,i,l,r,o)}function It(e){return new TypeError(`ReadableStreamDefaultController.prototype.${e} can only be used on a ReadableStreamDefaultController`)}function $t(e,t,r){return D(e,r),r=>S(e,t,[r])}function Mt(e,t,r){return D(e,r),r=>S(e,t,[r])}function Yt(e,t,r){return D(e,r),r=>g(e,t,[r])}function Qt(e,t){if("bytes"!==(e=`${e}`))throw new TypeError(`${t} '${e}' is not a valid enumeration value for ReadableStreamType`);return e}function Nt(e,t){if("byob"!==(e=`${e}`))throw new TypeError(`${t} '${e}' is not a valid enumeration value for ReadableStreamReaderMode`);return e}function Ht(e,t){F(e,t);const r=null==e?void 0:e.preventAbort,o=null==e?void 0:e.preventCancel,n=null==e?void 0:e.preventClose,a=null==e?void 0:e.signal;return void 0!==a&&function(e,t){if(!function(e){if("object"!=typeof e||null===e)return!1;try{return"boolean"==typeof e.aborted}catch(e){return!1}}(e))throw new TypeError(`${t} is not an AbortSignal.`)}(a,`${t} has member 'signal' that`),{preventAbort:Boolean(r),preventCancel:Boolean(o),preventClose:Boolean(n),signal:a}}function xt(e,t){F(e,t);const r=null==e?void 0:e.readable;M(r,"readable","ReadableWritablePair"),function(e,t){if(!H(e))throw new TypeError(`${t} is not a ReadableStream.`)}(r,`${t} has member 'readable' that`);const o=null==e?void 0:e.writable;return M(o,"writable","ReadableWritablePair"),function(e,t){if(!x(e))throw new TypeError(`${t} is not a WritableStream.`)}(o,`${t} has member 'writable' that`),{readable:r,writable:o}}Object.defineProperties(ReadableStreamDefaultController.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),n(ReadableStreamDefaultController.prototype.close,"close"),n(ReadableStreamDefaultController.prototype.enqueue,"enqueue"),n(ReadableStreamDefaultController.prototype.error,"error"),"symbol"==typeof e.toStringTag&&Object.defineProperty(ReadableStreamDefaultController.prototype,e.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});class ReadableStream{constructor(e={},t={}){void 0===e?e=null:I(e,"First parameter");const r=Ye(t,"Second parameter"),o=function(e,t){F(e,t);const r=e,o=null==r?void 0:r.autoAllocateChunkSize,n=null==r?void 0:r.cancel,a=null==r?void 0:r.pull,i=null==r?void 0:r.start,l=null==r?void 0:r.type;return{autoAllocateChunkSize:void 0===o?void 0:N(o,`${t} has member 'autoAllocateChunkSize' that`),cancel:void 0===n?void 0:$t(n,r,`${t} has member 'cancel' that`),pull:void 0===a?void 0:Mt(a,r,`${t} has member 'pull' that`),start:void 0===i?void 0:Yt(i,r,`${t} has member 'start' that`),type:void 0===l?void 0:Qt(l,`${t} has member 'type' that`)}}(e,"First parameter");var n;if((n=this)._state="readable",n._reader=void 0,n._storedError=void 0,n._disturbed=!1,"bytes"===o.type){if(void 0!==r.size)throw new RangeError("The strategy for a byte stream cannot have a size function");ke(this,o,$e(r,0))}else{const e=Me(r);Dt(this,o,$e(r,1),e)}}get locked(){if(!Vt(this))throw Kt("locked");return Ut(this)}cancel(e){return Vt(this)?Ut(this)?d(new TypeError("Cannot cancel a stream that already has a reader")):Gt(this,e):d(Kt("cancel"))}getReader(e){if(!Vt(this))throw Kt("getReader");return void 0===function(e,t){F(e,t);const r=null==e?void 0:e.mode;return{mode:void 0===r?void 0:Nt(r,`${t} has member 'mode' that`)}}(e,"First parameter").mode?new ReadableStreamDefaultReader(this):function(e){return new ReadableStreamBYOBReader(e)}(this)}pipeThrough(e,t={}){if(!H(this))throw Kt("pipeThrough");$(e,1,"pipeThrough");const r=xt(e,"First parameter"),o=Ht(t,"Second parameter");if(this.locked)throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(r.writable.locked)throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");return m(Ot(this,r.writable,o.preventClose,o.preventAbort,o.preventCancel,o.signal)),r.readable}pipeTo(e,t={}){if(!H(this))return d(Kt("pipeTo"));if(void 0===e)return d("Parameter 1 is required in 'pipeTo'.");if(!x(e))return d(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let r;try{r=Ht(t,"Second parameter")}catch(e){return d(e)}return this.locked?d(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):e.locked?d(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):Ot(this,e,r.preventClose,r.preventAbort,r.preventCancel,r.signal)}tee(){if(!H(this))throw Kt("tee");if(this.locked)throw new TypeError("Cannot tee a stream that already has a reader");return kt(this)}values(e){if(!H(this))throw Kt("values");return function(e,t){const r=e.getReader(),o=new te(r,t),n=Object.create(re);return n._asyncIteratorImpl=o,n}(this,function(e,t){F(e,t);const r=null==e?void 0:e.preventCancel;return{preventCancel:Boolean(r)}}(e,"First parameter").preventCancel)}}function Vt(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readableStreamController")&&e instanceof ReadableStream)}function Ut(e){return void 0!==e._reader}function Gt(e,r){if(e._disturbed=!0,"closed"===e._state)return c(void 0);if("errored"===e._state)return d(e._storedError);Xt(e);const o=e._reader;if(void 0!==o&&Fe(o)){const e=o._readIntoRequests;o._readIntoRequests=new w,e.forEach((e=>{e._closeSteps(void 0)}))}return p(e._readableStreamController[T](r),t)}function Xt(e){e._state="closed";const t=e._reader;if(void 0!==t&&(j(t),K(t))){const e=t._readRequests;t._readRequests=new w,e.forEach((e=>{e._closeSteps()}))}}function Jt(e,t){e._state="errored",e._storedError=t;const r=e._reader;void 0!==r&&(A(r,t),K(r)?Z(r,t):De(r,t))}function Kt(e){return new TypeError(`ReadableStream.prototype.${e} can only be used on a ReadableStream`)}function Zt(e,t){F(e,t);const r=null==e?void 0:e.highWaterMark;return M(r,"highWaterMark","QueuingStrategyInit"),{highWaterMark:Y(r)}}Object.defineProperties(ReadableStream.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),n(ReadableStream.prototype.cancel,"cancel"),n(ReadableStream.prototype.getReader,"getReader"),n(ReadableStream.prototype.pipeThrough,"pipeThrough"),n(ReadableStream.prototype.pipeTo,"pipeTo"),n(ReadableStream.prototype.tee,"tee"),n(ReadableStream.prototype.values,"values"),"symbol"==typeof e.toStringTag&&Object.defineProperty(ReadableStream.prototype,e.toStringTag,{value:"ReadableStream",configurable:!0}),"symbol"==typeof e.asyncIterator&&Object.defineProperty(ReadableStream.prototype,e.asyncIterator,{value:ReadableStream.prototype.values,writable:!0,configurable:!0});const er=e=>e.byteLength;n(er,"size");class ByteLengthQueuingStrategy{constructor(e){$(e,1,"ByteLengthQueuingStrategy"),e=Zt(e,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=e.highWaterMark}get highWaterMark(){if(!rr(this))throw tr("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!rr(this))throw tr("size");return er}}function tr(e){return new TypeError(`ByteLengthQueuingStrategy.prototype.${e} can only be used on a ByteLengthQueuingStrategy`)}function rr(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_byteLengthQueuingStrategyHighWaterMark")&&e instanceof ByteLengthQueuingStrategy)}Object.defineProperties(ByteLengthQueuingStrategy.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof e.toStringTag&&Object.defineProperty(ByteLengthQueuingStrategy.prototype,e.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});const or=()=>1;n(or,"size");class CountQueuingStrategy{constructor(e){$(e,1,"CountQueuingStrategy"),e=Zt(e,"First parameter"),this._countQueuingStrategyHighWaterMark=e.highWaterMark}get highWaterMark(){if(!ar(this))throw nr("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!ar(this))throw nr("size");return or}}function nr(e){return new TypeError(`CountQueuingStrategy.prototype.${e} can only be used on a CountQueuingStrategy`)}function ar(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_countQueuingStrategyHighWaterMark")&&e instanceof CountQueuingStrategy)}function ir(e,t,r){return D(e,r),r=>S(e,t,[r])}function lr(e,t,r){return D(e,r),r=>g(e,t,[r])}function sr(e,t,r){return D(e,r),(r,o)=>S(e,t,[r,o])}Object.defineProperties(CountQueuingStrategy.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof e.toStringTag&&Object.defineProperty(CountQueuingStrategy.prototype,e.toStringTag,{value:"CountQueuingStrategy",configurable:!0});class TransformStream{constructor(e={},t={},r={}){void 0===e&&(e=null);const o=Ye(t,"Second parameter"),n=Ye(r,"Third parameter"),a=function(e,t){F(e,t);const r=null==e?void 0:e.flush,o=null==e?void 0:e.readableType,n=null==e?void 0:e.start,a=null==e?void 0:e.transform,i=null==e?void 0:e.writableType;return{flush:void 0===r?void 0:ir(r,e,`${t} has member 'flush' that`),readableType:o,start:void 0===n?void 0:lr(n,e,`${t} has member 'start' that`),transform:void 0===a?void 0:sr(a,e,`${t} has member 'transform' that`),writableType:i}}(e,"First parameter");if(void 0!==a.readableType)throw new RangeError("Invalid readableType specified");if(void 0!==a.writableType)throw new RangeError("Invalid writableType specified");const i=$e(n,0),l=Me(n),s=$e(o,1),f=Me(o);let b;!function(e,t,r,o,n,a){function i(){return t}function l(t){return function(e,t){const r=e._transformStreamController;if(e._backpressure){return p(e._backpressureChangePromise,(()=>{if("erroring"===(Ge(e._writable)?e._writable._state:e._writableState))throw Ge(e._writable)?e._writable._storedError:e._writableStoredError;return pr(r,t)}))}return pr(r,t)}(e,t)}function s(t){return function(e,t){return cr(e,t),c(void 0)}(e,t)}function u(){return function(e){const t=e._transformStreamController,r=t._flushAlgorithm();return hr(t),p(r,(()=>{if("errored"===e._readableState)throw e._readableStoredError;gr(e)&&Sr(e)}),(t=>{throw cr(e,t),e._readableStoredError}))}(e)}function d(){return function(e){return fr(e,!1),e._backpressureChangePromise}(e)}function f(t){return dr(e,t),c(void 0)}e._writableState="writable",e._writableStoredError=void 0,e._writableHasInFlightOperation=!1,e._writableStarted=!1,e._writable=function(e,t,r,o,n,a,i){return new WritableStream({start(r){e._writableController=r;try{const t=r.signal;void 0!==t&&t.addEventListener("abort",(()=>{"writable"===e._writableState&&(e._writableState="erroring",t.reason&&(e._writableStoredError=t.reason))}))}catch(e){}return p(t(),(()=>(e._writableStarted=!0,Cr(e),null)),(t=>{throw e._writableStarted=!0,Rr(e,t),t}))},write:t=>(function(e){e._writableHasInFlightOperation=!0}(e),p(r(t),(()=>(function(e){e._writableHasInFlightOperation=!1}(e),Cr(e),null)),(t=>{throw function(e,t){e._writableHasInFlightOperation=!1,Rr(e,t)}(e,t),t}))),close:()=>(function(e){e._writableHasInFlightOperation=!0}(e),p(o(),(()=>(function(e){e._writableHasInFlightOperation=!1;"erroring"===e._writableState&&(e._writableStoredError=void 0);e._writableState="closed"}(e),null)),(t=>{throw function(e,t){e._writableHasInFlightOperation=!1,e._writableState,Rr(e,t)}(e,t),t}))),abort:t=>(e._writableState="errored",e._writableStoredError=t,n(t))},{highWaterMark:a,size:i})}(e,i,l,u,s,r,o),e._readableState="readable",e._readableStoredError=void 0,e._readableCloseRequested=!1,e._readablePulling=!1,e._readable=function(e,t,r,o,n,a){return new ReadableStream({start:r=>(e._readableController=r,t().catch((t=>{wr(e,t)}))),pull:()=>(e._readablePulling=!0,r().catch((t=>{wr(e,t)}))),cancel:t=>(e._readableState="closed",o(t))},{highWaterMark:n,size:a})}(e,i,d,f,n,a),e._backpressure=void 0,e._backpressureChangePromise=void 0,e._backpressureChangePromise_resolve=void 0,fr(e,!0),e._transformStreamController=void 0}(this,u((e=>{b=e})),s,f,i,l),function(e,t){const r=Object.create(TransformStreamDefaultController.prototype);let o,n;o=void 0!==t.transform?e=>t.transform(e,r):e=>{try{return _r(r,e),c(void 0)}catch(e){return d(e)}};n=void 0!==t.flush?()=>t.flush(r):()=>c(void 0);!function(e,t,r,o){t._controlledTransformStream=e,e._transformStreamController=t,t._transformAlgorithm=r,t._flushAlgorithm=o}(e,r,o,n)}(this,a),void 0!==a.start?b(a.start(this._transformStreamController)):b(void 0)}get readable(){if(!ur(this))throw yr("readable");return this._readable}get writable(){if(!ur(this))throw yr("writable");return this._writable}}function ur(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_transformStreamController")&&e instanceof TransformStream)}function cr(e,t){wr(e,t),dr(e,t)}function dr(e,t){hr(e._transformStreamController),function(e,t){e._writableController.error(t);"writable"===e._writableState&&Tr(e,t)}(e,t),e._backpressure&&fr(e,!1)}function fr(e,t){void 0!==e._backpressureChangePromise&&e._backpressureChangePromise_resolve(),e._backpressureChangePromise=u((t=>{e._backpressureChangePromise_resolve=t})),e._backpressure=t}Object.defineProperties(TransformStream.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),"symbol"==typeof e.toStringTag&&Object.defineProperty(TransformStream.prototype,e.toStringTag,{value:"TransformStream",configurable:!0});class TransformStreamDefaultController{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!br(this))throw mr("desiredSize");return vr(this._controlledTransformStream)}enqueue(e){if(!br(this))throw mr("enqueue");_r(this,e)}error(e){if(!br(this))throw mr("error");var t;t=e,cr(this._controlledTransformStream,t)}terminate(){if(!br(this))throw mr("terminate");!function(e){const t=e._controlledTransformStream;gr(t)&&Sr(t);const r=new TypeError("TransformStream terminated");dr(t,r)}(this)}}function br(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledTransformStream")&&e instanceof TransformStreamDefaultController)}function hr(e){e._transformAlgorithm=void 0,e._flushAlgorithm=void 0}function _r(e,t){const r=e._controlledTransformStream;if(!gr(r))throw new TypeError("Readable side is not in a state that permits enqueue");try{!function(e,t){e._readablePulling=!1;try{e._readableController.enqueue(t)}catch(t){throw wr(e,t),t}}(r,t)}catch(e){throw dr(r,e),r._readableStoredError}const o=function(e){return!function(e){if(!gr(e))return!1;if(e._readablePulling)return!0;if(vr(e)>0)return!0;return!1}(e)}(r);o!==r._backpressure&&fr(r,!0)}function pr(e,t){return p(e._transformAlgorithm(t),void 0,(t=>{throw cr(e._controlledTransformStream,t),t}))}function mr(e){return new TypeError(`TransformStreamDefaultController.prototype.${e} can only be used on a TransformStreamDefaultController`)}function yr(e){return new TypeError(`TransformStream.prototype.${e} can only be used on a TransformStream`)}function gr(e){return!e._readableCloseRequested&&"readable"===e._readableState}function Sr(e){e._readableState="closed",e._readableCloseRequested=!0,e._readableController.close()}function wr(e,t){"readable"===e._readableState&&(e._readableState="errored",e._readableStoredError=t),e._readableController.error(t)}function vr(e){return e._readableController.desiredSize}function Rr(e,t){"writable"!==e._writableState?qr(e):Tr(e,t)}function Tr(e,t){e._writableState="erroring",e._writableStoredError=t,!function(e){return e._writableHasInFlightOperation}(e)&&e._writableStarted&&qr(e)}function qr(e){e._writableState="errored"}function Cr(e){"erroring"===e._writableState&&qr(e)}Object.defineProperties(TransformStreamDefaultController.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),n(TransformStreamDefaultController.prototype.enqueue,"enqueue"),n(TransformStreamDefaultController.prototype.error,"error"),n(TransformStreamDefaultController.prototype.terminate,"terminate"),"symbol"==typeof e.toStringTag&&Object.defineProperty(TransformStreamDefaultController.prototype,e.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});const Pr="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof global?global:void 0,Er={ReadableStream:ReadableStream,ReadableStreamDefaultController:ReadableStreamDefaultController,ReadableByteStreamController:ReadableByteStreamController,ReadableStreamBYOBRequest:ReadableStreamBYOBRequest,ReadableStreamDefaultReader:ReadableStreamDefaultReader,ReadableStreamBYOBReader:ReadableStreamBYOBReader,WritableStream:WritableStream,WritableStreamDefaultController:WritableStreamDefaultController,WritableStreamDefaultWriter:WritableStreamDefaultWriter,ByteLengthQueuingStrategy:ByteLengthQueuingStrategy,CountQueuingStrategy:CountQueuingStrategy,TransformStream:TransformStream,TransformStreamDefaultController:TransformStreamDefaultController};for(const e in Er)Object.prototype.hasOwnProperty.call(Er,e)&&Object.defineProperty(Pr,e,{value:Er[e],writable:!0,configurable:!0})}(); diff --git a/backend/node_modules/formdata-node/node_modules/web-streams-polyfill/dist/ponyfill.es5.js b/backend/node_modules/formdata-node/node_modules/web-streams-polyfill/dist/ponyfill.es5.js new file mode 100644 index 0000000000000000000000000000000000000000..fb66f1ebb089055796bfb8f96bc080b52bfc92e8 --- /dev/null +++ b/backend/node_modules/formdata-node/node_modules/web-streams-polyfill/dist/ponyfill.es5.js @@ -0,0 +1,8 @@ +/** + * @license + * web-streams-polyfill v4.0.0-beta.3 + * Copyright 2021 Mattias Buelens, Diwank Singh Tomer and other contributors. + * This code is released under the MIT license. + * SPDX-License-Identifier: MIT + */ +!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports):"function"==typeof define&&define.amd?define(["exports"],r):r((e="undefined"!=typeof globalThis?globalThis:e||self).WebStreamsPolyfill={})}(this,(function(e){"use strict";var r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol:function(e){return"Symbol(".concat(e,")")};function t(){}function n(e){return"object"==typeof e&&null!==e||"function"==typeof e}var o=t;function a(e,r){try{Object.defineProperty(e,"name",{value:r,configurable:!0})}catch(e){}}var i=Promise,l=Promise.prototype.then,u=Promise.resolve.bind(i),s=Promise.reject.bind(i);function c(e){return new i(e)}function d(e){return u(e)}function f(e){return s(e)}function b(e,r,t){return l.call(e,r,t)}function p(e,r,t){b(b(e,r,t),void 0,o)}function h(e,r){p(e,r)}function _(e,r){p(e,void 0,r)}function y(e,r,t){return b(e,r,t)}function m(e){b(e,void 0,o)}var v=function(e){if("function"==typeof queueMicrotask)v=queueMicrotask;else{var r=d(void 0);v=function(e){return b(r,e)}}return v(e)};function g(e,r,t){if("function"!=typeof e)throw new TypeError("Argument is not a function");return Function.prototype.apply.call(e,r,t)}function w(e,r,t){try{return d(g(e,r,t))}catch(e){return f(e)}}var S=function(){function e(){this._cursor=0,this._size=0,this._front={_elements:[],_next:void 0},this._back=this._front,this._cursor=0,this._size=0}return Object.defineProperty(e.prototype,"length",{get:function(){return this._size},enumerable:!1,configurable:!0}),e.prototype.push=function(e){var r=this._back,t=r;16383===r._elements.length&&(t={_elements:[],_next:void 0}),r._elements.push(e),t!==r&&(this._back=t,r._next=t),++this._size},e.prototype.shift=function(){var e=this._front,r=e,t=this._cursor,n=t+1,o=e._elements,a=o[t];return 16384===n&&(r=e._next,n=0),--this._size,this._cursor=n,e!==r&&(this._front=r),o[t]=void 0,a},e.prototype.forEach=function(e){for(var r=this._cursor,t=this._front,n=t._elements;!(r===n.length&&void 0===t._next||r===n.length&&(r=0,0===(n=(t=t._next)._elements).length));)e(n[r]),++r},e.prototype.peek=function(){var e=this._front,r=this._cursor;return e._elements[r]},e}(),R=r("[[AbortSteps]]"),T=r("[[ErrorSteps]]"),q=r("[[CancelSteps]]"),P=r("[[PullSteps]]"),C=r("[[ReleaseSteps]]");function E(e,r){e._ownerReadableStream=r,r._reader=e,"readable"===r._state?j(e):"closed"===r._state?function(e){j(e),z(e)}(e):B(e,r._storedError)}function W(e,r){return it(e._ownerReadableStream,r)}function O(e){var r=e._ownerReadableStream;"readable"===r._state?A(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):function(e,r){B(e,r)}(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),r._readableStreamController[C](),r._reader=void 0,e._ownerReadableStream=void 0}function k(e){return new TypeError("Cannot "+e+" a stream using a released reader")}function j(e){e._closedPromise=c((function(r,t){e._closedPromise_resolve=r,e._closedPromise_reject=t}))}function B(e,r){j(e),A(e,r)}function A(e,r){void 0!==e._closedPromise_reject&&(m(e._closedPromise),e._closedPromise_reject(r),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}function z(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}var L=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},F=Math.trunc||function(e){return e<0?Math.ceil(e):Math.floor(e)};function I(e,r){if(void 0!==e&&("object"!=typeof(t=e)&&"function"!=typeof t))throw new TypeError("".concat(r," is not an object."));var t}function D(e,r){if("function"!=typeof e)throw new TypeError("".concat(r," is not a function."))}function M(e,r){if(!function(e){return"object"==typeof e&&null!==e||"function"==typeof e}(e))throw new TypeError("".concat(r," is not an object."))}function Q(e,r,t){if(void 0===e)throw new TypeError("Parameter ".concat(r," is required in '").concat(t,"'."))}function Y(e,r,t){if(void 0===e)throw new TypeError("".concat(r," is required in '").concat(t,"'."))}function N(e){return Number(e)}function x(e){return 0===e?0:e}function H(e,r){var t=Number.MAX_SAFE_INTEGER,n=Number(e);if(n=x(n),!L(n))throw new TypeError("".concat(r," is not a finite number"));if((n=function(e){return x(F(e))}(n))<0||n>t)throw new TypeError("".concat(r," is outside the accepted range of ").concat(0," to ").concat(t,", inclusive"));return L(n)&&0!==n?n:0}function V(e){if(!n(e))return!1;if("function"!=typeof e.getReader)return!1;try{return"boolean"==typeof e.locked}catch(e){return!1}}function U(e){if(!n(e))return!1;if("function"!=typeof e.getWriter)return!1;try{return"boolean"==typeof e.locked}catch(e){return!1}}function G(e,r){if(!ot(e))throw new TypeError("".concat(r," is not a ReadableStream."))}function X(e,r){e._reader._readRequests.push(r)}function J(e,r,t){var n=e._reader._readRequests.shift();t?n._closeSteps():n._chunkSteps(r)}function K(e){return e._reader._readRequests.length}function Z(e){var r=e._reader;return void 0!==r&&!!ee(r)}var $=function(){function ReadableStreamDefaultReader(e){if(Q(e,1,"ReadableStreamDefaultReader"),G(e,"First parameter"),at(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");E(this,e),this._readRequests=new S}return Object.defineProperty(ReadableStreamDefaultReader.prototype,"closed",{get:function(){return ee(this)?this._closedPromise:f(te("closed"))},enumerable:!1,configurable:!0}),ReadableStreamDefaultReader.prototype.cancel=function(e){return void 0===e&&(e=void 0),ee(this)?void 0===this._ownerReadableStream?f(k("cancel")):W(this,e):f(te("cancel"))},ReadableStreamDefaultReader.prototype.read=function(){if(!ee(this))return f(te("read"));if(void 0===this._ownerReadableStream)return f(k("read from"));var e,r,t=c((function(t,n){e=t,r=n}));return function(e,r){var t=e._ownerReadableStream;t._disturbed=!0,"closed"===t._state?r._closeSteps():"errored"===t._state?r._errorSteps(t._storedError):t._readableStreamController[P](r)}(this,{_chunkSteps:function(r){return e({value:r,done:!1})},_closeSteps:function(){return e({value:void 0,done:!0})},_errorSteps:function(e){return r(e)}}),t},ReadableStreamDefaultReader.prototype.releaseLock=function(){if(!ee(this))throw te("releaseLock");void 0!==this._ownerReadableStream&&function(e){O(e);var r=new TypeError("Reader was released");re(e,r)}(this)},ReadableStreamDefaultReader}();function ee(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readRequests")&&e instanceof $)}function re(e,r){var t=e._readRequests;e._readRequests=new S,t.forEach((function(e){e._errorSteps(r)}))}function te(e){return new TypeError("ReadableStreamDefaultReader.prototype.".concat(e," can only be used on a ReadableStreamDefaultReader"))}Object.defineProperties($.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),a($.prototype.cancel,"cancel"),a($.prototype.read,"read"),a($.prototype.releaseLock,"releaseLock"),"symbol"==typeof r.toStringTag&&Object.defineProperty($.prototype,r.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0});var ne=function(){function e(e,r){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=e,this._preventCancel=r}return e.prototype.next=function(){var e=this,r=function(){return e._nextSteps()};return this._ongoingPromise=this._ongoingPromise?y(this._ongoingPromise,r,r):r(),this._ongoingPromise},e.prototype.return=function(e){var r=this,t=function(){return r._returnSteps(e)};return this._ongoingPromise?y(this._ongoingPromise,t,t):t()},e.prototype._nextSteps=function(){var e=this;if(this._isFinished)return Promise.resolve({value:void 0,done:!0});var r=this._reader;return void 0===r?f(k("iterate")):b(r.read(),(function(r){var t;return e._ongoingPromise=void 0,r.done&&(e._isFinished=!0,null===(t=e._reader)||void 0===t||t.releaseLock(),e._reader=void 0),r}),(function(r){var t;throw e._ongoingPromise=void 0,e._isFinished=!0,null===(t=e._reader)||void 0===t||t.releaseLock(),e._reader=void 0,r}))},e.prototype._returnSteps=function(e){if(this._isFinished)return Promise.resolve({value:e,done:!0});this._isFinished=!0;var r=this._reader;if(void 0===r)return f(k("finish iterating"));if(this._reader=void 0,!this._preventCancel){var t=r.cancel(e);return r.releaseLock(),y(t,(function(){return{value:e,done:!0}}))}return r.releaseLock(),d({value:e,done:!0})},e}(),oe={next:function(){return ae(this)?this._asyncIteratorImpl.next():f(ie("next"))},return:function(e){return ae(this)?this._asyncIteratorImpl.return(e):f(ie("return"))}};function ae(e){if(!n(e))return!1;if(!Object.prototype.hasOwnProperty.call(e,"_asyncIteratorImpl"))return!1;try{return e._asyncIteratorImpl instanceof ne}catch(e){return!1}}function ie(e){return new TypeError("ReadableStreamAsyncIterator.".concat(e," can only be used on a ReadableSteamAsyncIterator"))}"symbol"==typeof r.asyncIterator&&Object.defineProperty(oe,r.asyncIterator,{value:function(){return this},writable:!0,configurable:!0});var le=Number.isNaN||function(e){return e!=e};function ue(e,r,t,n,o){new Uint8Array(e).set(new Uint8Array(t,n,o),r)}function se(e){var r=function(e,r,t){if(e.slice)return e.slice(r,t);var n=t-r,o=new ArrayBuffer(n);return ue(o,0,e,r,n),o}(e.buffer,e.byteOffset,e.byteOffset+e.byteLength);return new Uint8Array(r)}function ce(e){var r=e._queue.shift();return e._queueTotalSize-=r.size,e._queueTotalSize<0&&(e._queueTotalSize=0),r.value}function de(e,r,t){if("number"!=typeof(n=t)||le(n)||n<0||t===1/0)throw new RangeError("Size must be a finite, non-NaN, non-negative number.");var n;e._queue.push({value:r,size:t}),e._queueTotalSize+=t}function fe(e){e._queue=new S,e._queueTotalSize=0}var be=function(){function ReadableStreamBYOBRequest(){throw new TypeError("Illegal constructor")}return Object.defineProperty(ReadableStreamBYOBRequest.prototype,"view",{get:function(){if(!_e(this))throw Le("view");return this._view},enumerable:!1,configurable:!0}),ReadableStreamBYOBRequest.prototype.respond=function(e){if(!_e(this))throw Le("respond");if(Q(e,1,"respond"),e=H(e,"First parameter"),void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");this._view.buffer,function(e,r){var t=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==r)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream")}else{if(0===r)throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");if(t.bytesFilled+r>t.byteLength)throw new RangeError("bytesWritten out of range")}t.buffer=t.buffer,We(e,r)}(this._associatedReadableByteStreamController,e)},ReadableStreamBYOBRequest.prototype.respondWithNewView=function(e){if(!_e(this))throw Le("respondWithNewView");if(Q(e,1,"respondWithNewView"),!ArrayBuffer.isView(e))throw new TypeError("You can only respond with array buffer views");if(void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");e.buffer,function(e,r){var t=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==r.byteLength)throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream")}else if(0===r.byteLength)throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");if(t.byteOffset+t.bytesFilled!==r.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(t.bufferByteLength!==r.buffer.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");if(t.bytesFilled+r.byteLength>t.byteLength)throw new RangeError("The region specified by view is larger than byobRequest");var n=r.byteLength;t.buffer=r.buffer,We(e,n)}(this._associatedReadableByteStreamController,e)},ReadableStreamBYOBRequest}();Object.defineProperties(be.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),a(be.prototype.respond,"respond"),a(be.prototype.respondWithNewView,"respondWithNewView"),"symbol"==typeof r.toStringTag&&Object.defineProperty(be.prototype,r.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});var pe=function(){function ReadableByteStreamController(){throw new TypeError("Illegal constructor")}return Object.defineProperty(ReadableByteStreamController.prototype,"byobRequest",{get:function(){if(!he(this))throw Fe("byobRequest");return function(e){if(null===e._byobRequest&&e._pendingPullIntos.length>0){var r=e._pendingPullIntos.peek(),t=new Uint8Array(r.buffer,r.byteOffset+r.bytesFilled,r.byteLength-r.bytesFilled),n=Object.create(be.prototype);!function(e,r,t){e._associatedReadableByteStreamController=r,e._view=t}(n,e,t),e._byobRequest=n}return e._byobRequest}(this)},enumerable:!1,configurable:!0}),Object.defineProperty(ReadableByteStreamController.prototype,"desiredSize",{get:function(){if(!he(this))throw Fe("desiredSize");return Ae(this)},enumerable:!1,configurable:!0}),ReadableByteStreamController.prototype.close=function(){if(!he(this))throw Fe("close");if(this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");var e=this._controlledReadableByteStream._state;if("readable"!==e)throw new TypeError("The stream (in ".concat(e," state) is not in the readable state and cannot be closed"));!function(e){var r=e._controlledReadableByteStream;if(e._closeRequested||"readable"!==r._state)return;if(e._queueTotalSize>0)return void(e._closeRequested=!0);if(e._pendingPullIntos.length>0){if(e._pendingPullIntos.peek().bytesFilled>0){var t=new TypeError("Insufficient bytes to fill elements in the given buffer");throw je(e,t),t}}ke(e),lt(r)}(this)},ReadableByteStreamController.prototype.enqueue=function(e){if(!he(this))throw Fe("enqueue");if(Q(e,1,"enqueue"),!ArrayBuffer.isView(e))throw new TypeError("chunk must be an array buffer view");if(0===e.byteLength)throw new TypeError("chunk must have non-zero byteLength");if(0===e.buffer.byteLength)throw new TypeError("chunk's buffer must have non-zero byteLength");if(this._closeRequested)throw new TypeError("stream is closed or draining");var r=this._controlledReadableByteStream._state;if("readable"!==r)throw new TypeError("The stream (in ".concat(r," state) is not in the readable state and cannot be enqueued to"));!function(e,r){var t=e._controlledReadableByteStream;if(e._closeRequested||"readable"!==t._state)return;var n=r.buffer,o=r.byteOffset,a=r.byteLength,i=n;if(e._pendingPullIntos.length>0){var l=e._pendingPullIntos.peek();l.buffer,0,Ce(e),l.buffer=l.buffer,"none"===l.readerType&&Re(e,l)}if(Z(t)){if(function(e){var r=e._controlledReadableByteStream._reader;for(;r._readRequests.length>0;){if(0===e._queueTotalSize)return;Be(e,r._readRequests.shift())}}(e),0===K(t))we(e,i,o,a);else e._pendingPullIntos.length>0&&Oe(e),J(t,new Uint8Array(i,o,a),!1)}else Me(t)?(we(e,i,o,a),Ee(e)):we(e,i,o,a);ye(e)}(this,e)},ReadableByteStreamController.prototype.error=function(e){if(void 0===e&&(e=void 0),!he(this))throw Fe("error");je(this,e)},ReadableByteStreamController.prototype[q]=function(e){me(this),fe(this);var r=this._cancelAlgorithm(e);return ke(this),r},ReadableByteStreamController.prototype[P]=function(e){var r=this._controlledReadableByteStream;if(this._queueTotalSize>0)Be(this,e);else{var t=this._autoAllocateChunkSize;if(void 0!==t){var n=void 0;try{n=new ArrayBuffer(t)}catch(r){return void e._errorSteps(r)}var o={buffer:n,bufferByteLength:t,byteOffset:0,byteLength:t,bytesFilled:0,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(o)}X(r,e),ye(this)}},ReadableByteStreamController.prototype[C]=function(){if(this._pendingPullIntos.length>0){var e=this._pendingPullIntos.peek();e.readerType="none",this._pendingPullIntos=new S,this._pendingPullIntos.push(e)}},ReadableByteStreamController}();function he(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableByteStream")&&e instanceof pe)}function _e(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_associatedReadableByteStreamController")&&e instanceof be)}function ye(e){var r=function(e){var r=e._controlledReadableByteStream;if("readable"!==r._state)return!1;if(e._closeRequested)return!1;if(!e._started)return!1;if(Z(r)&&K(r)>0)return!0;if(Me(r)&&De(r)>0)return!0;if(Ae(e)>0)return!0;return!1}(e);r&&(e._pulling?e._pullAgain=!0:(e._pulling=!0,p(e._pullAlgorithm(),(function(){return e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,ye(e)),null}),(function(r){return je(e,r),null}))))}function me(e){Ce(e),e._pendingPullIntos=new S}function ve(e,r){var t=!1;"closed"===e._state&&(t=!0);var n=ge(r);"default"===r.readerType?J(e,n,t):function(e,r,t){var n=e._reader._readIntoRequests.shift();t?n._closeSteps(r):n._chunkSteps(r)}(e,n,t)}function ge(e){var r=e.bytesFilled,t=e.elementSize;return new e.viewConstructor(e.buffer,e.byteOffset,r/t)}function we(e,r,t,n){e._queue.push({buffer:r,byteOffset:t,byteLength:n}),e._queueTotalSize+=n}function Se(e,r,t,n){var o;try{o=r.slice(t,t+n)}catch(r){throw je(e,r),r}we(e,o,0,n)}function Re(e,r){r.bytesFilled>0&&Se(e,r.buffer,r.byteOffset,r.bytesFilled),Oe(e)}function Te(e,r){var t=r.elementSize,n=r.bytesFilled-r.bytesFilled%t,o=Math.min(e._queueTotalSize,r.byteLength-r.bytesFilled),a=r.bytesFilled+o,i=a-a%t,l=o,u=!1;i>n&&(l=i-r.bytesFilled,u=!0);for(var s=e._queue;l>0;){var c=s.peek(),d=Math.min(l,c.byteLength),f=r.byteOffset+r.bytesFilled;ue(r.buffer,f,c.buffer,c.byteOffset,d),c.byteLength===d?s.shift():(c.byteOffset+=d,c.byteLength-=d),e._queueTotalSize-=d,qe(e,d,r),l-=d}return u}function qe(e,r,t){t.bytesFilled+=r}function Pe(e){0===e._queueTotalSize&&e._closeRequested?(ke(e),lt(e._controlledReadableByteStream)):ye(e)}function Ce(e){null!==e._byobRequest&&(e._byobRequest._associatedReadableByteStreamController=void 0,e._byobRequest._view=null,e._byobRequest=null)}function Ee(e){for(;e._pendingPullIntos.length>0;){if(0===e._queueTotalSize)return;var r=e._pendingPullIntos.peek();Te(e,r)&&(Oe(e),ve(e._controlledReadableByteStream,r))}}function We(e,r){var t=e._pendingPullIntos.peek();Ce(e),"closed"===e._controlledReadableByteStream._state?function(e,r){"none"===r.readerType&&Oe(e);var t=e._controlledReadableByteStream;if(Me(t))for(;De(t)>0;)ve(t,Oe(e))}(e,t):function(e,r,t){if(qe(0,r,t),"none"===t.readerType)return Re(e,t),void Ee(e);if(!(t.bytesFilled0){var o=t.byteOffset+t.bytesFilled;Se(e,t.buffer,o-n,n)}t.bytesFilled-=n,ve(e._controlledReadableByteStream,t),Ee(e)}}(e,r,t),ye(e)}function Oe(e){return e._pendingPullIntos.shift()}function ke(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0}function je(e,r){var t=e._controlledReadableByteStream;"readable"===t._state&&(me(e),fe(e),ke(e),ut(t,r))}function Be(e,r){var t=e._queue.shift();e._queueTotalSize-=t.byteLength,Pe(e);var n=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);r._chunkSteps(n)}function Ae(e){var r=e._controlledReadableByteStream._state;return"errored"===r?null:"closed"===r?0:e._strategyHWM-e._queueTotalSize}function ze(e,r,t){var n,o,a,i=Object.create(pe.prototype);n=void 0!==r.start?function(){return r.start(i)}:function(){},o=void 0!==r.pull?function(){return r.pull(i)}:function(){return d(void 0)},a=void 0!==r.cancel?function(e){return r.cancel(e)}:function(){return d(void 0)};var l=r.autoAllocateChunkSize;if(0===l)throw new TypeError("autoAllocateChunkSize must be greater than 0");!function(e,r,t,n,o,a,i){r._controlledReadableByteStream=e,r._pullAgain=!1,r._pulling=!1,r._byobRequest=null,r._queue=r._queueTotalSize=void 0,fe(r),r._closeRequested=!1,r._started=!1,r._strategyHWM=a,r._pullAlgorithm=n,r._cancelAlgorithm=o,r._autoAllocateChunkSize=i,r._pendingPullIntos=new S,e._readableStreamController=r,p(d(t()),(function(){return r._started=!0,ye(r),null}),(function(e){return je(r,e),null}))}(e,i,n,o,a,t,l)}function Le(e){return new TypeError("ReadableStreamBYOBRequest.prototype.".concat(e," can only be used on a ReadableStreamBYOBRequest"))}function Fe(e){return new TypeError("ReadableByteStreamController.prototype.".concat(e," can only be used on a ReadableByteStreamController"))}function Ie(e,r){e._reader._readIntoRequests.push(r)}function De(e){return e._reader._readIntoRequests.length}function Me(e){var r=e._reader;return void 0!==r&&!!Ye(r)}Object.defineProperties(pe.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),a(pe.prototype.close,"close"),a(pe.prototype.enqueue,"enqueue"),a(pe.prototype.error,"error"),"symbol"==typeof r.toStringTag&&Object.defineProperty(pe.prototype,r.toStringTag,{value:"ReadableByteStreamController",configurable:!0});var Qe=function(){function ReadableStreamBYOBReader(e){if(Q(e,1,"ReadableStreamBYOBReader"),G(e,"First parameter"),at(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!he(e._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");E(this,e),this._readIntoRequests=new S}return Object.defineProperty(ReadableStreamBYOBReader.prototype,"closed",{get:function(){return Ye(this)?this._closedPromise:f(xe("closed"))},enumerable:!1,configurable:!0}),ReadableStreamBYOBReader.prototype.cancel=function(e){return void 0===e&&(e=void 0),Ye(this)?void 0===this._ownerReadableStream?f(k("cancel")):W(this,e):f(xe("cancel"))},ReadableStreamBYOBReader.prototype.read=function(e){if(!Ye(this))return f(xe("read"));if(!ArrayBuffer.isView(e))return f(new TypeError("view must be an array buffer view"));if(0===e.byteLength)return f(new TypeError("view must have non-zero byteLength"));if(0===e.buffer.byteLength)return f(new TypeError("view's buffer must have non-zero byteLength"));if(e.buffer,void 0===this._ownerReadableStream)return f(k("read from"));var r,t,n=c((function(e,n){r=e,t=n}));return function(e,r,t){var n=e._ownerReadableStream;n._disturbed=!0,"errored"===n._state?t._errorSteps(n._storedError):function(e,r,t){var n=e._controlledReadableByteStream,o=1;r.constructor!==DataView&&(o=r.constructor.BYTES_PER_ELEMENT);var a=r.constructor,i=r.buffer,l={buffer:i,bufferByteLength:i.byteLength,byteOffset:r.byteOffset,byteLength:r.byteLength,bytesFilled:0,elementSize:o,viewConstructor:a,readerType:"byob"};if(e._pendingPullIntos.length>0)return e._pendingPullIntos.push(l),void Ie(n,t);if("closed"!==n._state){if(e._queueTotalSize>0){if(Te(e,l)){var u=ge(l);return Pe(e),void t._chunkSteps(u)}if(e._closeRequested){var s=new TypeError("Insufficient bytes to fill elements in the given buffer");return je(e,s),void t._errorSteps(s)}}e._pendingPullIntos.push(l),Ie(n,t),ye(e)}else{var c=new a(l.buffer,l.byteOffset,0);t._closeSteps(c)}}(n._readableStreamController,r,t)}(this,e,{_chunkSteps:function(e){return r({value:e,done:!1})},_closeSteps:function(e){return r({value:e,done:!0})},_errorSteps:function(e){return t(e)}}),n},ReadableStreamBYOBReader.prototype.releaseLock=function(){if(!Ye(this))throw xe("releaseLock");void 0!==this._ownerReadableStream&&function(e){O(e);var r=new TypeError("Reader was released");Ne(e,r)}(this)},ReadableStreamBYOBReader}();function Ye(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readIntoRequests")&&e instanceof Qe)}function Ne(e,r){var t=e._readIntoRequests;e._readIntoRequests=new S,t.forEach((function(e){e._errorSteps(r)}))}function xe(e){return new TypeError("ReadableStreamBYOBReader.prototype.".concat(e," can only be used on a ReadableStreamBYOBReader"))}function He(e,r){var t=e.highWaterMark;if(void 0===t)return r;if(le(t)||t<0)throw new RangeError("Invalid highWaterMark");return t}function Ve(e){var r=e.size;return r||function(){return 1}}function Ue(e,r){I(e,r);var t=null==e?void 0:e.highWaterMark,n=null==e?void 0:e.size;return{highWaterMark:void 0===t?void 0:N(t),size:void 0===n?void 0:Ge(n,"".concat(r," has member 'size' that"))}}function Ge(e,r){return D(e,r),function(r){return N(e(r))}}function Xe(e,r,t){return D(e,t),function(t){return w(e,r,[t])}}function Je(e,r,t){return D(e,t),function(){return w(e,r,[])}}function Ke(e,r,t){return D(e,t),function(t){return g(e,r,[t])}}function Ze(e,r,t){return D(e,t),function(t,n){return w(e,r,[t,n])}}Object.defineProperties(Qe.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),a(Qe.prototype.cancel,"cancel"),a(Qe.prototype.read,"read"),a(Qe.prototype.releaseLock,"releaseLock"),"symbol"==typeof r.toStringTag&&Object.defineProperty(Qe.prototype,r.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});var $e="function"==typeof AbortController;var er=function(){function WritableStream(e,r){void 0===e&&(e={}),void 0===r&&(r={}),void 0===e?e=null:M(e,"First parameter");var t,n=Ue(r,"Second parameter"),o=function(e,r){I(e,r);var t=null==e?void 0:e.abort,n=null==e?void 0:e.close,o=null==e?void 0:e.start,a=null==e?void 0:e.type,i=null==e?void 0:e.write;return{abort:void 0===t?void 0:Xe(t,e,"".concat(r," has member 'abort' that")),close:void 0===n?void 0:Je(n,e,"".concat(r," has member 'close' that")),start:void 0===o?void 0:Ke(o,e,"".concat(r," has member 'start' that")),write:void 0===i?void 0:Ze(i,e,"".concat(r," has member 'write' that")),type:a}}(e,"First parameter");if((t=this)._state="writable",t._storedError=void 0,t._writer=void 0,t._writableStreamController=void 0,t._writeRequests=new S,t._inFlightWriteRequest=void 0,t._closeRequest=void 0,t._inFlightCloseRequest=void 0,t._pendingAbortRequest=void 0,t._backpressure=!1,void 0!==o.type)throw new RangeError("Invalid type is specified");var a=Ve(n);!function(e,r,t,n){var o,a,i,l,u=Object.create(hr.prototype);o=void 0!==r.start?function(){return r.start(u)}:function(){};a=void 0!==r.write?function(e){return r.write(e,u)}:function(){return d(void 0)};i=void 0!==r.close?function(){return r.close()}:function(){return d(void 0)};l=void 0!==r.abort?function(e){return r.abort(e)}:function(){return d(void 0)};!function(e,r,t,n,o,a,i,l){r._controlledWritableStream=e,e._writableStreamController=r,r._queue=void 0,r._queueTotalSize=void 0,fe(r),r._abortReason=void 0,r._abortController=function(){if($e)return new AbortController}(),r._started=!1,r._strategySizeAlgorithm=l,r._strategyHWM=i,r._writeAlgorithm=n,r._closeAlgorithm=o,r._abortAlgorithm=a;var u=wr(r);cr(e,u),p(d(t()),(function(){return r._started=!0,vr(r),null}),(function(t){return r._started=!0,ar(e,t),null}))}(e,u,o,a,i,l,t,n)}(this,o,He(n,1),a)}return Object.defineProperty(WritableStream.prototype,"locked",{get:function(){if(!rr(this))throw Rr("locked");return tr(this)},enumerable:!1,configurable:!0}),WritableStream.prototype.abort=function(e){return void 0===e&&(e=void 0),rr(this)?tr(this)?f(new TypeError("Cannot abort a stream that already has a writer")):nr(this,e):f(Rr("abort"))},WritableStream.prototype.close=function(){return rr(this)?tr(this)?f(new TypeError("Cannot close a stream that already has a writer")):ur(this)?f(new TypeError("Cannot close an already-closing stream")):or(this):f(Rr("close"))},WritableStream.prototype.getWriter=function(){if(!rr(this))throw Rr("getWriter");return new dr(this)},WritableStream}();function rr(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_writableStreamController")&&e instanceof er)}function tr(e){return void 0!==e._writer}function nr(e,r){var t;if("closed"===e._state||"errored"===e._state)return d(void 0);e._writableStreamController._abortReason=r,null===(t=e._writableStreamController._abortController)||void 0===t||t.abort(r);var n=e._state;if("closed"===n||"errored"===n)return d(void 0);if(void 0!==e._pendingAbortRequest)return e._pendingAbortRequest._promise;var o=!1;"erroring"===n&&(o=!0,r=void 0);var a=c((function(t,n){e._pendingAbortRequest={_promise:void 0,_resolve:t,_reject:n,_reason:r,_wasAlreadyErroring:o}}));return e._pendingAbortRequest._promise=a,o||ir(e,r),a}function or(e){var r=e._state;if("closed"===r||"errored"===r)return f(new TypeError("The stream (in ".concat(r," state) is not in the writable state and cannot be closed")));var t,n=c((function(r,t){var n={_resolve:r,_reject:t};e._closeRequest=n})),o=e._writer;return void 0!==o&&e._backpressure&&"writable"===r&&zr(o),de(t=e._writableStreamController,pr,0),vr(t),n}function ar(e,r){"writable"!==e._state?lr(e):ir(e,r)}function ir(e,r){var t=e._writableStreamController;e._state="erroring",e._storedError=r;var n=e._writer;void 0!==n&&br(n,r),!function(e){if(void 0===e._inFlightWriteRequest&&void 0===e._inFlightCloseRequest)return!1;return!0}(e)&&t._started&&lr(e)}function lr(e){e._state="errored",e._writableStreamController[T]();var r=e._storedError;if(e._writeRequests.forEach((function(e){e._reject(r)})),e._writeRequests=new S,void 0!==e._pendingAbortRequest){var t=e._pendingAbortRequest;if(e._pendingAbortRequest=void 0,t._wasAlreadyErroring)return t._reject(r),void sr(e);p(e._writableStreamController[R](t._reason),(function(){return t._resolve(),sr(e),null}),(function(r){return t._reject(r),sr(e),null}))}else sr(e)}function ur(e){return void 0!==e._closeRequest||void 0!==e._inFlightCloseRequest}function sr(e){void 0!==e._closeRequest&&(e._closeRequest._reject(e._storedError),e._closeRequest=void 0);var r=e._writer;void 0!==r&&Wr(r,e._storedError)}function cr(e,r){var t=e._writer;void 0!==t&&r!==e._backpressure&&(r?function(e){kr(e)}(t):zr(t)),e._backpressure=r}Object.defineProperties(er.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),a(er.prototype.abort,"abort"),a(er.prototype.close,"close"),a(er.prototype.getWriter,"getWriter"),"symbol"==typeof r.toStringTag&&Object.defineProperty(er.prototype,r.toStringTag,{value:"WritableStream",configurable:!0});var dr=function(){function WritableStreamDefaultWriter(e){if(Q(e,1,"WritableStreamDefaultWriter"),function(e,r){if(!rr(e))throw new TypeError("".concat(r," is not a WritableStream."))}(e,"First parameter"),tr(e))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=e,e._writer=this;var r,t=e._state;if("writable"===t)!ur(e)&&e._backpressure?kr(this):Br(this),Cr(this);else if("erroring"===t)jr(this,e._storedError),Cr(this);else if("closed"===t)Br(this),Cr(r=this),Or(r);else{var n=e._storedError;jr(this,n),Er(this,n)}}return Object.defineProperty(WritableStreamDefaultWriter.prototype,"closed",{get:function(){return fr(this)?this._closedPromise:f(qr("closed"))},enumerable:!1,configurable:!0}),Object.defineProperty(WritableStreamDefaultWriter.prototype,"desiredSize",{get:function(){if(!fr(this))throw qr("desiredSize");if(void 0===this._ownerWritableStream)throw Pr("desiredSize");return function(e){var r=e._ownerWritableStream,t=r._state;if("errored"===t||"erroring"===t)return null;if("closed"===t)return 0;return mr(r._writableStreamController)}(this)},enumerable:!1,configurable:!0}),Object.defineProperty(WritableStreamDefaultWriter.prototype,"ready",{get:function(){return fr(this)?this._readyPromise:f(qr("ready"))},enumerable:!1,configurable:!0}),WritableStreamDefaultWriter.prototype.abort=function(e){return void 0===e&&(e=void 0),fr(this)?void 0===this._ownerWritableStream?f(Pr("abort")):function(e,r){return nr(e._ownerWritableStream,r)}(this,e):f(qr("abort"))},WritableStreamDefaultWriter.prototype.close=function(){if(!fr(this))return f(qr("close"));var e=this._ownerWritableStream;return void 0===e?f(Pr("close")):ur(e)?f(new TypeError("Cannot close an already-closing stream")):or(this._ownerWritableStream)},WritableStreamDefaultWriter.prototype.releaseLock=function(){if(!fr(this))throw qr("releaseLock");void 0!==this._ownerWritableStream&&function(e){var r=e._ownerWritableStream,t=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");br(e,t),function(e,r){"pending"===e._closedPromiseState?Wr(e,r):function(e,r){Er(e,r)}(e,r)}(e,t),r._writer=void 0,e._ownerWritableStream=void 0}(this)},WritableStreamDefaultWriter.prototype.write=function(e){return void 0===e&&(e=void 0),fr(this)?void 0===this._ownerWritableStream?f(Pr("write to")):function(e,r){var t=e._ownerWritableStream,n=t._writableStreamController,o=function(e,r){try{return e._strategySizeAlgorithm(r)}catch(r){return gr(e,r),1}}(n,r);if(t!==e._ownerWritableStream)return f(Pr("write to"));var a=t._state;if("errored"===a)return f(t._storedError);if(ur(t)||"closed"===a)return f(new TypeError("The stream is closing or closed and cannot be written to"));if("erroring"===a)return f(t._storedError);var i=function(e){return c((function(r,t){var n={_resolve:r,_reject:t};e._writeRequests.push(n)}))}(t);return function(e,r,t){try{de(e,r,t)}catch(r){return void gr(e,r)}var n=e._controlledWritableStream;if(!ur(n)&&"writable"===n._state){cr(n,wr(e))}vr(e)}(n,r,o),i}(this,e):f(qr("write"))},WritableStreamDefaultWriter}();function fr(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_ownerWritableStream")&&e instanceof dr)}function br(e,r){"pending"===e._readyPromiseState?Ar(e,r):function(e,r){jr(e,r)}(e,r)}Object.defineProperties(dr.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),a(dr.prototype.abort,"abort"),a(dr.prototype.close,"close"),a(dr.prototype.releaseLock,"releaseLock"),a(dr.prototype.write,"write"),"symbol"==typeof r.toStringTag&&Object.defineProperty(dr.prototype,r.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});var pr={},hr=function(){function WritableStreamDefaultController(){throw new TypeError("Illegal constructor")}return Object.defineProperty(WritableStreamDefaultController.prototype,"abortReason",{get:function(){if(!_r(this))throw Tr("abortReason");return this._abortReason},enumerable:!1,configurable:!0}),Object.defineProperty(WritableStreamDefaultController.prototype,"signal",{get:function(){if(!_r(this))throw Tr("signal");if(void 0===this._abortController)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal},enumerable:!1,configurable:!0}),WritableStreamDefaultController.prototype.error=function(e){if(void 0===e&&(e=void 0),!_r(this))throw Tr("error");"writable"===this._controlledWritableStream._state&&Sr(this,e)},WritableStreamDefaultController.prototype[R]=function(e){var r=this._abortAlgorithm(e);return yr(this),r},WritableStreamDefaultController.prototype[T]=function(){fe(this)},WritableStreamDefaultController}();function _r(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledWritableStream")&&e instanceof hr)}function yr(e){e._writeAlgorithm=void 0,e._closeAlgorithm=void 0,e._abortAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function mr(e){return e._strategyHWM-e._queueTotalSize}function vr(e){var r=e._controlledWritableStream;if(e._started&&void 0===r._inFlightWriteRequest)if("erroring"!==r._state){if(0!==e._queue.length){var t=e._queue.peek().value;t===pr?function(e){var r=e._controlledWritableStream;(function(e){e._inFlightCloseRequest=e._closeRequest,e._closeRequest=void 0})(r),ce(e);var t=e._closeAlgorithm();yr(e),p(t,(function(){return function(e){e._inFlightCloseRequest._resolve(void 0),e._inFlightCloseRequest=void 0,"erroring"===e._state&&(e._storedError=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._resolve(),e._pendingAbortRequest=void 0)),e._state="closed";var r=e._writer;void 0!==r&&Or(r)}(r),null}),(function(e){return function(e,r){e._inFlightCloseRequest._reject(r),e._inFlightCloseRequest=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._reject(r),e._pendingAbortRequest=void 0),ar(e,r)}(r,e),null}))}(e):function(e,r){var t=e._controlledWritableStream;(function(e){e._inFlightWriteRequest=e._writeRequests.shift()})(t),p(e._writeAlgorithm(r),(function(){!function(e){e._inFlightWriteRequest._resolve(void 0),e._inFlightWriteRequest=void 0}(t);var r=t._state;if(ce(e),!ur(t)&&"writable"===r){var n=wr(e);cr(t,n)}return vr(e),null}),(function(r){return"writable"===t._state&&yr(e),function(e,r){e._inFlightWriteRequest._reject(r),e._inFlightWriteRequest=void 0,ar(e,r)}(t,r),null}))}(e,t)}}else lr(r)}function gr(e,r){"writable"===e._controlledWritableStream._state&&Sr(e,r)}function wr(e){return mr(e)<=0}function Sr(e,r){var t=e._controlledWritableStream;yr(e),ir(t,r)}function Rr(e){return new TypeError("WritableStream.prototype.".concat(e," can only be used on a WritableStream"))}function Tr(e){return new TypeError("WritableStreamDefaultController.prototype.".concat(e," can only be used on a WritableStreamDefaultController"))}function qr(e){return new TypeError("WritableStreamDefaultWriter.prototype.".concat(e," can only be used on a WritableStreamDefaultWriter"))}function Pr(e){return new TypeError("Cannot "+e+" a stream using a released writer")}function Cr(e){e._closedPromise=c((function(r,t){e._closedPromise_resolve=r,e._closedPromise_reject=t,e._closedPromiseState="pending"}))}function Er(e,r){Cr(e),Wr(e,r)}function Wr(e,r){void 0!==e._closedPromise_reject&&(m(e._closedPromise),e._closedPromise_reject(r),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="rejected")}function Or(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="resolved")}function kr(e){e._readyPromise=c((function(r,t){e._readyPromise_resolve=r,e._readyPromise_reject=t})),e._readyPromiseState="pending"}function jr(e,r){kr(e),Ar(e,r)}function Br(e){kr(e),zr(e)}function Ar(e,r){void 0!==e._readyPromise_reject&&(m(e._readyPromise),e._readyPromise_reject(r),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="rejected")}function zr(e){void 0!==e._readyPromise_resolve&&(e._readyPromise_resolve(void 0),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="fulfilled")}Object.defineProperties(hr.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),"symbol"==typeof r.toStringTag&&Object.defineProperty(hr.prototype,r.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});var Lr="undefined"!=typeof DOMException?DOMException:void 0;var Fr,Ir=function(e){if("function"!=typeof e&&"object"!=typeof e)return!1;try{return new e,!0}catch(e){return!1}}(Lr)?Lr:((Fr=function(e,r){this.message=e||"",this.name=r||"Error",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}).prototype=Object.create(Error.prototype),Object.defineProperty(Fr.prototype,"constructor",{value:Fr,writable:!0,configurable:!0}),Fr);function Dr(e,r,t,n,o,a){var i=e.getReader(),l=r.getWriter();ot(e)&&(e._disturbed=!0);var u,s,_,g=!1,w=!1,S="readable",R="writable",T=!1,q=!1,P=c((function(e){_=e})),C=Promise.resolve(void 0);return c((function(E,W){var O;function k(){if(!g){var e=c((function(e,r){!function t(n){n?e():b(function(){if(g)return d(!0);return b(l.ready,(function(){return b(i.read(),(function(e){return!!e.done||(m(C=l.write(e.value)),!1)}))}))}(),t,r)}(!1)}));m(e)}}function j(){return S="closed",t?F():L((function(){return rr(r)&&(T=ur(r),R=r._state),T||"closed"===R?d(void 0):"erroring"===R||"errored"===R?f(s):(T=!0,l.close())}),!1,void 0),null}function B(e){return g||(S="errored",u=e,n?F(!0,e):L((function(){return l.abort(e)}),!0,e)),null}function A(e){return w||(R="errored",s=e,o?F(!0,e):L((function(){return i.cancel(e)}),!0,e)),null}if(void 0!==a&&(O=function(){var e=void 0!==a.reason?a.reason:new Ir("Aborted","AbortError"),r=[];n||r.push((function(){return"writable"===R?l.abort(e):d(void 0)})),o||r.push((function(){return"readable"===S?i.cancel(e):d(void 0)})),L((function(){return Promise.all(r.map((function(e){return e()})))}),!0,e)},a.aborted?O():a.addEventListener("abort",O)),ot(e)&&(S=e._state,u=e._storedError),rr(r)&&(R=r._state,s=r._storedError,T=ur(r)),ot(e)&&rr(r)&&(q=!0,_()),"errored"===S)B(u);else if("erroring"===R||"errored"===R)A(s);else if("closed"===S)j();else if(T||"closed"===R){var z=new TypeError("the destination writable stream closed before all data could be piped to it");o?F(!0,z):L((function(){return i.cancel(z)}),!0,z)}function L(e,r,t){function n(){var e;return"writable"!==R||T?o():h(d(function r(){if(e!==C)return e=C,y(C,r,r)}()),o),null}function o(){return e?p(e(),(function(){return I(r,t)}),(function(e){return I(!0,e)})):I(r,t),null}g||(g=!0,q?n():h(P,n))}function F(e,r){L(void 0,e,r)}function I(e,r){return w=!0,l.releaseLock(),i.releaseLock(),void 0!==a&&a.removeEventListener("abort",O),e?W(r):E(void 0),null}g||(p(i.closed,j,B),p(l.closed,(function(){return w||(R="closed"),null}),A)),q?k():v((function(){q=!0,_(),k()}))}))}function Mr(e,r){return function(e){try{return e.getReader({mode:"byob"}).releaseLock(),!0}catch(e){return!1}}(e)?function(e){var r,t,n,o,a,i=e.getReader(),l=!1,u=!1,s=!1,f=!1,b=!1,h=!1,y=c((function(e){a=e}));function m(e){_(e.closed,(function(r){return e!==i||(n.error(r),o.error(r),b&&h||a(void 0)),null}))}function v(){l&&(i.releaseLock(),m(i=e.getReader()),l=!1),p(i.read(),(function(e){var r,t;if(s=!1,f=!1,e.done)return b||n.close(),h||o.close(),null===(r=n.byobRequest)||void 0===r||r.respond(0),null===(t=o.byobRequest)||void 0===t||t.respond(0),b&&h||a(void 0),null;var l=e.value,c=l,d=l;if(!b&&!h)try{d=se(l)}catch(e){return n.error(e),o.error(e),a(i.cancel(e)),null}return b||n.enqueue(c),h||o.enqueue(d),u=!1,s?w():f&&S(),null}),(function(){return u=!1,null}))}function g(r,t){l||(i.releaseLock(),m(i=e.getReader({mode:"byob"})),l=!0);var c=t?o:n,d=t?n:o;p(i.read(r),(function(e){var r;s=!1,f=!1;var n=t?h:b,o=t?b:h;if(e.done){n||c.close(),o||d.close();var l=e.value;return void 0!==l&&(n||c.byobRequest.respondWithNewView(l),o||null===(r=d.byobRequest)||void 0===r||r.respond(0)),n&&o||a(void 0),null}var p=e.value;if(o)n||c.byobRequest.respondWithNewView(p);else{var _=void 0;try{_=se(p)}catch(e){return c.error(e),d.error(e),a(i.cancel(e)),null}n||c.byobRequest.respondWithNewView(p),d.enqueue(_)}return u=!1,s?w():f&&S(),null}),(function(){return u=!1,null}))}function w(){if(u)return s=!0,d(void 0);u=!0;var e=n.byobRequest;return null===e?v():g(e.view,!1),d(void 0)}function S(){if(u)return f=!0,d(void 0);u=!0;var e=o.byobRequest;return null===e?v():g(e.view,!0),d(void 0)}function R(e){if(b=!0,r=e,h){var n=[r,t],o=i.cancel(n);a(o)}return y}function T(e){if(h=!0,t=e,b){var n=[r,t],o=i.cancel(n);a(o)}return y}var q=new nt({type:"bytes",start:function(e){n=e},pull:w,cancel:R}),P=new nt({type:"bytes",start:function(e){o=e},pull:S,cancel:T});return m(i),[q,P]}(e):function(e,r){var t,n,o,a,i,l=e.getReader(),u=!1,s=!1,f=!1,b=!1,h=c((function(e){i=e}));function y(){return u?(s=!0,d(void 0)):(u=!0,p(l.read(),(function(e){if(s=!1,e.done)return f||o.close(),b||a.close(),f&&b||i(void 0),null;var r=e.value,t=r,n=r;return f||o.enqueue(t),b||a.enqueue(n),u=!1,s&&y(),null}),(function(){return u=!1,null})),d(void 0))}function m(e){if(f=!0,t=e,b){var r=[t,n],o=l.cancel(r);i(o)}return h}function v(e){if(b=!0,n=e,f){var r=[t,n],o=l.cancel(r);i(o)}return h}var g=new nt({start:function(e){o=e},pull:y,cancel:m}),w=new nt({start:function(e){a=e},pull:y,cancel:v});return _(l.closed,(function(e){return o.error(e),a.error(e),f&&b||i(void 0),null})),[g,w]}(e)}var Qr=function(){function ReadableStreamDefaultController(){throw new TypeError("Illegal constructor")}return Object.defineProperty(ReadableStreamDefaultController.prototype,"desiredSize",{get:function(){if(!Yr(this))throw Xr("desiredSize");return Vr(this)},enumerable:!1,configurable:!0}),ReadableStreamDefaultController.prototype.close=function(){if(!Yr(this))throw Xr("close");if(!Ur(this))throw new TypeError("The stream is not in a state that permits close");!function(e){if(!Ur(e))return;var r=e._controlledReadableStream;e._closeRequested=!0,0===e._queue.length&&(xr(e),lt(r))}(this)},ReadableStreamDefaultController.prototype.enqueue=function(e){if(void 0===e&&(e=void 0),!Yr(this))throw Xr("enqueue");if(!Ur(this))throw new TypeError("The stream is not in a state that permits enqueue");return function(e,r){if(!Ur(e))return;var t=e._controlledReadableStream;if(at(t)&&K(t)>0)J(t,r,!1);else{var n=void 0;try{n=e._strategySizeAlgorithm(r)}catch(r){throw Hr(e,r),r}try{de(e,r,n)}catch(r){throw Hr(e,r),r}}Nr(e)}(this,e)},ReadableStreamDefaultController.prototype.error=function(e){if(void 0===e&&(e=void 0),!Yr(this))throw Xr("error");Hr(this,e)},ReadableStreamDefaultController.prototype[q]=function(e){fe(this);var r=this._cancelAlgorithm(e);return xr(this),r},ReadableStreamDefaultController.prototype[P]=function(e){var r=this._controlledReadableStream;if(this._queue.length>0){var t=ce(this);this._closeRequested&&0===this._queue.length?(xr(this),lt(r)):Nr(this),e._chunkSteps(t)}else X(r,e),Nr(this)},ReadableStreamDefaultController.prototype[C]=function(){},ReadableStreamDefaultController}();function Yr(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableStream")&&e instanceof Qr)}function Nr(e){var r=function(e){var r=e._controlledReadableStream;if(!Ur(e))return!1;if(!e._started)return!1;if(at(r)&&K(r)>0)return!0;if(Vr(e)>0)return!0;return!1}(e);r&&(e._pulling?e._pullAgain=!0:(e._pulling=!0,p(e._pullAlgorithm(),(function(){return e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,Nr(e)),null}),(function(r){return Hr(e,r),null}))))}function xr(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function Hr(e,r){var t=e._controlledReadableStream;"readable"===t._state&&(fe(e),xr(e),ut(t,r))}function Vr(e){var r=e._controlledReadableStream._state;return"errored"===r?null:"closed"===r?0:e._strategyHWM-e._queueTotalSize}function Ur(e){return!e._closeRequested&&"readable"===e._controlledReadableStream._state}function Gr(e,r,t,n){var o,a,i,l=Object.create(Qr.prototype);o=void 0!==r.start?function(){return r.start(l)}:function(){},a=void 0!==r.pull?function(){return r.pull(l)}:function(){return d(void 0)},i=void 0!==r.cancel?function(e){return r.cancel(e)}:function(){return d(void 0)},function(e,r,t,n,o,a,i){r._controlledReadableStream=e,r._queue=void 0,r._queueTotalSize=void 0,fe(r),r._started=!1,r._closeRequested=!1,r._pullAgain=!1,r._pulling=!1,r._strategySizeAlgorithm=i,r._strategyHWM=a,r._pullAlgorithm=n,r._cancelAlgorithm=o,e._readableStreamController=r,p(d(t()),(function(){return r._started=!0,Nr(r),null}),(function(e){return Hr(r,e),null}))}(e,l,o,a,i,t,n)}function Xr(e){return new TypeError("ReadableStreamDefaultController.prototype.".concat(e," can only be used on a ReadableStreamDefaultController"))}function Jr(e,r,t){return D(e,t),function(t){return w(e,r,[t])}}function Kr(e,r,t){return D(e,t),function(t){return w(e,r,[t])}}function Zr(e,r,t){return D(e,t),function(t){return g(e,r,[t])}}function $r(e,r){if("bytes"!==(e="".concat(e)))throw new TypeError("".concat(r," '").concat(e,"' is not a valid enumeration value for ReadableStreamType"));return e}function et(e,r){if("byob"!==(e="".concat(e)))throw new TypeError("".concat(r," '").concat(e,"' is not a valid enumeration value for ReadableStreamReaderMode"));return e}function rt(e,r){I(e,r);var t=null==e?void 0:e.preventAbort,n=null==e?void 0:e.preventCancel,o=null==e?void 0:e.preventClose,a=null==e?void 0:e.signal;return void 0!==a&&function(e,r){if(!function(e){if("object"!=typeof e||null===e)return!1;try{return"boolean"==typeof e.aborted}catch(e){return!1}}(e))throw new TypeError("".concat(r," is not an AbortSignal."))}(a,"".concat(r," has member 'signal' that")),{preventAbort:Boolean(t),preventCancel:Boolean(n),preventClose:Boolean(o),signal:a}}function tt(e,r){I(e,r);var t=null==e?void 0:e.readable;Y(t,"readable","ReadableWritablePair"),function(e,r){if(!V(e))throw new TypeError("".concat(r," is not a ReadableStream."))}(t,"".concat(r," has member 'readable' that"));var n=null==e?void 0:e.writable;return Y(n,"writable","ReadableWritablePair"),function(e,r){if(!U(e))throw new TypeError("".concat(r," is not a WritableStream."))}(n,"".concat(r," has member 'writable' that")),{readable:t,writable:n}}Object.defineProperties(Qr.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),a(Qr.prototype.close,"close"),a(Qr.prototype.enqueue,"enqueue"),a(Qr.prototype.error,"error"),"symbol"==typeof r.toStringTag&&Object.defineProperty(Qr.prototype,r.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});var nt=function(){function ReadableStream(e,r){void 0===e&&(e={}),void 0===r&&(r={}),void 0===e?e=null:M(e,"First parameter");var t,n=Ue(r,"Second parameter"),o=function(e,r){I(e,r);var t=e,n=null==t?void 0:t.autoAllocateChunkSize,o=null==t?void 0:t.cancel,a=null==t?void 0:t.pull,i=null==t?void 0:t.start,l=null==t?void 0:t.type;return{autoAllocateChunkSize:void 0===n?void 0:H(n,"".concat(r," has member 'autoAllocateChunkSize' that")),cancel:void 0===o?void 0:Jr(o,t,"".concat(r," has member 'cancel' that")),pull:void 0===a?void 0:Kr(a,t,"".concat(r," has member 'pull' that")),start:void 0===i?void 0:Zr(i,t,"".concat(r," has member 'start' that")),type:void 0===l?void 0:$r(l,"".concat(r," has member 'type' that"))}}(e,"First parameter");if((t=this)._state="readable",t._reader=void 0,t._storedError=void 0,t._disturbed=!1,"bytes"===o.type){if(void 0!==n.size)throw new RangeError("The strategy for a byte stream cannot have a size function");ze(this,o,He(n,0))}else{var a=Ve(n);Gr(this,o,He(n,1),a)}}return Object.defineProperty(ReadableStream.prototype,"locked",{get:function(){if(!ot(this))throw st("locked");return at(this)},enumerable:!1,configurable:!0}),ReadableStream.prototype.cancel=function(e){return void 0===e&&(e=void 0),ot(this)?at(this)?f(new TypeError("Cannot cancel a stream that already has a reader")):it(this,e):f(st("cancel"))},ReadableStream.prototype.getReader=function(e){if(void 0===e&&(e=void 0),!ot(this))throw st("getReader");return void 0===function(e,r){I(e,r);var t=null==e?void 0:e.mode;return{mode:void 0===t?void 0:et(t,"".concat(r," has member 'mode' that"))}}(e,"First parameter").mode?new $(this):function(e){return new Qe(e)}(this)},ReadableStream.prototype.pipeThrough=function(e,r){if(void 0===r&&(r={}),!V(this))throw st("pipeThrough");Q(e,1,"pipeThrough");var t=tt(e,"First parameter"),n=rt(r,"Second parameter");if(this.locked)throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(t.writable.locked)throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");return m(Dr(this,t.writable,n.preventClose,n.preventAbort,n.preventCancel,n.signal)),t.readable},ReadableStream.prototype.pipeTo=function(e,r){if(void 0===r&&(r={}),!V(this))return f(st("pipeTo"));if(void 0===e)return f("Parameter 1 is required in 'pipeTo'.");if(!U(e))return f(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));var t;try{t=rt(r,"Second parameter")}catch(e){return f(e)}return this.locked?f(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):e.locked?f(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):Dr(this,e,t.preventClose,t.preventAbort,t.preventCancel,t.signal)},ReadableStream.prototype.tee=function(){if(!V(this))throw st("tee");if(this.locked)throw new TypeError("Cannot tee a stream that already has a reader");return Mr(this)},ReadableStream.prototype.values=function(e){if(void 0===e&&(e=void 0),!V(this))throw st("values");var r,t,n,o,a,i=function(e,r){I(e,r);var t=null==e?void 0:e.preventCancel;return{preventCancel:Boolean(t)}}(e,"First parameter");return r=this,t=i.preventCancel,n=r.getReader(),o=new ne(n,t),(a=Object.create(oe))._asyncIteratorImpl=o,a},ReadableStream}();function ot(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readableStreamController")&&e instanceof nt)}function at(e){return void 0!==e._reader}function it(e,r){if(e._disturbed=!0,"closed"===e._state)return d(void 0);if("errored"===e._state)return f(e._storedError);lt(e);var n=e._reader;if(void 0!==n&&Ye(n)){var o=n._readIntoRequests;n._readIntoRequests=new S,o.forEach((function(e){e._closeSteps(void 0)}))}return y(e._readableStreamController[q](r),t)}function lt(e){e._state="closed";var r=e._reader;if(void 0!==r&&(z(r),ee(r))){var t=r._readRequests;r._readRequests=new S,t.forEach((function(e){e._closeSteps()}))}}function ut(e,r){e._state="errored",e._storedError=r;var t=e._reader;void 0!==t&&(A(t,r),ee(t)?re(t,r):Ne(t,r))}function st(e){return new TypeError("ReadableStream.prototype.".concat(e," can only be used on a ReadableStream"))}function ct(e,r){I(e,r);var t=null==e?void 0:e.highWaterMark;return Y(t,"highWaterMark","QueuingStrategyInit"),{highWaterMark:N(t)}}Object.defineProperties(nt.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),a(nt.prototype.cancel,"cancel"),a(nt.prototype.getReader,"getReader"),a(nt.prototype.pipeThrough,"pipeThrough"),a(nt.prototype.pipeTo,"pipeTo"),a(nt.prototype.tee,"tee"),a(nt.prototype.values,"values"),"symbol"==typeof r.toStringTag&&Object.defineProperty(nt.prototype,r.toStringTag,{value:"ReadableStream",configurable:!0}),"symbol"==typeof r.asyncIterator&&Object.defineProperty(nt.prototype,r.asyncIterator,{value:nt.prototype.values,writable:!0,configurable:!0});var dt=function(e){return e.byteLength};a(dt,"size");var ft=function(){function ByteLengthQueuingStrategy(e){Q(e,1,"ByteLengthQueuingStrategy"),e=ct(e,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=e.highWaterMark}return Object.defineProperty(ByteLengthQueuingStrategy.prototype,"highWaterMark",{get:function(){if(!pt(this))throw bt("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark},enumerable:!1,configurable:!0}),Object.defineProperty(ByteLengthQueuingStrategy.prototype,"size",{get:function(){if(!pt(this))throw bt("size");return dt},enumerable:!1,configurable:!0}),ByteLengthQueuingStrategy}();function bt(e){return new TypeError("ByteLengthQueuingStrategy.prototype.".concat(e," can only be used on a ByteLengthQueuingStrategy"))}function pt(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_byteLengthQueuingStrategyHighWaterMark")&&e instanceof ft)}Object.defineProperties(ft.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof r.toStringTag&&Object.defineProperty(ft.prototype,r.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});var ht=function(){return 1};a(ht,"size");var _t=function(){function CountQueuingStrategy(e){Q(e,1,"CountQueuingStrategy"),e=ct(e,"First parameter"),this._countQueuingStrategyHighWaterMark=e.highWaterMark}return Object.defineProperty(CountQueuingStrategy.prototype,"highWaterMark",{get:function(){if(!mt(this))throw yt("highWaterMark");return this._countQueuingStrategyHighWaterMark},enumerable:!1,configurable:!0}),Object.defineProperty(CountQueuingStrategy.prototype,"size",{get:function(){if(!mt(this))throw yt("size");return ht},enumerable:!1,configurable:!0}),CountQueuingStrategy}();function yt(e){return new TypeError("CountQueuingStrategy.prototype.".concat(e," can only be used on a CountQueuingStrategy"))}function mt(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_countQueuingStrategyHighWaterMark")&&e instanceof _t)}function vt(e,r,t){return D(e,t),function(t){return w(e,r,[t])}}function gt(e,r,t){return D(e,t),function(t){return g(e,r,[t])}}function wt(e,r,t){return D(e,t),function(t,n){return w(e,r,[t,n])}}Object.defineProperties(_t.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof r.toStringTag&&Object.defineProperty(_t.prototype,r.toStringTag,{value:"CountQueuingStrategy",configurable:!0});var St=function(){function TransformStream(e,r,t){void 0===e&&(e={}),void 0===r&&(r={}),void 0===t&&(t={}),void 0===e&&(e=null);var n=Ue(r,"Second parameter"),o=Ue(t,"Third parameter"),a=function(e,r){I(e,r);var t=null==e?void 0:e.flush,n=null==e?void 0:e.readableType,o=null==e?void 0:e.start,a=null==e?void 0:e.transform,i=null==e?void 0:e.writableType;return{flush:void 0===t?void 0:vt(t,e,"".concat(r," has member 'flush' that")),readableType:n,start:void 0===o?void 0:gt(o,e,"".concat(r," has member 'start' that")),transform:void 0===a?void 0:wt(a,e,"".concat(r," has member 'transform' that")),writableType:i}}(e,"First parameter");if(void 0!==a.readableType)throw new RangeError("Invalid readableType specified");if(void 0!==a.writableType)throw new RangeError("Invalid writableType specified");var i,l=He(o,0),u=Ve(o),s=He(n,1),b=Ve(n);!function(e,r,t,n,o,a){function i(){return r}function l(r){return function(e,r){var t=e._transformStreamController;if(e._backpressure){return y(e._backpressureChangePromise,(function(){if("erroring"===(rr(e._writable)?e._writable._state:e._writableState))throw rr(e._writable)?e._writable._storedError:e._writableStoredError;return kt(t,r)}))}return kt(t,r)}(e,r)}function u(r){return function(e,r){return Tt(e,r),d(void 0)}(e,r)}function s(){return function(e){var r=e._transformStreamController,t=r._flushAlgorithm();return Wt(r),y(t,(function(){if("errored"===e._readableState)throw e._readableStoredError;At(e)&&zt(e)}),(function(r){throw Tt(e,r),e._readableStoredError}))}(e)}function c(){return function(e){return Pt(e,!1),e._backpressureChangePromise}(e)}function f(r){return qt(e,r),d(void 0)}e._writableState="writable",e._writableStoredError=void 0,e._writableHasInFlightOperation=!1,e._writableStarted=!1,e._writable=function(e,r,t,n,o,a,i){return new er({start:function(t){e._writableController=t;try{var n=t.signal;void 0!==n&&n.addEventListener("abort",(function(){"writable"===e._writableState&&(e._writableState="erroring",n.reason&&(e._writableStoredError=n.reason))}))}catch(e){}return y(r(),(function(){return e._writableStarted=!0,Qt(e),null}),(function(r){throw e._writableStarted=!0,It(e,r),r}))},write:function(r){return function(e){e._writableHasInFlightOperation=!0}(e),y(t(r),(function(){return function(e){e._writableHasInFlightOperation=!1}(e),Qt(e),null}),(function(r){throw function(e,r){e._writableHasInFlightOperation=!1,It(e,r)}(e,r),r}))},close:function(){return function(e){e._writableHasInFlightOperation=!0}(e),y(n(),(function(){return function(e){e._writableHasInFlightOperation=!1,"erroring"===e._writableState&&(e._writableStoredError=void 0);e._writableState="closed"}(e),null}),(function(r){throw function(e,r){e._writableHasInFlightOperation=!1,e._writableState,It(e,r)}(e,r),r}))},abort:function(r){return e._writableState="errored",e._writableStoredError=r,o(r)}},{highWaterMark:a,size:i})}(e,i,l,s,u,t,n),e._readableState="readable",e._readableStoredError=void 0,e._readableCloseRequested=!1,e._readablePulling=!1,e._readable=function(e,r,t,n,o,a){return new nt({start:function(t){return e._readableController=t,r().catch((function(r){Lt(e,r)}))},pull:function(){return e._readablePulling=!0,t().catch((function(r){Lt(e,r)}))},cancel:function(r){return e._readableState="closed",n(r)}},{highWaterMark:o,size:a})}(e,i,c,f,o,a),e._backpressure=void 0,e._backpressureChangePromise=void 0,e._backpressureChangePromise_resolve=void 0,Pt(e,!0),e._transformStreamController=void 0}(this,c((function(e){i=e})),s,b,l,u),function(e,r){var t,n,o=Object.create(Ct.prototype);t=void 0!==r.transform?function(e){return r.transform(e,o)}:function(e){try{return Ot(o,e),d(void 0)}catch(e){return f(e)}};n=void 0!==r.flush?function(){return r.flush(o)}:function(){return d(void 0)};!function(e,r,t,n){r._controlledTransformStream=e,e._transformStreamController=r,r._transformAlgorithm=t,r._flushAlgorithm=n}(e,o,t,n)}(this,a),void 0!==a.start?i(a.start(this._transformStreamController)):i(void 0)}return Object.defineProperty(TransformStream.prototype,"readable",{get:function(){if(!Rt(this))throw Bt("readable");return this._readable},enumerable:!1,configurable:!0}),Object.defineProperty(TransformStream.prototype,"writable",{get:function(){if(!Rt(this))throw Bt("writable");return this._writable},enumerable:!1,configurable:!0}),TransformStream}();function Rt(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_transformStreamController")&&e instanceof St)}function Tt(e,r){Lt(e,r),qt(e,r)}function qt(e,r){Wt(e._transformStreamController),function(e,r){e._writableController.error(r),"writable"===e._writableState&&Dt(e,r)}(e,r),e._backpressure&&Pt(e,!1)}function Pt(e,r){void 0!==e._backpressureChangePromise&&e._backpressureChangePromise_resolve(),e._backpressureChangePromise=c((function(r){e._backpressureChangePromise_resolve=r})),e._backpressure=r}Object.defineProperties(St.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),"symbol"==typeof r.toStringTag&&Object.defineProperty(St.prototype,r.toStringTag,{value:"TransformStream",configurable:!0});var Ct=function(){function TransformStreamDefaultController(){throw new TypeError("Illegal constructor")}return Object.defineProperty(TransformStreamDefaultController.prototype,"desiredSize",{get:function(){if(!Et(this))throw jt("desiredSize");return Ft(this._controlledTransformStream)},enumerable:!1,configurable:!0}),TransformStreamDefaultController.prototype.enqueue=function(e){if(void 0===e&&(e=void 0),!Et(this))throw jt("enqueue");Ot(this,e)},TransformStreamDefaultController.prototype.error=function(e){if(void 0===e&&(e=void 0),!Et(this))throw jt("error");var r;r=e,Tt(this._controlledTransformStream,r)},TransformStreamDefaultController.prototype.terminate=function(){if(!Et(this))throw jt("terminate");!function(e){var r=e._controlledTransformStream;At(r)&&zt(r);var t=new TypeError("TransformStream terminated");qt(r,t)}(this)},TransformStreamDefaultController}();function Et(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledTransformStream")&&e instanceof Ct)}function Wt(e){e._transformAlgorithm=void 0,e._flushAlgorithm=void 0}function Ot(e,r){var t=e._controlledTransformStream;if(!At(t))throw new TypeError("Readable side is not in a state that permits enqueue");try{!function(e,r){e._readablePulling=!1;try{e._readableController.enqueue(r)}catch(r){throw Lt(e,r),r}}(t,r)}catch(e){throw qt(t,e),t._readableStoredError}var n=function(e){return!function(e){if(!At(e))return!1;if(e._readablePulling)return!0;if(Ft(e)>0)return!0;return!1}(e)}(t);n!==t._backpressure&&Pt(t,!0)}function kt(e,r){return y(e._transformAlgorithm(r),void 0,(function(r){throw Tt(e._controlledTransformStream,r),r}))}function jt(e){return new TypeError("TransformStreamDefaultController.prototype.".concat(e," can only be used on a TransformStreamDefaultController"))}function Bt(e){return new TypeError("TransformStream.prototype.".concat(e," can only be used on a TransformStream"))}function At(e){return!e._readableCloseRequested&&"readable"===e._readableState}function zt(e){e._readableState="closed",e._readableCloseRequested=!0,e._readableController.close()}function Lt(e,r){"readable"===e._readableState&&(e._readableState="errored",e._readableStoredError=r),e._readableController.error(r)}function Ft(e){return e._readableController.desiredSize}function It(e,r){"writable"!==e._writableState?Mt(e):Dt(e,r)}function Dt(e,r){e._writableState="erroring",e._writableStoredError=r,!function(e){return e._writableHasInFlightOperation}(e)&&e._writableStarted&&Mt(e)}function Mt(e){e._writableState="errored"}function Qt(e){"erroring"===e._writableState&&Mt(e)}Object.defineProperties(Ct.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),a(Ct.prototype.enqueue,"enqueue"),a(Ct.prototype.error,"error"),a(Ct.prototype.terminate,"terminate"),"symbol"==typeof r.toStringTag&&Object.defineProperty(Ct.prototype,r.toStringTag,{value:"TransformStreamDefaultController",configurable:!0}),e.ByteLengthQueuingStrategy=ft,e.CountQueuingStrategy=_t,e.ReadableByteStreamController=pe,e.ReadableStream=nt,e.ReadableStreamBYOBReader=Qe,e.ReadableStreamBYOBRequest=be,e.ReadableStreamDefaultController=Qr,e.ReadableStreamDefaultReader=$,e.TransformStream=St,e.TransformStreamDefaultController=Ct,e.WritableStream=er,e.WritableStreamDefaultController=hr,e.WritableStreamDefaultWriter=dr,Object.defineProperty(e,"__esModule",{value:!0})})); diff --git a/backend/node_modules/formdata-node/node_modules/web-streams-polyfill/dist/ponyfill.es5.mjs b/backend/node_modules/formdata-node/node_modules/web-streams-polyfill/dist/ponyfill.es5.mjs new file mode 100644 index 0000000000000000000000000000000000000000..fd39671a47430311c081029456a735585e34e87f --- /dev/null +++ b/backend/node_modules/formdata-node/node_modules/web-streams-polyfill/dist/ponyfill.es5.mjs @@ -0,0 +1,8 @@ +/** + * @license + * web-streams-polyfill v4.0.0-beta.3 + * Copyright 2021 Mattias Buelens, Diwank Singh Tomer and other contributors. + * This code is released under the MIT license. + * SPDX-License-Identifier: MIT + */ +var e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol:function(e){return"Symbol(".concat(e,")")};function r(){}function t(e){return"object"==typeof e&&null!==e||"function"==typeof e}var n=r;function o(e,r){try{Object.defineProperty(e,"name",{value:r,configurable:!0})}catch(e){}}var a=Promise,i=Promise.prototype.then,l=Promise.resolve.bind(a),u=Promise.reject.bind(a);function s(e){return new a(e)}function c(e){return l(e)}function d(e){return u(e)}function f(e,r,t){return i.call(e,r,t)}function b(e,r,t){f(f(e,r,t),void 0,n)}function p(e,r){b(e,r)}function h(e,r){b(e,void 0,r)}function _(e,r,t){return f(e,r,t)}function y(e){f(e,void 0,n)}var v=function(e){if("function"==typeof queueMicrotask)v=queueMicrotask;else{var r=c(void 0);v=function(e){return f(r,e)}}return v(e)};function m(e,r,t){if("function"!=typeof e)throw new TypeError("Argument is not a function");return Function.prototype.apply.call(e,r,t)}function g(e,r,t){try{return c(m(e,r,t))}catch(e){return d(e)}}var w=function(){function e(){this._cursor=0,this._size=0,this._front={_elements:[],_next:void 0},this._back=this._front,this._cursor=0,this._size=0}return Object.defineProperty(e.prototype,"length",{get:function(){return this._size},enumerable:!1,configurable:!0}),e.prototype.push=function(e){var r=this._back,t=r;16383===r._elements.length&&(t={_elements:[],_next:void 0}),r._elements.push(e),t!==r&&(this._back=t,r._next=t),++this._size},e.prototype.shift=function(){var e=this._front,r=e,t=this._cursor,n=t+1,o=e._elements,a=o[t];return 16384===n&&(r=e._next,n=0),--this._size,this._cursor=n,e!==r&&(this._front=r),o[t]=void 0,a},e.prototype.forEach=function(e){for(var r=this._cursor,t=this._front,n=t._elements;!(r===n.length&&void 0===t._next||r===n.length&&(r=0,0===(n=(t=t._next)._elements).length));)e(n[r]),++r},e.prototype.peek=function(){var e=this._front,r=this._cursor;return e._elements[r]},e}(),S=e("[[AbortSteps]]"),R=e("[[ErrorSteps]]"),T=e("[[CancelSteps]]"),q=e("[[PullSteps]]"),P=e("[[ReleaseSteps]]");function C(e,r){e._ownerReadableStream=r,r._reader=e,"readable"===r._state?k(e):"closed"===r._state?function(e){k(e),A(e)}(e):j(e,r._storedError)}function E(e,r){return at(e._ownerReadableStream,r)}function O(e){var r=e._ownerReadableStream;"readable"===r._state?B(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):function(e,r){j(e,r)}(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),r._readableStreamController[P](),r._reader=void 0,e._ownerReadableStream=void 0}function W(e){return new TypeError("Cannot "+e+" a stream using a released reader")}function k(e){e._closedPromise=s((function(r,t){e._closedPromise_resolve=r,e._closedPromise_reject=t}))}function j(e,r){k(e),B(e,r)}function B(e,r){void 0!==e._closedPromise_reject&&(y(e._closedPromise),e._closedPromise_reject(r),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}function A(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}var z=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},L=Math.trunc||function(e){return e<0?Math.ceil(e):Math.floor(e)};function F(e,r){if(void 0!==e&&("object"!=typeof(t=e)&&"function"!=typeof t))throw new TypeError("".concat(r," is not an object."));var t}function I(e,r){if("function"!=typeof e)throw new TypeError("".concat(r," is not a function."))}function D(e,r){if(!function(e){return"object"==typeof e&&null!==e||"function"==typeof e}(e))throw new TypeError("".concat(r," is not an object."))}function M(e,r,t){if(void 0===e)throw new TypeError("Parameter ".concat(r," is required in '").concat(t,"'."))}function Q(e,r,t){if(void 0===e)throw new TypeError("".concat(r," is required in '").concat(t,"'."))}function Y(e){return Number(e)}function N(e){return 0===e?0:e}function H(e,r){var t=Number.MAX_SAFE_INTEGER,n=Number(e);if(n=N(n),!z(n))throw new TypeError("".concat(r," is not a finite number"));if((n=function(e){return N(L(e))}(n))<0||n>t)throw new TypeError("".concat(r," is outside the accepted range of ").concat(0," to ").concat(t,", inclusive"));return z(n)&&0!==n?n:0}function x(e){if(!t(e))return!1;if("function"!=typeof e.getReader)return!1;try{return"boolean"==typeof e.locked}catch(e){return!1}}function V(e){if(!t(e))return!1;if("function"!=typeof e.getWriter)return!1;try{return"boolean"==typeof e.locked}catch(e){return!1}}function U(e,r){if(!nt(e))throw new TypeError("".concat(r," is not a ReadableStream."))}function G(e,r){e._reader._readRequests.push(r)}function X(e,r,t){var n=e._reader._readRequests.shift();t?n._closeSteps():n._chunkSteps(r)}function J(e){return e._reader._readRequests.length}function K(e){var r=e._reader;return void 0!==r&&!!$(r)}var Z=function(){function ReadableStreamDefaultReader(e){if(M(e,1,"ReadableStreamDefaultReader"),U(e,"First parameter"),ot(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");C(this,e),this._readRequests=new w}return Object.defineProperty(ReadableStreamDefaultReader.prototype,"closed",{get:function(){return $(this)?this._closedPromise:d(re("closed"))},enumerable:!1,configurable:!0}),ReadableStreamDefaultReader.prototype.cancel=function(e){return void 0===e&&(e=void 0),$(this)?void 0===this._ownerReadableStream?d(W("cancel")):E(this,e):d(re("cancel"))},ReadableStreamDefaultReader.prototype.read=function(){if(!$(this))return d(re("read"));if(void 0===this._ownerReadableStream)return d(W("read from"));var e,r,t=s((function(t,n){e=t,r=n}));return function(e,r){var t=e._ownerReadableStream;t._disturbed=!0,"closed"===t._state?r._closeSteps():"errored"===t._state?r._errorSteps(t._storedError):t._readableStreamController[q](r)}(this,{_chunkSteps:function(r){return e({value:r,done:!1})},_closeSteps:function(){return e({value:void 0,done:!0})},_errorSteps:function(e){return r(e)}}),t},ReadableStreamDefaultReader.prototype.releaseLock=function(){if(!$(this))throw re("releaseLock");void 0!==this._ownerReadableStream&&function(e){O(e);var r=new TypeError("Reader was released");ee(e,r)}(this)},ReadableStreamDefaultReader}();function $(e){return!!t(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readRequests")&&e instanceof Z)}function ee(e,r){var t=e._readRequests;e._readRequests=new w,t.forEach((function(e){e._errorSteps(r)}))}function re(e){return new TypeError("ReadableStreamDefaultReader.prototype.".concat(e," can only be used on a ReadableStreamDefaultReader"))}Object.defineProperties(Z.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),o(Z.prototype.cancel,"cancel"),o(Z.prototype.read,"read"),o(Z.prototype.releaseLock,"releaseLock"),"symbol"==typeof e.toStringTag&&Object.defineProperty(Z.prototype,e.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0});var te=function(){function e(e,r){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=e,this._preventCancel=r}return e.prototype.next=function(){var e=this,r=function(){return e._nextSteps()};return this._ongoingPromise=this._ongoingPromise?_(this._ongoingPromise,r,r):r(),this._ongoingPromise},e.prototype.return=function(e){var r=this,t=function(){return r._returnSteps(e)};return this._ongoingPromise?_(this._ongoingPromise,t,t):t()},e.prototype._nextSteps=function(){var e=this;if(this._isFinished)return Promise.resolve({value:void 0,done:!0});var r=this._reader;return void 0===r?d(W("iterate")):f(r.read(),(function(r){var t;return e._ongoingPromise=void 0,r.done&&(e._isFinished=!0,null===(t=e._reader)||void 0===t||t.releaseLock(),e._reader=void 0),r}),(function(r){var t;throw e._ongoingPromise=void 0,e._isFinished=!0,null===(t=e._reader)||void 0===t||t.releaseLock(),e._reader=void 0,r}))},e.prototype._returnSteps=function(e){if(this._isFinished)return Promise.resolve({value:e,done:!0});this._isFinished=!0;var r=this._reader;if(void 0===r)return d(W("finish iterating"));if(this._reader=void 0,!this._preventCancel){var t=r.cancel(e);return r.releaseLock(),_(t,(function(){return{value:e,done:!0}}))}return r.releaseLock(),c({value:e,done:!0})},e}(),ne={next:function(){return oe(this)?this._asyncIteratorImpl.next():d(ae("next"))},return:function(e){return oe(this)?this._asyncIteratorImpl.return(e):d(ae("return"))}};function oe(e){if(!t(e))return!1;if(!Object.prototype.hasOwnProperty.call(e,"_asyncIteratorImpl"))return!1;try{return e._asyncIteratorImpl instanceof te}catch(e){return!1}}function ae(e){return new TypeError("ReadableStreamAsyncIterator.".concat(e," can only be used on a ReadableSteamAsyncIterator"))}"symbol"==typeof e.asyncIterator&&Object.defineProperty(ne,e.asyncIterator,{value:function(){return this},writable:!0,configurable:!0});var ie=Number.isNaN||function(e){return e!=e};function le(e,r,t,n,o){new Uint8Array(e).set(new Uint8Array(t,n,o),r)}function ue(e){var r=function(e,r,t){if(e.slice)return e.slice(r,t);var n=t-r,o=new ArrayBuffer(n);return le(o,0,e,r,n),o}(e.buffer,e.byteOffset,e.byteOffset+e.byteLength);return new Uint8Array(r)}function se(e){var r=e._queue.shift();return e._queueTotalSize-=r.size,e._queueTotalSize<0&&(e._queueTotalSize=0),r.value}function ce(e,r,t){if("number"!=typeof(n=t)||ie(n)||n<0||t===1/0)throw new RangeError("Size must be a finite, non-NaN, non-negative number.");var n;e._queue.push({value:r,size:t}),e._queueTotalSize+=t}function de(e){e._queue=new w,e._queueTotalSize=0}var fe=function(){function ReadableStreamBYOBRequest(){throw new TypeError("Illegal constructor")}return Object.defineProperty(ReadableStreamBYOBRequest.prototype,"view",{get:function(){if(!he(this))throw ze("view");return this._view},enumerable:!1,configurable:!0}),ReadableStreamBYOBRequest.prototype.respond=function(e){if(!he(this))throw ze("respond");if(M(e,1,"respond"),e=H(e,"First parameter"),void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");this._view.buffer,function(e,r){var t=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==r)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream")}else{if(0===r)throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");if(t.bytesFilled+r>t.byteLength)throw new RangeError("bytesWritten out of range")}t.buffer=t.buffer,Ee(e,r)}(this._associatedReadableByteStreamController,e)},ReadableStreamBYOBRequest.prototype.respondWithNewView=function(e){if(!he(this))throw ze("respondWithNewView");if(M(e,1,"respondWithNewView"),!ArrayBuffer.isView(e))throw new TypeError("You can only respond with array buffer views");if(void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");e.buffer,function(e,r){var t=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==r.byteLength)throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream")}else if(0===r.byteLength)throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");if(t.byteOffset+t.bytesFilled!==r.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(t.bufferByteLength!==r.buffer.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");if(t.bytesFilled+r.byteLength>t.byteLength)throw new RangeError("The region specified by view is larger than byobRequest");var n=r.byteLength;t.buffer=r.buffer,Ee(e,n)}(this._associatedReadableByteStreamController,e)},ReadableStreamBYOBRequest}();Object.defineProperties(fe.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),o(fe.prototype.respond,"respond"),o(fe.prototype.respondWithNewView,"respondWithNewView"),"symbol"==typeof e.toStringTag&&Object.defineProperty(fe.prototype,e.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});var be=function(){function ReadableByteStreamController(){throw new TypeError("Illegal constructor")}return Object.defineProperty(ReadableByteStreamController.prototype,"byobRequest",{get:function(){if(!pe(this))throw Le("byobRequest");return function(e){if(null===e._byobRequest&&e._pendingPullIntos.length>0){var r=e._pendingPullIntos.peek(),t=new Uint8Array(r.buffer,r.byteOffset+r.bytesFilled,r.byteLength-r.bytesFilled),n=Object.create(fe.prototype);!function(e,r,t){e._associatedReadableByteStreamController=r,e._view=t}(n,e,t),e._byobRequest=n}return e._byobRequest}(this)},enumerable:!1,configurable:!0}),Object.defineProperty(ReadableByteStreamController.prototype,"desiredSize",{get:function(){if(!pe(this))throw Le("desiredSize");return Be(this)},enumerable:!1,configurable:!0}),ReadableByteStreamController.prototype.close=function(){if(!pe(this))throw Le("close");if(this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");var e=this._controlledReadableByteStream._state;if("readable"!==e)throw new TypeError("The stream (in ".concat(e," state) is not in the readable state and cannot be closed"));!function(e){var r=e._controlledReadableByteStream;if(e._closeRequested||"readable"!==r._state)return;if(e._queueTotalSize>0)return void(e._closeRequested=!0);if(e._pendingPullIntos.length>0){if(e._pendingPullIntos.peek().bytesFilled>0){var t=new TypeError("Insufficient bytes to fill elements in the given buffer");throw ke(e,t),t}}We(e),it(r)}(this)},ReadableByteStreamController.prototype.enqueue=function(e){if(!pe(this))throw Le("enqueue");if(M(e,1,"enqueue"),!ArrayBuffer.isView(e))throw new TypeError("chunk must be an array buffer view");if(0===e.byteLength)throw new TypeError("chunk must have non-zero byteLength");if(0===e.buffer.byteLength)throw new TypeError("chunk's buffer must have non-zero byteLength");if(this._closeRequested)throw new TypeError("stream is closed or draining");var r=this._controlledReadableByteStream._state;if("readable"!==r)throw new TypeError("The stream (in ".concat(r," state) is not in the readable state and cannot be enqueued to"));!function(e,r){var t=e._controlledReadableByteStream;if(e._closeRequested||"readable"!==t._state)return;var n=r.buffer,o=r.byteOffset,a=r.byteLength,i=n;if(e._pendingPullIntos.length>0){var l=e._pendingPullIntos.peek();l.buffer,0,Pe(e),l.buffer=l.buffer,"none"===l.readerType&&Se(e,l)}if(K(t)){if(function(e){var r=e._controlledReadableByteStream._reader;for(;r._readRequests.length>0;){if(0===e._queueTotalSize)return;je(e,r._readRequests.shift())}}(e),0===J(t))ge(e,i,o,a);else e._pendingPullIntos.length>0&&Oe(e),X(t,new Uint8Array(i,o,a),!1)}else De(t)?(ge(e,i,o,a),Ce(e)):ge(e,i,o,a);_e(e)}(this,e)},ReadableByteStreamController.prototype.error=function(e){if(void 0===e&&(e=void 0),!pe(this))throw Le("error");ke(this,e)},ReadableByteStreamController.prototype[T]=function(e){ye(this),de(this);var r=this._cancelAlgorithm(e);return We(this),r},ReadableByteStreamController.prototype[q]=function(e){var r=this._controlledReadableByteStream;if(this._queueTotalSize>0)je(this,e);else{var t=this._autoAllocateChunkSize;if(void 0!==t){var n=void 0;try{n=new ArrayBuffer(t)}catch(r){return void e._errorSteps(r)}var o={buffer:n,bufferByteLength:t,byteOffset:0,byteLength:t,bytesFilled:0,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(o)}G(r,e),_e(this)}},ReadableByteStreamController.prototype[P]=function(){if(this._pendingPullIntos.length>0){var e=this._pendingPullIntos.peek();e.readerType="none",this._pendingPullIntos=new w,this._pendingPullIntos.push(e)}},ReadableByteStreamController}();function pe(e){return!!t(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableByteStream")&&e instanceof be)}function he(e){return!!t(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_associatedReadableByteStreamController")&&e instanceof fe)}function _e(e){var r=function(e){var r=e._controlledReadableByteStream;if("readable"!==r._state)return!1;if(e._closeRequested)return!1;if(!e._started)return!1;if(K(r)&&J(r)>0)return!0;if(De(r)&&Ie(r)>0)return!0;if(Be(e)>0)return!0;return!1}(e);r&&(e._pulling?e._pullAgain=!0:(e._pulling=!0,b(e._pullAlgorithm(),(function(){return e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,_e(e)),null}),(function(r){return ke(e,r),null}))))}function ye(e){Pe(e),e._pendingPullIntos=new w}function ve(e,r){var t=!1;"closed"===e._state&&(t=!0);var n=me(r);"default"===r.readerType?X(e,n,t):function(e,r,t){var n=e._reader._readIntoRequests.shift();t?n._closeSteps(r):n._chunkSteps(r)}(e,n,t)}function me(e){var r=e.bytesFilled,t=e.elementSize;return new e.viewConstructor(e.buffer,e.byteOffset,r/t)}function ge(e,r,t,n){e._queue.push({buffer:r,byteOffset:t,byteLength:n}),e._queueTotalSize+=n}function we(e,r,t,n){var o;try{o=r.slice(t,t+n)}catch(r){throw ke(e,r),r}ge(e,o,0,n)}function Se(e,r){r.bytesFilled>0&&we(e,r.buffer,r.byteOffset,r.bytesFilled),Oe(e)}function Re(e,r){var t=r.elementSize,n=r.bytesFilled-r.bytesFilled%t,o=Math.min(e._queueTotalSize,r.byteLength-r.bytesFilled),a=r.bytesFilled+o,i=a-a%t,l=o,u=!1;i>n&&(l=i-r.bytesFilled,u=!0);for(var s=e._queue;l>0;){var c=s.peek(),d=Math.min(l,c.byteLength),f=r.byteOffset+r.bytesFilled;le(r.buffer,f,c.buffer,c.byteOffset,d),c.byteLength===d?s.shift():(c.byteOffset+=d,c.byteLength-=d),e._queueTotalSize-=d,Te(e,d,r),l-=d}return u}function Te(e,r,t){t.bytesFilled+=r}function qe(e){0===e._queueTotalSize&&e._closeRequested?(We(e),it(e._controlledReadableByteStream)):_e(e)}function Pe(e){null!==e._byobRequest&&(e._byobRequest._associatedReadableByteStreamController=void 0,e._byobRequest._view=null,e._byobRequest=null)}function Ce(e){for(;e._pendingPullIntos.length>0;){if(0===e._queueTotalSize)return;var r=e._pendingPullIntos.peek();Re(e,r)&&(Oe(e),ve(e._controlledReadableByteStream,r))}}function Ee(e,r){var t=e._pendingPullIntos.peek();Pe(e),"closed"===e._controlledReadableByteStream._state?function(e,r){"none"===r.readerType&&Oe(e);var t=e._controlledReadableByteStream;if(De(t))for(;Ie(t)>0;)ve(t,Oe(e))}(e,t):function(e,r,t){if(Te(0,r,t),"none"===t.readerType)return Se(e,t),void Ce(e);if(!(t.bytesFilled0){var o=t.byteOffset+t.bytesFilled;we(e,t.buffer,o-n,n)}t.bytesFilled-=n,ve(e._controlledReadableByteStream,t),Ce(e)}}(e,r,t),_e(e)}function Oe(e){return e._pendingPullIntos.shift()}function We(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0}function ke(e,r){var t=e._controlledReadableByteStream;"readable"===t._state&&(ye(e),de(e),We(e),lt(t,r))}function je(e,r){var t=e._queue.shift();e._queueTotalSize-=t.byteLength,qe(e);var n=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);r._chunkSteps(n)}function Be(e){var r=e._controlledReadableByteStream._state;return"errored"===r?null:"closed"===r?0:e._strategyHWM-e._queueTotalSize}function Ae(e,r,t){var n,o,a,i=Object.create(be.prototype);n=void 0!==r.start?function(){return r.start(i)}:function(){},o=void 0!==r.pull?function(){return r.pull(i)}:function(){return c(void 0)},a=void 0!==r.cancel?function(e){return r.cancel(e)}:function(){return c(void 0)};var l=r.autoAllocateChunkSize;if(0===l)throw new TypeError("autoAllocateChunkSize must be greater than 0");!function(e,r,t,n,o,a,i){r._controlledReadableByteStream=e,r._pullAgain=!1,r._pulling=!1,r._byobRequest=null,r._queue=r._queueTotalSize=void 0,de(r),r._closeRequested=!1,r._started=!1,r._strategyHWM=a,r._pullAlgorithm=n,r._cancelAlgorithm=o,r._autoAllocateChunkSize=i,r._pendingPullIntos=new w,e._readableStreamController=r,b(c(t()),(function(){return r._started=!0,_e(r),null}),(function(e){return ke(r,e),null}))}(e,i,n,o,a,t,l)}function ze(e){return new TypeError("ReadableStreamBYOBRequest.prototype.".concat(e," can only be used on a ReadableStreamBYOBRequest"))}function Le(e){return new TypeError("ReadableByteStreamController.prototype.".concat(e," can only be used on a ReadableByteStreamController"))}function Fe(e,r){e._reader._readIntoRequests.push(r)}function Ie(e){return e._reader._readIntoRequests.length}function De(e){var r=e._reader;return void 0!==r&&!!Qe(r)}Object.defineProperties(be.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),o(be.prototype.close,"close"),o(be.prototype.enqueue,"enqueue"),o(be.prototype.error,"error"),"symbol"==typeof e.toStringTag&&Object.defineProperty(be.prototype,e.toStringTag,{value:"ReadableByteStreamController",configurable:!0});var Me=function(){function ReadableStreamBYOBReader(e){if(M(e,1,"ReadableStreamBYOBReader"),U(e,"First parameter"),ot(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!pe(e._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");C(this,e),this._readIntoRequests=new w}return Object.defineProperty(ReadableStreamBYOBReader.prototype,"closed",{get:function(){return Qe(this)?this._closedPromise:d(Ne("closed"))},enumerable:!1,configurable:!0}),ReadableStreamBYOBReader.prototype.cancel=function(e){return void 0===e&&(e=void 0),Qe(this)?void 0===this._ownerReadableStream?d(W("cancel")):E(this,e):d(Ne("cancel"))},ReadableStreamBYOBReader.prototype.read=function(e){if(!Qe(this))return d(Ne("read"));if(!ArrayBuffer.isView(e))return d(new TypeError("view must be an array buffer view"));if(0===e.byteLength)return d(new TypeError("view must have non-zero byteLength"));if(0===e.buffer.byteLength)return d(new TypeError("view's buffer must have non-zero byteLength"));if(e.buffer,void 0===this._ownerReadableStream)return d(W("read from"));var r,t,n=s((function(e,n){r=e,t=n}));return function(e,r,t){var n=e._ownerReadableStream;n._disturbed=!0,"errored"===n._state?t._errorSteps(n._storedError):function(e,r,t){var n=e._controlledReadableByteStream,o=1;r.constructor!==DataView&&(o=r.constructor.BYTES_PER_ELEMENT);var a=r.constructor,i=r.buffer,l={buffer:i,bufferByteLength:i.byteLength,byteOffset:r.byteOffset,byteLength:r.byteLength,bytesFilled:0,elementSize:o,viewConstructor:a,readerType:"byob"};if(e._pendingPullIntos.length>0)return e._pendingPullIntos.push(l),void Fe(n,t);if("closed"!==n._state){if(e._queueTotalSize>0){if(Re(e,l)){var u=me(l);return qe(e),void t._chunkSteps(u)}if(e._closeRequested){var s=new TypeError("Insufficient bytes to fill elements in the given buffer");return ke(e,s),void t._errorSteps(s)}}e._pendingPullIntos.push(l),Fe(n,t),_e(e)}else{var c=new a(l.buffer,l.byteOffset,0);t._closeSteps(c)}}(n._readableStreamController,r,t)}(this,e,{_chunkSteps:function(e){return r({value:e,done:!1})},_closeSteps:function(e){return r({value:e,done:!0})},_errorSteps:function(e){return t(e)}}),n},ReadableStreamBYOBReader.prototype.releaseLock=function(){if(!Qe(this))throw Ne("releaseLock");void 0!==this._ownerReadableStream&&function(e){O(e);var r=new TypeError("Reader was released");Ye(e,r)}(this)},ReadableStreamBYOBReader}();function Qe(e){return!!t(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readIntoRequests")&&e instanceof Me)}function Ye(e,r){var t=e._readIntoRequests;e._readIntoRequests=new w,t.forEach((function(e){e._errorSteps(r)}))}function Ne(e){return new TypeError("ReadableStreamBYOBReader.prototype.".concat(e," can only be used on a ReadableStreamBYOBReader"))}function He(e,r){var t=e.highWaterMark;if(void 0===t)return r;if(ie(t)||t<0)throw new RangeError("Invalid highWaterMark");return t}function xe(e){var r=e.size;return r||function(){return 1}}function Ve(e,r){F(e,r);var t=null==e?void 0:e.highWaterMark,n=null==e?void 0:e.size;return{highWaterMark:void 0===t?void 0:Y(t),size:void 0===n?void 0:Ue(n,"".concat(r," has member 'size' that"))}}function Ue(e,r){return I(e,r),function(r){return Y(e(r))}}function Ge(e,r,t){return I(e,t),function(t){return g(e,r,[t])}}function Xe(e,r,t){return I(e,t),function(){return g(e,r,[])}}function Je(e,r,t){return I(e,t),function(t){return m(e,r,[t])}}function Ke(e,r,t){return I(e,t),function(t,n){return g(e,r,[t,n])}}Object.defineProperties(Me.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),o(Me.prototype.cancel,"cancel"),o(Me.prototype.read,"read"),o(Me.prototype.releaseLock,"releaseLock"),"symbol"==typeof e.toStringTag&&Object.defineProperty(Me.prototype,e.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});var Ze="function"==typeof AbortController;var $e=function(){function WritableStream(e,r){void 0===e&&(e={}),void 0===r&&(r={}),void 0===e?e=null:D(e,"First parameter");var t,n=Ve(r,"Second parameter"),o=function(e,r){F(e,r);var t=null==e?void 0:e.abort,n=null==e?void 0:e.close,o=null==e?void 0:e.start,a=null==e?void 0:e.type,i=null==e?void 0:e.write;return{abort:void 0===t?void 0:Ge(t,e,"".concat(r," has member 'abort' that")),close:void 0===n?void 0:Xe(n,e,"".concat(r," has member 'close' that")),start:void 0===o?void 0:Je(o,e,"".concat(r," has member 'start' that")),write:void 0===i?void 0:Ke(i,e,"".concat(r," has member 'write' that")),type:a}}(e,"First parameter");if((t=this)._state="writable",t._storedError=void 0,t._writer=void 0,t._writableStreamController=void 0,t._writeRequests=new w,t._inFlightWriteRequest=void 0,t._closeRequest=void 0,t._inFlightCloseRequest=void 0,t._pendingAbortRequest=void 0,t._backpressure=!1,void 0!==o.type)throw new RangeError("Invalid type is specified");var a=xe(n);!function(e,r,t,n){var o,a,i,l,u=Object.create(pr.prototype);o=void 0!==r.start?function(){return r.start(u)}:function(){};a=void 0!==r.write?function(e){return r.write(e,u)}:function(){return c(void 0)};i=void 0!==r.close?function(){return r.close()}:function(){return c(void 0)};l=void 0!==r.abort?function(e){return r.abort(e)}:function(){return c(void 0)};!function(e,r,t,n,o,a,i,l){r._controlledWritableStream=e,e._writableStreamController=r,r._queue=void 0,r._queueTotalSize=void 0,de(r),r._abortReason=void 0,r._abortController=function(){if(Ze)return new AbortController}(),r._started=!1,r._strategySizeAlgorithm=l,r._strategyHWM=i,r._writeAlgorithm=n,r._closeAlgorithm=o,r._abortAlgorithm=a;var u=gr(r);sr(e,u),b(c(t()),(function(){return r._started=!0,vr(r),null}),(function(t){return r._started=!0,or(e,t),null}))}(e,u,o,a,i,l,t,n)}(this,o,He(n,1),a)}return Object.defineProperty(WritableStream.prototype,"locked",{get:function(){if(!er(this))throw Sr("locked");return rr(this)},enumerable:!1,configurable:!0}),WritableStream.prototype.abort=function(e){return void 0===e&&(e=void 0),er(this)?rr(this)?d(new TypeError("Cannot abort a stream that already has a writer")):tr(this,e):d(Sr("abort"))},WritableStream.prototype.close=function(){return er(this)?rr(this)?d(new TypeError("Cannot close a stream that already has a writer")):lr(this)?d(new TypeError("Cannot close an already-closing stream")):nr(this):d(Sr("close"))},WritableStream.prototype.getWriter=function(){if(!er(this))throw Sr("getWriter");return new cr(this)},WritableStream}();function er(e){return!!t(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_writableStreamController")&&e instanceof $e)}function rr(e){return void 0!==e._writer}function tr(e,r){var t;if("closed"===e._state||"errored"===e._state)return c(void 0);e._writableStreamController._abortReason=r,null===(t=e._writableStreamController._abortController)||void 0===t||t.abort(r);var n=e._state;if("closed"===n||"errored"===n)return c(void 0);if(void 0!==e._pendingAbortRequest)return e._pendingAbortRequest._promise;var o=!1;"erroring"===n&&(o=!0,r=void 0);var a=s((function(t,n){e._pendingAbortRequest={_promise:void 0,_resolve:t,_reject:n,_reason:r,_wasAlreadyErroring:o}}));return e._pendingAbortRequest._promise=a,o||ar(e,r),a}function nr(e){var r=e._state;if("closed"===r||"errored"===r)return d(new TypeError("The stream (in ".concat(r," state) is not in the writable state and cannot be closed")));var t,n=s((function(r,t){var n={_resolve:r,_reject:t};e._closeRequest=n})),o=e._writer;return void 0!==o&&e._backpressure&&"writable"===r&&Ar(o),ce(t=e._writableStreamController,br,0),vr(t),n}function or(e,r){"writable"!==e._state?ir(e):ar(e,r)}function ar(e,r){var t=e._writableStreamController;e._state="erroring",e._storedError=r;var n=e._writer;void 0!==n&&fr(n,r),!function(e){if(void 0===e._inFlightWriteRequest&&void 0===e._inFlightCloseRequest)return!1;return!0}(e)&&t._started&&ir(e)}function ir(e){e._state="errored",e._writableStreamController[R]();var r=e._storedError;if(e._writeRequests.forEach((function(e){e._reject(r)})),e._writeRequests=new w,void 0!==e._pendingAbortRequest){var t=e._pendingAbortRequest;if(e._pendingAbortRequest=void 0,t._wasAlreadyErroring)return t._reject(r),void ur(e);b(e._writableStreamController[S](t._reason),(function(){return t._resolve(),ur(e),null}),(function(r){return t._reject(r),ur(e),null}))}else ur(e)}function lr(e){return void 0!==e._closeRequest||void 0!==e._inFlightCloseRequest}function ur(e){void 0!==e._closeRequest&&(e._closeRequest._reject(e._storedError),e._closeRequest=void 0);var r=e._writer;void 0!==r&&Er(r,e._storedError)}function sr(e,r){var t=e._writer;void 0!==t&&r!==e._backpressure&&(r?function(e){Wr(e)}(t):Ar(t)),e._backpressure=r}Object.defineProperties($e.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),o($e.prototype.abort,"abort"),o($e.prototype.close,"close"),o($e.prototype.getWriter,"getWriter"),"symbol"==typeof e.toStringTag&&Object.defineProperty($e.prototype,e.toStringTag,{value:"WritableStream",configurable:!0});var cr=function(){function WritableStreamDefaultWriter(e){if(M(e,1,"WritableStreamDefaultWriter"),function(e,r){if(!er(e))throw new TypeError("".concat(r," is not a WritableStream."))}(e,"First parameter"),rr(e))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=e,e._writer=this;var r,t=e._state;if("writable"===t)!lr(e)&&e._backpressure?Wr(this):jr(this),Pr(this);else if("erroring"===t)kr(this,e._storedError),Pr(this);else if("closed"===t)jr(this),Pr(r=this),Or(r);else{var n=e._storedError;kr(this,n),Cr(this,n)}}return Object.defineProperty(WritableStreamDefaultWriter.prototype,"closed",{get:function(){return dr(this)?this._closedPromise:d(Tr("closed"))},enumerable:!1,configurable:!0}),Object.defineProperty(WritableStreamDefaultWriter.prototype,"desiredSize",{get:function(){if(!dr(this))throw Tr("desiredSize");if(void 0===this._ownerWritableStream)throw qr("desiredSize");return function(e){var r=e._ownerWritableStream,t=r._state;if("errored"===t||"erroring"===t)return null;if("closed"===t)return 0;return yr(r._writableStreamController)}(this)},enumerable:!1,configurable:!0}),Object.defineProperty(WritableStreamDefaultWriter.prototype,"ready",{get:function(){return dr(this)?this._readyPromise:d(Tr("ready"))},enumerable:!1,configurable:!0}),WritableStreamDefaultWriter.prototype.abort=function(e){return void 0===e&&(e=void 0),dr(this)?void 0===this._ownerWritableStream?d(qr("abort")):function(e,r){return tr(e._ownerWritableStream,r)}(this,e):d(Tr("abort"))},WritableStreamDefaultWriter.prototype.close=function(){if(!dr(this))return d(Tr("close"));var e=this._ownerWritableStream;return void 0===e?d(qr("close")):lr(e)?d(new TypeError("Cannot close an already-closing stream")):nr(this._ownerWritableStream)},WritableStreamDefaultWriter.prototype.releaseLock=function(){if(!dr(this))throw Tr("releaseLock");void 0!==this._ownerWritableStream&&function(e){var r=e._ownerWritableStream,t=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");fr(e,t),function(e,r){"pending"===e._closedPromiseState?Er(e,r):function(e,r){Cr(e,r)}(e,r)}(e,t),r._writer=void 0,e._ownerWritableStream=void 0}(this)},WritableStreamDefaultWriter.prototype.write=function(e){return void 0===e&&(e=void 0),dr(this)?void 0===this._ownerWritableStream?d(qr("write to")):function(e,r){var t=e._ownerWritableStream,n=t._writableStreamController,o=function(e,r){try{return e._strategySizeAlgorithm(r)}catch(r){return mr(e,r),1}}(n,r);if(t!==e._ownerWritableStream)return d(qr("write to"));var a=t._state;if("errored"===a)return d(t._storedError);if(lr(t)||"closed"===a)return d(new TypeError("The stream is closing or closed and cannot be written to"));if("erroring"===a)return d(t._storedError);var i=function(e){return s((function(r,t){var n={_resolve:r,_reject:t};e._writeRequests.push(n)}))}(t);return function(e,r,t){try{ce(e,r,t)}catch(r){return void mr(e,r)}var n=e._controlledWritableStream;if(!lr(n)&&"writable"===n._state){sr(n,gr(e))}vr(e)}(n,r,o),i}(this,e):d(Tr("write"))},WritableStreamDefaultWriter}();function dr(e){return!!t(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_ownerWritableStream")&&e instanceof cr)}function fr(e,r){"pending"===e._readyPromiseState?Br(e,r):function(e,r){kr(e,r)}(e,r)}Object.defineProperties(cr.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),o(cr.prototype.abort,"abort"),o(cr.prototype.close,"close"),o(cr.prototype.releaseLock,"releaseLock"),o(cr.prototype.write,"write"),"symbol"==typeof e.toStringTag&&Object.defineProperty(cr.prototype,e.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});var br={},pr=function(){function WritableStreamDefaultController(){throw new TypeError("Illegal constructor")}return Object.defineProperty(WritableStreamDefaultController.prototype,"abortReason",{get:function(){if(!hr(this))throw Rr("abortReason");return this._abortReason},enumerable:!1,configurable:!0}),Object.defineProperty(WritableStreamDefaultController.prototype,"signal",{get:function(){if(!hr(this))throw Rr("signal");if(void 0===this._abortController)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal},enumerable:!1,configurable:!0}),WritableStreamDefaultController.prototype.error=function(e){if(void 0===e&&(e=void 0),!hr(this))throw Rr("error");"writable"===this._controlledWritableStream._state&&wr(this,e)},WritableStreamDefaultController.prototype[S]=function(e){var r=this._abortAlgorithm(e);return _r(this),r},WritableStreamDefaultController.prototype[R]=function(){de(this)},WritableStreamDefaultController}();function hr(e){return!!t(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledWritableStream")&&e instanceof pr)}function _r(e){e._writeAlgorithm=void 0,e._closeAlgorithm=void 0,e._abortAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function yr(e){return e._strategyHWM-e._queueTotalSize}function vr(e){var r=e._controlledWritableStream;if(e._started&&void 0===r._inFlightWriteRequest)if("erroring"!==r._state){if(0!==e._queue.length){var t=e._queue.peek().value;t===br?function(e){var r=e._controlledWritableStream;(function(e){e._inFlightCloseRequest=e._closeRequest,e._closeRequest=void 0})(r),se(e);var t=e._closeAlgorithm();_r(e),b(t,(function(){return function(e){e._inFlightCloseRequest._resolve(void 0),e._inFlightCloseRequest=void 0,"erroring"===e._state&&(e._storedError=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._resolve(),e._pendingAbortRequest=void 0)),e._state="closed";var r=e._writer;void 0!==r&&Or(r)}(r),null}),(function(e){return function(e,r){e._inFlightCloseRequest._reject(r),e._inFlightCloseRequest=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._reject(r),e._pendingAbortRequest=void 0),or(e,r)}(r,e),null}))}(e):function(e,r){var t=e._controlledWritableStream;(function(e){e._inFlightWriteRequest=e._writeRequests.shift()})(t),b(e._writeAlgorithm(r),(function(){!function(e){e._inFlightWriteRequest._resolve(void 0),e._inFlightWriteRequest=void 0}(t);var r=t._state;if(se(e),!lr(t)&&"writable"===r){var n=gr(e);sr(t,n)}return vr(e),null}),(function(r){return"writable"===t._state&&_r(e),function(e,r){e._inFlightWriteRequest._reject(r),e._inFlightWriteRequest=void 0,or(e,r)}(t,r),null}))}(e,t)}}else ir(r)}function mr(e,r){"writable"===e._controlledWritableStream._state&&wr(e,r)}function gr(e){return yr(e)<=0}function wr(e,r){var t=e._controlledWritableStream;_r(e),ar(t,r)}function Sr(e){return new TypeError("WritableStream.prototype.".concat(e," can only be used on a WritableStream"))}function Rr(e){return new TypeError("WritableStreamDefaultController.prototype.".concat(e," can only be used on a WritableStreamDefaultController"))}function Tr(e){return new TypeError("WritableStreamDefaultWriter.prototype.".concat(e," can only be used on a WritableStreamDefaultWriter"))}function qr(e){return new TypeError("Cannot "+e+" a stream using a released writer")}function Pr(e){e._closedPromise=s((function(r,t){e._closedPromise_resolve=r,e._closedPromise_reject=t,e._closedPromiseState="pending"}))}function Cr(e,r){Pr(e),Er(e,r)}function Er(e,r){void 0!==e._closedPromise_reject&&(y(e._closedPromise),e._closedPromise_reject(r),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="rejected")}function Or(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="resolved")}function Wr(e){e._readyPromise=s((function(r,t){e._readyPromise_resolve=r,e._readyPromise_reject=t})),e._readyPromiseState="pending"}function kr(e,r){Wr(e),Br(e,r)}function jr(e){Wr(e),Ar(e)}function Br(e,r){void 0!==e._readyPromise_reject&&(y(e._readyPromise),e._readyPromise_reject(r),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="rejected")}function Ar(e){void 0!==e._readyPromise_resolve&&(e._readyPromise_resolve(void 0),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="fulfilled")}Object.defineProperties(pr.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),"symbol"==typeof e.toStringTag&&Object.defineProperty(pr.prototype,e.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});var zr="undefined"!=typeof DOMException?DOMException:void 0;var Lr,Fr=function(e){if("function"!=typeof e&&"object"!=typeof e)return!1;try{return new e,!0}catch(e){return!1}}(zr)?zr:((Lr=function(e,r){this.message=e||"",this.name=r||"Error",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}).prototype=Object.create(Error.prototype),Object.defineProperty(Lr.prototype,"constructor",{value:Lr,writable:!0,configurable:!0}),Lr);function Ir(e,r,t,n,o,a){var i=e.getReader(),l=r.getWriter();nt(e)&&(e._disturbed=!0);var u,h,m,g=!1,w=!1,S="readable",R="writable",T=!1,q=!1,P=s((function(e){m=e})),C=Promise.resolve(void 0);return s((function(E,O){var W;function k(){if(!g){var e=s((function(e,r){!function t(n){n?e():f(function(){if(g)return c(!0);return f(l.ready,(function(){return f(i.read(),(function(e){return!!e.done||(y(C=l.write(e.value)),!1)}))}))}(),t,r)}(!1)}));y(e)}}function j(){return S="closed",t?F():L((function(){return er(r)&&(T=lr(r),R=r._state),T||"closed"===R?c(void 0):"erroring"===R||"errored"===R?d(h):(T=!0,l.close())}),!1,void 0),null}function B(e){return g||(S="errored",u=e,n?F(!0,e):L((function(){return l.abort(e)}),!0,e)),null}function A(e){return w||(R="errored",h=e,o?F(!0,e):L((function(){return i.cancel(e)}),!0,e)),null}if(void 0!==a&&(W=function(){var e=void 0!==a.reason?a.reason:new Fr("Aborted","AbortError"),r=[];n||r.push((function(){return"writable"===R?l.abort(e):c(void 0)})),o||r.push((function(){return"readable"===S?i.cancel(e):c(void 0)})),L((function(){return Promise.all(r.map((function(e){return e()})))}),!0,e)},a.aborted?W():a.addEventListener("abort",W)),nt(e)&&(S=e._state,u=e._storedError),er(r)&&(R=r._state,h=r._storedError,T=lr(r)),nt(e)&&er(r)&&(q=!0,m()),"errored"===S)B(u);else if("erroring"===R||"errored"===R)A(h);else if("closed"===S)j();else if(T||"closed"===R){var z=new TypeError("the destination writable stream closed before all data could be piped to it");o?F(!0,z):L((function(){return i.cancel(z)}),!0,z)}function L(e,r,t){function n(){var e;return"writable"!==R||T?o():p(c(function r(){if(e!==C)return e=C,_(C,r,r)}()),o),null}function o(){return e?b(e(),(function(){return I(r,t)}),(function(e){return I(!0,e)})):I(r,t),null}g||(g=!0,q?n():p(P,n))}function F(e,r){L(void 0,e,r)}function I(e,r){return w=!0,l.releaseLock(),i.releaseLock(),void 0!==a&&a.removeEventListener("abort",W),e?O(r):E(void 0),null}g||(b(i.closed,j,B),b(l.closed,(function(){return w||(R="closed"),null}),A)),q?k():v((function(){q=!0,m(),k()}))}))}function Dr(e,r){return function(e){try{return e.getReader({mode:"byob"}).releaseLock(),!0}catch(e){return!1}}(e)?function(e){var r,t,n,o,a,i=e.getReader(),l=!1,u=!1,d=!1,f=!1,p=!1,_=!1,y=s((function(e){a=e}));function v(e){h(e.closed,(function(r){return e!==i||(n.error(r),o.error(r),p&&_||a(void 0)),null}))}function m(){l&&(i.releaseLock(),v(i=e.getReader()),l=!1),b(i.read(),(function(e){var r,t;if(d=!1,f=!1,e.done)return p||n.close(),_||o.close(),null===(r=n.byobRequest)||void 0===r||r.respond(0),null===(t=o.byobRequest)||void 0===t||t.respond(0),p&&_||a(void 0),null;var l=e.value,s=l,c=l;if(!p&&!_)try{c=ue(l)}catch(e){return n.error(e),o.error(e),a(i.cancel(e)),null}return p||n.enqueue(s),_||o.enqueue(c),u=!1,d?w():f&&S(),null}),(function(){return u=!1,null}))}function g(r,t){l||(i.releaseLock(),v(i=e.getReader({mode:"byob"})),l=!0);var s=t?o:n,c=t?n:o;b(i.read(r),(function(e){var r;d=!1,f=!1;var n=t?_:p,o=t?p:_;if(e.done){n||s.close(),o||c.close();var l=e.value;return void 0!==l&&(n||s.byobRequest.respondWithNewView(l),o||null===(r=c.byobRequest)||void 0===r||r.respond(0)),n&&o||a(void 0),null}var b=e.value;if(o)n||s.byobRequest.respondWithNewView(b);else{var h=void 0;try{h=ue(b)}catch(e){return s.error(e),c.error(e),a(i.cancel(e)),null}n||s.byobRequest.respondWithNewView(b),c.enqueue(h)}return u=!1,d?w():f&&S(),null}),(function(){return u=!1,null}))}function w(){if(u)return d=!0,c(void 0);u=!0;var e=n.byobRequest;return null===e?m():g(e.view,!1),c(void 0)}function S(){if(u)return f=!0,c(void 0);u=!0;var e=o.byobRequest;return null===e?m():g(e.view,!0),c(void 0)}function R(e){if(p=!0,r=e,_){var n=[r,t],o=i.cancel(n);a(o)}return y}function T(e){if(_=!0,t=e,p){var n=[r,t],o=i.cancel(n);a(o)}return y}var q=new tt({type:"bytes",start:function(e){n=e},pull:w,cancel:R}),P=new tt({type:"bytes",start:function(e){o=e},pull:S,cancel:T});return v(i),[q,P]}(e):function(e,r){var t,n,o,a,i,l=e.getReader(),u=!1,d=!1,f=!1,p=!1,_=s((function(e){i=e}));function y(){return u?(d=!0,c(void 0)):(u=!0,b(l.read(),(function(e){if(d=!1,e.done)return f||o.close(),p||a.close(),f&&p||i(void 0),null;var r=e.value,t=r,n=r;return f||o.enqueue(t),p||a.enqueue(n),u=!1,d&&y(),null}),(function(){return u=!1,null})),c(void 0))}function v(e){if(f=!0,t=e,p){var r=[t,n],o=l.cancel(r);i(o)}return _}function m(e){if(p=!0,n=e,f){var r=[t,n],o=l.cancel(r);i(o)}return _}var g=new tt({start:function(e){o=e},pull:y,cancel:v}),w=new tt({start:function(e){a=e},pull:y,cancel:m});return h(l.closed,(function(e){return o.error(e),a.error(e),f&&p||i(void 0),null})),[g,w]}(e)}var Mr=function(){function ReadableStreamDefaultController(){throw new TypeError("Illegal constructor")}return Object.defineProperty(ReadableStreamDefaultController.prototype,"desiredSize",{get:function(){if(!Qr(this))throw Gr("desiredSize");return xr(this)},enumerable:!1,configurable:!0}),ReadableStreamDefaultController.prototype.close=function(){if(!Qr(this))throw Gr("close");if(!Vr(this))throw new TypeError("The stream is not in a state that permits close");!function(e){if(!Vr(e))return;var r=e._controlledReadableStream;e._closeRequested=!0,0===e._queue.length&&(Nr(e),it(r))}(this)},ReadableStreamDefaultController.prototype.enqueue=function(e){if(void 0===e&&(e=void 0),!Qr(this))throw Gr("enqueue");if(!Vr(this))throw new TypeError("The stream is not in a state that permits enqueue");return function(e,r){if(!Vr(e))return;var t=e._controlledReadableStream;if(ot(t)&&J(t)>0)X(t,r,!1);else{var n=void 0;try{n=e._strategySizeAlgorithm(r)}catch(r){throw Hr(e,r),r}try{ce(e,r,n)}catch(r){throw Hr(e,r),r}}Yr(e)}(this,e)},ReadableStreamDefaultController.prototype.error=function(e){if(void 0===e&&(e=void 0),!Qr(this))throw Gr("error");Hr(this,e)},ReadableStreamDefaultController.prototype[T]=function(e){de(this);var r=this._cancelAlgorithm(e);return Nr(this),r},ReadableStreamDefaultController.prototype[q]=function(e){var r=this._controlledReadableStream;if(this._queue.length>0){var t=se(this);this._closeRequested&&0===this._queue.length?(Nr(this),it(r)):Yr(this),e._chunkSteps(t)}else G(r,e),Yr(this)},ReadableStreamDefaultController.prototype[P]=function(){},ReadableStreamDefaultController}();function Qr(e){return!!t(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableStream")&&e instanceof Mr)}function Yr(e){var r=function(e){var r=e._controlledReadableStream;if(!Vr(e))return!1;if(!e._started)return!1;if(ot(r)&&J(r)>0)return!0;if(xr(e)>0)return!0;return!1}(e);r&&(e._pulling?e._pullAgain=!0:(e._pulling=!0,b(e._pullAlgorithm(),(function(){return e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,Yr(e)),null}),(function(r){return Hr(e,r),null}))))}function Nr(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function Hr(e,r){var t=e._controlledReadableStream;"readable"===t._state&&(de(e),Nr(e),lt(t,r))}function xr(e){var r=e._controlledReadableStream._state;return"errored"===r?null:"closed"===r?0:e._strategyHWM-e._queueTotalSize}function Vr(e){return!e._closeRequested&&"readable"===e._controlledReadableStream._state}function Ur(e,r,t,n){var o,a,i,l=Object.create(Mr.prototype);o=void 0!==r.start?function(){return r.start(l)}:function(){},a=void 0!==r.pull?function(){return r.pull(l)}:function(){return c(void 0)},i=void 0!==r.cancel?function(e){return r.cancel(e)}:function(){return c(void 0)},function(e,r,t,n,o,a,i){r._controlledReadableStream=e,r._queue=void 0,r._queueTotalSize=void 0,de(r),r._started=!1,r._closeRequested=!1,r._pullAgain=!1,r._pulling=!1,r._strategySizeAlgorithm=i,r._strategyHWM=a,r._pullAlgorithm=n,r._cancelAlgorithm=o,e._readableStreamController=r,b(c(t()),(function(){return r._started=!0,Yr(r),null}),(function(e){return Hr(r,e),null}))}(e,l,o,a,i,t,n)}function Gr(e){return new TypeError("ReadableStreamDefaultController.prototype.".concat(e," can only be used on a ReadableStreamDefaultController"))}function Xr(e,r,t){return I(e,t),function(t){return g(e,r,[t])}}function Jr(e,r,t){return I(e,t),function(t){return g(e,r,[t])}}function Kr(e,r,t){return I(e,t),function(t){return m(e,r,[t])}}function Zr(e,r){if("bytes"!==(e="".concat(e)))throw new TypeError("".concat(r," '").concat(e,"' is not a valid enumeration value for ReadableStreamType"));return e}function $r(e,r){if("byob"!==(e="".concat(e)))throw new TypeError("".concat(r," '").concat(e,"' is not a valid enumeration value for ReadableStreamReaderMode"));return e}function et(e,r){F(e,r);var t=null==e?void 0:e.preventAbort,n=null==e?void 0:e.preventCancel,o=null==e?void 0:e.preventClose,a=null==e?void 0:e.signal;return void 0!==a&&function(e,r){if(!function(e){if("object"!=typeof e||null===e)return!1;try{return"boolean"==typeof e.aborted}catch(e){return!1}}(e))throw new TypeError("".concat(r," is not an AbortSignal."))}(a,"".concat(r," has member 'signal' that")),{preventAbort:Boolean(t),preventCancel:Boolean(n),preventClose:Boolean(o),signal:a}}function rt(e,r){F(e,r);var t=null==e?void 0:e.readable;Q(t,"readable","ReadableWritablePair"),function(e,r){if(!x(e))throw new TypeError("".concat(r," is not a ReadableStream."))}(t,"".concat(r," has member 'readable' that"));var n=null==e?void 0:e.writable;return Q(n,"writable","ReadableWritablePair"),function(e,r){if(!V(e))throw new TypeError("".concat(r," is not a WritableStream."))}(n,"".concat(r," has member 'writable' that")),{readable:t,writable:n}}Object.defineProperties(Mr.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),o(Mr.prototype.close,"close"),o(Mr.prototype.enqueue,"enqueue"),o(Mr.prototype.error,"error"),"symbol"==typeof e.toStringTag&&Object.defineProperty(Mr.prototype,e.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});var tt=function(){function ReadableStream(e,r){void 0===e&&(e={}),void 0===r&&(r={}),void 0===e?e=null:D(e,"First parameter");var t,n=Ve(r,"Second parameter"),o=function(e,r){F(e,r);var t=e,n=null==t?void 0:t.autoAllocateChunkSize,o=null==t?void 0:t.cancel,a=null==t?void 0:t.pull,i=null==t?void 0:t.start,l=null==t?void 0:t.type;return{autoAllocateChunkSize:void 0===n?void 0:H(n,"".concat(r," has member 'autoAllocateChunkSize' that")),cancel:void 0===o?void 0:Xr(o,t,"".concat(r," has member 'cancel' that")),pull:void 0===a?void 0:Jr(a,t,"".concat(r," has member 'pull' that")),start:void 0===i?void 0:Kr(i,t,"".concat(r," has member 'start' that")),type:void 0===l?void 0:Zr(l,"".concat(r," has member 'type' that"))}}(e,"First parameter");if((t=this)._state="readable",t._reader=void 0,t._storedError=void 0,t._disturbed=!1,"bytes"===o.type){if(void 0!==n.size)throw new RangeError("The strategy for a byte stream cannot have a size function");Ae(this,o,He(n,0))}else{var a=xe(n);Ur(this,o,He(n,1),a)}}return Object.defineProperty(ReadableStream.prototype,"locked",{get:function(){if(!nt(this))throw ut("locked");return ot(this)},enumerable:!1,configurable:!0}),ReadableStream.prototype.cancel=function(e){return void 0===e&&(e=void 0),nt(this)?ot(this)?d(new TypeError("Cannot cancel a stream that already has a reader")):at(this,e):d(ut("cancel"))},ReadableStream.prototype.getReader=function(e){if(void 0===e&&(e=void 0),!nt(this))throw ut("getReader");return void 0===function(e,r){F(e,r);var t=null==e?void 0:e.mode;return{mode:void 0===t?void 0:$r(t,"".concat(r," has member 'mode' that"))}}(e,"First parameter").mode?new Z(this):function(e){return new Me(e)}(this)},ReadableStream.prototype.pipeThrough=function(e,r){if(void 0===r&&(r={}),!x(this))throw ut("pipeThrough");M(e,1,"pipeThrough");var t=rt(e,"First parameter"),n=et(r,"Second parameter");if(this.locked)throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(t.writable.locked)throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");return y(Ir(this,t.writable,n.preventClose,n.preventAbort,n.preventCancel,n.signal)),t.readable},ReadableStream.prototype.pipeTo=function(e,r){if(void 0===r&&(r={}),!x(this))return d(ut("pipeTo"));if(void 0===e)return d("Parameter 1 is required in 'pipeTo'.");if(!V(e))return d(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));var t;try{t=et(r,"Second parameter")}catch(e){return d(e)}return this.locked?d(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):e.locked?d(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):Ir(this,e,t.preventClose,t.preventAbort,t.preventCancel,t.signal)},ReadableStream.prototype.tee=function(){if(!x(this))throw ut("tee");if(this.locked)throw new TypeError("Cannot tee a stream that already has a reader");return Dr(this)},ReadableStream.prototype.values=function(e){if(void 0===e&&(e=void 0),!x(this))throw ut("values");var r,t,n,o,a,i=function(e,r){F(e,r);var t=null==e?void 0:e.preventCancel;return{preventCancel:Boolean(t)}}(e,"First parameter");return r=this,t=i.preventCancel,n=r.getReader(),o=new te(n,t),(a=Object.create(ne))._asyncIteratorImpl=o,a},ReadableStream}();function nt(e){return!!t(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readableStreamController")&&e instanceof tt)}function ot(e){return void 0!==e._reader}function at(e,t){if(e._disturbed=!0,"closed"===e._state)return c(void 0);if("errored"===e._state)return d(e._storedError);it(e);var n=e._reader;if(void 0!==n&&Qe(n)){var o=n._readIntoRequests;n._readIntoRequests=new w,o.forEach((function(e){e._closeSteps(void 0)}))}return _(e._readableStreamController[T](t),r)}function it(e){e._state="closed";var r=e._reader;if(void 0!==r&&(A(r),$(r))){var t=r._readRequests;r._readRequests=new w,t.forEach((function(e){e._closeSteps()}))}}function lt(e,r){e._state="errored",e._storedError=r;var t=e._reader;void 0!==t&&(B(t,r),$(t)?ee(t,r):Ye(t,r))}function ut(e){return new TypeError("ReadableStream.prototype.".concat(e," can only be used on a ReadableStream"))}function st(e,r){F(e,r);var t=null==e?void 0:e.highWaterMark;return Q(t,"highWaterMark","QueuingStrategyInit"),{highWaterMark:Y(t)}}Object.defineProperties(tt.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),o(tt.prototype.cancel,"cancel"),o(tt.prototype.getReader,"getReader"),o(tt.prototype.pipeThrough,"pipeThrough"),o(tt.prototype.pipeTo,"pipeTo"),o(tt.prototype.tee,"tee"),o(tt.prototype.values,"values"),"symbol"==typeof e.toStringTag&&Object.defineProperty(tt.prototype,e.toStringTag,{value:"ReadableStream",configurable:!0}),"symbol"==typeof e.asyncIterator&&Object.defineProperty(tt.prototype,e.asyncIterator,{value:tt.prototype.values,writable:!0,configurable:!0});var ct=function(e){return e.byteLength};o(ct,"size");var dt=function(){function ByteLengthQueuingStrategy(e){M(e,1,"ByteLengthQueuingStrategy"),e=st(e,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=e.highWaterMark}return Object.defineProperty(ByteLengthQueuingStrategy.prototype,"highWaterMark",{get:function(){if(!bt(this))throw ft("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark},enumerable:!1,configurable:!0}),Object.defineProperty(ByteLengthQueuingStrategy.prototype,"size",{get:function(){if(!bt(this))throw ft("size");return ct},enumerable:!1,configurable:!0}),ByteLengthQueuingStrategy}();function ft(e){return new TypeError("ByteLengthQueuingStrategy.prototype.".concat(e," can only be used on a ByteLengthQueuingStrategy"))}function bt(e){return!!t(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_byteLengthQueuingStrategyHighWaterMark")&&e instanceof dt)}Object.defineProperties(dt.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof e.toStringTag&&Object.defineProperty(dt.prototype,e.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});var pt=function(){return 1};o(pt,"size");var ht=function(){function CountQueuingStrategy(e){M(e,1,"CountQueuingStrategy"),e=st(e,"First parameter"),this._countQueuingStrategyHighWaterMark=e.highWaterMark}return Object.defineProperty(CountQueuingStrategy.prototype,"highWaterMark",{get:function(){if(!yt(this))throw _t("highWaterMark");return this._countQueuingStrategyHighWaterMark},enumerable:!1,configurable:!0}),Object.defineProperty(CountQueuingStrategy.prototype,"size",{get:function(){if(!yt(this))throw _t("size");return pt},enumerable:!1,configurable:!0}),CountQueuingStrategy}();function _t(e){return new TypeError("CountQueuingStrategy.prototype.".concat(e," can only be used on a CountQueuingStrategy"))}function yt(e){return!!t(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_countQueuingStrategyHighWaterMark")&&e instanceof ht)}function vt(e,r,t){return I(e,t),function(t){return g(e,r,[t])}}function mt(e,r,t){return I(e,t),function(t){return m(e,r,[t])}}function gt(e,r,t){return I(e,t),function(t,n){return g(e,r,[t,n])}}Object.defineProperties(ht.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof e.toStringTag&&Object.defineProperty(ht.prototype,e.toStringTag,{value:"CountQueuingStrategy",configurable:!0});var wt=function(){function TransformStream(e,r,t){void 0===e&&(e={}),void 0===r&&(r={}),void 0===t&&(t={}),void 0===e&&(e=null);var n=Ve(r,"Second parameter"),o=Ve(t,"Third parameter"),a=function(e,r){F(e,r);var t=null==e?void 0:e.flush,n=null==e?void 0:e.readableType,o=null==e?void 0:e.start,a=null==e?void 0:e.transform,i=null==e?void 0:e.writableType;return{flush:void 0===t?void 0:vt(t,e,"".concat(r," has member 'flush' that")),readableType:n,start:void 0===o?void 0:mt(o,e,"".concat(r," has member 'start' that")),transform:void 0===a?void 0:gt(a,e,"".concat(r," has member 'transform' that")),writableType:i}}(e,"First parameter");if(void 0!==a.readableType)throw new RangeError("Invalid readableType specified");if(void 0!==a.writableType)throw new RangeError("Invalid writableType specified");var i,l=He(o,0),u=xe(o),f=He(n,1),b=xe(n);!function(e,r,t,n,o,a){function i(){return r}function l(r){return function(e,r){var t=e._transformStreamController;if(e._backpressure){return _(e._backpressureChangePromise,(function(){if("erroring"===(er(e._writable)?e._writable._state:e._writableState))throw er(e._writable)?e._writable._storedError:e._writableStoredError;return Wt(t,r)}))}return Wt(t,r)}(e,r)}function u(r){return function(e,r){return Rt(e,r),c(void 0)}(e,r)}function s(){return function(e){var r=e._transformStreamController,t=r._flushAlgorithm();return Et(r),_(t,(function(){if("errored"===e._readableState)throw e._readableStoredError;Bt(e)&&At(e)}),(function(r){throw Rt(e,r),e._readableStoredError}))}(e)}function d(){return function(e){return qt(e,!1),e._backpressureChangePromise}(e)}function f(r){return Tt(e,r),c(void 0)}e._writableState="writable",e._writableStoredError=void 0,e._writableHasInFlightOperation=!1,e._writableStarted=!1,e._writable=function(e,r,t,n,o,a,i){return new $e({start:function(t){e._writableController=t;try{var n=t.signal;void 0!==n&&n.addEventListener("abort",(function(){"writable"===e._writableState&&(e._writableState="erroring",n.reason&&(e._writableStoredError=n.reason))}))}catch(e){}return _(r(),(function(){return e._writableStarted=!0,Mt(e),null}),(function(r){throw e._writableStarted=!0,Ft(e,r),r}))},write:function(r){return function(e){e._writableHasInFlightOperation=!0}(e),_(t(r),(function(){return function(e){e._writableHasInFlightOperation=!1}(e),Mt(e),null}),(function(r){throw function(e,r){e._writableHasInFlightOperation=!1,Ft(e,r)}(e,r),r}))},close:function(){return function(e){e._writableHasInFlightOperation=!0}(e),_(n(),(function(){return function(e){e._writableHasInFlightOperation=!1,"erroring"===e._writableState&&(e._writableStoredError=void 0);e._writableState="closed"}(e),null}),(function(r){throw function(e,r){e._writableHasInFlightOperation=!1,e._writableState,Ft(e,r)}(e,r),r}))},abort:function(r){return e._writableState="errored",e._writableStoredError=r,o(r)}},{highWaterMark:a,size:i})}(e,i,l,s,u,t,n),e._readableState="readable",e._readableStoredError=void 0,e._readableCloseRequested=!1,e._readablePulling=!1,e._readable=function(e,r,t,n,o,a){return new tt({start:function(t){return e._readableController=t,r().catch((function(r){zt(e,r)}))},pull:function(){return e._readablePulling=!0,t().catch((function(r){zt(e,r)}))},cancel:function(r){return e._readableState="closed",n(r)}},{highWaterMark:o,size:a})}(e,i,d,f,o,a),e._backpressure=void 0,e._backpressureChangePromise=void 0,e._backpressureChangePromise_resolve=void 0,qt(e,!0),e._transformStreamController=void 0}(this,s((function(e){i=e})),f,b,l,u),function(e,r){var t,n,o=Object.create(Pt.prototype);t=void 0!==r.transform?function(e){return r.transform(e,o)}:function(e){try{return Ot(o,e),c(void 0)}catch(e){return d(e)}};n=void 0!==r.flush?function(){return r.flush(o)}:function(){return c(void 0)};!function(e,r,t,n){r._controlledTransformStream=e,e._transformStreamController=r,r._transformAlgorithm=t,r._flushAlgorithm=n}(e,o,t,n)}(this,a),void 0!==a.start?i(a.start(this._transformStreamController)):i(void 0)}return Object.defineProperty(TransformStream.prototype,"readable",{get:function(){if(!St(this))throw jt("readable");return this._readable},enumerable:!1,configurable:!0}),Object.defineProperty(TransformStream.prototype,"writable",{get:function(){if(!St(this))throw jt("writable");return this._writable},enumerable:!1,configurable:!0}),TransformStream}();function St(e){return!!t(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_transformStreamController")&&e instanceof wt)}function Rt(e,r){zt(e,r),Tt(e,r)}function Tt(e,r){Et(e._transformStreamController),function(e,r){e._writableController.error(r),"writable"===e._writableState&&It(e,r)}(e,r),e._backpressure&&qt(e,!1)}function qt(e,r){void 0!==e._backpressureChangePromise&&e._backpressureChangePromise_resolve(),e._backpressureChangePromise=s((function(r){e._backpressureChangePromise_resolve=r})),e._backpressure=r}Object.defineProperties(wt.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),"symbol"==typeof e.toStringTag&&Object.defineProperty(wt.prototype,e.toStringTag,{value:"TransformStream",configurable:!0});var Pt=function(){function TransformStreamDefaultController(){throw new TypeError("Illegal constructor")}return Object.defineProperty(TransformStreamDefaultController.prototype,"desiredSize",{get:function(){if(!Ct(this))throw kt("desiredSize");return Lt(this._controlledTransformStream)},enumerable:!1,configurable:!0}),TransformStreamDefaultController.prototype.enqueue=function(e){if(void 0===e&&(e=void 0),!Ct(this))throw kt("enqueue");Ot(this,e)},TransformStreamDefaultController.prototype.error=function(e){if(void 0===e&&(e=void 0),!Ct(this))throw kt("error");var r;r=e,Rt(this._controlledTransformStream,r)},TransformStreamDefaultController.prototype.terminate=function(){if(!Ct(this))throw kt("terminate");!function(e){var r=e._controlledTransformStream;Bt(r)&&At(r);var t=new TypeError("TransformStream terminated");Tt(r,t)}(this)},TransformStreamDefaultController}();function Ct(e){return!!t(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledTransformStream")&&e instanceof Pt)}function Et(e){e._transformAlgorithm=void 0,e._flushAlgorithm=void 0}function Ot(e,r){var t=e._controlledTransformStream;if(!Bt(t))throw new TypeError("Readable side is not in a state that permits enqueue");try{!function(e,r){e._readablePulling=!1;try{e._readableController.enqueue(r)}catch(r){throw zt(e,r),r}}(t,r)}catch(e){throw Tt(t,e),t._readableStoredError}var n=function(e){return!function(e){if(!Bt(e))return!1;if(e._readablePulling)return!0;if(Lt(e)>0)return!0;return!1}(e)}(t);n!==t._backpressure&&qt(t,!0)}function Wt(e,r){return _(e._transformAlgorithm(r),void 0,(function(r){throw Rt(e._controlledTransformStream,r),r}))}function kt(e){return new TypeError("TransformStreamDefaultController.prototype.".concat(e," can only be used on a TransformStreamDefaultController"))}function jt(e){return new TypeError("TransformStream.prototype.".concat(e," can only be used on a TransformStream"))}function Bt(e){return!e._readableCloseRequested&&"readable"===e._readableState}function At(e){e._readableState="closed",e._readableCloseRequested=!0,e._readableController.close()}function zt(e,r){"readable"===e._readableState&&(e._readableState="errored",e._readableStoredError=r),e._readableController.error(r)}function Lt(e){return e._readableController.desiredSize}function Ft(e,r){"writable"!==e._writableState?Dt(e):It(e,r)}function It(e,r){e._writableState="erroring",e._writableStoredError=r,!function(e){return e._writableHasInFlightOperation}(e)&&e._writableStarted&&Dt(e)}function Dt(e){e._writableState="errored"}function Mt(e){"erroring"===e._writableState&&Dt(e)}Object.defineProperties(Pt.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),o(Pt.prototype.enqueue,"enqueue"),o(Pt.prototype.error,"error"),o(Pt.prototype.terminate,"terminate"),"symbol"==typeof e.toStringTag&&Object.defineProperty(Pt.prototype,e.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});export{dt as ByteLengthQueuingStrategy,ht as CountQueuingStrategy,be as ReadableByteStreamController,tt as ReadableStream,Me as ReadableStreamBYOBReader,fe as ReadableStreamBYOBRequest,Mr as ReadableStreamDefaultController,Z as ReadableStreamDefaultReader,wt as TransformStream,Pt as TransformStreamDefaultController,$e as WritableStream,pr as WritableStreamDefaultController,cr as WritableStreamDefaultWriter}; diff --git a/backend/node_modules/formdata-node/node_modules/web-streams-polyfill/dist/ponyfill.js b/backend/node_modules/formdata-node/node_modules/web-streams-polyfill/dist/ponyfill.js new file mode 100644 index 0000000000000000000000000000000000000000..32faf5ec09c60c6d8a72b245991ffc90764bb86c --- /dev/null +++ b/backend/node_modules/formdata-node/node_modules/web-streams-polyfill/dist/ponyfill.js @@ -0,0 +1,8 @@ +/** + * @license + * web-streams-polyfill v4.0.0-beta.3 + * Copyright 2021 Mattias Buelens, Diwank Singh Tomer and other contributors. + * This code is released under the MIT license. + * SPDX-License-Identifier: MIT + */ +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).WebStreamsPolyfill={})}(this,(function(e){"use strict";const t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol:e=>`Symbol(${e})`;function r(){}function o(e){return"object"==typeof e&&null!==e||"function"==typeof e}const n=r;function a(e,t){try{Object.defineProperty(e,"name",{value:t,configurable:!0})}catch(e){}}const i=Promise,l=Promise.prototype.then,s=Promise.resolve.bind(i),u=Promise.reject.bind(i);function c(e){return new i(e)}function d(e){return s(e)}function f(e){return u(e)}function b(e,t,r){return l.call(e,t,r)}function h(e,t,r){b(b(e,t,r),void 0,n)}function _(e,t){h(e,t)}function p(e,t){h(e,void 0,t)}function m(e,t,r){return b(e,t,r)}function y(e){b(e,void 0,n)}let g=e=>{if("function"==typeof queueMicrotask)g=queueMicrotask;else{const e=d(void 0);g=t=>b(e,t)}return g(e)};function S(e,t,r){if("function"!=typeof e)throw new TypeError("Argument is not a function");return Function.prototype.apply.call(e,t,r)}function w(e,t,r){try{return d(S(e,t,r))}catch(e){return f(e)}}class v{constructor(){this._cursor=0,this._size=0,this._front={_elements:[],_next:void 0},this._back=this._front,this._cursor=0,this._size=0}get length(){return this._size}push(e){const t=this._back;let r=t;16383===t._elements.length&&(r={_elements:[],_next:void 0}),t._elements.push(e),r!==t&&(this._back=r,t._next=r),++this._size}shift(){const e=this._front;let t=e;const r=this._cursor;let o=r+1;const n=e._elements,a=n[r];return 16384===o&&(t=e._next,o=0),--this._size,this._cursor=o,e!==t&&(this._front=t),n[r]=void 0,a}forEach(e){let t=this._cursor,r=this._front,o=r._elements;for(;!(t===o.length&&void 0===r._next||t===o.length&&(r=r._next,o=r._elements,t=0,0===o.length));)e(o[t]),++t}peek(){const e=this._front,t=this._cursor;return e._elements[t]}}const R=t("[[AbortSteps]]"),T=t("[[ErrorSteps]]"),q=t("[[CancelSteps]]"),C=t("[[PullSteps]]"),P=t("[[ReleaseSteps]]");function E(e,t){e._ownerReadableStream=t,t._reader=e,"readable"===t._state?B(e):"closed"===t._state?function(e){B(e),z(e)}(e):A(e,t._storedError)}function W(e,t){return Xt(e._ownerReadableStream,t)}function O(e){const t=e._ownerReadableStream;"readable"===t._state?j(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):function(e,t){A(e,t)}(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),t._readableStreamController[P](),t._reader=void 0,e._ownerReadableStream=void 0}function k(e){return new TypeError("Cannot "+e+" a stream using a released reader")}function B(e){e._closedPromise=c(((t,r)=>{e._closedPromise_resolve=t,e._closedPromise_reject=r}))}function A(e,t){B(e),j(e,t)}function j(e,t){void 0!==e._closedPromise_reject&&(y(e._closedPromise),e._closedPromise_reject(t),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}function z(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}const L=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},F=Math.trunc||function(e){return e<0?Math.ceil(e):Math.floor(e)};function D(e,t){if(void 0!==e&&("object"!=typeof(r=e)&&"function"!=typeof r))throw new TypeError(`${t} is not an object.`);var r}function I(e,t){if("function"!=typeof e)throw new TypeError(`${t} is not a function.`)}function $(e,t){if(!function(e){return"object"==typeof e&&null!==e||"function"==typeof e}(e))throw new TypeError(`${t} is not an object.`)}function M(e,t,r){if(void 0===e)throw new TypeError(`Parameter ${t} is required in '${r}'.`)}function Y(e,t,r){if(void 0===e)throw new TypeError(`${t} is required in '${r}'.`)}function Q(e){return Number(e)}function N(e){return 0===e?0:e}function x(e,t){const r=Number.MAX_SAFE_INTEGER;let o=Number(e);if(o=N(o),!L(o))throw new TypeError(`${t} is not a finite number`);if(o=function(e){return N(F(e))}(o),o<0||o>r)throw new TypeError(`${t} is outside the accepted range of 0 to ${r}, inclusive`);return L(o)&&0!==o?o:0}function H(e){if(!o(e))return!1;if("function"!=typeof e.getReader)return!1;try{return"boolean"==typeof e.locked}catch(e){return!1}}function V(e){if(!o(e))return!1;if("function"!=typeof e.getWriter)return!1;try{return"boolean"==typeof e.locked}catch(e){return!1}}function U(e,t){if(!Ut(e))throw new TypeError(`${t} is not a ReadableStream.`)}function G(e,t){e._reader._readRequests.push(t)}function X(e,t,r){const o=e._reader._readRequests.shift();r?o._closeSteps():o._chunkSteps(t)}function J(e){return e._reader._readRequests.length}function K(e){const t=e._reader;return void 0!==t&&!!Z(t)}class ReadableStreamDefaultReader{constructor(e){if(M(e,1,"ReadableStreamDefaultReader"),U(e,"First parameter"),Gt(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");E(this,e),this._readRequests=new v}get closed(){return Z(this)?this._closedPromise:f(te("closed"))}cancel(e){return Z(this)?void 0===this._ownerReadableStream?f(k("cancel")):W(this,e):f(te("cancel"))}read(){if(!Z(this))return f(te("read"));if(void 0===this._ownerReadableStream)return f(k("read from"));let e,t;const r=c(((r,o)=>{e=r,t=o}));return function(e,t){const r=e._ownerReadableStream;r._disturbed=!0,"closed"===r._state?t._closeSteps():"errored"===r._state?t._errorSteps(r._storedError):r._readableStreamController[C](t)}(this,{_chunkSteps:t=>e({value:t,done:!1}),_closeSteps:()=>e({value:void 0,done:!0}),_errorSteps:e=>t(e)}),r}releaseLock(){if(!Z(this))throw te("releaseLock");void 0!==this._ownerReadableStream&&function(e){O(e);const t=new TypeError("Reader was released");ee(e,t)}(this)}}function Z(e){return!!o(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readRequests")&&e instanceof ReadableStreamDefaultReader)}function ee(e,t){const r=e._readRequests;e._readRequests=new v,r.forEach((e=>{e._errorSteps(t)}))}function te(e){return new TypeError(`ReadableStreamDefaultReader.prototype.${e} can only be used on a ReadableStreamDefaultReader`)}Object.defineProperties(ReadableStreamDefaultReader.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),a(ReadableStreamDefaultReader.prototype.cancel,"cancel"),a(ReadableStreamDefaultReader.prototype.read,"read"),a(ReadableStreamDefaultReader.prototype.releaseLock,"releaseLock"),"symbol"==typeof t.toStringTag&&Object.defineProperty(ReadableStreamDefaultReader.prototype,t.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0});class re{constructor(e,t){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=e,this._preventCancel=t}next(){const e=()=>this._nextSteps();return this._ongoingPromise=this._ongoingPromise?m(this._ongoingPromise,e,e):e(),this._ongoingPromise}return(e){const t=()=>this._returnSteps(e);return this._ongoingPromise?m(this._ongoingPromise,t,t):t()}_nextSteps(){if(this._isFinished)return Promise.resolve({value:void 0,done:!0});const e=this._reader;return void 0===e?f(k("iterate")):b(e.read(),(e=>{var t;return this._ongoingPromise=void 0,e.done&&(this._isFinished=!0,null===(t=this._reader)||void 0===t||t.releaseLock(),this._reader=void 0),e}),(e=>{var t;throw this._ongoingPromise=void 0,this._isFinished=!0,null===(t=this._reader)||void 0===t||t.releaseLock(),this._reader=void 0,e}))}_returnSteps(e){if(this._isFinished)return Promise.resolve({value:e,done:!0});this._isFinished=!0;const t=this._reader;if(void 0===t)return f(k("finish iterating"));if(this._reader=void 0,!this._preventCancel){const r=t.cancel(e);return t.releaseLock(),m(r,(()=>({value:e,done:!0})))}return t.releaseLock(),d({value:e,done:!0})}}const oe={next(){return ne(this)?this._asyncIteratorImpl.next():f(ae("next"))},return(e){return ne(this)?this._asyncIteratorImpl.return(e):f(ae("return"))}};function ne(e){if(!o(e))return!1;if(!Object.prototype.hasOwnProperty.call(e,"_asyncIteratorImpl"))return!1;try{return e._asyncIteratorImpl instanceof re}catch(e){return!1}}function ae(e){return new TypeError(`ReadableStreamAsyncIterator.${e} can only be used on a ReadableSteamAsyncIterator`)}"symbol"==typeof t.asyncIterator&&Object.defineProperty(oe,t.asyncIterator,{value(){return this},writable:!0,configurable:!0});const ie=Number.isNaN||function(e){return e!=e};function le(e,t,r,o,n){new Uint8Array(e).set(new Uint8Array(r,o,n),t)}function se(e){const t=function(e,t,r){if(e.slice)return e.slice(t,r);const o=r-t,n=new ArrayBuffer(o);return le(n,0,e,t,o),n}(e.buffer,e.byteOffset,e.byteOffset+e.byteLength);return new Uint8Array(t)}function ue(e){const t=e._queue.shift();return e._queueTotalSize-=t.size,e._queueTotalSize<0&&(e._queueTotalSize=0),t.value}function ce(e,t,r){if("number"!=typeof(o=r)||ie(o)||o<0||r===1/0)throw new RangeError("Size must be a finite, non-NaN, non-negative number.");var o;e._queue.push({value:t,size:r}),e._queueTotalSize+=r}function de(e){e._queue=new v,e._queueTotalSize=0}class ReadableStreamBYOBRequest{constructor(){throw new TypeError("Illegal constructor")}get view(){if(!be(this))throw Ae("view");return this._view}respond(e){if(!be(this))throw Ae("respond");if(M(e,1,"respond"),e=x(e,"First parameter"),void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");this._view.buffer,function(e,t){const r=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==t)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream")}else{if(0===t)throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");if(r.bytesFilled+t>r.byteLength)throw new RangeError("bytesWritten out of range")}r.buffer=r.buffer,Ce(e,t)}(this._associatedReadableByteStreamController,e)}respondWithNewView(e){if(!be(this))throw Ae("respondWithNewView");if(M(e,1,"respondWithNewView"),!ArrayBuffer.isView(e))throw new TypeError("You can only respond with array buffer views");if(void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");e.buffer,function(e,t){const r=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==t.byteLength)throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream")}else if(0===t.byteLength)throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");if(r.byteOffset+r.bytesFilled!==t.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(r.bufferByteLength!==t.buffer.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");if(r.bytesFilled+t.byteLength>r.byteLength)throw new RangeError("The region specified by view is larger than byobRequest");const o=t.byteLength;r.buffer=t.buffer,Ce(e,o)}(this._associatedReadableByteStreamController,e)}}Object.defineProperties(ReadableStreamBYOBRequest.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),a(ReadableStreamBYOBRequest.prototype.respond,"respond"),a(ReadableStreamBYOBRequest.prototype.respondWithNewView,"respondWithNewView"),"symbol"==typeof t.toStringTag&&Object.defineProperty(ReadableStreamBYOBRequest.prototype,t.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});class ReadableByteStreamController{constructor(){throw new TypeError("Illegal constructor")}get byobRequest(){if(!fe(this))throw je("byobRequest");return function(e){if(null===e._byobRequest&&e._pendingPullIntos.length>0){const t=e._pendingPullIntos.peek(),r=new Uint8Array(t.buffer,t.byteOffset+t.bytesFilled,t.byteLength-t.bytesFilled),o=Object.create(ReadableStreamBYOBRequest.prototype);!function(e,t,r){e._associatedReadableByteStreamController=t,e._view=r}(o,e,r),e._byobRequest=o}return e._byobRequest}(this)}get desiredSize(){if(!fe(this))throw je("desiredSize");return ke(this)}close(){if(!fe(this))throw je("close");if(this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");const e=this._controlledReadableByteStream._state;if("readable"!==e)throw new TypeError(`The stream (in ${e} state) is not in the readable state and cannot be closed`);!function(e){const t=e._controlledReadableByteStream;if(e._closeRequested||"readable"!==t._state)return;if(e._queueTotalSize>0)return void(e._closeRequested=!0);if(e._pendingPullIntos.length>0){if(e._pendingPullIntos.peek().bytesFilled>0){const t=new TypeError("Insufficient bytes to fill elements in the given buffer");throw We(e,t),t}}Ee(e),Jt(t)}(this)}enqueue(e){if(!fe(this))throw je("enqueue");if(M(e,1,"enqueue"),!ArrayBuffer.isView(e))throw new TypeError("chunk must be an array buffer view");if(0===e.byteLength)throw new TypeError("chunk must have non-zero byteLength");if(0===e.buffer.byteLength)throw new TypeError("chunk's buffer must have non-zero byteLength");if(this._closeRequested)throw new TypeError("stream is closed or draining");const t=this._controlledReadableByteStream._state;if("readable"!==t)throw new TypeError(`The stream (in ${t} state) is not in the readable state and cannot be enqueued to`);!function(e,t){const r=e._controlledReadableByteStream;if(e._closeRequested||"readable"!==r._state)return;const o=t.buffer,n=t.byteOffset,a=t.byteLength,i=o;if(e._pendingPullIntos.length>0){const t=e._pendingPullIntos.peek();t.buffer,0,Te(e),t.buffer=t.buffer,"none"===t.readerType&&Se(e,t)}if(K(r))if(function(e){const t=e._controlledReadableByteStream._reader;for(;t._readRequests.length>0;){if(0===e._queueTotalSize)return;Oe(e,t._readRequests.shift())}}(e),0===J(r))ye(e,i,n,a);else{e._pendingPullIntos.length>0&&Pe(e);X(r,new Uint8Array(i,n,a),!1)}else Fe(r)?(ye(e,i,n,a),qe(e)):ye(e,i,n,a);he(e)}(this,e)}error(e){if(!fe(this))throw je("error");We(this,e)}[q](e){_e(this),de(this);const t=this._cancelAlgorithm(e);return Ee(this),t}[C](e){const t=this._controlledReadableByteStream;if(this._queueTotalSize>0)return void Oe(this,e);const r=this._autoAllocateChunkSize;if(void 0!==r){let t;try{t=new ArrayBuffer(r)}catch(t){return void e._errorSteps(t)}const o={buffer:t,bufferByteLength:r,byteOffset:0,byteLength:r,bytesFilled:0,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(o)}G(t,e),he(this)}[P](){if(this._pendingPullIntos.length>0){const e=this._pendingPullIntos.peek();e.readerType="none",this._pendingPullIntos=new v,this._pendingPullIntos.push(e)}}}function fe(e){return!!o(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableByteStream")&&e instanceof ReadableByteStreamController)}function be(e){return!!o(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_associatedReadableByteStreamController")&&e instanceof ReadableStreamBYOBRequest)}function he(e){const t=function(e){const t=e._controlledReadableByteStream;if("readable"!==t._state)return!1;if(e._closeRequested)return!1;if(!e._started)return!1;if(K(t)&&J(t)>0)return!0;if(Fe(t)&&Le(t)>0)return!0;if(ke(e)>0)return!0;return!1}(e);if(!t)return;if(e._pulling)return void(e._pullAgain=!0);e._pulling=!0;h(e._pullAlgorithm(),(()=>(e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,he(e)),null)),(t=>(We(e,t),null)))}function _e(e){Te(e),e._pendingPullIntos=new v}function pe(e,t){let r=!1;"closed"===e._state&&(r=!0);const o=me(t);"default"===t.readerType?X(e,o,r):function(e,t,r){const o=e._reader._readIntoRequests.shift();r?o._closeSteps(t):o._chunkSteps(t)}(e,o,r)}function me(e){const t=e.bytesFilled,r=e.elementSize;return new e.viewConstructor(e.buffer,e.byteOffset,t/r)}function ye(e,t,r,o){e._queue.push({buffer:t,byteOffset:r,byteLength:o}),e._queueTotalSize+=o}function ge(e,t,r,o){let n;try{n=t.slice(r,r+o)}catch(t){throw We(e,t),t}ye(e,n,0,o)}function Se(e,t){t.bytesFilled>0&&ge(e,t.buffer,t.byteOffset,t.bytesFilled),Pe(e)}function we(e,t){const r=t.elementSize,o=t.bytesFilled-t.bytesFilled%r,n=Math.min(e._queueTotalSize,t.byteLength-t.bytesFilled),a=t.bytesFilled+n,i=a-a%r;let l=n,s=!1;i>o&&(l=i-t.bytesFilled,s=!0);const u=e._queue;for(;l>0;){const r=u.peek(),o=Math.min(l,r.byteLength),n=t.byteOffset+t.bytesFilled;le(t.buffer,n,r.buffer,r.byteOffset,o),r.byteLength===o?u.shift():(r.byteOffset+=o,r.byteLength-=o),e._queueTotalSize-=o,ve(e,o,t),l-=o}return s}function ve(e,t,r){r.bytesFilled+=t}function Re(e){0===e._queueTotalSize&&e._closeRequested?(Ee(e),Jt(e._controlledReadableByteStream)):he(e)}function Te(e){null!==e._byobRequest&&(e._byobRequest._associatedReadableByteStreamController=void 0,e._byobRequest._view=null,e._byobRequest=null)}function qe(e){for(;e._pendingPullIntos.length>0;){if(0===e._queueTotalSize)return;const t=e._pendingPullIntos.peek();we(e,t)&&(Pe(e),pe(e._controlledReadableByteStream,t))}}function Ce(e,t){const r=e._pendingPullIntos.peek();Te(e);"closed"===e._controlledReadableByteStream._state?function(e,t){"none"===t.readerType&&Pe(e);const r=e._controlledReadableByteStream;if(Fe(r))for(;Le(r)>0;)pe(r,Pe(e))}(e,r):function(e,t,r){if(ve(0,t,r),"none"===r.readerType)return Se(e,r),void qe(e);if(r.bytesFilled0){const t=r.byteOffset+r.bytesFilled;ge(e,r.buffer,t-o,o)}r.bytesFilled-=o,pe(e._controlledReadableByteStream,r),qe(e)}(e,t,r),he(e)}function Pe(e){return e._pendingPullIntos.shift()}function Ee(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0}function We(e,t){const r=e._controlledReadableByteStream;"readable"===r._state&&(_e(e),de(e),Ee(e),Kt(r,t))}function Oe(e,t){const r=e._queue.shift();e._queueTotalSize-=r.byteLength,Re(e);const o=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);t._chunkSteps(o)}function ke(e){const t=e._controlledReadableByteStream._state;return"errored"===t?null:"closed"===t?0:e._strategyHWM-e._queueTotalSize}function Be(e,t,r){const o=Object.create(ReadableByteStreamController.prototype);let n,a,i;n=void 0!==t.start?()=>t.start(o):()=>{},a=void 0!==t.pull?()=>t.pull(o):()=>d(void 0),i=void 0!==t.cancel?e=>t.cancel(e):()=>d(void 0);const l=t.autoAllocateChunkSize;if(0===l)throw new TypeError("autoAllocateChunkSize must be greater than 0");!function(e,t,r,o,n,a,i){t._controlledReadableByteStream=e,t._pullAgain=!1,t._pulling=!1,t._byobRequest=null,t._queue=t._queueTotalSize=void 0,de(t),t._closeRequested=!1,t._started=!1,t._strategyHWM=a,t._pullAlgorithm=o,t._cancelAlgorithm=n,t._autoAllocateChunkSize=i,t._pendingPullIntos=new v,e._readableStreamController=t,h(d(r()),(()=>(t._started=!0,he(t),null)),(e=>(We(t,e),null)))}(e,o,n,a,i,r,l)}function Ae(e){return new TypeError(`ReadableStreamBYOBRequest.prototype.${e} can only be used on a ReadableStreamBYOBRequest`)}function je(e){return new TypeError(`ReadableByteStreamController.prototype.${e} can only be used on a ReadableByteStreamController`)}function ze(e,t){e._reader._readIntoRequests.push(t)}function Le(e){return e._reader._readIntoRequests.length}function Fe(e){const t=e._reader;return void 0!==t&&!!De(t)}Object.defineProperties(ReadableByteStreamController.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),a(ReadableByteStreamController.prototype.close,"close"),a(ReadableByteStreamController.prototype.enqueue,"enqueue"),a(ReadableByteStreamController.prototype.error,"error"),"symbol"==typeof t.toStringTag&&Object.defineProperty(ReadableByteStreamController.prototype,t.toStringTag,{value:"ReadableByteStreamController",configurable:!0});class ReadableStreamBYOBReader{constructor(e){if(M(e,1,"ReadableStreamBYOBReader"),U(e,"First parameter"),Gt(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!fe(e._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");E(this,e),this._readIntoRequests=new v}get closed(){return De(this)?this._closedPromise:f($e("closed"))}cancel(e){return De(this)?void 0===this._ownerReadableStream?f(k("cancel")):W(this,e):f($e("cancel"))}read(e){if(!De(this))return f($e("read"));if(!ArrayBuffer.isView(e))return f(new TypeError("view must be an array buffer view"));if(0===e.byteLength)return f(new TypeError("view must have non-zero byteLength"));if(0===e.buffer.byteLength)return f(new TypeError("view's buffer must have non-zero byteLength"));if(e.buffer,void 0===this._ownerReadableStream)return f(k("read from"));let t,r;const o=c(((e,o)=>{t=e,r=o}));return function(e,t,r){const o=e._ownerReadableStream;o._disturbed=!0,"errored"===o._state?r._errorSteps(o._storedError):function(e,t,r){const o=e._controlledReadableByteStream;let n=1;t.constructor!==DataView&&(n=t.constructor.BYTES_PER_ELEMENT);const a=t.constructor,i=t.buffer,l={buffer:i,bufferByteLength:i.byteLength,byteOffset:t.byteOffset,byteLength:t.byteLength,bytesFilled:0,elementSize:n,viewConstructor:a,readerType:"byob"};if(e._pendingPullIntos.length>0)return e._pendingPullIntos.push(l),void ze(o,r);if("closed"!==o._state){if(e._queueTotalSize>0){if(we(e,l)){const t=me(l);return Re(e),void r._chunkSteps(t)}if(e._closeRequested){const t=new TypeError("Insufficient bytes to fill elements in the given buffer");return We(e,t),void r._errorSteps(t)}}e._pendingPullIntos.push(l),ze(o,r),he(e)}else{const e=new a(l.buffer,l.byteOffset,0);r._closeSteps(e)}}(o._readableStreamController,t,r)}(this,e,{_chunkSteps:e=>t({value:e,done:!1}),_closeSteps:e=>t({value:e,done:!0}),_errorSteps:e=>r(e)}),o}releaseLock(){if(!De(this))throw $e("releaseLock");void 0!==this._ownerReadableStream&&function(e){O(e);const t=new TypeError("Reader was released");Ie(e,t)}(this)}}function De(e){return!!o(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readIntoRequests")&&e instanceof ReadableStreamBYOBReader)}function Ie(e,t){const r=e._readIntoRequests;e._readIntoRequests=new v,r.forEach((e=>{e._errorSteps(t)}))}function $e(e){return new TypeError(`ReadableStreamBYOBReader.prototype.${e} can only be used on a ReadableStreamBYOBReader`)}function Me(e,t){const{highWaterMark:r}=e;if(void 0===r)return t;if(ie(r)||r<0)throw new RangeError("Invalid highWaterMark");return r}function Ye(e){const{size:t}=e;return t||(()=>1)}function Qe(e,t){D(e,t);const r=null==e?void 0:e.highWaterMark,o=null==e?void 0:e.size;return{highWaterMark:void 0===r?void 0:Q(r),size:void 0===o?void 0:Ne(o,`${t} has member 'size' that`)}}function Ne(e,t){return I(e,t),t=>Q(e(t))}function xe(e,t,r){return I(e,r),r=>w(e,t,[r])}function He(e,t,r){return I(e,r),()=>w(e,t,[])}function Ve(e,t,r){return I(e,r),r=>S(e,t,[r])}function Ue(e,t,r){return I(e,r),(r,o)=>w(e,t,[r,o])}Object.defineProperties(ReadableStreamBYOBReader.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),a(ReadableStreamBYOBReader.prototype.cancel,"cancel"),a(ReadableStreamBYOBReader.prototype.read,"read"),a(ReadableStreamBYOBReader.prototype.releaseLock,"releaseLock"),"symbol"==typeof t.toStringTag&&Object.defineProperty(ReadableStreamBYOBReader.prototype,t.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});const Ge="function"==typeof AbortController;class WritableStream{constructor(e={},t={}){void 0===e?e=null:$(e,"First parameter");const r=Qe(t,"Second parameter"),o=function(e,t){D(e,t);const r=null==e?void 0:e.abort,o=null==e?void 0:e.close,n=null==e?void 0:e.start,a=null==e?void 0:e.type,i=null==e?void 0:e.write;return{abort:void 0===r?void 0:xe(r,e,`${t} has member 'abort' that`),close:void 0===o?void 0:He(o,e,`${t} has member 'close' that`),start:void 0===n?void 0:Ve(n,e,`${t} has member 'start' that`),write:void 0===i?void 0:Ue(i,e,`${t} has member 'write' that`),type:a}}(e,"First parameter");var n;(n=this)._state="writable",n._storedError=void 0,n._writer=void 0,n._writableStreamController=void 0,n._writeRequests=new v,n._inFlightWriteRequest=void 0,n._closeRequest=void 0,n._inFlightCloseRequest=void 0,n._pendingAbortRequest=void 0,n._backpressure=!1;if(void 0!==o.type)throw new RangeError("Invalid type is specified");const a=Ye(r);!function(e,t,r,o){const n=Object.create(WritableStreamDefaultController.prototype);let a,i,l,s;a=void 0!==t.start?()=>t.start(n):()=>{};i=void 0!==t.write?e=>t.write(e,n):()=>d(void 0);l=void 0!==t.close?()=>t.close():()=>d(void 0);s=void 0!==t.abort?e=>t.abort(e):()=>d(void 0);!function(e,t,r,o,n,a,i,l){t._controlledWritableStream=e,e._writableStreamController=t,t._queue=void 0,t._queueTotalSize=void 0,de(t),t._abortReason=void 0,t._abortController=function(){if(Ge)return new AbortController}(),t._started=!1,t._strategySizeAlgorithm=l,t._strategyHWM=i,t._writeAlgorithm=o,t._closeAlgorithm=n,t._abortAlgorithm=a;const s=ht(t);at(e,s);const u=r();h(d(u),(()=>(t._started=!0,ft(t),null)),(r=>(t._started=!0,et(e,r),null)))}(e,n,a,i,l,s,r,o)}(this,o,Me(r,1),a)}get locked(){if(!Xe(this))throw pt("locked");return Je(this)}abort(e){return Xe(this)?Je(this)?f(new TypeError("Cannot abort a stream that already has a writer")):Ke(this,e):f(pt("abort"))}close(){return Xe(this)?Je(this)?f(new TypeError("Cannot close a stream that already has a writer")):ot(this)?f(new TypeError("Cannot close an already-closing stream")):Ze(this):f(pt("close"))}getWriter(){if(!Xe(this))throw pt("getWriter");return new WritableStreamDefaultWriter(this)}}function Xe(e){return!!o(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_writableStreamController")&&e instanceof WritableStream)}function Je(e){return void 0!==e._writer}function Ke(e,t){var r;if("closed"===e._state||"errored"===e._state)return d(void 0);e._writableStreamController._abortReason=t,null===(r=e._writableStreamController._abortController)||void 0===r||r.abort(t);const o=e._state;if("closed"===o||"errored"===o)return d(void 0);if(void 0!==e._pendingAbortRequest)return e._pendingAbortRequest._promise;let n=!1;"erroring"===o&&(n=!0,t=void 0);const a=c(((r,o)=>{e._pendingAbortRequest={_promise:void 0,_resolve:r,_reject:o,_reason:t,_wasAlreadyErroring:n}}));return e._pendingAbortRequest._promise=a,n||tt(e,t),a}function Ze(e){const t=e._state;if("closed"===t||"errored"===t)return f(new TypeError(`The stream (in ${t} state) is not in the writable state and cannot be closed`));const r=c(((t,r)=>{const o={_resolve:t,_reject:r};e._closeRequest=o})),o=e._writer;var n;return void 0!==o&&e._backpressure&&"writable"===t&&Et(o),ce(n=e._writableStreamController,st,0),ft(n),r}function et(e,t){"writable"!==e._state?rt(e):tt(e,t)}function tt(e,t){const r=e._writableStreamController;e._state="erroring",e._storedError=t;const o=e._writer;void 0!==o&<(o,t),!function(e){if(void 0===e._inFlightWriteRequest&&void 0===e._inFlightCloseRequest)return!1;return!0}(e)&&r._started&&rt(e)}function rt(e){e._state="errored",e._writableStreamController[T]();const t=e._storedError;if(e._writeRequests.forEach((e=>{e._reject(t)})),e._writeRequests=new v,void 0===e._pendingAbortRequest)return void nt(e);const r=e._pendingAbortRequest;if(e._pendingAbortRequest=void 0,r._wasAlreadyErroring)return r._reject(t),void nt(e);h(e._writableStreamController[R](r._reason),(()=>(r._resolve(),nt(e),null)),(t=>(r._reject(t),nt(e),null)))}function ot(e){return void 0!==e._closeRequest||void 0!==e._inFlightCloseRequest}function nt(e){void 0!==e._closeRequest&&(e._closeRequest._reject(e._storedError),e._closeRequest=void 0);const t=e._writer;void 0!==t&&vt(t,e._storedError)}function at(e,t){const r=e._writer;void 0!==r&&t!==e._backpressure&&(t?function(e){Tt(e)}(r):Et(r)),e._backpressure=t}Object.defineProperties(WritableStream.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),a(WritableStream.prototype.abort,"abort"),a(WritableStream.prototype.close,"close"),a(WritableStream.prototype.getWriter,"getWriter"),"symbol"==typeof t.toStringTag&&Object.defineProperty(WritableStream.prototype,t.toStringTag,{value:"WritableStream",configurable:!0});class WritableStreamDefaultWriter{constructor(e){if(M(e,1,"WritableStreamDefaultWriter"),function(e,t){if(!Xe(e))throw new TypeError(`${t} is not a WritableStream.`)}(e,"First parameter"),Je(e))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=e,e._writer=this;const t=e._state;if("writable"===t)!ot(e)&&e._backpressure?Tt(this):Ct(this),St(this);else if("erroring"===t)qt(this,e._storedError),St(this);else if("closed"===t)Ct(this),St(r=this),Rt(r);else{const t=e._storedError;qt(this,t),wt(this,t)}var r}get closed(){return it(this)?this._closedPromise:f(yt("closed"))}get desiredSize(){if(!it(this))throw yt("desiredSize");if(void 0===this._ownerWritableStream)throw gt("desiredSize");return function(e){const t=e._ownerWritableStream,r=t._state;if("errored"===r||"erroring"===r)return null;if("closed"===r)return 0;return dt(t._writableStreamController)}(this)}get ready(){return it(this)?this._readyPromise:f(yt("ready"))}abort(e){return it(this)?void 0===this._ownerWritableStream?f(gt("abort")):function(e,t){return Ke(e._ownerWritableStream,t)}(this,e):f(yt("abort"))}close(){if(!it(this))return f(yt("close"));const e=this._ownerWritableStream;return void 0===e?f(gt("close")):ot(e)?f(new TypeError("Cannot close an already-closing stream")):Ze(this._ownerWritableStream)}releaseLock(){if(!it(this))throw yt("releaseLock");void 0!==this._ownerWritableStream&&function(e){const t=e._ownerWritableStream,r=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");lt(e,r),function(e,t){"pending"===e._closedPromiseState?vt(e,t):function(e,t){wt(e,t)}(e,t)}(e,r),t._writer=void 0,e._ownerWritableStream=void 0}(this)}write(e){return it(this)?void 0===this._ownerWritableStream?f(gt("write to")):function(e,t){const r=e._ownerWritableStream,o=r._writableStreamController,n=function(e,t){try{return e._strategySizeAlgorithm(t)}catch(t){return bt(e,t),1}}(o,t);if(r!==e._ownerWritableStream)return f(gt("write to"));const a=r._state;if("errored"===a)return f(r._storedError);if(ot(r)||"closed"===a)return f(new TypeError("The stream is closing or closed and cannot be written to"));if("erroring"===a)return f(r._storedError);const i=function(e){return c(((t,r)=>{const o={_resolve:t,_reject:r};e._writeRequests.push(o)}))}(r);return function(e,t,r){try{ce(e,t,r)}catch(t){return void bt(e,t)}const o=e._controlledWritableStream;if(!ot(o)&&"writable"===o._state){at(o,ht(e))}ft(e)}(o,t,n),i}(this,e):f(yt("write"))}}function it(e){return!!o(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_ownerWritableStream")&&e instanceof WritableStreamDefaultWriter)}function lt(e,t){"pending"===e._readyPromiseState?Pt(e,t):function(e,t){qt(e,t)}(e,t)}Object.defineProperties(WritableStreamDefaultWriter.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),a(WritableStreamDefaultWriter.prototype.abort,"abort"),a(WritableStreamDefaultWriter.prototype.close,"close"),a(WritableStreamDefaultWriter.prototype.releaseLock,"releaseLock"),a(WritableStreamDefaultWriter.prototype.write,"write"),"symbol"==typeof t.toStringTag&&Object.defineProperty(WritableStreamDefaultWriter.prototype,t.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});const st={};class WritableStreamDefaultController{constructor(){throw new TypeError("Illegal constructor")}get abortReason(){if(!ut(this))throw mt("abortReason");return this._abortReason}get signal(){if(!ut(this))throw mt("signal");if(void 0===this._abortController)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal}error(e){if(!ut(this))throw mt("error");"writable"===this._controlledWritableStream._state&&_t(this,e)}[R](e){const t=this._abortAlgorithm(e);return ct(this),t}[T](){de(this)}}function ut(e){return!!o(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledWritableStream")&&e instanceof WritableStreamDefaultController)}function ct(e){e._writeAlgorithm=void 0,e._closeAlgorithm=void 0,e._abortAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function dt(e){return e._strategyHWM-e._queueTotalSize}function ft(e){const t=e._controlledWritableStream;if(!e._started)return;if(void 0!==t._inFlightWriteRequest)return;if("erroring"===t._state)return void rt(t);if(0===e._queue.length)return;const r=e._queue.peek().value;r===st?function(e){const t=e._controlledWritableStream;(function(e){e._inFlightCloseRequest=e._closeRequest,e._closeRequest=void 0})(t),ue(e);const r=e._closeAlgorithm();ct(e),h(r,(()=>(function(e){e._inFlightCloseRequest._resolve(void 0),e._inFlightCloseRequest=void 0,"erroring"===e._state&&(e._storedError=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._resolve(),e._pendingAbortRequest=void 0)),e._state="closed";const t=e._writer;void 0!==t&&Rt(t)}(t),null)),(e=>(function(e,t){e._inFlightCloseRequest._reject(t),e._inFlightCloseRequest=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._reject(t),e._pendingAbortRequest=void 0),et(e,t)}(t,e),null)))}(e):function(e,t){const r=e._controlledWritableStream;!function(e){e._inFlightWriteRequest=e._writeRequests.shift()}(r);h(e._writeAlgorithm(t),(()=>{!function(e){e._inFlightWriteRequest._resolve(void 0),e._inFlightWriteRequest=void 0}(r);const t=r._state;if(ue(e),!ot(r)&&"writable"===t){const t=ht(e);at(r,t)}return ft(e),null}),(t=>("writable"===r._state&&ct(e),function(e,t){e._inFlightWriteRequest._reject(t),e._inFlightWriteRequest=void 0,et(e,t)}(r,t),null)))}(e,r)}function bt(e,t){"writable"===e._controlledWritableStream._state&&_t(e,t)}function ht(e){return dt(e)<=0}function _t(e,t){const r=e._controlledWritableStream;ct(e),tt(r,t)}function pt(e){return new TypeError(`WritableStream.prototype.${e} can only be used on a WritableStream`)}function mt(e){return new TypeError(`WritableStreamDefaultController.prototype.${e} can only be used on a WritableStreamDefaultController`)}function yt(e){return new TypeError(`WritableStreamDefaultWriter.prototype.${e} can only be used on a WritableStreamDefaultWriter`)}function gt(e){return new TypeError("Cannot "+e+" a stream using a released writer")}function St(e){e._closedPromise=c(((t,r)=>{e._closedPromise_resolve=t,e._closedPromise_reject=r,e._closedPromiseState="pending"}))}function wt(e,t){St(e),vt(e,t)}function vt(e,t){void 0!==e._closedPromise_reject&&(y(e._closedPromise),e._closedPromise_reject(t),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="rejected")}function Rt(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="resolved")}function Tt(e){e._readyPromise=c(((t,r)=>{e._readyPromise_resolve=t,e._readyPromise_reject=r})),e._readyPromiseState="pending"}function qt(e,t){Tt(e),Pt(e,t)}function Ct(e){Tt(e),Et(e)}function Pt(e,t){void 0!==e._readyPromise_reject&&(y(e._readyPromise),e._readyPromise_reject(t),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="rejected")}function Et(e){void 0!==e._readyPromise_resolve&&(e._readyPromise_resolve(void 0),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="fulfilled")}Object.defineProperties(WritableStreamDefaultController.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(WritableStreamDefaultController.prototype,t.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});const Wt="undefined"!=typeof DOMException?DOMException:void 0;const Ot=function(e){if("function"!=typeof e&&"object"!=typeof e)return!1;try{return new e,!0}catch(e){return!1}}(Wt)?Wt:function(){const e=function(e,t){this.message=e||"",this.name=t||"Error",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)};return e.prototype=Object.create(Error.prototype),Object.defineProperty(e.prototype,"constructor",{value:e,writable:!0,configurable:!0}),e}();function kt(e,t,r,o,n,a){const i=e.getReader(),l=t.getWriter();Ut(e)&&(e._disturbed=!0);let s,u,p,S=!1,w=!1,v="readable",R="writable",T=!1,q=!1;const C=c((e=>{p=e}));let P=Promise.resolve(void 0);return c(((E,W)=>{let O;function k(){if(S)return;const e=c(((e,t)=>{!function r(o){o?e():b(function(){if(S)return d(!0);return b(l.ready,(()=>b(i.read(),(e=>!!e.done||(P=l.write(e.value),y(P),!1)))))}(),r,t)}(!1)}));y(e)}function B(){return v="closed",r?L():z((()=>(Xe(t)&&(T=ot(t),R=t._state),T||"closed"===R?d(void 0):"erroring"===R||"errored"===R?f(u):(T=!0,l.close()))),!1,void 0),null}function A(e){return S||(v="errored",s=e,o?L(!0,e):z((()=>l.abort(e)),!0,e)),null}function j(e){return w||(R="errored",u=e,n?L(!0,e):z((()=>i.cancel(e)),!0,e)),null}if(void 0!==a&&(O=()=>{const e=void 0!==a.reason?a.reason:new Ot("Aborted","AbortError"),t=[];o||t.push((()=>"writable"===R?l.abort(e):d(void 0))),n||t.push((()=>"readable"===v?i.cancel(e):d(void 0))),z((()=>Promise.all(t.map((e=>e())))),!0,e)},a.aborted?O():a.addEventListener("abort",O)),Ut(e)&&(v=e._state,s=e._storedError),Xe(t)&&(R=t._state,u=t._storedError,T=ot(t)),Ut(e)&&Xe(t)&&(q=!0,p()),"errored"===v)A(s);else if("erroring"===R||"errored"===R)j(u);else if("closed"===v)B();else if(T||"closed"===R){const e=new TypeError("the destination writable stream closed before all data could be piped to it");n?L(!0,e):z((()=>i.cancel(e)),!0,e)}function z(e,t,r){function o(){return"writable"!==R||T?n():_(function(){let e;return d(function t(){if(e!==P)return e=P,m(P,t,t)}())}(),n),null}function n(){return e?h(e(),(()=>F(t,r)),(e=>F(!0,e))):F(t,r),null}S||(S=!0,q?o():_(C,o))}function L(e,t){z(void 0,e,t)}function F(e,t){return w=!0,l.releaseLock(),i.releaseLock(),void 0!==a&&a.removeEventListener("abort",O),e?W(t):E(void 0),null}S||(h(i.closed,B,A),h(l.closed,(function(){return w||(R="closed"),null}),j)),q?k():g((()=>{q=!0,p(),k()}))}))}function Bt(e,t){return function(e){try{return e.getReader({mode:"byob"}).releaseLock(),!0}catch(e){return!1}}(e)?function(e){let t,r,o,n,a,i=e.getReader(),l=!1,s=!1,u=!1,f=!1,b=!1,_=!1;const m=c((e=>{a=e}));function y(e){p(e.closed,(t=>(e!==i||(o.error(t),n.error(t),b&&_||a(void 0)),null)))}function g(){l&&(i.releaseLock(),i=e.getReader(),y(i),l=!1),h(i.read(),(e=>{var t,r;if(u=!1,f=!1,e.done)return b||o.close(),_||n.close(),null===(t=o.byobRequest)||void 0===t||t.respond(0),null===(r=n.byobRequest)||void 0===r||r.respond(0),b&&_||a(void 0),null;const l=e.value,c=l;let d=l;if(!b&&!_)try{d=se(l)}catch(e){return o.error(e),n.error(e),a(i.cancel(e)),null}return b||o.enqueue(c),_||n.enqueue(d),s=!1,u?w():f&&v(),null}),(()=>(s=!1,null)))}function S(t,r){l||(i.releaseLock(),i=e.getReader({mode:"byob"}),y(i),l=!0);const c=r?n:o,d=r?o:n;h(i.read(t),(e=>{var t;u=!1,f=!1;const o=r?_:b,n=r?b:_;if(e.done){o||c.close(),n||d.close();const r=e.value;return void 0!==r&&(o||c.byobRequest.respondWithNewView(r),n||null===(t=d.byobRequest)||void 0===t||t.respond(0)),o&&n||a(void 0),null}const l=e.value;if(n)o||c.byobRequest.respondWithNewView(l);else{let e;try{e=se(l)}catch(e){return c.error(e),d.error(e),a(i.cancel(e)),null}o||c.byobRequest.respondWithNewView(l),d.enqueue(e)}return s=!1,u?w():f&&v(),null}),(()=>(s=!1,null)))}function w(){if(s)return u=!0,d(void 0);s=!0;const e=o.byobRequest;return null===e?g():S(e.view,!1),d(void 0)}function v(){if(s)return f=!0,d(void 0);s=!0;const e=n.byobRequest;return null===e?g():S(e.view,!0),d(void 0)}function R(e){if(b=!0,t=e,_){const e=[t,r],o=i.cancel(e);a(o)}return m}function T(e){if(_=!0,r=e,b){const e=[t,r],o=i.cancel(e);a(o)}return m}const q=new ReadableStream({type:"bytes",start(e){o=e},pull:w,cancel:R}),C=new ReadableStream({type:"bytes",start(e){n=e},pull:v,cancel:T});return y(i),[q,C]}(e):function(e,t){const r=e.getReader();let o,n,a,i,l,s=!1,u=!1,f=!1,b=!1;const _=c((e=>{l=e}));function m(){return s?(u=!0,d(void 0)):(s=!0,h(r.read(),(e=>{if(u=!1,e.done)return f||a.close(),b||i.close(),f&&b||l(void 0),null;const t=e.value,r=t,o=t;return f||a.enqueue(r),b||i.enqueue(o),s=!1,u&&m(),null}),(()=>(s=!1,null))),d(void 0))}function y(e){if(f=!0,o=e,b){const e=[o,n],t=r.cancel(e);l(t)}return _}function g(e){if(b=!0,n=e,f){const e=[o,n],t=r.cancel(e);l(t)}return _}const S=new ReadableStream({start(e){a=e},pull:m,cancel:y}),w=new ReadableStream({start(e){i=e},pull:m,cancel:g});return p(r.closed,(e=>(a.error(e),i.error(e),f&&b||l(void 0),null))),[S,w]}(e)}class ReadableStreamDefaultController{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!At(this))throw $t("desiredSize");return Ft(this)}close(){if(!At(this))throw $t("close");if(!Dt(this))throw new TypeError("The stream is not in a state that permits close");!function(e){if(!Dt(e))return;const t=e._controlledReadableStream;e._closeRequested=!0,0===e._queue.length&&(zt(e),Jt(t))}(this)}enqueue(e){if(!At(this))throw $t("enqueue");if(!Dt(this))throw new TypeError("The stream is not in a state that permits enqueue");return function(e,t){if(!Dt(e))return;const r=e._controlledReadableStream;if(Gt(r)&&J(r)>0)X(r,t,!1);else{let r;try{r=e._strategySizeAlgorithm(t)}catch(t){throw Lt(e,t),t}try{ce(e,t,r)}catch(t){throw Lt(e,t),t}}jt(e)}(this,e)}error(e){if(!At(this))throw $t("error");Lt(this,e)}[q](e){de(this);const t=this._cancelAlgorithm(e);return zt(this),t}[C](e){const t=this._controlledReadableStream;if(this._queue.length>0){const r=ue(this);this._closeRequested&&0===this._queue.length?(zt(this),Jt(t)):jt(this),e._chunkSteps(r)}else G(t,e),jt(this)}[P](){}}function At(e){return!!o(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableStream")&&e instanceof ReadableStreamDefaultController)}function jt(e){const t=function(e){const t=e._controlledReadableStream;if(!Dt(e))return!1;if(!e._started)return!1;if(Gt(t)&&J(t)>0)return!0;if(Ft(e)>0)return!0;return!1}(e);if(!t)return;if(e._pulling)return void(e._pullAgain=!0);e._pulling=!0;h(e._pullAlgorithm(),(()=>(e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,jt(e)),null)),(t=>(Lt(e,t),null)))}function zt(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function Lt(e,t){const r=e._controlledReadableStream;"readable"===r._state&&(de(e),zt(e),Kt(r,t))}function Ft(e){const t=e._controlledReadableStream._state;return"errored"===t?null:"closed"===t?0:e._strategyHWM-e._queueTotalSize}function Dt(e){return!e._closeRequested&&"readable"===e._controlledReadableStream._state}function It(e,t,r,o){const n=Object.create(ReadableStreamDefaultController.prototype);let a,i,l;a=void 0!==t.start?()=>t.start(n):()=>{},i=void 0!==t.pull?()=>t.pull(n):()=>d(void 0),l=void 0!==t.cancel?e=>t.cancel(e):()=>d(void 0),function(e,t,r,o,n,a,i){t._controlledReadableStream=e,t._queue=void 0,t._queueTotalSize=void 0,de(t),t._started=!1,t._closeRequested=!1,t._pullAgain=!1,t._pulling=!1,t._strategySizeAlgorithm=i,t._strategyHWM=a,t._pullAlgorithm=o,t._cancelAlgorithm=n,e._readableStreamController=t,h(d(r()),(()=>(t._started=!0,jt(t),null)),(e=>(Lt(t,e),null)))}(e,n,a,i,l,r,o)}function $t(e){return new TypeError(`ReadableStreamDefaultController.prototype.${e} can only be used on a ReadableStreamDefaultController`)}function Mt(e,t,r){return I(e,r),r=>w(e,t,[r])}function Yt(e,t,r){return I(e,r),r=>w(e,t,[r])}function Qt(e,t,r){return I(e,r),r=>S(e,t,[r])}function Nt(e,t){if("bytes"!==(e=`${e}`))throw new TypeError(`${t} '${e}' is not a valid enumeration value for ReadableStreamType`);return e}function xt(e,t){if("byob"!==(e=`${e}`))throw new TypeError(`${t} '${e}' is not a valid enumeration value for ReadableStreamReaderMode`);return e}function Ht(e,t){D(e,t);const r=null==e?void 0:e.preventAbort,o=null==e?void 0:e.preventCancel,n=null==e?void 0:e.preventClose,a=null==e?void 0:e.signal;return void 0!==a&&function(e,t){if(!function(e){if("object"!=typeof e||null===e)return!1;try{return"boolean"==typeof e.aborted}catch(e){return!1}}(e))throw new TypeError(`${t} is not an AbortSignal.`)}(a,`${t} has member 'signal' that`),{preventAbort:Boolean(r),preventCancel:Boolean(o),preventClose:Boolean(n),signal:a}}function Vt(e,t){D(e,t);const r=null==e?void 0:e.readable;Y(r,"readable","ReadableWritablePair"),function(e,t){if(!H(e))throw new TypeError(`${t} is not a ReadableStream.`)}(r,`${t} has member 'readable' that`);const o=null==e?void 0:e.writable;return Y(o,"writable","ReadableWritablePair"),function(e,t){if(!V(e))throw new TypeError(`${t} is not a WritableStream.`)}(o,`${t} has member 'writable' that`),{readable:r,writable:o}}Object.defineProperties(ReadableStreamDefaultController.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),a(ReadableStreamDefaultController.prototype.close,"close"),a(ReadableStreamDefaultController.prototype.enqueue,"enqueue"),a(ReadableStreamDefaultController.prototype.error,"error"),"symbol"==typeof t.toStringTag&&Object.defineProperty(ReadableStreamDefaultController.prototype,t.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});class ReadableStream{constructor(e={},t={}){void 0===e?e=null:$(e,"First parameter");const r=Qe(t,"Second parameter"),o=function(e,t){D(e,t);const r=e,o=null==r?void 0:r.autoAllocateChunkSize,n=null==r?void 0:r.cancel,a=null==r?void 0:r.pull,i=null==r?void 0:r.start,l=null==r?void 0:r.type;return{autoAllocateChunkSize:void 0===o?void 0:x(o,`${t} has member 'autoAllocateChunkSize' that`),cancel:void 0===n?void 0:Mt(n,r,`${t} has member 'cancel' that`),pull:void 0===a?void 0:Yt(a,r,`${t} has member 'pull' that`),start:void 0===i?void 0:Qt(i,r,`${t} has member 'start' that`),type:void 0===l?void 0:Nt(l,`${t} has member 'type' that`)}}(e,"First parameter");var n;if((n=this)._state="readable",n._reader=void 0,n._storedError=void 0,n._disturbed=!1,"bytes"===o.type){if(void 0!==r.size)throw new RangeError("The strategy for a byte stream cannot have a size function");Be(this,o,Me(r,0))}else{const e=Ye(r);It(this,o,Me(r,1),e)}}get locked(){if(!Ut(this))throw Zt("locked");return Gt(this)}cancel(e){return Ut(this)?Gt(this)?f(new TypeError("Cannot cancel a stream that already has a reader")):Xt(this,e):f(Zt("cancel"))}getReader(e){if(!Ut(this))throw Zt("getReader");return void 0===function(e,t){D(e,t);const r=null==e?void 0:e.mode;return{mode:void 0===r?void 0:xt(r,`${t} has member 'mode' that`)}}(e,"First parameter").mode?new ReadableStreamDefaultReader(this):function(e){return new ReadableStreamBYOBReader(e)}(this)}pipeThrough(e,t={}){if(!H(this))throw Zt("pipeThrough");M(e,1,"pipeThrough");const r=Vt(e,"First parameter"),o=Ht(t,"Second parameter");if(this.locked)throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(r.writable.locked)throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");return y(kt(this,r.writable,o.preventClose,o.preventAbort,o.preventCancel,o.signal)),r.readable}pipeTo(e,t={}){if(!H(this))return f(Zt("pipeTo"));if(void 0===e)return f("Parameter 1 is required in 'pipeTo'.");if(!V(e))return f(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let r;try{r=Ht(t,"Second parameter")}catch(e){return f(e)}return this.locked?f(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):e.locked?f(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):kt(this,e,r.preventClose,r.preventAbort,r.preventCancel,r.signal)}tee(){if(!H(this))throw Zt("tee");if(this.locked)throw new TypeError("Cannot tee a stream that already has a reader");return Bt(this)}values(e){if(!H(this))throw Zt("values");return function(e,t){const r=e.getReader(),o=new re(r,t),n=Object.create(oe);return n._asyncIteratorImpl=o,n}(this,function(e,t){D(e,t);const r=null==e?void 0:e.preventCancel;return{preventCancel:Boolean(r)}}(e,"First parameter").preventCancel)}}function Ut(e){return!!o(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readableStreamController")&&e instanceof ReadableStream)}function Gt(e){return void 0!==e._reader}function Xt(e,t){if(e._disturbed=!0,"closed"===e._state)return d(void 0);if("errored"===e._state)return f(e._storedError);Jt(e);const o=e._reader;if(void 0!==o&&De(o)){const e=o._readIntoRequests;o._readIntoRequests=new v,e.forEach((e=>{e._closeSteps(void 0)}))}return m(e._readableStreamController[q](t),r)}function Jt(e){e._state="closed";const t=e._reader;if(void 0!==t&&(z(t),Z(t))){const e=t._readRequests;t._readRequests=new v,e.forEach((e=>{e._closeSteps()}))}}function Kt(e,t){e._state="errored",e._storedError=t;const r=e._reader;void 0!==r&&(j(r,t),Z(r)?ee(r,t):Ie(r,t))}function Zt(e){return new TypeError(`ReadableStream.prototype.${e} can only be used on a ReadableStream`)}function er(e,t){D(e,t);const r=null==e?void 0:e.highWaterMark;return Y(r,"highWaterMark","QueuingStrategyInit"),{highWaterMark:Q(r)}}Object.defineProperties(ReadableStream.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),a(ReadableStream.prototype.cancel,"cancel"),a(ReadableStream.prototype.getReader,"getReader"),a(ReadableStream.prototype.pipeThrough,"pipeThrough"),a(ReadableStream.prototype.pipeTo,"pipeTo"),a(ReadableStream.prototype.tee,"tee"),a(ReadableStream.prototype.values,"values"),"symbol"==typeof t.toStringTag&&Object.defineProperty(ReadableStream.prototype,t.toStringTag,{value:"ReadableStream",configurable:!0}),"symbol"==typeof t.asyncIterator&&Object.defineProperty(ReadableStream.prototype,t.asyncIterator,{value:ReadableStream.prototype.values,writable:!0,configurable:!0});const tr=e=>e.byteLength;a(tr,"size");class ByteLengthQueuingStrategy{constructor(e){M(e,1,"ByteLengthQueuingStrategy"),e=er(e,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=e.highWaterMark}get highWaterMark(){if(!or(this))throw rr("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!or(this))throw rr("size");return tr}}function rr(e){return new TypeError(`ByteLengthQueuingStrategy.prototype.${e} can only be used on a ByteLengthQueuingStrategy`)}function or(e){return!!o(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_byteLengthQueuingStrategyHighWaterMark")&&e instanceof ByteLengthQueuingStrategy)}Object.defineProperties(ByteLengthQueuingStrategy.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(ByteLengthQueuingStrategy.prototype,t.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});const nr=()=>1;a(nr,"size");class CountQueuingStrategy{constructor(e){M(e,1,"CountQueuingStrategy"),e=er(e,"First parameter"),this._countQueuingStrategyHighWaterMark=e.highWaterMark}get highWaterMark(){if(!ir(this))throw ar("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!ir(this))throw ar("size");return nr}}function ar(e){return new TypeError(`CountQueuingStrategy.prototype.${e} can only be used on a CountQueuingStrategy`)}function ir(e){return!!o(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_countQueuingStrategyHighWaterMark")&&e instanceof CountQueuingStrategy)}function lr(e,t,r){return I(e,r),r=>w(e,t,[r])}function sr(e,t,r){return I(e,r),r=>S(e,t,[r])}function ur(e,t,r){return I(e,r),(r,o)=>w(e,t,[r,o])}Object.defineProperties(CountQueuingStrategy.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(CountQueuingStrategy.prototype,t.toStringTag,{value:"CountQueuingStrategy",configurable:!0});class TransformStream{constructor(e={},t={},r={}){void 0===e&&(e=null);const o=Qe(t,"Second parameter"),n=Qe(r,"Third parameter"),a=function(e,t){D(e,t);const r=null==e?void 0:e.flush,o=null==e?void 0:e.readableType,n=null==e?void 0:e.start,a=null==e?void 0:e.transform,i=null==e?void 0:e.writableType;return{flush:void 0===r?void 0:lr(r,e,`${t} has member 'flush' that`),readableType:o,start:void 0===n?void 0:sr(n,e,`${t} has member 'start' that`),transform:void 0===a?void 0:ur(a,e,`${t} has member 'transform' that`),writableType:i}}(e,"First parameter");if(void 0!==a.readableType)throw new RangeError("Invalid readableType specified");if(void 0!==a.writableType)throw new RangeError("Invalid writableType specified");const i=Me(n,0),l=Ye(n),s=Me(o,1),u=Ye(o);let b;!function(e,t,r,o,n,a){function i(){return t}function l(t){return function(e,t){const r=e._transformStreamController;if(e._backpressure){return m(e._backpressureChangePromise,(()=>{if("erroring"===(Xe(e._writable)?e._writable._state:e._writableState))throw Xe(e._writable)?e._writable._storedError:e._writableStoredError;return mr(r,t)}))}return mr(r,t)}(e,t)}function s(t){return function(e,t){return dr(e,t),d(void 0)}(e,t)}function u(){return function(e){const t=e._transformStreamController,r=t._flushAlgorithm();return _r(t),m(r,(()=>{if("errored"===e._readableState)throw e._readableStoredError;Sr(e)&&wr(e)}),(t=>{throw dr(e,t),e._readableStoredError}))}(e)}function c(){return function(e){return br(e,!1),e._backpressureChangePromise}(e)}function f(t){return fr(e,t),d(void 0)}e._writableState="writable",e._writableStoredError=void 0,e._writableHasInFlightOperation=!1,e._writableStarted=!1,e._writable=function(e,t,r,o,n,a,i){return new WritableStream({start(r){e._writableController=r;try{const t=r.signal;void 0!==t&&t.addEventListener("abort",(()=>{"writable"===e._writableState&&(e._writableState="erroring",t.reason&&(e._writableStoredError=t.reason))}))}catch(e){}return m(t(),(()=>(e._writableStarted=!0,Pr(e),null)),(t=>{throw e._writableStarted=!0,Tr(e,t),t}))},write:t=>(function(e){e._writableHasInFlightOperation=!0}(e),m(r(t),(()=>(function(e){e._writableHasInFlightOperation=!1}(e),Pr(e),null)),(t=>{throw function(e,t){e._writableHasInFlightOperation=!1,Tr(e,t)}(e,t),t}))),close:()=>(function(e){e._writableHasInFlightOperation=!0}(e),m(o(),(()=>(function(e){e._writableHasInFlightOperation=!1;"erroring"===e._writableState&&(e._writableStoredError=void 0);e._writableState="closed"}(e),null)),(t=>{throw function(e,t){e._writableHasInFlightOperation=!1,e._writableState,Tr(e,t)}(e,t),t}))),abort:t=>(e._writableState="errored",e._writableStoredError=t,n(t))},{highWaterMark:a,size:i})}(e,i,l,u,s,r,o),e._readableState="readable",e._readableStoredError=void 0,e._readableCloseRequested=!1,e._readablePulling=!1,e._readable=function(e,t,r,o,n,a){return new ReadableStream({start:r=>(e._readableController=r,t().catch((t=>{vr(e,t)}))),pull:()=>(e._readablePulling=!0,r().catch((t=>{vr(e,t)}))),cancel:t=>(e._readableState="closed",o(t))},{highWaterMark:n,size:a})}(e,i,c,f,n,a),e._backpressure=void 0,e._backpressureChangePromise=void 0,e._backpressureChangePromise_resolve=void 0,br(e,!0),e._transformStreamController=void 0}(this,c((e=>{b=e})),s,u,i,l),function(e,t){const r=Object.create(TransformStreamDefaultController.prototype);let o,n;o=void 0!==t.transform?e=>t.transform(e,r):e=>{try{return pr(r,e),d(void 0)}catch(e){return f(e)}};n=void 0!==t.flush?()=>t.flush(r):()=>d(void 0);!function(e,t,r,o){t._controlledTransformStream=e,e._transformStreamController=t,t._transformAlgorithm=r,t._flushAlgorithm=o}(e,r,o,n)}(this,a),void 0!==a.start?b(a.start(this._transformStreamController)):b(void 0)}get readable(){if(!cr(this))throw gr("readable");return this._readable}get writable(){if(!cr(this))throw gr("writable");return this._writable}}function cr(e){return!!o(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_transformStreamController")&&e instanceof TransformStream)}function dr(e,t){vr(e,t),fr(e,t)}function fr(e,t){_r(e._transformStreamController),function(e,t){e._writableController.error(t);"writable"===e._writableState&&qr(e,t)}(e,t),e._backpressure&&br(e,!1)}function br(e,t){void 0!==e._backpressureChangePromise&&e._backpressureChangePromise_resolve(),e._backpressureChangePromise=c((t=>{e._backpressureChangePromise_resolve=t})),e._backpressure=t}Object.defineProperties(TransformStream.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(TransformStream.prototype,t.toStringTag,{value:"TransformStream",configurable:!0});class TransformStreamDefaultController{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!hr(this))throw yr("desiredSize");return Rr(this._controlledTransformStream)}enqueue(e){if(!hr(this))throw yr("enqueue");pr(this,e)}error(e){if(!hr(this))throw yr("error");var t;t=e,dr(this._controlledTransformStream,t)}terminate(){if(!hr(this))throw yr("terminate");!function(e){const t=e._controlledTransformStream;Sr(t)&&wr(t);const r=new TypeError("TransformStream terminated");fr(t,r)}(this)}}function hr(e){return!!o(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledTransformStream")&&e instanceof TransformStreamDefaultController)}function _r(e){e._transformAlgorithm=void 0,e._flushAlgorithm=void 0}function pr(e,t){const r=e._controlledTransformStream;if(!Sr(r))throw new TypeError("Readable side is not in a state that permits enqueue");try{!function(e,t){e._readablePulling=!1;try{e._readableController.enqueue(t)}catch(t){throw vr(e,t),t}}(r,t)}catch(e){throw fr(r,e),r._readableStoredError}const o=function(e){return!function(e){if(!Sr(e))return!1;if(e._readablePulling)return!0;if(Rr(e)>0)return!0;return!1}(e)}(r);o!==r._backpressure&&br(r,!0)}function mr(e,t){return m(e._transformAlgorithm(t),void 0,(t=>{throw dr(e._controlledTransformStream,t),t}))}function yr(e){return new TypeError(`TransformStreamDefaultController.prototype.${e} can only be used on a TransformStreamDefaultController`)}function gr(e){return new TypeError(`TransformStream.prototype.${e} can only be used on a TransformStream`)}function Sr(e){return!e._readableCloseRequested&&"readable"===e._readableState}function wr(e){e._readableState="closed",e._readableCloseRequested=!0,e._readableController.close()}function vr(e,t){"readable"===e._readableState&&(e._readableState="errored",e._readableStoredError=t),e._readableController.error(t)}function Rr(e){return e._readableController.desiredSize}function Tr(e,t){"writable"!==e._writableState?Cr(e):qr(e,t)}function qr(e,t){e._writableState="erroring",e._writableStoredError=t,!function(e){return e._writableHasInFlightOperation}(e)&&e._writableStarted&&Cr(e)}function Cr(e){e._writableState="errored"}function Pr(e){"erroring"===e._writableState&&Cr(e)}Object.defineProperties(TransformStreamDefaultController.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),a(TransformStreamDefaultController.prototype.enqueue,"enqueue"),a(TransformStreamDefaultController.prototype.error,"error"),a(TransformStreamDefaultController.prototype.terminate,"terminate"),"symbol"==typeof t.toStringTag&&Object.defineProperty(TransformStreamDefaultController.prototype,t.toStringTag,{value:"TransformStreamDefaultController",configurable:!0}),e.ByteLengthQueuingStrategy=ByteLengthQueuingStrategy,e.CountQueuingStrategy=CountQueuingStrategy,e.ReadableByteStreamController=ReadableByteStreamController,e.ReadableStream=ReadableStream,e.ReadableStreamBYOBReader=ReadableStreamBYOBReader,e.ReadableStreamBYOBRequest=ReadableStreamBYOBRequest,e.ReadableStreamDefaultController=ReadableStreamDefaultController,e.ReadableStreamDefaultReader=ReadableStreamDefaultReader,e.TransformStream=TransformStream,e.TransformStreamDefaultController=TransformStreamDefaultController,e.WritableStream=WritableStream,e.WritableStreamDefaultController=WritableStreamDefaultController,e.WritableStreamDefaultWriter=WritableStreamDefaultWriter,Object.defineProperty(e,"__esModule",{value:!0})})); diff --git a/backend/node_modules/formdata-node/node_modules/web-streams-polyfill/dist/ponyfill.mjs b/backend/node_modules/formdata-node/node_modules/web-streams-polyfill/dist/ponyfill.mjs new file mode 100644 index 0000000000000000000000000000000000000000..3df46d5d0d45129bea7300c11fd597ef871a06a2 --- /dev/null +++ b/backend/node_modules/formdata-node/node_modules/web-streams-polyfill/dist/ponyfill.mjs @@ -0,0 +1,8 @@ +/** + * @license + * web-streams-polyfill v4.0.0-beta.3 + * Copyright 2021 Mattias Buelens, Diwank Singh Tomer and other contributors. + * This code is released under the MIT license. + * SPDX-License-Identifier: MIT + */ +const e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol:e=>`Symbol(${e})`;function t(){}function r(e){return"object"==typeof e&&null!==e||"function"==typeof e}const o=t;function n(e,t){try{Object.defineProperty(e,"name",{value:t,configurable:!0})}catch(e){}}const a=Promise,i=Promise.prototype.then,l=Promise.resolve.bind(a),s=Promise.reject.bind(a);function u(e){return new a(e)}function c(e){return l(e)}function d(e){return s(e)}function f(e,t,r){return i.call(e,t,r)}function b(e,t,r){f(f(e,t,r),void 0,o)}function h(e,t){b(e,t)}function _(e,t){b(e,void 0,t)}function p(e,t,r){return f(e,t,r)}function m(e){f(e,void 0,o)}let y=e=>{if("function"==typeof queueMicrotask)y=queueMicrotask;else{const e=c(void 0);y=t=>f(e,t)}return y(e)};function g(e,t,r){if("function"!=typeof e)throw new TypeError("Argument is not a function");return Function.prototype.apply.call(e,t,r)}function w(e,t,r){try{return c(g(e,t,r))}catch(e){return d(e)}}class S{constructor(){this._cursor=0,this._size=0,this._front={_elements:[],_next:void 0},this._back=this._front,this._cursor=0,this._size=0}get length(){return this._size}push(e){const t=this._back;let r=t;16383===t._elements.length&&(r={_elements:[],_next:void 0}),t._elements.push(e),r!==t&&(this._back=r,t._next=r),++this._size}shift(){const e=this._front;let t=e;const r=this._cursor;let o=r+1;const n=e._elements,a=n[r];return 16384===o&&(t=e._next,o=0),--this._size,this._cursor=o,e!==t&&(this._front=t),n[r]=void 0,a}forEach(e){let t=this._cursor,r=this._front,o=r._elements;for(;!(t===o.length&&void 0===r._next||t===o.length&&(r=r._next,o=r._elements,t=0,0===o.length));)e(o[t]),++t}peek(){const e=this._front,t=this._cursor;return e._elements[t]}}const v=e("[[AbortSteps]]"),R=e("[[ErrorSteps]]"),T=e("[[CancelSteps]]"),q=e("[[PullSteps]]"),C=e("[[ReleaseSteps]]");function E(e,t){e._ownerReadableStream=t,t._reader=e,"readable"===t._state?O(e):"closed"===t._state?function(e){O(e),j(e)}(e):B(e,t._storedError)}function P(e,t){return Gt(e._ownerReadableStream,t)}function W(e){const t=e._ownerReadableStream;"readable"===t._state?A(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):function(e,t){B(e,t)}(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),t._readableStreamController[C](),t._reader=void 0,e._ownerReadableStream=void 0}function k(e){return new TypeError("Cannot "+e+" a stream using a released reader")}function O(e){e._closedPromise=u(((t,r)=>{e._closedPromise_resolve=t,e._closedPromise_reject=r}))}function B(e,t){O(e),A(e,t)}function A(e,t){void 0!==e._closedPromise_reject&&(m(e._closedPromise),e._closedPromise_reject(t),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}function j(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}const z=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},L=Math.trunc||function(e){return e<0?Math.ceil(e):Math.floor(e)};function F(e,t){if(void 0!==e&&("object"!=typeof(r=e)&&"function"!=typeof r))throw new TypeError(`${t} is not an object.`);var r}function I(e,t){if("function"!=typeof e)throw new TypeError(`${t} is not a function.`)}function D(e,t){if(!function(e){return"object"==typeof e&&null!==e||"function"==typeof e}(e))throw new TypeError(`${t} is not an object.`)}function $(e,t,r){if(void 0===e)throw new TypeError(`Parameter ${t} is required in '${r}'.`)}function M(e,t,r){if(void 0===e)throw new TypeError(`${t} is required in '${r}'.`)}function Y(e){return Number(e)}function Q(e){return 0===e?0:e}function N(e,t){const r=Number.MAX_SAFE_INTEGER;let o=Number(e);if(o=Q(o),!z(o))throw new TypeError(`${t} is not a finite number`);if(o=function(e){return Q(L(e))}(o),o<0||o>r)throw new TypeError(`${t} is outside the accepted range of 0 to ${r}, inclusive`);return z(o)&&0!==o?o:0}function H(e){if(!r(e))return!1;if("function"!=typeof e.getReader)return!1;try{return"boolean"==typeof e.locked}catch(e){return!1}}function x(e){if(!r(e))return!1;if("function"!=typeof e.getWriter)return!1;try{return"boolean"==typeof e.locked}catch(e){return!1}}function V(e,t){if(!Vt(e))throw new TypeError(`${t} is not a ReadableStream.`)}function U(e,t){e._reader._readRequests.push(t)}function G(e,t,r){const o=e._reader._readRequests.shift();r?o._closeSteps():o._chunkSteps(t)}function X(e){return e._reader._readRequests.length}function J(e){const t=e._reader;return void 0!==t&&!!K(t)}class ReadableStreamDefaultReader{constructor(e){if($(e,1,"ReadableStreamDefaultReader"),V(e,"First parameter"),Ut(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");E(this,e),this._readRequests=new S}get closed(){return K(this)?this._closedPromise:d(ee("closed"))}cancel(e){return K(this)?void 0===this._ownerReadableStream?d(k("cancel")):P(this,e):d(ee("cancel"))}read(){if(!K(this))return d(ee("read"));if(void 0===this._ownerReadableStream)return d(k("read from"));let e,t;const r=u(((r,o)=>{e=r,t=o}));return function(e,t){const r=e._ownerReadableStream;r._disturbed=!0,"closed"===r._state?t._closeSteps():"errored"===r._state?t._errorSteps(r._storedError):r._readableStreamController[q](t)}(this,{_chunkSteps:t=>e({value:t,done:!1}),_closeSteps:()=>e({value:void 0,done:!0}),_errorSteps:e=>t(e)}),r}releaseLock(){if(!K(this))throw ee("releaseLock");void 0!==this._ownerReadableStream&&function(e){W(e);const t=new TypeError("Reader was released");Z(e,t)}(this)}}function K(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readRequests")&&e instanceof ReadableStreamDefaultReader)}function Z(e,t){const r=e._readRequests;e._readRequests=new S,r.forEach((e=>{e._errorSteps(t)}))}function ee(e){return new TypeError(`ReadableStreamDefaultReader.prototype.${e} can only be used on a ReadableStreamDefaultReader`)}Object.defineProperties(ReadableStreamDefaultReader.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),n(ReadableStreamDefaultReader.prototype.cancel,"cancel"),n(ReadableStreamDefaultReader.prototype.read,"read"),n(ReadableStreamDefaultReader.prototype.releaseLock,"releaseLock"),"symbol"==typeof e.toStringTag&&Object.defineProperty(ReadableStreamDefaultReader.prototype,e.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0});class te{constructor(e,t){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=e,this._preventCancel=t}next(){const e=()=>this._nextSteps();return this._ongoingPromise=this._ongoingPromise?p(this._ongoingPromise,e,e):e(),this._ongoingPromise}return(e){const t=()=>this._returnSteps(e);return this._ongoingPromise?p(this._ongoingPromise,t,t):t()}_nextSteps(){if(this._isFinished)return Promise.resolve({value:void 0,done:!0});const e=this._reader;return void 0===e?d(k("iterate")):f(e.read(),(e=>{var t;return this._ongoingPromise=void 0,e.done&&(this._isFinished=!0,null===(t=this._reader)||void 0===t||t.releaseLock(),this._reader=void 0),e}),(e=>{var t;throw this._ongoingPromise=void 0,this._isFinished=!0,null===(t=this._reader)||void 0===t||t.releaseLock(),this._reader=void 0,e}))}_returnSteps(e){if(this._isFinished)return Promise.resolve({value:e,done:!0});this._isFinished=!0;const t=this._reader;if(void 0===t)return d(k("finish iterating"));if(this._reader=void 0,!this._preventCancel){const r=t.cancel(e);return t.releaseLock(),p(r,(()=>({value:e,done:!0})))}return t.releaseLock(),c({value:e,done:!0})}}const re={next(){return oe(this)?this._asyncIteratorImpl.next():d(ne("next"))},return(e){return oe(this)?this._asyncIteratorImpl.return(e):d(ne("return"))}};function oe(e){if(!r(e))return!1;if(!Object.prototype.hasOwnProperty.call(e,"_asyncIteratorImpl"))return!1;try{return e._asyncIteratorImpl instanceof te}catch(e){return!1}}function ne(e){return new TypeError(`ReadableStreamAsyncIterator.${e} can only be used on a ReadableSteamAsyncIterator`)}"symbol"==typeof e.asyncIterator&&Object.defineProperty(re,e.asyncIterator,{value(){return this},writable:!0,configurable:!0});const ae=Number.isNaN||function(e){return e!=e};function ie(e,t,r,o,n){new Uint8Array(e).set(new Uint8Array(r,o,n),t)}function le(e){const t=function(e,t,r){if(e.slice)return e.slice(t,r);const o=r-t,n=new ArrayBuffer(o);return ie(n,0,e,t,o),n}(e.buffer,e.byteOffset,e.byteOffset+e.byteLength);return new Uint8Array(t)}function se(e){const t=e._queue.shift();return e._queueTotalSize-=t.size,e._queueTotalSize<0&&(e._queueTotalSize=0),t.value}function ue(e,t,r){if("number"!=typeof(o=r)||ae(o)||o<0||r===1/0)throw new RangeError("Size must be a finite, non-NaN, non-negative number.");var o;e._queue.push({value:t,size:r}),e._queueTotalSize+=r}function ce(e){e._queue=new S,e._queueTotalSize=0}class ReadableStreamBYOBRequest{constructor(){throw new TypeError("Illegal constructor")}get view(){if(!fe(this))throw Be("view");return this._view}respond(e){if(!fe(this))throw Be("respond");if($(e,1,"respond"),e=N(e,"First parameter"),void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");this._view.buffer,function(e,t){const r=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==t)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream")}else{if(0===t)throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");if(r.bytesFilled+t>r.byteLength)throw new RangeError("bytesWritten out of range")}r.buffer=r.buffer,qe(e,t)}(this._associatedReadableByteStreamController,e)}respondWithNewView(e){if(!fe(this))throw Be("respondWithNewView");if($(e,1,"respondWithNewView"),!ArrayBuffer.isView(e))throw new TypeError("You can only respond with array buffer views");if(void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");e.buffer,function(e,t){const r=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==t.byteLength)throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream")}else if(0===t.byteLength)throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");if(r.byteOffset+r.bytesFilled!==t.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(r.bufferByteLength!==t.buffer.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");if(r.bytesFilled+t.byteLength>r.byteLength)throw new RangeError("The region specified by view is larger than byobRequest");const o=t.byteLength;r.buffer=t.buffer,qe(e,o)}(this._associatedReadableByteStreamController,e)}}Object.defineProperties(ReadableStreamBYOBRequest.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),n(ReadableStreamBYOBRequest.prototype.respond,"respond"),n(ReadableStreamBYOBRequest.prototype.respondWithNewView,"respondWithNewView"),"symbol"==typeof e.toStringTag&&Object.defineProperty(ReadableStreamBYOBRequest.prototype,e.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});class ReadableByteStreamController{constructor(){throw new TypeError("Illegal constructor")}get byobRequest(){if(!de(this))throw Ae("byobRequest");return function(e){if(null===e._byobRequest&&e._pendingPullIntos.length>0){const t=e._pendingPullIntos.peek(),r=new Uint8Array(t.buffer,t.byteOffset+t.bytesFilled,t.byteLength-t.bytesFilled),o=Object.create(ReadableStreamBYOBRequest.prototype);!function(e,t,r){e._associatedReadableByteStreamController=t,e._view=r}(o,e,r),e._byobRequest=o}return e._byobRequest}(this)}get desiredSize(){if(!de(this))throw Ae("desiredSize");return ke(this)}close(){if(!de(this))throw Ae("close");if(this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");const e=this._controlledReadableByteStream._state;if("readable"!==e)throw new TypeError(`The stream (in ${e} state) is not in the readable state and cannot be closed`);!function(e){const t=e._controlledReadableByteStream;if(e._closeRequested||"readable"!==t._state)return;if(e._queueTotalSize>0)return void(e._closeRequested=!0);if(e._pendingPullIntos.length>0){if(e._pendingPullIntos.peek().bytesFilled>0){const t=new TypeError("Insufficient bytes to fill elements in the given buffer");throw Pe(e,t),t}}Ee(e),Xt(t)}(this)}enqueue(e){if(!de(this))throw Ae("enqueue");if($(e,1,"enqueue"),!ArrayBuffer.isView(e))throw new TypeError("chunk must be an array buffer view");if(0===e.byteLength)throw new TypeError("chunk must have non-zero byteLength");if(0===e.buffer.byteLength)throw new TypeError("chunk's buffer must have non-zero byteLength");if(this._closeRequested)throw new TypeError("stream is closed or draining");const t=this._controlledReadableByteStream._state;if("readable"!==t)throw new TypeError(`The stream (in ${t} state) is not in the readable state and cannot be enqueued to`);!function(e,t){const r=e._controlledReadableByteStream;if(e._closeRequested||"readable"!==r._state)return;const o=t.buffer,n=t.byteOffset,a=t.byteLength,i=o;if(e._pendingPullIntos.length>0){const t=e._pendingPullIntos.peek();t.buffer,0,Re(e),t.buffer=t.buffer,"none"===t.readerType&&ge(e,t)}if(J(r))if(function(e){const t=e._controlledReadableByteStream._reader;for(;t._readRequests.length>0;){if(0===e._queueTotalSize)return;We(e,t._readRequests.shift())}}(e),0===X(r))me(e,i,n,a);else{e._pendingPullIntos.length>0&&Ce(e);G(r,new Uint8Array(i,n,a),!1)}else Le(r)?(me(e,i,n,a),Te(e)):me(e,i,n,a);be(e)}(this,e)}error(e){if(!de(this))throw Ae("error");Pe(this,e)}[T](e){he(this),ce(this);const t=this._cancelAlgorithm(e);return Ee(this),t}[q](e){const t=this._controlledReadableByteStream;if(this._queueTotalSize>0)return void We(this,e);const r=this._autoAllocateChunkSize;if(void 0!==r){let t;try{t=new ArrayBuffer(r)}catch(t){return void e._errorSteps(t)}const o={buffer:t,bufferByteLength:r,byteOffset:0,byteLength:r,bytesFilled:0,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(o)}U(t,e),be(this)}[C](){if(this._pendingPullIntos.length>0){const e=this._pendingPullIntos.peek();e.readerType="none",this._pendingPullIntos=new S,this._pendingPullIntos.push(e)}}}function de(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableByteStream")&&e instanceof ReadableByteStreamController)}function fe(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_associatedReadableByteStreamController")&&e instanceof ReadableStreamBYOBRequest)}function be(e){const t=function(e){const t=e._controlledReadableByteStream;if("readable"!==t._state)return!1;if(e._closeRequested)return!1;if(!e._started)return!1;if(J(t)&&X(t)>0)return!0;if(Le(t)&&ze(t)>0)return!0;if(ke(e)>0)return!0;return!1}(e);if(!t)return;if(e._pulling)return void(e._pullAgain=!0);e._pulling=!0;b(e._pullAlgorithm(),(()=>(e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,be(e)),null)),(t=>(Pe(e,t),null)))}function he(e){Re(e),e._pendingPullIntos=new S}function _e(e,t){let r=!1;"closed"===e._state&&(r=!0);const o=pe(t);"default"===t.readerType?G(e,o,r):function(e,t,r){const o=e._reader._readIntoRequests.shift();r?o._closeSteps(t):o._chunkSteps(t)}(e,o,r)}function pe(e){const t=e.bytesFilled,r=e.elementSize;return new e.viewConstructor(e.buffer,e.byteOffset,t/r)}function me(e,t,r,o){e._queue.push({buffer:t,byteOffset:r,byteLength:o}),e._queueTotalSize+=o}function ye(e,t,r,o){let n;try{n=t.slice(r,r+o)}catch(t){throw Pe(e,t),t}me(e,n,0,o)}function ge(e,t){t.bytesFilled>0&&ye(e,t.buffer,t.byteOffset,t.bytesFilled),Ce(e)}function we(e,t){const r=t.elementSize,o=t.bytesFilled-t.bytesFilled%r,n=Math.min(e._queueTotalSize,t.byteLength-t.bytesFilled),a=t.bytesFilled+n,i=a-a%r;let l=n,s=!1;i>o&&(l=i-t.bytesFilled,s=!0);const u=e._queue;for(;l>0;){const r=u.peek(),o=Math.min(l,r.byteLength),n=t.byteOffset+t.bytesFilled;ie(t.buffer,n,r.buffer,r.byteOffset,o),r.byteLength===o?u.shift():(r.byteOffset+=o,r.byteLength-=o),e._queueTotalSize-=o,Se(e,o,t),l-=o}return s}function Se(e,t,r){r.bytesFilled+=t}function ve(e){0===e._queueTotalSize&&e._closeRequested?(Ee(e),Xt(e._controlledReadableByteStream)):be(e)}function Re(e){null!==e._byobRequest&&(e._byobRequest._associatedReadableByteStreamController=void 0,e._byobRequest._view=null,e._byobRequest=null)}function Te(e){for(;e._pendingPullIntos.length>0;){if(0===e._queueTotalSize)return;const t=e._pendingPullIntos.peek();we(e,t)&&(Ce(e),_e(e._controlledReadableByteStream,t))}}function qe(e,t){const r=e._pendingPullIntos.peek();Re(e);"closed"===e._controlledReadableByteStream._state?function(e,t){"none"===t.readerType&&Ce(e);const r=e._controlledReadableByteStream;if(Le(r))for(;ze(r)>0;)_e(r,Ce(e))}(e,r):function(e,t,r){if(Se(0,t,r),"none"===r.readerType)return ge(e,r),void Te(e);if(r.bytesFilled0){const t=r.byteOffset+r.bytesFilled;ye(e,r.buffer,t-o,o)}r.bytesFilled-=o,_e(e._controlledReadableByteStream,r),Te(e)}(e,t,r),be(e)}function Ce(e){return e._pendingPullIntos.shift()}function Ee(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0}function Pe(e,t){const r=e._controlledReadableByteStream;"readable"===r._state&&(he(e),ce(e),Ee(e),Jt(r,t))}function We(e,t){const r=e._queue.shift();e._queueTotalSize-=r.byteLength,ve(e);const o=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);t._chunkSteps(o)}function ke(e){const t=e._controlledReadableByteStream._state;return"errored"===t?null:"closed"===t?0:e._strategyHWM-e._queueTotalSize}function Oe(e,t,r){const o=Object.create(ReadableByteStreamController.prototype);let n,a,i;n=void 0!==t.start?()=>t.start(o):()=>{},a=void 0!==t.pull?()=>t.pull(o):()=>c(void 0),i=void 0!==t.cancel?e=>t.cancel(e):()=>c(void 0);const l=t.autoAllocateChunkSize;if(0===l)throw new TypeError("autoAllocateChunkSize must be greater than 0");!function(e,t,r,o,n,a,i){t._controlledReadableByteStream=e,t._pullAgain=!1,t._pulling=!1,t._byobRequest=null,t._queue=t._queueTotalSize=void 0,ce(t),t._closeRequested=!1,t._started=!1,t._strategyHWM=a,t._pullAlgorithm=o,t._cancelAlgorithm=n,t._autoAllocateChunkSize=i,t._pendingPullIntos=new S,e._readableStreamController=t,b(c(r()),(()=>(t._started=!0,be(t),null)),(e=>(Pe(t,e),null)))}(e,o,n,a,i,r,l)}function Be(e){return new TypeError(`ReadableStreamBYOBRequest.prototype.${e} can only be used on a ReadableStreamBYOBRequest`)}function Ae(e){return new TypeError(`ReadableByteStreamController.prototype.${e} can only be used on a ReadableByteStreamController`)}function je(e,t){e._reader._readIntoRequests.push(t)}function ze(e){return e._reader._readIntoRequests.length}function Le(e){const t=e._reader;return void 0!==t&&!!Fe(t)}Object.defineProperties(ReadableByteStreamController.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),n(ReadableByteStreamController.prototype.close,"close"),n(ReadableByteStreamController.prototype.enqueue,"enqueue"),n(ReadableByteStreamController.prototype.error,"error"),"symbol"==typeof e.toStringTag&&Object.defineProperty(ReadableByteStreamController.prototype,e.toStringTag,{value:"ReadableByteStreamController",configurable:!0});class ReadableStreamBYOBReader{constructor(e){if($(e,1,"ReadableStreamBYOBReader"),V(e,"First parameter"),Ut(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!de(e._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");E(this,e),this._readIntoRequests=new S}get closed(){return Fe(this)?this._closedPromise:d(De("closed"))}cancel(e){return Fe(this)?void 0===this._ownerReadableStream?d(k("cancel")):P(this,e):d(De("cancel"))}read(e){if(!Fe(this))return d(De("read"));if(!ArrayBuffer.isView(e))return d(new TypeError("view must be an array buffer view"));if(0===e.byteLength)return d(new TypeError("view must have non-zero byteLength"));if(0===e.buffer.byteLength)return d(new TypeError("view's buffer must have non-zero byteLength"));if(e.buffer,void 0===this._ownerReadableStream)return d(k("read from"));let t,r;const o=u(((e,o)=>{t=e,r=o}));return function(e,t,r){const o=e._ownerReadableStream;o._disturbed=!0,"errored"===o._state?r._errorSteps(o._storedError):function(e,t,r){const o=e._controlledReadableByteStream;let n=1;t.constructor!==DataView&&(n=t.constructor.BYTES_PER_ELEMENT);const a=t.constructor,i=t.buffer,l={buffer:i,bufferByteLength:i.byteLength,byteOffset:t.byteOffset,byteLength:t.byteLength,bytesFilled:0,elementSize:n,viewConstructor:a,readerType:"byob"};if(e._pendingPullIntos.length>0)return e._pendingPullIntos.push(l),void je(o,r);if("closed"!==o._state){if(e._queueTotalSize>0){if(we(e,l)){const t=pe(l);return ve(e),void r._chunkSteps(t)}if(e._closeRequested){const t=new TypeError("Insufficient bytes to fill elements in the given buffer");return Pe(e,t),void r._errorSteps(t)}}e._pendingPullIntos.push(l),je(o,r),be(e)}else{const e=new a(l.buffer,l.byteOffset,0);r._closeSteps(e)}}(o._readableStreamController,t,r)}(this,e,{_chunkSteps:e=>t({value:e,done:!1}),_closeSteps:e=>t({value:e,done:!0}),_errorSteps:e=>r(e)}),o}releaseLock(){if(!Fe(this))throw De("releaseLock");void 0!==this._ownerReadableStream&&function(e){W(e);const t=new TypeError("Reader was released");Ie(e,t)}(this)}}function Fe(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readIntoRequests")&&e instanceof ReadableStreamBYOBReader)}function Ie(e,t){const r=e._readIntoRequests;e._readIntoRequests=new S,r.forEach((e=>{e._errorSteps(t)}))}function De(e){return new TypeError(`ReadableStreamBYOBReader.prototype.${e} can only be used on a ReadableStreamBYOBReader`)}function $e(e,t){const{highWaterMark:r}=e;if(void 0===r)return t;if(ae(r)||r<0)throw new RangeError("Invalid highWaterMark");return r}function Me(e){const{size:t}=e;return t||(()=>1)}function Ye(e,t){F(e,t);const r=null==e?void 0:e.highWaterMark,o=null==e?void 0:e.size;return{highWaterMark:void 0===r?void 0:Y(r),size:void 0===o?void 0:Qe(o,`${t} has member 'size' that`)}}function Qe(e,t){return I(e,t),t=>Y(e(t))}function Ne(e,t,r){return I(e,r),r=>w(e,t,[r])}function He(e,t,r){return I(e,r),()=>w(e,t,[])}function xe(e,t,r){return I(e,r),r=>g(e,t,[r])}function Ve(e,t,r){return I(e,r),(r,o)=>w(e,t,[r,o])}Object.defineProperties(ReadableStreamBYOBReader.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),n(ReadableStreamBYOBReader.prototype.cancel,"cancel"),n(ReadableStreamBYOBReader.prototype.read,"read"),n(ReadableStreamBYOBReader.prototype.releaseLock,"releaseLock"),"symbol"==typeof e.toStringTag&&Object.defineProperty(ReadableStreamBYOBReader.prototype,e.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});const Ue="function"==typeof AbortController;class WritableStream{constructor(e={},t={}){void 0===e?e=null:D(e,"First parameter");const r=Ye(t,"Second parameter"),o=function(e,t){F(e,t);const r=null==e?void 0:e.abort,o=null==e?void 0:e.close,n=null==e?void 0:e.start,a=null==e?void 0:e.type,i=null==e?void 0:e.write;return{abort:void 0===r?void 0:Ne(r,e,`${t} has member 'abort' that`),close:void 0===o?void 0:He(o,e,`${t} has member 'close' that`),start:void 0===n?void 0:xe(n,e,`${t} has member 'start' that`),write:void 0===i?void 0:Ve(i,e,`${t} has member 'write' that`),type:a}}(e,"First parameter");var n;(n=this)._state="writable",n._storedError=void 0,n._writer=void 0,n._writableStreamController=void 0,n._writeRequests=new S,n._inFlightWriteRequest=void 0,n._closeRequest=void 0,n._inFlightCloseRequest=void 0,n._pendingAbortRequest=void 0,n._backpressure=!1;if(void 0!==o.type)throw new RangeError("Invalid type is specified");const a=Me(r);!function(e,t,r,o){const n=Object.create(WritableStreamDefaultController.prototype);let a,i,l,s;a=void 0!==t.start?()=>t.start(n):()=>{};i=void 0!==t.write?e=>t.write(e,n):()=>c(void 0);l=void 0!==t.close?()=>t.close():()=>c(void 0);s=void 0!==t.abort?e=>t.abort(e):()=>c(void 0);!function(e,t,r,o,n,a,i,l){t._controlledWritableStream=e,e._writableStreamController=t,t._queue=void 0,t._queueTotalSize=void 0,ce(t),t._abortReason=void 0,t._abortController=function(){if(Ue)return new AbortController}(),t._started=!1,t._strategySizeAlgorithm=l,t._strategyHWM=i,t._writeAlgorithm=o,t._closeAlgorithm=n,t._abortAlgorithm=a;const s=bt(t);nt(e,s);const u=r();b(c(u),(()=>(t._started=!0,dt(t),null)),(r=>(t._started=!0,Ze(e,r),null)))}(e,n,a,i,l,s,r,o)}(this,o,$e(r,1),a)}get locked(){if(!Ge(this))throw _t("locked");return Xe(this)}abort(e){return Ge(this)?Xe(this)?d(new TypeError("Cannot abort a stream that already has a writer")):Je(this,e):d(_t("abort"))}close(){return Ge(this)?Xe(this)?d(new TypeError("Cannot close a stream that already has a writer")):rt(this)?d(new TypeError("Cannot close an already-closing stream")):Ke(this):d(_t("close"))}getWriter(){if(!Ge(this))throw _t("getWriter");return new WritableStreamDefaultWriter(this)}}function Ge(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_writableStreamController")&&e instanceof WritableStream)}function Xe(e){return void 0!==e._writer}function Je(e,t){var r;if("closed"===e._state||"errored"===e._state)return c(void 0);e._writableStreamController._abortReason=t,null===(r=e._writableStreamController._abortController)||void 0===r||r.abort(t);const o=e._state;if("closed"===o||"errored"===o)return c(void 0);if(void 0!==e._pendingAbortRequest)return e._pendingAbortRequest._promise;let n=!1;"erroring"===o&&(n=!0,t=void 0);const a=u(((r,o)=>{e._pendingAbortRequest={_promise:void 0,_resolve:r,_reject:o,_reason:t,_wasAlreadyErroring:n}}));return e._pendingAbortRequest._promise=a,n||et(e,t),a}function Ke(e){const t=e._state;if("closed"===t||"errored"===t)return d(new TypeError(`The stream (in ${t} state) is not in the writable state and cannot be closed`));const r=u(((t,r)=>{const o={_resolve:t,_reject:r};e._closeRequest=o})),o=e._writer;var n;return void 0!==o&&e._backpressure&&"writable"===t&&Et(o),ue(n=e._writableStreamController,lt,0),dt(n),r}function Ze(e,t){"writable"!==e._state?tt(e):et(e,t)}function et(e,t){const r=e._writableStreamController;e._state="erroring",e._storedError=t;const o=e._writer;void 0!==o&&it(o,t),!function(e){if(void 0===e._inFlightWriteRequest&&void 0===e._inFlightCloseRequest)return!1;return!0}(e)&&r._started&&tt(e)}function tt(e){e._state="errored",e._writableStreamController[R]();const t=e._storedError;if(e._writeRequests.forEach((e=>{e._reject(t)})),e._writeRequests=new S,void 0===e._pendingAbortRequest)return void ot(e);const r=e._pendingAbortRequest;if(e._pendingAbortRequest=void 0,r._wasAlreadyErroring)return r._reject(t),void ot(e);b(e._writableStreamController[v](r._reason),(()=>(r._resolve(),ot(e),null)),(t=>(r._reject(t),ot(e),null)))}function rt(e){return void 0!==e._closeRequest||void 0!==e._inFlightCloseRequest}function ot(e){void 0!==e._closeRequest&&(e._closeRequest._reject(e._storedError),e._closeRequest=void 0);const t=e._writer;void 0!==t&&St(t,e._storedError)}function nt(e,t){const r=e._writer;void 0!==r&&t!==e._backpressure&&(t?function(e){Rt(e)}(r):Et(r)),e._backpressure=t}Object.defineProperties(WritableStream.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),n(WritableStream.prototype.abort,"abort"),n(WritableStream.prototype.close,"close"),n(WritableStream.prototype.getWriter,"getWriter"),"symbol"==typeof e.toStringTag&&Object.defineProperty(WritableStream.prototype,e.toStringTag,{value:"WritableStream",configurable:!0});class WritableStreamDefaultWriter{constructor(e){if($(e,1,"WritableStreamDefaultWriter"),function(e,t){if(!Ge(e))throw new TypeError(`${t} is not a WritableStream.`)}(e,"First parameter"),Xe(e))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=e,e._writer=this;const t=e._state;if("writable"===t)!rt(e)&&e._backpressure?Rt(this):qt(this),gt(this);else if("erroring"===t)Tt(this,e._storedError),gt(this);else if("closed"===t)qt(this),gt(r=this),vt(r);else{const t=e._storedError;Tt(this,t),wt(this,t)}var r}get closed(){return at(this)?this._closedPromise:d(mt("closed"))}get desiredSize(){if(!at(this))throw mt("desiredSize");if(void 0===this._ownerWritableStream)throw yt("desiredSize");return function(e){const t=e._ownerWritableStream,r=t._state;if("errored"===r||"erroring"===r)return null;if("closed"===r)return 0;return ct(t._writableStreamController)}(this)}get ready(){return at(this)?this._readyPromise:d(mt("ready"))}abort(e){return at(this)?void 0===this._ownerWritableStream?d(yt("abort")):function(e,t){return Je(e._ownerWritableStream,t)}(this,e):d(mt("abort"))}close(){if(!at(this))return d(mt("close"));const e=this._ownerWritableStream;return void 0===e?d(yt("close")):rt(e)?d(new TypeError("Cannot close an already-closing stream")):Ke(this._ownerWritableStream)}releaseLock(){if(!at(this))throw mt("releaseLock");void 0!==this._ownerWritableStream&&function(e){const t=e._ownerWritableStream,r=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");it(e,r),function(e,t){"pending"===e._closedPromiseState?St(e,t):function(e,t){wt(e,t)}(e,t)}(e,r),t._writer=void 0,e._ownerWritableStream=void 0}(this)}write(e){return at(this)?void 0===this._ownerWritableStream?d(yt("write to")):function(e,t){const r=e._ownerWritableStream,o=r._writableStreamController,n=function(e,t){try{return e._strategySizeAlgorithm(t)}catch(t){return ft(e,t),1}}(o,t);if(r!==e._ownerWritableStream)return d(yt("write to"));const a=r._state;if("errored"===a)return d(r._storedError);if(rt(r)||"closed"===a)return d(new TypeError("The stream is closing or closed and cannot be written to"));if("erroring"===a)return d(r._storedError);const i=function(e){return u(((t,r)=>{const o={_resolve:t,_reject:r};e._writeRequests.push(o)}))}(r);return function(e,t,r){try{ue(e,t,r)}catch(t){return void ft(e,t)}const o=e._controlledWritableStream;if(!rt(o)&&"writable"===o._state){nt(o,bt(e))}dt(e)}(o,t,n),i}(this,e):d(mt("write"))}}function at(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_ownerWritableStream")&&e instanceof WritableStreamDefaultWriter)}function it(e,t){"pending"===e._readyPromiseState?Ct(e,t):function(e,t){Tt(e,t)}(e,t)}Object.defineProperties(WritableStreamDefaultWriter.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),n(WritableStreamDefaultWriter.prototype.abort,"abort"),n(WritableStreamDefaultWriter.prototype.close,"close"),n(WritableStreamDefaultWriter.prototype.releaseLock,"releaseLock"),n(WritableStreamDefaultWriter.prototype.write,"write"),"symbol"==typeof e.toStringTag&&Object.defineProperty(WritableStreamDefaultWriter.prototype,e.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});const lt={};class WritableStreamDefaultController{constructor(){throw new TypeError("Illegal constructor")}get abortReason(){if(!st(this))throw pt("abortReason");return this._abortReason}get signal(){if(!st(this))throw pt("signal");if(void 0===this._abortController)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal}error(e){if(!st(this))throw pt("error");"writable"===this._controlledWritableStream._state&&ht(this,e)}[v](e){const t=this._abortAlgorithm(e);return ut(this),t}[R](){ce(this)}}function st(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledWritableStream")&&e instanceof WritableStreamDefaultController)}function ut(e){e._writeAlgorithm=void 0,e._closeAlgorithm=void 0,e._abortAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function ct(e){return e._strategyHWM-e._queueTotalSize}function dt(e){const t=e._controlledWritableStream;if(!e._started)return;if(void 0!==t._inFlightWriteRequest)return;if("erroring"===t._state)return void tt(t);if(0===e._queue.length)return;const r=e._queue.peek().value;r===lt?function(e){const t=e._controlledWritableStream;(function(e){e._inFlightCloseRequest=e._closeRequest,e._closeRequest=void 0})(t),se(e);const r=e._closeAlgorithm();ut(e),b(r,(()=>(function(e){e._inFlightCloseRequest._resolve(void 0),e._inFlightCloseRequest=void 0,"erroring"===e._state&&(e._storedError=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._resolve(),e._pendingAbortRequest=void 0)),e._state="closed";const t=e._writer;void 0!==t&&vt(t)}(t),null)),(e=>(function(e,t){e._inFlightCloseRequest._reject(t),e._inFlightCloseRequest=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._reject(t),e._pendingAbortRequest=void 0),Ze(e,t)}(t,e),null)))}(e):function(e,t){const r=e._controlledWritableStream;!function(e){e._inFlightWriteRequest=e._writeRequests.shift()}(r);b(e._writeAlgorithm(t),(()=>{!function(e){e._inFlightWriteRequest._resolve(void 0),e._inFlightWriteRequest=void 0}(r);const t=r._state;if(se(e),!rt(r)&&"writable"===t){const t=bt(e);nt(r,t)}return dt(e),null}),(t=>("writable"===r._state&&ut(e),function(e,t){e._inFlightWriteRequest._reject(t),e._inFlightWriteRequest=void 0,Ze(e,t)}(r,t),null)))}(e,r)}function ft(e,t){"writable"===e._controlledWritableStream._state&&ht(e,t)}function bt(e){return ct(e)<=0}function ht(e,t){const r=e._controlledWritableStream;ut(e),et(r,t)}function _t(e){return new TypeError(`WritableStream.prototype.${e} can only be used on a WritableStream`)}function pt(e){return new TypeError(`WritableStreamDefaultController.prototype.${e} can only be used on a WritableStreamDefaultController`)}function mt(e){return new TypeError(`WritableStreamDefaultWriter.prototype.${e} can only be used on a WritableStreamDefaultWriter`)}function yt(e){return new TypeError("Cannot "+e+" a stream using a released writer")}function gt(e){e._closedPromise=u(((t,r)=>{e._closedPromise_resolve=t,e._closedPromise_reject=r,e._closedPromiseState="pending"}))}function wt(e,t){gt(e),St(e,t)}function St(e,t){void 0!==e._closedPromise_reject&&(m(e._closedPromise),e._closedPromise_reject(t),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="rejected")}function vt(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="resolved")}function Rt(e){e._readyPromise=u(((t,r)=>{e._readyPromise_resolve=t,e._readyPromise_reject=r})),e._readyPromiseState="pending"}function Tt(e,t){Rt(e),Ct(e,t)}function qt(e){Rt(e),Et(e)}function Ct(e,t){void 0!==e._readyPromise_reject&&(m(e._readyPromise),e._readyPromise_reject(t),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="rejected")}function Et(e){void 0!==e._readyPromise_resolve&&(e._readyPromise_resolve(void 0),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="fulfilled")}Object.defineProperties(WritableStreamDefaultController.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),"symbol"==typeof e.toStringTag&&Object.defineProperty(WritableStreamDefaultController.prototype,e.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});const Pt="undefined"!=typeof DOMException?DOMException:void 0;const Wt=function(e){if("function"!=typeof e&&"object"!=typeof e)return!1;try{return new e,!0}catch(e){return!1}}(Pt)?Pt:function(){const e=function(e,t){this.message=e||"",this.name=t||"Error",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)};return e.prototype=Object.create(Error.prototype),Object.defineProperty(e.prototype,"constructor",{value:e,writable:!0,configurable:!0}),e}();function kt(e,t,r,o,n,a){const i=e.getReader(),l=t.getWriter();Vt(e)&&(e._disturbed=!0);let s,_,g,w=!1,S=!1,v="readable",R="writable",T=!1,q=!1;const C=u((e=>{g=e}));let E=Promise.resolve(void 0);return u(((P,W)=>{let k;function O(){if(w)return;const e=u(((e,t)=>{!function r(o){o?e():f(function(){if(w)return c(!0);return f(l.ready,(()=>f(i.read(),(e=>!!e.done||(E=l.write(e.value),m(E),!1)))))}(),r,t)}(!1)}));m(e)}function B(){return v="closed",r?L():z((()=>(Ge(t)&&(T=rt(t),R=t._state),T||"closed"===R?c(void 0):"erroring"===R||"errored"===R?d(_):(T=!0,l.close()))),!1,void 0),null}function A(e){return w||(v="errored",s=e,o?L(!0,e):z((()=>l.abort(e)),!0,e)),null}function j(e){return S||(R="errored",_=e,n?L(!0,e):z((()=>i.cancel(e)),!0,e)),null}if(void 0!==a&&(k=()=>{const e=void 0!==a.reason?a.reason:new Wt("Aborted","AbortError"),t=[];o||t.push((()=>"writable"===R?l.abort(e):c(void 0))),n||t.push((()=>"readable"===v?i.cancel(e):c(void 0))),z((()=>Promise.all(t.map((e=>e())))),!0,e)},a.aborted?k():a.addEventListener("abort",k)),Vt(e)&&(v=e._state,s=e._storedError),Ge(t)&&(R=t._state,_=t._storedError,T=rt(t)),Vt(e)&&Ge(t)&&(q=!0,g()),"errored"===v)A(s);else if("erroring"===R||"errored"===R)j(_);else if("closed"===v)B();else if(T||"closed"===R){const e=new TypeError("the destination writable stream closed before all data could be piped to it");n?L(!0,e):z((()=>i.cancel(e)),!0,e)}function z(e,t,r){function o(){return"writable"!==R||T?n():h(function(){let e;return c(function t(){if(e!==E)return e=E,p(E,t,t)}())}(),n),null}function n(){return e?b(e(),(()=>F(t,r)),(e=>F(!0,e))):F(t,r),null}w||(w=!0,q?o():h(C,o))}function L(e,t){z(void 0,e,t)}function F(e,t){return S=!0,l.releaseLock(),i.releaseLock(),void 0!==a&&a.removeEventListener("abort",k),e?W(t):P(void 0),null}w||(b(i.closed,B,A),b(l.closed,(function(){return S||(R="closed"),null}),j)),q?O():y((()=>{q=!0,g(),O()}))}))}function Ot(e,t){return function(e){try{return e.getReader({mode:"byob"}).releaseLock(),!0}catch(e){return!1}}(e)?function(e){let t,r,o,n,a,i=e.getReader(),l=!1,s=!1,d=!1,f=!1,h=!1,p=!1;const m=u((e=>{a=e}));function y(e){_(e.closed,(t=>(e!==i||(o.error(t),n.error(t),h&&p||a(void 0)),null)))}function g(){l&&(i.releaseLock(),i=e.getReader(),y(i),l=!1),b(i.read(),(e=>{var t,r;if(d=!1,f=!1,e.done)return h||o.close(),p||n.close(),null===(t=o.byobRequest)||void 0===t||t.respond(0),null===(r=n.byobRequest)||void 0===r||r.respond(0),h&&p||a(void 0),null;const l=e.value,u=l;let c=l;if(!h&&!p)try{c=le(l)}catch(e){return o.error(e),n.error(e),a(i.cancel(e)),null}return h||o.enqueue(u),p||n.enqueue(c),s=!1,d?S():f&&v(),null}),(()=>(s=!1,null)))}function w(t,r){l||(i.releaseLock(),i=e.getReader({mode:"byob"}),y(i),l=!0);const u=r?n:o,c=r?o:n;b(i.read(t),(e=>{var t;d=!1,f=!1;const o=r?p:h,n=r?h:p;if(e.done){o||u.close(),n||c.close();const r=e.value;return void 0!==r&&(o||u.byobRequest.respondWithNewView(r),n||null===(t=c.byobRequest)||void 0===t||t.respond(0)),o&&n||a(void 0),null}const l=e.value;if(n)o||u.byobRequest.respondWithNewView(l);else{let e;try{e=le(l)}catch(e){return u.error(e),c.error(e),a(i.cancel(e)),null}o||u.byobRequest.respondWithNewView(l),c.enqueue(e)}return s=!1,d?S():f&&v(),null}),(()=>(s=!1,null)))}function S(){if(s)return d=!0,c(void 0);s=!0;const e=o.byobRequest;return null===e?g():w(e.view,!1),c(void 0)}function v(){if(s)return f=!0,c(void 0);s=!0;const e=n.byobRequest;return null===e?g():w(e.view,!0),c(void 0)}function R(e){if(h=!0,t=e,p){const e=[t,r],o=i.cancel(e);a(o)}return m}function T(e){if(p=!0,r=e,h){const e=[t,r],o=i.cancel(e);a(o)}return m}const q=new ReadableStream({type:"bytes",start(e){o=e},pull:S,cancel:R}),C=new ReadableStream({type:"bytes",start(e){n=e},pull:v,cancel:T});return y(i),[q,C]}(e):function(e,t){const r=e.getReader();let o,n,a,i,l,s=!1,d=!1,f=!1,h=!1;const p=u((e=>{l=e}));function m(){return s?(d=!0,c(void 0)):(s=!0,b(r.read(),(e=>{if(d=!1,e.done)return f||a.close(),h||i.close(),f&&h||l(void 0),null;const t=e.value,r=t,o=t;return f||a.enqueue(r),h||i.enqueue(o),s=!1,d&&m(),null}),(()=>(s=!1,null))),c(void 0))}function y(e){if(f=!0,o=e,h){const e=[o,n],t=r.cancel(e);l(t)}return p}function g(e){if(h=!0,n=e,f){const e=[o,n],t=r.cancel(e);l(t)}return p}const w=new ReadableStream({start(e){a=e},pull:m,cancel:y}),S=new ReadableStream({start(e){i=e},pull:m,cancel:g});return _(r.closed,(e=>(a.error(e),i.error(e),f&&h||l(void 0),null))),[w,S]}(e)}class ReadableStreamDefaultController{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Bt(this))throw Dt("desiredSize");return Lt(this)}close(){if(!Bt(this))throw Dt("close");if(!Ft(this))throw new TypeError("The stream is not in a state that permits close");!function(e){if(!Ft(e))return;const t=e._controlledReadableStream;e._closeRequested=!0,0===e._queue.length&&(jt(e),Xt(t))}(this)}enqueue(e){if(!Bt(this))throw Dt("enqueue");if(!Ft(this))throw new TypeError("The stream is not in a state that permits enqueue");return function(e,t){if(!Ft(e))return;const r=e._controlledReadableStream;if(Ut(r)&&X(r)>0)G(r,t,!1);else{let r;try{r=e._strategySizeAlgorithm(t)}catch(t){throw zt(e,t),t}try{ue(e,t,r)}catch(t){throw zt(e,t),t}}At(e)}(this,e)}error(e){if(!Bt(this))throw Dt("error");zt(this,e)}[T](e){ce(this);const t=this._cancelAlgorithm(e);return jt(this),t}[q](e){const t=this._controlledReadableStream;if(this._queue.length>0){const r=se(this);this._closeRequested&&0===this._queue.length?(jt(this),Xt(t)):At(this),e._chunkSteps(r)}else U(t,e),At(this)}[C](){}}function Bt(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableStream")&&e instanceof ReadableStreamDefaultController)}function At(e){const t=function(e){const t=e._controlledReadableStream;if(!Ft(e))return!1;if(!e._started)return!1;if(Ut(t)&&X(t)>0)return!0;if(Lt(e)>0)return!0;return!1}(e);if(!t)return;if(e._pulling)return void(e._pullAgain=!0);e._pulling=!0;b(e._pullAlgorithm(),(()=>(e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,At(e)),null)),(t=>(zt(e,t),null)))}function jt(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function zt(e,t){const r=e._controlledReadableStream;"readable"===r._state&&(ce(e),jt(e),Jt(r,t))}function Lt(e){const t=e._controlledReadableStream._state;return"errored"===t?null:"closed"===t?0:e._strategyHWM-e._queueTotalSize}function Ft(e){return!e._closeRequested&&"readable"===e._controlledReadableStream._state}function It(e,t,r,o){const n=Object.create(ReadableStreamDefaultController.prototype);let a,i,l;a=void 0!==t.start?()=>t.start(n):()=>{},i=void 0!==t.pull?()=>t.pull(n):()=>c(void 0),l=void 0!==t.cancel?e=>t.cancel(e):()=>c(void 0),function(e,t,r,o,n,a,i){t._controlledReadableStream=e,t._queue=void 0,t._queueTotalSize=void 0,ce(t),t._started=!1,t._closeRequested=!1,t._pullAgain=!1,t._pulling=!1,t._strategySizeAlgorithm=i,t._strategyHWM=a,t._pullAlgorithm=o,t._cancelAlgorithm=n,e._readableStreamController=t,b(c(r()),(()=>(t._started=!0,At(t),null)),(e=>(zt(t,e),null)))}(e,n,a,i,l,r,o)}function Dt(e){return new TypeError(`ReadableStreamDefaultController.prototype.${e} can only be used on a ReadableStreamDefaultController`)}function $t(e,t,r){return I(e,r),r=>w(e,t,[r])}function Mt(e,t,r){return I(e,r),r=>w(e,t,[r])}function Yt(e,t,r){return I(e,r),r=>g(e,t,[r])}function Qt(e,t){if("bytes"!==(e=`${e}`))throw new TypeError(`${t} '${e}' is not a valid enumeration value for ReadableStreamType`);return e}function Nt(e,t){if("byob"!==(e=`${e}`))throw new TypeError(`${t} '${e}' is not a valid enumeration value for ReadableStreamReaderMode`);return e}function Ht(e,t){F(e,t);const r=null==e?void 0:e.preventAbort,o=null==e?void 0:e.preventCancel,n=null==e?void 0:e.preventClose,a=null==e?void 0:e.signal;return void 0!==a&&function(e,t){if(!function(e){if("object"!=typeof e||null===e)return!1;try{return"boolean"==typeof e.aborted}catch(e){return!1}}(e))throw new TypeError(`${t} is not an AbortSignal.`)}(a,`${t} has member 'signal' that`),{preventAbort:Boolean(r),preventCancel:Boolean(o),preventClose:Boolean(n),signal:a}}function xt(e,t){F(e,t);const r=null==e?void 0:e.readable;M(r,"readable","ReadableWritablePair"),function(e,t){if(!H(e))throw new TypeError(`${t} is not a ReadableStream.`)}(r,`${t} has member 'readable' that`);const o=null==e?void 0:e.writable;return M(o,"writable","ReadableWritablePair"),function(e,t){if(!x(e))throw new TypeError(`${t} is not a WritableStream.`)}(o,`${t} has member 'writable' that`),{readable:r,writable:o}}Object.defineProperties(ReadableStreamDefaultController.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),n(ReadableStreamDefaultController.prototype.close,"close"),n(ReadableStreamDefaultController.prototype.enqueue,"enqueue"),n(ReadableStreamDefaultController.prototype.error,"error"),"symbol"==typeof e.toStringTag&&Object.defineProperty(ReadableStreamDefaultController.prototype,e.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});class ReadableStream{constructor(e={},t={}){void 0===e?e=null:D(e,"First parameter");const r=Ye(t,"Second parameter"),o=function(e,t){F(e,t);const r=e,o=null==r?void 0:r.autoAllocateChunkSize,n=null==r?void 0:r.cancel,a=null==r?void 0:r.pull,i=null==r?void 0:r.start,l=null==r?void 0:r.type;return{autoAllocateChunkSize:void 0===o?void 0:N(o,`${t} has member 'autoAllocateChunkSize' that`),cancel:void 0===n?void 0:$t(n,r,`${t} has member 'cancel' that`),pull:void 0===a?void 0:Mt(a,r,`${t} has member 'pull' that`),start:void 0===i?void 0:Yt(i,r,`${t} has member 'start' that`),type:void 0===l?void 0:Qt(l,`${t} has member 'type' that`)}}(e,"First parameter");var n;if((n=this)._state="readable",n._reader=void 0,n._storedError=void 0,n._disturbed=!1,"bytes"===o.type){if(void 0!==r.size)throw new RangeError("The strategy for a byte stream cannot have a size function");Oe(this,o,$e(r,0))}else{const e=Me(r);It(this,o,$e(r,1),e)}}get locked(){if(!Vt(this))throw Kt("locked");return Ut(this)}cancel(e){return Vt(this)?Ut(this)?d(new TypeError("Cannot cancel a stream that already has a reader")):Gt(this,e):d(Kt("cancel"))}getReader(e){if(!Vt(this))throw Kt("getReader");return void 0===function(e,t){F(e,t);const r=null==e?void 0:e.mode;return{mode:void 0===r?void 0:Nt(r,`${t} has member 'mode' that`)}}(e,"First parameter").mode?new ReadableStreamDefaultReader(this):function(e){return new ReadableStreamBYOBReader(e)}(this)}pipeThrough(e,t={}){if(!H(this))throw Kt("pipeThrough");$(e,1,"pipeThrough");const r=xt(e,"First parameter"),o=Ht(t,"Second parameter");if(this.locked)throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(r.writable.locked)throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");return m(kt(this,r.writable,o.preventClose,o.preventAbort,o.preventCancel,o.signal)),r.readable}pipeTo(e,t={}){if(!H(this))return d(Kt("pipeTo"));if(void 0===e)return d("Parameter 1 is required in 'pipeTo'.");if(!x(e))return d(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let r;try{r=Ht(t,"Second parameter")}catch(e){return d(e)}return this.locked?d(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):e.locked?d(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):kt(this,e,r.preventClose,r.preventAbort,r.preventCancel,r.signal)}tee(){if(!H(this))throw Kt("tee");if(this.locked)throw new TypeError("Cannot tee a stream that already has a reader");return Ot(this)}values(e){if(!H(this))throw Kt("values");return function(e,t){const r=e.getReader(),o=new te(r,t),n=Object.create(re);return n._asyncIteratorImpl=o,n}(this,function(e,t){F(e,t);const r=null==e?void 0:e.preventCancel;return{preventCancel:Boolean(r)}}(e,"First parameter").preventCancel)}}function Vt(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readableStreamController")&&e instanceof ReadableStream)}function Ut(e){return void 0!==e._reader}function Gt(e,r){if(e._disturbed=!0,"closed"===e._state)return c(void 0);if("errored"===e._state)return d(e._storedError);Xt(e);const o=e._reader;if(void 0!==o&&Fe(o)){const e=o._readIntoRequests;o._readIntoRequests=new S,e.forEach((e=>{e._closeSteps(void 0)}))}return p(e._readableStreamController[T](r),t)}function Xt(e){e._state="closed";const t=e._reader;if(void 0!==t&&(j(t),K(t))){const e=t._readRequests;t._readRequests=new S,e.forEach((e=>{e._closeSteps()}))}}function Jt(e,t){e._state="errored",e._storedError=t;const r=e._reader;void 0!==r&&(A(r,t),K(r)?Z(r,t):Ie(r,t))}function Kt(e){return new TypeError(`ReadableStream.prototype.${e} can only be used on a ReadableStream`)}function Zt(e,t){F(e,t);const r=null==e?void 0:e.highWaterMark;return M(r,"highWaterMark","QueuingStrategyInit"),{highWaterMark:Y(r)}}Object.defineProperties(ReadableStream.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),n(ReadableStream.prototype.cancel,"cancel"),n(ReadableStream.prototype.getReader,"getReader"),n(ReadableStream.prototype.pipeThrough,"pipeThrough"),n(ReadableStream.prototype.pipeTo,"pipeTo"),n(ReadableStream.prototype.tee,"tee"),n(ReadableStream.prototype.values,"values"),"symbol"==typeof e.toStringTag&&Object.defineProperty(ReadableStream.prototype,e.toStringTag,{value:"ReadableStream",configurable:!0}),"symbol"==typeof e.asyncIterator&&Object.defineProperty(ReadableStream.prototype,e.asyncIterator,{value:ReadableStream.prototype.values,writable:!0,configurable:!0});const er=e=>e.byteLength;n(er,"size");class ByteLengthQueuingStrategy{constructor(e){$(e,1,"ByteLengthQueuingStrategy"),e=Zt(e,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=e.highWaterMark}get highWaterMark(){if(!rr(this))throw tr("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!rr(this))throw tr("size");return er}}function tr(e){return new TypeError(`ByteLengthQueuingStrategy.prototype.${e} can only be used on a ByteLengthQueuingStrategy`)}function rr(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_byteLengthQueuingStrategyHighWaterMark")&&e instanceof ByteLengthQueuingStrategy)}Object.defineProperties(ByteLengthQueuingStrategy.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof e.toStringTag&&Object.defineProperty(ByteLengthQueuingStrategy.prototype,e.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});const or=()=>1;n(or,"size");class CountQueuingStrategy{constructor(e){$(e,1,"CountQueuingStrategy"),e=Zt(e,"First parameter"),this._countQueuingStrategyHighWaterMark=e.highWaterMark}get highWaterMark(){if(!ar(this))throw nr("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!ar(this))throw nr("size");return or}}function nr(e){return new TypeError(`CountQueuingStrategy.prototype.${e} can only be used on a CountQueuingStrategy`)}function ar(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_countQueuingStrategyHighWaterMark")&&e instanceof CountQueuingStrategy)}function ir(e,t,r){return I(e,r),r=>w(e,t,[r])}function lr(e,t,r){return I(e,r),r=>g(e,t,[r])}function sr(e,t,r){return I(e,r),(r,o)=>w(e,t,[r,o])}Object.defineProperties(CountQueuingStrategy.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof e.toStringTag&&Object.defineProperty(CountQueuingStrategy.prototype,e.toStringTag,{value:"CountQueuingStrategy",configurable:!0});class TransformStream{constructor(e={},t={},r={}){void 0===e&&(e=null);const o=Ye(t,"Second parameter"),n=Ye(r,"Third parameter"),a=function(e,t){F(e,t);const r=null==e?void 0:e.flush,o=null==e?void 0:e.readableType,n=null==e?void 0:e.start,a=null==e?void 0:e.transform,i=null==e?void 0:e.writableType;return{flush:void 0===r?void 0:ir(r,e,`${t} has member 'flush' that`),readableType:o,start:void 0===n?void 0:lr(n,e,`${t} has member 'start' that`),transform:void 0===a?void 0:sr(a,e,`${t} has member 'transform' that`),writableType:i}}(e,"First parameter");if(void 0!==a.readableType)throw new RangeError("Invalid readableType specified");if(void 0!==a.writableType)throw new RangeError("Invalid writableType specified");const i=$e(n,0),l=Me(n),s=$e(o,1),f=Me(o);let b;!function(e,t,r,o,n,a){function i(){return t}function l(t){return function(e,t){const r=e._transformStreamController;if(e._backpressure){return p(e._backpressureChangePromise,(()=>{if("erroring"===(Ge(e._writable)?e._writable._state:e._writableState))throw Ge(e._writable)?e._writable._storedError:e._writableStoredError;return pr(r,t)}))}return pr(r,t)}(e,t)}function s(t){return function(e,t){return cr(e,t),c(void 0)}(e,t)}function u(){return function(e){const t=e._transformStreamController,r=t._flushAlgorithm();return hr(t),p(r,(()=>{if("errored"===e._readableState)throw e._readableStoredError;gr(e)&&wr(e)}),(t=>{throw cr(e,t),e._readableStoredError}))}(e)}function d(){return function(e){return fr(e,!1),e._backpressureChangePromise}(e)}function f(t){return dr(e,t),c(void 0)}e._writableState="writable",e._writableStoredError=void 0,e._writableHasInFlightOperation=!1,e._writableStarted=!1,e._writable=function(e,t,r,o,n,a,i){return new WritableStream({start(r){e._writableController=r;try{const t=r.signal;void 0!==t&&t.addEventListener("abort",(()=>{"writable"===e._writableState&&(e._writableState="erroring",t.reason&&(e._writableStoredError=t.reason))}))}catch(e){}return p(t(),(()=>(e._writableStarted=!0,Cr(e),null)),(t=>{throw e._writableStarted=!0,Rr(e,t),t}))},write:t=>(function(e){e._writableHasInFlightOperation=!0}(e),p(r(t),(()=>(function(e){e._writableHasInFlightOperation=!1}(e),Cr(e),null)),(t=>{throw function(e,t){e._writableHasInFlightOperation=!1,Rr(e,t)}(e,t),t}))),close:()=>(function(e){e._writableHasInFlightOperation=!0}(e),p(o(),(()=>(function(e){e._writableHasInFlightOperation=!1;"erroring"===e._writableState&&(e._writableStoredError=void 0);e._writableState="closed"}(e),null)),(t=>{throw function(e,t){e._writableHasInFlightOperation=!1,e._writableState,Rr(e,t)}(e,t),t}))),abort:t=>(e._writableState="errored",e._writableStoredError=t,n(t))},{highWaterMark:a,size:i})}(e,i,l,u,s,r,o),e._readableState="readable",e._readableStoredError=void 0,e._readableCloseRequested=!1,e._readablePulling=!1,e._readable=function(e,t,r,o,n,a){return new ReadableStream({start:r=>(e._readableController=r,t().catch((t=>{Sr(e,t)}))),pull:()=>(e._readablePulling=!0,r().catch((t=>{Sr(e,t)}))),cancel:t=>(e._readableState="closed",o(t))},{highWaterMark:n,size:a})}(e,i,d,f,n,a),e._backpressure=void 0,e._backpressureChangePromise=void 0,e._backpressureChangePromise_resolve=void 0,fr(e,!0),e._transformStreamController=void 0}(this,u((e=>{b=e})),s,f,i,l),function(e,t){const r=Object.create(TransformStreamDefaultController.prototype);let o,n;o=void 0!==t.transform?e=>t.transform(e,r):e=>{try{return _r(r,e),c(void 0)}catch(e){return d(e)}};n=void 0!==t.flush?()=>t.flush(r):()=>c(void 0);!function(e,t,r,o){t._controlledTransformStream=e,e._transformStreamController=t,t._transformAlgorithm=r,t._flushAlgorithm=o}(e,r,o,n)}(this,a),void 0!==a.start?b(a.start(this._transformStreamController)):b(void 0)}get readable(){if(!ur(this))throw yr("readable");return this._readable}get writable(){if(!ur(this))throw yr("writable");return this._writable}}function ur(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_transformStreamController")&&e instanceof TransformStream)}function cr(e,t){Sr(e,t),dr(e,t)}function dr(e,t){hr(e._transformStreamController),function(e,t){e._writableController.error(t);"writable"===e._writableState&&Tr(e,t)}(e,t),e._backpressure&&fr(e,!1)}function fr(e,t){void 0!==e._backpressureChangePromise&&e._backpressureChangePromise_resolve(),e._backpressureChangePromise=u((t=>{e._backpressureChangePromise_resolve=t})),e._backpressure=t}Object.defineProperties(TransformStream.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),"symbol"==typeof e.toStringTag&&Object.defineProperty(TransformStream.prototype,e.toStringTag,{value:"TransformStream",configurable:!0});class TransformStreamDefaultController{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!br(this))throw mr("desiredSize");return vr(this._controlledTransformStream)}enqueue(e){if(!br(this))throw mr("enqueue");_r(this,e)}error(e){if(!br(this))throw mr("error");var t;t=e,cr(this._controlledTransformStream,t)}terminate(){if(!br(this))throw mr("terminate");!function(e){const t=e._controlledTransformStream;gr(t)&&wr(t);const r=new TypeError("TransformStream terminated");dr(t,r)}(this)}}function br(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledTransformStream")&&e instanceof TransformStreamDefaultController)}function hr(e){e._transformAlgorithm=void 0,e._flushAlgorithm=void 0}function _r(e,t){const r=e._controlledTransformStream;if(!gr(r))throw new TypeError("Readable side is not in a state that permits enqueue");try{!function(e,t){e._readablePulling=!1;try{e._readableController.enqueue(t)}catch(t){throw Sr(e,t),t}}(r,t)}catch(e){throw dr(r,e),r._readableStoredError}const o=function(e){return!function(e){if(!gr(e))return!1;if(e._readablePulling)return!0;if(vr(e)>0)return!0;return!1}(e)}(r);o!==r._backpressure&&fr(r,!0)}function pr(e,t){return p(e._transformAlgorithm(t),void 0,(t=>{throw cr(e._controlledTransformStream,t),t}))}function mr(e){return new TypeError(`TransformStreamDefaultController.prototype.${e} can only be used on a TransformStreamDefaultController`)}function yr(e){return new TypeError(`TransformStream.prototype.${e} can only be used on a TransformStream`)}function gr(e){return!e._readableCloseRequested&&"readable"===e._readableState}function wr(e){e._readableState="closed",e._readableCloseRequested=!0,e._readableController.close()}function Sr(e,t){"readable"===e._readableState&&(e._readableState="errored",e._readableStoredError=t),e._readableController.error(t)}function vr(e){return e._readableController.desiredSize}function Rr(e,t){"writable"!==e._writableState?qr(e):Tr(e,t)}function Tr(e,t){e._writableState="erroring",e._writableStoredError=t,!function(e){return e._writableHasInFlightOperation}(e)&&e._writableStarted&&qr(e)}function qr(e){e._writableState="errored"}function Cr(e){"erroring"===e._writableState&&qr(e)}Object.defineProperties(TransformStreamDefaultController.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),n(TransformStreamDefaultController.prototype.enqueue,"enqueue"),n(TransformStreamDefaultController.prototype.error,"error"),n(TransformStreamDefaultController.prototype.terminate,"terminate"),"symbol"==typeof e.toStringTag&&Object.defineProperty(TransformStreamDefaultController.prototype,e.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});export{ByteLengthQueuingStrategy,CountQueuingStrategy,ReadableByteStreamController,ReadableStream,ReadableStreamBYOBReader,ReadableStreamBYOBRequest,ReadableStreamDefaultController,ReadableStreamDefaultReader,TransformStream,TransformStreamDefaultController,WritableStream,WritableStreamDefaultController,WritableStreamDefaultWriter}; diff --git a/backend/node_modules/formdata-node/node_modules/web-streams-polyfill/es5/package.json b/backend/node_modules/formdata-node/node_modules/web-streams-polyfill/es5/package.json new file mode 100644 index 0000000000000000000000000000000000000000..1334ba91c7567c8800f21462532de3a5bbd33c2f --- /dev/null +++ b/backend/node_modules/formdata-node/node_modules/web-streams-polyfill/es5/package.json @@ -0,0 +1,6 @@ +{ + "name": "web-streams-polyfill", + "main": "../dist/ponyfill.es5.js", + "module": "../dist/ponyfill.es5.mjs", + "types": "../types/ponyfill.d.ts" +} diff --git a/backend/node_modules/formdata-node/node_modules/web-streams-polyfill/package.json b/backend/node_modules/formdata-node/node_modules/web-streams-polyfill/package.json new file mode 100644 index 0000000000000000000000000000000000000000..213ddaebdae0c2af6f091838dbd2c4a4a53ff606 --- /dev/null +++ b/backend/node_modules/formdata-node/node_modules/web-streams-polyfill/package.json @@ -0,0 +1,101 @@ +{ + "name": "web-streams-polyfill", + "version": "4.0.0-beta.3", + "description": "Web Streams, based on the WHATWG spec reference implementation", + "main": "dist/ponyfill.js", + "module": "dist/ponyfill.mjs", + "types": "types/ponyfill.d.ts", + "exports": { + ".": { + "types": "./types/ponyfill.d.ts", + "import": "./dist/ponyfill.mjs", + "require": "./dist/ponyfill.js" + }, + "./es5": { + "types": "./types/ponyfill.d.ts", + "import": "./dist/ponyfill.es5.mjs", + "require": "./dist/ponyfill.es5.js" + }, + "./polyfill": { + "types": "./types/polyfill.d.ts", + "default": "./dist/polyfill.js" + }, + "./polyfill/es5": { + "types": "./types/polyfill.d.ts", + "default": "./dist/polyfill.es5.js" + }, + "./dist/*": "./dist/*", + "./types/*": "./types/*", + "./package": "./package.json", + "./package.json": "./package.json" + }, + "scripts": { + "test": "npm run test:types && npm run test:unit && npm run test:wpt && npm run test:bundler", + "test:wpt": "npm run test:wpt:node && npm run test:wpt:chromium && npm run test:wpt:firefox", + "test:wpt:node": "node --expose_gc ./test/wpt/node/run.js", + "test:wpt:chromium": "node ./test/wpt/browser/run.js --browser chromium", + "test:wpt:firefox": "node ./test/wpt/browser/run.js --browser firefox", + "test:bundler": "npm run test:bundler:rollup && npm run test:bundler:webpack", + "test:bundler:rollup": "cd test/rollup && npm ci && npm test", + "test:bundler:webpack": "cd test/webpack && npm ci && npm test", + "test:types": "tsc -p ./test/types/tsconfig.json", + "test:unit": "node --experimental-import-meta-resolve ./node_modules/jasmine/bin/jasmine.js --config=test/unit/jasmine.json", + "lint": "eslint \"src/**/*.ts\"", + "build": "npm run build:bundle && npm run build:types", + "build:bundle": "rollup -c", + "build:types": "tsc --project . --emitDeclarationOnly --declarationDir ./lib && api-extractor run", + "accept:types": "tsc --project . --emitDeclarationOnly --declarationDir ./lib && api-extractor run --local", + "prepare": "npm run build" + }, + "files": [ + "dist", + "es5", + "polyfill", + "types" + ], + "engines": { + "node": ">= 14" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/MattiasBuelens/web-streams-polyfill.git" + }, + "keywords": [ + "streams", + "whatwg", + "polyfill" + ], + "author": "Mattias Buelens ", + "contributors": [ + "Diwank Singh " + ], + "license": "MIT", + "bugs": { + "url": "https://github.com/MattiasBuelens/web-streams-polyfill/issues" + }, + "homepage": "https://github.com/MattiasBuelens/web-streams-polyfill#readme", + "devDependencies": { + "@microsoft/api-extractor": "^7.21.2", + "@rollup/plugin-inject": "^4.0.4", + "@rollup/plugin-replace": "^4.0.0", + "@rollup/plugin-strip": "^2.1.0", + "@rollup/plugin-typescript": "^8.3.1", + "@types/jasmine": "^4.0.2", + "@types/node": "^14.18.12", + "@typescript-eslint/eslint-plugin": "^5.19.0", + "@typescript-eslint/parser": "^5.19.0", + "@ungap/promise-all-settled": "^1.1.2", + "abort-controller": "^3.0.0", + "eslint": "^8.13.0", + "jasmine": "^4.0.2", + "micromatch": "^4.0.5", + "minimist": "^1.2.6", + "playwright": "^1.20.2", + "recursive-readdir": "^2.2.2", + "rollup": "^2.70.1", + "rollup-plugin-terser": "^7.0.2", + "tslib": "^2.3.1", + "typescript": "^4.7.0-beta", + "wpt-runner": "^4.1.0" + } +} diff --git a/backend/node_modules/formdata-node/node_modules/web-streams-polyfill/polyfill/es5/package.json b/backend/node_modules/formdata-node/node_modules/web-streams-polyfill/polyfill/es5/package.json new file mode 100644 index 0000000000000000000000000000000000000000..20f00bf287fcec4e420a1c9123db1965f6926ea2 --- /dev/null +++ b/backend/node_modules/formdata-node/node_modules/web-streams-polyfill/polyfill/es5/package.json @@ -0,0 +1,5 @@ +{ + "name": "web-streams-polyfill", + "main": "../../dist/polyfill.es5.js", + "types": "../../types/polyfill.d.ts" +} diff --git a/backend/node_modules/formdata-node/node_modules/web-streams-polyfill/polyfill/package.json b/backend/node_modules/formdata-node/node_modules/web-streams-polyfill/polyfill/package.json new file mode 100644 index 0000000000000000000000000000000000000000..6bc6f97acf0b07d811cdfa336072a1d4e271b6f0 --- /dev/null +++ b/backend/node_modules/formdata-node/node_modules/web-streams-polyfill/polyfill/package.json @@ -0,0 +1,5 @@ +{ + "name": "web-streams-polyfill", + "main": "../dist/polyfill.js", + "types": "../types/polyfill.d.ts" +} diff --git a/backend/node_modules/formdata-node/node_modules/web-streams-polyfill/types/polyfill.d.ts b/backend/node_modules/formdata-node/node_modules/web-streams-polyfill/types/polyfill.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..27680df252e68432acacc1bcfc8069769ea93394 --- /dev/null +++ b/backend/node_modules/formdata-node/node_modules/web-streams-polyfill/types/polyfill.d.ts @@ -0,0 +1,62 @@ +/// +/// + +import type { + ReadableStreamAsyncIterator, + ReadableStreamBYOBReader, + ReadableStreamBYOBReadResult, + ReadableStreamIteratorOptions +} from './ponyfill'; + +export type { + ReadableStreamAsyncIterator, + ReadableStreamBYOBReader, + ReadableStreamBYOBReadResult, + ReadableStreamIteratorOptions +}; + +declare global { + interface ReadableStream { + /** + * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader. + * + * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams, + * i.e. streams which were constructed specifically with the ability to handle "bring your own buffer" reading. + * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its + * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise + * control over allocation. + */ + getReader({ mode }: { + mode: 'byob'; + }): ReadableStreamBYOBReader; + + /** + * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader. + * While the stream is locked, no other reader can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to consume a stream + * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours + * or cancel the stream, which would interfere with your abstraction. + */ + getReader(): ReadableStreamDefaultReader; + + /** + * Asynchronously iterates over the chunks in the stream's internal queue. + * + * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader. + * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method + * is called, e.g. by breaking out of the loop. + * + * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also + * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing + * `true` for the `preventCancel` option. + */ + values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator; + + /** + * {@inheritDoc ReadableStream.values} + */ + [Symbol.asyncIterator]: (options?: ReadableStreamIteratorOptions) => ReadableStreamAsyncIterator; + } +} + diff --git a/backend/node_modules/formdata-node/node_modules/web-streams-polyfill/types/ponyfill.d.ts b/backend/node_modules/formdata-node/node_modules/web-streams-polyfill/types/ponyfill.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6fdcff47cad6ea289744dcecc02c6f7c58456f1c --- /dev/null +++ b/backend/node_modules/formdata-node/node_modules/web-streams-polyfill/types/ponyfill.d.ts @@ -0,0 +1,775 @@ +/// + +/** + * A signal object that allows you to communicate with a request and abort it if required + * via its associated `AbortController` object. + * + * @remarks + * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types. + * It is redefined here, so it can be polyfilled without a DOM, for example with + * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment. + * + * @public + */ +export declare interface AbortSignal { + /** + * Whether the request is aborted. + */ + readonly aborted: boolean; + /** + * The abort reason. + */ + readonly reason?: any; + /** + * Add an event listener to be triggered when this signal becomes aborted. + */ + addEventListener(type: 'abort', listener: () => void): void; + /** + * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}. + */ + removeEventListener(type: 'abort', listener: () => void): void; +} + +/** + * A queuing strategy that counts the number of bytes in each chunk. + * + * @public + */ +export declare class ByteLengthQueuingStrategy implements QueuingStrategy { + constructor(options: QueuingStrategyInit); + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark(): number; + /** + * Measures the size of `chunk` by returning the value of its `byteLength` property. + */ + get size(): (chunk: ArrayBufferView) => number; +} + +/** + * A queuing strategy that counts the number of chunks. + * + * @public + */ +export declare class CountQueuingStrategy implements QueuingStrategy { + constructor(options: QueuingStrategyInit); + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark(): number; + /** + * Measures the size of `chunk` by always returning 1. + * This ensures that the total queue size is a count of the number of chunks in the queue. + */ + get size(): (chunk: any) => 1; +} + +/** + * A queuing strategy. + * + * @public + */ +export declare interface QueuingStrategy { + /** + * A non-negative number indicating the high water mark of the stream using this queuing strategy. + */ + highWaterMark?: number; + /** + * A function that computes and returns the finite non-negative size of the given chunk value. + */ + size?: QueuingStrategySizeCallback; +} + +/** + * @public + */ +export declare interface QueuingStrategyInit { + /** + * {@inheritDoc QueuingStrategy.highWaterMark} + */ + highWaterMark: number; +} + +/** + * {@inheritDoc QueuingStrategy.size} + * @public + */ +export declare type QueuingStrategySizeCallback = (chunk: T) => number; + +/** + * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. + * + * @public + */ +export declare class ReadableByteStreamController { + private constructor(); + /** + * Returns the current BYOB pull request, or `null` if there isn't one. + */ + get byobRequest(): ReadableStreamBYOBRequest | null; + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize(): number | null; + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close(): void; + /** + * Enqueues the given chunk chunk in the controlled readable stream. + * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown. + */ + enqueue(chunk: ArrayBufferView): void; + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e?: any): void; +} + +/** + * A readable stream represents a source of data, from which you can read. + * + * @public + */ +export declare class ReadableStream { + constructor(underlyingSource: UnderlyingByteSource, strategy?: { + highWaterMark?: number; + size?: undefined; + }); + constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy); + /** + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. + */ + get locked(): boolean; + /** + * Cancels the stream, signaling a loss of interest in the stream by a consumer. + * + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} + * method, which might or might not use it. + */ + cancel(reason?: any): Promise; + /** + * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader. + * + * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams, + * i.e. streams which were constructed specifically with the ability to handle "bring your own buffer" reading. + * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its + * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise + * control over allocation. + */ + getReader({ mode }: { + mode: 'byob'; + }): ReadableStreamBYOBReader; + /** + * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader. + * While the stream is locked, no other reader can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to consume a stream + * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours + * or cancel the stream, which would interfere with your abstraction. + */ + getReader(): ReadableStreamDefaultReader; + /** + * Provides a convenient, chainable way of piping this readable stream through a transform stream + * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream + * into the writable side of the supplied pair, and returns the readable side for further use. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + */ + pipeThrough(transform: { + readable: RS; + writable: WritableStream; + }, options?: StreamPipeOptions): RS; + /** + * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under + * various error conditions can be customized with a number of passed options. It returns a promise that fulfills + * when the piping process completes successfully, or rejects if any errors were encountered. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + */ + pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise; + /** + * Tees this readable stream, returning a two-element array containing the two resulting branches as + * new {@link ReadableStream} instances. + * + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be + * propagated to the stream's underlying source. + * + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, + * this could allow interference between the two branches. + */ + tee(): [ReadableStream, ReadableStream]; + /** + * Asynchronously iterates over the chunks in the stream's internal queue. + * + * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader. + * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method + * is called, e.g. by breaking out of the loop. + * + * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also + * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing + * `true` for the `preventCancel` option. + */ + values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator; + /** + * {@inheritDoc ReadableStream.values} + */ + [Symbol.asyncIterator]: (options?: ReadableStreamIteratorOptions) => ReadableStreamAsyncIterator; +} + +/** + * An async iterator returned by {@link ReadableStream.values}. + * + * @public + */ +export declare interface ReadableStreamAsyncIterator extends AsyncIterator { + next(): Promise>; + return(value?: any): Promise>; +} + +/** + * A BYOB reader vended by a {@link ReadableStream}. + * + * @public + */ +export declare class ReadableStreamBYOBReader { + constructor(stream: ReadableStream); + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the reader's lock is released before the stream finishes closing. + */ + get closed(): Promise; + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason?: any): Promise; + /** + * Attempts to reads bytes into view, and returns a promise resolved with the result. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read(view: T): Promise>; + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock(): void; +} + +/** + * A result returned by {@link ReadableStreamBYOBReader.read}. + * + * @public + */ +export declare type ReadableStreamBYOBReadResult = { + done: false; + value: T; +} | { + done: true; + value: T | undefined; +}; + +/** + * A pull-into request in a {@link ReadableByteStreamController}. + * + * @public + */ +export declare class ReadableStreamBYOBRequest { + private constructor(); + /** + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. + */ + get view(): ArrayBufferView | null; + /** + * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into + * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer. + * + * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer + * modifiable. + */ + respond(bytesWritten: number): void; + /** + * Indicates to the associated readable byte stream that instead of writing into + * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`, + * which will be given to the consumer of the readable byte stream. + * + * After this method is called, `view` will be transferred and no longer modifiable. + */ + respondWithNewView(view: ArrayBufferView): void; +} + +/** + * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. + * + * @public + */ +export declare class ReadableStreamDefaultController { + private constructor(); + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize(): number | null; + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close(): void; + /** + * Enqueues the given chunk `chunk` in the controlled readable stream. + */ + enqueue(chunk: R): void; + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e?: any): void; +} + +/** + * A default reader vended by a {@link ReadableStream}. + * + * @public + */ +export declare class ReadableStreamDefaultReader { + constructor(stream: ReadableStream); + /** + * Returns a promise that will be fulfilled when the stream becomes closed, + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + */ + get closed(): Promise; + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason?: any): Promise; + /** + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read(): Promise>; + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock(): void; +} + +/** + * A result returned by {@link ReadableStreamDefaultReader.read}. + * + * @public + */ +export declare type ReadableStreamDefaultReadResult = { + done: false; + value: T; +} | { + done: true; + value?: undefined; +}; + +/** + * Options for {@link ReadableStream.values | async iterating} a stream. + * + * @public + */ +export declare interface ReadableStreamIteratorOptions { + preventCancel?: boolean; +} + +/** + * A pair of a {@link ReadableStream | readable stream} and {@link WritableStream | writable stream} that can be passed + * to {@link ReadableStream.pipeThrough}. + * + * @public + */ +export declare interface ReadableWritablePair { + readable: ReadableStream; + writable: WritableStream; +} + +/** + * Options for {@link ReadableStream.pipeTo | piping} a stream. + * + * @public + */ +export declare interface StreamPipeOptions { + /** + * If set to true, {@link ReadableStream.pipeTo} will not abort the writable stream if the readable stream errors. + */ + preventAbort?: boolean; + /** + * If set to true, {@link ReadableStream.pipeTo} will not cancel the readable stream if the writable stream closes + * or errors. + */ + preventCancel?: boolean; + /** + * If set to true, {@link ReadableStream.pipeTo} will not close the writable stream if the readable stream closes. + */ + preventClose?: boolean; + /** + * Can be set to an {@link AbortSignal} to allow aborting an ongoing pipe operation via the corresponding + * `AbortController`. In this case, the source readable stream will be canceled, and the destination writable stream + * aborted, unless the respective options `preventCancel` or `preventAbort` are set. + */ + signal?: AbortSignal; +} + +/** + * A transformer for constructing a {@link TransformStream}. + * + * @public + */ +export declare interface Transformer { + /** + * A function that is called immediately during creation of the {@link TransformStream}. + */ + start?: TransformerStartCallback; + /** + * A function called when a new chunk originally written to the writable side is ready to be transformed. + */ + transform?: TransformerTransformCallback; + /** + * A function called after all chunks written to the writable side have been transformed by successfully passing + * through {@link Transformer.transform | transform()}, and the writable side is about to be closed. + */ + flush?: TransformerFlushCallback; + readableType?: undefined; + writableType?: undefined; +} + +/** @public */ +export declare type TransformerFlushCallback = (controller: TransformStreamDefaultController) => void | PromiseLike; + +/** @public */ +export declare type TransformerStartCallback = (controller: TransformStreamDefaultController) => void | PromiseLike; + +/** @public */ +export declare type TransformerTransformCallback = (chunk: I, controller: TransformStreamDefaultController) => void | PromiseLike; + +/** + * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, + * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. + * In a manner specific to the transform stream in question, writes to the writable side result in new data being + * made available for reading from the readable side. + * + * @public + */ +export declare class TransformStream { + constructor(transformer?: Transformer, writableStrategy?: QueuingStrategy, readableStrategy?: QueuingStrategy); + /** + * The readable side of the transform stream. + */ + get readable(): ReadableStream; + /** + * The writable side of the transform stream. + */ + get writable(): WritableStream; +} + +/** + * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. + * + * @public + */ +export declare class TransformStreamDefaultController { + private constructor(); + /** + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. + */ + get desiredSize(): number | null; + /** + * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream. + */ + enqueue(chunk: O): void; + /** + * Errors both the readable side and the writable side of the controlled transform stream, making all future + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. + */ + error(reason?: any): void; + /** + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the + * transformer only needs to consume a portion of the chunks written to the writable side. + */ + terminate(): void; +} + +/** + * An underlying byte source for constructing a {@link ReadableStream}. + * + * @public + */ +export declare interface UnderlyingByteSource { + /** + * {@inheritDoc UnderlyingSource.start} + */ + start?: UnderlyingByteSourceStartCallback; + /** + * {@inheritDoc UnderlyingSource.pull} + */ + pull?: UnderlyingByteSourcePullCallback; + /** + * {@inheritDoc UnderlyingSource.cancel} + */ + cancel?: UnderlyingSourceCancelCallback; + /** + * Can be set to "bytes" to signal that the constructed {@link ReadableStream} is a readable byte stream. + * This ensures that the resulting {@link ReadableStream} will successfully be able to vend BYOB readers via its + * {@link ReadableStream.(getReader:1) | getReader()} method. + * It also affects the controller argument passed to the {@link UnderlyingByteSource.start | start()} + * and {@link UnderlyingByteSource.pull | pull()} methods. + */ + type: 'bytes'; + /** + * Can be set to a positive integer to cause the implementation to automatically allocate buffers for the + * underlying source code to write into. In this case, when a consumer is using a default reader, the stream + * implementation will automatically allocate an ArrayBuffer of the given size, so that + * {@link ReadableByteStreamController.byobRequest | controller.byobRequest} is always present, + * as if the consumer was using a BYOB reader. + */ + autoAllocateChunkSize?: number; +} + +/** @public */ +export declare type UnderlyingByteSourcePullCallback = (controller: ReadableByteStreamController) => void | PromiseLike; + +/** @public */ +export declare type UnderlyingByteSourceStartCallback = (controller: ReadableByteStreamController) => void | PromiseLike; + +/** + * An underlying sink for constructing a {@link WritableStream}. + * + * @public + */ +export declare interface UnderlyingSink { + /** + * A function that is called immediately during creation of the {@link WritableStream}. + */ + start?: UnderlyingSinkStartCallback; + /** + * A function that is called when a new chunk of data is ready to be written to the underlying sink. The stream + * implementation guarantees that this function will be called only after previous writes have succeeded, and never + * before {@link UnderlyingSink.start | start()} has succeeded or after {@link UnderlyingSink.close | close()} or + * {@link UnderlyingSink.abort | abort()} have been called. + * + * This function is used to actually send the data to the resource presented by the underlying sink, for example by + * calling a lower-level API. + */ + write?: UnderlyingSinkWriteCallback; + /** + * A function that is called after the producer signals, via + * {@link WritableStreamDefaultWriter.close | writer.close()}, that they are done writing chunks to the stream, and + * subsequently all queued-up writes have successfully completed. + * + * This function can perform any actions necessary to finalize or flush writes to the underlying sink, and release + * access to any held resources. + */ + close?: UnderlyingSinkCloseCallback; + /** + * A function that is called after the producer signals, via {@link WritableStream.abort | stream.abort()} or + * {@link WritableStreamDefaultWriter.abort | writer.abort()}, that they wish to abort the stream. It takes as its + * argument the same value as was passed to those methods by the producer. + * + * Writable streams can additionally be aborted under certain conditions during piping; see the definition of the + * {@link ReadableStream.pipeTo | pipeTo()} method for more details. + * + * This function can clean up any held resources, much like {@link UnderlyingSink.close | close()}, but perhaps with + * some custom handling. + */ + abort?: UnderlyingSinkAbortCallback; + type?: undefined; +} + +/** @public */ +export declare type UnderlyingSinkAbortCallback = (reason: any) => void | PromiseLike; + +/** @public */ +export declare type UnderlyingSinkCloseCallback = () => void | PromiseLike; + +/** @public */ +export declare type UnderlyingSinkStartCallback = (controller: WritableStreamDefaultController) => void | PromiseLike; + +/** @public */ +export declare type UnderlyingSinkWriteCallback = (chunk: W, controller: WritableStreamDefaultController) => void | PromiseLike; + +/** + * An underlying source for constructing a {@link ReadableStream}. + * + * @public + */ +export declare interface UnderlyingSource { + /** + * A function that is called immediately during creation of the {@link ReadableStream}. + */ + start?: UnderlyingSourceStartCallback; + /** + * A function that is called whenever the stream’s internal queue of chunks becomes not full, + * i.e. whenever the queue’s desired size becomes positive. Generally, it will be called repeatedly + * until the queue reaches its high water mark (i.e. until the desired size becomes non-positive). + */ + pull?: UnderlyingSourcePullCallback; + /** + * A function that is called whenever the consumer cancels the stream, via + * {@link ReadableStream.cancel | stream.cancel()}, + * {@link ReadableStreamDefaultReader.cancel | defaultReader.cancel()}, or + * {@link ReadableStreamBYOBReader.cancel | byobReader.cancel()}. + * It takes as its argument the same value as was passed to those methods by the consumer. + */ + cancel?: UnderlyingSourceCancelCallback; + type?: undefined; +} + +/** @public */ +export declare type UnderlyingSourceCancelCallback = (reason: any) => void | PromiseLike; + +/** @public */ +export declare type UnderlyingSourcePullCallback = (controller: ReadableStreamDefaultController) => void | PromiseLike; + +/** @public */ +export declare type UnderlyingSourceStartCallback = (controller: ReadableStreamDefaultController) => void | PromiseLike; + +/** + * A writable stream represents a destination for data, into which you can write. + * + * @public + */ +export declare class WritableStream { + constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy); + /** + * Returns whether or not the writable stream is locked to a writer. + */ + get locked(): boolean; + /** + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort + * mechanism of the underlying sink. + * + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel + * the stream) if the stream is currently locked. + */ + abort(reason?: any): Promise; + /** + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its + * close behavior. During this time any further attempts to write will fail (without erroring the stream). + * + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + */ + close(): Promise; + /** + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream + * is locked, no other writer can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at + * the same time, which would cause the resulting written data to be unpredictable and probably useless. + */ + getWriter(): WritableStreamDefaultWriter; +} + +/** + * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. + * + * @public + */ +export declare class WritableStreamDefaultController { + private constructor(); + /** + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. + * + * @deprecated + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. + */ + get abortReason(): any; + /** + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. + */ + get signal(): AbortSignal; + /** + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. + * + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the + * normal lifecycle of interactions with the underlying sink. + */ + error(e?: any): void; +} + +/** + * A default writer vended by a {@link WritableStream}. + * + * @public + */ +export declare class WritableStreamDefaultWriter { + constructor(stream: WritableStream); + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the writer’s lock is released before the stream finishes closing. + */ + get closed(): Promise; + /** + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. + * A producer can use this information to determine the right amount of data to write. + * + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when + * the writer’s lock is released. + */ + get desiredSize(): number | null; + /** + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips + * back to zero or below, the getter will return a new promise that stays pending until the next transition. + * + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become + * rejected. + */ + get ready(): Promise; + /** + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + */ + abort(reason?: any): Promise; + /** + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + */ + close(): Promise; + /** + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from + * now on; otherwise, the writer will appear closed. + * + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents + * other producers from writing in an interleaved manner. + */ + releaseLock(): void; + /** + * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully, + * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return + * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes + * errored before the writing process is initiated. + * + * Note that what "success" means is up to the underlying sink; it might indicate simply that the chunk has been + * accepted, and not necessarily that it is safely saved to its ultimate destination. + */ + write(chunk: W): Promise; +} + +export { } diff --git a/backend/node_modules/formdata-node/node_modules/web-streams-polyfill/types/tsdoc-metadata.json b/backend/node_modules/formdata-node/node_modules/web-streams-polyfill/types/tsdoc-metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..7058852bf8e220f18615dce0ea70fc73e3ef2819 --- /dev/null +++ b/backend/node_modules/formdata-node/node_modules/web-streams-polyfill/types/tsdoc-metadata.json @@ -0,0 +1,11 @@ +// This file is read by tools that parse documentation comments conforming to the TSDoc standard. +// It should be published with your NPM package. It should not be tracked by Git. +{ + "tsdocVersion": "0.12", + "toolPackages": [ + { + "packageName": "@microsoft/api-extractor", + "packageVersion": "7.21.2" + } + ] +} diff --git a/backend/node_modules/formdata-node/package.json b/backend/node_modules/formdata-node/package.json new file mode 100644 index 0000000000000000000000000000000000000000..0f8c97e43b82a2520bfd210f801036a80e365a06 --- /dev/null +++ b/backend/node_modules/formdata-node/package.json @@ -0,0 +1,94 @@ +{ + "name": "formdata-node", + "version": "4.4.1", + "description": "Spec-compliant FormData implementation for Node.js", + "repository": "octet-stream/form-data", + "sideEffects": false, + "keywords": [ + "form-data", + "node", + "form", + "upload", + "files-upload", + "ponyfill" + ], + "author": "Nick K. ", + "license": "MIT", + "main": "./lib/cjs/index.js", + "module": "./lib/esm/browser.js", + "browser": "./lib/cjs/browser.js", + "exports": { + "./package.json": "./package.json", + ".": { + "node": { + "types": "./@type/index.d.ts", + "import": "./lib/esm/index.js", + "require": "./lib/cjs/index.js" + }, + "browser": { + "types": "./@type/browser.d.ts", + "import": "./lib/esm/browser.js", + "require": "./lib/cjs/browser.js" + }, + "default": "./lib/esm/index.js" + }, + "./file-from-path": { + "types": "./@type/fileFromPath.d.ts", + "import": "./lib/esm/fileFromPath.js", + "require": "./lib/cjs/fileFromPath.js" + } + }, + "types": "./@type/index.d.ts", + "typesVersions": { + "*": { + "file-from-path": [ + "@type/fileFromPath.d.ts" + ] + } + }, + "engines": { + "node": ">= 12.20" + }, + "scripts": { + "eslint": "eslint lib/**/*.ts", + "staged": "lint-staged", + "coverage": "c8 npm test", + "report:html": "c8 -r=html npm test", + "ci": "c8 npm test && c8 report --reporter=json", + "build:esm": "ttsc --project tsconfig.esm.json", + "build:cjs": "ttsc --project tsconfig.cjs.json", + "build:types": "ttsc --project tsconfig.d.ts.json", + "build": "npm run build:esm && npm run build:cjs && npm run build:types", + "test": "ava --fail-fast", + "cleanup": "npx rimraf @type \"lib/**/*.js\"", + "prepare": "npm run cleanup && npm run build", + "husky": "husky install" + }, + "devDependencies": { + "@octetstream/eslint-config": "5.0.0", + "@types/node": "17.0.19", + "@types/sinon": "10.0.11", + "@typescript-eslint/eslint-plugin": "4.32.0", + "@typescript-eslint/parser": "4.32.0", + "@zoltu/typescript-transformer-append-js-extension": "1.0.1", + "ava": "4.0.1", + "c8": "7.12.0", + "eslint": "7.32.0", + "eslint-config-airbnb-typescript": "12.3.1", + "eslint-import-resolver-typescript": "2.5.0", + "eslint-plugin-ava": "12.0.0", + "eslint-plugin-jsx-a11y": "6.4.1", + "eslint-plugin-react": "7.26.1", + "husky": "7.0.4", + "lint-staged": "12.3.4", + "rimraf": "^3.0.2", + "sinon": "13.0.1", + "ts-node": "10.5.0", + "ttypescript": "1.5.13", + "typescript": "4.5.5" + }, + "dependencies": { + "node-domexception": "1.0.0", + "web-streams-polyfill": "4.0.0-beta.3" + } +} diff --git a/backend/node_modules/formdata-node/readme.md b/backend/node_modules/formdata-node/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..d67d0cbdaa46a4742c20a5cec8bc3d82f6935631 --- /dev/null +++ b/backend/node_modules/formdata-node/readme.md @@ -0,0 +1,444 @@ +# FormData + +Spec-compliant [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData) implementation for Node.js + +[![Code Coverage](https://codecov.io/github/octet-stream/form-data/coverage.svg?branch=master)](https://codecov.io/github/octet-stream/form-data?branch=master) +[![CI](https://github.com/octet-stream/form-data/workflows/CI/badge.svg)](https://github.com/octet-stream/form-data/actions/workflows/ci.yml) +[![ESLint](https://github.com/octet-stream/form-data/workflows/ESLint/badge.svg)](https://github.com/octet-stream/form-data/actions/workflows/eslint.yml) + +## Highlights + +1. Spec-compliant: implements every method of the [`FormData interface`](https://developer.mozilla.org/en-US/docs/Web/API/FormData). +2. Supports Blobs and Files sourced from anywhere: you can use builtin [`fileFromPath`](#filefrompathpath-filename-options---promisefile) and [`fileFromPathSync`](#filefrompathsyncpath-filename-options---file) helpers to create a File from FS, or you can implement your `BlobDataItem` object to use a different source of data. +3. Supports both ESM and CJS targets. See [`ESM/CJS support`](#esmcjs-support) section for details. +4. Written on TypeScript and ships with TS typings. +5. Isomorphic, but only re-exports native FormData object for browsers. If you need a polyfill for browsers, use [`formdata-polyfill`](https://github.com/jimmywarting/FormData) +6. It's a [`ponyfill`](https://ponyfill.com/)! Which means, no effect has been caused on `globalThis` or native `FormData` implementation. + +## Installation + +You can install this package with npm: + +``` +npm install formdata-node +``` + +Or yarn: + +``` +yarn add formdata-node +``` + +Or pnpm + +``` +pnpm add formdata-node +``` + +## ESM/CJS support + +This package is targeting ESM and CJS for backwards compatibility reasons and smoothen transition period while you convert your projects to ESM only. Note that CJS support will be removed as [Node.js v12 will reach its EOL](https://github.com/nodejs/release#release-schedule). This change will be released as major version update, so you won't miss it. + +## Usage + +1. Let's take a look at minimal example with [got](https://github.com/sindresorhus/got): + +```js +import {FormData} from "formdata-node" + +// I assume Got >= 12.x is used for this example +import got from "got" + +const form = new FormData() + +form.set("greeting", "Hello, World!") + +const data = await got.post("https://httpbin.org/post", {body: form}).json() + +console.log(data.form.greeting) // => Hello, World! +``` + +2. If your HTTP client does not support spec-compliant FormData, you can use [`form-data-encoder`](https://github.com/octet-stream/form-data-encoder) to encode entries: + +```js +import {Readable} from "stream" + +import {FormDataEncoder} from "form-data-encoder" +import {FormData} from "formdata-node" + +// Note that `node-fetch` >= 3.x have builtin support for spec-compliant FormData, sou you'll only need the `form-data-encoder` if you use `node-fetch` <= 2.x. +import fetch from "node-fetch" + +const form = new FormData() + +form.set("field", "Some value") + +const encoder = new FormDataEncoder(form) + +const options = { + method: "post", + headers: encoder.headers, + body: Readable.from(encoder) +} + +await fetch("https://httpbin.org/post", options) +``` + +3. Sending files over form-data: + +```js +import {FormData, File} from "formdata-node" // You can use `File` from fetch-blob >= 3.x + +import fetch from "node-fetch" + +const form = new FormData() +const file = new File(["My hovercraft is full of eels"], "file.txt") + +form.set("file", file) + +await fetch("https://httpbin.org/post", {method: "post", body: form}) +``` + +4. Blobs as field's values allowed too: + +```js +import {FormData, Blob} from "formdata-node" // You can use `Blob` from fetch-blob + +const form = new FormData() +const blob = new Blob(["Some content"], {type: "text/plain"}) + +form.set("blob", blob) + +// Will always be returned as `File` +let file = form.get("blob") + +// The created file has "blob" as the name by default +console.log(file.name) // -> blob + +// To change that, you need to set filename argument manually +form.set("file", blob, "some-file.txt") + +file = form.get("file") + +console.log(file.name) // -> some-file.txt +``` + +5. You can also append files using `fileFromPath` or `fileFromPathSync` helpers. It does the same thing as [`fetch-blob/from`](https://github.com/node-fetch/fetch-blob#blob-part-backed-up-by-filesystem), but returns a `File` instead of `Blob`: + +```js +import {fileFromPath} from "formdata-node/file-from-path" +import {FormData} from "formdata-node" + +import fetch from "node-fetch" + +const form = new FormData() + +form.set("file", await fileFromPath("/path/to/a/file")) + +await fetch("https://httpbin.org/post", {method: "post", body: form}) +``` + +6. You can still use files sourced from any stream, but unlike in v2 you'll need some extra work to achieve that: + +```js +import {Readable} from "stream" + +import {FormData} from "formdata-node" + +class BlobFromStream { + #stream + + constructor(stream, size) { + this.#stream = stream + this.size = size + } + + stream() { + return this.#stream + } + + get [Symbol.toStringTag]() { + return "Blob" + } +} + +const content = Buffer.from("Stream content") + +const stream = new Readable({ + read() { + this.push(content) + this.push(null) + } +}) + +const form = new FormData() + +form.set("stream", new BlobFromStream(stream, content.length), "file.txt") + +await fetch("https://httpbin.org/post", {method: "post", body: form}) +``` + +7. Note that if you don't know the length of that stream, you'll also need to handle form-data encoding manually or use [`form-data-encoder`](https://github.com/octet-stream/form-data-encoder) package. This is necessary to control which headers will be sent with your HTTP request: + +```js +import {Readable} from "stream" + +import {Encoder} from "form-data-encoder" +import {FormData} from "formdata-node" + +const form = new FormData() + +// You can use file-shaped or blob-shaped objects as FormData value instead of creating separate class +form.set("stream", { + type: "text/plain", + name: "file.txt", + [Symbol.toStringTag]: "File", + stream() { + return getStreamFromSomewhere() + } +}) + +const encoder = new Encoder(form) + +const options = { + method: "post", + headers: { + "content-type": encoder.contentType + }, + body: Readable.from(encoder) +} + +await fetch("https://httpbin.org/post", {method: "post", body: form}) +``` + +## Comparison + +| | formdata-node | formdata-polyfill | undici FormData | form-data | +| ---------------- | ------------- | ----------------- | --------------- | -------------------- | +| .append() | ✔️ | ✔️ | ✔️ | ✔️1 | +| .set() | ✔️ | ✔️ | ✔️ | ❌ | +| .get() | ✔️ | ✔️ | ✔️ | ❌ | +| .getAll() | ✔️ | ✔️ | ✔️ | ❌ | +| .forEach() | ✔️ | ✔️ | ✔️ | ❌ | +| .keys() | ✔️ | ✔️ | ✔️ | ❌ | +| .values() | ✔️ | ✔️ | ✔️ | ❌ | +| .entries() | ✔️ | ✔️ | ✔️ | ❌ | +| Symbol.iterator | ✔️ | ✔️ | ✔️ | ❌ | +| CommonJS | ✔️ | ❌ | ✔️ | ✔️ | +| ESM | ✔️ | ✔️ | ✔️2 | ✔️2 | +| Blob | ✔️3 | ✔️4 | ✔️3 | ❌ | +| Browser polyfill | ❌ | ✔️ | ✔️ | ❌ | +| Builtin encoder | ❌ | ✔️ | ✔️5 | ✔️ | + +1 Does not support Blob and File in entry value, but allows streams and Buffer (which is not spec-compiant, however). + +2 Can be imported in ESM, because Node.js support for CJS modules in ESM context, but it does not have ESM entry point. + +3 Have builtin implementations of Blob and/or File, allows native Blob and File as entry value. + +4 Support Blob and File via fetch-blob package, allows native Blob and File as entry value. + +5 Have `multipart/form-data` encoder as part of their `fetch` implementation. + +✔️ - For FormData methods, indicates that the method is present and spec-compliant. For features, shows its presence. + +❌ - Indicates that method or feature is not implemented. + +## API + +### `class FormData` + +##### `constructor([entries]) -> {FormData}` + +Creates a new FormData instance + + - **{array}** [entries = null] – an optional FormData initial entries. + Each initial field should be passed as a collection of the objects + with "name", "value" and "filename" props. + See the [FormData#append()](#appendname-value-filename---void) for more info about the available format. + +#### Instance methods + +##### `set(name, value[, filename]) -> {void}` + +Set a new value for an existing key inside **FormData**, +or add the new field if it does not already exist. + + - **{string}** name – The name of the field whose data is contained in `value`. + - **{unknown}** value – The field's value. This can be [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) + or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File). If none of these are specified the value is converted to a string. + - **{string}** [filename = undefined] – The filename reported to the server, when a Blob or File is passed as the second parameter. The default filename for Blob objects is "blob". The default filename for File objects is the file's filename. + +##### `append(name, value[, filename]) -> {void}` + +Appends a new value onto an existing key inside a FormData object, +or adds the key if it does not already exist. + +The difference between `set()` and `append()` is that if the specified key already exists, `set()` will overwrite all existing values with the new one, whereas `append()` will append the new value onto the end of the existing set of values. + + - **{string}** name – The name of the field whose data is contained in `value`. + - **{unknown}** value – The field's value. This can be [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) + or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File). If none of these are specified the value is converted to a string. + - **{string}** [filename = undefined] – The filename reported to the server, when a Blob or File is passed as the second parameter. The default filename for Blob objects is "blob". The default filename for File objects is the file's filename. + +##### `get(name) -> {FormDataValue}` + +Returns the first value associated with a given key from within a `FormData` object. +If you expect multiple values and want all of them, use the `getAll()` method instead. + + - **{string}** name – A name of the value you want to retrieve. + +##### `getAll(name) -> {Array}` + +Returns all the values associated with a given key from within a `FormData` object. + + - **{string}** name – A name of the value you want to retrieve. + +##### `has(name) -> {boolean}` + +Returns a boolean stating whether a `FormData` object contains a certain key. + + - **{string}** – A string representing the name of the key you want to test for. + +##### `delete(name) -> {void}` + +Deletes a key and its value(s) from a `FormData` object. + + - **{string}** name – The name of the key you want to delete. + +##### `forEach(callback[, thisArg]) -> {void}` + +Executes a given **callback** for each field of the FormData instance + + - **{function}** callback – Function to execute for each element, taking three arguments: + + **{FormDataValue}** value – A value(s) of the current field. + + **{string}** name – Name of the current field. + + **{FormData}** form – The FormData instance that **forEach** is being applied to + - **{unknown}** [thisArg = null] – Value to use as **this** context when executing the given **callback** + +##### `keys() -> {Generator}` + +Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through all keys contained in this `FormData` object. +Each key is a `string`. + +##### `values() -> {Generator}` + +Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through all values contained in this object `FormData` object. +Each value is a [`FormDataValue`](https://developer.mozilla.org/en-US/docs/Web/API/FormDataEntryValue). + +##### `entries() -> {Generator<[string, FormDataValue]>}` + +Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through key/value pairs contained in this `FormData` object. +The key of each pair is a string; the value is a [`FormDataValue`](https://developer.mozilla.org/en-US/docs/Web/API/FormDataEntryValue). + +##### `[Symbol.iterator]() -> {Generator<[string, FormDataValue]>}` + +An alias for [`FormData#entries()`](#entries---iterator) + +### `class Blob` + +The `Blob` object represents a blob, which is a file-like object of immutable, raw data; +they can be read as text or binary data, or converted into a ReadableStream +so its methods can be used for processing the data. + +##### `constructor(blobParts[, options]) -> {Blob}` + +Creates a new `Blob` instance. The `Blob` constructor accepts following arguments: + + - **{(ArrayBufferLike | ArrayBufferView | File | Blob | string)[]}** blobParts – An `Array` strings, or [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer), [`ArrayBufferView`](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView), [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) objects, or a mix of any of such objects, that will be put inside the [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob); + - **{object}** [options = {}] - An options object containing optional attributes for the file. Available options are as follows; + - **{string}** [options.type = ""] - Returns the media type ([`MIME`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types)) of the blob represented by a `Blob` object. + +#### Instance properties + +##### `type -> {string}` + +Returns the [`MIME type`](https://developer.mozilla.org/en-US/docs/Glossary/MIME_type) of the [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File). + +##### `size -> {number}` + +Returns the size of the [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File) in bytes. + +#### Instance methods + +##### `slice([start, end, contentType]) -> {Blob}` + +Creates and returns a new [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) object which contains data from a subset of the blob on which it's called. + +- **{number}** [start = 0] An index into the `Blob` indicating the first byte to include in the new `Blob`. If you specify a negative value, it's treated as an offset from the end of the `Blob` toward the beginning. For example, -10 would be the 10th from last byte in the `Blob`. The default value is 0. If you specify a value for start that is larger than the size of the source `Blob`, the returned `Blob` has size 0 and contains no data. + +- **{number}** [end = `blob`.size] An index into the `Blob` indicating the first byte that will *not* be included in the new `Blob` (i.e. the byte exactly at this index is not included). If you specify a negative value, it's treated as an offset from the end of the `Blob` toward the beginning. For example, -10 would be the 10th from last byte in the `Blob`. The default value is size. + +- **{string}** [contentType = ""] The content type to assign to the new ``Blob``; this will be the value of its type property. The default value is an empty string. + +##### `stream() -> {ReadableStream}` + +Returns a [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) which upon reading returns the data contained within the [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob). + +##### `arrayBuffer() -> {Promise}` + +Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves with the contents of the blob as binary data contained in an [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). + +##### `text() -> {Promise}` + +Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves with a string containing the contents of the blob, interpreted as UTF-8. + +### `class File extends Blob` + +The `File` class provides information about files. The `File` class inherits `Blob`. + +##### `constructor(fileBits, filename[, options]) -> {File}` + +Creates a new `File` instance. The `File` constructor accepts following arguments: + + - **{(ArrayBufferLike | ArrayBufferView | File | Blob | string)[]}** fileBits – An `Array` strings, or [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer), [`ArrayBufferView`](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView), [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) objects, or a mix of any of such objects, that will be put inside the [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File); + - **{string}** filename – Representing the file name. + - **{object}** [options = {}] - An options object containing optional attributes for the file. Available options are as follows; + - **{number}** [options.lastModified = Date.now()] – provides the last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). Files without a known last modified date return the current date; + - **{string}** [options.type = ""] - Returns the media type ([`MIME`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types)) of the file represented by a `File` object. + +### `fileFromPath(path[, filename, options]) -> {Promise}` + +Available from `formdata-node/file-from-path` subpath. + +Creates a `File` referencing the one on a disk by given path. + + - **{string}** path - Path to a file + - **{string}** [filename] - Optional name of the file. Will be passed as the second argument in `File` constructor. If not presented, the name will be taken from the file's path. + - **{object}** [options = {}] - Additional `File` options, except for `lastModified`. + - **{string}** [options.type = ""] - Returns the media type ([`MIME`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types)) of the file represented by a `File` object. + +### `fileFromPathSync(path[, filename, options]) -> {File}` + +Available from `formdata-node/file-from-path` subpath. + +Creates a `File` referencing the one on a disk by given path. Synchronous version of the `fileFromPath`. + - **{string}** path - Path to a file + - **{string}** [filename] - Optional name of the file. Will be passed as the second argument in `File` constructor. If not presented, the name will be taken from the file's path. + - **{object}** [options = {}] - Additional `File` options, except for `lastModified`. + - **{string}** [options.type = ""] - Returns the media type ([`MIME`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types)) of the file represented by a `File` object. + +### `isFile(value) -> {boolean}` + +Available from `formdata-node/file-from-path` subpath. + +Checks if given value is a File, Blob or file-look-a-like object. + + - **{unknown}** value - A value to test + +### Husky installation + +This package is using `husky` to perform git hooks on developer's machine, so your changes might be verified before you push them to `GitHub`. If you want to install these hooks, run `npm run husky` command. + +## Related links + +- [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData) documentation on MDN +- [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File) documentation on MDN +- [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) documentation on MDN +- [`FormDataValue`](https://developer.mozilla.org/en-US/docs/Web/API/FormDataEntryValue) documentation on MDN. +- [`formdata-polyfill`](https://github.com/jimmywarting/FormData) HTML5 `FormData` for Browsers & NodeJS. +- [`node-fetch`](https://github.com/node-fetch/node-fetch) a light-weight module that brings the Fetch API to Node.js +- [`fetch-blob`](https://github.com/node-fetch/fetch-blob) a Blob implementation on node.js, originally from `node-fetch`. +- [`form-data-encoder`](https://github.com/octet-stream/form-data-encoder) spec-compliant `multipart/form-data` encoder implementation. +- [`then-busboy`](https://github.com/octet-stream/then-busboy) a promise-based wrapper around Busboy. Process multipart/form-data content and returns it as a single object. Will be helpful to handle your data on the server-side applications. +- [`@octetstream/object-to-form-data`](https://github.com/octet-stream/object-to-form-data) converts JavaScript object to FormData. diff --git a/backend/node_modules/forwarded/HISTORY.md b/backend/node_modules/forwarded/HISTORY.md new file mode 100644 index 0000000000000000000000000000000000000000..381e6aad4619cbed1e74bf64a0dc3fe216dc0abe --- /dev/null +++ b/backend/node_modules/forwarded/HISTORY.md @@ -0,0 +1,21 @@ +0.2.0 / 2021-05-31 +================== + + * Use `req.socket` over deprecated `req.connection` + +0.1.2 / 2017-09-14 +================== + + * perf: improve header parsing + * perf: reduce overhead when no `X-Forwarded-For` header + +0.1.1 / 2017-09-10 +================== + + * Fix trimming leading / trailing OWS + * perf: hoist regular expression + +0.1.0 / 2014-09-21 +================== + + * Initial release diff --git a/backend/node_modules/forwarded/LICENSE b/backend/node_modules/forwarded/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..84441fbb5709262c2bfc9b5ff0166ad4f024a1b8 --- /dev/null +++ b/backend/node_modules/forwarded/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/backend/node_modules/forwarded/README.md b/backend/node_modules/forwarded/README.md new file mode 100644 index 0000000000000000000000000000000000000000..fdd220bcaab88b00b844736404c326fa6bdfbc0e --- /dev/null +++ b/backend/node_modules/forwarded/README.md @@ -0,0 +1,57 @@ +# forwarded + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][ci-image]][ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Parse HTTP X-Forwarded-For header + +## 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 forwarded +``` + +## API + +```js +var forwarded = require('forwarded') +``` + +### forwarded(req) + +```js +var addresses = forwarded(req) +``` + +Parse the `X-Forwarded-For` header from the request. Returns an array +of the addresses, including the socket address for the `req`, in reverse +order (i.e. index `0` is the socket address and the last index is the +furthest address, typically the end-user). + +## Testing + +```sh +$ npm test +``` + +## License + +[MIT](LICENSE) + +[ci-image]: https://badgen.net/github/checks/jshttp/forwarded/master?label=ci +[ci-url]: https://github.com/jshttp/forwarded/actions?query=workflow%3Aci +[npm-image]: https://img.shields.io/npm/v/forwarded.svg +[npm-url]: https://npmjs.org/package/forwarded +[node-version-image]: https://img.shields.io/node/v/forwarded.svg +[node-version-url]: https://nodejs.org/en/download/ +[coveralls-image]: https://img.shields.io/coveralls/jshttp/forwarded/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/forwarded?branch=master +[downloads-image]: https://img.shields.io/npm/dm/forwarded.svg +[downloads-url]: https://npmjs.org/package/forwarded diff --git a/backend/node_modules/forwarded/index.js b/backend/node_modules/forwarded/index.js new file mode 100644 index 0000000000000000000000000000000000000000..b2b6bdd3c98349ba48b5dc150e66746dab1beec1 --- /dev/null +++ b/backend/node_modules/forwarded/index.js @@ -0,0 +1,90 @@ +/*! + * forwarded + * Copyright(c) 2014-2017 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = forwarded + +/** + * Get all addresses in the request, using the `X-Forwarded-For` header. + * + * @param {object} req + * @return {array} + * @public + */ + +function forwarded (req) { + if (!req) { + throw new TypeError('argument req is required') + } + + // simple header parsing + var proxyAddrs = parse(req.headers['x-forwarded-for'] || '') + var socketAddr = getSocketAddr(req) + var addrs = [socketAddr].concat(proxyAddrs) + + // return all addresses + return addrs +} + +/** + * Get the socket address for a request. + * + * @param {object} req + * @return {string} + * @private + */ + +function getSocketAddr (req) { + return req.socket + ? req.socket.remoteAddress + : req.connection.remoteAddress +} + +/** + * Parse the X-Forwarded-For header. + * + * @param {string} header + * @private + */ + +function parse (header) { + var end = header.length + var list = [] + var start = header.length + + // gather addresses, backwards + for (var i = header.length - 1; i >= 0; i--) { + switch (header.charCodeAt(i)) { + case 0x20: /* */ + if (start === end) { + start = end = i + } + break + case 0x2c: /* , */ + if (start !== end) { + list.push(header.substring(start, end)) + } + start = end = i + break + default: + start = i + break + } + } + + // final address + if (start !== end) { + list.push(header.substring(start, end)) + } + + return list +} diff --git a/backend/node_modules/forwarded/package.json b/backend/node_modules/forwarded/package.json new file mode 100644 index 0000000000000000000000000000000000000000..bf9c7d6550b4efceee2f6f55350860097b218a0a --- /dev/null +++ b/backend/node_modules/forwarded/package.json @@ -0,0 +1,45 @@ +{ + "name": "forwarded", + "description": "Parse HTTP X-Forwarded-For header", + "version": "0.2.0", + "contributors": [ + "Douglas Christopher Wilson " + ], + "license": "MIT", + "keywords": [ + "x-forwarded-for", + "http", + "req" + ], + "repository": "jshttp/forwarded", + "devDependencies": { + "beautify-benchmark": "0.2.4", + "benchmark": "2.1.4", + "deep-equal": "1.0.1", + "eslint": "7.27.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.23.4", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "4.3.1", + "eslint-plugin-standard": "4.1.0", + "mocha": "8.4.0", + "nyc": "15.1.0" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "bench": "node benchmark/index.js", + "lint": "eslint .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-ci": "nyc --reporter=lcov --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/backend/node_modules/fresh/HISTORY.md b/backend/node_modules/fresh/HISTORY.md new file mode 100644 index 0000000000000000000000000000000000000000..4586996a3c6e13633a678339ff6075c60567c233 --- /dev/null +++ b/backend/node_modules/fresh/HISTORY.md @@ -0,0 +1,70 @@ +0.5.2 / 2017-09-13 +================== + + * Fix regression matching multiple ETags in `If-None-Match` + * perf: improve `If-None-Match` token parsing + +0.5.1 / 2017-09-11 +================== + + * Fix handling of modified headers with invalid dates + * perf: improve ETag match loop + +0.5.0 / 2017-02-21 +================== + + * Fix incorrect result when `If-None-Match` has both `*` and ETags + * Fix weak `ETag` matching to match spec + * perf: delay reading header values until needed + * perf: skip checking modified time if ETag check failed + * perf: skip parsing `If-None-Match` when no `ETag` header + * perf: use `Date.parse` instead of `new Date` + +0.4.0 / 2017-02-05 +================== + + * Fix false detection of `no-cache` request directive + * perf: enable strict mode + * perf: hoist regular expressions + * perf: remove duplicate conditional + * perf: remove unnecessary boolean coercions + +0.3.0 / 2015-05-12 +================== + + * Add weak `ETag` matching support + +0.2.4 / 2014-09-07 +================== + + * Support Node.js 0.6 + +0.2.3 / 2014-09-07 +================== + + * Move repository to jshttp + +0.2.2 / 2014-02-19 +================== + + * Revert "Fix for blank page on Safari reload" + +0.2.1 / 2014-01-29 +================== + + * Fix for blank page on Safari reload + +0.2.0 / 2013-08-11 +================== + + * Return stale for `Cache-Control: no-cache` + +0.1.0 / 2012-06-15 +================== + + * Add `If-None-Match: *` support + +0.0.1 / 2012-06-10 +================== + + * Initial release diff --git a/backend/node_modules/fresh/LICENSE b/backend/node_modules/fresh/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..1434ade75d1fc4faf25a6ac5daed813e12eaed28 --- /dev/null +++ b/backend/node_modules/fresh/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2012 TJ Holowaychuk +Copyright (c) 2016-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/backend/node_modules/fresh/README.md b/backend/node_modules/fresh/README.md new file mode 100644 index 0000000000000000000000000000000000000000..1c1c680d151e5a64ab39cb88afc4600f554f00d5 --- /dev/null +++ b/backend/node_modules/fresh/README.md @@ -0,0 +1,119 @@ +# fresh + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +HTTP response freshness testing + +## 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): + +``` +$ npm install fresh +``` + +## API + + + +```js +var fresh = require('fresh') +``` + +### fresh(reqHeaders, resHeaders) + +Check freshness of the response using request and response headers. + +When the response is still "fresh" in the client's cache `true` is +returned, otherwise `false` is returned to indicate that the client +cache is now stale and the full response should be sent. + +When a client sends the `Cache-Control: no-cache` request header to +indicate an end-to-end reload request, this module will return `false` +to make handling these requests transparent. + +## Known Issues + +This module is designed to only follow the HTTP specifications, not +to work-around all kinda of client bugs (especially since this module +typically does not recieve enough information to understand what the +client actually is). + +There is a known issue that in certain versions of Safari, Safari +will incorrectly make a request that allows this module to validate +freshness of the resource even when Safari does not have a +representation of the resource in the cache. The module +[jumanji](https://www.npmjs.com/package/jumanji) can be used in +an Express application to work-around this issue and also provides +links to further reading on this Safari bug. + +## Example + +### API usage + + + +```js +var reqHeaders = { 'if-none-match': '"foo"' } +var resHeaders = { 'etag': '"bar"' } +fresh(reqHeaders, resHeaders) +// => false + +var reqHeaders = { 'if-none-match': '"foo"' } +var resHeaders = { 'etag': '"foo"' } +fresh(reqHeaders, resHeaders) +// => true +``` + +### Using with Node.js http server + +```js +var fresh = require('fresh') +var http = require('http') + +var server = http.createServer(function (req, res) { + // perform server logic + // ... including adding ETag / Last-Modified response headers + + if (isFresh(req, res)) { + // client has a fresh copy of resource + res.statusCode = 304 + res.end() + return + } + + // send the resource + res.statusCode = 200 + res.end('hello, world!') +}) + +function isFresh (req, res) { + return fresh(req.headers, { + 'etag': res.getHeader('ETag'), + 'last-modified': res.getHeader('Last-Modified') + }) +} + +server.listen(3000) +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/fresh.svg +[npm-url]: https://npmjs.org/package/fresh +[node-version-image]: https://img.shields.io/node/v/fresh.svg +[node-version-url]: https://nodejs.org/en/ +[travis-image]: https://img.shields.io/travis/jshttp/fresh/master.svg +[travis-url]: https://travis-ci.org/jshttp/fresh +[coveralls-image]: https://img.shields.io/coveralls/jshttp/fresh/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/fresh?branch=master +[downloads-image]: https://img.shields.io/npm/dm/fresh.svg +[downloads-url]: https://npmjs.org/package/fresh diff --git a/backend/node_modules/fresh/index.js b/backend/node_modules/fresh/index.js new file mode 100644 index 0000000000000000000000000000000000000000..d154f5a7d23975af101646b65e74abf8490f50a5 --- /dev/null +++ b/backend/node_modules/fresh/index.js @@ -0,0 +1,137 @@ +/*! + * fresh + * Copyright(c) 2012 TJ Holowaychuk + * Copyright(c) 2016-2017 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * RegExp to check for no-cache token in Cache-Control. + * @private + */ + +var CACHE_CONTROL_NO_CACHE_REGEXP = /(?:^|,)\s*?no-cache\s*?(?:,|$)/ + +/** + * Module exports. + * @public + */ + +module.exports = fresh + +/** + * Check freshness of the response using request and response headers. + * + * @param {Object} reqHeaders + * @param {Object} resHeaders + * @return {Boolean} + * @public + */ + +function fresh (reqHeaders, resHeaders) { + // fields + var modifiedSince = reqHeaders['if-modified-since'] + var noneMatch = reqHeaders['if-none-match'] + + // unconditional request + if (!modifiedSince && !noneMatch) { + return false + } + + // Always return stale when Cache-Control: no-cache + // to support end-to-end reload requests + // https://tools.ietf.org/html/rfc2616#section-14.9.4 + var cacheControl = reqHeaders['cache-control'] + if (cacheControl && CACHE_CONTROL_NO_CACHE_REGEXP.test(cacheControl)) { + return false + } + + // if-none-match + if (noneMatch && noneMatch !== '*') { + var etag = resHeaders['etag'] + + if (!etag) { + return false + } + + var etagStale = true + var matches = parseTokenList(noneMatch) + for (var i = 0; i < matches.length; i++) { + var match = matches[i] + if (match === etag || match === 'W/' + etag || 'W/' + match === etag) { + etagStale = false + break + } + } + + if (etagStale) { + return false + } + } + + // if-modified-since + if (modifiedSince) { + var lastModified = resHeaders['last-modified'] + var modifiedStale = !lastModified || !(parseHttpDate(lastModified) <= parseHttpDate(modifiedSince)) + + if (modifiedStale) { + return false + } + } + + return true +} + +/** + * Parse an HTTP Date into a number. + * + * @param {string} date + * @private + */ + +function parseHttpDate (date) { + var timestamp = date && Date.parse(date) + + // istanbul ignore next: guard against date.js Date.parse patching + return typeof timestamp === 'number' + ? timestamp + : NaN +} + +/** + * Parse a HTTP token list. + * + * @param {string} str + * @private + */ + +function parseTokenList (str) { + var end = 0 + var list = [] + var start = 0 + + // gather tokens + for (var i = 0, len = str.length; i < len; i++) { + switch (str.charCodeAt(i)) { + case 0x20: /* */ + if (start === end) { + start = end = i + 1 + } + break + case 0x2c: /* , */ + list.push(str.substring(start, end)) + start = end = i + 1 + break + default: + end = i + 1 + break + } + } + + // final token + list.push(str.substring(start, end)) + + return list +} diff --git a/backend/node_modules/fresh/package.json b/backend/node_modules/fresh/package.json new file mode 100644 index 0000000000000000000000000000000000000000..c2fa0f4870b44895b8d59f1de9d14da0319f5793 --- /dev/null +++ b/backend/node_modules/fresh/package.json @@ -0,0 +1,46 @@ +{ + "name": "fresh", + "description": "HTTP response freshness testing", + "version": "0.5.2", + "author": "TJ Holowaychuk (http://tjholowaychuk.com)", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)" + ], + "license": "MIT", + "keywords": [ + "fresh", + "http", + "conditional", + "cache" + ], + "repository": "jshttp/fresh", + "devDependencies": { + "beautify-benchmark": "0.2.4", + "benchmark": "2.1.4", + "eslint": "3.19.0", + "eslint-config-standard": "10.2.1", + "eslint-plugin-import": "2.7.0", + "eslint-plugin-markdown": "1.0.0-beta.6", + "eslint-plugin-node": "5.1.1", + "eslint-plugin-promise": "3.5.0", + "eslint-plugin-standard": "3.0.1", + "istanbul": "0.4.5", + "mocha": "1.21.5" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "bench": "node benchmark/index.js", + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + } +} diff --git a/backend/node_modules/function-bind/.eslintrc b/backend/node_modules/function-bind/.eslintrc new file mode 100644 index 0000000000000000000000000000000000000000..71a054fd370a627af5171153377e7c78ba8937f9 --- /dev/null +++ b/backend/node_modules/function-bind/.eslintrc @@ -0,0 +1,21 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "func-name-matching": 0, + "indent": [2, 4], + "no-new-func": [1], + }, + + "overrides": [ + { + "files": "test/**", + "rules": { + "max-lines-per-function": 0, + "strict": [0] + }, + }, + ], +} diff --git a/backend/node_modules/function-bind/.github/FUNDING.yml b/backend/node_modules/function-bind/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..74482195934a98d0ce03d92cdabbc8a36e647d6f --- /dev/null +++ b/backend/node_modules/function-bind/.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/function-bind +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/backend/node_modules/function-bind/.github/SECURITY.md b/backend/node_modules/function-bind/.github/SECURITY.md new file mode 100644 index 0000000000000000000000000000000000000000..82e4285adc6285693cd6c06af02d606e09dd8fcd --- /dev/null +++ b/backend/node_modules/function-bind/.github/SECURITY.md @@ -0,0 +1,3 @@ +# Security + +Please email [@ljharb](https://github.com/ljharb) or see https://tidelift.com/security if you have a potential security vulnerability to report. diff --git a/backend/node_modules/function-bind/.nycrc b/backend/node_modules/function-bind/.nycrc new file mode 100644 index 0000000000000000000000000000000000000000..1826526e091b89c896e7099ccd891db79165e329 --- /dev/null +++ b/backend/node_modules/function-bind/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "test" + ] +} diff --git a/backend/node_modules/function-bind/CHANGELOG.md b/backend/node_modules/function-bind/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..f9e6cc078dadd58957c92af75542453c18169d73 --- /dev/null +++ b/backend/node_modules/function-bind/CHANGELOG.md @@ -0,0 +1,136 @@ +# 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.1.2](https://github.com/ljharb/function-bind/compare/v1.1.1...v1.1.2) - 2023-10-12 + +### Merged + +- Point to the correct file [`#16`](https://github.com/ljharb/function-bind/pull/16) + +### Commits + +- [Tests] migrate tests to Github Actions [`4f8b57c`](https://github.com/ljharb/function-bind/commit/4f8b57c02f2011fe9ae353d5e74e8745f0988af8) +- [Tests] remove `jscs` [`90eb2ed`](https://github.com/ljharb/function-bind/commit/90eb2edbeefd5b76cd6c3a482ea3454db169b31f) +- [meta] update `.gitignore` [`53fcdc3`](https://github.com/ljharb/function-bind/commit/53fcdc371cd66634d6e9b71c836a50f437e89fed) +- [Tests] up to `node` `v11.10`, `v10.15`, `v9.11`, `v8.15`, `v6.16`, `v4.9`; use `nvm install-latest-npm`; run audit script in tests [`1fe8f6e`](https://github.com/ljharb/function-bind/commit/1fe8f6e9aed0dfa8d8b3cdbd00c7f5ea0cd2b36e) +- [meta] add `auto-changelog` [`1921fcb`](https://github.com/ljharb/function-bind/commit/1921fcb5b416b63ffc4acad051b6aad5722f777d) +- [Robustness] remove runtime dependency on all builtins except `.apply` [`f743e61`](https://github.com/ljharb/function-bind/commit/f743e61aa6bb2360358c04d4884c9db853d118b7) +- Docs: enable badges; update wording [`503cb12`](https://github.com/ljharb/function-bind/commit/503cb12d998b5f91822776c73332c7adcd6355dd) +- [readme] update badges [`290c5db`](https://github.com/ljharb/function-bind/commit/290c5dbbbda7264efaeb886552a374b869a4bb48) +- [Tests] switch to nyc for coverage [`ea360ba`](https://github.com/ljharb/function-bind/commit/ea360ba907fc2601ed18d01a3827fa2d3533cdf8) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`cae5e9e`](https://github.com/ljharb/function-bind/commit/cae5e9e07a5578dc6df26c03ee22851ce05b943c) +- [meta] add `funding` field; create FUNDING.yml [`c9f4274`](https://github.com/ljharb/function-bind/commit/c9f4274aa80ea3aae9657a3938fdba41a3b04ca6) +- [Tests] fix eslint errors from #15 [`f69aaa2`](https://github.com/ljharb/function-bind/commit/f69aaa2beb2fdab4415bfb885760a699d0b9c964) +- [actions] fix permissions [`99a0cd9`](https://github.com/ljharb/function-bind/commit/99a0cd9f3b5bac223a0d572f081834cd73314be7) +- [meta] use `npmignore` to autogenerate an npmignore file [`f03b524`](https://github.com/ljharb/function-bind/commit/f03b524ca91f75a109a5d062f029122c86ecd1ae) +- [Dev Deps] update `@ljharb/eslint‑config`, `eslint`, `tape` [`7af9300`](https://github.com/ljharb/function-bind/commit/7af930023ae2ce7645489532821e4fbbcd7a2280) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `covert`, `tape` [`64a9127`](https://github.com/ljharb/function-bind/commit/64a9127ab0bd331b93d6572eaf6e9971967fc08c) +- [Tests] use `aud` instead of `npm audit` [`e75069c`](https://github.com/ljharb/function-bind/commit/e75069c50010a8fcce2a9ce2324934c35fdb4386) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `tape` [`d03555c`](https://github.com/ljharb/function-bind/commit/d03555ca59dea3b71ce710045e4303b9e2619e28) +- [meta] add `safe-publish-latest` [`9c8f809`](https://github.com/ljharb/function-bind/commit/9c8f8092aed027d7e80c94f517aa892385b64f09) +- [Dev Deps] update `@ljharb/eslint-config`, `tape` [`baf6893`](https://github.com/ljharb/function-bind/commit/baf6893e27f5b59abe88bc1995e6f6ed1e527397) +- [meta] create SECURITY.md [`4db1779`](https://github.com/ljharb/function-bind/commit/4db17799f1f28ae294cb95e0081ca2b591c3911b) +- [Tests] add `npm run audit` [`c8b38ec`](https://github.com/ljharb/function-bind/commit/c8b38ec40ed3f85dabdee40ed4148f1748375bc2) +- Revert "Point to the correct file" [`05cdf0f`](https://github.com/ljharb/function-bind/commit/05cdf0fa205c6a3c5ba40bbedd1dfa9874f915c9) + +## [v1.1.1](https://github.com/ljharb/function-bind/compare/v1.1.0...v1.1.1) - 2017-08-28 + +### Commits + +- [Tests] up to `node` `v8`; newer npm breaks on older node; fix scripts [`817f7d2`](https://github.com/ljharb/function-bind/commit/817f7d28470fdbff8ef608d4d565dd4d1430bc5e) +- [Dev Deps] update `eslint`, `jscs`, `tape`, `@ljharb/eslint-config` [`854288b`](https://github.com/ljharb/function-bind/commit/854288b1b6f5c555f89aceb9eff1152510262084) +- [Dev Deps] update `tape`, `jscs`, `eslint`, `@ljharb/eslint-config` [`83e639f`](https://github.com/ljharb/function-bind/commit/83e639ff74e6cd6921285bccec22c1bcf72311bd) +- Only apps should have lockfiles [`5ed97f5`](https://github.com/ljharb/function-bind/commit/5ed97f51235c17774e0832e122abda0f3229c908) +- Use a SPDX-compliant “license” field. [`5feefea`](https://github.com/ljharb/function-bind/commit/5feefea0dc0193993e83e5df01ded424403a5381) + +## [v1.1.0](https://github.com/ljharb/function-bind/compare/v1.0.2...v1.1.0) - 2016-02-14 + +### Commits + +- Update `eslint`, `tape`; use my personal shared `eslint` config [`9c9062a`](https://github.com/ljharb/function-bind/commit/9c9062abbe9dd70b59ea2c3a3c3a81f29b457097) +- Add `npm run eslint` [`dd96c56`](https://github.com/ljharb/function-bind/commit/dd96c56720034a3c1ffee10b8a59a6f7c53e24ad) +- [New] return the native `bind` when available. [`82186e0`](https://github.com/ljharb/function-bind/commit/82186e03d73e580f95ff167e03f3582bed90ed72) +- [Dev Deps] update `tape`, `jscs`, `eslint`, `@ljharb/eslint-config` [`a3dd767`](https://github.com/ljharb/function-bind/commit/a3dd76720c795cb7f4586b0544efabf8aa107b8b) +- Update `eslint` [`3dae2f7`](https://github.com/ljharb/function-bind/commit/3dae2f7423de30a2d20313ddb1edc19660142fe9) +- Update `tape`, `covert`, `jscs` [`a181eee`](https://github.com/ljharb/function-bind/commit/a181eee0cfa24eb229c6e843a971f36e060a2f6a) +- [Tests] up to `node` `v5.6`, `v4.3` [`964929a`](https://github.com/ljharb/function-bind/commit/964929a6a4ddb36fb128de2bcc20af5e4f22e1ed) +- Test up to `io.js` `v2.1` [`2be7310`](https://github.com/ljharb/function-bind/commit/2be7310f2f74886a7124ca925be411117d41d5ea) +- Update `tape`, `jscs`, `eslint`, `@ljharb/eslint-config` [`45f3d68`](https://github.com/ljharb/function-bind/commit/45f3d6865c6ca93726abcef54febe009087af101) +- [Dev Deps] update `tape`, `jscs` [`6e1340d`](https://github.com/ljharb/function-bind/commit/6e1340d94642deaecad3e717825db641af4f8b1f) +- [Tests] up to `io.js` `v3.3`, `node` `v4.1` [`d9bad2b`](https://github.com/ljharb/function-bind/commit/d9bad2b778b1b3a6dd2876087b88b3acf319f8cc) +- Update `eslint` [`935590c`](https://github.com/ljharb/function-bind/commit/935590caa024ab356102e4858e8fc315b2ccc446) +- [Dev Deps] update `jscs`, `eslint`, `@ljharb/eslint-config` [`8c9a1ef`](https://github.com/ljharb/function-bind/commit/8c9a1efd848e5167887aa8501857a0940a480c57) +- Test on `io.js` `v2.2` [`9a3a38c`](https://github.com/ljharb/function-bind/commit/9a3a38c92013aed6e108666e7bd40969b84ac86e) +- Run `travis-ci` tests on `iojs` and `node` v0.12; speed up builds; allow 0.8 failures. [`69afc26`](https://github.com/ljharb/function-bind/commit/69afc2617405b147dd2a8d8ae73ca9e9283f18b4) +- [Dev Deps] Update `tape`, `eslint` [`36c1be0`](https://github.com/ljharb/function-bind/commit/36c1be0ab12b45fe5df6b0fdb01a5d5137fd0115) +- Update `tape`, `jscs` [`98d8303`](https://github.com/ljharb/function-bind/commit/98d8303cd5ca1c6b8f985469f86b0d44d7d45f6e) +- Update `jscs` [`9633a4e`](https://github.com/ljharb/function-bind/commit/9633a4e9fbf82051c240855166e468ba8ba0846f) +- Update `tape`, `jscs` [`c80ef0f`](https://github.com/ljharb/function-bind/commit/c80ef0f46efc9791e76fa50de4414092ac147831) +- Test up to `io.js` `v3.0` [`7e2c853`](https://github.com/ljharb/function-bind/commit/7e2c8537d52ab9cf5a655755561d8917684c0df4) +- Test on `io.js` `v2.4` [`5a199a2`](https://github.com/ljharb/function-bind/commit/5a199a27ba46795ba5eaf0845d07d4b8232895c9) +- Test on `io.js` `v2.3` [`a511b88`](https://github.com/ljharb/function-bind/commit/a511b8896de0bddf3b56862daa416c701f4d0453) +- Fixing a typo from 822b4e1938db02dc9584aa434fd3a45cb20caf43 [`732d6b6`](https://github.com/ljharb/function-bind/commit/732d6b63a9b33b45230e630dbcac7a10855d3266) +- Update `jscs` [`da52a48`](https://github.com/ljharb/function-bind/commit/da52a4886c06d6490f46ae30b15e4163ba08905d) +- Lock covert to v1.0.0. [`d6150fd`](https://github.com/ljharb/function-bind/commit/d6150fda1e6f486718ebdeff823333d9e48e7430) + +## [v1.0.2](https://github.com/ljharb/function-bind/compare/v1.0.1...v1.0.2) - 2014-10-04 + +## [v1.0.1](https://github.com/ljharb/function-bind/compare/v1.0.0...v1.0.1) - 2014-10-03 + +### Merged + +- make CI build faster [`#3`](https://github.com/ljharb/function-bind/pull/3) + +### Commits + +- Using my standard jscs.json [`d8ee94c`](https://github.com/ljharb/function-bind/commit/d8ee94c993eff0a84cf5744fe6a29627f5cffa1a) +- Adding `npm run lint` [`7571ab7`](https://github.com/ljharb/function-bind/commit/7571ab7dfdbd99b25a1dbb2d232622bd6f4f9c10) +- Using consistent indentation [`e91a1b1`](https://github.com/ljharb/function-bind/commit/e91a1b13a61e99ec1e530e299b55508f74218a95) +- Updating jscs [`7e17892`](https://github.com/ljharb/function-bind/commit/7e1789284bc629bc9c1547a61c9b227bbd8c7a65) +- Using consistent quotes [`c50b57f`](https://github.com/ljharb/function-bind/commit/c50b57fcd1c5ec38320979c837006069ebe02b77) +- Adding keywords [`cb94631`](https://github.com/ljharb/function-bind/commit/cb946314eed35f21186a25fb42fc118772f9ee00) +- Directly export a function expression instead of using a declaration, and relying on hoisting. [`5a33c5f`](https://github.com/ljharb/function-bind/commit/5a33c5f45642de180e0d207110bf7d1843ceb87c) +- Naming npm URL and badge in README; use SVG [`2aef8fc`](https://github.com/ljharb/function-bind/commit/2aef8fcb79d54e63a58ae557c4e60949e05d5e16) +- Naming deps URLs in README [`04228d7`](https://github.com/ljharb/function-bind/commit/04228d766670ee45ca24e98345c1f6a7621065b5) +- Naming travis-ci URLs in README; using SVG [`62c810c`](https://github.com/ljharb/function-bind/commit/62c810c2f54ced956cd4d4ab7b793055addfe36e) +- Make sure functions are invoked correctly (also passing coverage tests) [`2b289b4`](https://github.com/ljharb/function-bind/commit/2b289b4dfbf037ffcfa4dc95eb540f6165e9e43a) +- Removing the strict mode pragmas; they make tests fail. [`1aa701d`](https://github.com/ljharb/function-bind/commit/1aa701d199ddc3782476e8f7eef82679be97b845) +- Adding myself as a contributor [`85fd57b`](https://github.com/ljharb/function-bind/commit/85fd57b0860e5a7af42de9a287f3f265fc6d72fc) +- Adding strict mode pragmas [`915b08e`](https://github.com/ljharb/function-bind/commit/915b08e084c86a722eafe7245e21db74aa21ca4c) +- Adding devDeps URLs to README [`4ccc731`](https://github.com/ljharb/function-bind/commit/4ccc73112c1769859e4ca3076caf4086b3cba2cd) +- Fixing the description. [`a7a472c`](https://github.com/ljharb/function-bind/commit/a7a472cf649af515c635cf560fc478fbe48999c8) +- Using a function expression instead of a function declaration. [`b5d3e4e`](https://github.com/ljharb/function-bind/commit/b5d3e4ea6aaffc63888953eeb1fbc7ff45f1fa14) +- Updating tape [`f086be6`](https://github.com/ljharb/function-bind/commit/f086be6029fb56dde61a258c1340600fa174d1e0) +- Updating jscs [`5f9bdb3`](https://github.com/ljharb/function-bind/commit/5f9bdb375ab13ba48f30852aab94029520c54d71) +- Updating jscs [`9b409ba`](https://github.com/ljharb/function-bind/commit/9b409ba6118e23395a4e5d83ef39152aab9d3bfc) +- Run coverage as part of tests. [`8e1b6d4`](https://github.com/ljharb/function-bind/commit/8e1b6d459f047d1bd4fee814e01247c984c80bd0) +- Run linter as part of tests [`c1ca83f`](https://github.com/ljharb/function-bind/commit/c1ca83f832df94587d09e621beba682fabfaa987) +- Updating covert [`701e837`](https://github.com/ljharb/function-bind/commit/701e83774b57b4d3ef631e1948143f43a72f4bb9) + +## [v1.0.0](https://github.com/ljharb/function-bind/compare/v0.2.0...v1.0.0) - 2014-08-09 + +### Commits + +- Make sure old and unstable nodes don't fail Travis [`27adca3`](https://github.com/ljharb/function-bind/commit/27adca34a4ab6ad67b6dfde43942a1b103ce4d75) +- Fixing an issue when the bound function is called as a constructor in ES3. [`e20122d`](https://github.com/ljharb/function-bind/commit/e20122d267d92ce553859b280cbbea5d27c07731) +- Adding `npm run coverage` [`a2e29c4`](https://github.com/ljharb/function-bind/commit/a2e29c4ecaef9e2f6cd1603e868c139073375502) +- Updating tape [`b741168`](https://github.com/ljharb/function-bind/commit/b741168b12b235b1717ff696087645526b69213c) +- Upgrading tape [`63631a0`](https://github.com/ljharb/function-bind/commit/63631a04c7fbe97cc2fa61829cc27246d6986f74) +- Updating tape [`363cb46`](https://github.com/ljharb/function-bind/commit/363cb46dafb23cb3e347729a22f9448051d78464) + +## v0.2.0 - 2014-03-23 + +### Commits + +- Updating test coverage to match es5-shim. [`aa94d44`](https://github.com/ljharb/function-bind/commit/aa94d44b8f9d7f69f10e060db7709aa7a694e5d4) +- initial [`942ee07`](https://github.com/ljharb/function-bind/commit/942ee07e94e542d91798137bc4b80b926137e066) +- Setting the bound function's length properly. [`079f46a`](https://github.com/ljharb/function-bind/commit/079f46a2d3515b7c0b308c2c13fceb641f97ca25) +- Ensuring that some older browsers will throw when given a regex. [`36ac55b`](https://github.com/ljharb/function-bind/commit/36ac55b87f460d4330253c92870aa26fbfe8227f) +- Removing npm scripts that don't have dependencies [`9d2be60`](https://github.com/ljharb/function-bind/commit/9d2be600002cb8bc8606f8f3585ad3e05868c750) +- Updating tape [`297a4ac`](https://github.com/ljharb/function-bind/commit/297a4acc5464db381940aafb194d1c88f4e678f3) +- Skipping length tests for now. [`d9891ea`](https://github.com/ljharb/function-bind/commit/d9891ea4d2aaffa69f408339cdd61ff740f70565) +- don't take my tea [`dccd930`](https://github.com/ljharb/function-bind/commit/dccd930bfd60ea10cb178d28c97550c3bc8c1e07) diff --git a/backend/node_modules/function-bind/LICENSE b/backend/node_modules/function-bind/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..62d6d237ff179b118746a64a34967f7ff4b5dff8 --- /dev/null +++ b/backend/node_modules/function-bind/LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2013 Raynos. + +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/backend/node_modules/function-bind/README.md b/backend/node_modules/function-bind/README.md new file mode 100644 index 0000000000000000000000000000000000000000..814c20b5a9e3c97f41dde308939b358f9ed93931 --- /dev/null +++ b/backend/node_modules/function-bind/README.md @@ -0,0 +1,46 @@ +# function-bind [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-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] + +Implementation of function.prototype.bind + +Old versions of phantomjs, Internet Explorer < 9, and node < 0.6 don't support `Function.prototype.bind`. + +## Example + +```js +Function.prototype.bind = require("function-bind") +``` + +## Installation + +`npm install function-bind` + +## Contributors + + - Raynos + +## MIT Licenced + +[package-url]: https://npmjs.org/package/function-bind +[npm-version-svg]: https://versionbadg.es/Raynos/function-bind.svg +[deps-svg]: https://david-dm.org/Raynos/function-bind.svg +[deps-url]: https://david-dm.org/Raynos/function-bind +[dev-deps-svg]: https://david-dm.org/Raynos/function-bind/dev-status.svg +[dev-deps-url]: https://david-dm.org/Raynos/function-bind#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/function-bind.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/function-bind.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/function-bind.svg +[downloads-url]: https://npm-stat.com/charts.html?package=function-bind +[codecov-image]: https://codecov.io/gh/Raynos/function-bind/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/Raynos/function-bind/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/Raynos/function-bind +[actions-url]: https://github.com/Raynos/function-bind/actions diff --git a/backend/node_modules/function-bind/implementation.js b/backend/node_modules/function-bind/implementation.js new file mode 100644 index 0000000000000000000000000000000000000000..fd4384cc0c34ce3e1e411bc8b0557680cf000eff --- /dev/null +++ b/backend/node_modules/function-bind/implementation.js @@ -0,0 +1,84 @@ +'use strict'; + +/* eslint no-invalid-this: 1 */ + +var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; +var toStr = Object.prototype.toString; +var max = Math.max; +var funcType = '[object Function]'; + +var concatty = function concatty(a, b) { + var arr = []; + + for (var i = 0; i < a.length; i += 1) { + arr[i] = a[i]; + } + for (var j = 0; j < b.length; j += 1) { + arr[j + a.length] = b[j]; + } + + return arr; +}; + +var slicy = function slicy(arrLike, offset) { + var arr = []; + for (var i = offset || 0, j = 0; i < arrLike.length; i += 1, j += 1) { + arr[j] = arrLike[i]; + } + return arr; +}; + +var joiny = function (arr, joiner) { + var str = ''; + for (var i = 0; i < arr.length; i += 1) { + str += arr[i]; + if (i + 1 < arr.length) { + str += joiner; + } + } + return str; +}; + +module.exports = function bind(that) { + var target = this; + if (typeof target !== 'function' || toStr.apply(target) !== funcType) { + throw new TypeError(ERROR_MESSAGE + target); + } + var args = slicy(arguments, 1); + + var bound; + var binder = function () { + if (this instanceof bound) { + var result = target.apply( + this, + concatty(args, arguments) + ); + if (Object(result) === result) { + return result; + } + return this; + } + return target.apply( + that, + concatty(args, arguments) + ); + + }; + + var boundLength = max(0, target.length - args.length); + var boundArgs = []; + for (var i = 0; i < boundLength; i++) { + boundArgs[i] = '$' + i; + } + + bound = Function('binder', 'return function (' + joiny(boundArgs, ',') + '){ return binder.apply(this,arguments); }')(binder); + + if (target.prototype) { + var Empty = function Empty() {}; + Empty.prototype = target.prototype; + bound.prototype = new Empty(); + Empty.prototype = null; + } + + return bound; +}; diff --git a/backend/node_modules/function-bind/index.js b/backend/node_modules/function-bind/index.js new file mode 100644 index 0000000000000000000000000000000000000000..3bb6b9609889f8131b2d6732ff1606e01e1365b2 --- /dev/null +++ b/backend/node_modules/function-bind/index.js @@ -0,0 +1,5 @@ +'use strict'; + +var implementation = require('./implementation'); + +module.exports = Function.prototype.bind || implementation; diff --git a/backend/node_modules/function-bind/package.json b/backend/node_modules/function-bind/package.json new file mode 100644 index 0000000000000000000000000000000000000000..618596389779061eb7f6f34edc61add4a517ca4f --- /dev/null +++ b/backend/node_modules/function-bind/package.json @@ -0,0 +1,87 @@ +{ + "name": "function-bind", + "version": "1.1.2", + "description": "Implementation of Function.prototype.bind", + "keywords": [ + "function", + "bind", + "shim", + "es5" + ], + "author": "Raynos ", + "repository": { + "type": "git", + "url": "https://github.com/Raynos/function-bind.git" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "main": "index", + "homepage": "https://github.com/Raynos/function-bind", + "contributors": [ + { + "name": "Raynos" + }, + { + "name": "Jordan Harband", + "url": "https://github.com/ljharb" + } + ], + "bugs": { + "url": "https://github.com/Raynos/function-bind/issues", + "email": "raynos2@gmail.com" + }, + "devDependencies": { + "@ljharb/eslint-config": "^21.1.0", + "aud": "^2.0.3", + "auto-changelog": "^2.4.0", + "eslint": "=8.8.0", + "in-publish": "^2.0.1", + "npmignore": "^0.3.0", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.7.1" + }, + "license": "MIT", + "scripts": { + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepack": "npmignore --auto --commentLines=autogenerated", + "pretest": "npm run lint", + "test": "npm run tests-only", + "posttest": "aud --production", + "tests-only": "nyc tape 'test/**/*.js'", + "lint": "eslint --ext=js,mjs .", + "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)\")\"" + }, + "testling": { + "files": "test/index.js", + "browsers": [ + "ie/8..latest", + "firefox/16..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" + ] + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + } +} diff --git a/backend/node_modules/function-bind/test/.eslintrc b/backend/node_modules/function-bind/test/.eslintrc new file mode 100644 index 0000000000000000000000000000000000000000..8a56d5b72fb008043cc69939648790ef482cdab8 --- /dev/null +++ b/backend/node_modules/function-bind/test/.eslintrc @@ -0,0 +1,9 @@ +{ + "rules": { + "array-bracket-newline": 0, + "array-element-newline": 0, + "max-statements-per-line": [2, { "max": 2 }], + "no-invalid-this": 0, + "no-magic-numbers": 0, + } +} diff --git a/backend/node_modules/function-bind/test/index.js b/backend/node_modules/function-bind/test/index.js new file mode 100644 index 0000000000000000000000000000000000000000..2edecce2f0fa5adcc88ebc609440221621048c05 --- /dev/null +++ b/backend/node_modules/function-bind/test/index.js @@ -0,0 +1,252 @@ +// jscs:disable requireUseStrict + +var test = require('tape'); + +var functionBind = require('../implementation'); +var getCurrentContext = function () { return this; }; + +test('functionBind is a function', function (t) { + t.equal(typeof functionBind, 'function'); + t.end(); +}); + +test('non-functions', function (t) { + var nonFunctions = [true, false, [], {}, 42, 'foo', NaN, /a/g]; + t.plan(nonFunctions.length); + for (var i = 0; i < nonFunctions.length; ++i) { + try { functionBind.call(nonFunctions[i]); } catch (ex) { + t.ok(ex instanceof TypeError, 'throws when given ' + String(nonFunctions[i])); + } + } + t.end(); +}); + +test('without a context', function (t) { + t.test('binds properly', function (st) { + var args, context; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + context = this; + }) + }; + namespace.func(1, 2, 3); + st.deepEqual(args, [1, 2, 3]); + st.equal(context, getCurrentContext.call()); + st.end(); + }); + + t.test('binds properly, and still supplies bound arguments', function (st) { + var args, context; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + context = this; + }, undefined, 1, 2, 3) + }; + namespace.func(4, 5, 6); + st.deepEqual(args, [1, 2, 3, 4, 5, 6]); + st.equal(context, getCurrentContext.call()); + st.end(); + }); + + t.test('returns properly', function (st) { + var args; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + return this; + }, null) + }; + var context = namespace.func(1, 2, 3); + st.equal(context, getCurrentContext.call(), 'returned context is namespaced context'); + st.deepEqual(args, [1, 2, 3], 'passed arguments are correct'); + st.end(); + }); + + t.test('returns properly with bound arguments', function (st) { + var args; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + return this; + }, null, 1, 2, 3) + }; + var context = namespace.func(4, 5, 6); + st.equal(context, getCurrentContext.call(), 'returned context is namespaced context'); + st.deepEqual(args, [1, 2, 3, 4, 5, 6], 'passed arguments are correct'); + st.end(); + }); + + t.test('called as a constructor', function (st) { + var thunkify = function (value) { + return function () { return value; }; + }; + st.test('returns object value', function (sst) { + var expectedReturnValue = [1, 2, 3]; + var Constructor = functionBind.call(thunkify(expectedReturnValue), null); + var result = new Constructor(); + sst.equal(result, expectedReturnValue); + sst.end(); + }); + + st.test('does not return primitive value', function (sst) { + var Constructor = functionBind.call(thunkify(42), null); + var result = new Constructor(); + sst.notEqual(result, 42); + sst.end(); + }); + + st.test('object from bound constructor is instance of original and bound constructor', function (sst) { + var A = function (x) { + this.name = x || 'A'; + }; + var B = functionBind.call(A, null, 'B'); + + var result = new B(); + sst.ok(result instanceof B, 'result is instance of bound constructor'); + sst.ok(result instanceof A, 'result is instance of original constructor'); + sst.end(); + }); + + st.end(); + }); + + t.end(); +}); + +test('with a context', function (t) { + t.test('with no bound arguments', function (st) { + var args, context; + var boundContext = {}; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + context = this; + }, boundContext) + }; + namespace.func(1, 2, 3); + st.equal(context, boundContext, 'binds a context properly'); + st.deepEqual(args, [1, 2, 3], 'supplies passed arguments'); + st.end(); + }); + + t.test('with bound arguments', function (st) { + var args, context; + var boundContext = {}; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + context = this; + }, boundContext, 1, 2, 3) + }; + namespace.func(4, 5, 6); + st.equal(context, boundContext, 'binds a context properly'); + st.deepEqual(args, [1, 2, 3, 4, 5, 6], 'supplies bound and passed arguments'); + st.end(); + }); + + t.test('returns properly', function (st) { + var boundContext = {}; + var args; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + return this; + }, boundContext) + }; + var context = namespace.func(1, 2, 3); + st.equal(context, boundContext, 'returned context is bound context'); + st.notEqual(context, getCurrentContext.call(), 'returned context is not lexical context'); + st.deepEqual(args, [1, 2, 3], 'passed arguments are correct'); + st.end(); + }); + + t.test('returns properly with bound arguments', function (st) { + var boundContext = {}; + var args; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + return this; + }, boundContext, 1, 2, 3) + }; + var context = namespace.func(4, 5, 6); + st.equal(context, boundContext, 'returned context is bound context'); + st.notEqual(context, getCurrentContext.call(), 'returned context is not lexical context'); + st.deepEqual(args, [1, 2, 3, 4, 5, 6], 'passed arguments are correct'); + st.end(); + }); + + t.test('passes the correct arguments when called as a constructor', function (st) { + var expected = { name: 'Correct' }; + var namespace = { + Func: functionBind.call(function (arg) { + return arg; + }, { name: 'Incorrect' }) + }; + var returned = new namespace.Func(expected); + st.equal(returned, expected, 'returns the right arg when called as a constructor'); + st.end(); + }); + + t.test('has the new instance\'s context when called as a constructor', function (st) { + var actualContext; + var expectedContext = { foo: 'bar' }; + var namespace = { + Func: functionBind.call(function () { + actualContext = this; + }, expectedContext) + }; + var result = new namespace.Func(); + st.equal(result instanceof namespace.Func, true); + st.notEqual(actualContext, expectedContext); + st.end(); + }); + + t.end(); +}); + +test('bound function length', function (t) { + t.test('sets a correct length without thisArg', function (st) { + var subject = functionBind.call(function (a, b, c) { return a + b + c; }); + st.equal(subject.length, 3); + st.equal(subject(1, 2, 3), 6); + st.end(); + }); + + t.test('sets a correct length with thisArg', function (st) { + var subject = functionBind.call(function (a, b, c) { return a + b + c; }, {}); + st.equal(subject.length, 3); + st.equal(subject(1, 2, 3), 6); + st.end(); + }); + + t.test('sets a correct length without thisArg and first argument', function (st) { + var subject = functionBind.call(function (a, b, c) { return a + b + c; }, undefined, 1); + st.equal(subject.length, 2); + st.equal(subject(2, 3), 6); + st.end(); + }); + + t.test('sets a correct length with thisArg and first argument', function (st) { + var subject = functionBind.call(function (a, b, c) { return a + b + c; }, {}, 1); + st.equal(subject.length, 2); + st.equal(subject(2, 3), 6); + st.end(); + }); + + t.test('sets a correct length without thisArg and too many arguments', function (st) { + var subject = functionBind.call(function (a, b, c) { return a + b + c; }, undefined, 1, 2, 3, 4); + st.equal(subject.length, 0); + st.equal(subject(), 6); + st.end(); + }); + + t.test('sets a correct length with thisArg and too many arguments', function (st) { + var subject = functionBind.call(function (a, b, c) { return a + b + c; }, {}, 1, 2, 3, 4); + st.equal(subject.length, 0); + st.equal(subject(), 6); + st.end(); + }); +}); diff --git a/backend/node_modules/get-intrinsic/.eslintrc b/backend/node_modules/get-intrinsic/.eslintrc new file mode 100644 index 0000000000000000000000000000000000000000..8376636235836c26c93bb23afd5fdf74c0cb67af --- /dev/null +++ b/backend/node_modules/get-intrinsic/.eslintrc @@ -0,0 +1,38 @@ +{ + "root": true, + + "extends": "@ljharb", + + "env": { + "es6": true, + "es2017": true, + "es2020": true, + "es2021": true, + "es2022": true, + }, + + "rules": { + "array-bracket-newline": 0, + "complexity": 0, + "eqeqeq": [2, "allow-null"], + "func-name-matching": 0, + "id-length": 0, + "max-lines": 0, + "max-lines-per-function": [2, 90], + "max-params": [2, 4], + "max-statements": 0, + "max-statements-per-line": [2, { "max": 2 }], + "multiline-comment-style": 0, + "no-magic-numbers": 0, + "sort-keys": 0, + }, + + "overrides": [ + { + "files": "test/**", + "rules": { + "new-cap": 0, + }, + }, + ], +} diff --git a/backend/node_modules/get-intrinsic/.github/FUNDING.yml b/backend/node_modules/get-intrinsic/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..8e8da0dda153deb6bf1bfbb2c1a7e5e19aea08c5 --- /dev/null +++ b/backend/node_modules/get-intrinsic/.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/get-intrinsic +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/backend/node_modules/get-intrinsic/.nycrc b/backend/node_modules/get-intrinsic/.nycrc new file mode 100644 index 0000000000000000000000000000000000000000..bdd626ce91477abbdd489b79988baebadbd3c897 --- /dev/null +++ b/backend/node_modules/get-intrinsic/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/backend/node_modules/get-intrinsic/CHANGELOG.md b/backend/node_modules/get-intrinsic/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..96d5397fca046fc1ed65104609c18d1a73ae8725 --- /dev/null +++ b/backend/node_modules/get-intrinsic/CHANGELOG.md @@ -0,0 +1,143 @@ +# 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.2.4](https://github.com/ljharb/get-intrinsic/compare/v1.2.3...v1.2.4) - 2024-02-05 + +### Commits + +- [Refactor] use all 7 <+ ES6 Errors from `es-errors` [`bcac811`](https://github.com/ljharb/get-intrinsic/commit/bcac811abdc1c982e12abf848a410d6aae148d14) + +## [v1.2.3](https://github.com/ljharb/get-intrinsic/compare/v1.2.2...v1.2.3) - 2024-02-03 + +### Commits + +- [Refactor] use `es-errors`, so things that only need those do not need `get-intrinsic` [`f11db9c`](https://github.com/ljharb/get-intrinsic/commit/f11db9c4fb97d87bbd53d3c73ac6b3db3613ad3b) +- [Dev Deps] update `aud`, `es-abstract`, `mock-property`, `npmignore` [`b7ac7d1`](https://github.com/ljharb/get-intrinsic/commit/b7ac7d1616fefb03877b1aed0c8f8d61aad32b6c) +- [meta] simplify `exports` [`faa0cc6`](https://github.com/ljharb/get-intrinsic/commit/faa0cc618e2830ffb51a8202490b0c215d965cbc) +- [meta] add missing `engines.node` [`774dd0b`](https://github.com/ljharb/get-intrinsic/commit/774dd0b3e8f741c3f05a6322d124d6087f146af1) +- [Dev Deps] update `tape` [`5828e8e`](https://github.com/ljharb/get-intrinsic/commit/5828e8e4a04e69312e87a36c0ea39428a7a4c3d8) +- [Robustness] use null objects for lookups [`eb9a11f`](https://github.com/ljharb/get-intrinsic/commit/eb9a11fa9eb3e13b193fcc05a7fb814341b1a7b7) +- [meta] add `sideEffects` flag [`89bcc7a`](https://github.com/ljharb/get-intrinsic/commit/89bcc7a42e19bf07b7c21e3094d5ab177109e6d2) + +## [v1.2.2](https://github.com/ljharb/get-intrinsic/compare/v1.2.1...v1.2.2) - 2023-10-20 + +### Commits + +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `call-bind`, `es-abstract`, `mock-property`, `object-inspect`, `tape` [`f51bcf2`](https://github.com/ljharb/get-intrinsic/commit/f51bcf26412d58d17ce17c91c9afd0ad271f0762) +- [Refactor] use `hasown` instead of `has` [`18d14b7`](https://github.com/ljharb/get-intrinsic/commit/18d14b799bea6b5765e1cec91890830cbcdb0587) +- [Deps] update `function-bind` [`6e109c8`](https://github.com/ljharb/get-intrinsic/commit/6e109c81e03804cc5e7824fb64353cdc3d8ee2c7) + +## [v1.2.1](https://github.com/ljharb/get-intrinsic/compare/v1.2.0...v1.2.1) - 2023-05-13 + +### Commits + +- [Fix] avoid a crash in envs without `__proto__` [`7bad8d0`](https://github.com/ljharb/get-intrinsic/commit/7bad8d061bf8721733b58b73a2565af2b6756b64) +- [Dev Deps] update `es-abstract` [`c60e6b7`](https://github.com/ljharb/get-intrinsic/commit/c60e6b7b4cf9660c7f27ed970970fd55fac48dc5) + +## [v1.2.0](https://github.com/ljharb/get-intrinsic/compare/v1.1.3...v1.2.0) - 2023-01-19 + +### Commits + +- [actions] update checkout action [`ca6b12f`](https://github.com/ljharb/get-intrinsic/commit/ca6b12f31eaacea4ea3b055e744cd61623385ffb) +- [Dev Deps] update `@ljharb/eslint-config`, `es-abstract`, `object-inspect`, `tape` [`41a3727`](https://github.com/ljharb/get-intrinsic/commit/41a3727d0026fa04273ae216a5f8e12eefd72da8) +- [Fix] ensure `Error.prototype` is undeniable [`c511e97`](https://github.com/ljharb/get-intrinsic/commit/c511e97ae99c764c4524b540dee7a70757af8da3) +- [Dev Deps] update `aud`, `es-abstract`, `tape` [`1bef8a8`](https://github.com/ljharb/get-intrinsic/commit/1bef8a8fd439ebb80863199b6189199e0851ac67) +- [Dev Deps] update `aud`, `es-abstract` [`0d41f16`](https://github.com/ljharb/get-intrinsic/commit/0d41f16bcd500bc28b7bfc98043ebf61ea081c26) +- [New] add `BigInt64Array` and `BigUint64Array` [`a6cca25`](https://github.com/ljharb/get-intrinsic/commit/a6cca25f29635889b7e9bd669baf9e04be90e48c) +- [Tests] use `gopd` [`ecf7722`](https://github.com/ljharb/get-intrinsic/commit/ecf7722240d15cfd16edda06acf63359c10fb9bd) + +## [v1.1.3](https://github.com/ljharb/get-intrinsic/compare/v1.1.2...v1.1.3) - 2022-09-12 + +### Commits + +- [Dev Deps] update `es-abstract`, `es-value-fixtures`, `tape` [`07ff291`](https://github.com/ljharb/get-intrinsic/commit/07ff291816406ebe5a12d7f16965bde0942dd688) +- [Fix] properly check for % signs [`50ac176`](https://github.com/ljharb/get-intrinsic/commit/50ac1760fe99c227e64eabde76e9c0e44cd881b5) + +## [v1.1.2](https://github.com/ljharb/get-intrinsic/compare/v1.1.1...v1.1.2) - 2022-06-08 + +### Fixed + +- [Fix] properly validate against extra % signs [`#16`](https://github.com/ljharb/get-intrinsic/issues/16) + +### Commits + +- [actions] reuse common workflows [`0972547`](https://github.com/ljharb/get-intrinsic/commit/0972547efd0abc863fe4c445a6ca7eb4f8c6901d) +- [meta] use `npmignore` to autogenerate an npmignore file [`5ba0b51`](https://github.com/ljharb/get-intrinsic/commit/5ba0b51d8d8d4f1c31d426d74abc0770fd106bad) +- [actions] use `node/install` instead of `node/run`; use `codecov` action [`c364492`](https://github.com/ljharb/get-intrinsic/commit/c364492af4af51333e6f81c0bf21fd3d602c3661) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `es-abstract`, `object-inspect`, `tape` [`dc04dad`](https://github.com/ljharb/get-intrinsic/commit/dc04dad86f6e5608775a2640cb0db5927ae29ed9) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `es-abstract`, `object-inspect`, `safe-publish-latest`, `tape` [`1c14059`](https://github.com/ljharb/get-intrinsic/commit/1c1405984e86dd2dc9366c15d8a0294a96a146a5) +- [Tests] use `mock-property` [`b396ef0`](https://github.com/ljharb/get-intrinsic/commit/b396ef05bb73b1d699811abd64b0d9b97997fdda) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `object-inspect`, `tape` [`c2c758d`](https://github.com/ljharb/get-intrinsic/commit/c2c758d3b90af4fef0a76910d8d3c292ec8d1d3e) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `es-abstract`, `es-value-fixtures`, `object-inspect`, `tape` [`29e3c09`](https://github.com/ljharb/get-intrinsic/commit/29e3c091c2bf3e17099969847e8729d0e46896de) +- [actions] update codecov uploader [`8cbc141`](https://github.com/ljharb/get-intrinsic/commit/8cbc1418940d7a8941f3a7985cbc4ac095c5e13d) +- [Dev Deps] update `@ljharb/eslint-config`, `es-abstract`, `es-value-fixtures`, `object-inspect`, `tape` [`10b6f5c`](https://github.com/ljharb/get-intrinsic/commit/10b6f5c02593fb3680c581d696ac124e30652932) +- [readme] add github actions/codecov badges [`4e25400`](https://github.com/ljharb/get-intrinsic/commit/4e25400d9f51ae9eb059cbe22d9144e70ea214e8) +- [Tests] use `for-each` instead of `foreach` [`c05b957`](https://github.com/ljharb/get-intrinsic/commit/c05b957ad9a7bc7721af7cc9e9be1edbfe057496) +- [Dev Deps] update `es-abstract` [`29b05ae`](https://github.com/ljharb/get-intrinsic/commit/29b05aec3e7330e9ad0b8e0f685a9112c20cdd97) +- [meta] use `prepublishOnly` script for npm 7+ [`95c285d`](https://github.com/ljharb/get-intrinsic/commit/95c285da810516057d3bbfa871176031af38f05d) +- [Deps] update `has-symbols` [`593cb4f`](https://github.com/ljharb/get-intrinsic/commit/593cb4fb38e7922e40e42c183f45274b636424cd) +- [readme] fix repo URLs [`1c8305b`](https://github.com/ljharb/get-intrinsic/commit/1c8305b5365827c9b6fc785434aac0e1328ff2f5) +- [Deps] update `has-symbols` [`c7138b6`](https://github.com/ljharb/get-intrinsic/commit/c7138b6c6d73132d859471fb8c13304e1e7c8b20) +- [Dev Deps] remove unused `has-bigints` [`bd63aff`](https://github.com/ljharb/get-intrinsic/commit/bd63aff6ad8f3a986c557fcda2914187bdaab359) + +## [v1.1.1](https://github.com/ljharb/get-intrinsic/compare/v1.1.0...v1.1.1) - 2021-02-03 + +### Fixed + +- [meta] export `./package.json` [`#9`](https://github.com/ljharb/get-intrinsic/issues/9) + +### Commits + +- [readme] flesh out the readme; use `evalmd` [`d12f12c`](https://github.com/ljharb/get-intrinsic/commit/d12f12c15345a0a0772cc65a7c64369529abd614) +- [eslint] set up proper globals config [`5a8c098`](https://github.com/ljharb/get-intrinsic/commit/5a8c0984e3319d1ac0e64b102f8ec18b64e79f36) +- [Dev Deps] update `eslint` [`7b9a5c0`](https://github.com/ljharb/get-intrinsic/commit/7b9a5c0d31a90ca1a1234181c74988fb046701cd) + +## [v1.1.0](https://github.com/ljharb/get-intrinsic/compare/v1.0.2...v1.1.0) - 2021-01-25 + +### Fixed + +- [Refactor] delay `Function` eval until syntax-derived values are requested [`#3`](https://github.com/ljharb/get-intrinsic/issues/3) + +### Commits + +- [Tests] migrate tests to Github Actions [`2ab762b`](https://github.com/ljharb/get-intrinsic/commit/2ab762b48164aea8af37a40ba105bbc8246ab8c4) +- [meta] do not publish github action workflow files [`5e7108e`](https://github.com/ljharb/get-intrinsic/commit/5e7108e4768b244d48d9567ba4f8a6cab9c65b8e) +- [Tests] add some coverage [`01ac7a8`](https://github.com/ljharb/get-intrinsic/commit/01ac7a87ac29738567e8524cd8c9e026b1fa8cb3) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `call-bind`, `es-abstract`, `tape`; add `call-bind` [`911b672`](https://github.com/ljharb/get-intrinsic/commit/911b672fbffae433a96924c6ce013585e425f4b7) +- [Refactor] rearrange evalled constructors a bit [`7e7e4bf`](https://github.com/ljharb/get-intrinsic/commit/7e7e4bf583f3799c8ac1c6c5e10d2cb553957347) +- [meta] add Automatic Rebase and Require Allow Edits workflows [`0199968`](https://github.com/ljharb/get-intrinsic/commit/01999687a263ffce0a3cb011dfbcb761754aedbc) + +## [v1.0.2](https://github.com/ljharb/get-intrinsic/compare/v1.0.1...v1.0.2) - 2020-12-17 + +### Commits + +- [Fix] Throw for non‑existent intrinsics [`68f873b`](https://github.com/ljharb/get-intrinsic/commit/68f873b013c732a05ad6f5fc54f697e55515461b) +- [Fix] Throw for non‑existent segments in the intrinsic path [`8325dee`](https://github.com/ljharb/get-intrinsic/commit/8325deee43128f3654d3399aa9591741ebe17b21) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `has-bigints`, `object-inspect` [`0c227a7`](https://github.com/ljharb/get-intrinsic/commit/0c227a7d8b629166f25715fd242553892e458525) +- [meta] do not lint coverage output [`70d2419`](https://github.com/ljharb/get-intrinsic/commit/70d24199b620043cd9110fc5f426d214ebe21dc9) + +## [v1.0.1](https://github.com/ljharb/get-intrinsic/compare/v1.0.0...v1.0.1) - 2020-10-30 + +### Commits + +- [Tests] gather coverage data on every job [`d1d280d`](https://github.com/ljharb/get-intrinsic/commit/d1d280dec714e3f0519cc877dbcb193057d9cac6) +- [Fix] add missing dependencies [`5031771`](https://github.com/ljharb/get-intrinsic/commit/5031771bb1095b38be88ce7c41d5de88718e432e) +- [Tests] use `es-value-fixtures` [`af48765`](https://github.com/ljharb/get-intrinsic/commit/af48765a23c5323fb0b6b38dbf00eb5099c7bebc) + +## v1.0.0 - 2020-10-29 + +### Commits + +- Implementation [`bbce57c`](https://github.com/ljharb/get-intrinsic/commit/bbce57c6f33d05b2d8d3efa273ceeb3ee01127bb) +- Tests [`17b4f0d`](https://github.com/ljharb/get-intrinsic/commit/17b4f0d56dea6b4059b56fc30ef3ee4d9500ebc2) +- Initial commit [`3153294`](https://github.com/ljharb/get-intrinsic/commit/31532948de363b0a27dd9fd4649e7b7028ec4b44) +- npm init [`fb326c4`](https://github.com/ljharb/get-intrinsic/commit/fb326c4d2817c8419ec31de1295f06bb268a7902) +- [meta] add Automatic Rebase and Require Allow Edits workflows [`48862fb`](https://github.com/ljharb/get-intrinsic/commit/48862fb2508c8f6a57968e6d08b7c883afc9d550) +- [meta] add `auto-changelog` [`5f28ad0`](https://github.com/ljharb/get-intrinsic/commit/5f28ad019e060a353d8028f9f2591a9cc93074a1) +- [meta] add "funding"; create `FUNDING.yml` [`c2bbdde`](https://github.com/ljharb/get-intrinsic/commit/c2bbddeba73a875be61484ee4680b129a6d4e0a1) +- [Tests] add `npm run lint` [`0a84b98`](https://github.com/ljharb/get-intrinsic/commit/0a84b98b22b7cf7a748666f705b0003a493c35fd) +- Only apps should have lockfiles [`9586c75`](https://github.com/ljharb/get-intrinsic/commit/9586c75866c1ee678e4d5d4dbbdef6997e511b05) diff --git a/backend/node_modules/get-intrinsic/LICENSE b/backend/node_modules/get-intrinsic/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..48f05d01d0acae75acada5bd42a3442d0699d067 --- /dev/null +++ b/backend/node_modules/get-intrinsic/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 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/backend/node_modules/get-intrinsic/README.md b/backend/node_modules/get-intrinsic/README.md new file mode 100644 index 0000000000000000000000000000000000000000..3aa0bba4037e57211920a2cf8b57194b61eb24d9 --- /dev/null +++ b/backend/node_modules/get-intrinsic/README.md @@ -0,0 +1,71 @@ +# get-intrinsic [![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] + +Get and robustly cache all JS language-level intrinsics at first require time. + +See the syntax described [in the JS spec](https://tc39.es/ecma262/#sec-well-known-intrinsic-objects) for reference. + +## Example + +```js +var GetIntrinsic = require('get-intrinsic'); +var assert = require('assert'); + +// static methods +assert.equal(GetIntrinsic('%Math.pow%'), Math.pow); +assert.equal(Math.pow(2, 3), 8); +assert.equal(GetIntrinsic('%Math.pow%')(2, 3), 8); +delete Math.pow; +assert.equal(GetIntrinsic('%Math.pow%')(2, 3), 8); + +// instance methods +var arr = [1]; +assert.equal(GetIntrinsic('%Array.prototype.push%'), Array.prototype.push); +assert.deepEqual(arr, [1]); + +arr.push(2); +assert.deepEqual(arr, [1, 2]); + +GetIntrinsic('%Array.prototype.push%').call(arr, 3); +assert.deepEqual(arr, [1, 2, 3]); + +delete Array.prototype.push; +GetIntrinsic('%Array.prototype.push%').call(arr, 4); +assert.deepEqual(arr, [1, 2, 3, 4]); + +// missing features +delete JSON.parse; // to simulate a real intrinsic that is missing in the environment +assert.throws(() => GetIntrinsic('%JSON.parse%')); +assert.equal(undefined, GetIntrinsic('%JSON.parse%', true)); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +## Security + +Please email [@ljharb](https://github.com/ljharb) or see https://tidelift.com/security if you have a potential security vulnerability to report. + +[package-url]: https://npmjs.org/package/get-intrinsic +[npm-version-svg]: https://versionbadg.es/ljharb/get-intrinsic.svg +[deps-svg]: https://david-dm.org/ljharb/get-intrinsic.svg +[deps-url]: https://david-dm.org/ljharb/get-intrinsic +[dev-deps-svg]: https://david-dm.org/ljharb/get-intrinsic/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/get-intrinsic#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/get-intrinsic.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/get-intrinsic.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/get-intrinsic.svg +[downloads-url]: https://npm-stat.com/charts.html?package=get-intrinsic +[codecov-image]: https://codecov.io/gh/ljharb/get-intrinsic/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/get-intrinsic/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/get-intrinsic +[actions-url]: https://github.com/ljharb/get-intrinsic/actions diff --git a/backend/node_modules/get-intrinsic/index.js b/backend/node_modules/get-intrinsic/index.js new file mode 100644 index 0000000000000000000000000000000000000000..c25e2c42eeef322ae75b87691be7217c665965b1 --- /dev/null +++ b/backend/node_modules/get-intrinsic/index.js @@ -0,0 +1,359 @@ +'use strict'; + +var undefined; + +var $Error = require('es-errors'); +var $EvalError = require('es-errors/eval'); +var $RangeError = require('es-errors/range'); +var $ReferenceError = require('es-errors/ref'); +var $SyntaxError = require('es-errors/syntax'); +var $TypeError = require('es-errors/type'); +var $URIError = require('es-errors/uri'); + +var $Function = Function; + +// eslint-disable-next-line consistent-return +var getEvalledConstructor = function (expressionSyntax) { + try { + return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')(); + } catch (e) {} +}; + +var $gOPD = Object.getOwnPropertyDescriptor; +if ($gOPD) { + try { + $gOPD({}, ''); + } catch (e) { + $gOPD = null; // this is IE 8, which has a broken gOPD + } +} + +var throwTypeError = function () { + throw new $TypeError(); +}; +var ThrowTypeError = $gOPD + ? (function () { + try { + // eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties + arguments.callee; // IE 8 does not throw here + return throwTypeError; + } catch (calleeThrows) { + try { + // IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '') + return $gOPD(arguments, 'callee').get; + } catch (gOPDthrows) { + return throwTypeError; + } + } + }()) + : throwTypeError; + +var hasSymbols = require('has-symbols')(); +var hasProto = require('has-proto')(); + +var getProto = Object.getPrototypeOf || ( + hasProto + ? function (x) { return x.__proto__; } // eslint-disable-line no-proto + : null +); + +var needsEval = {}; + +var TypedArray = typeof Uint8Array === 'undefined' || !getProto ? undefined : getProto(Uint8Array); + +var INTRINSICS = { + __proto__: null, + '%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError, + '%Array%': Array, + '%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer, + '%ArrayIteratorPrototype%': hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined, + '%AsyncFromSyncIteratorPrototype%': undefined, + '%AsyncFunction%': needsEval, + '%AsyncGenerator%': needsEval, + '%AsyncGeneratorFunction%': needsEval, + '%AsyncIteratorPrototype%': needsEval, + '%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics, + '%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt, + '%BigInt64Array%': typeof BigInt64Array === 'undefined' ? undefined : BigInt64Array, + '%BigUint64Array%': typeof BigUint64Array === 'undefined' ? undefined : BigUint64Array, + '%Boolean%': Boolean, + '%DataView%': typeof DataView === 'undefined' ? undefined : DataView, + '%Date%': Date, + '%decodeURI%': decodeURI, + '%decodeURIComponent%': decodeURIComponent, + '%encodeURI%': encodeURI, + '%encodeURIComponent%': encodeURIComponent, + '%Error%': $Error, + '%eval%': eval, // eslint-disable-line no-eval + '%EvalError%': $EvalError, + '%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array, + '%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array, + '%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry, + '%Function%': $Function, + '%GeneratorFunction%': needsEval, + '%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array, + '%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array, + '%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array, + '%isFinite%': isFinite, + '%isNaN%': isNaN, + '%IteratorPrototype%': hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined, + '%JSON%': typeof JSON === 'object' ? JSON : undefined, + '%Map%': typeof Map === 'undefined' ? undefined : Map, + '%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Map()[Symbol.iterator]()), + '%Math%': Math, + '%Number%': Number, + '%Object%': Object, + '%parseFloat%': parseFloat, + '%parseInt%': parseInt, + '%Promise%': typeof Promise === 'undefined' ? undefined : Promise, + '%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy, + '%RangeError%': $RangeError, + '%ReferenceError%': $ReferenceError, + '%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect, + '%RegExp%': RegExp, + '%Set%': typeof Set === 'undefined' ? undefined : Set, + '%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Set()[Symbol.iterator]()), + '%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer, + '%String%': String, + '%StringIteratorPrototype%': hasSymbols && getProto ? getProto(''[Symbol.iterator]()) : undefined, + '%Symbol%': hasSymbols ? Symbol : undefined, + '%SyntaxError%': $SyntaxError, + '%ThrowTypeError%': ThrowTypeError, + '%TypedArray%': TypedArray, + '%TypeError%': $TypeError, + '%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array, + '%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray, + '%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array, + '%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array, + '%URIError%': $URIError, + '%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap, + '%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef, + '%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet +}; + +if (getProto) { + try { + null.error; // eslint-disable-line no-unused-expressions + } catch (e) { + // https://github.com/tc39/proposal-shadowrealm/pull/384#issuecomment-1364264229 + var errorProto = getProto(getProto(e)); + INTRINSICS['%Error.prototype%'] = errorProto; + } +} + +var doEval = function doEval(name) { + var value; + if (name === '%AsyncFunction%') { + value = getEvalledConstructor('async function () {}'); + } else if (name === '%GeneratorFunction%') { + value = getEvalledConstructor('function* () {}'); + } else if (name === '%AsyncGeneratorFunction%') { + value = getEvalledConstructor('async function* () {}'); + } else if (name === '%AsyncGenerator%') { + var fn = doEval('%AsyncGeneratorFunction%'); + if (fn) { + value = fn.prototype; + } + } else if (name === '%AsyncIteratorPrototype%') { + var gen = doEval('%AsyncGenerator%'); + if (gen && getProto) { + value = getProto(gen.prototype); + } + } + + INTRINSICS[name] = value; + + return value; +}; + +var LEGACY_ALIASES = { + __proto__: null, + '%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'], + '%ArrayPrototype%': ['Array', 'prototype'], + '%ArrayProto_entries%': ['Array', 'prototype', 'entries'], + '%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'], + '%ArrayProto_keys%': ['Array', 'prototype', 'keys'], + '%ArrayProto_values%': ['Array', 'prototype', 'values'], + '%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'], + '%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'], + '%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'], + '%BooleanPrototype%': ['Boolean', 'prototype'], + '%DataViewPrototype%': ['DataView', 'prototype'], + '%DatePrototype%': ['Date', 'prototype'], + '%ErrorPrototype%': ['Error', 'prototype'], + '%EvalErrorPrototype%': ['EvalError', 'prototype'], + '%Float32ArrayPrototype%': ['Float32Array', 'prototype'], + '%Float64ArrayPrototype%': ['Float64Array', 'prototype'], + '%FunctionPrototype%': ['Function', 'prototype'], + '%Generator%': ['GeneratorFunction', 'prototype'], + '%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'], + '%Int8ArrayPrototype%': ['Int8Array', 'prototype'], + '%Int16ArrayPrototype%': ['Int16Array', 'prototype'], + '%Int32ArrayPrototype%': ['Int32Array', 'prototype'], + '%JSONParse%': ['JSON', 'parse'], + '%JSONStringify%': ['JSON', 'stringify'], + '%MapPrototype%': ['Map', 'prototype'], + '%NumberPrototype%': ['Number', 'prototype'], + '%ObjectPrototype%': ['Object', 'prototype'], + '%ObjProto_toString%': ['Object', 'prototype', 'toString'], + '%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'], + '%PromisePrototype%': ['Promise', 'prototype'], + '%PromiseProto_then%': ['Promise', 'prototype', 'then'], + '%Promise_all%': ['Promise', 'all'], + '%Promise_reject%': ['Promise', 'reject'], + '%Promise_resolve%': ['Promise', 'resolve'], + '%RangeErrorPrototype%': ['RangeError', 'prototype'], + '%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'], + '%RegExpPrototype%': ['RegExp', 'prototype'], + '%SetPrototype%': ['Set', 'prototype'], + '%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'], + '%StringPrototype%': ['String', 'prototype'], + '%SymbolPrototype%': ['Symbol', 'prototype'], + '%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'], + '%TypedArrayPrototype%': ['TypedArray', 'prototype'], + '%TypeErrorPrototype%': ['TypeError', 'prototype'], + '%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'], + '%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'], + '%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'], + '%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'], + '%URIErrorPrototype%': ['URIError', 'prototype'], + '%WeakMapPrototype%': ['WeakMap', 'prototype'], + '%WeakSetPrototype%': ['WeakSet', 'prototype'] +}; + +var bind = require('function-bind'); +var hasOwn = require('hasown'); +var $concat = bind.call(Function.call, Array.prototype.concat); +var $spliceApply = bind.call(Function.apply, Array.prototype.splice); +var $replace = bind.call(Function.call, String.prototype.replace); +var $strSlice = bind.call(Function.call, String.prototype.slice); +var $exec = bind.call(Function.call, RegExp.prototype.exec); + +/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */ +var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; +var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */ +var stringToPath = function stringToPath(string) { + var first = $strSlice(string, 0, 1); + var last = $strSlice(string, -1); + if (first === '%' && last !== '%') { + throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`'); + } else if (last === '%' && first !== '%') { + throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`'); + } + var result = []; + $replace(string, rePropName, function (match, number, quote, subString) { + result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match; + }); + return result; +}; +/* end adaptation */ + +var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) { + var intrinsicName = name; + var alias; + if (hasOwn(LEGACY_ALIASES, intrinsicName)) { + alias = LEGACY_ALIASES[intrinsicName]; + intrinsicName = '%' + alias[0] + '%'; + } + + if (hasOwn(INTRINSICS, intrinsicName)) { + var value = INTRINSICS[intrinsicName]; + if (value === needsEval) { + value = doEval(intrinsicName); + } + if (typeof value === 'undefined' && !allowMissing) { + throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!'); + } + + return { + alias: alias, + name: intrinsicName, + value: value + }; + } + + throw new $SyntaxError('intrinsic ' + name + ' does not exist!'); +}; + +module.exports = function GetIntrinsic(name, allowMissing) { + if (typeof name !== 'string' || name.length === 0) { + throw new $TypeError('intrinsic name must be a non-empty string'); + } + if (arguments.length > 1 && typeof allowMissing !== 'boolean') { + throw new $TypeError('"allowMissing" argument must be a boolean'); + } + + if ($exec(/^%?[^%]*%?$/, name) === null) { + throw new $SyntaxError('`%` may not be present anywhere but at the beginning and end of the intrinsic name'); + } + var parts = stringToPath(name); + var intrinsicBaseName = parts.length > 0 ? parts[0] : ''; + + var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing); + var intrinsicRealName = intrinsic.name; + var value = intrinsic.value; + var skipFurtherCaching = false; + + var alias = intrinsic.alias; + if (alias) { + intrinsicBaseName = alias[0]; + $spliceApply(parts, $concat([0, 1], alias)); + } + + for (var i = 1, isOwn = true; i < parts.length; i += 1) { + var part = parts[i]; + var first = $strSlice(part, 0, 1); + var last = $strSlice(part, -1); + if ( + ( + (first === '"' || first === "'" || first === '`') + || (last === '"' || last === "'" || last === '`') + ) + && first !== last + ) { + throw new $SyntaxError('property names with quotes must have matching quotes'); + } + if (part === 'constructor' || !isOwn) { + skipFurtherCaching = true; + } + + intrinsicBaseName += '.' + part; + intrinsicRealName = '%' + intrinsicBaseName + '%'; + + if (hasOwn(INTRINSICS, intrinsicRealName)) { + value = INTRINSICS[intrinsicRealName]; + } else if (value != null) { + if (!(part in value)) { + if (!allowMissing) { + throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.'); + } + return void undefined; + } + if ($gOPD && (i + 1) >= parts.length) { + var desc = $gOPD(value, part); + isOwn = !!desc; + + // By convention, when a data property is converted to an accessor + // property to emulate a data property that does not suffer from + // the override mistake, that accessor's getter is marked with + // an `originalValue` property. Here, when we detect this, we + // uphold the illusion by pretending to see that original data + // property, i.e., returning the value rather than the getter + // itself. + if (isOwn && 'get' in desc && !('originalValue' in desc.get)) { + value = desc.get; + } else { + value = value[part]; + } + } else { + isOwn = hasOwn(value, part); + value = value[part]; + } + + if (isOwn && !skipFurtherCaching) { + INTRINSICS[intrinsicRealName] = value; + } + } + } + return value; +}; diff --git a/backend/node_modules/get-intrinsic/package.json b/backend/node_modules/get-intrinsic/package.json new file mode 100644 index 0000000000000000000000000000000000000000..568dff9972c31779bc37cc583f6e5fb3ae493c4d --- /dev/null +++ b/backend/node_modules/get-intrinsic/package.json @@ -0,0 +1,93 @@ +{ + "name": "get-intrinsic", + "version": "1.2.4", + "description": "Get and robustly cache all JS language-level intrinsics at first require time", + "main": "index.js", + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "sideEffects": false, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "prelint": "evalmd README.md", + "lint": "eslint --ext=.js,.mjs .", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "aud --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/get-intrinsic.git" + }, + "keywords": [ + "javascript", + "ecmascript", + "es", + "js", + "intrinsic", + "getintrinsic", + "es-abstract" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/get-intrinsic/issues" + }, + "homepage": "https://github.com/ljharb/get-intrinsic#readme", + "devDependencies": { + "@ljharb/eslint-config": "^21.1.0", + "aud": "^2.0.4", + "auto-changelog": "^2.4.0", + "call-bind": "^1.0.5", + "es-abstract": "^1.22.3", + "es-value-fixtures": "^1.4.2", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "for-each": "^0.3.3", + "gopd": "^1.0.1", + "make-async-function": "^1.0.0", + "make-async-generator-function": "^1.0.0", + "make-generator-function": "^2.0.0", + "mock-property": "^1.0.3", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "object-inspect": "^1.13.1", + "safe-publish-latest": "^2.0.0", + "tape": "^5.7.4" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "has-proto": "^1.0.1", + "has-symbols": "^1.0.3", + "hasown": "^2.0.0" + }, + "testling": { + "files": "test/GetIntrinsic.js" + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + }, + "engines": { + "node": ">= 0.4" + } +} diff --git a/backend/node_modules/get-intrinsic/test/GetIntrinsic.js b/backend/node_modules/get-intrinsic/test/GetIntrinsic.js new file mode 100644 index 0000000000000000000000000000000000000000..1cc08e00ce925497d3247253d0d86f4b8ad5ee24 --- /dev/null +++ b/backend/node_modules/get-intrinsic/test/GetIntrinsic.js @@ -0,0 +1,274 @@ +'use strict'; + +var GetIntrinsic = require('../'); + +var test = require('tape'); +var forEach = require('for-each'); +var debug = require('object-inspect'); +var generatorFns = require('make-generator-function')(); +var asyncFns = require('make-async-function').list(); +var asyncGenFns = require('make-async-generator-function')(); +var mockProperty = require('mock-property'); + +var callBound = require('call-bind/callBound'); +var v = require('es-value-fixtures'); +var $gOPD = require('gopd'); +var DefinePropertyOrThrow = require('es-abstract/2021/DefinePropertyOrThrow'); + +var $isProto = callBound('%Object.prototype.isPrototypeOf%'); + +test('export', function (t) { + t.equal(typeof GetIntrinsic, 'function', 'it is a function'); + t.equal(GetIntrinsic.length, 2, 'function has length of 2'); + + t.end(); +}); + +test('throws', function (t) { + t['throws']( + function () { GetIntrinsic('not an intrinsic'); }, + SyntaxError, + 'nonexistent intrinsic throws a syntax error' + ); + + t['throws']( + function () { GetIntrinsic(''); }, + TypeError, + 'empty string intrinsic throws a type error' + ); + + t['throws']( + function () { GetIntrinsic('.'); }, + SyntaxError, + '"just a dot" intrinsic throws a syntax error' + ); + + t['throws']( + function () { GetIntrinsic('%String'); }, + SyntaxError, + 'Leading % without trailing % throws a syntax error' + ); + + t['throws']( + function () { GetIntrinsic('String%'); }, + SyntaxError, + 'Trailing % without leading % throws a syntax error' + ); + + t['throws']( + function () { GetIntrinsic("String['prototype]"); }, + SyntaxError, + 'Dynamic property access is disallowed for intrinsics (unterminated string)' + ); + + t['throws']( + function () { GetIntrinsic('%Proxy.prototype.undefined%'); }, + TypeError, + "Throws when middle part doesn't exist (%Proxy.prototype.undefined%)" + ); + + t['throws']( + function () { GetIntrinsic('%Array.prototype%garbage%'); }, + SyntaxError, + 'Throws with extra percent signs' + ); + + t['throws']( + function () { GetIntrinsic('%Array.prototype%push%'); }, + SyntaxError, + 'Throws with extra percent signs, even on an existing intrinsic' + ); + + forEach(v.nonStrings, function (nonString) { + t['throws']( + function () { GetIntrinsic(nonString); }, + TypeError, + debug(nonString) + ' is not a String' + ); + }); + + forEach(v.nonBooleans, function (nonBoolean) { + t['throws']( + function () { GetIntrinsic('%', nonBoolean); }, + TypeError, + debug(nonBoolean) + ' is not a Boolean' + ); + }); + + forEach([ + 'toString', + 'propertyIsEnumerable', + 'hasOwnProperty' + ], function (objectProtoMember) { + t['throws']( + function () { GetIntrinsic(objectProtoMember); }, + SyntaxError, + debug(objectProtoMember) + ' is not an intrinsic' + ); + }); + + t.end(); +}); + +test('base intrinsics', function (t) { + t.equal(GetIntrinsic('%Object%'), Object, '%Object% yields Object'); + t.equal(GetIntrinsic('Object'), Object, 'Object yields Object'); + t.equal(GetIntrinsic('%Array%'), Array, '%Array% yields Array'); + t.equal(GetIntrinsic('Array'), Array, 'Array yields Array'); + + t.end(); +}); + +test('dotted paths', function (t) { + t.equal(GetIntrinsic('%Object.prototype.toString%'), Object.prototype.toString, '%Object.prototype.toString% yields Object.prototype.toString'); + t.equal(GetIntrinsic('Object.prototype.toString'), Object.prototype.toString, 'Object.prototype.toString yields Object.prototype.toString'); + t.equal(GetIntrinsic('%Array.prototype.push%'), Array.prototype.push, '%Array.prototype.push% yields Array.prototype.push'); + t.equal(GetIntrinsic('Array.prototype.push'), Array.prototype.push, 'Array.prototype.push yields Array.prototype.push'); + + test('underscore paths are aliases for dotted paths', { skip: !Object.isFrozen || Object.isFrozen(Object.prototype) }, function (st) { + var original = GetIntrinsic('%ObjProto_toString%'); + + forEach([ + '%Object.prototype.toString%', + 'Object.prototype.toString', + '%ObjectPrototype.toString%', + 'ObjectPrototype.toString', + '%ObjProto_toString%', + 'ObjProto_toString' + ], function (name) { + DefinePropertyOrThrow(Object.prototype, 'toString', { + '[[Value]]': function toString() { + return original.apply(this, arguments); + } + }); + st.equal(GetIntrinsic(name), original, name + ' yields original Object.prototype.toString'); + }); + + DefinePropertyOrThrow(Object.prototype, 'toString', { '[[Value]]': original }); + st.end(); + }); + + test('dotted paths cache', { skip: !Object.isFrozen || Object.isFrozen(Object.prototype) }, function (st) { + var original = GetIntrinsic('%Object.prototype.propertyIsEnumerable%'); + + forEach([ + '%Object.prototype.propertyIsEnumerable%', + 'Object.prototype.propertyIsEnumerable', + '%ObjectPrototype.propertyIsEnumerable%', + 'ObjectPrototype.propertyIsEnumerable' + ], function (name) { + var restore = mockProperty(Object.prototype, 'propertyIsEnumerable', { + value: function propertyIsEnumerable() { + return original.apply(this, arguments); + } + }); + st.equal(GetIntrinsic(name), original, name + ' yields cached Object.prototype.propertyIsEnumerable'); + + restore(); + }); + + st.end(); + }); + + test('dotted path reports correct error', function (st) { + st['throws'](function () { + GetIntrinsic('%NonExistentIntrinsic.prototype.property%'); + }, /%NonExistentIntrinsic%/, 'The base intrinsic of %NonExistentIntrinsic.prototype.property% is %NonExistentIntrinsic%'); + + st['throws'](function () { + GetIntrinsic('%NonExistentIntrinsicPrototype.property%'); + }, /%NonExistentIntrinsicPrototype%/, 'The base intrinsic of %NonExistentIntrinsicPrototype.property% is %NonExistentIntrinsicPrototype%'); + + st.end(); + }); + + t.end(); +}); + +test('accessors', { skip: !$gOPD || typeof Map !== 'function' }, function (t) { + var actual = $gOPD(Map.prototype, 'size'); + t.ok(actual, 'Map.prototype.size has a descriptor'); + t.equal(typeof actual.get, 'function', 'Map.prototype.size has a getter function'); + t.equal(GetIntrinsic('%Map.prototype.size%'), actual.get, '%Map.prototype.size% yields the getter for it'); + t.equal(GetIntrinsic('Map.prototype.size'), actual.get, 'Map.prototype.size yields the getter for it'); + + t.end(); +}); + +test('generator functions', { skip: !generatorFns.length }, function (t) { + var $GeneratorFunction = GetIntrinsic('%GeneratorFunction%'); + var $GeneratorFunctionPrototype = GetIntrinsic('%Generator%'); + var $GeneratorPrototype = GetIntrinsic('%GeneratorPrototype%'); + + forEach(generatorFns, function (genFn) { + var fnName = genFn.name; + fnName = fnName ? "'" + fnName + "'" : 'genFn'; + + t.ok(genFn instanceof $GeneratorFunction, fnName + ' instanceof %GeneratorFunction%'); + t.ok($isProto($GeneratorFunctionPrototype, genFn), '%Generator% is prototype of ' + fnName); + t.ok($isProto($GeneratorPrototype, genFn.prototype), '%GeneratorPrototype% is prototype of ' + fnName + '.prototype'); + }); + + t.end(); +}); + +test('async functions', { skip: !asyncFns.length }, function (t) { + var $AsyncFunction = GetIntrinsic('%AsyncFunction%'); + var $AsyncFunctionPrototype = GetIntrinsic('%AsyncFunctionPrototype%'); + + forEach(asyncFns, function (asyncFn) { + var fnName = asyncFn.name; + fnName = fnName ? "'" + fnName + "'" : 'asyncFn'; + + t.ok(asyncFn instanceof $AsyncFunction, fnName + ' instanceof %AsyncFunction%'); + t.ok($isProto($AsyncFunctionPrototype, asyncFn), '%AsyncFunctionPrototype% is prototype of ' + fnName); + }); + + t.end(); +}); + +test('async generator functions', { skip: asyncGenFns.length === 0 }, function (t) { + var $AsyncGeneratorFunction = GetIntrinsic('%AsyncGeneratorFunction%'); + var $AsyncGeneratorFunctionPrototype = GetIntrinsic('%AsyncGenerator%'); + var $AsyncGeneratorPrototype = GetIntrinsic('%AsyncGeneratorPrototype%'); + + forEach(asyncGenFns, function (asyncGenFn) { + var fnName = asyncGenFn.name; + fnName = fnName ? "'" + fnName + "'" : 'asyncGenFn'; + + t.ok(asyncGenFn instanceof $AsyncGeneratorFunction, fnName + ' instanceof %AsyncGeneratorFunction%'); + t.ok($isProto($AsyncGeneratorFunctionPrototype, asyncGenFn), '%AsyncGenerator% is prototype of ' + fnName); + t.ok($isProto($AsyncGeneratorPrototype, asyncGenFn.prototype), '%AsyncGeneratorPrototype% is prototype of ' + fnName + '.prototype'); + }); + + t.end(); +}); + +test('%ThrowTypeError%', function (t) { + var $ThrowTypeError = GetIntrinsic('%ThrowTypeError%'); + + t.equal(typeof $ThrowTypeError, 'function', 'is a function'); + t['throws']( + $ThrowTypeError, + TypeError, + '%ThrowTypeError% throws a TypeError' + ); + + t.end(); +}); + +test('allowMissing', { skip: asyncGenFns.length > 0 }, function (t) { + t['throws']( + function () { GetIntrinsic('%AsyncGeneratorPrototype%'); }, + TypeError, + 'throws when missing' + ); + + t.equal( + GetIntrinsic('%AsyncGeneratorPrototype%', true), + undefined, + 'does not throw when allowMissing' + ); + + t.end(); +}); diff --git a/backend/node_modules/gopd/.eslintrc b/backend/node_modules/gopd/.eslintrc new file mode 100644 index 0000000000000000000000000000000000000000..e2550c0fb7e8a8b16191ac89b2aaab429948720d --- /dev/null +++ b/backend/node_modules/gopd/.eslintrc @@ -0,0 +1,16 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "func-style": [2, "declaration"], + "id-length": 0, + "multiline-comment-style": 0, + "new-cap": [2, { + "capIsNewExceptions": [ + "GetIntrinsic", + ], + }], + }, +} diff --git a/backend/node_modules/gopd/.github/FUNDING.yml b/backend/node_modules/gopd/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..94a44a8e83ff69f9167af25ae71c238d0f07250e --- /dev/null +++ b/backend/node_modules/gopd/.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/gopd +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/backend/node_modules/gopd/CHANGELOG.md b/backend/node_modules/gopd/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..f111eb1784b5baf1e7f2b898da76f0e99a030087 --- /dev/null +++ b/backend/node_modules/gopd/CHANGELOG.md @@ -0,0 +1,25 @@ +# 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.1](https://github.com/ljharb/gopd/compare/v1.0.0...v1.0.1) - 2022-11-01 + +### Commits + +- [Fix] actually export gOPD instead of dP [`4b624bf`](https://github.com/ljharb/gopd/commit/4b624bfbeff788c5e3ff16d9443a83627847234f) + +## v1.0.0 - 2022-11-01 + +### Commits + +- Initial implementation, tests, readme [`0911e01`](https://github.com/ljharb/gopd/commit/0911e012cd642092bd88b732c161c58bf4f20bea) +- Initial commit [`b84e33f`](https://github.com/ljharb/gopd/commit/b84e33f5808a805ac57ff88d4247ad935569acbe) +- [actions] add reusable workflows [`12ae28a`](https://github.com/ljharb/gopd/commit/12ae28ae5f50f86e750215b6e2188901646d0119) +- npm init [`280118b`](https://github.com/ljharb/gopd/commit/280118badb45c80b4483836b5cb5315bddf6e582) +- [meta] add `auto-changelog` [`bb78de5`](https://github.com/ljharb/gopd/commit/bb78de5639a180747fb290c28912beaaf1615709) +- [meta] create FUNDING.yml; add `funding` in package.json [`11c22e6`](https://github.com/ljharb/gopd/commit/11c22e6355bb01f24e7fac4c9bb3055eb5b25002) +- [meta] use `npmignore` to autogenerate an npmignore file [`4f4537a`](https://github.com/ljharb/gopd/commit/4f4537a843b39f698c52f072845092e6fca345bb) +- Only apps should have lockfiles [`c567022`](https://github.com/ljharb/gopd/commit/c567022a18573aa7951cf5399445d9840e23e98b) diff --git a/backend/node_modules/gopd/LICENSE b/backend/node_modules/gopd/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..6abfe1434ebd5c15c245b9f0a7c25e36b581df19 --- /dev/null +++ b/backend/node_modules/gopd/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 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/backend/node_modules/gopd/README.md b/backend/node_modules/gopd/README.md new file mode 100644 index 0000000000000000000000000000000000000000..784e56a09695adb47410cb6cf08e96334a9f9c1f --- /dev/null +++ b/backend/node_modules/gopd/README.md @@ -0,0 +1,40 @@ +# gopd [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +`Object.getOwnPropertyDescriptor`, but accounts for IE's broken implementation. + +## Usage + +```javascript +var gOPD = require('gopd'); +var assert = require('assert'); + +if (gOPD) { + assert.equal(typeof gOPD, 'function', 'descriptors supported'); + // use gOPD like Object.getOwnPropertyDescriptor here +} else { + assert.ok(!gOPD, 'descriptors not supported'); +} +``` + +[package-url]: https://npmjs.org/package/gopd +[npm-version-svg]: https://versionbadg.es/ljharb/gopd.svg +[deps-svg]: https://david-dm.org/ljharb/gopd.svg +[deps-url]: https://david-dm.org/ljharb/gopd +[dev-deps-svg]: https://david-dm.org/ljharb/gopd/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/gopd#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/gopd.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/gopd.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/gopd.svg +[downloads-url]: https://npm-stat.com/charts.html?package=gopd +[codecov-image]: https://codecov.io/gh/ljharb/gopd/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/gopd/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/gopd +[actions-url]: https://github.com/ljharb/gopd/actions diff --git a/backend/node_modules/gopd/index.js b/backend/node_modules/gopd/index.js new file mode 100644 index 0000000000000000000000000000000000000000..fb6d3bbefd0214ce19e84664eb8f59fdfed2f35e --- /dev/null +++ b/backend/node_modules/gopd/index.js @@ -0,0 +1,16 @@ +'use strict'; + +var GetIntrinsic = require('get-intrinsic'); + +var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%', true); + +if ($gOPD) { + try { + $gOPD([], 'length'); + } catch (e) { + // IE 8 has a broken gOPD + $gOPD = null; + } +} + +module.exports = $gOPD; diff --git a/backend/node_modules/gopd/package.json b/backend/node_modules/gopd/package.json new file mode 100644 index 0000000000000000000000000000000000000000..d5e1fa4a277b2d85d4b95d2fadf09bdaccfcf1c1 --- /dev/null +++ b/backend/node_modules/gopd/package.json @@ -0,0 +1,71 @@ +{ + "name": "gopd", + "version": "1.0.1", + "description": "`Object.getOwnPropertyDescriptor`, but accounts for IE's broken implementation.", + "main": "index.js", + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "sideEffects": false, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "lint": "eslint --ext=js,mjs .", + "postlint": "evalmd README.md", + "pretest": "npm run lint", + "tests-only": "tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "aud --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/gopd.git" + }, + "keywords": [ + "ecmascript", + "javascript", + "getownpropertydescriptor", + "property", + "descriptor" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/gopd/issues" + }, + "homepage": "https://github.com/ljharb/gopd#readme", + "dependencies": { + "get-intrinsic": "^1.1.3" + }, + "devDependencies": { + "@ljharb/eslint-config": "^21.0.0", + "aud": "^2.0.1", + "auto-changelog": "^2.4.0", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "in-publish": "^2.0.1", + "npmignore": "^0.3.0", + "safe-publish-latest": "^2.0.0", + "tape": "^5.6.1" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + } +} diff --git a/backend/node_modules/gopd/test/index.js b/backend/node_modules/gopd/test/index.js new file mode 100644 index 0000000000000000000000000000000000000000..0376bfbadeaa10588135869695cf0e0736f135cb --- /dev/null +++ b/backend/node_modules/gopd/test/index.js @@ -0,0 +1,35 @@ +'use strict'; + +var test = require('tape'); +var gOPD = require('../'); + +test('gOPD', function (t) { + t.test('supported', { skip: !gOPD }, function (st) { + st.equal(typeof gOPD, 'function', 'is a function'); + + var obj = { x: 1 }; + st.ok('x' in obj, 'property exists'); + + var desc = gOPD(obj, 'x'); + st.deepEqual( + desc, + { + configurable: true, + enumerable: true, + value: 1, + writable: true + }, + 'descriptor is as expected' + ); + + st.end(); + }); + + t.test('not supported', { skip: gOPD }, function (st) { + st.notOk(gOPD, 'is falsy'); + + st.end(); + }); + + t.end(); +}); diff --git a/backend/node_modules/has-property-descriptors/.eslintrc b/backend/node_modules/has-property-descriptors/.eslintrc new file mode 100644 index 0000000000000000000000000000000000000000..2fcc002b0a7f59de19f8b130d5b09bfeb99124a6 --- /dev/null +++ b/backend/node_modules/has-property-descriptors/.eslintrc @@ -0,0 +1,13 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "func-name-matching": 0, + "id-length": 0, + "new-cap": [2, { + "capIsNewExceptions": ["GetIntrinsic"], + }], + }, +} diff --git a/backend/node_modules/has-property-descriptors/.github/FUNDING.yml b/backend/node_modules/has-property-descriptors/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..817aacf1f4268093d88f152efd214e45ef6a7bc7 --- /dev/null +++ b/backend/node_modules/has-property-descriptors/.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/has-property-descriptors +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/backend/node_modules/has-property-descriptors/.nycrc b/backend/node_modules/has-property-descriptors/.nycrc new file mode 100644 index 0000000000000000000000000000000000000000..bdd626ce91477abbdd489b79988baebadbd3c897 --- /dev/null +++ b/backend/node_modules/has-property-descriptors/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/backend/node_modules/has-property-descriptors/CHANGELOG.md b/backend/node_modules/has-property-descriptors/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..19c8a959c6153dd7dd01c4c249b7ccd7059f31e9 --- /dev/null +++ b/backend/node_modules/has-property-descriptors/CHANGELOG.md @@ -0,0 +1,35 @@ +# 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/inspect-js/has-property-descriptors/compare/v1.0.1...v1.0.2) - 2024-02-12 + +### Commits + +- [Refactor] use `es-define-property` [`f93a8c8`](https://github.com/inspect-js/has-property-descriptors/commit/f93a8c85eba70cbceab500f2619fb5cce73a1805) +- [Dev Deps] update `aud`, `npmignore`, `tape` [`42b0c9d`](https://github.com/inspect-js/has-property-descriptors/commit/42b0c9d1c23e747755f0f2924923c418ea34a9ee) +- [Deps] update `get-intrinsic` [`35e9b46`](https://github.com/inspect-js/has-property-descriptors/commit/35e9b46a7f14331bf0de98b644dd803676746037) + +## [v1.0.1](https://github.com/inspect-js/has-property-descriptors/compare/v1.0.0...v1.0.1) - 2023-10-20 + +### Commits + +- [meta] use `npmignore` to autogenerate an npmignore file [`5bbf4da`](https://github.com/inspect-js/has-property-descriptors/commit/5bbf4dae1b58950d87bb3af508bee7513e640868) +- [actions] update rebase action to use reusable workflow [`3a5585b`](https://github.com/inspect-js/has-property-descriptors/commit/3a5585bf74988f71a8f59e67a07d594e62c51fd8) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `tape` [`e5c1212`](https://github.com/inspect-js/has-property-descriptors/commit/e5c1212048a8fda549794c47863724ca60b89cae) +- [Dev Deps] update `aud`, `tape` [`e942917`](https://github.com/inspect-js/has-property-descriptors/commit/e942917b6c2f7c090d5623048989cf20d0834ebf) +- [Deps] update `get-intrinsic` [`f4a44ec`](https://github.com/inspect-js/has-property-descriptors/commit/f4a44ec6d94146fa6c550d3c15c31a2062c83ef4) +- [Deps] update `get-intrinsic` [`eeb275b`](https://github.com/inspect-js/has-property-descriptors/commit/eeb275b473e5d72ca843b61ca25cfcb06a5d4300) + +## v1.0.0 - 2022-04-14 + +### Commits + +- Initial implementation, tests [`303559f`](https://github.com/inspect-js/has-property-descriptors/commit/303559f2a72dfe7111573a1aec475ed4a184c35a) +- Initial commit [`3a7ca2d`](https://github.com/inspect-js/has-property-descriptors/commit/3a7ca2dc49f1fff0279a28bb16265e7615e14749) +- read me [`dd73dce`](https://github.com/inspect-js/has-property-descriptors/commit/dd73dce09d89d0f7a4a6e3b1e562a506f979a767) +- npm init [`c1e6557`](https://github.com/inspect-js/has-property-descriptors/commit/c1e655779de632d68cb944c50da6b71bcb7b8c85) +- Only apps should have lockfiles [`e72f7c6`](https://github.com/inspect-js/has-property-descriptors/commit/e72f7c68de534b2d273ee665f8b18d4ecc7f70b0) diff --git a/backend/node_modules/has-property-descriptors/LICENSE b/backend/node_modules/has-property-descriptors/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..2e7b9a3eacf263cb418f4c16b087290ef78c39b2 --- /dev/null +++ b/backend/node_modules/has-property-descriptors/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 Inspect JS + +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/backend/node_modules/has-property-descriptors/README.md b/backend/node_modules/has-property-descriptors/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d81fbd99e91a3ec97fc930ffb985819dacae39a6 --- /dev/null +++ b/backend/node_modules/has-property-descriptors/README.md @@ -0,0 +1,43 @@ +# has-property-descriptors [![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] + +Does the environment have full property descriptor support? Handles IE 8's broken defineProperty/gOPD. + +## Example + +```js +var hasPropertyDescriptors = require('has-property-descriptors'); +var assert = require('assert'); + +assert.equal(hasPropertyDescriptors(), true); // will be `false` in IE 6-8, and ES5 engines + +// Arrays can not have their length `[[Defined]]` in some engines +assert.equal(hasPropertyDescriptors.hasArrayLengthDefineBug(), false); // will be `true` in Firefox 4-22, and node v0.6 +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/has-property-descriptors +[npm-version-svg]: https://versionbadg.es/inspect-js/has-property-descriptors.svg +[deps-svg]: https://david-dm.org/inspect-js/has-property-descriptors.svg +[deps-url]: https://david-dm.org/inspect-js/has-property-descriptors +[dev-deps-svg]: https://david-dm.org/inspect-js/has-property-descriptors/dev-status.svg +[dev-deps-url]: https://david-dm.org/inspect-js/has-property-descriptors#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/has-property-descriptors.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/has-property-descriptors.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/has-property-descriptors.svg +[downloads-url]: https://npm-stat.com/charts.html?package=has-property-descriptors +[codecov-image]: https://codecov.io/gh/inspect-js/has-property-descriptors/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/has-property-descriptors/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/has-property-descriptors +[actions-url]: https://github.com/inspect-js/has-property-descriptors/actions diff --git a/backend/node_modules/has-property-descriptors/index.js b/backend/node_modules/has-property-descriptors/index.js new file mode 100644 index 0000000000000000000000000000000000000000..04804379cb13a68f351905f39b1d85d128d0720a --- /dev/null +++ b/backend/node_modules/has-property-descriptors/index.js @@ -0,0 +1,22 @@ +'use strict'; + +var $defineProperty = require('es-define-property'); + +var hasPropertyDescriptors = function hasPropertyDescriptors() { + return !!$defineProperty; +}; + +hasPropertyDescriptors.hasArrayLengthDefineBug = function hasArrayLengthDefineBug() { + // node v0.6 has a bug where array lengths can be Set but not Defined + if (!$defineProperty) { + return null; + } + try { + return $defineProperty([], 'length', { value: 1 }).length !== 1; + } catch (e) { + // In Firefox 4-22, defining length on an array throws an exception. + return true; + } +}; + +module.exports = hasPropertyDescriptors; diff --git a/backend/node_modules/has-property-descriptors/package.json b/backend/node_modules/has-property-descriptors/package.json new file mode 100644 index 0000000000000000000000000000000000000000..7e70218b478caca5c0ecd4b58b2e62f23eb28003 --- /dev/null +++ b/backend/node_modules/has-property-descriptors/package.json @@ -0,0 +1,77 @@ +{ + "name": "has-property-descriptors", + "version": "1.0.2", + "description": "Does the environment have full property descriptor support? Handles IE 8's broken defineProperty/gOPD.", + "main": "index.js", + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "sideEffects": false, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "pretest": "npm run lint", + "prelint": "evalmd README.md", + "lint": "eslint --ext=js,mjs .", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "aud --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/inspect-js/has-property-descriptors.git" + }, + "keywords": [ + "property", + "descriptors", + "has", + "environment", + "env", + "defineProperty", + "getOwnPropertyDescriptor" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/inspect-js/has-property-descriptors/issues" + }, + "homepage": "https://github.com/inspect-js/has-property-descriptors#readme", + "devDependencies": { + "@ljharb/eslint-config": "^21.1.0", + "aud": "^2.0.4", + "auto-changelog": "^2.4.0", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.7.4" + }, + "dependencies": { + "es-define-property": "^1.0.0" + }, + "testling": { + "files": "test/index.js" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + } +} diff --git a/backend/node_modules/has-property-descriptors/test/index.js b/backend/node_modules/has-property-descriptors/test/index.js new file mode 100644 index 0000000000000000000000000000000000000000..7f02bd3e68e63a7e8ff2ee3016a57dfe35463918 --- /dev/null +++ b/backend/node_modules/has-property-descriptors/test/index.js @@ -0,0 +1,57 @@ +'use strict'; + +var test = require('tape'); + +var hasPropertyDescriptors = require('../'); + +var sentinel = {}; + +test('hasPropertyDescriptors', function (t) { + t.equal(typeof hasPropertyDescriptors, 'function', 'is a function'); + t.equal(typeof hasPropertyDescriptors.hasArrayLengthDefineBug, 'function', '`hasArrayLengthDefineBug` property is a function'); + + var yes = hasPropertyDescriptors(); + t.test('property descriptors', { skip: !yes }, function (st) { + var o = { a: sentinel }; + + st.deepEqual( + Object.getOwnPropertyDescriptor(o, 'a'), + { + configurable: true, + enumerable: true, + value: sentinel, + writable: true + }, + 'has expected property descriptor' + ); + + Object.defineProperty(o, 'a', { enumerable: false, writable: false }); + + st.deepEqual( + Object.getOwnPropertyDescriptor(o, 'a'), + { + configurable: true, + enumerable: false, + value: sentinel, + writable: false + }, + 'has expected property descriptor after [[Define]]' + ); + + st.end(); + }); + + var arrayBug = hasPropertyDescriptors.hasArrayLengthDefineBug(); + t.test('defining array lengths', { skip: !yes || arrayBug }, function (st) { + var arr = [1, , 3]; // eslint-disable-line no-sparse-arrays + st.equal(arr.length, 3, 'array starts with length 3'); + + Object.defineProperty(arr, 'length', { value: 5 }); + + st.equal(arr.length, 5, 'array ends with length 5'); + + st.end(); + }); + + t.end(); +}); diff --git a/backend/node_modules/has-proto/.eslintrc b/backend/node_modules/has-proto/.eslintrc new file mode 100644 index 0000000000000000000000000000000000000000..3b5d9e90ec405f85dd7f9066656efccc51193697 --- /dev/null +++ b/backend/node_modules/has-proto/.eslintrc @@ -0,0 +1,5 @@ +{ + "root": true, + + "extends": "@ljharb", +} diff --git a/backend/node_modules/has-proto/.github/FUNDING.yml b/backend/node_modules/has-proto/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..613705c7eb37d52c2ab1c67862b167714b9b2f57 --- /dev/null +++ b/backend/node_modules/has-proto/.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/has-proto +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/backend/node_modules/has-proto/CHANGELOG.md b/backend/node_modules/has-proto/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..6690f28e6785d5ef86e3e4bb34a43cece2485529 --- /dev/null +++ b/backend/node_modules/has-proto/CHANGELOG.md @@ -0,0 +1,38 @@ +# 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.3](https://github.com/inspect-js/has-proto/compare/v1.0.2...v1.0.3) - 2024-02-19 + +### Commits + +- [types] add missing declaration file [`26ecade`](https://github.com/inspect-js/has-proto/commit/26ecade05d253bb5dc376945ee3186d1fbe334f8) + +## [v1.0.2](https://github.com/inspect-js/has-proto/compare/v1.0.1...v1.0.2) - 2024-02-19 + +### Commits + +- add types [`6435262`](https://github.com/inspect-js/has-proto/commit/64352626cf511c0276d5f4bb6be770a0bf0f8524) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `npmignore`, `tape` [`f16a5e4`](https://github.com/inspect-js/has-proto/commit/f16a5e4121651e551271419f9d60fdd3561fd82c) +- [Refactor] tiny cleanup [`d1f1a4b`](https://github.com/inspect-js/has-proto/commit/d1f1a4bdc135f115a10f148ce302676224534702) +- [meta] add `sideEffects` flag [`e7ab1a6`](https://github.com/inspect-js/has-proto/commit/e7ab1a6f153b3e80dee68d1748b71e46767a0531) + +## [v1.0.1](https://github.com/inspect-js/has-proto/compare/v1.0.0...v1.0.1) - 2022-12-21 + +### Commits + +- [meta] correct URLs and description [`ef34483`](https://github.com/inspect-js/has-proto/commit/ef34483ca0d35680f271b6b96e35526151b25dfc) +- [patch] add an additional criteria [`e81959e`](https://github.com/inspect-js/has-proto/commit/e81959ed7c7a77fbf459f00cb4ef824f1099497f) +- [Dev Deps] update `aud` [`2bec2c4`](https://github.com/inspect-js/has-proto/commit/2bec2c47b072b122ff5443fba0263f6dc649531f) + +## v1.0.0 - 2022-12-12 + +### Commits + +- Initial implementation, tests, readme [`6886fea`](https://github.com/inspect-js/has-proto/commit/6886fea578f67daf69a7920b2eb7637ea6ebb0bc) +- Initial commit [`99129c8`](https://github.com/inspect-js/has-proto/commit/99129c8f42471ac89cb681ba9cb9d52a583eb94f) +- npm init [`2844ad8`](https://github.com/inspect-js/has-proto/commit/2844ad8e75b84d66a46765b3bab9d2e8ea692e10) +- Only apps should have lockfiles [`c65bc5e`](https://github.com/inspect-js/has-proto/commit/c65bc5e40b9004463f7336d47c67245fb139a36a) diff --git a/backend/node_modules/has-proto/LICENSE b/backend/node_modules/has-proto/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..2e7b9a3eacf263cb418f4c16b087290ef78c39b2 --- /dev/null +++ b/backend/node_modules/has-proto/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 Inspect JS + +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/backend/node_modules/has-proto/README.md b/backend/node_modules/has-proto/README.md new file mode 100644 index 0000000000000000000000000000000000000000..145676547c24d5f7a2da6ee82a1b78fe272f0326 --- /dev/null +++ b/backend/node_modules/has-proto/README.md @@ -0,0 +1,38 @@ +# has-proto [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Does this environment have the ability to set the [[Prototype]] of an object on creation with `__proto__`? + +## Example + +```js +var hasProto = require('has-proto'); +var assert = require('assert'); + +assert.equal(typeof hasProto(), 'boolean'); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/has-proto +[npm-version-svg]: https://versionbadg.es/inspect-js/has-proto.svg +[deps-svg]: https://david-dm.org/inspect-js/has-proto.svg +[deps-url]: https://david-dm.org/inspect-js/has-proto +[dev-deps-svg]: https://david-dm.org/inspect-js/has-proto/dev-status.svg +[dev-deps-url]: https://david-dm.org/inspect-js/has-proto#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/has-proto.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/has-proto.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/has-proto.svg +[downloads-url]: https://npm-stat.com/charts.html?package=has-proto +[codecov-image]: https://codecov.io/gh/inspect-js/has-proto/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/has-proto/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/has-proto +[actions-url]: https://github.com/inspect-js/has-proto/actions diff --git a/backend/node_modules/has-proto/index.d.ts b/backend/node_modules/has-proto/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cfed6951baf2c153ab65ea5a549e2cf0035a06db --- /dev/null +++ b/backend/node_modules/has-proto/index.d.ts @@ -0,0 +1,3 @@ +declare function hasProto(): boolean; + +export = hasProto; \ No newline at end of file diff --git a/backend/node_modules/has-proto/index.js b/backend/node_modules/has-proto/index.js new file mode 100644 index 0000000000000000000000000000000000000000..d3c8a0afd3cb8f386e763bd3b7376afd1488b37c --- /dev/null +++ b/backend/node_modules/has-proto/index.js @@ -0,0 +1,15 @@ +'use strict'; + +var test = { + __proto__: null, + foo: {} +}; + +var $Object = Object; + +/** @type {import('.')} */ +module.exports = function hasProto() { + // @ts-expect-error: TS errors on an inherited property for some reason + return { __proto__: test }.foo === test.foo + && !(test instanceof $Object); +}; diff --git a/backend/node_modules/has-proto/package.json b/backend/node_modules/has-proto/package.json new file mode 100644 index 0000000000000000000000000000000000000000..9d37e4ed18d57a982b1292332806fb899f748301 --- /dev/null +++ b/backend/node_modules/has-proto/package.json @@ -0,0 +1,78 @@ +{ + "name": "has-proto", + "version": "1.0.3", + "description": "Does this environment have the ability to get the [[Prototype]] of an object on creation with `__proto__`?", + "main": "index.js", + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "sideEffects": false, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "lint": "eslint --ext=js,mjs .", + "postlint": "tsc -p .", + "pretest": "npm run lint", + "tests-only": "tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "aud --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/inspect-js/has-proto.git" + }, + "keywords": [ + "prototype", + "proto", + "set", + "get", + "__proto__", + "getPrototypeOf", + "setPrototypeOf", + "has" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/inspect-js/has-proto/issues" + }, + "homepage": "https://github.com/inspect-js/has-proto#readme", + "testling": { + "files": "test/index.js" + }, + "devDependencies": { + "@ljharb/eslint-config": "^21.1.0", + "@types/tape": "^5.6.4", + "aud": "^2.0.4", + "auto-changelog": "^2.4.0", + "eslint": "=8.8.0", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "safe-publish-latest": "^2.0.0", + "tape": "^5.7.5", + "typescript": "next" + }, + "engines": { + "node": ">= 0.4" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + } +} diff --git a/backend/node_modules/has-proto/test/index.js b/backend/node_modules/has-proto/test/index.js new file mode 100644 index 0000000000000000000000000000000000000000..5da1a3aa6c686463071db25151aa4d2683d5dc5a --- /dev/null +++ b/backend/node_modules/has-proto/test/index.js @@ -0,0 +1,19 @@ +'use strict'; + +var test = require('tape'); +var hasProto = require('../'); + +test('hasProto', function (t) { + var result = hasProto(); + t.equal(typeof result, 'boolean', 'returns a boolean (' + result + ')'); + + var obj = { __proto__: null }; + if (result) { + t.notOk('toString' in obj, 'null object lacks toString'); + } else { + t.ok('toString' in obj, 'without proto, null object has toString'); + t.equal(obj.__proto__, null); // eslint-disable-line no-proto + } + + t.end(); +}); diff --git a/backend/node_modules/has-proto/tsconfig.json b/backend/node_modules/has-proto/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..2002ce5a53532769b9b5bc561dac11518c384d13 --- /dev/null +++ b/backend/node_modules/has-proto/tsconfig.json @@ -0,0 +1,49 @@ +{ + "compilerOptions": { + /* Visit https://aka.ms/tsconfig to read more about this file */ + + /* Projects */ + + /* Language and Environment */ + "target": "ESNext", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ + // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ + // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ + "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ + // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ + + /* Modules */ + "module": "commonjs", /* Specify what module code is generated. */ + // "rootDir": "./", /* Specify the root folder within your source files. */ + // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */ + // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ + // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ + // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ + "typeRoots": ["types"], /* Specify multiple folders that act like './node_modules/@types'. */ + "resolveJsonModule": true, /* Enable importing .json files. */ + // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */ + + /* JavaScript Support */ + "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ + "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ + "maxNodeModuleJsDepth": 0, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ + + /* Emit */ + "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ + "declarationMap": true, /* Create sourcemaps for d.ts files. */ + "noEmit": true, /* Disable emitting files from a compilation. */ + + /* Interop Constraints */ + "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ + "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */ + "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ + + /* Type Checking */ + "strict": true, /* Enable all strict type-checking options. */ + + /* Completeness */ + //"skipLibCheck": true /* Skip type checking all .d.ts files. */ + }, + "exclude": [ + "coverage" + ] +} diff --git a/backend/node_modules/has-symbols/.eslintrc b/backend/node_modules/has-symbols/.eslintrc new file mode 100644 index 0000000000000000000000000000000000000000..2d9a66a8acdbacede413918d9c0c8eaaacee7457 --- /dev/null +++ b/backend/node_modules/has-symbols/.eslintrc @@ -0,0 +1,11 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "max-statements-per-line": [2, { "max": 2 }], + "no-magic-numbers": 0, + "multiline-comment-style": 0, + } +} diff --git a/backend/node_modules/has-symbols/.github/FUNDING.yml b/backend/node_modules/has-symbols/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..04cf87e66ed8daa00712b7926d2ed63a9108c2ae --- /dev/null +++ b/backend/node_modules/has-symbols/.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/has-symbols +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/backend/node_modules/has-symbols/.nycrc b/backend/node_modules/has-symbols/.nycrc new file mode 100644 index 0000000000000000000000000000000000000000..bdd626ce91477abbdd489b79988baebadbd3c897 --- /dev/null +++ b/backend/node_modules/has-symbols/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/backend/node_modules/has-symbols/CHANGELOG.md b/backend/node_modules/has-symbols/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..cd532a2b460b20c40fc2c965c6be45e71c661c4b --- /dev/null +++ b/backend/node_modules/has-symbols/CHANGELOG.md @@ -0,0 +1,75 @@ +# 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.3](https://github.com/inspect-js/has-symbols/compare/v1.0.2...v1.0.3) - 2022-03-01 + +### Commits + +- [actions] use `node/install` instead of `node/run`; use `codecov` action [`518b28f`](https://github.com/inspect-js/has-symbols/commit/518b28f6c5a516cbccae30794e40aa9f738b1693) +- [meta] add `bugs` and `homepage` fields; reorder package.json [`c480b13`](https://github.com/inspect-js/has-symbols/commit/c480b13fd6802b557e1cef9749872cb5fdeef744) +- [actions] reuse common workflows [`01d0ee0`](https://github.com/inspect-js/has-symbols/commit/01d0ee0a8d97c0947f5edb73eb722027a77b2b07) +- [actions] update codecov uploader [`6424ebe`](https://github.com/inspect-js/has-symbols/commit/6424ebe86b2c9c7c3d2e9bd4413a4e4f168cb275) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `tape` [`dfa7e7f`](https://github.com/inspect-js/has-symbols/commit/dfa7e7ff38b594645d8c8222aab895157fa7e282) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `safe-publish-latest`, `tape` [`0c8d436`](https://github.com/inspect-js/has-symbols/commit/0c8d43685c45189cea9018191d4fd7eca91c9d02) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`9026554`](https://github.com/inspect-js/has-symbols/commit/902655442a1bf88e72b42345494ef0c60f5d36ab) +- [readme] add actions and codecov badges [`eaa9682`](https://github.com/inspect-js/has-symbols/commit/eaa9682f990f481d3acf7a1c7600bec36f7b3adc) +- [Dev Deps] update `eslint`, `tape` [`bc7a3ba`](https://github.com/inspect-js/has-symbols/commit/bc7a3ba46f27b7743f8a2579732d59d1b9ac791e) +- [Dev Deps] update `eslint`, `auto-changelog` [`0ace00a`](https://github.com/inspect-js/has-symbols/commit/0ace00af08a88cdd1e6ce0d60357d941c60c2d9f) +- [meta] use `prepublishOnly` script for npm 7+ [`093f72b`](https://github.com/inspect-js/has-symbols/commit/093f72bc2b0ed00c781f444922a5034257bf561d) +- [Tests] test on all 16 minors [`9b80d3d`](https://github.com/inspect-js/has-symbols/commit/9b80d3d9102529f04c20ec5b1fcc6e38426c6b03) + +## [v1.0.2](https://github.com/inspect-js/has-symbols/compare/v1.0.1...v1.0.2) - 2021-02-27 + +### Fixed + +- [Fix] use a universal way to get the original Symbol [`#11`](https://github.com/inspect-js/has-symbols/issues/11) + +### Commits + +- [Tests] migrate tests to Github Actions [`90ae798`](https://github.com/inspect-js/has-symbols/commit/90ae79820bdfe7bc703d67f5f3c5e205f98556d3) +- [meta] do not publish github action workflow files [`29e60a1`](https://github.com/inspect-js/has-symbols/commit/29e60a1b7c25c7f1acf7acff4a9320d0d10c49b4) +- [Tests] run `nyc` on all tests [`8476b91`](https://github.com/inspect-js/has-symbols/commit/8476b915650d360915abe2522505abf4b0e8f0ae) +- [readme] fix repo URLs, remove defunct badges [`126288e`](https://github.com/inspect-js/has-symbols/commit/126288ecc1797c0a40247a6b78bcb2e0bc5d7036) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `core-js`, `get-own-property-symbols` [`d84bdfa`](https://github.com/inspect-js/has-symbols/commit/d84bdfa48ac5188abbb4904b42614cd6c030940a) +- [Tests] fix linting errors [`0df3070`](https://github.com/inspect-js/has-symbols/commit/0df3070b981b6c9f2ee530c09189a7f5c6def839) +- [actions] add "Allow Edits" workflow [`1e6bc29`](https://github.com/inspect-js/has-symbols/commit/1e6bc29b188f32b9648657b07eda08504be5aa9c) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`36cea2a`](https://github.com/inspect-js/has-symbols/commit/36cea2addd4e6ec435f35a2656b4e9ef82498e9b) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`1278338`](https://github.com/inspect-js/has-symbols/commit/127833801865fbc2cc8979beb9ca869c7bfe8222) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`1493254`](https://github.com/inspect-js/has-symbols/commit/1493254eda13db5fb8fc5e4a3e8324b3d196029d) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `core-js` [`b090bf2`](https://github.com/inspect-js/has-symbols/commit/b090bf214d3679a30edc1e2d729d466ab5183e1d) +- [actions] switch Automatic Rebase workflow to `pull_request_target` event [`4addb7a`](https://github.com/inspect-js/has-symbols/commit/4addb7ab4dc73f927ae99928d68817554fc21dc0) +- [Dev Deps] update `auto-changelog`, `tape` [`81d0baf`](https://github.com/inspect-js/has-symbols/commit/81d0baf3816096a89a8558e8043895f7a7d10d8b) +- [Dev Deps] update `auto-changelog`; add `aud` [`1a4e561`](https://github.com/inspect-js/has-symbols/commit/1a4e5612c25d91c3a03d509721d02630bc4fe3da) +- [readme] remove unused testling URLs [`3000941`](https://github.com/inspect-js/has-symbols/commit/3000941f958046e923ed8152edb1ef4a599e6fcc) +- [Tests] only audit prod deps [`692e974`](https://github.com/inspect-js/has-symbols/commit/692e9743c912410e9440207631a643a34b4741a1) +- [Dev Deps] update `@ljharb/eslint-config` [`51c946c`](https://github.com/inspect-js/has-symbols/commit/51c946c7f6baa793ec5390bb5a45cdce16b4ba76) + +## [v1.0.1](https://github.com/inspect-js/has-symbols/compare/v1.0.0...v1.0.1) - 2019-11-16 + +### Commits + +- [Tests] use shared travis-ci configs [`ce396c9`](https://github.com/inspect-js/has-symbols/commit/ce396c9419ff11c43d0da5d05cdbb79f7fb42229) +- [Tests] up to `node` `v12.4`, `v11.15`, `v10.15`, `v9.11`, `v8.15`, `v7.10`, `v6.17`, `v4.9`; use `nvm install-latest-npm` [`0690732`](https://github.com/inspect-js/has-symbols/commit/0690732801f47ab429f39ba1962f522d5c462d6b) +- [meta] add `auto-changelog` [`2163d0b`](https://github.com/inspect-js/has-symbols/commit/2163d0b7f36343076b8f947cd1667dd1750f26fc) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `core-js`, `safe-publish-latest`, `tape` [`8e0951f`](https://github.com/inspect-js/has-symbols/commit/8e0951f1a7a2e52068222b7bb73511761e6e4d9c) +- [actions] add automatic rebasing / merge commit blocking [`b09cdb7`](https://github.com/inspect-js/has-symbols/commit/b09cdb7cd7ee39e7a769878f56e2d6066f5ccd1d) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `safe-publish-latest`, `core-js`, `get-own-property-symbols`, `tape` [`1dd42cd`](https://github.com/inspect-js/has-symbols/commit/1dd42cd86183ed0c50f99b1062345c458babca91) +- [meta] create FUNDING.yml [`aa57a17`](https://github.com/inspect-js/has-symbols/commit/aa57a17b19708906d1927f821ea8e73394d84ca4) +- Only apps should have lockfiles [`a2d8bea`](https://github.com/inspect-js/has-symbols/commit/a2d8bea23a97d15c09eaf60f5b107fcf9a4d57aa) +- [Tests] use `npx aud` instead of `nsp` or `npm audit` with hoops [`9e96cb7`](https://github.com/inspect-js/has-symbols/commit/9e96cb783746cbed0c10ef78e599a8eaa7ebe193) +- [meta] add `funding` field [`a0b32cf`](https://github.com/inspect-js/has-symbols/commit/a0b32cf68e803f963c1639b6d47b0a9d6440bab0) +- [Dev Deps] update `safe-publish-latest` [`cb9f0a5`](https://github.com/inspect-js/has-symbols/commit/cb9f0a521a3a1790f1064d437edd33bb6c3d6af0) + +## v1.0.0 - 2016-09-19 + +### Commits + +- Tests. [`ecb6eb9`](https://github.com/inspect-js/has-symbols/commit/ecb6eb934e4883137f3f93b965ba5e0a98df430d) +- package.json [`88a337c`](https://github.com/inspect-js/has-symbols/commit/88a337cee0864a0da35f5d19e69ff0ef0150e46a) +- Initial commit [`42e1e55`](https://github.com/inspect-js/has-symbols/commit/42e1e5502536a2b8ac529c9443984acd14836b1c) +- Initial implementation. [`33f5cc6`](https://github.com/inspect-js/has-symbols/commit/33f5cc6cdff86e2194b081ee842bfdc63caf43fb) +- read me [`01f1170`](https://github.com/inspect-js/has-symbols/commit/01f1170188ff7cb1558aa297f6ba5b516c6d7b0c) diff --git a/backend/node_modules/has-symbols/LICENSE b/backend/node_modules/has-symbols/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..df31cbf3c064d00ba5f15a3bb13c957b598b96a1 --- /dev/null +++ b/backend/node_modules/has-symbols/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2016 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/backend/node_modules/has-symbols/README.md b/backend/node_modules/has-symbols/README.md new file mode 100644 index 0000000000000000000000000000000000000000..33905f0fc92c406715fef234ba43605c95390b30 --- /dev/null +++ b/backend/node_modules/has-symbols/README.md @@ -0,0 +1,46 @@ +# has-symbols [![Version Badge][2]][1] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][5]][6] +[![dev dependency status][7]][8] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][11]][1] + +Determine if the JS environment has Symbol support. Supports spec, or shams. + +## Example + +```js +var hasSymbols = require('has-symbols'); + +hasSymbols() === true; // if the environment has native Symbol support. Not polyfillable, not forgeable. + +var hasSymbolsKinda = require('has-symbols/shams'); +hasSymbolsKinda() === true; // if the environment has a Symbol sham that mostly follows the spec. +``` + +## Supported Symbol shams + - get-own-property-symbols [npm](https://www.npmjs.com/package/get-own-property-symbols) | [github](https://github.com/WebReflection/get-own-property-symbols) + - core-js [npm](https://www.npmjs.com/package/core-js) | [github](https://github.com/zloirock/core-js) + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[1]: https://npmjs.org/package/has-symbols +[2]: https://versionbadg.es/inspect-js/has-symbols.svg +[5]: https://david-dm.org/inspect-js/has-symbols.svg +[6]: https://david-dm.org/inspect-js/has-symbols +[7]: https://david-dm.org/inspect-js/has-symbols/dev-status.svg +[8]: https://david-dm.org/inspect-js/has-symbols#info=devDependencies +[11]: https://nodei.co/npm/has-symbols.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/has-symbols.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/has-symbols.svg +[downloads-url]: https://npm-stat.com/charts.html?package=has-symbols +[codecov-image]: https://codecov.io/gh/inspect-js/has-symbols/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/has-symbols/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/has-symbols +[actions-url]: https://github.com/inspect-js/has-symbols/actions diff --git a/backend/node_modules/has-symbols/index.js b/backend/node_modules/has-symbols/index.js new file mode 100644 index 0000000000000000000000000000000000000000..17044fa21daa70b21359aa18e71bd98dec1b7a7b --- /dev/null +++ b/backend/node_modules/has-symbols/index.js @@ -0,0 +1,13 @@ +'use strict'; + +var origSymbol = typeof Symbol !== 'undefined' && Symbol; +var hasSymbolSham = require('./shams'); + +module.exports = function hasNativeSymbols() { + if (typeof origSymbol !== 'function') { return false; } + if (typeof Symbol !== 'function') { return false; } + if (typeof origSymbol('foo') !== 'symbol') { return false; } + if (typeof Symbol('bar') !== 'symbol') { return false; } + + return hasSymbolSham(); +}; diff --git a/backend/node_modules/has-symbols/package.json b/backend/node_modules/has-symbols/package.json new file mode 100644 index 0000000000000000000000000000000000000000..fe7004a10b169c9e283b1c5adf7af4a41195ba43 --- /dev/null +++ b/backend/node_modules/has-symbols/package.json @@ -0,0 +1,101 @@ +{ + "name": "has-symbols", + "version": "1.0.3", + "description": "Determine if the JS environment has Symbol support. Supports spec, or shams.", + "main": "index.js", + "scripts": { + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "pretest": "npm run --silent lint", + "test": "npm run tests-only", + "posttest": "aud --production", + "tests-only": "npm run test:stock && npm run test:staging && npm run test:shams", + "test:stock": "nyc node test", + "test:staging": "nyc node --harmony --es-staging test", + "test:shams": "npm run --silent test:shams:getownpropertysymbols && npm run --silent test:shams:corejs", + "test:shams:corejs": "nyc node test/shams/core-js.js", + "test:shams:getownpropertysymbols": "nyc node test/shams/get-own-property-symbols.js", + "lint": "eslint --ext=js,mjs .", + "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://github.com/inspect-js/has-symbols.git" + }, + "keywords": [ + "Symbol", + "symbols", + "typeof", + "sham", + "polyfill", + "native", + "core-js", + "ES6" + ], + "author": { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + }, + "contributors": [ + { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + } + ], + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/has-symbols/issues" + }, + "homepage": "https://github.com/ljharb/has-symbols#readme", + "devDependencies": { + "@ljharb/eslint-config": "^20.2.3", + "aud": "^2.0.0", + "auto-changelog": "^2.4.0", + "core-js": "^2.6.12", + "eslint": "=8.8.0", + "get-own-property-symbols": "^0.9.5", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.5.2" + }, + "testling": { + "files": "test/index.js", + "browsers": [ + "iexplore/6.0..latest", + "firefox/3.0..6.0", + "firefox/15.0..latest", + "firefox/nightly", + "chrome/4.0..10.0", + "chrome/20.0..latest", + "chrome/canary", + "opera/10.0..latest", + "opera/next", + "safari/4.0..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2" + ] + }, + "engines": { + "node": ">= 0.4" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "greenkeeper": { + "ignore": [ + "core-js" + ] + } +} diff --git a/backend/node_modules/has-symbols/shams.js b/backend/node_modules/has-symbols/shams.js new file mode 100644 index 0000000000000000000000000000000000000000..1285210ef7ccef1eae88c888694eb481b2d23997 --- /dev/null +++ b/backend/node_modules/has-symbols/shams.js @@ -0,0 +1,42 @@ +'use strict'; + +/* eslint complexity: [2, 18], max-statements: [2, 33] */ +module.exports = function hasSymbols() { + if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; } + if (typeof Symbol.iterator === 'symbol') { return true; } + + var obj = {}; + var sym = Symbol('test'); + var symObj = Object(sym); + if (typeof sym === 'string') { return false; } + + if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; } + if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; } + + // temp disabled per https://github.com/ljharb/object.assign/issues/17 + // if (sym instanceof Symbol) { return false; } + // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4 + // if (!(symObj instanceof Symbol)) { return false; } + + // if (typeof Symbol.prototype.toString !== 'function') { return false; } + // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; } + + var symVal = 42; + obj[sym] = symVal; + for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop + if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; } + + if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; } + + var syms = Object.getOwnPropertySymbols(obj); + if (syms.length !== 1 || syms[0] !== sym) { return false; } + + if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; } + + if (typeof Object.getOwnPropertyDescriptor === 'function') { + var descriptor = Object.getOwnPropertyDescriptor(obj, sym); + if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; } + } + + return true; +}; diff --git a/backend/node_modules/has-symbols/test/index.js b/backend/node_modules/has-symbols/test/index.js new file mode 100644 index 0000000000000000000000000000000000000000..352129ca356c8ce4ba2e5e6b78c092f401e0f2da --- /dev/null +++ b/backend/node_modules/has-symbols/test/index.js @@ -0,0 +1,22 @@ +'use strict'; + +var test = require('tape'); +var hasSymbols = require('../'); +var runSymbolTests = require('./tests'); + +test('interface', function (t) { + t.equal(typeof hasSymbols, 'function', 'is a function'); + t.equal(typeof hasSymbols(), 'boolean', 'returns a boolean'); + t.end(); +}); + +test('Symbols are supported', { skip: !hasSymbols() }, function (t) { + runSymbolTests(t); + t.end(); +}); + +test('Symbols are not supported', { skip: hasSymbols() }, function (t) { + t.equal(typeof Symbol, 'undefined', 'global Symbol is undefined'); + t.equal(typeof Object.getOwnPropertySymbols, 'undefined', 'Object.getOwnPropertySymbols does not exist'); + t.end(); +}); diff --git a/backend/node_modules/has-symbols/test/shams/core-js.js b/backend/node_modules/has-symbols/test/shams/core-js.js new file mode 100644 index 0000000000000000000000000000000000000000..df5365c23ed741baceb4aa000e828bab21de9047 --- /dev/null +++ b/backend/node_modules/has-symbols/test/shams/core-js.js @@ -0,0 +1,28 @@ +'use strict'; + +var test = require('tape'); + +if (typeof Symbol === 'function' && typeof Symbol() === 'symbol') { + test('has native Symbol support', function (t) { + t.equal(typeof Symbol, 'function'); + t.equal(typeof Symbol(), 'symbol'); + t.end(); + }); + return; +} + +var hasSymbols = require('../../shams'); + +test('polyfilled Symbols', function (t) { + /* eslint-disable global-require */ + t.equal(hasSymbols(), false, 'hasSymbols is false before polyfilling'); + require('core-js/fn/symbol'); + require('core-js/fn/symbol/to-string-tag'); + + require('../tests')(t); + + var hasSymbolsAfter = hasSymbols(); + t.equal(hasSymbolsAfter, true, 'hasSymbols is true after polyfilling'); + /* eslint-enable global-require */ + t.end(); +}); diff --git a/backend/node_modules/has-symbols/test/shams/get-own-property-symbols.js b/backend/node_modules/has-symbols/test/shams/get-own-property-symbols.js new file mode 100644 index 0000000000000000000000000000000000000000..9191b248baa14b9866da65ccf638b96b71c046e7 --- /dev/null +++ b/backend/node_modules/has-symbols/test/shams/get-own-property-symbols.js @@ -0,0 +1,28 @@ +'use strict'; + +var test = require('tape'); + +if (typeof Symbol === 'function' && typeof Symbol() === 'symbol') { + test('has native Symbol support', function (t) { + t.equal(typeof Symbol, 'function'); + t.equal(typeof Symbol(), 'symbol'); + t.end(); + }); + return; +} + +var hasSymbols = require('../../shams'); + +test('polyfilled Symbols', function (t) { + /* eslint-disable global-require */ + t.equal(hasSymbols(), false, 'hasSymbols is false before polyfilling'); + + require('get-own-property-symbols'); + + require('../tests')(t); + + var hasSymbolsAfter = hasSymbols(); + t.equal(hasSymbolsAfter, true, 'hasSymbols is true after polyfilling'); + /* eslint-enable global-require */ + t.end(); +}); diff --git a/backend/node_modules/has-symbols/test/tests.js b/backend/node_modules/has-symbols/test/tests.js new file mode 100644 index 0000000000000000000000000000000000000000..89edd1291ca79ff85ca71ced9a65e4a2b4443fd9 --- /dev/null +++ b/backend/node_modules/has-symbols/test/tests.js @@ -0,0 +1,56 @@ +'use strict'; + +// eslint-disable-next-line consistent-return +module.exports = function runSymbolTests(t) { + t.equal(typeof Symbol, 'function', 'global Symbol is a function'); + + if (typeof Symbol !== 'function') { return false; } + + t.notEqual(Symbol(), Symbol(), 'two symbols are not equal'); + + /* + t.equal( + Symbol.prototype.toString.call(Symbol('foo')), + Symbol.prototype.toString.call(Symbol('foo')), + 'two symbols with the same description stringify the same' + ); + */ + + /* + var foo = Symbol('foo'); + + t.notEqual( + String(foo), + String(Symbol('bar')), + 'two symbols with different descriptions do not stringify the same' + ); + */ + + t.equal(typeof Symbol.prototype.toString, 'function', 'Symbol#toString is a function'); + // t.equal(String(foo), Symbol.prototype.toString.call(foo), 'Symbol#toString equals String of the same symbol'); + + t.equal(typeof Object.getOwnPropertySymbols, 'function', 'Object.getOwnPropertySymbols is a function'); + + var obj = {}; + var sym = Symbol('test'); + var symObj = Object(sym); + t.notEqual(typeof sym, 'string', 'Symbol is not a string'); + t.equal(Object.prototype.toString.call(sym), '[object Symbol]', 'symbol primitive Object#toStrings properly'); + t.equal(Object.prototype.toString.call(symObj), '[object Symbol]', 'symbol primitive Object#toStrings properly'); + + var symVal = 42; + obj[sym] = symVal; + // eslint-disable-next-line no-restricted-syntax + for (sym in obj) { t.fail('symbol property key was found in for..in of object'); } + + t.deepEqual(Object.keys(obj), [], 'no enumerable own keys on symbol-valued object'); + t.deepEqual(Object.getOwnPropertyNames(obj), [], 'no own names on symbol-valued object'); + t.deepEqual(Object.getOwnPropertySymbols(obj), [sym], 'one own symbol on symbol-valued object'); + t.equal(Object.prototype.propertyIsEnumerable.call(obj, sym), true, 'symbol is enumerable'); + t.deepEqual(Object.getOwnPropertyDescriptor(obj, sym), { + configurable: true, + enumerable: true, + value: 42, + writable: true + }, 'property descriptor is correct'); +}; diff --git a/backend/node_modules/hasown/.eslintrc b/backend/node_modules/hasown/.eslintrc new file mode 100644 index 0000000000000000000000000000000000000000..3b5d9e90ec405f85dd7f9066656efccc51193697 --- /dev/null +++ b/backend/node_modules/hasown/.eslintrc @@ -0,0 +1,5 @@ +{ + "root": true, + + "extends": "@ljharb", +} diff --git a/backend/node_modules/hasown/.github/FUNDING.yml b/backend/node_modules/hasown/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..d68c8b716ff04186cd4c0ed8f85af474cfbfbc6a --- /dev/null +++ b/backend/node_modules/hasown/.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/hasown +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 a single custom sponsorship URL diff --git a/backend/node_modules/hasown/.nycrc b/backend/node_modules/hasown/.nycrc new file mode 100644 index 0000000000000000000000000000000000000000..1826526e091b89c896e7099ccd891db79165e329 --- /dev/null +++ b/backend/node_modules/hasown/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "test" + ] +} diff --git a/backend/node_modules/hasown/CHANGELOG.md b/backend/node_modules/hasown/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..2b0a980fbd767e2c3ac910e34158964e7dcdbf2c --- /dev/null +++ b/backend/node_modules/hasown/CHANGELOG.md @@ -0,0 +1,40 @@ +# 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). + +## [v2.0.2](https://github.com/inspect-js/hasOwn/compare/v2.0.1...v2.0.2) - 2024-03-10 + +### Commits + +- [types] use shared config [`68e9d4d`](https://github.com/inspect-js/hasOwn/commit/68e9d4dab6facb4f05f02c6baea94a3f2a4e44b2) +- [actions] remove redundant finisher; use reusable workflow [`241a68e`](https://github.com/inspect-js/hasOwn/commit/241a68e13ea1fe52bec5ba7f74144befc31fae7b) +- [Tests] increase coverage [`4125c0d`](https://github.com/inspect-js/hasOwn/commit/4125c0d6121db56ae30e38346dfb0c000b04f0a7) +- [Tests] skip `npm ls` in old node due to TS [`01b9282`](https://github.com/inspect-js/hasOwn/commit/01b92822f9971dea031eafdd14767df41d61c202) +- [types] improve predicate type [`d340f85`](https://github.com/inspect-js/hasOwn/commit/d340f85ce02e286ef61096cbbb6697081d40a12b) +- [Dev Deps] update `tape` [`70089fc`](https://github.com/inspect-js/hasOwn/commit/70089fcf544e64acc024cbe60f5a9b00acad86de) +- [Tests] use `@arethetypeswrong/cli` [`50b272c`](https://github.com/inspect-js/hasOwn/commit/50b272c829f40d053a3dd91c9796e0ac0b2af084) + +## [v2.0.1](https://github.com/inspect-js/hasOwn/compare/v2.0.0...v2.0.1) - 2024-02-10 + +### Commits + +- [types] use a handwritten d.ts file; fix exported type [`012b989`](https://github.com/inspect-js/hasOwn/commit/012b9898ccf91dc441e2ebf594ff70270a5fda58) +- [Dev Deps] update `@types/function-bind`, `@types/mock-property`, `@types/tape`, `aud`, `mock-property`, `npmignore`, `tape`, `typescript` [`977a56f`](https://github.com/inspect-js/hasOwn/commit/977a56f51a1f8b20566f3c471612137894644025) +- [meta] add `sideEffects` flag [`3a60b7b`](https://github.com/inspect-js/hasOwn/commit/3a60b7bf42fccd8c605e5f145a6fcc83b13cb46f) + +## [v2.0.0](https://github.com/inspect-js/hasOwn/compare/v1.0.1...v2.0.0) - 2023-10-19 + +### Commits + +- revamped implementation, tests, readme [`72bf8b3`](https://github.com/inspect-js/hasOwn/commit/72bf8b338e77a638f0a290c63ffaed18339c36b4) +- [meta] revamp package.json [`079775f`](https://github.com/inspect-js/hasOwn/commit/079775fb1ec72c1c6334069593617a0be3847458) +- Only apps should have lockfiles [`6640e23`](https://github.com/inspect-js/hasOwn/commit/6640e233d1bb8b65260880f90787637db157d215) + +## v1.0.1 - 2023-10-10 + +### Commits + +- Initial commit [`8dbfde6`](https://github.com/inspect-js/hasOwn/commit/8dbfde6e8fb0ebb076fab38d138f2984eb340a62) diff --git a/backend/node_modules/hasown/LICENSE b/backend/node_modules/hasown/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..0314929078de8a733a0af9c8ba5bc00aca094cc9 --- /dev/null +++ b/backend/node_modules/hasown/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Jordan Harband and 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/backend/node_modules/hasown/README.md b/backend/node_modules/hasown/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f759b8a8396e3993fb7901d7551d38ee2a786b31 --- /dev/null +++ b/backend/node_modules/hasown/README.md @@ -0,0 +1,40 @@ +# hasown [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +A robust, ES3 compatible, "has own property" predicate. + +## Example + +```js +const assert = require('assert'); +const hasOwn = require('hasown'); + +assert.equal(hasOwn({}, 'toString'), false); +assert.equal(hasOwn([], 'length'), true); +assert.equal(hasOwn({ a: 42 }, 'a'), true); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/hasown +[npm-version-svg]: https://versionbadg.es/inspect-js/hasown.svg +[deps-svg]: https://david-dm.org/inspect-js/hasOwn.svg +[deps-url]: https://david-dm.org/inspect-js/hasOwn +[dev-deps-svg]: https://david-dm.org/inspect-js/hasOwn/dev-status.svg +[dev-deps-url]: https://david-dm.org/inspect-js/hasOwn#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/hasown.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/hasown.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/hasown.svg +[downloads-url]: https://npm-stat.com/charts.html?package=hasown +[codecov-image]: https://codecov.io/gh/inspect-js/hasOwn/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/hasOwn/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/hasOwn +[actions-url]: https://github.com/inspect-js/hasOwn/actions diff --git a/backend/node_modules/hasown/index.d.ts b/backend/node_modules/hasown/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..aafdf3b2b8f0ef01aa1b3e44596560eee3f38ff7 --- /dev/null +++ b/backend/node_modules/hasown/index.d.ts @@ -0,0 +1,3 @@ +declare function hasOwn(o: O, p: K): o is O & Record; + +export = hasOwn; diff --git a/backend/node_modules/hasown/index.js b/backend/node_modules/hasown/index.js new file mode 100644 index 0000000000000000000000000000000000000000..34e60591349679d8cbdb1033a60eb5d171d7637e --- /dev/null +++ b/backend/node_modules/hasown/index.js @@ -0,0 +1,8 @@ +'use strict'; + +var call = Function.prototype.call; +var $hasOwn = Object.prototype.hasOwnProperty; +var bind = require('function-bind'); + +/** @type {import('.')} */ +module.exports = bind.call(call, $hasOwn); diff --git a/backend/node_modules/hasown/package.json b/backend/node_modules/hasown/package.json new file mode 100644 index 0000000000000000000000000000000000000000..8502e13dd5c835ead21cfc21ead0dbdce432f741 --- /dev/null +++ b/backend/node_modules/hasown/package.json @@ -0,0 +1,92 @@ +{ + "name": "hasown", + "version": "2.0.2", + "description": "A robust, ES3 compatible, \"has own property\" predicate.", + "main": "index.js", + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "types": "index.d.ts", + "sideEffects": false, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "prelint": "evalmd README.md", + "lint": "eslint --ext=js,mjs .", + "postlint": "npm run tsc", + "pretest": "npm run lint", + "tsc": "tsc -p .", + "posttsc": "attw -P", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "aud --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/inspect-js/hasOwn.git" + }, + "keywords": [ + "has", + "hasOwnProperty", + "hasOwn", + "has-own", + "own", + "has", + "property", + "in", + "javascript", + "ecmascript" + ], + "author": "Jordan Harband ", + "license": "MIT", + "bugs": { + "url": "https://github.com/inspect-js/hasOwn/issues" + }, + "homepage": "https://github.com/inspect-js/hasOwn#readme", + "dependencies": { + "function-bind": "^1.1.2" + }, + "devDependencies": { + "@arethetypeswrong/cli": "^0.15.1", + "@ljharb/eslint-config": "^21.1.0", + "@ljharb/tsconfig": "^0.2.0", + "@types/function-bind": "^1.1.10", + "@types/mock-property": "^1.0.2", + "@types/tape": "^5.6.4", + "aud": "^2.0.4", + "auto-changelog": "^2.4.0", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "in-publish": "^2.0.1", + "mock-property": "^1.0.3", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.7.5", + "typescript": "next" + }, + "engines": { + "node": ">= 0.4" + }, + "testling": { + "files": "test/index.js" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows", + "test" + ] + } +} diff --git a/backend/node_modules/hasown/tsconfig.json b/backend/node_modules/hasown/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..0930c565850326810b8efe09ca98895aeffd8f21 --- /dev/null +++ b/backend/node_modules/hasown/tsconfig.json @@ -0,0 +1,6 @@ +{ + "extends": "@ljharb/tsconfig", + "exclude": [ + "coverage", + ], +} diff --git a/backend/node_modules/http-errors/HISTORY.md b/backend/node_modules/http-errors/HISTORY.md new file mode 100644 index 0000000000000000000000000000000000000000..7228684298c364a907e54732f4ddcce110efe6b2 --- /dev/null +++ b/backend/node_modules/http-errors/HISTORY.md @@ -0,0 +1,180 @@ +2.0.0 / 2021-12-17 +================== + + * Drop support for Node.js 0.6 + * Remove `I'mateapot` export; use `ImATeapot` instead + * Remove support for status being non-first argument + * Rename `UnorderedCollection` constructor to `TooEarly` + * deps: depd@2.0.0 + - Replace internal `eval` usage with `Function` constructor + - Use instance methods on `process` to check for listeners + * deps: statuses@2.0.1 + - Fix messaging casing of `418 I'm a Teapot` + - Remove code 306 + - Rename `425 Unordered Collection` to standard `425 Too Early` + +2021-11-14 / 1.8.1 +================== + + * deps: toidentifier@1.0.1 + +2020-06-29 / 1.8.0 +================== + + * Add `isHttpError` export to determine if value is an HTTP error + * deps: setprototypeof@1.2.0 + +2019-06-24 / 1.7.3 +================== + + * deps: inherits@2.0.4 + +2019-02-18 / 1.7.2 +================== + + * deps: setprototypeof@1.1.1 + +2018-09-08 / 1.7.1 +================== + + * Fix error creating objects in some environments + +2018-07-30 / 1.7.0 +================== + + * Set constructor name when possible + * Use `toidentifier` module to make class names + * deps: statuses@'>= 1.5.0 < 2' + +2018-03-29 / 1.6.3 +================== + + * deps: depd@~1.1.2 + - perf: remove argument reassignment + * deps: setprototypeof@1.1.0 + * deps: statuses@'>= 1.4.0 < 2' + +2017-08-04 / 1.6.2 +================== + + * deps: depd@1.1.1 + - Remove unnecessary `Buffer` loading + +2017-02-20 / 1.6.1 +================== + + * deps: setprototypeof@1.0.3 + - Fix shim for old browsers + +2017-02-14 / 1.6.0 +================== + + * Accept custom 4xx and 5xx status codes in factory + * Add deprecation message to `"I'mateapot"` export + * Deprecate passing status code as anything except first argument in factory + * Deprecate using non-error status codes + * Make `message` property enumerable for `HttpError`s + +2016-11-16 / 1.5.1 +================== + + * deps: inherits@2.0.3 + - Fix issue loading in browser + * deps: setprototypeof@1.0.2 + * deps: statuses@'>= 1.3.1 < 2' + +2016-05-18 / 1.5.0 +================== + + * Support new code `421 Misdirected Request` + * Use `setprototypeof` module to replace `__proto__` setting + * deps: statuses@'>= 1.3.0 < 2' + - Add `421 Misdirected Request` + - perf: enable strict mode + * perf: enable strict mode + +2016-01-28 / 1.4.0 +================== + + * Add `HttpError` export, for `err instanceof createError.HttpError` + * deps: inherits@2.0.1 + * deps: statuses@'>= 1.2.1 < 2' + - Fix message for status 451 + - Remove incorrect nginx status code + +2015-02-02 / 1.3.1 +================== + + * Fix regression where status can be overwritten in `createError` `props` + +2015-02-01 / 1.3.0 +================== + + * Construct errors using defined constructors from `createError` + * Fix error names that are not identifiers + - `createError["I'mateapot"]` is now `createError.ImATeapot` + * Set a meaningful `name` property on constructed errors + +2014-12-09 / 1.2.8 +================== + + * Fix stack trace from exported function + * Remove `arguments.callee` usage + +2014-10-14 / 1.2.7 +================== + + * Remove duplicate line + +2014-10-02 / 1.2.6 +================== + + * Fix `expose` to be `true` for `ClientError` constructor + +2014-09-28 / 1.2.5 +================== + + * deps: statuses@1 + +2014-09-21 / 1.2.4 +================== + + * Fix dependency version to work with old `npm`s + +2014-09-21 / 1.2.3 +================== + + * deps: statuses@~1.1.0 + +2014-09-21 / 1.2.2 +================== + + * Fix publish error + +2014-09-21 / 1.2.1 +================== + + * Support Node.js 0.6 + * Use `inherits` instead of `util` + +2014-09-09 / 1.2.0 +================== + + * Fix the way inheriting functions + * Support `expose` being provided in properties argument + +2014-09-08 / 1.1.0 +================== + + * Default status to 500 + * Support provided `error` to extend + +2014-09-08 / 1.0.1 +================== + + * Fix accepting string message + +2014-09-08 / 1.0.0 +================== + + * Initial release diff --git a/backend/node_modules/http-errors/LICENSE b/backend/node_modules/http-errors/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..82af4df54b4ce9aad915485c4660a0abab727a07 --- /dev/null +++ b/backend/node_modules/http-errors/LICENSE @@ -0,0 +1,23 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong me@jongleberry.com +Copyright (c) 2016 Douglas Christopher Wilson doug@somethingdoug.com + +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/backend/node_modules/http-errors/README.md b/backend/node_modules/http-errors/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a8b7330b09582701c7f06f4b4e5a332b3481c55c --- /dev/null +++ b/backend/node_modules/http-errors/README.md @@ -0,0 +1,169 @@ +# http-errors + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][node-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][ci-image]][ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Create HTTP errors for Express, Koa, Connect, etc. with ease. + +## Install + +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): + +```console +$ npm install http-errors +``` + +## Example + +```js +var createError = require('http-errors') +var express = require('express') +var app = express() + +app.use(function (req, res, next) { + if (!req.user) return next(createError(401, 'Please login to view this page.')) + next() +}) +``` + +## API + +This is the current API, currently extracted from Koa and subject to change. + +### Error Properties + +- `expose` - can be used to signal if `message` should be sent to the client, + defaulting to `false` when `status` >= 500 +- `headers` - can be an object of header names to values to be sent to the + client, defaulting to `undefined`. When defined, the key names should all + be lower-cased +- `message` - the traditional error message, which should be kept short and all + single line +- `status` - the status code of the error, mirroring `statusCode` for general + compatibility +- `statusCode` - the status code of the error, defaulting to `500` + +### createError([status], [message], [properties]) + +Create a new error object with the given message `msg`. +The error object inherits from `createError.HttpError`. + +```js +var err = createError(404, 'This video does not exist!') +``` + +- `status: 500` - the status code as a number +- `message` - the message of the error, defaulting to node's text for that status code. +- `properties` - custom properties to attach to the object + +### createError([status], [error], [properties]) + +Extend the given `error` object with `createError.HttpError` +properties. This will not alter the inheritance of the given +`error` object, and the modified `error` object is the +return value. + + + +```js +fs.readFile('foo.txt', function (err, buf) { + if (err) { + if (err.code === 'ENOENT') { + var httpError = createError(404, err, { expose: false }) + } else { + var httpError = createError(500, err) + } + } +}) +``` + +- `status` - the status code as a number +- `error` - the error object to extend +- `properties` - custom properties to attach to the object + +### createError.isHttpError(val) + +Determine if the provided `val` is an `HttpError`. This will return `true` +if the error inherits from the `HttpError` constructor of this module or +matches the "duck type" for an error this module creates. All outputs from +the `createError` factory will return `true` for this function, including +if an non-`HttpError` was passed into the factory. + +### new createError\[code || name\](\[msg]\)) + +Create a new error object with the given message `msg`. +The error object inherits from `createError.HttpError`. + +```js +var err = new createError.NotFound() +``` + +- `code` - the status code as a number +- `name` - the name of the error as a "bumpy case", i.e. `NotFound` or `InternalServerError`. + +#### List of all constructors + +|Status Code|Constructor Name | +|-----------|-----------------------------| +|400 |BadRequest | +|401 |Unauthorized | +|402 |PaymentRequired | +|403 |Forbidden | +|404 |NotFound | +|405 |MethodNotAllowed | +|406 |NotAcceptable | +|407 |ProxyAuthenticationRequired | +|408 |RequestTimeout | +|409 |Conflict | +|410 |Gone | +|411 |LengthRequired | +|412 |PreconditionFailed | +|413 |PayloadTooLarge | +|414 |URITooLong | +|415 |UnsupportedMediaType | +|416 |RangeNotSatisfiable | +|417 |ExpectationFailed | +|418 |ImATeapot | +|421 |MisdirectedRequest | +|422 |UnprocessableEntity | +|423 |Locked | +|424 |FailedDependency | +|425 |TooEarly | +|426 |UpgradeRequired | +|428 |PreconditionRequired | +|429 |TooManyRequests | +|431 |RequestHeaderFieldsTooLarge | +|451 |UnavailableForLegalReasons | +|500 |InternalServerError | +|501 |NotImplemented | +|502 |BadGateway | +|503 |ServiceUnavailable | +|504 |GatewayTimeout | +|505 |HTTPVersionNotSupported | +|506 |VariantAlsoNegotiates | +|507 |InsufficientStorage | +|508 |LoopDetected | +|509 |BandwidthLimitExceeded | +|510 |NotExtended | +|511 |NetworkAuthenticationRequired| + +## License + +[MIT](LICENSE) + +[ci-image]: https://badgen.net/github/checks/jshttp/http-errors/master?label=ci +[ci-url]: https://github.com/jshttp/http-errors/actions?query=workflow%3Aci +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/http-errors/master +[coveralls-url]: https://coveralls.io/r/jshttp/http-errors?branch=master +[node-image]: https://badgen.net/npm/node/http-errors +[node-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/http-errors +[npm-url]: https://npmjs.org/package/http-errors +[npm-version-image]: https://badgen.net/npm/v/http-errors +[travis-image]: https://badgen.net/travis/jshttp/http-errors/master +[travis-url]: https://travis-ci.org/jshttp/http-errors diff --git a/backend/node_modules/http-errors/index.js b/backend/node_modules/http-errors/index.js new file mode 100644 index 0000000000000000000000000000000000000000..c425f1ee9d0944b1e2274ebb78528febf563d17e --- /dev/null +++ b/backend/node_modules/http-errors/index.js @@ -0,0 +1,289 @@ +/*! + * http-errors + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2016 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var deprecate = require('depd')('http-errors') +var setPrototypeOf = require('setprototypeof') +var statuses = require('statuses') +var inherits = require('inherits') +var toIdentifier = require('toidentifier') + +/** + * Module exports. + * @public + */ + +module.exports = createError +module.exports.HttpError = createHttpErrorConstructor() +module.exports.isHttpError = createIsHttpErrorFunction(module.exports.HttpError) + +// Populate exports for all constructors +populateConstructorExports(module.exports, statuses.codes, module.exports.HttpError) + +/** + * Get the code class of a status code. + * @private + */ + +function codeClass (status) { + return Number(String(status).charAt(0) + '00') +} + +/** + * Create a new HTTP Error. + * + * @returns {Error} + * @public + */ + +function createError () { + // so much arity going on ~_~ + var err + var msg + var status = 500 + var props = {} + for (var i = 0; i < arguments.length; i++) { + var arg = arguments[i] + var type = typeof arg + if (type === 'object' && arg instanceof Error) { + err = arg + status = err.status || err.statusCode || status + } else if (type === 'number' && i === 0) { + status = arg + } else if (type === 'string') { + msg = arg + } else if (type === 'object') { + props = arg + } else { + throw new TypeError('argument #' + (i + 1) + ' unsupported type ' + type) + } + } + + if (typeof status === 'number' && (status < 400 || status >= 600)) { + deprecate('non-error status code; use only 4xx or 5xx status codes') + } + + if (typeof status !== 'number' || + (!statuses.message[status] && (status < 400 || status >= 600))) { + status = 500 + } + + // constructor + var HttpError = createError[status] || createError[codeClass(status)] + + if (!err) { + // create error + err = HttpError + ? new HttpError(msg) + : new Error(msg || statuses.message[status]) + Error.captureStackTrace(err, createError) + } + + if (!HttpError || !(err instanceof HttpError) || err.status !== status) { + // add properties to generic error + err.expose = status < 500 + err.status = err.statusCode = status + } + + for (var key in props) { + if (key !== 'status' && key !== 'statusCode') { + err[key] = props[key] + } + } + + return err +} + +/** + * Create HTTP error abstract base class. + * @private + */ + +function createHttpErrorConstructor () { + function HttpError () { + throw new TypeError('cannot construct abstract class') + } + + inherits(HttpError, Error) + + return HttpError +} + +/** + * Create a constructor for a client error. + * @private + */ + +function createClientErrorConstructor (HttpError, name, code) { + var className = toClassName(name) + + function ClientError (message) { + // create the error object + var msg = message != null ? message : statuses.message[code] + var err = new Error(msg) + + // capture a stack trace to the construction point + Error.captureStackTrace(err, ClientError) + + // adjust the [[Prototype]] + setPrototypeOf(err, ClientError.prototype) + + // redefine the error message + Object.defineProperty(err, 'message', { + enumerable: true, + configurable: true, + value: msg, + writable: true + }) + + // redefine the error name + Object.defineProperty(err, 'name', { + enumerable: false, + configurable: true, + value: className, + writable: true + }) + + return err + } + + inherits(ClientError, HttpError) + nameFunc(ClientError, className) + + ClientError.prototype.status = code + ClientError.prototype.statusCode = code + ClientError.prototype.expose = true + + return ClientError +} + +/** + * Create function to test is a value is a HttpError. + * @private + */ + +function createIsHttpErrorFunction (HttpError) { + return function isHttpError (val) { + if (!val || typeof val !== 'object') { + return false + } + + if (val instanceof HttpError) { + return true + } + + return val instanceof Error && + typeof val.expose === 'boolean' && + typeof val.statusCode === 'number' && val.status === val.statusCode + } +} + +/** + * Create a constructor for a server error. + * @private + */ + +function createServerErrorConstructor (HttpError, name, code) { + var className = toClassName(name) + + function ServerError (message) { + // create the error object + var msg = message != null ? message : statuses.message[code] + var err = new Error(msg) + + // capture a stack trace to the construction point + Error.captureStackTrace(err, ServerError) + + // adjust the [[Prototype]] + setPrototypeOf(err, ServerError.prototype) + + // redefine the error message + Object.defineProperty(err, 'message', { + enumerable: true, + configurable: true, + value: msg, + writable: true + }) + + // redefine the error name + Object.defineProperty(err, 'name', { + enumerable: false, + configurable: true, + value: className, + writable: true + }) + + return err + } + + inherits(ServerError, HttpError) + nameFunc(ServerError, className) + + ServerError.prototype.status = code + ServerError.prototype.statusCode = code + ServerError.prototype.expose = false + + return ServerError +} + +/** + * Set the name of a function, if possible. + * @private + */ + +function nameFunc (func, name) { + var desc = Object.getOwnPropertyDescriptor(func, 'name') + + if (desc && desc.configurable) { + desc.value = name + Object.defineProperty(func, 'name', desc) + } +} + +/** + * Populate the exports object with constructors for every error class. + * @private + */ + +function populateConstructorExports (exports, codes, HttpError) { + codes.forEach(function forEachCode (code) { + var CodeError + var name = toIdentifier(statuses.message[code]) + + switch (codeClass(code)) { + case 400: + CodeError = createClientErrorConstructor(HttpError, name, code) + break + case 500: + CodeError = createServerErrorConstructor(HttpError, name, code) + break + } + + if (CodeError) { + // export the constructor + exports[code] = CodeError + exports[name] = CodeError + } + }) +} + +/** + * Get a class name from a name identifier. + * @private + */ + +function toClassName (name) { + return name.substr(-5) !== 'Error' + ? name + 'Error' + : name +} diff --git a/backend/node_modules/http-errors/package.json b/backend/node_modules/http-errors/package.json new file mode 100644 index 0000000000000000000000000000000000000000..4cb6d7edad5952ce18bc5d1a65483a1da82a485b --- /dev/null +++ b/backend/node_modules/http-errors/package.json @@ -0,0 +1,50 @@ +{ + "name": "http-errors", + "description": "Create HTTP error objects", + "version": "2.0.0", + "author": "Jonathan Ong (http://jongleberry.com)", + "contributors": [ + "Alan Plum ", + "Douglas Christopher Wilson " + ], + "license": "MIT", + "repository": "jshttp/http-errors", + "dependencies": { + "depd": "2.0.0", + "inherits": "2.0.4", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "toidentifier": "1.0.1" + }, + "devDependencies": { + "eslint": "7.32.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.25.3", + "eslint-plugin-markdown": "2.2.1", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "5.2.0", + "eslint-plugin-standard": "4.1.0", + "mocha": "9.1.3", + "nyc": "15.1.0" + }, + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "lint": "eslint . && node ./scripts/lint-readme-list.js", + "test": "mocha --reporter spec --bail", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test", + "version": "node scripts/version-history.js && git add HISTORY.md" + }, + "keywords": [ + "http", + "error" + ], + "files": [ + "index.js", + "HISTORY.md", + "LICENSE", + "README.md" + ] +} diff --git a/backend/node_modules/humanize-ms/History.md b/backend/node_modules/humanize-ms/History.md new file mode 100644 index 0000000000000000000000000000000000000000..b1595870501193cf638fe9f3d2d34f9a9229e46e --- /dev/null +++ b/backend/node_modules/humanize-ms/History.md @@ -0,0 +1,25 @@ + +1.2.1 / 2017-05-19 +================== + + * fix: package.json to reduce vulnerabilities (#3) + +1.2.0 / 2016-05-21 +================== + + * feat: warn with stack + +1.1.0 / 2016-04-04 +================== + + * deps: upgrade ms to 0.7.0 + +1.0.1 / 2014-12-31 +================== + + * feat(index.js): warn when result is undefined + +1.0.0 / 2014-08-14 +================== + + * init diff --git a/backend/node_modules/humanize-ms/LICENSE b/backend/node_modules/humanize-ms/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..89de354795ec7a7cdab07c091029653d3618540d --- /dev/null +++ b/backend/node_modules/humanize-ms/LICENSE @@ -0,0 +1,17 @@ +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/backend/node_modules/humanize-ms/README.md b/backend/node_modules/humanize-ms/README.md new file mode 100644 index 0000000000000000000000000000000000000000..20a2ca35b89fbc26f92986f2d7ad9b9f579e42ef --- /dev/null +++ b/backend/node_modules/humanize-ms/README.md @@ -0,0 +1,40 @@ +humanize-ms +--------------- + +[![NPM version][npm-image]][npm-url] +[![build status][travis-image]][travis-url] +[![Test coverage][coveralls-image]][coveralls-url] +[![Gittip][gittip-image]][gittip-url] +[![David deps][david-image]][david-url] + +[npm-image]: https://img.shields.io/npm/v/humanize-ms.svg?style=flat +[npm-url]: https://npmjs.org/package/humanize-ms +[travis-image]: https://img.shields.io/travis/node-modules/humanize-ms.svg?style=flat +[travis-url]: https://travis-ci.org/node-modules/humanize-ms +[coveralls-image]: https://img.shields.io/coveralls/node-modules/humanize-ms.svg?style=flat +[coveralls-url]: https://coveralls.io/r/node-modules/humanize-ms?branch=master +[gittip-image]: https://img.shields.io/gittip/dead-horse.svg?style=flat +[gittip-url]: https://www.gittip.com/dead-horse/ +[david-image]: https://img.shields.io/david/node-modules/humanize-ms.svg?style=flat +[david-url]: https://david-dm.org/node-modules/humanize-ms + +transform humanize time to ms + +## Installation + +```bash +$ npm install humanize-ms +``` + +## Examples + +```js +var ms = require('humanize-ms'); + +ms('1s') // 1000 +ms(1000) // 1000 +``` + +### License + +MIT diff --git a/backend/node_modules/humanize-ms/index.js b/backend/node_modules/humanize-ms/index.js new file mode 100644 index 0000000000000000000000000000000000000000..660df81def51203e511a0bd801655225e9d08ade --- /dev/null +++ b/backend/node_modules/humanize-ms/index.js @@ -0,0 +1,24 @@ +/*! + * humanize-ms - index.js + * Copyright(c) 2014 dead_horse + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + */ + +var util = require('util'); +var ms = require('ms'); + +module.exports = function (t) { + if (typeof t === 'number') return t; + var r = ms(t); + if (r === undefined) { + var err = new Error(util.format('humanize-ms(%j) result undefined', t)); + console.warn(err.stack); + } + return r; +}; diff --git a/backend/node_modules/humanize-ms/package.json b/backend/node_modules/humanize-ms/package.json new file mode 100644 index 0000000000000000000000000000000000000000..da4ab7f571a686b90680ae00f9284ab886c772f3 --- /dev/null +++ b/backend/node_modules/humanize-ms/package.json @@ -0,0 +1,37 @@ +{ + "name": "humanize-ms", + "version": "1.2.1", + "description": "transform humanize time to ms", + "main": "index.js", + "files": [ + "index.js" + ], + "scripts": { + "test": "make test" + }, + "keywords": [ + "humanize", + "ms" + ], + "author": { + "name": "dead-horse", + "email": "dead_horse@qq.com", + "url": "http://deadhorse.me" + }, + "repository": { + "type": "git", + "url": "https://github.com/node-modules/humanize-ms" + }, + "license": "MIT", + "dependencies": { + "ms": "^2.0.0" + }, + "devDependencies": { + "autod": "*", + "beautify-benchmark": "~0.2.4", + "benchmark": "~1.0.0", + "istanbul": "*", + "mocha": "*", + "should": "*" + } +} diff --git a/backend/node_modules/iconv-lite/Changelog.md b/backend/node_modules/iconv-lite/Changelog.md new file mode 100644 index 0000000000000000000000000000000000000000..f252313f8d0a145a3d1bacb68dbf06c0bf8e67c0 --- /dev/null +++ b/backend/node_modules/iconv-lite/Changelog.md @@ -0,0 +1,162 @@ +# 0.4.24 / 2018-08-22 + + * Added MIK encoding (#196, by @Ivan-Kalatchev) + + +# 0.4.23 / 2018-05-07 + + * Fix deprecation warning in Node v10 due to the last usage of `new Buffer` (#185, by @felixbuenemann) + * Switched from NodeBuffer to Buffer in typings (#155 by @felixfbecker, #186 by @larssn) + + +# 0.4.22 / 2018-05-05 + + * Use older semver style for dependencies to be compatible with Node version 0.10 (#182, by @dougwilson) + * Fix tests to accomodate fixes in Node v10 (#182, by @dougwilson) + + +# 0.4.21 / 2018-04-06 + + * Fix encoding canonicalization (#156) + * Fix the paths in the "browser" field in package.json (#174 by @LMLB) + * Removed "contributors" section in package.json - see Git history instead. + + +# 0.4.20 / 2018-04-06 + + * Updated `new Buffer()` usages with recommended replacements as it's being deprecated in Node v10 (#176, #178 by @ChALkeR) + + +# 0.4.19 / 2017-09-09 + + * Fixed iso8859-1 codec regression in handling untranslatable characters (#162, caused by #147) + * Re-generated windows1255 codec, because it was updated in iconv project + * Fixed grammar in error message when iconv-lite is loaded with encoding other than utf8 + + +# 0.4.18 / 2017-06-13 + + * Fixed CESU-8 regression in Node v8. + + +# 0.4.17 / 2017-04-22 + + * Updated typescript definition file to support Angular 2 AoT mode (#153 by @larssn) + + +# 0.4.16 / 2017-04-22 + + * Added support for React Native (#150) + * Changed iso8859-1 encoding to usine internal 'binary' encoding, as it's the same thing (#147 by @mscdex) + * Fixed typo in Readme (#138 by @jiangzhuo) + * Fixed build for Node v6.10+ by making correct version comparison + * Added a warning if iconv-lite is loaded not as utf-8 (see #142) + + +# 0.4.15 / 2016-11-21 + + * Fixed typescript type definition (#137) + + +# 0.4.14 / 2016-11-20 + + * Preparation for v1.0 + * Added Node v6 and latest Node versions to Travis CI test rig + * Deprecated Node v0.8 support + * Typescript typings (@larssn) + * Fix encoding of Euro character in GB 18030 (inspired by @lygstate) + * Add ms prefix to dbcs windows encodings (@rokoroku) + + +# 0.4.13 / 2015-10-01 + + * Fix silly mistake in deprecation notice. + + +# 0.4.12 / 2015-09-26 + + * Node v4 support: + * Added CESU-8 decoding (#106) + * Added deprecation notice for `extendNodeEncodings` + * Added Travis tests for Node v4 and io.js latest (#105 by @Mithgol) + + +# 0.4.11 / 2015-07-03 + + * Added CESU-8 encoding. + + +# 0.4.10 / 2015-05-26 + + * Changed UTF-16 endianness heuristic to take into account any ASCII chars, not + just spaces. This should minimize the importance of "default" endianness. + + +# 0.4.9 / 2015-05-24 + + * Streamlined BOM handling: strip BOM by default, add BOM when encoding if + addBOM: true. Added docs to Readme. + * UTF16 now uses UTF16-LE by default. + * Fixed minor issue with big5 encoding. + * Added io.js testing on Travis; updated node-iconv version to test against. + Now we just skip testing SBCS encodings that node-iconv doesn't support. + * (internal refactoring) Updated codec interface to use classes. + * Use strict mode in all files. + + +# 0.4.8 / 2015-04-14 + + * added alias UNICODE-1-1-UTF-7 for UTF-7 encoding (#94) + + +# 0.4.7 / 2015-02-05 + + * stop official support of Node.js v0.8. Should still work, but no guarantees. + reason: Packages needed for testing are hard to get on Travis CI. + * work in environment where Object.prototype is monkey patched with enumerable + props (#89). + + +# 0.4.6 / 2015-01-12 + + * fix rare aliases of single-byte encodings (thanks @mscdex) + * double the timeout for dbcs tests to make them less flaky on travis + + +# 0.4.5 / 2014-11-20 + + * fix windows-31j and x-sjis encoding support (@nleush) + * minor fix: undefined variable reference when internal error happens + + +# 0.4.4 / 2014-07-16 + + * added encodings UTF-7 (RFC2152) and UTF-7-IMAP (RFC3501 Section 5.1.3) + * fixed streaming base64 encoding + + +# 0.4.3 / 2014-06-14 + + * added encodings UTF-16BE and UTF-16 with BOM + + +# 0.4.2 / 2014-06-12 + + * don't throw exception if `extendNodeEncodings()` is called more than once + + +# 0.4.1 / 2014-06-11 + + * codepage 808 added + + +# 0.4.0 / 2014-06-10 + + * code is rewritten from scratch + * all widespread encodings are supported + * streaming interface added + * browserify compatibility added + * (optional) extend core primitive encodings to make usage even simpler + * moved from vows to mocha as the testing framework + + diff --git a/backend/node_modules/iconv-lite/LICENSE b/backend/node_modules/iconv-lite/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d518d8376af9faa47af875d83c8cdd51a11f9099 --- /dev/null +++ b/backend/node_modules/iconv-lite/LICENSE @@ -0,0 +1,21 @@ +Copyright (c) 2011 Alexander Shtuchkin + +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/backend/node_modules/iconv-lite/README.md b/backend/node_modules/iconv-lite/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c981c3708582a563f0f463c1e01715257d5148bd --- /dev/null +++ b/backend/node_modules/iconv-lite/README.md @@ -0,0 +1,156 @@ +## Pure JS character encoding conversion [![Build Status](https://travis-ci.org/ashtuchkin/iconv-lite.svg?branch=master)](https://travis-ci.org/ashtuchkin/iconv-lite) + + * Doesn't need native code compilation. Works on Windows and in sandboxed environments like [Cloud9](http://c9.io). + * Used in popular projects like [Express.js (body_parser)](https://github.com/expressjs/body-parser), + [Grunt](http://gruntjs.com/), [Nodemailer](http://www.nodemailer.com/), [Yeoman](http://yeoman.io/) and others. + * Faster than [node-iconv](https://github.com/bnoordhuis/node-iconv) (see below for performance comparison). + * Intuitive encode/decode API + * Streaming support for Node v0.10+ + * [Deprecated] Can extend Node.js primitives (buffers, streams) to support all iconv-lite encodings. + * In-browser usage via [Browserify](https://github.com/substack/node-browserify) (~180k gzip compressed with Buffer shim included). + * Typescript [type definition file](https://github.com/ashtuchkin/iconv-lite/blob/master/lib/index.d.ts) included. + * React Native is supported (need to explicitly `npm install` two more modules: `buffer` and `stream`). + * License: MIT. + +[![NPM Stats](https://nodei.co/npm/iconv-lite.png?downloads=true&downloadRank=true)](https://npmjs.org/packages/iconv-lite/) + +## Usage +### Basic API +```javascript +var iconv = require('iconv-lite'); + +// Convert from an encoded buffer to js string. +str = iconv.decode(Buffer.from([0x68, 0x65, 0x6c, 0x6c, 0x6f]), 'win1251'); + +// Convert from js string to an encoded buffer. +buf = iconv.encode("Sample input string", 'win1251'); + +// Check if encoding is supported +iconv.encodingExists("us-ascii") +``` + +### Streaming API (Node v0.10+) +```javascript + +// Decode stream (from binary stream to js strings) +http.createServer(function(req, res) { + var converterStream = iconv.decodeStream('win1251'); + req.pipe(converterStream); + + converterStream.on('data', function(str) { + console.log(str); // Do something with decoded strings, chunk-by-chunk. + }); +}); + +// Convert encoding streaming example +fs.createReadStream('file-in-win1251.txt') + .pipe(iconv.decodeStream('win1251')) + .pipe(iconv.encodeStream('ucs2')) + .pipe(fs.createWriteStream('file-in-ucs2.txt')); + +// Sugar: all encode/decode streams have .collect(cb) method to accumulate data. +http.createServer(function(req, res) { + req.pipe(iconv.decodeStream('win1251')).collect(function(err, body) { + assert(typeof body == 'string'); + console.log(body); // full request body string + }); +}); +``` + +### [Deprecated] Extend Node.js own encodings +> NOTE: This doesn't work on latest Node versions. See [details](https://github.com/ashtuchkin/iconv-lite/wiki/Node-v4-compatibility). + +```javascript +// After this call all Node basic primitives will understand iconv-lite encodings. +iconv.extendNodeEncodings(); + +// Examples: +buf = new Buffer(str, 'win1251'); +buf.write(str, 'gbk'); +str = buf.toString('latin1'); +assert(Buffer.isEncoding('iso-8859-15')); +Buffer.byteLength(str, 'us-ascii'); + +http.createServer(function(req, res) { + req.setEncoding('big5'); + req.collect(function(err, body) { + console.log(body); + }); +}); + +fs.createReadStream("file.txt", "shift_jis"); + +// External modules are also supported (if they use Node primitives, which they probably do). +request = require('request'); +request({ + url: "http://github.com/", + encoding: "cp932" +}); + +// To remove extensions +iconv.undoExtendNodeEncodings(); +``` + +## Supported encodings + + * All node.js native encodings: utf8, ucs2 / utf16-le, ascii, binary, base64, hex. + * Additional unicode encodings: utf16, utf16-be, utf-7, utf-7-imap. + * All widespread singlebyte encodings: Windows 125x family, ISO-8859 family, + IBM/DOS codepages, Macintosh family, KOI8 family, all others supported by iconv library. + Aliases like 'latin1', 'us-ascii' also supported. + * All widespread multibyte encodings: CP932, CP936, CP949, CP950, GB2312, GBK, GB18030, Big5, Shift_JIS, EUC-JP. + +See [all supported encodings on wiki](https://github.com/ashtuchkin/iconv-lite/wiki/Supported-Encodings). + +Most singlebyte encodings are generated automatically from [node-iconv](https://github.com/bnoordhuis/node-iconv). Thank you Ben Noordhuis and libiconv authors! + +Multibyte encodings are generated from [Unicode.org mappings](http://www.unicode.org/Public/MAPPINGS/) and [WHATWG Encoding Standard mappings](http://encoding.spec.whatwg.org/). Thank you, respective authors! + + +## Encoding/decoding speed + +Comparison with node-iconv module (1000x256kb, on MacBook Pro, Core i5/2.6 GHz, Node v0.12.0). +Note: your results may vary, so please always check on your hardware. + + operation iconv@2.1.4 iconv-lite@0.4.7 + ---------------------------------------------------------- + encode('win1251') ~96 Mb/s ~320 Mb/s + decode('win1251') ~95 Mb/s ~246 Mb/s + +## BOM handling + + * Decoding: BOM is stripped by default, unless overridden by passing `stripBOM: false` in options + (f.ex. `iconv.decode(buf, enc, {stripBOM: false})`). + A callback might also be given as a `stripBOM` parameter - it'll be called if BOM character was actually found. + * If you want to detect UTF-8 BOM when decoding other encodings, use [node-autodetect-decoder-stream](https://github.com/danielgindi/node-autodetect-decoder-stream) module. + * Encoding: No BOM added, unless overridden by `addBOM: true` option. + +## UTF-16 Encodings + +This library supports UTF-16LE, UTF-16BE and UTF-16 encodings. First two are straightforward, but UTF-16 is trying to be +smart about endianness in the following ways: + * Decoding: uses BOM and 'spaces heuristic' to determine input endianness. Default is UTF-16LE, but can be + overridden with `defaultEncoding: 'utf-16be'` option. Strips BOM unless `stripBOM: false`. + * Encoding: uses UTF-16LE and writes BOM by default. Use `addBOM: false` to override. + +## Other notes + +When decoding, be sure to supply a Buffer to decode() method, otherwise [bad things usually happen](https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding). +Untranslatable characters are set to � or ?. No transliteration is currently supported. +Node versions 0.10.31 and 0.11.13 are buggy, don't use them (see #65, #77). + +## Testing + +```bash +$ git clone git@github.com:ashtuchkin/iconv-lite.git +$ cd iconv-lite +$ npm install +$ npm test + +$ # To view performance: +$ node test/performance.js + +$ # To view test coverage: +$ npm run coverage +$ open coverage/lcov-report/index.html +``` diff --git a/backend/node_modules/iconv-lite/encodings/dbcs-codec.js b/backend/node_modules/iconv-lite/encodings/dbcs-codec.js new file mode 100644 index 0000000000000000000000000000000000000000..1fe3e160112aa9b896df4b30a0184d76a69dfaef --- /dev/null +++ b/backend/node_modules/iconv-lite/encodings/dbcs-codec.js @@ -0,0 +1,555 @@ +"use strict"; +var Buffer = require("safer-buffer").Buffer; + +// Multibyte codec. In this scheme, a character is represented by 1 or more bytes. +// Our codec supports UTF-16 surrogates, extensions for GB18030 and unicode sequences. +// To save memory and loading time, we read table files only when requested. + +exports._dbcs = DBCSCodec; + +var UNASSIGNED = -1, + GB18030_CODE = -2, + SEQ_START = -10, + NODE_START = -1000, + UNASSIGNED_NODE = new Array(0x100), + DEF_CHAR = -1; + +for (var i = 0; i < 0x100; i++) + UNASSIGNED_NODE[i] = UNASSIGNED; + + +// Class DBCSCodec reads and initializes mapping tables. +function DBCSCodec(codecOptions, iconv) { + this.encodingName = codecOptions.encodingName; + if (!codecOptions) + throw new Error("DBCS codec is called without the data.") + if (!codecOptions.table) + throw new Error("Encoding '" + this.encodingName + "' has no data."); + + // Load tables. + var mappingTable = codecOptions.table(); + + + // Decode tables: MBCS -> Unicode. + + // decodeTables is a trie, encoded as an array of arrays of integers. Internal arrays are trie nodes and all have len = 256. + // Trie root is decodeTables[0]. + // Values: >= 0 -> unicode character code. can be > 0xFFFF + // == UNASSIGNED -> unknown/unassigned sequence. + // == GB18030_CODE -> this is the end of a GB18030 4-byte sequence. + // <= NODE_START -> index of the next node in our trie to process next byte. + // <= SEQ_START -> index of the start of a character code sequence, in decodeTableSeq. + this.decodeTables = []; + this.decodeTables[0] = UNASSIGNED_NODE.slice(0); // Create root node. + + // Sometimes a MBCS char corresponds to a sequence of unicode chars. We store them as arrays of integers here. + this.decodeTableSeq = []; + + // Actual mapping tables consist of chunks. Use them to fill up decode tables. + for (var i = 0; i < mappingTable.length; i++) + this._addDecodeChunk(mappingTable[i]); + + this.defaultCharUnicode = iconv.defaultCharUnicode; + + + // Encode tables: Unicode -> DBCS. + + // `encodeTable` is array mapping from unicode char to encoded char. All its values are integers for performance. + // Because it can be sparse, it is represented as array of buckets by 256 chars each. Bucket can be null. + // Values: >= 0 -> it is a normal char. Write the value (if <=256 then 1 byte, if <=65536 then 2 bytes, etc.). + // == UNASSIGNED -> no conversion found. Output a default char. + // <= SEQ_START -> it's an index in encodeTableSeq, see below. The character starts a sequence. + this.encodeTable = []; + + // `encodeTableSeq` is used when a sequence of unicode characters is encoded as a single code. We use a tree of + // objects where keys correspond to characters in sequence and leafs are the encoded dbcs values. A special DEF_CHAR key + // means end of sequence (needed when one sequence is a strict subsequence of another). + // Objects are kept separately from encodeTable to increase performance. + this.encodeTableSeq = []; + + // Some chars can be decoded, but need not be encoded. + var skipEncodeChars = {}; + if (codecOptions.encodeSkipVals) + for (var i = 0; i < codecOptions.encodeSkipVals.length; i++) { + var val = codecOptions.encodeSkipVals[i]; + if (typeof val === 'number') + skipEncodeChars[val] = true; + else + for (var j = val.from; j <= val.to; j++) + skipEncodeChars[j] = true; + } + + // Use decode trie to recursively fill out encode tables. + this._fillEncodeTable(0, 0, skipEncodeChars); + + // Add more encoding pairs when needed. + if (codecOptions.encodeAdd) { + for (var uChar in codecOptions.encodeAdd) + if (Object.prototype.hasOwnProperty.call(codecOptions.encodeAdd, uChar)) + this._setEncodeChar(uChar.charCodeAt(0), codecOptions.encodeAdd[uChar]); + } + + this.defCharSB = this.encodeTable[0][iconv.defaultCharSingleByte.charCodeAt(0)]; + if (this.defCharSB === UNASSIGNED) this.defCharSB = this.encodeTable[0]['?']; + if (this.defCharSB === UNASSIGNED) this.defCharSB = "?".charCodeAt(0); + + + // Load & create GB18030 tables when needed. + if (typeof codecOptions.gb18030 === 'function') { + this.gb18030 = codecOptions.gb18030(); // Load GB18030 ranges. + + // Add GB18030 decode tables. + var thirdByteNodeIdx = this.decodeTables.length; + var thirdByteNode = this.decodeTables[thirdByteNodeIdx] = UNASSIGNED_NODE.slice(0); + + var fourthByteNodeIdx = this.decodeTables.length; + var fourthByteNode = this.decodeTables[fourthByteNodeIdx] = UNASSIGNED_NODE.slice(0); + + for (var i = 0x81; i <= 0xFE; i++) { + var secondByteNodeIdx = NODE_START - this.decodeTables[0][i]; + var secondByteNode = this.decodeTables[secondByteNodeIdx]; + for (var j = 0x30; j <= 0x39; j++) + secondByteNode[j] = NODE_START - thirdByteNodeIdx; + } + for (var i = 0x81; i <= 0xFE; i++) + thirdByteNode[i] = NODE_START - fourthByteNodeIdx; + for (var i = 0x30; i <= 0x39; i++) + fourthByteNode[i] = GB18030_CODE + } +} + +DBCSCodec.prototype.encoder = DBCSEncoder; +DBCSCodec.prototype.decoder = DBCSDecoder; + +// Decoder helpers +DBCSCodec.prototype._getDecodeTrieNode = function(addr) { + var bytes = []; + for (; addr > 0; addr >>= 8) + bytes.push(addr & 0xFF); + if (bytes.length == 0) + bytes.push(0); + + var node = this.decodeTables[0]; + for (var i = bytes.length-1; i > 0; i--) { // Traverse nodes deeper into the trie. + var val = node[bytes[i]]; + + if (val == UNASSIGNED) { // Create new node. + node[bytes[i]] = NODE_START - this.decodeTables.length; + this.decodeTables.push(node = UNASSIGNED_NODE.slice(0)); + } + else if (val <= NODE_START) { // Existing node. + node = this.decodeTables[NODE_START - val]; + } + else + throw new Error("Overwrite byte in " + this.encodingName + ", addr: " + addr.toString(16)); + } + return node; +} + + +DBCSCodec.prototype._addDecodeChunk = function(chunk) { + // First element of chunk is the hex mbcs code where we start. + var curAddr = parseInt(chunk[0], 16); + + // Choose the decoding node where we'll write our chars. + var writeTable = this._getDecodeTrieNode(curAddr); + curAddr = curAddr & 0xFF; + + // Write all other elements of the chunk to the table. + for (var k = 1; k < chunk.length; k++) { + var part = chunk[k]; + if (typeof part === "string") { // String, write as-is. + for (var l = 0; l < part.length;) { + var code = part.charCodeAt(l++); + if (0xD800 <= code && code < 0xDC00) { // Decode surrogate + var codeTrail = part.charCodeAt(l++); + if (0xDC00 <= codeTrail && codeTrail < 0xE000) + writeTable[curAddr++] = 0x10000 + (code - 0xD800) * 0x400 + (codeTrail - 0xDC00); + else + throw new Error("Incorrect surrogate pair in " + this.encodingName + " at chunk " + chunk[0]); + } + else if (0x0FF0 < code && code <= 0x0FFF) { // Character sequence (our own encoding used) + var len = 0xFFF - code + 2; + var seq = []; + for (var m = 0; m < len; m++) + seq.push(part.charCodeAt(l++)); // Simple variation: don't support surrogates or subsequences in seq. + + writeTable[curAddr++] = SEQ_START - this.decodeTableSeq.length; + this.decodeTableSeq.push(seq); + } + else + writeTable[curAddr++] = code; // Basic char + } + } + else if (typeof part === "number") { // Integer, meaning increasing sequence starting with prev character. + var charCode = writeTable[curAddr - 1] + 1; + for (var l = 0; l < part; l++) + writeTable[curAddr++] = charCode++; + } + else + throw new Error("Incorrect type '" + typeof part + "' given in " + this.encodingName + " at chunk " + chunk[0]); + } + if (curAddr > 0xFF) + throw new Error("Incorrect chunk in " + this.encodingName + " at addr " + chunk[0] + ": too long" + curAddr); +} + +// Encoder helpers +DBCSCodec.prototype._getEncodeBucket = function(uCode) { + var high = uCode >> 8; // This could be > 0xFF because of astral characters. + if (this.encodeTable[high] === undefined) + this.encodeTable[high] = UNASSIGNED_NODE.slice(0); // Create bucket on demand. + return this.encodeTable[high]; +} + +DBCSCodec.prototype._setEncodeChar = function(uCode, dbcsCode) { + var bucket = this._getEncodeBucket(uCode); + var low = uCode & 0xFF; + if (bucket[low] <= SEQ_START) + this.encodeTableSeq[SEQ_START-bucket[low]][DEF_CHAR] = dbcsCode; // There's already a sequence, set a single-char subsequence of it. + else if (bucket[low] == UNASSIGNED) + bucket[low] = dbcsCode; +} + +DBCSCodec.prototype._setEncodeSequence = function(seq, dbcsCode) { + + // Get the root of character tree according to first character of the sequence. + var uCode = seq[0]; + var bucket = this._getEncodeBucket(uCode); + var low = uCode & 0xFF; + + var node; + if (bucket[low] <= SEQ_START) { + // There's already a sequence with - use it. + node = this.encodeTableSeq[SEQ_START-bucket[low]]; + } + else { + // There was no sequence object - allocate a new one. + node = {}; + if (bucket[low] !== UNASSIGNED) node[DEF_CHAR] = bucket[low]; // If a char was set before - make it a single-char subsequence. + bucket[low] = SEQ_START - this.encodeTableSeq.length; + this.encodeTableSeq.push(node); + } + + // Traverse the character tree, allocating new nodes as needed. + for (var j = 1; j < seq.length-1; j++) { + var oldVal = node[uCode]; + if (typeof oldVal === 'object') + node = oldVal; + else { + node = node[uCode] = {} + if (oldVal !== undefined) + node[DEF_CHAR] = oldVal + } + } + + // Set the leaf to given dbcsCode. + uCode = seq[seq.length-1]; + node[uCode] = dbcsCode; +} + +DBCSCodec.prototype._fillEncodeTable = function(nodeIdx, prefix, skipEncodeChars) { + var node = this.decodeTables[nodeIdx]; + for (var i = 0; i < 0x100; i++) { + var uCode = node[i]; + var mbCode = prefix + i; + if (skipEncodeChars[mbCode]) + continue; + + if (uCode >= 0) + this._setEncodeChar(uCode, mbCode); + else if (uCode <= NODE_START) + this._fillEncodeTable(NODE_START - uCode, mbCode << 8, skipEncodeChars); + else if (uCode <= SEQ_START) + this._setEncodeSequence(this.decodeTableSeq[SEQ_START - uCode], mbCode); + } +} + + + +// == Encoder ================================================================== + +function DBCSEncoder(options, codec) { + // Encoder state + this.leadSurrogate = -1; + this.seqObj = undefined; + + // Static data + this.encodeTable = codec.encodeTable; + this.encodeTableSeq = codec.encodeTableSeq; + this.defaultCharSingleByte = codec.defCharSB; + this.gb18030 = codec.gb18030; +} + +DBCSEncoder.prototype.write = function(str) { + var newBuf = Buffer.alloc(str.length * (this.gb18030 ? 4 : 3)), + leadSurrogate = this.leadSurrogate, + seqObj = this.seqObj, nextChar = -1, + i = 0, j = 0; + + while (true) { + // 0. Get next character. + if (nextChar === -1) { + if (i == str.length) break; + var uCode = str.charCodeAt(i++); + } + else { + var uCode = nextChar; + nextChar = -1; + } + + // 1. Handle surrogates. + if (0xD800 <= uCode && uCode < 0xE000) { // Char is one of surrogates. + if (uCode < 0xDC00) { // We've got lead surrogate. + if (leadSurrogate === -1) { + leadSurrogate = uCode; + continue; + } else { + leadSurrogate = uCode; + // Double lead surrogate found. + uCode = UNASSIGNED; + } + } else { // We've got trail surrogate. + if (leadSurrogate !== -1) { + uCode = 0x10000 + (leadSurrogate - 0xD800) * 0x400 + (uCode - 0xDC00); + leadSurrogate = -1; + } else { + // Incomplete surrogate pair - only trail surrogate found. + uCode = UNASSIGNED; + } + + } + } + else if (leadSurrogate !== -1) { + // Incomplete surrogate pair - only lead surrogate found. + nextChar = uCode; uCode = UNASSIGNED; // Write an error, then current char. + leadSurrogate = -1; + } + + // 2. Convert uCode character. + var dbcsCode = UNASSIGNED; + if (seqObj !== undefined && uCode != UNASSIGNED) { // We are in the middle of the sequence + var resCode = seqObj[uCode]; + if (typeof resCode === 'object') { // Sequence continues. + seqObj = resCode; + continue; + + } else if (typeof resCode == 'number') { // Sequence finished. Write it. + dbcsCode = resCode; + + } else if (resCode == undefined) { // Current character is not part of the sequence. + + // Try default character for this sequence + resCode = seqObj[DEF_CHAR]; + if (resCode !== undefined) { + dbcsCode = resCode; // Found. Write it. + nextChar = uCode; // Current character will be written too in the next iteration. + + } else { + // TODO: What if we have no default? (resCode == undefined) + // Then, we should write first char of the sequence as-is and try the rest recursively. + // Didn't do it for now because no encoding has this situation yet. + // Currently, just skip the sequence and write current char. + } + } + seqObj = undefined; + } + else if (uCode >= 0) { // Regular character + var subtable = this.encodeTable[uCode >> 8]; + if (subtable !== undefined) + dbcsCode = subtable[uCode & 0xFF]; + + if (dbcsCode <= SEQ_START) { // Sequence start + seqObj = this.encodeTableSeq[SEQ_START-dbcsCode]; + continue; + } + + if (dbcsCode == UNASSIGNED && this.gb18030) { + // Use GB18030 algorithm to find character(s) to write. + var idx = findIdx(this.gb18030.uChars, uCode); + if (idx != -1) { + var dbcsCode = this.gb18030.gbChars[idx] + (uCode - this.gb18030.uChars[idx]); + newBuf[j++] = 0x81 + Math.floor(dbcsCode / 12600); dbcsCode = dbcsCode % 12600; + newBuf[j++] = 0x30 + Math.floor(dbcsCode / 1260); dbcsCode = dbcsCode % 1260; + newBuf[j++] = 0x81 + Math.floor(dbcsCode / 10); dbcsCode = dbcsCode % 10; + newBuf[j++] = 0x30 + dbcsCode; + continue; + } + } + } + + // 3. Write dbcsCode character. + if (dbcsCode === UNASSIGNED) + dbcsCode = this.defaultCharSingleByte; + + if (dbcsCode < 0x100) { + newBuf[j++] = dbcsCode; + } + else if (dbcsCode < 0x10000) { + newBuf[j++] = dbcsCode >> 8; // high byte + newBuf[j++] = dbcsCode & 0xFF; // low byte + } + else { + newBuf[j++] = dbcsCode >> 16; + newBuf[j++] = (dbcsCode >> 8) & 0xFF; + newBuf[j++] = dbcsCode & 0xFF; + } + } + + this.seqObj = seqObj; + this.leadSurrogate = leadSurrogate; + return newBuf.slice(0, j); +} + +DBCSEncoder.prototype.end = function() { + if (this.leadSurrogate === -1 && this.seqObj === undefined) + return; // All clean. Most often case. + + var newBuf = Buffer.alloc(10), j = 0; + + if (this.seqObj) { // We're in the sequence. + var dbcsCode = this.seqObj[DEF_CHAR]; + if (dbcsCode !== undefined) { // Write beginning of the sequence. + if (dbcsCode < 0x100) { + newBuf[j++] = dbcsCode; + } + else { + newBuf[j++] = dbcsCode >> 8; // high byte + newBuf[j++] = dbcsCode & 0xFF; // low byte + } + } else { + // See todo above. + } + this.seqObj = undefined; + } + + if (this.leadSurrogate !== -1) { + // Incomplete surrogate pair - only lead surrogate found. + newBuf[j++] = this.defaultCharSingleByte; + this.leadSurrogate = -1; + } + + return newBuf.slice(0, j); +} + +// Export for testing +DBCSEncoder.prototype.findIdx = findIdx; + + +// == Decoder ================================================================== + +function DBCSDecoder(options, codec) { + // Decoder state + this.nodeIdx = 0; + this.prevBuf = Buffer.alloc(0); + + // Static data + this.decodeTables = codec.decodeTables; + this.decodeTableSeq = codec.decodeTableSeq; + this.defaultCharUnicode = codec.defaultCharUnicode; + this.gb18030 = codec.gb18030; +} + +DBCSDecoder.prototype.write = function(buf) { + var newBuf = Buffer.alloc(buf.length*2), + nodeIdx = this.nodeIdx, + prevBuf = this.prevBuf, prevBufOffset = this.prevBuf.length, + seqStart = -this.prevBuf.length, // idx of the start of current parsed sequence. + uCode; + + if (prevBufOffset > 0) // Make prev buf overlap a little to make it easier to slice later. + prevBuf = Buffer.concat([prevBuf, buf.slice(0, 10)]); + + for (var i = 0, j = 0; i < buf.length; i++) { + var curByte = (i >= 0) ? buf[i] : prevBuf[i + prevBufOffset]; + + // Lookup in current trie node. + var uCode = this.decodeTables[nodeIdx][curByte]; + + if (uCode >= 0) { + // Normal character, just use it. + } + else if (uCode === UNASSIGNED) { // Unknown char. + // TODO: Callback with seq. + //var curSeq = (seqStart >= 0) ? buf.slice(seqStart, i+1) : prevBuf.slice(seqStart + prevBufOffset, i+1 + prevBufOffset); + i = seqStart; // Try to parse again, after skipping first byte of the sequence ('i' will be incremented by 'for' cycle). + uCode = this.defaultCharUnicode.charCodeAt(0); + } + else if (uCode === GB18030_CODE) { + var curSeq = (seqStart >= 0) ? buf.slice(seqStart, i+1) : prevBuf.slice(seqStart + prevBufOffset, i+1 + prevBufOffset); + var ptr = (curSeq[0]-0x81)*12600 + (curSeq[1]-0x30)*1260 + (curSeq[2]-0x81)*10 + (curSeq[3]-0x30); + var idx = findIdx(this.gb18030.gbChars, ptr); + uCode = this.gb18030.uChars[idx] + ptr - this.gb18030.gbChars[idx]; + } + else if (uCode <= NODE_START) { // Go to next trie node. + nodeIdx = NODE_START - uCode; + continue; + } + else if (uCode <= SEQ_START) { // Output a sequence of chars. + var seq = this.decodeTableSeq[SEQ_START - uCode]; + for (var k = 0; k < seq.length - 1; k++) { + uCode = seq[k]; + newBuf[j++] = uCode & 0xFF; + newBuf[j++] = uCode >> 8; + } + uCode = seq[seq.length-1]; + } + else + throw new Error("iconv-lite internal error: invalid decoding table value " + uCode + " at " + nodeIdx + "/" + curByte); + + // Write the character to buffer, handling higher planes using surrogate pair. + if (uCode > 0xFFFF) { + uCode -= 0x10000; + var uCodeLead = 0xD800 + Math.floor(uCode / 0x400); + newBuf[j++] = uCodeLead & 0xFF; + newBuf[j++] = uCodeLead >> 8; + + uCode = 0xDC00 + uCode % 0x400; + } + newBuf[j++] = uCode & 0xFF; + newBuf[j++] = uCode >> 8; + + // Reset trie node. + nodeIdx = 0; seqStart = i+1; + } + + this.nodeIdx = nodeIdx; + this.prevBuf = (seqStart >= 0) ? buf.slice(seqStart) : prevBuf.slice(seqStart + prevBufOffset); + return newBuf.slice(0, j).toString('ucs2'); +} + +DBCSDecoder.prototype.end = function() { + var ret = ''; + + // Try to parse all remaining chars. + while (this.prevBuf.length > 0) { + // Skip 1 character in the buffer. + ret += this.defaultCharUnicode; + var buf = this.prevBuf.slice(1); + + // Parse remaining as usual. + this.prevBuf = Buffer.alloc(0); + this.nodeIdx = 0; + if (buf.length > 0) + ret += this.write(buf); + } + + this.nodeIdx = 0; + return ret; +} + +// Binary search for GB18030. Returns largest i such that table[i] <= val. +function findIdx(table, val) { + if (table[0] > val) + return -1; + + var l = 0, r = table.length; + while (l < r-1) { // always table[l] <= val < table[r] + var mid = l + Math.floor((r-l+1)/2); + if (table[mid] <= val) + l = mid; + else + r = mid; + } + return l; +} + diff --git a/backend/node_modules/iconv-lite/encodings/dbcs-data.js b/backend/node_modules/iconv-lite/encodings/dbcs-data.js new file mode 100644 index 0000000000000000000000000000000000000000..4b61914341f9165a4b54543d49e93af6b0d559cf --- /dev/null +++ b/backend/node_modules/iconv-lite/encodings/dbcs-data.js @@ -0,0 +1,176 @@ +"use strict"; + +// Description of supported double byte encodings and aliases. +// Tables are not require()-d until they are needed to speed up library load. +// require()-s are direct to support Browserify. + +module.exports = { + + // == Japanese/ShiftJIS ==================================================== + // All japanese encodings are based on JIS X set of standards: + // JIS X 0201 - Single-byte encoding of ASCII + ¥ + Kana chars at 0xA1-0xDF. + // JIS X 0208 - Main set of 6879 characters, placed in 94x94 plane, to be encoded by 2 bytes. + // Has several variations in 1978, 1983, 1990 and 1997. + // JIS X 0212 - Supplementary plane of 6067 chars in 94x94 plane. 1990. Effectively dead. + // JIS X 0213 - Extension and modern replacement of 0208 and 0212. Total chars: 11233. + // 2 planes, first is superset of 0208, second - revised 0212. + // Introduced in 2000, revised 2004. Some characters are in Unicode Plane 2 (0x2xxxx) + + // Byte encodings are: + // * Shift_JIS: Compatible with 0201, uses not defined chars in top half as lead bytes for double-byte + // encoding of 0208. Lead byte ranges: 0x81-0x9F, 0xE0-0xEF; Trail byte ranges: 0x40-0x7E, 0x80-0x9E, 0x9F-0xFC. + // Windows CP932 is a superset of Shift_JIS. Some companies added more chars, notably KDDI. + // * EUC-JP: Up to 3 bytes per character. Used mostly on *nixes. + // 0x00-0x7F - lower part of 0201 + // 0x8E, 0xA1-0xDF - upper part of 0201 + // (0xA1-0xFE)x2 - 0208 plane (94x94). + // 0x8F, (0xA1-0xFE)x2 - 0212 plane (94x94). + // * JIS X 208: 7-bit, direct encoding of 0208. Byte ranges: 0x21-0x7E (94 values). Uncommon. + // Used as-is in ISO2022 family. + // * ISO2022-JP: Stateful encoding, with escape sequences to switch between ASCII, + // 0201-1976 Roman, 0208-1978, 0208-1983. + // * ISO2022-JP-1: Adds esc seq for 0212-1990. + // * ISO2022-JP-2: Adds esc seq for GB2313-1980, KSX1001-1992, ISO8859-1, ISO8859-7. + // * ISO2022-JP-3: Adds esc seq for 0201-1976 Kana set, 0213-2000 Planes 1, 2. + // * ISO2022-JP-2004: Adds 0213-2004 Plane 1. + // + // After JIS X 0213 appeared, Shift_JIS-2004, EUC-JISX0213 and ISO2022-JP-2004 followed, with just changing the planes. + // + // Overall, it seems that it's a mess :( http://www8.plala.or.jp/tkubota1/unicode-symbols-map2.html + + 'shiftjis': { + type: '_dbcs', + table: function() { return require('./tables/shiftjis.json') }, + encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E}, + encodeSkipVals: [{from: 0xED40, to: 0xF940}], + }, + 'csshiftjis': 'shiftjis', + 'mskanji': 'shiftjis', + 'sjis': 'shiftjis', + 'windows31j': 'shiftjis', + 'ms31j': 'shiftjis', + 'xsjis': 'shiftjis', + 'windows932': 'shiftjis', + 'ms932': 'shiftjis', + '932': 'shiftjis', + 'cp932': 'shiftjis', + + 'eucjp': { + type: '_dbcs', + table: function() { return require('./tables/eucjp.json') }, + encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E}, + }, + + // TODO: KDDI extension to Shift_JIS + // TODO: IBM CCSID 942 = CP932, but F0-F9 custom chars and other char changes. + // TODO: IBM CCSID 943 = Shift_JIS = CP932 with original Shift_JIS lower 128 chars. + + + // == Chinese/GBK ========================================================== + // http://en.wikipedia.org/wiki/GBK + // We mostly implement W3C recommendation: https://www.w3.org/TR/encoding/#gbk-encoder + + // Oldest GB2312 (1981, ~7600 chars) is a subset of CP936 + 'gb2312': 'cp936', + 'gb231280': 'cp936', + 'gb23121980': 'cp936', + 'csgb2312': 'cp936', + 'csiso58gb231280': 'cp936', + 'euccn': 'cp936', + + // Microsoft's CP936 is a subset and approximation of GBK. + 'windows936': 'cp936', + 'ms936': 'cp936', + '936': 'cp936', + 'cp936': { + type: '_dbcs', + table: function() { return require('./tables/cp936.json') }, + }, + + // GBK (~22000 chars) is an extension of CP936 that added user-mapped chars and some other. + 'gbk': { + type: '_dbcs', + table: function() { return require('./tables/cp936.json').concat(require('./tables/gbk-added.json')) }, + }, + 'xgbk': 'gbk', + 'isoir58': 'gbk', + + // GB18030 is an algorithmic extension of GBK. + // Main source: https://www.w3.org/TR/encoding/#gbk-encoder + // http://icu-project.org/docs/papers/gb18030.html + // http://source.icu-project.org/repos/icu/data/trunk/charset/data/xml/gb-18030-2000.xml + // http://www.khngai.com/chinese/charmap/tblgbk.php?page=0 + 'gb18030': { + type: '_dbcs', + table: function() { return require('./tables/cp936.json').concat(require('./tables/gbk-added.json')) }, + gb18030: function() { return require('./tables/gb18030-ranges.json') }, + encodeSkipVals: [0x80], + encodeAdd: {'€': 0xA2E3}, + }, + + 'chinese': 'gb18030', + + + // == Korean =============================================================== + // EUC-KR, KS_C_5601 and KS X 1001 are exactly the same. + 'windows949': 'cp949', + 'ms949': 'cp949', + '949': 'cp949', + 'cp949': { + type: '_dbcs', + table: function() { return require('./tables/cp949.json') }, + }, + + 'cseuckr': 'cp949', + 'csksc56011987': 'cp949', + 'euckr': 'cp949', + 'isoir149': 'cp949', + 'korean': 'cp949', + 'ksc56011987': 'cp949', + 'ksc56011989': 'cp949', + 'ksc5601': 'cp949', + + + // == Big5/Taiwan/Hong Kong ================================================ + // There are lots of tables for Big5 and cp950. Please see the following links for history: + // http://moztw.org/docs/big5/ http://www.haible.de/bruno/charsets/conversion-tables/Big5.html + // Variations, in roughly number of defined chars: + // * Windows CP 950: Microsoft variant of Big5. Canonical: http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP950.TXT + // * Windows CP 951: Microsoft variant of Big5-HKSCS-2001. Seems to be never public. http://me.abelcheung.org/articles/research/what-is-cp951/ + // * Big5-2003 (Taiwan standard) almost superset of cp950. + // * Unicode-at-on (UAO) / Mozilla 1.8. Falling out of use on the Web. Not supported by other browsers. + // * Big5-HKSCS (-2001, -2004, -2008). Hong Kong standard. + // many unicode code points moved from PUA to Supplementary plane (U+2XXXX) over the years. + // Plus, it has 4 combining sequences. + // Seems that Mozilla refused to support it for 10 yrs. https://bugzilla.mozilla.org/show_bug.cgi?id=162431 https://bugzilla.mozilla.org/show_bug.cgi?id=310299 + // because big5-hkscs is the only encoding to include astral characters in non-algorithmic way. + // Implementations are not consistent within browsers; sometimes labeled as just big5. + // MS Internet Explorer switches from big5 to big5-hkscs when a patch applied. + // Great discussion & recap of what's going on https://bugzilla.mozilla.org/show_bug.cgi?id=912470#c31 + // In the encoder, it might make sense to support encoding old PUA mappings to Big5 bytes seq-s. + // Official spec: http://www.ogcio.gov.hk/en/business/tech_promotion/ccli/terms/doc/2003cmp_2008.txt + // http://www.ogcio.gov.hk/tc/business/tech_promotion/ccli/terms/doc/hkscs-2008-big5-iso.txt + // + // Current understanding of how to deal with Big5(-HKSCS) is in the Encoding Standard, http://encoding.spec.whatwg.org/#big5-encoder + // Unicode mapping (http://www.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/OTHER/BIG5.TXT) is said to be wrong. + + 'windows950': 'cp950', + 'ms950': 'cp950', + '950': 'cp950', + 'cp950': { + type: '_dbcs', + table: function() { return require('./tables/cp950.json') }, + }, + + // Big5 has many variations and is an extension of cp950. We use Encoding Standard's as a consensus. + 'big5': 'big5hkscs', + 'big5hkscs': { + type: '_dbcs', + table: function() { return require('./tables/cp950.json').concat(require('./tables/big5-added.json')) }, + encodeSkipVals: [0xa2cc], + }, + + 'cnbig5': 'big5hkscs', + 'csbig5': 'big5hkscs', + 'xxbig5': 'big5hkscs', +}; diff --git a/backend/node_modules/iconv-lite/encodings/index.js b/backend/node_modules/iconv-lite/encodings/index.js new file mode 100644 index 0000000000000000000000000000000000000000..e30400317c18fb2fd374e01d52c8f815976db6a5 --- /dev/null +++ b/backend/node_modules/iconv-lite/encodings/index.js @@ -0,0 +1,22 @@ +"use strict"; + +// Update this array if you add/rename/remove files in this directory. +// We support Browserify by skipping automatic module discovery and requiring modules directly. +var modules = [ + require("./internal"), + require("./utf16"), + require("./utf7"), + require("./sbcs-codec"), + require("./sbcs-data"), + require("./sbcs-data-generated"), + require("./dbcs-codec"), + require("./dbcs-data"), +]; + +// Put all encoding/alias/codec definitions to single object and export it. +for (var i = 0; i < modules.length; i++) { + var module = modules[i]; + for (var enc in module) + if (Object.prototype.hasOwnProperty.call(module, enc)) + exports[enc] = module[enc]; +} diff --git a/backend/node_modules/iconv-lite/encodings/internal.js b/backend/node_modules/iconv-lite/encodings/internal.js new file mode 100644 index 0000000000000000000000000000000000000000..05ce38b276eee23753837bea9df92a96e5d02c1a --- /dev/null +++ b/backend/node_modules/iconv-lite/encodings/internal.js @@ -0,0 +1,188 @@ +"use strict"; +var Buffer = require("safer-buffer").Buffer; + +// Export Node.js internal encodings. + +module.exports = { + // Encodings + utf8: { type: "_internal", bomAware: true}, + cesu8: { type: "_internal", bomAware: true}, + unicode11utf8: "utf8", + + ucs2: { type: "_internal", bomAware: true}, + utf16le: "ucs2", + + binary: { type: "_internal" }, + base64: { type: "_internal" }, + hex: { type: "_internal" }, + + // Codec. + _internal: InternalCodec, +}; + +//------------------------------------------------------------------------------ + +function InternalCodec(codecOptions, iconv) { + this.enc = codecOptions.encodingName; + this.bomAware = codecOptions.bomAware; + + if (this.enc === "base64") + this.encoder = InternalEncoderBase64; + else if (this.enc === "cesu8") { + this.enc = "utf8"; // Use utf8 for decoding. + this.encoder = InternalEncoderCesu8; + + // Add decoder for versions of Node not supporting CESU-8 + if (Buffer.from('eda0bdedb2a9', 'hex').toString() !== '💩') { + this.decoder = InternalDecoderCesu8; + this.defaultCharUnicode = iconv.defaultCharUnicode; + } + } +} + +InternalCodec.prototype.encoder = InternalEncoder; +InternalCodec.prototype.decoder = InternalDecoder; + +//------------------------------------------------------------------------------ + +// We use node.js internal decoder. Its signature is the same as ours. +var StringDecoder = require('string_decoder').StringDecoder; + +if (!StringDecoder.prototype.end) // Node v0.8 doesn't have this method. + StringDecoder.prototype.end = function() {}; + + +function InternalDecoder(options, codec) { + StringDecoder.call(this, codec.enc); +} + +InternalDecoder.prototype = StringDecoder.prototype; + + +//------------------------------------------------------------------------------ +// Encoder is mostly trivial + +function InternalEncoder(options, codec) { + this.enc = codec.enc; +} + +InternalEncoder.prototype.write = function(str) { + return Buffer.from(str, this.enc); +} + +InternalEncoder.prototype.end = function() { +} + + +//------------------------------------------------------------------------------ +// Except base64 encoder, which must keep its state. + +function InternalEncoderBase64(options, codec) { + this.prevStr = ''; +} + +InternalEncoderBase64.prototype.write = function(str) { + str = this.prevStr + str; + var completeQuads = str.length - (str.length % 4); + this.prevStr = str.slice(completeQuads); + str = str.slice(0, completeQuads); + + return Buffer.from(str, "base64"); +} + +InternalEncoderBase64.prototype.end = function() { + return Buffer.from(this.prevStr, "base64"); +} + + +//------------------------------------------------------------------------------ +// CESU-8 encoder is also special. + +function InternalEncoderCesu8(options, codec) { +} + +InternalEncoderCesu8.prototype.write = function(str) { + var buf = Buffer.alloc(str.length * 3), bufIdx = 0; + for (var i = 0; i < str.length; i++) { + var charCode = str.charCodeAt(i); + // Naive implementation, but it works because CESU-8 is especially easy + // to convert from UTF-16 (which all JS strings are encoded in). + if (charCode < 0x80) + buf[bufIdx++] = charCode; + else if (charCode < 0x800) { + buf[bufIdx++] = 0xC0 + (charCode >>> 6); + buf[bufIdx++] = 0x80 + (charCode & 0x3f); + } + else { // charCode will always be < 0x10000 in javascript. + buf[bufIdx++] = 0xE0 + (charCode >>> 12); + buf[bufIdx++] = 0x80 + ((charCode >>> 6) & 0x3f); + buf[bufIdx++] = 0x80 + (charCode & 0x3f); + } + } + return buf.slice(0, bufIdx); +} + +InternalEncoderCesu8.prototype.end = function() { +} + +//------------------------------------------------------------------------------ +// CESU-8 decoder is not implemented in Node v4.0+ + +function InternalDecoderCesu8(options, codec) { + this.acc = 0; + this.contBytes = 0; + this.accBytes = 0; + this.defaultCharUnicode = codec.defaultCharUnicode; +} + +InternalDecoderCesu8.prototype.write = function(buf) { + var acc = this.acc, contBytes = this.contBytes, accBytes = this.accBytes, + res = ''; + for (var i = 0; i < buf.length; i++) { + var curByte = buf[i]; + if ((curByte & 0xC0) !== 0x80) { // Leading byte + if (contBytes > 0) { // Previous code is invalid + res += this.defaultCharUnicode; + contBytes = 0; + } + + if (curByte < 0x80) { // Single-byte code + res += String.fromCharCode(curByte); + } else if (curByte < 0xE0) { // Two-byte code + acc = curByte & 0x1F; + contBytes = 1; accBytes = 1; + } else if (curByte < 0xF0) { // Three-byte code + acc = curByte & 0x0F; + contBytes = 2; accBytes = 1; + } else { // Four or more are not supported for CESU-8. + res += this.defaultCharUnicode; + } + } else { // Continuation byte + if (contBytes > 0) { // We're waiting for it. + acc = (acc << 6) | (curByte & 0x3f); + contBytes--; accBytes++; + if (contBytes === 0) { + // Check for overlong encoding, but support Modified UTF-8 (encoding NULL as C0 80) + if (accBytes === 2 && acc < 0x80 && acc > 0) + res += this.defaultCharUnicode; + else if (accBytes === 3 && acc < 0x800) + res += this.defaultCharUnicode; + else + // Actually add character. + res += String.fromCharCode(acc); + } + } else { // Unexpected continuation byte + res += this.defaultCharUnicode; + } + } + } + this.acc = acc; this.contBytes = contBytes; this.accBytes = accBytes; + return res; +} + +InternalDecoderCesu8.prototype.end = function() { + var res = 0; + if (this.contBytes > 0) + res += this.defaultCharUnicode; + return res; +} diff --git a/backend/node_modules/iconv-lite/encodings/sbcs-codec.js b/backend/node_modules/iconv-lite/encodings/sbcs-codec.js new file mode 100644 index 0000000000000000000000000000000000000000..abac5ffaac97da29fa5c5d8aedf5b47763fc7c58 --- /dev/null +++ b/backend/node_modules/iconv-lite/encodings/sbcs-codec.js @@ -0,0 +1,72 @@ +"use strict"; +var Buffer = require("safer-buffer").Buffer; + +// Single-byte codec. Needs a 'chars' string parameter that contains 256 or 128 chars that +// correspond to encoded bytes (if 128 - then lower half is ASCII). + +exports._sbcs = SBCSCodec; +function SBCSCodec(codecOptions, iconv) { + if (!codecOptions) + throw new Error("SBCS codec is called without the data.") + + // Prepare char buffer for decoding. + if (!codecOptions.chars || (codecOptions.chars.length !== 128 && codecOptions.chars.length !== 256)) + throw new Error("Encoding '"+codecOptions.type+"' has incorrect 'chars' (must be of len 128 or 256)"); + + if (codecOptions.chars.length === 128) { + var asciiString = ""; + for (var i = 0; i < 128; i++) + asciiString += String.fromCharCode(i); + codecOptions.chars = asciiString + codecOptions.chars; + } + + this.decodeBuf = Buffer.from(codecOptions.chars, 'ucs2'); + + // Encoding buffer. + var encodeBuf = Buffer.alloc(65536, iconv.defaultCharSingleByte.charCodeAt(0)); + + for (var i = 0; i < codecOptions.chars.length; i++) + encodeBuf[codecOptions.chars.charCodeAt(i)] = i; + + this.encodeBuf = encodeBuf; +} + +SBCSCodec.prototype.encoder = SBCSEncoder; +SBCSCodec.prototype.decoder = SBCSDecoder; + + +function SBCSEncoder(options, codec) { + this.encodeBuf = codec.encodeBuf; +} + +SBCSEncoder.prototype.write = function(str) { + var buf = Buffer.alloc(str.length); + for (var i = 0; i < str.length; i++) + buf[i] = this.encodeBuf[str.charCodeAt(i)]; + + return buf; +} + +SBCSEncoder.prototype.end = function() { +} + + +function SBCSDecoder(options, codec) { + this.decodeBuf = codec.decodeBuf; +} + +SBCSDecoder.prototype.write = function(buf) { + // Strings are immutable in JS -> we use ucs2 buffer to speed up computations. + var decodeBuf = this.decodeBuf; + var newBuf = Buffer.alloc(buf.length*2); + var idx1 = 0, idx2 = 0; + for (var i = 0; i < buf.length; i++) { + idx1 = buf[i]*2; idx2 = i*2; + newBuf[idx2] = decodeBuf[idx1]; + newBuf[idx2+1] = decodeBuf[idx1+1]; + } + return newBuf.toString('ucs2'); +} + +SBCSDecoder.prototype.end = function() { +} diff --git a/backend/node_modules/iconv-lite/encodings/sbcs-data-generated.js b/backend/node_modules/iconv-lite/encodings/sbcs-data-generated.js new file mode 100644 index 0000000000000000000000000000000000000000..9b4823607b6071c67dd7b553767bfee98a49de1c --- /dev/null +++ b/backend/node_modules/iconv-lite/encodings/sbcs-data-generated.js @@ -0,0 +1,451 @@ +"use strict"; + +// Generated data for sbcs codec. Don't edit manually. Regenerate using generation/gen-sbcs.js script. +module.exports = { + "437": "cp437", + "737": "cp737", + "775": "cp775", + "850": "cp850", + "852": "cp852", + "855": "cp855", + "856": "cp856", + "857": "cp857", + "858": "cp858", + "860": "cp860", + "861": "cp861", + "862": "cp862", + "863": "cp863", + "864": "cp864", + "865": "cp865", + "866": "cp866", + "869": "cp869", + "874": "windows874", + "922": "cp922", + "1046": "cp1046", + "1124": "cp1124", + "1125": "cp1125", + "1129": "cp1129", + "1133": "cp1133", + "1161": "cp1161", + "1162": "cp1162", + "1163": "cp1163", + "1250": "windows1250", + "1251": "windows1251", + "1252": "windows1252", + "1253": "windows1253", + "1254": "windows1254", + "1255": "windows1255", + "1256": "windows1256", + "1257": "windows1257", + "1258": "windows1258", + "28591": "iso88591", + "28592": "iso88592", + "28593": "iso88593", + "28594": "iso88594", + "28595": "iso88595", + "28596": "iso88596", + "28597": "iso88597", + "28598": "iso88598", + "28599": "iso88599", + "28600": "iso885910", + "28601": "iso885911", + "28603": "iso885913", + "28604": "iso885914", + "28605": "iso885915", + "28606": "iso885916", + "windows874": { + "type": "_sbcs", + "chars": "€����…�����������‘’“”•–—�������� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" + }, + "win874": "windows874", + "cp874": "windows874", + "windows1250": { + "type": "_sbcs", + "chars": "€�‚�„…†‡�‰Š‹ŚŤŽŹ�‘’“”•–—�™š›śťžź ˇ˘Ł¤Ą¦§¨©Ş«¬­®Ż°±˛ł´µ¶·¸ąş»Ľ˝ľżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙" + }, + "win1250": "windows1250", + "cp1250": "windows1250", + "windows1251": { + "type": "_sbcs", + "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊЌЋЏђ‘’“”•–—�™љ›њќћџ ЎўЈ¤Ґ¦§Ё©Є«¬­®Ї°±Ііґµ¶·ё№є»јЅѕїАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" + }, + "win1251": "windows1251", + "cp1251": "windows1251", + "windows1252": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ�Ž��‘’“”•–—˜™š›œ�žŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "win1252": "windows1252", + "cp1252": "windows1252", + "windows1253": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡�‰�‹�����‘’“”•–—�™�›���� ΅Ά£¤¥¦§¨©�«¬­®―°±²³΄µ¶·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�" + }, + "win1253": "windows1253", + "cp1253": "windows1253", + "windows1254": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ����‘’“”•–—˜™š›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖ×ØÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ" + }, + "win1254": "windows1254", + "cp1254": "windows1254", + "windows1255": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡ˆ‰�‹�����‘’“”•–—˜™�›���� ¡¢£₪¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾¿ְֱֲֳִֵֶַָֹֺֻּֽ־ֿ׀ׁׂ׃װױײ׳״�������אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�" + }, + "win1255": "windows1255", + "cp1255": "windows1255", + "windows1256": { + "type": "_sbcs", + "chars": "€پ‚ƒ„…†‡ˆ‰ٹ‹Œچژڈگ‘’“”•–—ک™ڑ›œ‌‍ں ،¢£¤¥¦§¨©ھ«¬­®¯°±²³´µ¶·¸¹؛»¼½¾؟ہءآأؤإئابةتثجحخدذرزسشصض×طظعغـفقكàلâمنهوçèéêëىيîïًٌٍَôُِ÷ّùْûü‎‏ے" + }, + "win1256": "windows1256", + "cp1256": "windows1256", + "windows1257": { + "type": "_sbcs", + "chars": "€�‚�„…†‡�‰�‹�¨ˇ¸�‘’“”•–—�™�›�¯˛� �¢£¤�¦§Ø©Ŗ«¬­®Æ°±²³´µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž˙" + }, + "win1257": "windows1257", + "cp1257": "windows1257", + "windows1258": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡ˆ‰�‹Œ����‘’“”•–—˜™�›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖ×ØÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" + }, + "win1258": "windows1258", + "cp1258": "windows1258", + "iso88591": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "cp28591": "iso88591", + "iso88592": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ą˘Ł¤ĽŚ§¨ŠŞŤŹ­ŽŻ°ą˛ł´ľśˇ¸šşťź˝žżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙" + }, + "cp28592": "iso88592", + "iso88593": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ħ˘£¤�Ĥ§¨İŞĞĴ­�Ż°ħ²³´µĥ·¸ışğĵ½�żÀÁÂ�ÄĊĈÇÈÉÊËÌÍÎÏ�ÑÒÓÔĠÖ×ĜÙÚÛÜŬŜßàáâ�äċĉçèéêëìíîï�ñòóôġö÷ĝùúûüŭŝ˙" + }, + "cp28593": "iso88593", + "iso88594": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄĸŖ¤ĨĻ§¨ŠĒĢŦ­Ž¯°ą˛ŗ´ĩļˇ¸šēģŧŊžŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎĪĐŅŌĶÔÕÖ×ØŲÚÛÜŨŪßāáâãäåæįčéęëėíîīđņōķôõö÷øųúûüũū˙" + }, + "cp28594": "iso88594", + "iso88595": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂЃЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђѓєѕіїјљњћќ§ўџ" + }, + "cp28595": "iso88595", + "iso88596": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ���¤�������،­�������������؛���؟�ءآأؤإئابةتثجحخدذرزسشصضطظعغ�����ـفقكلمنهوىيًٌٍَُِّْ�������������" + }, + "cp28596": "iso88596", + "iso88597": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ‘’£€₯¦§¨©ͺ«¬­�―°±²³΄΅Ά·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�" + }, + "cp28597": "iso88597", + "iso88598": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ �¢£¤¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾��������������������������������‗אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�" + }, + "cp28598": "iso88598", + "iso88599": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖ×ØÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ" + }, + "cp28599": "iso88599", + "iso885910": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄĒĢĪĨĶ§ĻĐŠŦŽ­ŪŊ°ąēģīĩķ·ļđšŧž―ūŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎÏÐŅŌÓÔÕÖŨØŲÚÛÜÝÞßāáâãäåæįčéęëėíîïðņōóôõöũøųúûüýþĸ" + }, + "cp28600": "iso885910", + "iso885911": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" + }, + "cp28601": "iso885911", + "iso885913": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ”¢£¤„¦§Ø©Ŗ«¬­®Æ°±²³“µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž’" + }, + "cp28603": "iso885913", + "iso885914": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ḃḃ£ĊċḊ§Ẁ©ẂḋỲ­®ŸḞḟĠġṀṁ¶ṖẁṗẃṠỳẄẅṡÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŴÑÒÓÔÕÖṪØÙÚÛÜÝŶßàáâãäåæçèéêëìíîïŵñòóôõöṫøùúûüýŷÿ" + }, + "cp28604": "iso885914", + "iso885915": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥Š§š©ª«¬­®¯°±²³Žµ¶·ž¹º»ŒœŸ¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "cp28605": "iso885915", + "iso885916": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄąŁ€„Š§š©Ș«Ź­źŻ°±ČłŽ”¶·žčș»ŒœŸżÀÁÂĂÄĆÆÇÈÉÊËÌÍÎÏĐŃÒÓÔŐÖŚŰÙÚÛÜĘȚßàáâăäćæçèéêëìíîïđńòóôőöśűùúûüęțÿ" + }, + "cp28606": "iso885916", + "cp437": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm437": "cp437", + "csibm437": "cp437", + "cp737": { + "type": "_sbcs", + "chars": "ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩαβγδεζηθικλμνξοπρσςτυφχψ░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀ωάέήϊίόύϋώΆΈΉΊΌΎΏ±≥≤ΪΫ÷≈°∙·√ⁿ²■ " + }, + "ibm737": "cp737", + "csibm737": "cp737", + "cp775": { + "type": "_sbcs", + "chars": "ĆüéāäģåćłēŖŗīŹÄÅÉæÆōöĢ¢ŚśÖÜø£ØפĀĪóŻżź”¦©®¬½¼Ł«»░▒▓│┤ĄČĘĖ╣║╗╝ĮŠ┐└┴┬├─┼ŲŪ╚╔╩╦╠═╬Žąčęėįšųūž┘┌█▄▌▐▀ÓßŌŃõÕµńĶķĻļņĒŅ’­±“¾¶§÷„°∙·¹³²■ " + }, + "ibm775": "cp775", + "csibm775": "cp775", + "cp850": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø׃áíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈıÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ " + }, + "ibm850": "cp850", + "csibm850": "cp850", + "cp852": { + "type": "_sbcs", + "chars": "ÇüéâäůćçłëŐőîŹÄĆÉĹĺôöĽľŚśÖÜŤťŁ×čáíóúĄąŽžĘ꬟Ⱥ«»░▒▓│┤ÁÂĚŞ╣║╗╝Żż┐└┴┬├─┼Ăă╚╔╩╦╠═╬¤đĐĎËďŇÍÎě┘┌█▄ŢŮ▀ÓßÔŃńňŠšŔÚŕŰýÝţ´­˝˛ˇ˘§÷¸°¨˙űŘř■ " + }, + "ibm852": "cp852", + "csibm852": "cp852", + "cp855": { + "type": "_sbcs", + "chars": "ђЂѓЃёЁєЄѕЅіІїЇјЈљЉњЊћЋќЌўЎџЏюЮъЪаАбБцЦдДеЕфФгГ«»░▒▓│┤хХиИ╣║╗╝йЙ┐└┴┬├─┼кК╚╔╩╦╠═╬¤лЛмМнНоОп┘┌█▄Пя▀ЯрРсСтТуУжЖвВьЬ№­ыЫзЗшШэЭщЩчЧ§■ " + }, + "ibm855": "cp855", + "csibm855": "cp855", + "cp856": { + "type": "_sbcs", + "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת�£�×����������®¬½¼�«»░▒▓│┤���©╣║╗╝¢¥┐└┴┬├─┼��╚╔╩╦╠═╬¤���������┘┌█▄¦�▀������µ�������¯´­±‗¾¶§÷¸°¨·¹³²■ " + }, + "ibm856": "cp856", + "csibm856": "cp856", + "cp857": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîıÄÅÉæÆôöòûùİÖÜø£ØŞşáíóúñÑĞ𿮬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ºªÊËÈ�ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµ�×ÚÛÙìÿ¯´­±�¾¶§÷¸°¨·¹³²■ " + }, + "ibm857": "cp857", + "csibm857": "cp857", + "cp858": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø׃áíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈ€ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ " + }, + "ibm858": "cp858", + "csibm858": "cp858", + "cp860": { + "type": "_sbcs", + "chars": "ÇüéâãàÁçêÊèÍÔìÃÂÉÀÈôõòÚùÌÕÜ¢£Ù₧ÓáíóúñѪº¿Ò¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm860": "cp860", + "csibm860": "cp860", + "cp861": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèÐðÞÄÅÉæÆôöþûÝýÖÜø£Ø₧ƒáíóúÁÍÓÚ¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm861": "cp861", + "csibm861": "cp861", + "cp862": { + "type": "_sbcs", + "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm862": "cp862", + "csibm862": "cp862", + "cp863": { + "type": "_sbcs", + "chars": "ÇüéâÂà¶çêëèïî‗À§ÉÈÊôËÏûù¤ÔÜ¢£ÙÛƒ¦´óú¨¸³¯Î⌐¬½¼¾«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm863": "cp863", + "csibm863": "cp863", + "cp864": { + "type": "_sbcs", + "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$٪&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~°·∙√▒─│┼┤┬├┴┐┌└┘β∞φ±½¼≈«»ﻷﻸ��ﻻﻼ� ­ﺂ£¤ﺄ��ﺎﺏﺕﺙ،ﺝﺡﺥ٠١٢٣٤٥٦٧٨٩ﻑ؛ﺱﺵﺹ؟¢ﺀﺁﺃﺅﻊﺋﺍﺑﺓﺗﺛﺟﺣﺧﺩﺫﺭﺯﺳﺷﺻﺿﻁﻅﻋﻏ¦¬÷×ﻉـﻓﻗﻛﻟﻣﻧﻫﻭﻯﻳﺽﻌﻎﻍﻡﹽّﻥﻩﻬﻰﻲﻐﻕﻵﻶﻝﻙﻱ■�" + }, + "ibm864": "cp864", + "csibm864": "cp864", + "cp865": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø₧ƒáíóúñѪº¿⌐¬½¼¡«¤░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm865": "cp865", + "csibm865": "cp865", + "cp866": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№¤■ " + }, + "ibm866": "cp866", + "csibm866": "cp866", + "cp869": { + "type": "_sbcs", + "chars": "������Ά�·¬¦‘’Έ―ΉΊΪΌ��ΎΫ©Ώ²³ά£έήίϊΐόύΑΒΓΔΕΖΗ½ΘΙ«»░▒▓│┤ΚΛΜΝ╣║╗╝ΞΟ┐└┴┬├─┼ΠΡ╚╔╩╦╠═╬ΣΤΥΦΧΨΩαβγ┘┌█▄δε▀ζηθικλμνξοπρσςτ΄­±υφχ§ψ΅°¨ωϋΰώ■ " + }, + "ibm869": "cp869", + "csibm869": "cp869", + "cp922": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®‾°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŠÑÒÓÔÕÖ×ØÙÚÛÜÝŽßàáâãäåæçèéêëìíîïšñòóôõö÷øùúûüýžÿ" + }, + "ibm922": "cp922", + "csibm922": "cp922", + "cp1046": { + "type": "_sbcs", + "chars": "ﺈ×÷ﹱˆ■│─┐┌└┘ﹹﹻﹽﹿﹷﺊﻰﻳﻲﻎﻏﻐﻶﻸﻺﻼ ¤ﺋﺑﺗﺛﺟﺣ،­ﺧﺳ٠١٢٣٤٥٦٧٨٩ﺷ؛ﺻﺿﻊ؟ﻋءآأؤإئابةتثجحخدذرزسشصضطﻇعغﻌﺂﺄﺎﻓـفقكلمنهوىيًٌٍَُِّْﻗﻛﻟﻵﻷﻹﻻﻣﻧﻬﻩ�" + }, + "ibm1046": "cp1046", + "csibm1046": "cp1046", + "cp1124": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂҐЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђґєѕіїјљњћќ§ўџ" + }, + "ibm1124": "cp1124", + "csibm1124": "cp1124", + "cp1125": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёҐґЄєІіЇї·√№¤■ " + }, + "ibm1125": "cp1125", + "csibm1125": "cp1125", + "cp1129": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖ×ØÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" + }, + "ibm1129": "cp1129", + "csibm1129": "cp1129", + "cp1133": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ກຂຄງຈສຊຍດຕຖທນບປຜຝພຟມຢຣລວຫອຮ���ຯະາຳິີຶືຸູຼັົຽ���ເແໂໃໄ່້໊໋໌ໍໆ�ໜໝ₭����������������໐໑໒໓໔໕໖໗໘໙��¢¬¦�" + }, + "ibm1133": "cp1133", + "csibm1133": "cp1133", + "cp1161": { + "type": "_sbcs", + "chars": "��������������������������������่กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู้๊๋€฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛¢¬¦ " + }, + "ibm1161": "cp1161", + "csibm1161": "cp1161", + "cp1162": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" + }, + "ibm1162": "cp1162", + "csibm1162": "cp1162", + "cp1163": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖ×ØÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" + }, + "ibm1163": "cp1163", + "csibm1163": "cp1163", + "maccroatian": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø¿¡¬√ƒ≈Ć«Č… ÀÃÕŒœĐ—“”‘’÷◊�©⁄¤‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ" + }, + "maccyrillic": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°¢£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµ∂ЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤" + }, + "macgreek": { + "type": "_sbcs", + "chars": "Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦­ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩάΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ�" + }, + "maciceland": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüÝ°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" + }, + "macroman": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" + }, + "macromania": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂŞ∞±≤≥¥µ∂∑∏π∫ªºΩăş¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›Ţţ‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" + }, + "macthai": { + "type": "_sbcs", + "chars": "«»…“”�•‘’� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู​–—฿เแโใไๅๆ็่้๊๋์ํ™๏๐๑๒๓๔๕๖๗๘๙®©����" + }, + "macturkish": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙ�ˆ˜¯˘˙˚¸˝˛ˇ" + }, + "macukraine": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤" + }, + "koi8r": { + "type": "_sbcs", + "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ё╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡Ё╢╣╤╥╦╧╨╩╪╫╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" + }, + "koi8u": { + "type": "_sbcs", + "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґ╝╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪Ґ╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" + }, + "koi8ru": { + "type": "_sbcs", + "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґў╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪ҐЎ©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" + }, + "koi8t": { + "type": "_sbcs", + "chars": "қғ‚Ғ„…†‡�‰ҳ‹ҲҷҶ�Қ‘’“”•–—�™�›�����ӯӮё¤ӣ¦§���«¬­®�°±²Ё�Ӣ¶·�№�»���©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" + }, + "armscii8": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ �և։)(»«—.՝,-֊…՜՛՞ԱաԲբԳգԴդԵեԶզԷէԸըԹթԺժԻիԼլԽխԾծԿկՀհՁձՂղՃճՄմՅյՆնՇշՈոՉչՊպՋջՌռՍսՎվՏտՐրՑցՒւՓփՔքՕօՖֆ՚�" + }, + "rk1048": { + "type": "_sbcs", + "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊҚҺЏђ‘’“”•–—�™љ›њқһџ ҰұӘ¤Ө¦§Ё©Ғ«¬­®Ү°±Ііөµ¶·ё№ғ»әҢңүАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" + }, + "tcvn": { + "type": "_sbcs", + "chars": "\u0000ÚỤ\u0003ỪỬỮ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010ỨỰỲỶỸÝỴ\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ÀẢÃÁẠẶẬÈẺẼÉẸỆÌỈĨÍỊÒỎÕÓỌỘỜỞỠỚỢÙỦŨ ĂÂÊÔƠƯĐăâêôơưđẶ̀̀̉̃́àảãáạẲằẳẵắẴẮẦẨẪẤỀặầẩẫấậèỂẻẽéẹềểễếệìỉỄẾỒĩíịòỔỏõóọồổỗốộờởỡớợùỖủũúụừửữứựỳỷỹýỵỐ" + }, + "georgianacademy": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზთიკლმნოპჟრსტუფქღყშჩცძწჭხჯჰჱჲჳჴჵჶçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "georgianps": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზჱთიკლმნჲოპჟრსტჳუფქღყშჩცძწჭხჴჯჰჵæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "pt154": { + "type": "_sbcs", + "chars": "ҖҒӮғ„…ҶҮҲүҠӢҢҚҺҸҗ‘’“”•–—ҳҷҡӣңқһҹ ЎўЈӨҘҰ§Ё©Ә«¬ӯ®Ҝ°ұІіҙө¶·ё№ә»јҪҫҝАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" + }, + "viscii": { + "type": "_sbcs", + "chars": "\u0000\u0001Ẳ\u0003\u0004ẴẪ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013Ỷ\u0015\u0016\u0017\u0018Ỹ\u001a\u001b\u001c\u001dỴ\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ẠẮẰẶẤẦẨẬẼẸẾỀỂỄỆỐỒỔỖỘỢỚỜỞỊỎỌỈỦŨỤỲÕắằặấầẩậẽẹếềểễệốồổỗỠƠộờởịỰỨỪỬơớƯÀÁÂÃẢĂẳẵÈÉÊẺÌÍĨỳĐứÒÓÔạỷừửÙÚỹỵÝỡưàáâãảăữẫèéêẻìíĩỉđựòóôõỏọụùúũủýợỮ" + }, + "iso646cn": { + "type": "_sbcs", + "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#¥%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������" + }, + "iso646jp": { + "type": "_sbcs", + "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[¥]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������" + }, + "hproman8": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ÀÂÈÊËÎÏ´ˋˆ¨˜ÙÛ₤¯Ýý°ÇçÑñ¡¿¤£¥§ƒ¢âêôûáéóúàèòùäëöüÅîØÆåíøæÄìÖÜÉïßÔÁÃãÐðÍÌÓÒÕõŠšÚŸÿÞþ·µ¶¾—¼½ªº«■»±�" + }, + "macintosh": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" + }, + "ascii": { + "type": "_sbcs", + "chars": "��������������������������������������������������������������������������������������������������������������������������������" + }, + "tis620": { + "type": "_sbcs", + "chars": "���������������������������������กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" + } +} \ No newline at end of file diff --git a/backend/node_modules/iconv-lite/encodings/sbcs-data.js b/backend/node_modules/iconv-lite/encodings/sbcs-data.js new file mode 100644 index 0000000000000000000000000000000000000000..fdb81a39ac985322057f18f455f9f1160e7ac17f --- /dev/null +++ b/backend/node_modules/iconv-lite/encodings/sbcs-data.js @@ -0,0 +1,174 @@ +"use strict"; + +// Manually added data to be used by sbcs codec in addition to generated one. + +module.exports = { + // Not supported by iconv, not sure why. + "10029": "maccenteuro", + "maccenteuro": { + "type": "_sbcs", + "chars": "ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ" + }, + + "808": "cp808", + "ibm808": "cp808", + "cp808": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№€■ " + }, + + "mik": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя└┴┬├─┼╣║╚╔╩╦╠═╬┐░▒▓│┤№§╗╝┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + + // Aliases of generated encodings. + "ascii8bit": "ascii", + "usascii": "ascii", + "ansix34": "ascii", + "ansix341968": "ascii", + "ansix341986": "ascii", + "csascii": "ascii", + "cp367": "ascii", + "ibm367": "ascii", + "isoir6": "ascii", + "iso646us": "ascii", + "iso646irv": "ascii", + "us": "ascii", + + "latin1": "iso88591", + "latin2": "iso88592", + "latin3": "iso88593", + "latin4": "iso88594", + "latin5": "iso88599", + "latin6": "iso885910", + "latin7": "iso885913", + "latin8": "iso885914", + "latin9": "iso885915", + "latin10": "iso885916", + + "csisolatin1": "iso88591", + "csisolatin2": "iso88592", + "csisolatin3": "iso88593", + "csisolatin4": "iso88594", + "csisolatincyrillic": "iso88595", + "csisolatinarabic": "iso88596", + "csisolatingreek" : "iso88597", + "csisolatinhebrew": "iso88598", + "csisolatin5": "iso88599", + "csisolatin6": "iso885910", + + "l1": "iso88591", + "l2": "iso88592", + "l3": "iso88593", + "l4": "iso88594", + "l5": "iso88599", + "l6": "iso885910", + "l7": "iso885913", + "l8": "iso885914", + "l9": "iso885915", + "l10": "iso885916", + + "isoir14": "iso646jp", + "isoir57": "iso646cn", + "isoir100": "iso88591", + "isoir101": "iso88592", + "isoir109": "iso88593", + "isoir110": "iso88594", + "isoir144": "iso88595", + "isoir127": "iso88596", + "isoir126": "iso88597", + "isoir138": "iso88598", + "isoir148": "iso88599", + "isoir157": "iso885910", + "isoir166": "tis620", + "isoir179": "iso885913", + "isoir199": "iso885914", + "isoir203": "iso885915", + "isoir226": "iso885916", + + "cp819": "iso88591", + "ibm819": "iso88591", + + "cyrillic": "iso88595", + + "arabic": "iso88596", + "arabic8": "iso88596", + "ecma114": "iso88596", + "asmo708": "iso88596", + + "greek" : "iso88597", + "greek8" : "iso88597", + "ecma118" : "iso88597", + "elot928" : "iso88597", + + "hebrew": "iso88598", + "hebrew8": "iso88598", + + "turkish": "iso88599", + "turkish8": "iso88599", + + "thai": "iso885911", + "thai8": "iso885911", + + "celtic": "iso885914", + "celtic8": "iso885914", + "isoceltic": "iso885914", + + "tis6200": "tis620", + "tis62025291": "tis620", + "tis62025330": "tis620", + + "10000": "macroman", + "10006": "macgreek", + "10007": "maccyrillic", + "10079": "maciceland", + "10081": "macturkish", + + "cspc8codepage437": "cp437", + "cspc775baltic": "cp775", + "cspc850multilingual": "cp850", + "cspcp852": "cp852", + "cspc862latinhebrew": "cp862", + "cpgr": "cp869", + + "msee": "cp1250", + "mscyrl": "cp1251", + "msansi": "cp1252", + "msgreek": "cp1253", + "msturk": "cp1254", + "mshebr": "cp1255", + "msarab": "cp1256", + "winbaltrim": "cp1257", + + "cp20866": "koi8r", + "20866": "koi8r", + "ibm878": "koi8r", + "cskoi8r": "koi8r", + + "cp21866": "koi8u", + "21866": "koi8u", + "ibm1168": "koi8u", + + "strk10482002": "rk1048", + + "tcvn5712": "tcvn", + "tcvn57121": "tcvn", + + "gb198880": "iso646cn", + "cn": "iso646cn", + + "csiso14jisc6220ro": "iso646jp", + "jisc62201969ro": "iso646jp", + "jp": "iso646jp", + + "cshproman8": "hproman8", + "r8": "hproman8", + "roman8": "hproman8", + "xroman8": "hproman8", + "ibm1051": "hproman8", + + "mac": "macintosh", + "csmacintosh": "macintosh", +}; + diff --git a/backend/node_modules/iconv-lite/encodings/tables/big5-added.json b/backend/node_modules/iconv-lite/encodings/tables/big5-added.json new file mode 100644 index 0000000000000000000000000000000000000000..3c3d3c2f7b14c6a570e58184f68ef0894a5f812d --- /dev/null +++ b/backend/node_modules/iconv-lite/encodings/tables/big5-added.json @@ -0,0 +1,122 @@ +[ +["8740","䏰䰲䘃䖦䕸𧉧䵷䖳𧲱䳢𧳅㮕䜶䝄䱇䱀𤊿𣘗𧍒𦺋𧃒䱗𪍑䝏䗚䲅𧱬䴇䪤䚡𦬣爥𥩔𡩣𣸆𣽡晍囻"], +["8767","綕夝𨮹㷴霴𧯯寛𡵞媤㘥𩺰嫑宷峼杮薓𩥅瑡璝㡵𡵓𣚞𦀡㻬"], +["87a1","𥣞㫵竼龗𤅡𨤍𣇪𠪊𣉞䌊蒄龖鐯䤰蘓墖靊鈘秐稲晠権袝瑌篅枂稬剏遆㓦珄𥶹瓆鿇垳䤯呌䄱𣚎堘穲𧭥讏䚮𦺈䆁𥶙箮𢒼鿈𢓁𢓉𢓌鿉蔄𣖻䂴鿊䓡𪷿拁灮鿋"], +["8840","㇀",4,"𠄌㇅𠃑𠃍㇆㇇𠃋𡿨㇈𠃊㇉㇊㇋㇌𠄎㇍㇎ĀÁǍÀĒÉĚÈŌÓǑÒ࿿Ê̄Ế࿿Ê̌ỀÊāáǎàɑēéěèīíǐìōóǒòūúǔùǖǘǚ"], +["88a1","ǜü࿿ê̄ế࿿ê̌ềêɡ⏚⏛"], +["8940","𪎩𡅅"], +["8943","攊"], +["8946","丽滝鵎釟"], +["894c","𧜵撑会伨侨兖兴农凤务动医华发变团声处备夲头学实実岚庆总斉柾栄桥济炼电纤纬纺织经统缆缷艺苏药视设询车轧轮"], +["89a1","琑糼緍楆竉刧"], +["89ab","醌碸酞肼"], +["89b0","贋胶𠧧"], +["89b5","肟黇䳍鷉鸌䰾𩷶𧀎鸊𪄳㗁"], +["89c1","溚舾甙"], +["89c5","䤑马骏龙禇𨑬𡷊𠗐𢫦两亁亀亇亿仫伷㑌侽㹈倃傈㑽㒓㒥円夅凛凼刅争剹劐匧㗇厩㕑厰㕓参吣㕭㕲㚁咓咣咴咹哐哯唘唣唨㖘唿㖥㖿嗗㗅"], +["8a40","𧶄唥"], +["8a43","𠱂𠴕𥄫喐𢳆㧬𠍁蹆𤶸𩓥䁓𨂾睺𢰸㨴䟕𨅝𦧲𤷪擝𠵼𠾴𠳕𡃴撍蹾𠺖𠰋𠽤𢲩𨉖𤓓"], +["8a64","𠵆𩩍𨃩䟴𤺧𢳂骲㩧𩗴㿭㔆𥋇𩟔𧣈𢵄鵮頕"], +["8a76","䏙𦂥撴哣𢵌𢯊𡁷㧻𡁯"], +["8aa1","𦛚𦜖𧦠擪𥁒𠱃蹨𢆡𨭌𠜱"], +["8aac","䠋𠆩㿺塳𢶍"], +["8ab2","𤗈𠓼𦂗𠽌𠶖啹䂻䎺"], +["8abb","䪴𢩦𡂝膪飵𠶜捹㧾𢝵跀嚡摼㹃"], +["8ac9","𪘁𠸉𢫏𢳉"], +["8ace","𡃈𣧂㦒㨆𨊛㕸𥹉𢃇噒𠼱𢲲𩜠㒼氽𤸻"], +["8adf","𧕴𢺋𢈈𪙛𨳍𠹺𠰴𦠜羓𡃏𢠃𢤹㗻𥇣𠺌𠾍𠺪㾓𠼰𠵇𡅏𠹌"], +["8af6","𠺫𠮩𠵈𡃀𡄽㿹𢚖搲𠾭"], +["8b40","𣏴𧘹𢯎𠵾𠵿𢱑𢱕㨘𠺘𡃇𠼮𪘲𦭐𨳒𨶙𨳊閪哌苄喹"], +["8b55","𩻃鰦骶𧝞𢷮煀腭胬尜𦕲脴㞗卟𨂽醶𠻺𠸏𠹷𠻻㗝𤷫㘉𠳖嚯𢞵𡃉𠸐𠹸𡁸𡅈𨈇𡑕𠹹𤹐𢶤婔𡀝𡀞𡃵𡃶垜𠸑"], +["8ba1","𧚔𨋍𠾵𠹻𥅾㜃𠾶𡆀𥋘𪊽𤧚𡠺𤅷𨉼墙剨㘚𥜽箲孨䠀䬬鼧䧧鰟鮍𥭴𣄽嗻㗲嚉丨夂𡯁屮靑𠂆乛亻㔾尣彑忄㣺扌攵歺氵氺灬爫丬犭𤣩罒礻糹罓𦉪㓁"], +["8bde","𦍋耂肀𦘒𦥑卝衤见𧢲讠贝钅镸长门𨸏韦页风飞饣𩠐鱼鸟黄歯龜丷𠂇阝户钢"], +["8c40","倻淾𩱳龦㷉袏𤅎灷峵䬠𥇍㕙𥴰愢𨨲辧釶熑朙玺𣊁𪄇㲋𡦀䬐磤琂冮𨜏䀉橣𪊺䈣蘏𠩯稪𩥇𨫪靕灍匤𢁾鏴盙𨧣龧矝亣俰傼丯众龨吴綋墒壐𡶶庒庙忂𢜒斋"], +["8ca1","𣏹椙橃𣱣泿"], +["8ca7","爀𤔅玌㻛𤨓嬕璹讃𥲤𥚕窓篬糃繬苸薗龩袐龪躹龫迏蕟駠鈡龬𨶹𡐿䁱䊢娚"], +["8cc9","顨杫䉶圽"], +["8cce","藖𤥻芿𧄍䲁𦵴嵻𦬕𦾾龭龮宖龯曧繛湗秊㶈䓃𣉖𢞖䎚䔶"], +["8ce6","峕𣬚諹屸㴒𣕑嵸龲煗䕘𤃬𡸣䱷㥸㑊𠆤𦱁諌侴𠈹妿腬顖𩣺弻"], +["8d40","𠮟"], +["8d42","𢇁𨥭䄂䚻𩁹㼇龳𪆵䃸㟖䛷𦱆䅼𨚲𧏿䕭㣔𥒚䕡䔛䶉䱻䵶䗪㿈𤬏㙡䓞䒽䇭崾嵈嵖㷼㠏嶤嶹㠠㠸幂庽弥徃㤈㤔㤿㥍惗愽峥㦉憷憹懏㦸戬抐拥挘㧸嚱"], +["8da1","㨃揢揻搇摚㩋擀崕嘡龟㪗斆㪽旿晓㫲暒㬢朖㭂枤栀㭘桊梄㭲㭱㭻椉楃牜楤榟榅㮼槖㯝橥橴橱檂㯬檙㯲檫檵櫔櫶殁毁毪汵沪㳋洂洆洦涁㳯涤涱渕渘温溆𨧀溻滢滚齿滨滩漤漴㵆𣽁澁澾㵪㵵熷岙㶊瀬㶑灐灔灯灿炉𠌥䏁㗱𠻘"], +["8e40","𣻗垾𦻓焾𥟠㙎榢𨯩孴穉𥣡𩓙穥穽𥦬窻窰竂竃燑𦒍䇊竚竝竪䇯咲𥰁笋筕笩𥌎𥳾箢筯莜𥮴𦱿篐萡箒箸𥴠㶭𥱥蒒篺簆簵𥳁籄粃𤢂粦晽𤕸糉糇糦籴糳糵糎"], +["8ea1","繧䔝𦹄絝𦻖璍綉綫焵綳緒𤁗𦀩緤㴓緵𡟹緥𨍭縝𦄡𦅚繮纒䌫鑬縧罀罁罇礶𦋐駡羗𦍑羣𡙡𠁨䕜𣝦䔃𨌺翺𦒉者耈耝耨耯𪂇𦳃耻耼聡𢜔䦉𦘦𣷣𦛨朥肧𨩈脇脚墰𢛶汿𦒘𤾸擧𡒊舘𡡞橓𤩥𤪕䑺舩𠬍𦩒𣵾俹𡓽蓢荢𦬊𤦧𣔰𡝳𣷸芪椛芳䇛"], +["8f40","蕋苐茚𠸖𡞴㛁𣅽𣕚艻苢茘𣺋𦶣𦬅𦮗𣗎㶿茝嗬莅䔋𦶥莬菁菓㑾𦻔橗蕚㒖𦹂𢻯葘𥯤葱㷓䓤檧葊𣲵祘蒨𦮖𦹷𦹃蓞萏莑䒠蒓蓤𥲑䉀𥳀䕃蔴嫲𦺙䔧蕳䔖枿蘖"], +["8fa1","𨘥𨘻藁𧂈蘂𡖂𧃍䕫䕪蘨㙈𡢢号𧎚虾蝱𪃸蟮𢰧螱蟚蠏噡虬桖䘏衅衆𧗠𣶹𧗤衞袜䙛袴袵揁装睷𧜏覇覊覦覩覧覼𨨥觧𧤤𧪽誜瞓釾誐𧩙竩𧬺𣾏䜓𧬸煼謌謟𥐰𥕥謿譌譍誩𤩺讐讛誯𡛟䘕衏貛𧵔𧶏貫㜥𧵓賖𧶘𧶽贒贃𡤐賛灜贑𤳉㻐起"], +["9040","趩𨀂𡀔𤦊㭼𨆼𧄌竧躭躶軃鋔輙輭𨍥𨐒辥錃𪊟𠩐辳䤪𨧞𨔽𣶻廸𣉢迹𪀔𨚼𨔁𢌥㦀𦻗逷𨔼𧪾遡𨕬𨘋邨𨜓郄𨛦邮都酧㫰醩釄粬𨤳𡺉鈎沟鉁鉢𥖹銹𨫆𣲛𨬌𥗛"], +["90a1","𠴱錬鍫𨫡𨯫炏嫃𨫢𨫥䥥鉄𨯬𨰹𨯿鍳鑛躼閅閦鐦閠濶䊹𢙺𨛘𡉼𣸮䧟氜陻隖䅬隣𦻕懚隶磵𨫠隽双䦡𦲸𠉴𦐐𩂯𩃥𤫑𡤕𣌊霱虂霶䨏䔽䖅𤫩灵孁霛靜𩇕靗孊𩇫靟鐥僐𣂷𣂼鞉鞟鞱鞾韀韒韠𥑬韮琜𩐳響韵𩐝𧥺䫑頴頳顋顦㬎𧅵㵑𠘰𤅜"], +["9140","𥜆飊颷飈飇䫿𦴧𡛓喰飡飦飬鍸餹𤨩䭲𩡗𩤅駵騌騻騐驘𥜥㛄𩂱𩯕髠髢𩬅髴䰎鬔鬭𨘀倴鬴𦦨㣃𣁽魐魀𩴾婅𡡣鮎𤉋鰂鯿鰌𩹨鷔𩾷𪆒𪆫𪃡𪄣𪇟鵾鶃𪄴鸎梈"], +["91a1","鷄𢅛𪆓𪈠𡤻𪈳鴹𪂹𪊴麐麕麞麢䴴麪麯𤍤黁㭠㧥㴝伲㞾𨰫鼂鼈䮖鐤𦶢鼗鼖鼹嚟嚊齅馸𩂋韲葿齢齩竜龎爖䮾𤥵𤦻煷𤧸𤍈𤩑玞𨯚𡣺禟𨥾𨸶鍩鏳𨩄鋬鎁鏋𨥬𤒹爗㻫睲穃烐𤑳𤏸煾𡟯炣𡢾𣖙㻇𡢅𥐯𡟸㜢𡛻𡠹㛡𡝴𡣑𥽋㜣𡛀坛𤨥𡏾𡊨"], +["9240","𡏆𡒶蔃𣚦蔃葕𤦔𧅥𣸱𥕜𣻻𧁒䓴𣛮𩦝𦼦柹㜳㰕㷧塬𡤢栐䁗𣜿𤃡𤂋𤄏𦰡哋嚞𦚱嚒𠿟𠮨𠸍鏆𨬓鎜仸儫㠙𤐶亼𠑥𠍿佋侊𥙑婨𠆫𠏋㦙𠌊𠐔㐵伩𠋀𨺳𠉵諚𠈌亘"], +["92a1","働儍侢伃𤨎𣺊佂倮偬傁俌俥偘僼兙兛兝兞湶𣖕𣸹𣺿浲𡢄𣺉冨凃𠗠䓝𠒣𠒒𠒑赺𨪜𠜎剙劤𠡳勡鍮䙺熌𤎌𠰠𤦬𡃤槑𠸝瑹㻞璙琔瑖玘䮎𤪼𤂍叐㖄爏𤃉喴𠍅响𠯆圝鉝雴鍦埝垍坿㘾壋媙𨩆𡛺𡝯𡜐娬妸銏婾嫏娒𥥆𡧳𡡡𤊕㛵洅瑃娡𥺃"], +["9340","媁𨯗𠐓鏠璌𡌃焅䥲鐈𨧻鎽㞠尞岞幞幈𡦖𡥼𣫮廍孏𡤃𡤄㜁𡢠㛝𡛾㛓脪𨩇𡶺𣑲𨦨弌弎𡤧𡞫婫𡜻孄蘔𧗽衠恾𢡠𢘫忛㺸𢖯𢖾𩂈𦽳懀𠀾𠁆𢘛憙憘恵𢲛𢴇𤛔𩅍"], +["93a1","摱𤙥𢭪㨩𢬢𣑐𩣪𢹸挷𪑛撶挱揑𤧣𢵧护𢲡搻敫楲㯴𣂎𣊭𤦉𣊫唍𣋠𡣙𩐿曎𣊉𣆳㫠䆐𥖄𨬢𥖏𡛼𥕛𥐥磮𣄃𡠪𣈴㑤𣈏𣆂𤋉暎𦴤晫䮓昰𧡰𡷫晣𣋒𣋡昞𥡲㣑𣠺𣞼㮙𣞢𣏾瓐㮖枏𤘪梶栞㯄檾㡣𣟕𤒇樳橒櫉欅𡤒攑梘橌㯗橺歗𣿀𣲚鎠鋲𨯪𨫋"], +["9440","銉𨀞𨧜鑧涥漋𤧬浧𣽿㶏渄𤀼娽渊塇洤硂焻𤌚𤉶烱牐犇犔𤞏𤜥兹𤪤𠗫瑺𣻸𣙟𤩊𤤗𥿡㼆㺱𤫟𨰣𣼵悧㻳瓌琼鎇琷䒟𦷪䕑疃㽣𤳙𤴆㽘畕癳𪗆㬙瑨𨫌𤦫𤦎㫻"], +["94a1","㷍𤩎㻿𤧅𤣳釺圲鍂𨫣𡡤僟𥈡𥇧睸𣈲眎眏睻𤚗𣞁㩞𤣰琸璛㺿𤪺𤫇䃈𤪖𦆮錇𥖁砞碍碈磒珐祙𧝁𥛣䄎禛蒖禥樭𣻺稺秴䅮𡛦䄲鈵秱𠵌𤦌𠊙𣶺𡝮㖗啫㕰㚪𠇔𠰍竢婙𢛵𥪯𥪜娍𠉛磰娪𥯆竾䇹籝籭䈑𥮳𥺼𥺦糍𤧹𡞰粎籼粮檲緜縇緓罎𦉡"], +["9540","𦅜𧭈綗𥺂䉪𦭵𠤖柖𠁎𣗏埄𦐒𦏸𤥢翝笧𠠬𥫩𥵃笌𥸎駦虅驣樜𣐿㧢𤧷𦖭騟𦖠蒀𧄧𦳑䓪脷䐂胆脉腂𦞴飃𦩂艢艥𦩑葓𦶧蘐𧈛媆䅿𡡀嬫𡢡嫤𡣘蚠蜨𣶏蠭𧐢娂"], +["95a1","衮佅袇袿裦襥襍𥚃襔𧞅𧞄𨯵𨯙𨮜𨧹㺭蒣䛵䛏㟲訽訜𩑈彍鈫𤊄旔焩烄𡡅鵭貟賩𧷜妚矃姰䍮㛔踪躧𤰉輰轊䋴汘澻𢌡䢛潹溋𡟚鯩㚵𤤯邻邗啱䤆醻鐄𨩋䁢𨫼鐧𨰝𨰻蓥訫閙閧閗閖𨴴瑅㻂𤣿𤩂𤏪㻧𣈥随𨻧𨹦𨹥㻌𤧭𤩸𣿮琒瑫㻼靁𩂰"], +["9640","桇䨝𩂓𥟟靝鍨𨦉𨰦𨬯𦎾銺嬑譩䤼珹𤈛鞛靱餸𠼦巁𨯅𤪲頟𩓚鋶𩗗釥䓀𨭐𤩧𨭤飜𨩅㼀鈪䤥萔餻饍𧬆㷽馛䭯馪驜𨭥𥣈檏騡嫾騯𩣱䮐𩥈馼䮽䮗鍽塲𡌂堢𤦸"], +["96a1","𡓨硄𢜟𣶸棅㵽鑘㤧慐𢞁𢥫愇鱏鱓鱻鰵鰐魿鯏𩸭鮟𪇵𪃾鴡䲮𤄄鸘䲰鴌𪆴𪃭𪃳𩤯鶥蒽𦸒𦿟𦮂藼䔳𦶤𦺄𦷰萠藮𦸀𣟗𦁤秢𣖜𣙀䤭𤧞㵢鏛銾鍈𠊿碹鉷鑍俤㑀遤𥕝砽硔碶硋𡝗𣇉𤥁㚚佲濚濙瀞瀞吔𤆵垻壳垊鴖埗焴㒯𤆬燫𦱀𤾗嬨𡞵𨩉"], +["9740","愌嫎娋䊼𤒈㜬䭻𨧼鎻鎸𡣖𠼝葲𦳀𡐓𤋺𢰦𤏁妔𣶷𦝁綨𦅛𦂤𤦹𤦋𨧺鋥珢㻩璴𨭣𡢟㻡𤪳櫘珳珻㻖𤨾𤪔𡟙𤩦𠎧𡐤𤧥瑈𤤖炥𤥶銄珦鍟𠓾錱𨫎𨨖鎆𨯧𥗕䤵𨪂煫"], +["97a1","𤥃𠳿嚤𠘚𠯫𠲸唂秄𡟺緾𡛂𤩐𡡒䔮鐁㜊𨫀𤦭妰𡢿𡢃𧒄媡㛢𣵛㚰鉟婹𨪁𡡢鍴㳍𠪴䪖㦊僴㵩㵌𡎜煵䋻𨈘渏𩃤䓫浗𧹏灧沯㳖𣿭𣸭渂漌㵯𠏵畑㚼㓈䚀㻚䡱姄鉮䤾轁𨰜𦯀堒埈㛖𡑒烾𤍢𤩱𢿣𡊰𢎽梹楧𡎘𣓥𧯴𣛟𨪃𣟖𣏺𤲟樚𣚭𦲷萾䓟䓎"], +["9840","𦴦𦵑𦲂𦿞漗𧄉茽𡜺菭𦲀𧁓𡟛妉媂𡞳婡婱𡤅𤇼㜭姯𡜼㛇熎鎐暚𤊥婮娫𤊓樫𣻹𧜶𤑛𤋊焝𤉙𨧡侰𦴨峂𤓎𧹍𤎽樌𤉖𡌄炦焳𤏩㶥泟勇𤩏繥姫崯㷳彜𤩝𡟟綤萦"], +["98a1","咅𣫺𣌀𠈔坾𠣕𠘙㿥𡾞𪊶瀃𩅛嵰玏糓𨩙𩐠俈翧狍猐𧫴猸猹𥛶獁獈㺩𧬘遬燵𤣲珡臶㻊県㻑沢国琙琞琟㻢㻰㻴㻺瓓㼎㽓畂畭畲疍㽼痈痜㿀癍㿗癴㿜発𤽜熈嘣覀塩䀝睃䀹条䁅㗛瞘䁪䁯属瞾矋売砘点砜䂨砹硇硑硦葈𥔵礳栃礲䄃"], +["9940","䄉禑禙辻稆込䅧窑䆲窼艹䇄竏竛䇏両筢筬筻簒簛䉠䉺类粜䊌粸䊔糭输烀𠳏総緔緐緽羮羴犟䎗耠耥笹耮耱联㷌垴炠肷胩䏭脌猪脎脒畠脔䐁㬹腖腙腚"], +["99a1","䐓堺腼膄䐥膓䐭膥埯臁臤艔䒏芦艶苊苘苿䒰荗险榊萅烵葤惣蒈䔄蒾蓡蓸蔐蔸蕒䔻蕯蕰藠䕷虲蚒蚲蛯际螋䘆䘗袮裿褤襇覑𧥧訩訸誔誴豑賔賲贜䞘塟跃䟭仮踺嗘坔蹱嗵躰䠷軎転軤軭軲辷迁迊迌逳駄䢭飠鈓䤞鈨鉘鉫銱銮銿"], +["9a40","鋣鋫鋳鋴鋽鍃鎄鎭䥅䥑麿鐗匁鐝鐭鐾䥪鑔鑹锭関䦧间阳䧥枠䨤靀䨵鞲韂噔䫤惨颹䬙飱塄餎餙冴餜餷饂饝饢䭰駅䮝騼鬏窃魩鮁鯝鯱鯴䱭鰠㝯𡯂鵉鰺"], +["9aa1","黾噐鶓鶽鷀鷼银辶鹻麬麱麽黆铜黢黱黸竈齄𠂔𠊷𠎠椚铃妬𠓗塀铁㞹𠗕𠘕𠙶𡚺块煳𠫂𠫍𠮿呪吆𠯋咞𠯻𠰻𠱓𠱥𠱼惧𠲍噺𠲵𠳝𠳭𠵯𠶲𠷈楕鰯螥𠸄𠸎𠻗𠾐𠼭𠹳尠𠾼帋𡁜𡁏𡁶朞𡁻𡂈𡂖㙇𡂿𡃓𡄯𡄻卤蒭𡋣𡍵𡌶讁𡕷𡘙𡟃𡟇乸炻𡠭𡥪"], +["9b40","𡨭𡩅𡰪𡱰𡲬𡻈拃𡻕𡼕熘桕𢁅槩㛈𢉼𢏗𢏺𢜪𢡱𢥏苽𢥧𢦓𢫕覥𢫨辠𢬎鞸𢬿顇骽𢱌"], +["9b62","𢲈𢲷𥯨𢴈𢴒𢶷𢶕𢹂𢽴𢿌𣀳𣁦𣌟𣏞徱晈暿𧩹𣕧𣗳爁𤦺矗𣘚𣜖纇𠍆墵朎"], +["9ba1","椘𣪧𧙗𥿢𣸑𣺹𧗾𢂚䣐䪸𤄙𨪚𤋮𤌍𤀻𤌴𤎖𤩅𠗊凒𠘑妟𡺨㮾𣳿𤐄𤓖垈𤙴㦛𤜯𨗨𩧉㝢𢇃譞𨭎駖𤠒𤣻𤨕爉𤫀𠱸奥𤺥𤾆𠝹軚𥀬劏圿煱𥊙𥐙𣽊𤪧喼𥑆𥑮𦭒釔㑳𥔿𧘲𥕞䜘𥕢𥕦𥟇𤤿𥡝偦㓻𣏌惞𥤃䝼𨥈𥪮𥮉𥰆𡶐垡煑澶𦄂𧰒遖𦆲𤾚譢𦐂𦑊"], +["9c40","嵛𦯷輶𦒄𡤜諪𤧶𦒈𣿯𦔒䯀𦖿𦚵𢜛鑥𥟡憕娧晉侻嚹𤔡𦛼乪𤤴陖涏𦲽㘘襷𦞙𦡮𦐑𦡞營𦣇筂𩃀𠨑𦤦鄄𦤹穅鷰𦧺騦𦨭㙟𦑩𠀡禃𦨴𦭛崬𣔙菏𦮝䛐𦲤画补𦶮墶"], +["9ca1","㜜𢖍𧁋𧇍㱔𧊀𧊅銁𢅺𧊋錰𧋦𤧐氹钟𧑐𠻸蠧裵𢤦𨑳𡞱溸𤨪𡠠㦤㚹尐秣䔿暶𩲭𩢤襃𧟌𧡘囖䃟𡘊㦡𣜯𨃨𡏅熭荦𧧝𩆨婧䲷𧂯𨦫𧧽𧨊𧬋𧵦𤅺筃祾𨀉澵𪋟樃𨌘厢𦸇鎿栶靝𨅯𨀣𦦵𡏭𣈯𨁈嶅𨰰𨂃圕頣𨥉嶫𤦈斾槕叒𤪥𣾁㰑朶𨂐𨃴𨄮𡾡𨅏"], +["9d40","𨆉𨆯𨈚𨌆𨌯𨎊㗊𨑨𨚪䣺揦𨥖砈鉕𨦸䏲𨧧䏟𨧨𨭆𨯔姸𨰉輋𨿅𩃬筑𩄐𩄼㷷𩅞𤫊运犏嚋𩓧𩗩𩖰𩖸𩜲𩣑𩥉𩥪𩧃𩨨𩬎𩵚𩶛纟𩻸𩼣䲤镇𪊓熢𪋿䶑递𪗋䶜𠲜达嗁"], +["9da1","辺𢒰边𤪓䔉繿潖檱仪㓤𨬬𧢝㜺躀𡟵𨀤𨭬𨮙𧨾𦚯㷫𧙕𣲷𥘵𥥖亚𥺁𦉘嚿𠹭踎孭𣺈𤲞揞拐𡟶𡡻攰嘭𥱊吚𥌑㷆𩶘䱽嘢嘞罉𥻘奵𣵀蝰东𠿪𠵉𣚺脗鵞贘瘻鱅癎瞹鍅吲腈苷嘥脲萘肽嗪祢噃吖𠺝㗎嘅嗱曱𨋢㘭甴嗰喺咗啲𠱁𠲖廐𥅈𠹶𢱢"], +["9e40","𠺢麫絚嗞𡁵抝靭咔賍燶酶揼掹揾啩𢭃鱲𢺳冚㓟𠶧冧呍唞唓癦踭𦢊疱肶蠄螆裇膶萜𡃁䓬猄𤜆宐茋𦢓噻𢛴𧴯𤆣𧵳𦻐𧊶酰𡇙鈈𣳼𪚩𠺬𠻹牦𡲢䝎𤿂𧿹𠿫䃺"], +["9ea1","鱝攟𢶠䣳𤟠𩵼𠿬𠸊恢𧖣𠿭"], +["9ead","𦁈𡆇熣纎鵐业丄㕷嬍沲卧㚬㧜卽㚥𤘘墚𤭮舭呋垪𥪕𠥹"], +["9ec5","㩒𢑥獴𩺬䴉鯭𣳾𩼰䱛𤾩𩖞𩿞葜𣶶𧊲𦞳𣜠挮紥𣻷𣸬㨪逈勌㹴㙺䗩𠒎癀嫰𠺶硺𧼮墧䂿噼鮋嵴癔𪐴麅䳡痹㟻愙𣃚𤏲"], +["9ef5","噝𡊩垧𤥣𩸆刴𧂮㖭汊鵼"], +["9f40","籖鬹埞𡝬屓擓𩓐𦌵𧅤蚭𠴨𦴢𤫢𠵱"], +["9f4f","凾𡼏嶎霃𡷑麁遌笟鬂峑箣扨挵髿篏鬪籾鬮籂粆鰕篼鬉鼗鰛𤤾齚啳寃俽麘俲剠㸆勑坧偖妷帒韈鶫轜呩鞴饀鞺匬愰"], +["9fa1","椬叚鰊鴂䰻陁榀傦畆𡝭駚剳"], +["9fae","酙隁酜"], +["9fb2","酑𨺗捿𦴣櫊嘑醎畺抅𠏼獏籰𥰡𣳽"], +["9fc1","𤤙盖鮝个𠳔莾衂"], +["9fc9","届槀僭坺刟巵从氱𠇲伹咜哚劚趂㗾弌㗳"], +["9fdb","歒酼龥鮗頮颴骺麨麄煺笔"], +["9fe7","毺蠘罸"], +["9feb","嘠𪙊蹷齓"], +["9ff0","跔蹏鸜踁抂𨍽踨蹵竓𤩷稾磘泪詧瘇"], +["a040","𨩚鼦泎蟖痃𪊲硓咢贌狢獱謭猂瓱賫𤪻蘯徺袠䒷"], +["a055","𡠻𦸅"], +["a058","詾𢔛"], +["a05b","惽癧髗鵄鍮鮏蟵"], +["a063","蠏賷猬霡鮰㗖犲䰇籑饊𦅙慙䰄麖慽"], +["a073","坟慯抦戹拎㩜懢厪𣏵捤栂㗒"], +["a0a1","嵗𨯂迚𨸹"], +["a0a6","僙𡵆礆匲阸𠼻䁥"], +["a0ae","矾"], +["a0b0","糂𥼚糚稭聦聣絍甅瓲覔舚朌聢𧒆聛瓰脃眤覉𦟌畓𦻑螩蟎臈螌詉貭譃眫瓸蓚㘵榲趦"], +["a0d4","覩瑨涹蟁𤀑瓧㷛煶悤憜㳑煢恷"], +["a0e2","罱𨬭牐惩䭾删㰘𣳇𥻗𧙖𥔱𡥄𡋾𩤃𦷜𧂭峁𦆭𨨏𣙷𠃮𦡆𤼎䕢嬟𦍌齐麦𦉫"], +["a3c0","␀",31,"␡"], +["c6a1","①",9,"⑴",9,"ⅰ",9,"丶丿亅亠冂冖冫勹匸卩厶夊宀巛⼳广廴彐彡攴无疒癶辵隶¨ˆヽヾゝゞ〃仝々〆〇ー[]✽ぁ",23], +["c740","す",58,"ァアィイ"], +["c7a1","ゥ",81,"А",5,"ЁЖ",4], +["c840","Л",26,"ёж",25,"⇧↸↹㇏𠃌乚𠂊刂䒑"], +["c8a1","龰冈龱𧘇"], +["c8cd","¬¦'"㈱№℡゛゜⺀⺄⺆⺇⺈⺊⺌⺍⺕⺜⺝⺥⺧⺪⺬⺮⺶⺼⺾⻆⻊⻌⻍⻏⻖⻗⻞⻣"], +["c8f5","ʃɐɛɔɵœøŋʊɪ"], +["f9fe","■"], +["fa40","𠕇鋛𠗟𣿅蕌䊵珯况㙉𤥂𨧤鍄𡧛苮𣳈砼杄拟𤤳𨦪𠊠𦮳𡌅侫𢓭倈𦴩𧪄𣘀𤪱𢔓倩𠍾徤𠎀𠍇滛𠐟偽儁㑺儎顬㝃萖𤦤𠒇兠𣎴兪𠯿𢃼𠋥𢔰𠖎𣈳𡦃宂蝽𠖳𣲙冲冸"], +["faa1","鴴凉减凑㳜凓𤪦决凢卂凭菍椾𣜭彻刋刦刼劵剗劔効勅簕蕂勠蘍𦬓包𨫞啉滙𣾀𠥔𣿬匳卄𠯢泋𡜦栛珕恊㺪㣌𡛨燝䒢卭却𨚫卾卿𡖖𡘓矦厓𨪛厠厫厮玧𥝲㽙玜叁叅汉义埾叙㪫𠮏叠𣿫𢶣叶𠱷吓灹唫晗浛呭𦭓𠵴啝咏咤䞦𡜍𠻝㶴𠵍"], +["fb40","𨦼𢚘啇䳭启琗喆喩嘅𡣗𤀺䕒𤐵暳𡂴嘷曍𣊊暤暭噍噏磱囱鞇叾圀囯园𨭦㘣𡉏坆𤆥汮炋坂㚱𦱾埦𡐖堃𡑔𤍣堦𤯵塜墪㕡壠壜𡈼壻寿坃𪅐𤉸鏓㖡够梦㛃湙"], +["fba1","𡘾娤啓𡚒蔅姉𠵎𦲁𦴪𡟜姙𡟻𡞲𦶦浱𡠨𡛕姹𦹅媫婣㛦𤦩婷㜈媖瑥嫓𦾡𢕔㶅𡤑㜲𡚸広勐孶斈孼𧨎䀄䡝𠈄寕慠𡨴𥧌𠖥寳宝䴐尅𡭄尓珎尔𡲥𦬨屉䣝岅峩峯嶋𡷹𡸷崐崘嵆𡺤岺巗苼㠭𤤁𢁉𢅳芇㠶㯂帮檊幵幺𤒼𠳓厦亷廐厨𡝱帉廴𨒂"], +["fc40","廹廻㢠廼栾鐛弍𠇁弢㫞䢮𡌺强𦢈𢏐彘𢑱彣鞽𦹮彲鍀𨨶徧嶶㵟𥉐𡽪𧃸𢙨釖𠊞𨨩怱暅𡡷㥣㷇㘹垐𢞴祱㹀悞悤悳𤦂𤦏𧩓璤僡媠慤萤慂慈𦻒憁凴𠙖憇宪𣾷"], +["fca1","𢡟懓𨮝𩥝懐㤲𢦀𢣁怣慜攞掋𠄘担𡝰拕𢸍捬𤧟㨗搸揸𡎎𡟼撐澊𢸶頔𤂌𥜝擡擥鑻㩦携㩗敍漖𤨨𤨣斅敭敟𣁾斵𤥀䬷旑䃘𡠩无旣忟𣐀昘𣇷𣇸晄𣆤𣆥晋𠹵晧𥇦晳晴𡸽𣈱𨗴𣇈𥌓矅𢣷馤朂𤎜𤨡㬫槺𣟂杞杧杢𤇍𩃭柗䓩栢湐鈼栁𣏦𦶠桝"], +["fd40","𣑯槡樋𨫟楳棃𣗍椁椀㴲㨁𣘼㮀枬楡𨩊䋼椶榘㮡𠏉荣傐槹𣙙𢄪橅𣜃檝㯳枱櫈𩆜㰍欝𠤣惞欵歴𢟍溵𣫛𠎵𡥘㝀吡𣭚毡𣻼毜氷𢒋𤣱𦭑汚舦汹𣶼䓅𣶽𤆤𤤌𤤀"], +["fda1","𣳉㛥㳫𠴲鮃𣇹𢒑羏样𦴥𦶡𦷫涖浜湼漄𤥿𤂅𦹲蔳𦽴凇沜渝萮𨬡港𣸯瑓𣾂秌湏媑𣁋濸㜍澝𣸰滺𡒗𤀽䕕鏰潄潜㵎潴𩅰㴻澟𤅄濓𤂑𤅕𤀹𣿰𣾴𤄿凟𤅖𤅗𤅀𦇝灋灾炧炁烌烕烖烟䄄㷨熴熖𤉷焫煅媈煊煮岜𤍥煏鍢𤋁焬𤑚𤨧𤨢熺𨯨炽爎"], +["fe40","鑂爕夑鑃爤鍁𥘅爮牀𤥴梽牕牗㹕𣁄栍漽犂猪猫𤠣𨠫䣭𨠄猨献珏玪𠰺𦨮珉瑉𤇢𡛧𤨤昣㛅𤦷𤦍𤧻珷琕椃𤨦琹𠗃㻗瑜𢢭瑠𨺲瑇珤瑶莹瑬㜰瑴鏱樬璂䥓𤪌"], +["fea1","𤅟𤩹𨮏孆𨰃𡢞瓈𡦈甎瓩甞𨻙𡩋寗𨺬鎅畍畊畧畮𤾂㼄𤴓疎瑝疞疴瘂瘬癑癏癯癶𦏵皐臯㟸𦤑𦤎皡皥皷盌𦾟葢𥂝𥅽𡸜眞眦着撯𥈠睘𣊬瞯𨥤𨥨𡛁矴砉𡍶𤨒棊碯磇磓隥礮𥗠磗礴碱𧘌辸袄𨬫𦂃𢘜禆褀椂禀𥡗禝𧬹礼禩渪𧄦㺨秆𩄍秔"] +] diff --git a/backend/node_modules/iconv-lite/encodings/tables/cp936.json b/backend/node_modules/iconv-lite/encodings/tables/cp936.json new file mode 100644 index 0000000000000000000000000000000000000000..49ddb9a1d68fd76a82904ef694de6b2770c04575 --- /dev/null +++ b/backend/node_modules/iconv-lite/encodings/tables/cp936.json @@ -0,0 +1,264 @@ +[ +["0","\u0000",127,"€"], +["8140","丂丄丅丆丏丒丗丟丠両丣並丩丮丯丱丳丵丷丼乀乁乂乄乆乊乑乕乗乚乛乢乣乤乥乧乨乪",5,"乲乴",9,"乿",6,"亇亊"], +["8180","亐亖亗亙亜亝亞亣亪亯亰亱亴亶亷亸亹亼亽亾仈仌仏仐仒仚仛仜仠仢仦仧仩仭仮仯仱仴仸仹仺仼仾伀伂",6,"伋伌伒",4,"伜伝伡伣伨伩伬伭伮伱伳伵伷伹伻伾",4,"佄佅佇",5,"佒佔佖佡佢佦佨佪佫佭佮佱佲併佷佸佹佺佽侀侁侂侅來侇侊侌侎侐侒侓侕侖侘侙侚侜侞侟価侢"], +["8240","侤侫侭侰",4,"侶",8,"俀俁係俆俇俈俉俋俌俍俒",4,"俙俛俠俢俤俥俧俫俬俰俲俴俵俶俷俹俻俼俽俿",11], +["8280","個倎倐們倓倕倖倗倛倝倞倠倢倣値倧倫倯",10,"倻倽倿偀偁偂偄偅偆偉偊偋偍偐",4,"偖偗偘偙偛偝",7,"偦",5,"偭",8,"偸偹偺偼偽傁傂傃傄傆傇傉傊傋傌傎",20,"傤傦傪傫傭",4,"傳",6,"傼"], +["8340","傽",17,"僐",5,"僗僘僙僛",10,"僨僩僪僫僯僰僱僲僴僶",4,"僼",9,"儈"], +["8380","儉儊儌",5,"儓",13,"儢",28,"兂兇兊兌兎兏児兒兓兗兘兙兛兝",4,"兣兤兦內兩兪兯兲兺兾兿冃冄円冇冊冋冎冏冐冑冓冔冘冚冝冞冟冡冣冦",4,"冭冮冴冸冹冺冾冿凁凂凃凅凈凊凍凎凐凒",5], +["8440","凘凙凚凜凞凟凢凣凥",5,"凬凮凱凲凴凷凾刄刅刉刋刌刏刐刓刔刕刜刞刟刡刢刣別刦刧刪刬刯刱刲刴刵刼刾剄",5,"剋剎剏剒剓剕剗剘"], +["8480","剙剚剛剝剟剠剢剣剤剦剨剫剬剭剮剰剱剳",9,"剾劀劃",4,"劉",6,"劑劒劔",6,"劜劤劥劦劧劮劯劰労",9,"勀勁勂勄勅勆勈勊勌勍勎勏勑勓勔動勗務",5,"勠勡勢勣勥",10,"勱",7,"勻勼勽匁匂匃匄匇匉匊匋匌匎"], +["8540","匑匒匓匔匘匛匜匞匟匢匤匥匧匨匩匫匬匭匯",9,"匼匽區卂卄卆卋卌卍卐協単卙卛卝卥卨卪卬卭卲卶卹卻卼卽卾厀厁厃厇厈厊厎厏"], +["8580","厐",4,"厖厗厙厛厜厞厠厡厤厧厪厫厬厭厯",6,"厷厸厹厺厼厽厾叀參",4,"収叏叐叒叓叕叚叜叝叞叡叢叧叴叺叾叿吀吂吅吇吋吔吘吙吚吜吢吤吥吪吰吳吶吷吺吽吿呁呂呄呅呇呉呌呍呎呏呑呚呝",4,"呣呥呧呩",7,"呴呹呺呾呿咁咃咅咇咈咉咊咍咑咓咗咘咜咞咟咠咡"], +["8640","咢咥咮咰咲咵咶咷咹咺咼咾哃哅哊哋哖哘哛哠",4,"哫哬哯哰哱哴",5,"哻哾唀唂唃唄唅唈唊",4,"唒唓唕",5,"唜唝唞唟唡唥唦"], +["8680","唨唩唫唭唲唴唵唶唸唹唺唻唽啀啂啅啇啈啋",4,"啑啒啓啔啗",4,"啝啞啟啠啢啣啨啩啫啯",5,"啹啺啽啿喅喆喌喍喎喐喒喓喕喖喗喚喛喞喠",6,"喨",8,"喲喴営喸喺喼喿",4,"嗆嗇嗈嗊嗋嗎嗏嗐嗕嗗",4,"嗞嗠嗢嗧嗩嗭嗮嗰嗱嗴嗶嗸",4,"嗿嘂嘃嘄嘅"], +["8740","嘆嘇嘊嘋嘍嘐",7,"嘙嘚嘜嘝嘠嘡嘢嘥嘦嘨嘩嘪嘫嘮嘯嘰嘳嘵嘷嘸嘺嘼嘽嘾噀",11,"噏",4,"噕噖噚噛噝",4], +["8780","噣噥噦噧噭噮噯噰噲噳噴噵噷噸噹噺噽",7,"嚇",6,"嚐嚑嚒嚔",14,"嚤",10,"嚰",6,"嚸嚹嚺嚻嚽",12,"囋",8,"囕囖囘囙囜団囥",5,"囬囮囯囲図囶囷囸囻囼圀圁圂圅圇國",6], +["8840","園",9,"圝圞圠圡圢圤圥圦圧圫圱圲圴",4,"圼圽圿坁坃坄坅坆坈坉坋坒",4,"坘坙坢坣坥坧坬坮坰坱坲坴坵坸坹坺坽坾坿垀"], +["8880","垁垇垈垉垊垍",4,"垔",6,"垜垝垞垟垥垨垪垬垯垰垱垳垵垶垷垹",8,"埄",6,"埌埍埐埑埓埖埗埛埜埞埡埢埣埥",7,"埮埰埱埲埳埵埶執埻埼埾埿堁堃堄堅堈堉堊堌堎堏堐堒堓堔堖堗堘堚堛堜堝堟堢堣堥",4,"堫",4,"報堲堳場堶",7], +["8940","堾",5,"塅",6,"塎塏塐塒塓塕塖塗塙",4,"塟",5,"塦",4,"塭",16,"塿墂墄墆墇墈墊墋墌"], +["8980","墍",4,"墔",4,"墛墜墝墠",7,"墪",17,"墽墾墿壀壂壃壄壆",10,"壒壓壔壖",13,"壥",5,"壭壯壱売壴壵壷壸壺",7,"夃夅夆夈",4,"夎夐夑夒夓夗夘夛夝夞夠夡夢夣夦夨夬夰夲夳夵夶夻"], +["8a40","夽夾夿奀奃奅奆奊奌奍奐奒奓奙奛",4,"奡奣奤奦",12,"奵奷奺奻奼奾奿妀妅妉妋妌妎妏妐妑妔妕妘妚妛妜妝妟妠妡妢妦"], +["8a80","妧妬妭妰妱妳",5,"妺妼妽妿",6,"姇姈姉姌姍姎姏姕姖姙姛姞",4,"姤姦姧姩姪姫姭",11,"姺姼姽姾娀娂娊娋娍娎娏娐娒娔娕娖娗娙娚娛娝娞娡娢娤娦娧娨娪",6,"娳娵娷",4,"娽娾娿婁",4,"婇婈婋",9,"婖婗婘婙婛",5], +["8b40","婡婣婤婥婦婨婩婫",8,"婸婹婻婼婽婾媀",17,"媓",6,"媜",13,"媫媬"], +["8b80","媭",4,"媴媶媷媹",4,"媿嫀嫃",5,"嫊嫋嫍",4,"嫓嫕嫗嫙嫚嫛嫝嫞嫟嫢嫤嫥嫧嫨嫪嫬",4,"嫲",22,"嬊",11,"嬘",25,"嬳嬵嬶嬸",7,"孁",6], +["8c40","孈",7,"孒孖孞孠孡孧孨孫孭孮孯孲孴孶孷學孹孻孼孾孿宂宆宊宍宎宐宑宒宔宖実宧宨宩宬宭宮宯宱宲宷宺宻宼寀寁寃寈寉寊寋寍寎寏"], +["8c80","寑寔",8,"寠寢寣實寧審",4,"寯寱",6,"寽対尀専尃尅將專尋尌對導尐尒尓尗尙尛尞尟尠尡尣尦尨尩尪尫尭尮尯尰尲尳尵尶尷屃屄屆屇屌屍屒屓屔屖屗屘屚屛屜屝屟屢層屧",6,"屰屲",6,"屻屼屽屾岀岃",4,"岉岊岋岎岏岒岓岕岝",4,"岤",4], +["8d40","岪岮岯岰岲岴岶岹岺岻岼岾峀峂峃峅",5,"峌",5,"峓",5,"峚",6,"峢峣峧峩峫峬峮峯峱",9,"峼",4], +["8d80","崁崄崅崈",5,"崏",4,"崕崗崘崙崚崜崝崟",4,"崥崨崪崫崬崯",4,"崵",7,"崿",7,"嵈嵉嵍",10,"嵙嵚嵜嵞",10,"嵪嵭嵮嵰嵱嵲嵳嵵",12,"嶃",21,"嶚嶛嶜嶞嶟嶠"], +["8e40","嶡",21,"嶸",12,"巆",6,"巎",12,"巜巟巠巣巤巪巬巭"], +["8e80","巰巵巶巸",4,"巿帀帄帇帉帊帋帍帎帒帓帗帞",7,"帨",4,"帯帰帲",4,"帹帺帾帿幀幁幃幆",5,"幍",6,"幖",4,"幜幝幟幠幣",14,"幵幷幹幾庁庂広庅庈庉庌庍庎庒庘庛庝庡庢庣庤庨",4,"庮",4,"庴庺庻庼庽庿",6], +["8f40","廆廇廈廋",5,"廔廕廗廘廙廚廜",11,"廩廫",8,"廵廸廹廻廼廽弅弆弇弉弌弍弎弐弒弔弖弙弚弜弝弞弡弢弣弤"], +["8f80","弨弫弬弮弰弲",6,"弻弽弾弿彁",14,"彑彔彙彚彛彜彞彟彠彣彥彧彨彫彮彯彲彴彵彶彸彺彽彾彿徃徆徍徎徏徑従徔徖徚徛徝從徟徠徢",5,"復徫徬徯",5,"徶徸徹徺徻徾",4,"忇忈忊忋忎忓忔忕忚忛応忞忟忢忣忥忦忨忩忬忯忰忲忳忴忶忷忹忺忼怇"], +["9040","怈怉怋怌怐怑怓怗怘怚怞怟怢怣怤怬怭怮怰",4,"怶",4,"怽怾恀恄",6,"恌恎恏恑恓恔恖恗恘恛恜恞恟恠恡恥恦恮恱恲恴恵恷恾悀"], +["9080","悁悂悅悆悇悈悊悋悎悏悐悑悓悕悗悘悙悜悞悡悢悤悥悧悩悪悮悰悳悵悶悷悹悺悽",7,"惇惈惉惌",4,"惒惓惔惖惗惙惛惞惡",4,"惪惱惲惵惷惸惻",4,"愂愃愄愅愇愊愋愌愐",4,"愖愗愘愙愛愜愝愞愡愢愥愨愩愪愬",18,"慀",6], +["9140","慇慉態慍慏慐慒慓慔慖",6,"慞慟慠慡慣慤慥慦慩",6,"慱慲慳慴慶慸",18,"憌憍憏",4,"憕"], +["9180","憖",6,"憞",8,"憪憫憭",9,"憸",5,"憿懀懁懃",4,"應懌",4,"懓懕",16,"懧",13,"懶",8,"戀",5,"戇戉戓戔戙戜戝戞戠戣戦戧戨戩戫戭戯戰戱戲戵戶戸",4,"扂扄扅扆扊"], +["9240","扏扐払扖扗扙扚扜",6,"扤扥扨扱扲扴扵扷扸扺扻扽抁抂抃抅抆抇抈抋",5,"抔抙抜抝択抣抦抧抩抪抭抮抯抰抲抳抴抶抷抸抺抾拀拁"], +["9280","拃拋拏拑拕拝拞拠拡拤拪拫拰拲拵拸拹拺拻挀挃挄挅挆挊挋挌挍挏挐挒挓挔挕挗挘挙挜挦挧挩挬挭挮挰挱挳",5,"挻挼挾挿捀捁捄捇捈捊捑捒捓捔捖",7,"捠捤捥捦捨捪捫捬捯捰捲捳捴捵捸捹捼捽捾捿掁掃掄掅掆掋掍掑掓掔掕掗掙",6,"採掤掦掫掯掱掲掵掶掹掻掽掿揀"], +["9340","揁揂揃揅揇揈揊揋揌揑揓揔揕揗",6,"揟揢揤",4,"揫揬揮揯揰揱揳揵揷揹揺揻揼揾搃搄搆",4,"損搎搑搒搕",5,"搝搟搢搣搤"], +["9380","搥搧搨搩搫搮",5,"搵",4,"搻搼搾摀摂摃摉摋",6,"摓摕摖摗摙",4,"摟",7,"摨摪摫摬摮",9,"摻",6,"撃撆撈",8,"撓撔撗撘撚撛撜撝撟",4,"撥撦撧撨撪撫撯撱撲撳撴撶撹撻撽撾撿擁擃擄擆",6,"擏擑擓擔擕擖擙據"], +["9440","擛擜擝擟擠擡擣擥擧",24,"攁",7,"攊",7,"攓",4,"攙",8], +["9480","攢攣攤攦",4,"攬攭攰攱攲攳攷攺攼攽敀",4,"敆敇敊敋敍敎敐敒敓敔敗敘敚敜敟敠敡敤敥敧敨敩敪敭敮敯敱敳敵敶數",14,"斈斉斊斍斎斏斒斔斕斖斘斚斝斞斠斢斣斦斨斪斬斮斱",7,"斺斻斾斿旀旂旇旈旉旊旍旐旑旓旔旕旘",7,"旡旣旤旪旫"], +["9540","旲旳旴旵旸旹旻",4,"昁昄昅昇昈昉昋昍昐昑昒昖昗昘昚昛昜昞昡昢昣昤昦昩昪昫昬昮昰昲昳昷",4,"昽昿晀時晄",6,"晍晎晐晑晘"], +["9580","晙晛晜晝晞晠晢晣晥晧晩",4,"晱晲晳晵晸晹晻晼晽晿暀暁暃暅暆暈暉暊暋暍暎暏暐暒暓暔暕暘",4,"暞",8,"暩",4,"暯",4,"暵暶暷暸暺暻暼暽暿",25,"曚曞",7,"曧曨曪",5,"曱曵曶書曺曻曽朁朂會"], +["9640","朄朅朆朇朌朎朏朑朒朓朖朘朙朚朜朞朠",5,"朧朩朮朰朲朳朶朷朸朹朻朼朾朿杁杄杅杇杊杋杍杒杔杕杗",4,"杝杢杣杤杦杧杫杬杮東杴杶"], +["9680","杸杹杺杻杽枀枂枃枅枆枈枊枌枍枎枏枑枒枓枔枖枙枛枟枠枡枤枦枩枬枮枱枲枴枹",7,"柂柅",9,"柕柖柗柛柟柡柣柤柦柧柨柪柫柭柮柲柵",7,"柾栁栂栃栄栆栍栐栒栔栕栘",4,"栞栟栠栢",6,"栫",6,"栴栵栶栺栻栿桇桋桍桏桒桖",5], +["9740","桜桝桞桟桪桬",7,"桵桸",8,"梂梄梇",7,"梐梑梒梔梕梖梘",9,"梣梤梥梩梪梫梬梮梱梲梴梶梷梸"], +["9780","梹",6,"棁棃",5,"棊棌棎棏棐棑棓棔棖棗棙棛",4,"棡棢棤",9,"棯棲棳棴棶棷棸棻棽棾棿椀椂椃椄椆",4,"椌椏椑椓",11,"椡椢椣椥",7,"椮椯椱椲椳椵椶椷椸椺椻椼椾楀楁楃",16,"楕楖楘楙楛楜楟"], +["9840","楡楢楤楥楧楨楩楪楬業楯楰楲",4,"楺楻楽楾楿榁榃榅榊榋榌榎",5,"榖榗榙榚榝",9,"榩榪榬榮榯榰榲榳榵榶榸榹榺榼榽"], +["9880","榾榿槀槂",7,"構槍槏槑槒槓槕",5,"槜槝槞槡",11,"槮槯槰槱槳",9,"槾樀",9,"樋",11,"標",5,"樠樢",5,"権樫樬樭樮樰樲樳樴樶",6,"樿",4,"橅橆橈",7,"橑",6,"橚"], +["9940","橜",4,"橢橣橤橦",10,"橲",6,"橺橻橽橾橿檁檂檃檅",8,"檏檒",4,"檘",7,"檡",5], +["9980","檧檨檪檭",114,"欥欦欨",6], +["9a40","欯欰欱欳欴欵欶欸欻欼欽欿歀歁歂歄歅歈歊歋歍",11,"歚",7,"歨歩歫",13,"歺歽歾歿殀殅殈"], +["9a80","殌殎殏殐殑殔殕殗殘殙殜",4,"殢",7,"殫",7,"殶殸",6,"毀毃毄毆",4,"毌毎毐毑毘毚毜",4,"毢",7,"毬毭毮毰毱毲毴毶毷毸毺毻毼毾",6,"氈",4,"氎氒気氜氝氞氠氣氥氫氬氭氱氳氶氷氹氺氻氼氾氿汃汄汅汈汋",4,"汑汒汓汖汘"], +["9b40","汙汚汢汣汥汦汧汫",4,"汱汳汵汷汸決汻汼汿沀沄沇沊沋沍沎沑沒沕沖沗沘沚沜沝沞沠沢沨沬沯沰沴沵沶沷沺泀況泂泃泆泇泈泋泍泎泏泑泒泘"], +["9b80","泙泚泜泝泟泤泦泧泩泬泭泲泴泹泿洀洂洃洅洆洈洉洊洍洏洐洑洓洔洕洖洘洜洝洟",5,"洦洨洩洬洭洯洰洴洶洷洸洺洿浀浂浄浉浌浐浕浖浗浘浛浝浟浡浢浤浥浧浨浫浬浭浰浱浲浳浵浶浹浺浻浽",4,"涃涄涆涇涊涋涍涏涐涒涖",4,"涜涢涥涬涭涰涱涳涴涶涷涹",5,"淁淂淃淈淉淊"], +["9c40","淍淎淏淐淒淓淔淕淗淚淛淜淟淢淣淥淧淨淩淪淭淯淰淲淴淵淶淸淺淽",7,"渆渇済渉渋渏渒渓渕渘渙減渜渞渟渢渦渧渨渪測渮渰渱渳渵"], +["9c80","渶渷渹渻",7,"湅",7,"湏湐湑湒湕湗湙湚湜湝湞湠",10,"湬湭湯",14,"満溁溂溄溇溈溊",4,"溑",6,"溙溚溛溝溞溠溡溣溤溦溨溩溫溬溭溮溰溳溵溸溹溼溾溿滀滃滄滅滆滈滉滊滌滍滎滐滒滖滘滙滛滜滝滣滧滪",5], +["9d40","滰滱滲滳滵滶滷滸滺",7,"漃漄漅漇漈漊",4,"漐漑漒漖",9,"漡漢漣漥漦漧漨漬漮漰漲漴漵漷",6,"漿潀潁潂"], +["9d80","潃潄潅潈潉潊潌潎",9,"潙潚潛潝潟潠潡潣潤潥潧",5,"潯潰潱潳潵潶潷潹潻潽",6,"澅澆澇澊澋澏",12,"澝澞澟澠澢",4,"澨",10,"澴澵澷澸澺",5,"濁濃",5,"濊",6,"濓",10,"濟濢濣濤濥"], +["9e40","濦",7,"濰",32,"瀒",7,"瀜",6,"瀤",6], +["9e80","瀫",9,"瀶瀷瀸瀺",17,"灍灎灐",13,"灟",11,"灮灱灲灳灴灷灹灺灻災炁炂炃炄炆炇炈炋炌炍炏炐炑炓炗炘炚炛炞",12,"炰炲炴炵炶為炾炿烄烅烆烇烉烋",12,"烚"], +["9f40","烜烝烞烠烡烢烣烥烪烮烰",6,"烸烺烻烼烾",10,"焋",4,"焑焒焔焗焛",10,"焧",7,"焲焳焴"], +["9f80","焵焷",13,"煆煇煈煉煋煍煏",12,"煝煟",4,"煥煩",4,"煯煰煱煴煵煶煷煹煻煼煾",5,"熅",4,"熋熌熍熎熐熑熒熓熕熖熗熚",4,"熡",6,"熩熪熫熭",5,"熴熶熷熸熺",8,"燄",9,"燏",4], +["a040","燖",9,"燡燢燣燤燦燨",5,"燯",9,"燺",11,"爇",19], +["a080","爛爜爞",9,"爩爫爭爮爯爲爳爴爺爼爾牀",6,"牉牊牋牎牏牐牑牓牔牕牗牘牚牜牞牠牣牤牥牨牪牫牬牭牰牱牳牴牶牷牸牻牼牽犂犃犅",4,"犌犎犐犑犓",11,"犠",11,"犮犱犲犳犵犺",6,"狅狆狇狉狊狋狌狏狑狓狔狕狖狘狚狛"], +["a1a1"," 、。·ˉˇ¨〃々—~‖…‘’“”〔〕〈",7,"〖〗【】±×÷∶∧∨∑∏∪∩∈∷√⊥∥∠⌒⊙∫∮≡≌≈∽∝≠≮≯≤≥∞∵∴♂♀°′″℃$¤¢£‰§№☆★○●◎◇◆□■△▲※→←↑↓〓"], +["a2a1","ⅰ",9], +["a2b1","⒈",19,"⑴",19,"①",9], +["a2e5","㈠",9], +["a2f1","Ⅰ",11], +["a3a1","!"#¥%",88," ̄"], +["a4a1","ぁ",82], +["a5a1","ァ",85], +["a6a1","Α",16,"Σ",6], +["a6c1","α",16,"σ",6], +["a6e0","︵︶︹︺︿﹀︽︾﹁﹂﹃﹄"], +["a6ee","︻︼︷︸︱"], +["a6f4","︳︴"], +["a7a1","А",5,"ЁЖ",25], +["a7d1","а",5,"ёж",25], +["a840","ˊˋ˙–―‥‵℅℉↖↗↘↙∕∟∣≒≦≧⊿═",35,"▁",6], +["a880","█",7,"▓▔▕▼▽◢◣◤◥☉⊕〒〝〞"], +["a8a1","āáǎàēéěèīíǐìōóǒòūúǔùǖǘǚǜüêɑ"], +["a8bd","ńň"], +["a8c0","ɡ"], +["a8c5","ㄅ",36], +["a940","〡",8,"㊣㎎㎏㎜㎝㎞㎡㏄㏎㏑㏒㏕︰¬¦"], +["a959","℡㈱"], +["a95c","‐"], +["a960","ー゛゜ヽヾ〆ゝゞ﹉",9,"﹔﹕﹖﹗﹙",8], +["a980","﹢",4,"﹨﹩﹪﹫"], +["a996","〇"], +["a9a4","─",75], +["aa40","狜狝狟狢",5,"狪狫狵狶狹狽狾狿猀猂猄",5,"猋猌猍猏猐猑猒猔猘猙猚猟猠猣猤猦猧猨猭猯猰猲猳猵猶猺猻猼猽獀",8], +["aa80","獉獊獋獌獎獏獑獓獔獕獖獘",7,"獡",10,"獮獰獱"], +["ab40","獲",11,"獿",4,"玅玆玈玊玌玍玏玐玒玓玔玕玗玘玙玚玜玝玞玠玡玣",5,"玪玬玭玱玴玵玶玸玹玼玽玾玿珁珃",4], +["ab80","珋珌珎珒",6,"珚珛珜珝珟珡珢珣珤珦珨珪珫珬珮珯珰珱珳",4], +["ac40","珸",10,"琄琇琈琋琌琍琎琑",8,"琜",5,"琣琤琧琩琫琭琯琱琲琷",4,"琽琾琿瑀瑂",11], +["ac80","瑎",6,"瑖瑘瑝瑠",12,"瑮瑯瑱",4,"瑸瑹瑺"], +["ad40","瑻瑼瑽瑿璂璄璅璆璈璉璊璌璍璏璑",10,"璝璟",7,"璪",15,"璻",12], +["ad80","瓈",9,"瓓",8,"瓝瓟瓡瓥瓧",6,"瓰瓱瓲"], +["ae40","瓳瓵瓸",6,"甀甁甂甃甅",7,"甎甐甒甔甕甖甗甛甝甞甠",4,"甦甧甪甮甴甶甹甼甽甿畁畂畃畄畆畇畉畊畍畐畑畒畓畕畖畗畘"], +["ae80","畝",7,"畧畨畩畫",6,"畳畵當畷畺",4,"疀疁疂疄疅疇"], +["af40","疈疉疊疌疍疎疐疓疕疘疛疜疞疢疦",4,"疭疶疷疺疻疿痀痁痆痋痌痎痏痐痑痓痗痙痚痜痝痟痠痡痥痩痬痭痮痯痲痳痵痶痷痸痺痻痽痾瘂瘄瘆瘇"], +["af80","瘈瘉瘋瘍瘎瘏瘑瘒瘓瘔瘖瘚瘜瘝瘞瘡瘣瘧瘨瘬瘮瘯瘱瘲瘶瘷瘹瘺瘻瘽癁療癄"], +["b040","癅",6,"癎",5,"癕癗",4,"癝癟癠癡癢癤",6,"癬癭癮癰",7,"癹発發癿皀皁皃皅皉皊皌皍皏皐皒皔皕皗皘皚皛"], +["b080","皜",7,"皥",8,"皯皰皳皵",9,"盀盁盃啊阿埃挨哎唉哀皑癌蔼矮艾碍爱隘鞍氨安俺按暗岸胺案肮昂盎凹敖熬翱袄傲奥懊澳芭捌扒叭吧笆八疤巴拔跋靶把耙坝霸罢爸白柏百摆佰败拜稗斑班搬扳般颁板版扮拌伴瓣半办绊邦帮梆榜膀绑棒磅蚌镑傍谤苞胞包褒剥"], +["b140","盄盇盉盋盌盓盕盙盚盜盝盞盠",4,"盦",7,"盰盳盵盶盷盺盻盽盿眀眂眃眅眆眊県眎",10,"眛眜眝眞眡眣眤眥眧眪眫"], +["b180","眬眮眰",4,"眹眻眽眾眿睂睄睅睆睈",7,"睒",7,"睜薄雹保堡饱宝抱报暴豹鲍爆杯碑悲卑北辈背贝钡倍狈备惫焙被奔苯本笨崩绷甭泵蹦迸逼鼻比鄙笔彼碧蓖蔽毕毙毖币庇痹闭敝弊必辟壁臂避陛鞭边编贬扁便变卞辨辩辫遍标彪膘表鳖憋别瘪彬斌濒滨宾摈兵冰柄丙秉饼炳"], +["b240","睝睞睟睠睤睧睩睪睭",11,"睺睻睼瞁瞂瞃瞆",5,"瞏瞐瞓",11,"瞡瞣瞤瞦瞨瞫瞭瞮瞯瞱瞲瞴瞶",4], +["b280","瞼瞾矀",12,"矎",8,"矘矙矚矝",4,"矤病并玻菠播拨钵波博勃搏铂箔伯帛舶脖膊渤泊驳捕卜哺补埠不布步簿部怖擦猜裁材才财睬踩采彩菜蔡餐参蚕残惭惨灿苍舱仓沧藏操糙槽曹草厕策侧册测层蹭插叉茬茶查碴搽察岔差诧拆柴豺搀掺蝉馋谗缠铲产阐颤昌猖"], +["b340","矦矨矪矯矰矱矲矴矵矷矹矺矻矼砃",5,"砊砋砎砏砐砓砕砙砛砞砠砡砢砤砨砪砫砮砯砱砲砳砵砶砽砿硁硂硃硄硆硈硉硊硋硍硏硑硓硔硘硙硚"], +["b380","硛硜硞",11,"硯",7,"硸硹硺硻硽",6,"场尝常长偿肠厂敞畅唱倡超抄钞朝嘲潮巢吵炒车扯撤掣彻澈郴臣辰尘晨忱沉陈趁衬撑称城橙成呈乘程惩澄诚承逞骋秤吃痴持匙池迟弛驰耻齿侈尺赤翅斥炽充冲虫崇宠抽酬畴踌稠愁筹仇绸瞅丑臭初出橱厨躇锄雏滁除楚"], +["b440","碄碅碆碈碊碋碏碐碒碔碕碖碙碝碞碠碢碤碦碨",7,"碵碶碷碸確碻碼碽碿磀磂磃磄磆磇磈磌磍磎磏磑磒磓磖磗磘磚",9], +["b480","磤磥磦磧磩磪磫磭",4,"磳磵磶磸磹磻",5,"礂礃礄礆",6,"础储矗搐触处揣川穿椽传船喘串疮窗幢床闯创吹炊捶锤垂春椿醇唇淳纯蠢戳绰疵茨磁雌辞慈瓷词此刺赐次聪葱囱匆从丛凑粗醋簇促蹿篡窜摧崔催脆瘁粹淬翠村存寸磋撮搓措挫错搭达答瘩打大呆歹傣戴带殆代贷袋待逮"], +["b540","礍",5,"礔",9,"礟",4,"礥",14,"礵",4,"礽礿祂祃祄祅祇祊",8,"祔祕祘祙祡祣"], +["b580","祤祦祩祪祫祬祮祰",6,"祹祻",4,"禂禃禆禇禈禉禋禌禍禎禐禑禒怠耽担丹单郸掸胆旦氮但惮淡诞弹蛋当挡党荡档刀捣蹈倒岛祷导到稻悼道盗德得的蹬灯登等瞪凳邓堤低滴迪敌笛狄涤翟嫡抵底地蒂第帝弟递缔颠掂滇碘点典靛垫电佃甸店惦奠淀殿碉叼雕凋刁掉吊钓调跌爹碟蝶迭谍叠"], +["b640","禓",6,"禛",11,"禨",10,"禴",4,"禼禿秂秄秅秇秈秊秌秎秏秐秓秔秖秗秙",5,"秠秡秢秥秨秪"], +["b680","秬秮秱",6,"秹秺秼秾秿稁稄稅稇稈稉稊稌稏",4,"稕稖稘稙稛稜丁盯叮钉顶鼎锭定订丢东冬董懂动栋侗恫冻洞兜抖斗陡豆逗痘都督毒犊独读堵睹赌杜镀肚度渡妒端短锻段断缎堆兑队对墩吨蹲敦顿囤钝盾遁掇哆多夺垛躲朵跺舵剁惰堕蛾峨鹅俄额讹娥恶厄扼遏鄂饿恩而儿耳尔饵洱二"], +["b740","稝稟稡稢稤",14,"稴稵稶稸稺稾穀",5,"穇",9,"穒",4,"穘",16], +["b780","穩",6,"穱穲穳穵穻穼穽穾窂窅窇窉窊窋窌窎窏窐窓窔窙窚窛窞窡窢贰发罚筏伐乏阀法珐藩帆番翻樊矾钒繁凡烦反返范贩犯饭泛坊芳方肪房防妨仿访纺放菲非啡飞肥匪诽吠肺废沸费芬酚吩氛分纷坟焚汾粉奋份忿愤粪丰封枫蜂峰锋风疯烽逢冯缝讽奉凤佛否夫敷肤孵扶拂辐幅氟符伏俘服"], +["b840","窣窤窧窩窪窫窮",4,"窴",10,"竀",10,"竌",9,"竗竘竚竛竜竝竡竢竤竧",5,"竮竰竱竲竳"], +["b880","竴",4,"竻竼竾笀笁笂笅笇笉笌笍笎笐笒笓笖笗笘笚笜笝笟笡笢笣笧笩笭浮涪福袱弗甫抚辅俯釜斧脯腑府腐赴副覆赋复傅付阜父腹负富讣附妇缚咐噶嘎该改概钙盖溉干甘杆柑竿肝赶感秆敢赣冈刚钢缸肛纲岗港杠篙皋高膏羔糕搞镐稿告哥歌搁戈鸽胳疙割革葛格蛤阁隔铬个各给根跟耕更庚羹"], +["b940","笯笰笲笴笵笶笷笹笻笽笿",5,"筆筈筊筍筎筓筕筗筙筜筞筟筡筣",10,"筯筰筳筴筶筸筺筼筽筿箁箂箃箄箆",6,"箎箏"], +["b980","箑箒箓箖箘箙箚箛箞箟箠箣箤箥箮箯箰箲箳箵箶箷箹",7,"篂篃範埂耿梗工攻功恭龚供躬公宫弓巩汞拱贡共钩勾沟苟狗垢构购够辜菇咕箍估沽孤姑鼓古蛊骨谷股故顾固雇刮瓜剐寡挂褂乖拐怪棺关官冠观管馆罐惯灌贯光广逛瑰规圭硅归龟闺轨鬼诡癸桂柜跪贵刽辊滚棍锅郭国果裹过哈"], +["ba40","篅篈築篊篋篍篎篏篐篒篔",4,"篛篜篞篟篠篢篣篤篧篨篩篫篬篭篯篰篲",4,"篸篹篺篻篽篿",7,"簈簉簊簍簎簐",5,"簗簘簙"], +["ba80","簚",4,"簠",5,"簨簩簫",12,"簹",5,"籂骸孩海氦亥害骇酣憨邯韩含涵寒函喊罕翰撼捍旱憾悍焊汗汉夯杭航壕嚎豪毫郝好耗号浩呵喝荷菏核禾和何合盒貉阂河涸赫褐鹤贺嘿黑痕很狠恨哼亨横衡恒轰哄烘虹鸿洪宏弘红喉侯猴吼厚候后呼乎忽瑚壶葫胡蝴狐糊湖"], +["bb40","籃",9,"籎",36,"籵",5,"籾",9], +["bb80","粈粊",6,"粓粔粖粙粚粛粠粡粣粦粧粨粩粫粬粭粯粰粴",4,"粺粻弧虎唬护互沪户花哗华猾滑画划化话槐徊怀淮坏欢环桓还缓换患唤痪豢焕涣宦幻荒慌黄磺蝗簧皇凰惶煌晃幌恍谎灰挥辉徽恢蛔回毁悔慧卉惠晦贿秽会烩汇讳诲绘荤昏婚魂浑混豁活伙火获或惑霍货祸击圾基机畸稽积箕"], +["bc40","粿糀糂糃糄糆糉糋糎",6,"糘糚糛糝糞糡",6,"糩",5,"糰",7,"糹糺糼",13,"紋",5], +["bc80","紑",14,"紡紣紤紥紦紨紩紪紬紭紮細",6,"肌饥迹激讥鸡姬绩缉吉极棘辑籍集及急疾汲即嫉级挤几脊己蓟技冀季伎祭剂悸济寄寂计记既忌际妓继纪嘉枷夹佳家加荚颊贾甲钾假稼价架驾嫁歼监坚尖笺间煎兼肩艰奸缄茧检柬碱硷拣捡简俭剪减荐槛鉴践贱见键箭件"], +["bd40","紷",54,"絯",7], +["bd80","絸",32,"健舰剑饯渐溅涧建僵姜将浆江疆蒋桨奖讲匠酱降蕉椒礁焦胶交郊浇骄娇嚼搅铰矫侥脚狡角饺缴绞剿教酵轿较叫窖揭接皆秸街阶截劫节桔杰捷睫竭洁结解姐戒藉芥界借介疥诫届巾筋斤金今津襟紧锦仅谨进靳晋禁近烬浸"], +["be40","継",12,"綧",6,"綯",42], +["be80","線",32,"尽劲荆兢茎睛晶鲸京惊精粳经井警景颈静境敬镜径痉靖竟竞净炯窘揪究纠玖韭久灸九酒厩救旧臼舅咎就疚鞠拘狙疽居驹菊局咀矩举沮聚拒据巨具距踞锯俱句惧炬剧捐鹃娟倦眷卷绢撅攫抉掘倔爵觉决诀绝均菌钧军君峻"], +["bf40","緻",62], +["bf80","縺縼",4,"繂",4,"繈",21,"俊竣浚郡骏喀咖卡咯开揩楷凯慨刊堪勘坎砍看康慷糠扛抗亢炕考拷烤靠坷苛柯棵磕颗科壳咳可渴克刻客课肯啃垦恳坑吭空恐孔控抠口扣寇枯哭窟苦酷库裤夸垮挎跨胯块筷侩快宽款匡筐狂框矿眶旷况亏盔岿窥葵奎魁傀"], +["c040","繞",35,"纃",23,"纜纝纞"], +["c080","纮纴纻纼绖绤绬绹缊缐缞缷缹缻",6,"罃罆",9,"罒罓馈愧溃坤昆捆困括扩廓阔垃拉喇蜡腊辣啦莱来赖蓝婪栏拦篮阑兰澜谰揽览懒缆烂滥琅榔狼廊郎朗浪捞劳牢老佬姥酪烙涝勒乐雷镭蕾磊累儡垒擂肋类泪棱楞冷厘梨犁黎篱狸离漓理李里鲤礼莉荔吏栗丽厉励砾历利傈例俐"], +["c140","罖罙罛罜罝罞罠罣",4,"罫罬罭罯罰罳罵罶罷罸罺罻罼罽罿羀羂",7,"羋羍羏",4,"羕",4,"羛羜羠羢羣羥羦羨",6,"羱"], +["c180","羳",4,"羺羻羾翀翂翃翄翆翇翈翉翋翍翏",4,"翖翗翙",5,"翢翣痢立粒沥隶力璃哩俩联莲连镰廉怜涟帘敛脸链恋炼练粮凉梁粱良两辆量晾亮谅撩聊僚疗燎寥辽潦了撂镣廖料列裂烈劣猎琳林磷霖临邻鳞淋凛赁吝拎玲菱零龄铃伶羚凌灵陵岭领另令溜琉榴硫馏留刘瘤流柳六龙聋咙笼窿"], +["c240","翤翧翨翪翫翬翭翯翲翴",6,"翽翾翿耂耇耈耉耊耎耏耑耓耚耛耝耞耟耡耣耤耫",5,"耲耴耹耺耼耾聀聁聄聅聇聈聉聎聏聐聑聓聕聖聗"], +["c280","聙聛",13,"聫",5,"聲",11,"隆垄拢陇楼娄搂篓漏陋芦卢颅庐炉掳卤虏鲁麓碌露路赂鹿潞禄录陆戮驴吕铝侣旅履屡缕虑氯律率滤绿峦挛孪滦卵乱掠略抡轮伦仑沦纶论萝螺罗逻锣箩骡裸落洛骆络妈麻玛码蚂马骂嘛吗埋买麦卖迈脉瞒馒蛮满蔓曼慢漫"], +["c340","聾肁肂肅肈肊肍",5,"肔肕肗肙肞肣肦肧肨肬肰肳肵肶肸肹肻胅胇",4,"胏",6,"胘胟胠胢胣胦胮胵胷胹胻胾胿脀脁脃脄脅脇脈脋"], +["c380","脌脕脗脙脛脜脝脟",12,"脭脮脰脳脴脵脷脹",4,"脿谩芒茫盲氓忙莽猫茅锚毛矛铆卯茂冒帽貌贸么玫枚梅酶霉煤没眉媒镁每美昧寐妹媚门闷们萌蒙檬盟锰猛梦孟眯醚靡糜迷谜弥米秘觅泌蜜密幂棉眠绵冕免勉娩缅面苗描瞄藐秒渺庙妙蔑灭民抿皿敏悯闽明螟鸣铭名命谬摸"], +["c440","腀",5,"腇腉腍腎腏腒腖腗腘腛",4,"腡腢腣腤腦腨腪腫腬腯腲腳腵腶腷腸膁膃",4,"膉膋膌膍膎膐膒",5,"膙膚膞",4,"膤膥"], +["c480","膧膩膫",7,"膴",5,"膼膽膾膿臄臅臇臈臉臋臍",6,"摹蘑模膜磨摩魔抹末莫墨默沫漠寞陌谋牟某拇牡亩姆母墓暮幕募慕木目睦牧穆拿哪呐钠那娜纳氖乃奶耐奈南男难囊挠脑恼闹淖呢馁内嫩能妮霓倪泥尼拟你匿腻逆溺蔫拈年碾撵捻念娘酿鸟尿捏聂孽啮镊镍涅您柠狞凝宁"], +["c540","臔",14,"臤臥臦臨臩臫臮",4,"臵",5,"臽臿舃與",4,"舎舏舑舓舕",5,"舝舠舤舥舦舧舩舮舲舺舼舽舿"], +["c580","艀艁艂艃艅艆艈艊艌艍艎艐",7,"艙艛艜艝艞艠",7,"艩拧泞牛扭钮纽脓浓农弄奴努怒女暖虐疟挪懦糯诺哦欧鸥殴藕呕偶沤啪趴爬帕怕琶拍排牌徘湃派攀潘盘磐盼畔判叛乓庞旁耪胖抛咆刨炮袍跑泡呸胚培裴赔陪配佩沛喷盆砰抨烹澎彭蓬棚硼篷膨朋鹏捧碰坯砒霹批披劈琵毗"], +["c640","艪艫艬艭艱艵艶艷艸艻艼芀芁芃芅芆芇芉芌芐芓芔芕芖芚芛芞芠芢芣芧芲芵芶芺芻芼芿苀苂苃苅苆苉苐苖苙苚苝苢苧苨苩苪苬苭苮苰苲苳苵苶苸"], +["c680","苺苼",4,"茊茋茍茐茒茓茖茘茙茝",9,"茩茪茮茰茲茷茻茽啤脾疲皮匹痞僻屁譬篇偏片骗飘漂瓢票撇瞥拼频贫品聘乒坪苹萍平凭瓶评屏坡泼颇婆破魄迫粕剖扑铺仆莆葡菩蒲埔朴圃普浦谱曝瀑期欺栖戚妻七凄漆柒沏其棋奇歧畦崎脐齐旗祈祁骑起岂乞企启契砌器气迄弃汽泣讫掐"], +["c740","茾茿荁荂荄荅荈荊",4,"荓荕",4,"荝荢荰",6,"荹荺荾",6,"莇莈莊莋莌莍莏莐莑莔莕莖莗莙莚莝莟莡",6,"莬莭莮"], +["c780","莯莵莻莾莿菂菃菄菆菈菉菋菍菎菐菑菒菓菕菗菙菚菛菞菢菣菤菦菧菨菫菬菭恰洽牵扦钎铅千迁签仟谦乾黔钱钳前潜遣浅谴堑嵌欠歉枪呛腔羌墙蔷强抢橇锹敲悄桥瞧乔侨巧鞘撬翘峭俏窍切茄且怯窃钦侵亲秦琴勤芹擒禽寝沁青轻氢倾卿清擎晴氰情顷请庆琼穷秋丘邱球求囚酋泅趋区蛆曲躯屈驱渠"], +["c840","菮華菳",4,"菺菻菼菾菿萀萂萅萇萈萉萊萐萒",5,"萙萚萛萞",5,"萩",7,"萲",5,"萹萺萻萾",7,"葇葈葉"], +["c880","葊",6,"葒",4,"葘葝葞葟葠葢葤",4,"葪葮葯葰葲葴葷葹葻葼取娶龋趣去圈颧权醛泉全痊拳犬券劝缺炔瘸却鹊榷确雀裙群然燃冉染瓤壤攘嚷让饶扰绕惹热壬仁人忍韧任认刃妊纫扔仍日戎茸蓉荣融熔溶容绒冗揉柔肉茹蠕儒孺如辱乳汝入褥软阮蕊瑞锐闰润若弱撒洒萨腮鳃塞赛三叁"], +["c940","葽",4,"蒃蒄蒅蒆蒊蒍蒏",7,"蒘蒚蒛蒝蒞蒟蒠蒢",12,"蒰蒱蒳蒵蒶蒷蒻蒼蒾蓀蓂蓃蓅蓆蓇蓈蓋蓌蓎蓏蓒蓔蓕蓗"], +["c980","蓘",4,"蓞蓡蓢蓤蓧",4,"蓭蓮蓯蓱",10,"蓽蓾蔀蔁蔂伞散桑嗓丧搔骚扫嫂瑟色涩森僧莎砂杀刹沙纱傻啥煞筛晒珊苫杉山删煽衫闪陕擅赡膳善汕扇缮墒伤商赏晌上尚裳梢捎稍烧芍勺韶少哨邵绍奢赊蛇舌舍赦摄射慑涉社设砷申呻伸身深娠绅神沈审婶甚肾慎渗声生甥牲升绳"], +["ca40","蔃",8,"蔍蔎蔏蔐蔒蔔蔕蔖蔘蔙蔛蔜蔝蔞蔠蔢",8,"蔭",9,"蔾",4,"蕄蕅蕆蕇蕋",10], +["ca80","蕗蕘蕚蕛蕜蕝蕟",4,"蕥蕦蕧蕩",8,"蕳蕵蕶蕷蕸蕼蕽蕿薀薁省盛剩胜圣师失狮施湿诗尸虱十石拾时什食蚀实识史矢使屎驶始式示士世柿事拭誓逝势是嗜噬适仕侍释饰氏市恃室视试收手首守寿授售受瘦兽蔬枢梳殊抒输叔舒淑疏书赎孰熟薯暑曙署蜀黍鼠属术述树束戍竖墅庶数漱"], +["cb40","薂薃薆薈",6,"薐",10,"薝",6,"薥薦薧薩薫薬薭薱",5,"薸薺",6,"藂",6,"藊",4,"藑藒"], +["cb80","藔藖",5,"藝",6,"藥藦藧藨藪",14,"恕刷耍摔衰甩帅栓拴霜双爽谁水睡税吮瞬顺舜说硕朔烁斯撕嘶思私司丝死肆寺嗣四伺似饲巳松耸怂颂送宋讼诵搜艘擞嗽苏酥俗素速粟僳塑溯宿诉肃酸蒜算虽隋随绥髓碎岁穗遂隧祟孙损笋蓑梭唆缩琐索锁所塌他它她塔"], +["cc40","藹藺藼藽藾蘀",4,"蘆",10,"蘒蘓蘔蘕蘗",15,"蘨蘪",13,"蘹蘺蘻蘽蘾蘿虀"], +["cc80","虁",11,"虒虓處",4,"虛虜虝號虠虡虣",7,"獭挞蹋踏胎苔抬台泰酞太态汰坍摊贪瘫滩坛檀痰潭谭谈坦毯袒碳探叹炭汤塘搪堂棠膛唐糖倘躺淌趟烫掏涛滔绦萄桃逃淘陶讨套特藤腾疼誊梯剔踢锑提题蹄啼体替嚏惕涕剃屉天添填田甜恬舔腆挑条迢眺跳贴铁帖厅听烃"], +["cd40","虭虯虰虲",6,"蚃",6,"蚎",4,"蚔蚖",5,"蚞",4,"蚥蚦蚫蚭蚮蚲蚳蚷蚸蚹蚻",4,"蛁蛂蛃蛅蛈蛌蛍蛒蛓蛕蛖蛗蛚蛜"], +["cd80","蛝蛠蛡蛢蛣蛥蛦蛧蛨蛪蛫蛬蛯蛵蛶蛷蛺蛻蛼蛽蛿蜁蜄蜅蜆蜋蜌蜎蜏蜐蜑蜔蜖汀廷停亭庭挺艇通桐酮瞳同铜彤童桶捅筒统痛偷投头透凸秃突图徒途涂屠土吐兔湍团推颓腿蜕褪退吞屯臀拖托脱鸵陀驮驼椭妥拓唾挖哇蛙洼娃瓦袜歪外豌弯湾玩顽丸烷完碗挽晚皖惋宛婉万腕汪王亡枉网往旺望忘妄威"], +["ce40","蜙蜛蜝蜟蜠蜤蜦蜧蜨蜪蜫蜬蜭蜯蜰蜲蜳蜵蜶蜸蜹蜺蜼蜽蝀",6,"蝊蝋蝍蝏蝐蝑蝒蝔蝕蝖蝘蝚",5,"蝡蝢蝦",7,"蝯蝱蝲蝳蝵"], +["ce80","蝷蝸蝹蝺蝿螀螁螄螆螇螉螊螌螎",4,"螔螕螖螘",6,"螠",4,"巍微危韦违桅围唯惟为潍维苇萎委伟伪尾纬未蔚味畏胃喂魏位渭谓尉慰卫瘟温蚊文闻纹吻稳紊问嗡翁瓮挝蜗涡窝我斡卧握沃巫呜钨乌污诬屋无芜梧吾吴毋武五捂午舞伍侮坞戊雾晤物勿务悟误昔熙析西硒矽晰嘻吸锡牺"], +["cf40","螥螦螧螩螪螮螰螱螲螴螶螷螸螹螻螼螾螿蟁",4,"蟇蟈蟉蟌",4,"蟔",6,"蟜蟝蟞蟟蟡蟢蟣蟤蟦蟧蟨蟩蟫蟬蟭蟯",9], +["cf80","蟺蟻蟼蟽蟿蠀蠁蠂蠄",5,"蠋",7,"蠔蠗蠘蠙蠚蠜",4,"蠣稀息希悉膝夕惜熄烯溪汐犀檄袭席习媳喜铣洗系隙戏细瞎虾匣霞辖暇峡侠狭下厦夏吓掀锨先仙鲜纤咸贤衔舷闲涎弦嫌显险现献县腺馅羡宪陷限线相厢镶香箱襄湘乡翔祥详想响享项巷橡像向象萧硝霄削哮嚣销消宵淆晓"], +["d040","蠤",13,"蠳",5,"蠺蠻蠽蠾蠿衁衂衃衆",5,"衎",5,"衕衖衘衚",6,"衦衧衪衭衯衱衳衴衵衶衸衹衺"], +["d080","衻衼袀袃袆袇袉袊袌袎袏袐袑袓袔袕袗",4,"袝",4,"袣袥",5,"小孝校肖啸笑效楔些歇蝎鞋协挟携邪斜胁谐写械卸蟹懈泄泻谢屑薪芯锌欣辛新忻心信衅星腥猩惺兴刑型形邢行醒幸杏性姓兄凶胸匈汹雄熊休修羞朽嗅锈秀袖绣墟戌需虚嘘须徐许蓄酗叙旭序畜恤絮婿绪续轩喧宣悬旋玄"], +["d140","袬袮袯袰袲",4,"袸袹袺袻袽袾袿裀裃裄裇裈裊裋裌裍裏裐裑裓裖裗裚",4,"裠裡裦裧裩",6,"裲裵裶裷裺裻製裿褀褁褃",5], +["d180","褉褋",4,"褑褔",4,"褜",4,"褢褣褤褦褧褨褩褬褭褮褯褱褲褳褵褷选癣眩绚靴薛学穴雪血勋熏循旬询寻驯巡殉汛训讯逊迅压押鸦鸭呀丫芽牙蚜崖衙涯雅哑亚讶焉咽阉烟淹盐严研蜒岩延言颜阎炎沿奄掩眼衍演艳堰燕厌砚雁唁彦焰宴谚验殃央鸯秧杨扬佯疡羊洋阳氧仰痒养样漾邀腰妖瑶"], +["d240","褸",8,"襂襃襅",24,"襠",5,"襧",19,"襼"], +["d280","襽襾覀覂覄覅覇",26,"摇尧遥窑谣姚咬舀药要耀椰噎耶爷野冶也页掖业叶曳腋夜液一壹医揖铱依伊衣颐夷遗移仪胰疑沂宜姨彝椅蚁倚已乙矣以艺抑易邑屹亿役臆逸肄疫亦裔意毅忆义益溢诣议谊译异翼翌绎茵荫因殷音阴姻吟银淫寅饮尹引隐"], +["d340","覢",30,"觃觍觓觔觕觗觘觙觛觝觟觠觡觢觤觧觨觩觪觬觭觮觰觱觲觴",6], +["d380","觻",4,"訁",5,"計",21,"印英樱婴鹰应缨莹萤营荧蝇迎赢盈影颖硬映哟拥佣臃痈庸雍踊蛹咏泳涌永恿勇用幽优悠忧尤由邮铀犹油游酉有友右佑釉诱又幼迂淤于盂榆虞愚舆余俞逾鱼愉渝渔隅予娱雨与屿禹宇语羽玉域芋郁吁遇喻峪御愈欲狱育誉"], +["d440","訞",31,"訿",8,"詉",21], +["d480","詟",25,"詺",6,"浴寓裕预豫驭鸳渊冤元垣袁原援辕园员圆猿源缘远苑愿怨院曰约越跃钥岳粤月悦阅耘云郧匀陨允运蕴酝晕韵孕匝砸杂栽哉灾宰载再在咱攒暂赞赃脏葬遭糟凿藻枣早澡蚤躁噪造皂灶燥责择则泽贼怎增憎曾赠扎喳渣札轧"], +["d540","誁",7,"誋",7,"誔",46], +["d580","諃",32,"铡闸眨栅榨咋乍炸诈摘斋宅窄债寨瞻毡詹粘沾盏斩辗崭展蘸栈占战站湛绽樟章彰漳张掌涨杖丈帐账仗胀瘴障招昭找沼赵照罩兆肇召遮折哲蛰辙者锗蔗这浙珍斟真甄砧臻贞针侦枕疹诊震振镇阵蒸挣睁征狰争怔整拯正政"], +["d640","諤",34,"謈",27], +["d680","謤謥謧",30,"帧症郑证芝枝支吱蜘知肢脂汁之织职直植殖执值侄址指止趾只旨纸志挚掷至致置帜峙制智秩稚质炙痔滞治窒中盅忠钟衷终种肿重仲众舟周州洲诌粥轴肘帚咒皱宙昼骤珠株蛛朱猪诸诛逐竹烛煮拄瞩嘱主著柱助蛀贮铸筑"], +["d740","譆",31,"譧",4,"譭",25], +["d780","讇",24,"讬讱讻诇诐诪谉谞住注祝驻抓爪拽专砖转撰赚篆桩庄装妆撞壮状椎锥追赘坠缀谆准捉拙卓桌琢茁酌啄着灼浊兹咨资姿滋淄孜紫仔籽滓子自渍字鬃棕踪宗综总纵邹走奏揍租足卒族祖诅阻组钻纂嘴醉最罪尊遵昨左佐柞做作坐座"], +["d840","谸",8,"豂豃豄豅豈豊豋豍",7,"豖豗豘豙豛",5,"豣",6,"豬",6,"豴豵豶豷豻",6,"貃貄貆貇"], +["d880","貈貋貍",6,"貕貖貗貙",20,"亍丌兀丐廿卅丕亘丞鬲孬噩丨禺丿匕乇夭爻卮氐囟胤馗毓睾鼗丶亟鼐乜乩亓芈孛啬嘏仄厍厝厣厥厮靥赝匚叵匦匮匾赜卦卣刂刈刎刭刳刿剀剌剞剡剜蒯剽劂劁劐劓冂罔亻仃仉仂仨仡仫仞伛仳伢佤仵伥伧伉伫佞佧攸佚佝"], +["d940","貮",62], +["d980","賭",32,"佟佗伲伽佶佴侑侉侃侏佾佻侪佼侬侔俦俨俪俅俚俣俜俑俟俸倩偌俳倬倏倮倭俾倜倌倥倨偾偃偕偈偎偬偻傥傧傩傺僖儆僭僬僦僮儇儋仝氽佘佥俎龠汆籴兮巽黉馘冁夔勹匍訇匐凫夙兕亠兖亳衮袤亵脔裒禀嬴蠃羸冫冱冽冼"], +["da40","贎",14,"贠赑赒赗赟赥赨赩赪赬赮赯赱赲赸",8,"趂趃趆趇趈趉趌",4,"趒趓趕",9,"趠趡"], +["da80","趢趤",12,"趲趶趷趹趻趽跀跁跂跅跇跈跉跊跍跐跒跓跔凇冖冢冥讠讦讧讪讴讵讷诂诃诋诏诎诒诓诔诖诘诙诜诟诠诤诨诩诮诰诳诶诹诼诿谀谂谄谇谌谏谑谒谔谕谖谙谛谘谝谟谠谡谥谧谪谫谮谯谲谳谵谶卩卺阝阢阡阱阪阽阼陂陉陔陟陧陬陲陴隈隍隗隰邗邛邝邙邬邡邴邳邶邺"], +["db40","跕跘跙跜跠跡跢跥跦跧跩跭跮跰跱跲跴跶跼跾",6,"踆踇踈踋踍踎踐踑踒踓踕",7,"踠踡踤",4,"踫踭踰踲踳踴踶踷踸踻踼踾"], +["db80","踿蹃蹅蹆蹌",4,"蹓",5,"蹚",11,"蹧蹨蹪蹫蹮蹱邸邰郏郅邾郐郄郇郓郦郢郜郗郛郫郯郾鄄鄢鄞鄣鄱鄯鄹酃酆刍奂劢劬劭劾哿勐勖勰叟燮矍廴凵凼鬯厶弁畚巯坌垩垡塾墼壅壑圩圬圪圳圹圮圯坜圻坂坩垅坫垆坼坻坨坭坶坳垭垤垌垲埏垧垴垓垠埕埘埚埙埒垸埴埯埸埤埝"], +["dc40","蹳蹵蹷",4,"蹽蹾躀躂躃躄躆躈",6,"躑躒躓躕",6,"躝躟",11,"躭躮躰躱躳",6,"躻",7], +["dc80","軃",10,"軏",21,"堋堍埽埭堀堞堙塄堠塥塬墁墉墚墀馨鼙懿艹艽艿芏芊芨芄芎芑芗芙芫芸芾芰苈苊苣芘芷芮苋苌苁芩芴芡芪芟苄苎芤苡茉苷苤茏茇苜苴苒苘茌苻苓茑茚茆茔茕苠苕茜荑荛荜茈莒茼茴茱莛荞茯荏荇荃荟荀茗荠茭茺茳荦荥"], +["dd40","軥",62], +["dd80","輤",32,"荨茛荩荬荪荭荮莰荸莳莴莠莪莓莜莅荼莶莩荽莸荻莘莞莨莺莼菁萁菥菘堇萘萋菝菽菖萜萸萑萆菔菟萏萃菸菹菪菅菀萦菰菡葜葑葚葙葳蒇蒈葺蒉葸萼葆葩葶蒌蒎萱葭蓁蓍蓐蓦蒽蓓蓊蒿蒺蓠蒡蒹蒴蒗蓥蓣蔌甍蔸蓰蔹蔟蔺"], +["de40","轅",32,"轪辀辌辒辝辠辡辢辤辥辦辧辪辬辭辮辯農辳辴辵辷辸辺辻込辿迀迃迆"], +["de80","迉",4,"迏迒迖迗迚迠迡迣迧迬迯迱迲迴迵迶迺迻迼迾迿逇逈逌逎逓逕逘蕖蔻蓿蓼蕙蕈蕨蕤蕞蕺瞢蕃蕲蕻薤薨薇薏蕹薮薜薅薹薷薰藓藁藜藿蘧蘅蘩蘖蘼廾弈夼奁耷奕奚奘匏尢尥尬尴扌扪抟抻拊拚拗拮挢拶挹捋捃掭揶捱捺掎掴捭掬掊捩掮掼揲揸揠揿揄揞揎摒揆掾摅摁搋搛搠搌搦搡摞撄摭撖"], +["df40","這逜連逤逥逧",5,"逰",4,"逷逹逺逽逿遀遃遅遆遈",4,"過達違遖遙遚遜",5,"遤遦遧適遪遫遬遯",4,"遶",6,"遾邁"], +["df80","還邅邆邇邉邊邌",4,"邒邔邖邘邚邜邞邟邠邤邥邧邨邩邫邭邲邷邼邽邿郀摺撷撸撙撺擀擐擗擤擢攉攥攮弋忒甙弑卟叱叽叩叨叻吒吖吆呋呒呓呔呖呃吡呗呙吣吲咂咔呷呱呤咚咛咄呶呦咝哐咭哂咴哒咧咦哓哔呲咣哕咻咿哌哙哚哜咩咪咤哝哏哞唛哧唠哽唔哳唢唣唏唑唧唪啧喏喵啉啭啁啕唿啐唼"], +["e040","郂郃郆郈郉郋郌郍郒郔郕郖郘郙郚郞郟郠郣郤郥郩郪郬郮郰郱郲郳郵郶郷郹郺郻郼郿鄀鄁鄃鄅",19,"鄚鄛鄜"], +["e080","鄝鄟鄠鄡鄤",10,"鄰鄲",6,"鄺",8,"酄唷啖啵啶啷唳唰啜喋嗒喃喱喹喈喁喟啾嗖喑啻嗟喽喾喔喙嗪嗷嗉嘟嗑嗫嗬嗔嗦嗝嗄嗯嗥嗲嗳嗌嗍嗨嗵嗤辔嘞嘈嘌嘁嘤嘣嗾嘀嘧嘭噘嘹噗嘬噍噢噙噜噌噔嚆噤噱噫噻噼嚅嚓嚯囔囗囝囡囵囫囹囿圄圊圉圜帏帙帔帑帱帻帼"], +["e140","酅酇酈酑酓酔酕酖酘酙酛酜酟酠酦酧酨酫酭酳酺酻酼醀",4,"醆醈醊醎醏醓",6,"醜",5,"醤",5,"醫醬醰醱醲醳醶醷醸醹醻"], +["e180","醼",10,"釈釋釐釒",9,"針",8,"帷幄幔幛幞幡岌屺岍岐岖岈岘岙岑岚岜岵岢岽岬岫岱岣峁岷峄峒峤峋峥崂崃崧崦崮崤崞崆崛嵘崾崴崽嵬嵛嵯嵝嵫嵋嵊嵩嵴嶂嶙嶝豳嶷巅彳彷徂徇徉後徕徙徜徨徭徵徼衢彡犭犰犴犷犸狃狁狎狍狒狨狯狩狲狴狷猁狳猃狺"], +["e240","釦",62], +["e280","鈥",32,"狻猗猓猡猊猞猝猕猢猹猥猬猸猱獐獍獗獠獬獯獾舛夥飧夤夂饣饧",5,"饴饷饽馀馄馇馊馍馐馑馓馔馕庀庑庋庖庥庠庹庵庾庳赓廒廑廛廨廪膺忄忉忖忏怃忮怄忡忤忾怅怆忪忭忸怙怵怦怛怏怍怩怫怊怿怡恸恹恻恺恂"], +["e340","鉆",45,"鉵",16], +["e380","銆",7,"銏",24,"恪恽悖悚悭悝悃悒悌悛惬悻悱惝惘惆惚悴愠愦愕愣惴愀愎愫慊慵憬憔憧憷懔懵忝隳闩闫闱闳闵闶闼闾阃阄阆阈阊阋阌阍阏阒阕阖阗阙阚丬爿戕氵汔汜汊沣沅沐沔沌汨汩汴汶沆沩泐泔沭泷泸泱泗沲泠泖泺泫泮沱泓泯泾"], +["e440","銨",5,"銯",24,"鋉",31], +["e480","鋩",32,"洹洧洌浃浈洇洄洙洎洫浍洮洵洚浏浒浔洳涑浯涞涠浞涓涔浜浠浼浣渚淇淅淞渎涿淠渑淦淝淙渖涫渌涮渫湮湎湫溲湟溆湓湔渲渥湄滟溱溘滠漭滢溥溧溽溻溷滗溴滏溏滂溟潢潆潇漤漕滹漯漶潋潴漪漉漩澉澍澌潸潲潼潺濑"], +["e540","錊",51,"錿",10], +["e580","鍊",31,"鍫濉澧澹澶濂濡濮濞濠濯瀚瀣瀛瀹瀵灏灞宀宄宕宓宥宸甯骞搴寤寮褰寰蹇謇辶迓迕迥迮迤迩迦迳迨逅逄逋逦逑逍逖逡逵逶逭逯遄遑遒遐遨遘遢遛暹遴遽邂邈邃邋彐彗彖彘尻咫屐屙孱屣屦羼弪弩弭艴弼鬻屮妁妃妍妩妪妣"], +["e640","鍬",34,"鎐",27], +["e680","鎬",29,"鏋鏌鏍妗姊妫妞妤姒妲妯姗妾娅娆姝娈姣姘姹娌娉娲娴娑娣娓婀婧婊婕娼婢婵胬媪媛婷婺媾嫫媲嫒嫔媸嫠嫣嫱嫖嫦嫘嫜嬉嬗嬖嬲嬷孀尕尜孚孥孳孑孓孢驵驷驸驺驿驽骀骁骅骈骊骐骒骓骖骘骛骜骝骟骠骢骣骥骧纟纡纣纥纨纩"], +["e740","鏎",7,"鏗",54], +["e780","鐎",32,"纭纰纾绀绁绂绉绋绌绐绔绗绛绠绡绨绫绮绯绱绲缍绶绺绻绾缁缂缃缇缈缋缌缏缑缒缗缙缜缛缟缡",6,"缪缫缬缭缯",4,"缵幺畿巛甾邕玎玑玮玢玟珏珂珑玷玳珀珉珈珥珙顼琊珩珧珞玺珲琏琪瑛琦琥琨琰琮琬"], +["e840","鐯",14,"鐿",43,"鑬鑭鑮鑯"], +["e880","鑰",20,"钑钖钘铇铏铓铔铚铦铻锜锠琛琚瑁瑜瑗瑕瑙瑷瑭瑾璜璎璀璁璇璋璞璨璩璐璧瓒璺韪韫韬杌杓杞杈杩枥枇杪杳枘枧杵枨枞枭枋杷杼柰栉柘栊柩枰栌柙枵柚枳柝栀柃枸柢栎柁柽栲栳桠桡桎桢桄桤梃栝桕桦桁桧桀栾桊桉栩梵梏桴桷梓桫棂楮棼椟椠棹"], +["e940","锧锳锽镃镈镋镕镚镠镮镴镵長",7,"門",42], +["e980","閫",32,"椤棰椋椁楗棣椐楱椹楠楂楝榄楫榀榘楸椴槌榇榈槎榉楦楣楹榛榧榻榫榭槔榱槁槊槟榕槠榍槿樯槭樗樘橥槲橄樾檠橐橛樵檎橹樽樨橘橼檑檐檩檗檫猷獒殁殂殇殄殒殓殍殚殛殡殪轫轭轱轲轳轵轶轸轷轹轺轼轾辁辂辄辇辋"], +["ea40","闌",27,"闬闿阇阓阘阛阞阠阣",6,"阫阬阭阯阰阷阸阹阺阾陁陃陊陎陏陑陒陓陖陗"], +["ea80","陘陙陚陜陝陞陠陣陥陦陫陭",4,"陳陸",12,"隇隉隊辍辎辏辘辚軎戋戗戛戟戢戡戥戤戬臧瓯瓴瓿甏甑甓攴旮旯旰昊昙杲昃昕昀炅曷昝昴昱昶昵耆晟晔晁晏晖晡晗晷暄暌暧暝暾曛曜曦曩贲贳贶贻贽赀赅赆赈赉赇赍赕赙觇觊觋觌觎觏觐觑牮犟牝牦牯牾牿犄犋犍犏犒挈挲掰"], +["eb40","隌階隑隒隓隕隖隚際隝",9,"隨",7,"隱隲隴隵隷隸隺隻隿雂雃雈雊雋雐雑雓雔雖",9,"雡",6,"雫"], +["eb80","雬雭雮雰雱雲雴雵雸雺電雼雽雿霂霃霅霊霋霌霐霑霒霔霕霗",4,"霝霟霠搿擘耄毪毳毽毵毹氅氇氆氍氕氘氙氚氡氩氤氪氲攵敕敫牍牒牖爰虢刖肟肜肓肼朊肽肱肫肭肴肷胧胨胩胪胛胂胄胙胍胗朐胝胫胱胴胭脍脎胲胼朕脒豚脶脞脬脘脲腈腌腓腴腙腚腱腠腩腼腽腭腧塍媵膈膂膑滕膣膪臌朦臊膻"], +["ec40","霡",8,"霫霬霮霯霱霳",4,"霺霻霼霽霿",18,"靔靕靗靘靚靜靝靟靣靤靦靧靨靪",7], +["ec80","靲靵靷",4,"靽",7,"鞆",4,"鞌鞎鞏鞐鞓鞕鞖鞗鞙",4,"臁膦欤欷欹歃歆歙飑飒飓飕飙飚殳彀毂觳斐齑斓於旆旄旃旌旎旒旖炀炜炖炝炻烀炷炫炱烨烊焐焓焖焯焱煳煜煨煅煲煊煸煺熘熳熵熨熠燠燔燧燹爝爨灬焘煦熹戾戽扃扈扉礻祀祆祉祛祜祓祚祢祗祠祯祧祺禅禊禚禧禳忑忐"], +["ed40","鞞鞟鞡鞢鞤",6,"鞬鞮鞰鞱鞳鞵",46], +["ed80","韤韥韨韮",4,"韴韷",23,"怼恝恚恧恁恙恣悫愆愍慝憩憝懋懑戆肀聿沓泶淼矶矸砀砉砗砘砑斫砭砜砝砹砺砻砟砼砥砬砣砩硎硭硖硗砦硐硇硌硪碛碓碚碇碜碡碣碲碹碥磔磙磉磬磲礅磴礓礤礞礴龛黹黻黼盱眄眍盹眇眈眚眢眙眭眦眵眸睐睑睇睃睚睨"], +["ee40","頏",62], +["ee80","顎",32,"睢睥睿瞍睽瞀瞌瞑瞟瞠瞰瞵瞽町畀畎畋畈畛畲畹疃罘罡罟詈罨罴罱罹羁罾盍盥蠲钅钆钇钋钊钌钍钏钐钔钗钕钚钛钜钣钤钫钪钭钬钯钰钲钴钶",4,"钼钽钿铄铈",6,"铐铑铒铕铖铗铙铘铛铞铟铠铢铤铥铧铨铪"], +["ef40","顯",5,"颋颎颒颕颙颣風",37,"飏飐飔飖飗飛飜飝飠",4], +["ef80","飥飦飩",30,"铩铫铮铯铳铴铵铷铹铼铽铿锃锂锆锇锉锊锍锎锏锒",4,"锘锛锝锞锟锢锪锫锩锬锱锲锴锶锷锸锼锾锿镂锵镄镅镆镉镌镎镏镒镓镔镖镗镘镙镛镞镟镝镡镢镤",8,"镯镱镲镳锺矧矬雉秕秭秣秫稆嵇稃稂稞稔"], +["f040","餈",4,"餎餏餑",28,"餯",26], +["f080","饊",9,"饖",12,"饤饦饳饸饹饻饾馂馃馉稹稷穑黏馥穰皈皎皓皙皤瓞瓠甬鸠鸢鸨",4,"鸲鸱鸶鸸鸷鸹鸺鸾鹁鹂鹄鹆鹇鹈鹉鹋鹌鹎鹑鹕鹗鹚鹛鹜鹞鹣鹦",6,"鹱鹭鹳疒疔疖疠疝疬疣疳疴疸痄疱疰痃痂痖痍痣痨痦痤痫痧瘃痱痼痿瘐瘀瘅瘌瘗瘊瘥瘘瘕瘙"], +["f140","馌馎馚",10,"馦馧馩",47], +["f180","駙",32,"瘛瘼瘢瘠癀瘭瘰瘿瘵癃瘾瘳癍癞癔癜癖癫癯翊竦穸穹窀窆窈窕窦窠窬窨窭窳衤衩衲衽衿袂袢裆袷袼裉裢裎裣裥裱褚裼裨裾裰褡褙褓褛褊褴褫褶襁襦襻疋胥皲皴矜耒耔耖耜耠耢耥耦耧耩耨耱耋耵聃聆聍聒聩聱覃顸颀颃"], +["f240","駺",62], +["f280","騹",32,"颉颌颍颏颔颚颛颞颟颡颢颥颦虍虔虬虮虿虺虼虻蚨蚍蚋蚬蚝蚧蚣蚪蚓蚩蚶蛄蚵蛎蚰蚺蚱蚯蛉蛏蚴蛩蛱蛲蛭蛳蛐蜓蛞蛴蛟蛘蛑蜃蜇蛸蜈蜊蜍蜉蜣蜻蜞蜥蜮蜚蜾蝈蜴蜱蜩蜷蜿螂蜢蝽蝾蝻蝠蝰蝌蝮螋蝓蝣蝼蝤蝙蝥螓螯螨蟒"], +["f340","驚",17,"驲骃骉骍骎骔骕骙骦骩",6,"骲骳骴骵骹骻骽骾骿髃髄髆",4,"髍髎髏髐髒體髕髖髗髙髚髛髜"], +["f380","髝髞髠髢髣髤髥髧髨髩髪髬髮髰",8,"髺髼",6,"鬄鬅鬆蟆螈螅螭螗螃螫蟥螬螵螳蟋蟓螽蟑蟀蟊蟛蟪蟠蟮蠖蠓蟾蠊蠛蠡蠹蠼缶罂罄罅舐竺竽笈笃笄笕笊笫笏筇笸笪笙笮笱笠笥笤笳笾笞筘筚筅筵筌筝筠筮筻筢筲筱箐箦箧箸箬箝箨箅箪箜箢箫箴篑篁篌篝篚篥篦篪簌篾篼簏簖簋"], +["f440","鬇鬉",5,"鬐鬑鬒鬔",10,"鬠鬡鬢鬤",10,"鬰鬱鬳",7,"鬽鬾鬿魀魆魊魋魌魎魐魒魓魕",5], +["f480","魛",32,"簟簪簦簸籁籀臾舁舂舄臬衄舡舢舣舭舯舨舫舸舻舳舴舾艄艉艋艏艚艟艨衾袅袈裘裟襞羝羟羧羯羰羲籼敉粑粝粜粞粢粲粼粽糁糇糌糍糈糅糗糨艮暨羿翎翕翥翡翦翩翮翳糸絷綦綮繇纛麸麴赳趄趔趑趱赧赭豇豉酊酐酎酏酤"], +["f540","魼",62], +["f580","鮻",32,"酢酡酰酩酯酽酾酲酴酹醌醅醐醍醑醢醣醪醭醮醯醵醴醺豕鹾趸跫踅蹙蹩趵趿趼趺跄跖跗跚跞跎跏跛跆跬跷跸跣跹跻跤踉跽踔踝踟踬踮踣踯踺蹀踹踵踽踱蹉蹁蹂蹑蹒蹊蹰蹶蹼蹯蹴躅躏躔躐躜躞豸貂貊貅貘貔斛觖觞觚觜"], +["f640","鯜",62], +["f680","鰛",32,"觥觫觯訾謦靓雩雳雯霆霁霈霏霎霪霭霰霾龀龃龅",5,"龌黾鼋鼍隹隼隽雎雒瞿雠銎銮鋈錾鍪鏊鎏鐾鑫鱿鲂鲅鲆鲇鲈稣鲋鲎鲐鲑鲒鲔鲕鲚鲛鲞",5,"鲥",4,"鲫鲭鲮鲰",7,"鲺鲻鲼鲽鳄鳅鳆鳇鳊鳋"], +["f740","鰼",62], +["f780","鱻鱽鱾鲀鲃鲄鲉鲊鲌鲏鲓鲖鲗鲘鲙鲝鲪鲬鲯鲹鲾",4,"鳈鳉鳑鳒鳚鳛鳠鳡鳌",4,"鳓鳔鳕鳗鳘鳙鳜鳝鳟鳢靼鞅鞑鞒鞔鞯鞫鞣鞲鞴骱骰骷鹘骶骺骼髁髀髅髂髋髌髑魅魃魇魉魈魍魑飨餍餮饕饔髟髡髦髯髫髻髭髹鬈鬏鬓鬟鬣麽麾縻麂麇麈麋麒鏖麝麟黛黜黝黠黟黢黩黧黥黪黯鼢鼬鼯鼹鼷鼽鼾齄"], +["f840","鳣",62], +["f880","鴢",32], +["f940","鵃",62], +["f980","鶂",32], +["fa40","鶣",62], +["fa80","鷢",32], +["fb40","鸃",27,"鸤鸧鸮鸰鸴鸻鸼鹀鹍鹐鹒鹓鹔鹖鹙鹝鹟鹠鹡鹢鹥鹮鹯鹲鹴",9,"麀"], +["fb80","麁麃麄麅麆麉麊麌",5,"麔",8,"麞麠",5,"麧麨麩麪"], +["fc40","麫",8,"麵麶麷麹麺麼麿",4,"黅黆黇黈黊黋黌黐黒黓黕黖黗黙黚點黡黣黤黦黨黫黬黭黮黰",8,"黺黽黿",6], +["fc80","鼆",4,"鼌鼏鼑鼒鼔鼕鼖鼘鼚",5,"鼡鼣",8,"鼭鼮鼰鼱"], +["fd40","鼲",4,"鼸鼺鼼鼿",4,"齅",10,"齒",38], +["fd80","齹",5,"龁龂龍",11,"龜龝龞龡",4,"郎凉秊裏隣"], +["fe40","兀嗀﨎﨏﨑﨓﨔礼﨟蘒﨡﨣﨤﨧﨨﨩"] +] diff --git a/backend/node_modules/iconv-lite/encodings/tables/cp949.json b/backend/node_modules/iconv-lite/encodings/tables/cp949.json new file mode 100644 index 0000000000000000000000000000000000000000..2022a007ff7ac97ce51167903d116eec42bffd9a --- /dev/null +++ b/backend/node_modules/iconv-lite/encodings/tables/cp949.json @@ -0,0 +1,273 @@ +[ +["0","\u0000",127], +["8141","갂갃갅갆갋",4,"갘갞갟갡갢갣갥",6,"갮갲갳갴"], +["8161","갵갶갷갺갻갽갾갿걁",9,"걌걎",5,"걕"], +["8181","걖걗걙걚걛걝",18,"걲걳걵걶걹걻",4,"겂겇겈겍겎겏겑겒겓겕",6,"겞겢",5,"겫겭겮겱",6,"겺겾겿곀곂곃곅곆곇곉곊곋곍",7,"곖곘",7,"곢곣곥곦곩곫곭곮곲곴곷",4,"곾곿괁괂괃괅괇",4,"괎괐괒괓"], +["8241","괔괕괖괗괙괚괛괝괞괟괡",7,"괪괫괮",5], +["8261","괶괷괹괺괻괽",6,"굆굈굊",5,"굑굒굓굕굖굗"], +["8281","굙",7,"굢굤",7,"굮굯굱굲굷굸굹굺굾궀궃",4,"궊궋궍궎궏궑",10,"궞",5,"궥",17,"궸",7,"귂귃귅귆귇귉",6,"귒귔",7,"귝귞귟귡귢귣귥",18], +["8341","귺귻귽귾긂",5,"긊긌긎",5,"긕",7], +["8361","긝",18,"긲긳긵긶긹긻긼"], +["8381","긽긾긿깂깄깇깈깉깋깏깑깒깓깕깗",4,"깞깢깣깤깦깧깪깫깭깮깯깱",6,"깺깾",5,"꺆",5,"꺍",46,"꺿껁껂껃껅",6,"껎껒",5,"껚껛껝",8], +["8441","껦껧껩껪껬껮",5,"껵껶껷껹껺껻껽",8], +["8461","꼆꼉꼊꼋꼌꼎꼏꼑",18], +["8481","꼤",7,"꼮꼯꼱꼳꼵",6,"꼾꽀꽄꽅꽆꽇꽊",5,"꽑",10,"꽞",5,"꽦",18,"꽺",5,"꾁꾂꾃꾅꾆꾇꾉",6,"꾒꾓꾔꾖",5,"꾝",26,"꾺꾻꾽꾾"], +["8541","꾿꿁",5,"꿊꿌꿏",4,"꿕",6,"꿝",4], +["8561","꿢",5,"꿪",5,"꿲꿳꿵꿶꿷꿹",6,"뀂뀃"], +["8581","뀅",6,"뀍뀎뀏뀑뀒뀓뀕",6,"뀞",9,"뀩",26,"끆끇끉끋끍끏끐끑끒끖끘끚끛끜끞",29,"끾끿낁낂낃낅",6,"낎낐낒",5,"낛낝낞낣낤"], +["8641","낥낦낧낪낰낲낶낷낹낺낻낽",6,"냆냊",5,"냒"], +["8661","냓냕냖냗냙",6,"냡냢냣냤냦",10], +["8681","냱",22,"넊넍넎넏넑넔넕넖넗넚넞",4,"넦넧넩넪넫넭",6,"넶넺",5,"녂녃녅녆녇녉",6,"녒녓녖녗녙녚녛녝녞녟녡",22,"녺녻녽녾녿놁놃",4,"놊놌놎놏놐놑놕놖놗놙놚놛놝"], +["8741","놞",9,"놩",15], +["8761","놹",18,"뇍뇎뇏뇑뇒뇓뇕"], +["8781","뇖",5,"뇞뇠",7,"뇪뇫뇭뇮뇯뇱",7,"뇺뇼뇾",5,"눆눇눉눊눍",6,"눖눘눚",5,"눡",18,"눵",6,"눽",26,"뉙뉚뉛뉝뉞뉟뉡",6,"뉪",4], +["8841","뉯",4,"뉶",5,"뉽",6,"늆늇늈늊",4], +["8861","늏늒늓늕늖늗늛",4,"늢늤늧늨늩늫늭늮늯늱늲늳늵늶늷"], +["8881","늸",15,"닊닋닍닎닏닑닓",4,"닚닜닞닟닠닡닣닧닩닪닰닱닲닶닼닽닾댂댃댅댆댇댉",6,"댒댖",5,"댝",54,"덗덙덚덝덠덡덢덣"], +["8941","덦덨덪덬덭덯덲덳덵덶덷덹",6,"뎂뎆",5,"뎍"], +["8961","뎎뎏뎑뎒뎓뎕",10,"뎢",5,"뎩뎪뎫뎭"], +["8981","뎮",21,"돆돇돉돊돍돏돑돒돓돖돘돚돜돞돟돡돢돣돥돦돧돩",18,"돽",18,"됑",6,"됙됚됛됝됞됟됡",6,"됪됬",7,"됵",15], +["8a41","둅",10,"둒둓둕둖둗둙",6,"둢둤둦"], +["8a61","둧",4,"둭",18,"뒁뒂"], +["8a81","뒃",4,"뒉",19,"뒞",5,"뒥뒦뒧뒩뒪뒫뒭",7,"뒶뒸뒺",5,"듁듂듃듅듆듇듉",6,"듑듒듓듔듖",5,"듞듟듡듢듥듧",4,"듮듰듲",5,"듹",26,"딖딗딙딚딝"], +["8b41","딞",5,"딦딫",4,"딲딳딵딶딷딹",6,"땂땆"], +["8b61","땇땈땉땊땎땏땑땒땓땕",6,"땞땢",8], +["8b81","땫",52,"떢떣떥떦떧떩떬떭떮떯떲떶",4,"떾떿뗁뗂뗃뗅",6,"뗎뗒",5,"뗙",18,"뗭",18], +["8c41","똀",15,"똒똓똕똖똗똙",4], +["8c61","똞",6,"똦",5,"똭",6,"똵",5], +["8c81","똻",12,"뙉",26,"뙥뙦뙧뙩",50,"뚞뚟뚡뚢뚣뚥",5,"뚭뚮뚯뚰뚲",16], +["8d41","뛃",16,"뛕",8], +["8d61","뛞",17,"뛱뛲뛳뛵뛶뛷뛹뛺"], +["8d81","뛻",4,"뜂뜃뜄뜆",33,"뜪뜫뜭뜮뜱",6,"뜺뜼",7,"띅띆띇띉띊띋띍",6,"띖",9,"띡띢띣띥띦띧띩",6,"띲띴띶",5,"띾띿랁랂랃랅",6,"랎랓랔랕랚랛랝랞"], +["8e41","랟랡",6,"랪랮",5,"랶랷랹",8], +["8e61","럂",4,"럈럊",19], +["8e81","럞",13,"럮럯럱럲럳럵",6,"럾렂",4,"렊렋렍렎렏렑",6,"렚렜렞",5,"렦렧렩렪렫렭",6,"렶렺",5,"롁롂롃롅",11,"롒롔",7,"롞롟롡롢롣롥",6,"롮롰롲",5,"롹롺롻롽",7], +["8f41","뢅",7,"뢎",17], +["8f61","뢠",7,"뢩",6,"뢱뢲뢳뢵뢶뢷뢹",4], +["8f81","뢾뢿룂룄룆",5,"룍룎룏룑룒룓룕",7,"룞룠룢",5,"룪룫룭룮룯룱",6,"룺룼룾",5,"뤅",18,"뤙",6,"뤡",26,"뤾뤿륁륂륃륅",6,"륍륎륐륒",5], +["9041","륚륛륝륞륟륡",6,"륪륬륮",5,"륶륷륹륺륻륽"], +["9061","륾",5,"릆릈릋릌릏",15], +["9081","릟",12,"릮릯릱릲릳릵",6,"릾맀맂",5,"맊맋맍맓",4,"맚맜맟맠맢맦맧맩맪맫맭",6,"맶맻",4,"먂",5,"먉",11,"먖",33,"먺먻먽먾먿멁멃멄멅멆"], +["9141","멇멊멌멏멐멑멒멖멗멙멚멛멝",6,"멦멪",5], +["9161","멲멳멵멶멷멹",9,"몆몈몉몊몋몍",5], +["9181","몓",20,"몪몭몮몯몱몳",4,"몺몼몾",5,"뫅뫆뫇뫉",14,"뫚",33,"뫽뫾뫿묁묂묃묅",7,"묎묐묒",5,"묙묚묛묝묞묟묡",6], +["9241","묨묪묬",7,"묷묹묺묿",4,"뭆뭈뭊뭋뭌뭎뭑뭒"], +["9261","뭓뭕뭖뭗뭙",7,"뭢뭤",7,"뭭",4], +["9281","뭲",21,"뮉뮊뮋뮍뮎뮏뮑",18,"뮥뮦뮧뮩뮪뮫뮭",6,"뮵뮶뮸",7,"믁믂믃믅믆믇믉",6,"믑믒믔",35,"믺믻믽믾밁"], +["9341","밃",4,"밊밎밐밒밓밙밚밠밡밢밣밦밨밪밫밬밮밯밲밳밵"], +["9361","밶밷밹",6,"뱂뱆뱇뱈뱊뱋뱎뱏뱑",8], +["9381","뱚뱛뱜뱞",37,"벆벇벉벊벍벏",4,"벖벘벛",4,"벢벣벥벦벩",6,"벲벶",5,"벾벿볁볂볃볅",7,"볎볒볓볔볖볗볙볚볛볝",22,"볷볹볺볻볽"], +["9441","볾",5,"봆봈봊",5,"봑봒봓봕",8], +["9461","봞",5,"봥",6,"봭",12], +["9481","봺",5,"뵁",6,"뵊뵋뵍뵎뵏뵑",6,"뵚",9,"뵥뵦뵧뵩",22,"붂붃붅붆붋",4,"붒붔붖붗붘붛붝",6,"붥",10,"붱",6,"붹",24], +["9541","뷒뷓뷖뷗뷙뷚뷛뷝",11,"뷪",5,"뷱"], +["9561","뷲뷳뷵뷶뷷뷹",6,"븁븂븄븆",5,"븎븏븑븒븓"], +["9581","븕",6,"븞븠",35,"빆빇빉빊빋빍빏",4,"빖빘빜빝빞빟빢빣빥빦빧빩빫",4,"빲빶",4,"빾빿뺁뺂뺃뺅",6,"뺎뺒",5,"뺚",13,"뺩",14], +["9641","뺸",23,"뻒뻓"], +["9661","뻕뻖뻙",6,"뻡뻢뻦",5,"뻭",8], +["9681","뻶",10,"뼂",5,"뼊",13,"뼚뼞",33,"뽂뽃뽅뽆뽇뽉",6,"뽒뽓뽔뽖",44], +["9741","뾃",16,"뾕",8], +["9761","뾞",17,"뾱",7], +["9781","뾹",11,"뿆",5,"뿎뿏뿑뿒뿓뿕",6,"뿝뿞뿠뿢",89,"쀽쀾쀿"], +["9841","쁀",16,"쁒",5,"쁙쁚쁛"], +["9861","쁝쁞쁟쁡",6,"쁪",15], +["9881","쁺",21,"삒삓삕삖삗삙",6,"삢삤삦",5,"삮삱삲삷",4,"삾샂샃샄샆샇샊샋샍샎샏샑",6,"샚샞",5,"샦샧샩샪샫샭",6,"샶샸샺",5,"섁섂섃섅섆섇섉",6,"섑섒섓섔섖",5,"섡섢섥섨섩섪섫섮"], +["9941","섲섳섴섵섷섺섻섽섾섿셁",6,"셊셎",5,"셖셗"], +["9961","셙셚셛셝",6,"셦셪",5,"셱셲셳셵셶셷셹셺셻"], +["9981","셼",8,"솆",5,"솏솑솒솓솕솗",4,"솞솠솢솣솤솦솧솪솫솭솮솯솱",11,"솾",5,"쇅쇆쇇쇉쇊쇋쇍",6,"쇕쇖쇙",6,"쇡쇢쇣쇥쇦쇧쇩",6,"쇲쇴",7,"쇾쇿숁숂숃숅",6,"숎숐숒",5,"숚숛숝숞숡숢숣"], +["9a41","숤숥숦숧숪숬숮숰숳숵",16], +["9a61","쉆쉇쉉",6,"쉒쉓쉕쉖쉗쉙",6,"쉡쉢쉣쉤쉦"], +["9a81","쉧",4,"쉮쉯쉱쉲쉳쉵",6,"쉾슀슂",5,"슊",5,"슑",6,"슙슚슜슞",5,"슦슧슩슪슫슮",5,"슶슸슺",33,"싞싟싡싢싥",5,"싮싰싲싳싴싵싷싺싽싾싿쌁",6,"쌊쌋쌎쌏"], +["9b41","쌐쌑쌒쌖쌗쌙쌚쌛쌝",6,"쌦쌧쌪",8], +["9b61","쌳",17,"썆",7], +["9b81","썎",25,"썪썫썭썮썯썱썳",4,"썺썻썾",5,"쎅쎆쎇쎉쎊쎋쎍",50,"쏁",22,"쏚"], +["9c41","쏛쏝쏞쏡쏣",4,"쏪쏫쏬쏮",5,"쏶쏷쏹",5], +["9c61","쏿",8,"쐉",6,"쐑",9], +["9c81","쐛",8,"쐥",6,"쐭쐮쐯쐱쐲쐳쐵",6,"쐾",9,"쑉",26,"쑦쑧쑩쑪쑫쑭",6,"쑶쑷쑸쑺",5,"쒁",18,"쒕",6,"쒝",12], +["9d41","쒪",13,"쒹쒺쒻쒽",8], +["9d61","쓆",25], +["9d81","쓠",8,"쓪",5,"쓲쓳쓵쓶쓷쓹쓻쓼쓽쓾씂",9,"씍씎씏씑씒씓씕",6,"씝",10,"씪씫씭씮씯씱",6,"씺씼씾",5,"앆앇앋앏앐앑앒앖앚앛앜앟앢앣앥앦앧앩",6,"앲앶",5,"앾앿얁얂얃얅얆얈얉얊얋얎얐얒얓얔"], +["9e41","얖얙얚얛얝얞얟얡",7,"얪",9,"얶"], +["9e61","얷얺얿",4,"엋엍엏엒엓엕엖엗엙",6,"엢엤엦엧"], +["9e81","엨엩엪엫엯엱엲엳엵엸엹엺엻옂옃옄옉옊옋옍옎옏옑",6,"옚옝",6,"옦옧옩옪옫옯옱옲옶옸옺옼옽옾옿왂왃왅왆왇왉",6,"왒왖",5,"왞왟왡",10,"왭왮왰왲",5,"왺왻왽왾왿욁",6,"욊욌욎",5,"욖욗욙욚욛욝",6,"욦"], +["9f41","욨욪",5,"욲욳욵욶욷욻",4,"웂웄웆",5,"웎"], +["9f61","웏웑웒웓웕",6,"웞웟웢",5,"웪웫웭웮웯웱웲"], +["9f81","웳",4,"웺웻웼웾",5,"윆윇윉윊윋윍",6,"윖윘윚",5,"윢윣윥윦윧윩",6,"윲윴윶윸윹윺윻윾윿읁읂읃읅",4,"읋읎읐읙읚읛읝읞읟읡",6,"읩읪읬",7,"읶읷읹읺읻읿잀잁잂잆잋잌잍잏잒잓잕잙잛",4,"잢잧",4,"잮잯잱잲잳잵잶잷"], +["a041","잸잹잺잻잾쟂",5,"쟊쟋쟍쟏쟑",6,"쟙쟚쟛쟜"], +["a061","쟞",5,"쟥쟦쟧쟩쟪쟫쟭",13], +["a081","쟻",4,"젂젃젅젆젇젉젋",4,"젒젔젗",4,"젞젟젡젢젣젥",6,"젮젰젲",5,"젹젺젻젽젾젿졁",6,"졊졋졎",5,"졕",26,"졲졳졵졶졷졹졻",4,"좂좄좈좉좊좎",5,"좕",7,"좞좠좢좣좤"], +["a141","좥좦좧좩",18,"좾좿죀죁"], +["a161","죂죃죅죆죇죉죊죋죍",6,"죖죘죚",5,"죢죣죥"], +["a181","죦",14,"죶",5,"죾죿줁줂줃줇",4,"줎 、。·‥…¨〃­―∥\∼‘’“”〔〕〈",9,"±×÷≠≤≥∞∴°′″℃Å¢£¥♂♀∠⊥⌒∂∇≡≒§※☆★○●◎◇◆□■△▲▽▼→←↑↓↔〓≪≫√∽∝∵∫∬∈∋⊆⊇⊂⊃∪∩∧∨¬"], +["a241","줐줒",5,"줙",18], +["a261","줭",6,"줵",18], +["a281","쥈",7,"쥒쥓쥕쥖쥗쥙",6,"쥢쥤",7,"쥭쥮쥯⇒⇔∀∃´~ˇ˘˝˚˙¸˛¡¿ː∮∑∏¤℉‰◁◀▷▶♤♠♡♥♧♣⊙◈▣◐◑▒▤▥▨▧▦▩♨☏☎☜☞¶†‡↕↗↙↖↘♭♩♪♬㉿㈜№㏇™㏂㏘℡€®"], +["a341","쥱쥲쥳쥵",6,"쥽",10,"즊즋즍즎즏"], +["a361","즑",6,"즚즜즞",16], +["a381","즯",16,"짂짃짅짆짉짋",4,"짒짔짗짘짛!",58,"₩]",32," ̄"], +["a441","짞짟짡짣짥짦짨짩짪짫짮짲",5,"짺짻짽짾짿쨁쨂쨃쨄"], +["a461","쨅쨆쨇쨊쨎",5,"쨕쨖쨗쨙",12], +["a481","쨦쨧쨨쨪",28,"ㄱ",93], +["a541","쩇",4,"쩎쩏쩑쩒쩓쩕",6,"쩞쩢",5,"쩩쩪"], +["a561","쩫",17,"쩾",5,"쪅쪆"], +["a581","쪇",16,"쪙",14,"ⅰ",9], +["a5b0","Ⅰ",9], +["a5c1","Α",16,"Σ",6], +["a5e1","α",16,"σ",6], +["a641","쪨",19,"쪾쪿쫁쫂쫃쫅"], +["a661","쫆",5,"쫎쫐쫒쫔쫕쫖쫗쫚",5,"쫡",6], +["a681","쫨쫩쫪쫫쫭",6,"쫵",18,"쬉쬊─│┌┐┘└├┬┤┴┼━┃┏┓┛┗┣┳┫┻╋┠┯┨┷┿┝┰┥┸╂┒┑┚┙┖┕┎┍┞┟┡┢┦┧┩┪┭┮┱┲┵┶┹┺┽┾╀╁╃",7], +["a741","쬋",4,"쬑쬒쬓쬕쬖쬗쬙",6,"쬢",7], +["a761","쬪",22,"쭂쭃쭄"], +["a781","쭅쭆쭇쭊쭋쭍쭎쭏쭑",6,"쭚쭛쭜쭞",5,"쭥",7,"㎕㎖㎗ℓ㎘㏄㎣㎤㎥㎦㎙",9,"㏊㎍㎎㎏㏏㎈㎉㏈㎧㎨㎰",9,"㎀",4,"㎺",5,"㎐",4,"Ω㏀㏁㎊㎋㎌㏖㏅㎭㎮㎯㏛㎩㎪㎫㎬㏝㏐㏓㏃㏉㏜㏆"], +["a841","쭭",10,"쭺",14], +["a861","쮉",18,"쮝",6], +["a881","쮤",19,"쮹",11,"ÆЪĦ"], +["a8a6","IJ"], +["a8a8","ĿŁØŒºÞŦŊ"], +["a8b1","㉠",27,"ⓐ",25,"①",14,"½⅓⅔¼¾⅛⅜⅝⅞"], +["a941","쯅",14,"쯕",10], +["a961","쯠쯡쯢쯣쯥쯦쯨쯪",18], +["a981","쯽",14,"찎찏찑찒찓찕",6,"찞찟찠찣찤æđðħıijĸŀłøœßþŧŋʼn㈀",27,"⒜",25,"⑴",14,"¹²³⁴ⁿ₁₂₃₄"], +["aa41","찥찦찪찫찭찯찱",6,"찺찿",4,"챆챇챉챊챋챍챎"], +["aa61","챏",4,"챖챚",5,"챡챢챣챥챧챩",6,"챱챲"], +["aa81","챳챴챶",29,"ぁ",82], +["ab41","첔첕첖첗첚첛첝첞첟첡",6,"첪첮",5,"첶첷첹"], +["ab61","첺첻첽",6,"쳆쳈쳊",5,"쳑쳒쳓쳕",5], +["ab81","쳛",8,"쳥",6,"쳭쳮쳯쳱",12,"ァ",85], +["ac41","쳾쳿촀촂",5,"촊촋촍촎촏촑",6,"촚촜촞촟촠"], +["ac61","촡촢촣촥촦촧촩촪촫촭",11,"촺",4], +["ac81","촿",28,"쵝쵞쵟А",5,"ЁЖ",25], +["acd1","а",5,"ёж",25], +["ad41","쵡쵢쵣쵥",6,"쵮쵰쵲",5,"쵹",7], +["ad61","춁",6,"춉",10,"춖춗춙춚춛춝춞춟"], +["ad81","춠춡춢춣춦춨춪",5,"춱",18,"췅"], +["ae41","췆",5,"췍췎췏췑",16], +["ae61","췢",5,"췩췪췫췭췮췯췱",6,"췺췼췾",4], +["ae81","츃츅츆츇츉츊츋츍",6,"츕츖츗츘츚",5,"츢츣츥츦츧츩츪츫"], +["af41","츬츭츮츯츲츴츶",19], +["af61","칊",13,"칚칛칝칞칢",5,"칪칬"], +["af81","칮",5,"칶칷칹칺칻칽",6,"캆캈캊",5,"캒캓캕캖캗캙"], +["b041","캚",5,"캢캦",5,"캮",12], +["b061","캻",5,"컂",19], +["b081","컖",13,"컦컧컩컪컭",6,"컶컺",5,"가각간갇갈갉갊감",7,"같",4,"갠갤갬갭갯갰갱갸갹갼걀걋걍걔걘걜거걱건걷걸걺검겁것겄겅겆겉겊겋게겐겔겜겝겟겠겡겨격겪견겯결겸겹겻겼경곁계곈곌곕곗고곡곤곧골곪곬곯곰곱곳공곶과곽관괄괆"], +["b141","켂켃켅켆켇켉",6,"켒켔켖",5,"켝켞켟켡켢켣"], +["b161","켥",6,"켮켲",5,"켹",11], +["b181","콅",14,"콖콗콙콚콛콝",6,"콦콨콪콫콬괌괍괏광괘괜괠괩괬괭괴괵괸괼굄굅굇굉교굔굘굡굣구국군굳굴굵굶굻굼굽굿궁궂궈궉권궐궜궝궤궷귀귁귄귈귐귑귓규균귤그극근귿글긁금급긋긍긔기긱긴긷길긺김깁깃깅깆깊까깍깎깐깔깖깜깝깟깠깡깥깨깩깬깰깸"], +["b241","콭콮콯콲콳콵콶콷콹",6,"쾁쾂쾃쾄쾆",5,"쾍"], +["b261","쾎",18,"쾢",5,"쾩"], +["b281","쾪",5,"쾱",18,"쿅",6,"깹깻깼깽꺄꺅꺌꺼꺽꺾껀껄껌껍껏껐껑께껙껜껨껫껭껴껸껼꼇꼈꼍꼐꼬꼭꼰꼲꼴꼼꼽꼿꽁꽂꽃꽈꽉꽐꽜꽝꽤꽥꽹꾀꾄꾈꾐꾑꾕꾜꾸꾹꾼꿀꿇꿈꿉꿋꿍꿎꿔꿜꿨꿩꿰꿱꿴꿸뀀뀁뀄뀌뀐뀔뀜뀝뀨끄끅끈끊끌끎끓끔끕끗끙"], +["b341","쿌",19,"쿢쿣쿥쿦쿧쿩"], +["b361","쿪",5,"쿲쿴쿶",5,"쿽쿾쿿퀁퀂퀃퀅",5], +["b381","퀋",5,"퀒",5,"퀙",19,"끝끼끽낀낄낌낍낏낑나낙낚난낟날낡낢남납낫",4,"낱낳내낵낸낼냄냅냇냈냉냐냑냔냘냠냥너넉넋넌널넒넓넘넙넛넜넝넣네넥넨넬넴넵넷넸넹녀녁년녈념녑녔녕녘녜녠노녹논놀놂놈놉놋농높놓놔놘놜놨뇌뇐뇔뇜뇝"], +["b441","퀮",5,"퀶퀷퀹퀺퀻퀽",6,"큆큈큊",5], +["b461","큑큒큓큕큖큗큙",6,"큡",10,"큮큯"], +["b481","큱큲큳큵",6,"큾큿킀킂",18,"뇟뇨뇩뇬뇰뇹뇻뇽누눅눈눋눌눔눕눗눙눠눴눼뉘뉜뉠뉨뉩뉴뉵뉼늄늅늉느늑는늘늙늚늠늡늣능늦늪늬늰늴니닉닌닐닒님닙닛닝닢다닥닦단닫",4,"닳담답닷",4,"닿대댁댄댈댐댑댓댔댕댜더덕덖던덛덜덞덟덤덥"], +["b541","킕",14,"킦킧킩킪킫킭",5], +["b561","킳킶킸킺",5,"탂탃탅탆탇탊",5,"탒탖",4], +["b581","탛탞탟탡탢탣탥",6,"탮탲",5,"탹",11,"덧덩덫덮데덱덴델뎀뎁뎃뎄뎅뎌뎐뎔뎠뎡뎨뎬도독돈돋돌돎돐돔돕돗동돛돝돠돤돨돼됐되된될됨됩됫됴두둑둔둘둠둡둣둥둬뒀뒈뒝뒤뒨뒬뒵뒷뒹듀듄듈듐듕드득든듣들듦듬듭듯등듸디딕딘딛딜딤딥딧딨딩딪따딱딴딸"], +["b641","턅",7,"턎",17], +["b661","턠",15,"턲턳턵턶턷턹턻턼턽턾"], +["b681","턿텂텆",5,"텎텏텑텒텓텕",6,"텞텠텢",5,"텩텪텫텭땀땁땃땄땅땋때땍땐땔땜땝땟땠땡떠떡떤떨떪떫떰떱떳떴떵떻떼떽뗀뗄뗌뗍뗏뗐뗑뗘뗬또똑똔똘똥똬똴뙈뙤뙨뚜뚝뚠뚤뚫뚬뚱뛔뛰뛴뛸뜀뜁뜅뜨뜩뜬뜯뜰뜸뜹뜻띄띈띌띔띕띠띤띨띰띱띳띵라락란랄람랍랏랐랑랒랖랗"], +["b741","텮",13,"텽",6,"톅톆톇톉톊"], +["b761","톋",20,"톢톣톥톦톧"], +["b781","톩",6,"톲톴톶톷톸톹톻톽톾톿퇁",14,"래랙랜랠램랩랫랬랭랴략랸럇량러럭런럴럼럽럿렀렁렇레렉렌렐렘렙렛렝려력련렬렴렵렷렸령례롄롑롓로록론롤롬롭롯롱롸롼뢍뢨뢰뢴뢸룀룁룃룅료룐룔룝룟룡루룩룬룰룸룹룻룽뤄뤘뤠뤼뤽륀륄륌륏륑류륙륜률륨륩"], +["b841","퇐",7,"퇙",17], +["b861","퇫",8,"퇵퇶퇷퇹",13], +["b881","툈툊",5,"툑",24,"륫륭르륵른를름릅릇릉릊릍릎리릭린릴림립릿링마막만많",4,"맘맙맛망맞맡맣매맥맨맬맴맵맷맸맹맺먀먁먈먕머먹먼멀멂멈멉멋멍멎멓메멕멘멜멤멥멧멨멩며멱면멸몃몄명몇몌모목몫몬몰몲몸몹못몽뫄뫈뫘뫙뫼"], +["b941","툪툫툮툯툱툲툳툵",6,"툾퉀퉂",5,"퉉퉊퉋퉌"], +["b961","퉍",14,"퉝",6,"퉥퉦퉧퉨"], +["b981","퉩",22,"튂튃튅튆튇튉튊튋튌묀묄묍묏묑묘묜묠묩묫무묵묶문묻물묽묾뭄뭅뭇뭉뭍뭏뭐뭔뭘뭡뭣뭬뮈뮌뮐뮤뮨뮬뮴뮷므믄믈믐믓미믹민믿밀밂밈밉밋밌밍및밑바",4,"받",4,"밤밥밧방밭배백밴밸뱀뱁뱃뱄뱅뱉뱌뱍뱐뱝버벅번벋벌벎범법벗"], +["ba41","튍튎튏튒튓튔튖",5,"튝튞튟튡튢튣튥",6,"튭"], +["ba61","튮튯튰튲",5,"튺튻튽튾틁틃",4,"틊틌",5], +["ba81","틒틓틕틖틗틙틚틛틝",6,"틦",9,"틲틳틵틶틷틹틺벙벚베벡벤벧벨벰벱벳벴벵벼벽변별볍볏볐병볕볘볜보복볶본볼봄봅봇봉봐봔봤봬뵀뵈뵉뵌뵐뵘뵙뵤뵨부북분붇불붉붊붐붑붓붕붙붚붜붤붰붸뷔뷕뷘뷜뷩뷰뷴뷸븀븃븅브븍븐블븜븝븟비빅빈빌빎빔빕빗빙빚빛빠빡빤"], +["bb41","틻",4,"팂팄팆",5,"팏팑팒팓팕팗",4,"팞팢팣"], +["bb61","팤팦팧팪팫팭팮팯팱",6,"팺팾",5,"퍆퍇퍈퍉"], +["bb81","퍊",31,"빨빪빰빱빳빴빵빻빼빽뺀뺄뺌뺍뺏뺐뺑뺘뺙뺨뻐뻑뻔뻗뻘뻠뻣뻤뻥뻬뼁뼈뼉뼘뼙뼛뼜뼝뽀뽁뽄뽈뽐뽑뽕뾔뾰뿅뿌뿍뿐뿔뿜뿟뿡쀼쁑쁘쁜쁠쁨쁩삐삑삔삘삠삡삣삥사삭삯산삳살삵삶삼삽삿샀상샅새색샌샐샘샙샛샜생샤"], +["bc41","퍪",17,"퍾퍿펁펂펃펅펆펇"], +["bc61","펈펉펊펋펎펒",5,"펚펛펝펞펟펡",6,"펪펬펮"], +["bc81","펯",4,"펵펶펷펹펺펻펽",6,"폆폇폊",5,"폑",5,"샥샨샬샴샵샷샹섀섄섈섐섕서",4,"섣설섦섧섬섭섯섰성섶세섹센셀셈셉셋셌셍셔셕션셜셤셥셧셨셩셰셴셸솅소속솎손솔솖솜솝솟송솥솨솩솬솰솽쇄쇈쇌쇔쇗쇘쇠쇤쇨쇰쇱쇳쇼쇽숀숄숌숍숏숑수숙순숟술숨숩숫숭"], +["bd41","폗폙",7,"폢폤",7,"폮폯폱폲폳폵폶폷"], +["bd61","폸폹폺폻폾퐀퐂",5,"퐉",13], +["bd81","퐗",5,"퐞",25,"숯숱숲숴쉈쉐쉑쉔쉘쉠쉥쉬쉭쉰쉴쉼쉽쉿슁슈슉슐슘슛슝스슥슨슬슭슴습슷승시식신싣실싫심십싯싱싶싸싹싻싼쌀쌈쌉쌌쌍쌓쌔쌕쌘쌜쌤쌥쌨쌩썅써썩썬썰썲썸썹썼썽쎄쎈쎌쏀쏘쏙쏜쏟쏠쏢쏨쏩쏭쏴쏵쏸쐈쐐쐤쐬쐰"], +["be41","퐸",7,"푁푂푃푅",14], +["be61","푔",7,"푝푞푟푡푢푣푥",7,"푮푰푱푲"], +["be81","푳",4,"푺푻푽푾풁풃",4,"풊풌풎",5,"풕",8,"쐴쐼쐽쑈쑤쑥쑨쑬쑴쑵쑹쒀쒔쒜쒸쒼쓩쓰쓱쓴쓸쓺쓿씀씁씌씐씔씜씨씩씬씰씸씹씻씽아악안앉않알앍앎앓암압앗았앙앝앞애액앤앨앰앱앳앴앵야약얀얄얇얌얍얏양얕얗얘얜얠얩어억언얹얻얼얽얾엄",6,"엌엎"], +["bf41","풞",10,"풪",14], +["bf61","풹",18,"퓍퓎퓏퓑퓒퓓퓕"], +["bf81","퓖",5,"퓝퓞퓠",7,"퓩퓪퓫퓭퓮퓯퓱",6,"퓹퓺퓼에엑엔엘엠엡엣엥여역엮연열엶엷염",5,"옅옆옇예옌옐옘옙옛옜오옥온올옭옮옰옳옴옵옷옹옻와왁완왈왐왑왓왔왕왜왝왠왬왯왱외왹왼욀욈욉욋욍요욕욘욜욤욥욧용우욱운울욹욺움웁웃웅워웍원월웜웝웠웡웨"], +["c041","퓾",5,"픅픆픇픉픊픋픍",6,"픖픘",5], +["c061","픞",25], +["c081","픸픹픺픻픾픿핁핂핃핅",6,"핎핐핒",5,"핚핛핝핞핟핡핢핣웩웬웰웸웹웽위윅윈윌윔윕윗윙유육윤율윰윱윳융윷으윽은을읊음읍읏응",7,"읜읠읨읫이익인일읽읾잃임입잇있잉잊잎자작잔잖잗잘잚잠잡잣잤장잦재잭잰잴잼잽잿쟀쟁쟈쟉쟌쟎쟐쟘쟝쟤쟨쟬저적전절젊"], +["c141","핤핦핧핪핬핮",5,"핶핷핹핺핻핽",6,"햆햊햋"], +["c161","햌햍햎햏햑",19,"햦햧"], +["c181","햨",31,"점접젓정젖제젝젠젤젬젭젯젱져젼졀졈졉졌졍졔조족존졸졺좀좁좃종좆좇좋좌좍좔좝좟좡좨좼좽죄죈죌죔죕죗죙죠죡죤죵주죽준줄줅줆줌줍줏중줘줬줴쥐쥑쥔쥘쥠쥡쥣쥬쥰쥴쥼즈즉즌즐즘즙즛증지직진짇질짊짐집짓"], +["c241","헊헋헍헎헏헑헓",4,"헚헜헞",5,"헦헧헩헪헫헭헮"], +["c261","헯",4,"헶헸헺",5,"혂혃혅혆혇혉",6,"혒"], +["c281","혖",5,"혝혞혟혡혢혣혥",7,"혮",9,"혺혻징짖짙짚짜짝짠짢짤짧짬짭짯짰짱째짹짼쨀쨈쨉쨋쨌쨍쨔쨘쨩쩌쩍쩐쩔쩜쩝쩟쩠쩡쩨쩽쪄쪘쪼쪽쫀쫄쫌쫍쫏쫑쫓쫘쫙쫠쫬쫴쬈쬐쬔쬘쬠쬡쭁쭈쭉쭌쭐쭘쭙쭝쭤쭸쭹쮜쮸쯔쯤쯧쯩찌찍찐찔찜찝찡찢찧차착찬찮찰참찹찻"], +["c341","혽혾혿홁홂홃홄홆홇홊홌홎홏홐홒홓홖홗홙홚홛홝",4], +["c361","홢",4,"홨홪",5,"홲홳홵",11], +["c381","횁횂횄횆",5,"횎횏횑횒횓횕",7,"횞횠횢",5,"횩횪찼창찾채책챈챌챔챕챗챘챙챠챤챦챨챰챵처척천철첨첩첫첬청체첵첸첼쳄쳅쳇쳉쳐쳔쳤쳬쳰촁초촉촌촐촘촙촛총촤촨촬촹최쵠쵤쵬쵭쵯쵱쵸춈추축춘출춤춥춧충춰췄췌췐취췬췰췸췹췻췽츄츈츌츔츙츠측츤츨츰츱츳층"], +["c441","횫횭횮횯횱",7,"횺횼",7,"훆훇훉훊훋"], +["c461","훍훎훏훐훒훓훕훖훘훚",5,"훡훢훣훥훦훧훩",4], +["c481","훮훯훱훲훳훴훶",5,"훾훿휁휂휃휅",11,"휒휓휔치칙친칟칠칡침칩칫칭카칵칸칼캄캅캇캉캐캑캔캘캠캡캣캤캥캬캭컁커컥컨컫컬컴컵컷컸컹케켁켄켈켐켑켓켕켜켠켤켬켭켯켰켱켸코콕콘콜콤콥콧콩콰콱콴콸쾀쾅쾌쾡쾨쾰쿄쿠쿡쿤쿨쿰쿱쿳쿵쿼퀀퀄퀑퀘퀭퀴퀵퀸퀼"], +["c541","휕휖휗휚휛휝휞휟휡",6,"휪휬휮",5,"휶휷휹"], +["c561","휺휻휽",6,"흅흆흈흊",5,"흒흓흕흚",4], +["c581","흟흢흤흦흧흨흪흫흭흮흯흱흲흳흵",6,"흾흿힀힂",5,"힊힋큄큅큇큉큐큔큘큠크큭큰클큼큽킁키킥킨킬킴킵킷킹타탁탄탈탉탐탑탓탔탕태택탠탤탬탭탯탰탱탸턍터턱턴털턺텀텁텃텄텅테텍텐텔템텝텟텡텨텬텼톄톈토톡톤톨톰톱톳통톺톼퇀퇘퇴퇸툇툉툐투툭툰툴툼툽툿퉁퉈퉜"], +["c641","힍힎힏힑",6,"힚힜힞",5], +["c6a1","퉤튀튁튄튈튐튑튕튜튠튤튬튱트특튼튿틀틂틈틉틋틔틘틜틤틥티틱틴틸팀팁팃팅파팍팎판팔팖팜팝팟팠팡팥패팩팬팰팸팹팻팼팽퍄퍅퍼퍽펀펄펌펍펏펐펑페펙펜펠펨펩펫펭펴편펼폄폅폈평폐폘폡폣포폭폰폴폼폽폿퐁"], +["c7a1","퐈퐝푀푄표푠푤푭푯푸푹푼푿풀풂품풉풋풍풔풩퓌퓐퓔퓜퓟퓨퓬퓰퓸퓻퓽프픈플픔픕픗피픽핀필핌핍핏핑하학한할핥함합핫항해핵핸핼햄햅햇했행햐향허헉헌헐헒험헙헛헝헤헥헨헬헴헵헷헹혀혁현혈혐협혓혔형혜혠"], +["c8a1","혤혭호혹혼홀홅홈홉홋홍홑화확환활홧황홰홱홴횃횅회획횐횔횝횟횡효횬횰횹횻후훅훈훌훑훔훗훙훠훤훨훰훵훼훽휀휄휑휘휙휜휠휨휩휫휭휴휵휸휼흄흇흉흐흑흔흖흗흘흙흠흡흣흥흩희흰흴흼흽힁히힉힌힐힘힙힛힝"], +["caa1","伽佳假價加可呵哥嘉嫁家暇架枷柯歌珂痂稼苛茄街袈訶賈跏軻迦駕刻却各恪慤殼珏脚覺角閣侃刊墾奸姦干幹懇揀杆柬桿澗癎看磵稈竿簡肝艮艱諫間乫喝曷渴碣竭葛褐蝎鞨勘坎堪嵌感憾戡敢柑橄減甘疳監瞰紺邯鑑鑒龕"], +["cba1","匣岬甲胛鉀閘剛堈姜岡崗康强彊慷江畺疆糠絳綱羌腔舡薑襁講鋼降鱇介价個凱塏愷愾慨改槪漑疥皆盖箇芥蓋豈鎧開喀客坑更粳羹醵倨去居巨拒据據擧渠炬祛距踞車遽鉅鋸乾件健巾建愆楗腱虔蹇鍵騫乞傑杰桀儉劍劒檢"], +["cca1","瞼鈐黔劫怯迲偈憩揭擊格檄激膈覡隔堅牽犬甄絹繭肩見譴遣鵑抉決潔結缺訣兼慊箝謙鉗鎌京俓倞傾儆勁勍卿坰境庚徑慶憬擎敬景暻更梗涇炅烱璟璥瓊痙硬磬竟競絅經耕耿脛莖警輕逕鏡頃頸驚鯨係啓堺契季屆悸戒桂械"], +["cda1","棨溪界癸磎稽系繫繼計誡谿階鷄古叩告呱固姑孤尻庫拷攷故敲暠枯槁沽痼皐睾稿羔考股膏苦苽菰藁蠱袴誥賈辜錮雇顧高鼓哭斛曲梏穀谷鵠困坤崑昆梱棍滾琨袞鯤汨滑骨供公共功孔工恐恭拱控攻珙空蚣貢鞏串寡戈果瓜"], +["cea1","科菓誇課跨過鍋顆廓槨藿郭串冠官寬慣棺款灌琯瓘管罐菅觀貫關館刮恝括适侊光匡壙廣曠洸炚狂珖筐胱鑛卦掛罫乖傀塊壞怪愧拐槐魁宏紘肱轟交僑咬喬嬌嶠巧攪敎校橋狡皎矯絞翹膠蕎蛟較轎郊餃驕鮫丘久九仇俱具勾"], +["cfa1","區口句咎嘔坵垢寇嶇廐懼拘救枸柩構歐毆毬求溝灸狗玖球瞿矩究絿耉臼舅舊苟衢謳購軀逑邱鉤銶駒驅鳩鷗龜國局菊鞠鞫麴君窘群裙軍郡堀屈掘窟宮弓穹窮芎躬倦券勸卷圈拳捲權淃眷厥獗蕨蹶闕机櫃潰詭軌饋句晷歸貴"], +["d0a1","鬼龜叫圭奎揆槻珪硅窺竅糾葵規赳逵閨勻均畇筠菌鈞龜橘克剋劇戟棘極隙僅劤勤懃斤根槿瑾筋芹菫覲謹近饉契今妗擒昑檎琴禁禽芩衾衿襟金錦伋及急扱汲級給亘兢矜肯企伎其冀嗜器圻基埼夔奇妓寄岐崎己幾忌技旗旣"], +["d1a1","朞期杞棋棄機欺氣汽沂淇玘琦琪璂璣畸畿碁磯祁祇祈祺箕紀綺羈耆耭肌記譏豈起錡錤飢饑騎騏驥麒緊佶吉拮桔金喫儺喇奈娜懦懶拏拿癩",5,"那樂",4,"諾酪駱亂卵暖欄煖爛蘭難鸞捏捺南嵐枏楠湳濫男藍襤拉"], +["d2a1","納臘蠟衲囊娘廊",4,"乃來內奈柰耐冷女年撚秊念恬拈捻寧寗努勞奴弩怒擄櫓爐瑙盧",5,"駑魯",10,"濃籠聾膿農惱牢磊腦賂雷尿壘",7,"嫩訥杻紐勒",5,"能菱陵尼泥匿溺多茶"], +["d3a1","丹亶但單團壇彖斷旦檀段湍短端簞緞蛋袒鄲鍛撻澾獺疸達啖坍憺擔曇淡湛潭澹痰聃膽蕁覃談譚錟沓畓答踏遝唐堂塘幢戇撞棠當糖螳黨代垈坮大對岱帶待戴擡玳臺袋貸隊黛宅德悳倒刀到圖堵塗導屠島嶋度徒悼挑掉搗桃"], +["d4a1","棹櫂淘渡滔濤燾盜睹禱稻萄覩賭跳蹈逃途道都鍍陶韜毒瀆牘犢獨督禿篤纛讀墩惇敦旽暾沌焞燉豚頓乭突仝冬凍動同憧東桐棟洞潼疼瞳童胴董銅兜斗杜枓痘竇荳讀豆逗頭屯臀芚遁遯鈍得嶝橙燈登等藤謄鄧騰喇懶拏癩羅"], +["d5a1","蘿螺裸邏樂洛烙珞絡落諾酪駱丹亂卵欄欒瀾爛蘭鸞剌辣嵐擥攬欖濫籃纜藍襤覽拉臘蠟廊朗浪狼琅瑯螂郞來崍徠萊冷掠略亮倆兩凉梁樑粮粱糧良諒輛量侶儷勵呂廬慮戾旅櫚濾礪藜蠣閭驢驪麗黎力曆歷瀝礫轢靂憐戀攣漣"], +["d6a1","煉璉練聯蓮輦連鍊冽列劣洌烈裂廉斂殮濂簾獵令伶囹寧岺嶺怜玲笭羚翎聆逞鈴零靈領齡例澧禮醴隷勞怒撈擄櫓潞瀘爐盧老蘆虜路輅露魯鷺鹵碌祿綠菉錄鹿麓論壟弄朧瀧瓏籠聾儡瀨牢磊賂賚賴雷了僚寮廖料燎療瞭聊蓼"], +["d7a1","遼鬧龍壘婁屢樓淚漏瘻累縷蔞褸鏤陋劉旒柳榴流溜瀏琉瑠留瘤硫謬類六戮陸侖倫崙淪綸輪律慄栗率隆勒肋凜凌楞稜綾菱陵俚利厘吏唎履悧李梨浬犁狸理璃異痢籬罹羸莉裏裡里釐離鯉吝潾燐璘藺躪隣鱗麟林淋琳臨霖砬"], +["d8a1","立笠粒摩瑪痲碼磨馬魔麻寞幕漠膜莫邈万卍娩巒彎慢挽晩曼滿漫灣瞞萬蔓蠻輓饅鰻唜抹末沫茉襪靺亡妄忘忙望網罔芒茫莽輞邙埋妹媒寐昧枚梅每煤罵買賣邁魅脈貊陌驀麥孟氓猛盲盟萌冪覓免冕勉棉沔眄眠綿緬面麵滅"], +["d9a1","蔑冥名命明暝椧溟皿瞑茗蓂螟酩銘鳴袂侮冒募姆帽慕摸摹暮某模母毛牟牡瑁眸矛耗芼茅謀謨貌木沐牧目睦穆鶩歿沒夢朦蒙卯墓妙廟描昴杳渺猫竗苗錨務巫憮懋戊拇撫无楙武毋無珷畝繆舞茂蕪誣貿霧鵡墨默們刎吻問文"], +["daa1","汶紊紋聞蚊門雯勿沕物味媚尾嵋彌微未梶楣渼湄眉米美薇謎迷靡黴岷悶愍憫敏旻旼民泯玟珉緡閔密蜜謐剝博拍搏撲朴樸泊珀璞箔粕縛膊舶薄迫雹駁伴半反叛拌搬攀斑槃泮潘班畔瘢盤盼磐磻礬絆般蟠返頒飯勃拔撥渤潑"], +["dba1","發跋醱鉢髮魃倣傍坊妨尨幇彷房放方旁昉枋榜滂磅紡肪膀舫芳蒡蚌訪謗邦防龐倍俳北培徘拜排杯湃焙盃背胚裴裵褙賠輩配陪伯佰帛柏栢白百魄幡樊煩燔番磻繁蕃藩飜伐筏罰閥凡帆梵氾汎泛犯範范法琺僻劈壁擘檗璧癖"], +["dca1","碧蘗闢霹便卞弁變辨辯邊別瞥鱉鼈丙倂兵屛幷昞昺柄棅炳甁病秉竝輧餠騈保堡報寶普步洑湺潽珤甫菩補褓譜輔伏僕匐卜宓復服福腹茯蔔複覆輹輻馥鰒本乶俸奉封峯峰捧棒烽熢琫縫蓬蜂逢鋒鳳不付俯傅剖副否咐埠夫婦"], +["dda1","孚孵富府復扶敷斧浮溥父符簿缶腐腑膚艀芙莩訃負賦賻赴趺部釜阜附駙鳧北分吩噴墳奔奮忿憤扮昐汾焚盆粉糞紛芬賁雰不佛弗彿拂崩朋棚硼繃鵬丕備匕匪卑妃婢庇悲憊扉批斐枇榧比毖毗毘沸泌琵痺砒碑秕秘粃緋翡肥"], +["dea1","脾臂菲蜚裨誹譬費鄙非飛鼻嚬嬪彬斌檳殯浜濱瀕牝玭貧賓頻憑氷聘騁乍事些仕伺似使俟僿史司唆嗣四士奢娑寫寺射巳師徙思捨斜斯柶査梭死沙泗渣瀉獅砂社祀祠私篩紗絲肆舍莎蓑蛇裟詐詞謝賜赦辭邪飼駟麝削數朔索"], +["dfa1","傘刪山散汕珊産疝算蒜酸霰乷撒殺煞薩三參杉森渗芟蔘衫揷澁鈒颯上傷像償商喪嘗孀尙峠常床庠廂想桑橡湘爽牀狀相祥箱翔裳觴詳象賞霜塞璽賽嗇塞穡索色牲生甥省笙墅壻嶼序庶徐恕抒捿敍暑曙書栖棲犀瑞筮絮緖署"], +["e0a1","胥舒薯西誓逝鋤黍鼠夕奭席惜昔晳析汐淅潟石碩蓆釋錫仙僊先善嬋宣扇敾旋渲煽琁瑄璇璿癬禪線繕羨腺膳船蘚蟬詵跣選銑鐥饍鮮卨屑楔泄洩渫舌薛褻設說雪齧剡暹殲纖蟾贍閃陝攝涉燮葉城姓宬性惺成星晟猩珹盛省筬"], +["e1a1","聖聲腥誠醒世勢歲洗稅笹細說貰召嘯塑宵小少巢所掃搔昭梳沼消溯瀟炤燒甦疏疎瘙笑篠簫素紹蔬蕭蘇訴逍遡邵銷韶騷俗屬束涑粟續謖贖速孫巽損蓀遜飡率宋悚松淞訟誦送頌刷殺灑碎鎖衰釗修受嗽囚垂壽嫂守岫峀帥愁"], +["e2a1","戍手授搜收數樹殊水洙漱燧狩獸琇璲瘦睡秀穗竪粹綏綬繡羞脩茱蒐蓚藪袖誰讐輸遂邃酬銖銹隋隧隨雖需須首髓鬚叔塾夙孰宿淑潚熟琡璹肅菽巡徇循恂旬栒楯橓殉洵淳珣盾瞬筍純脣舜荀蓴蕣詢諄醇錞順馴戌術述鉥崇崧"], +["e3a1","嵩瑟膝蝨濕拾習褶襲丞乘僧勝升承昇繩蠅陞侍匙嘶始媤尸屎屍市弑恃施是時枾柴猜矢示翅蒔蓍視試詩諡豕豺埴寔式息拭植殖湜熄篒蝕識軾食飾伸侁信呻娠宸愼新晨燼申神紳腎臣莘薪藎蜃訊身辛辰迅失室實悉審尋心沁"], +["e4a1","沈深瀋甚芯諶什十拾雙氏亞俄兒啞娥峨我牙芽莪蛾衙訝阿雅餓鴉鵝堊岳嶽幄惡愕握樂渥鄂鍔顎鰐齷安岸按晏案眼雁鞍顔鮟斡謁軋閼唵岩巖庵暗癌菴闇壓押狎鴨仰央怏昻殃秧鴦厓哀埃崖愛曖涯碍艾隘靄厄扼掖液縊腋額"], +["e5a1","櫻罌鶯鸚也倻冶夜惹揶椰爺耶若野弱掠略約若葯蒻藥躍亮佯兩凉壤孃恙揚攘敭暘梁楊樣洋瀁煬痒瘍禳穰糧羊良襄諒讓釀陽量養圄御於漁瘀禦語馭魚齬億憶抑檍臆偃堰彦焉言諺孼蘖俺儼嚴奄掩淹嶪業円予余勵呂女如廬"], +["e6a1","旅歟汝濾璵礖礪與艅茹輿轝閭餘驪麗黎亦力域役易曆歷疫繹譯轢逆驛嚥堧姸娟宴年延憐戀捐挻撚椽沇沿涎涓淵演漣烟然煙煉燃燕璉硏硯秊筵緣練縯聯衍軟輦蓮連鉛鍊鳶列劣咽悅涅烈熱裂說閱厭廉念捻染殮炎焰琰艶苒"], +["e7a1","簾閻髥鹽曄獵燁葉令囹塋寧嶺嶸影怜映暎楹榮永泳渶潁濚瀛瀯煐營獰玲瑛瑩瓔盈穎纓羚聆英詠迎鈴鍈零霙靈領乂倪例刈叡曳汭濊猊睿穢芮藝蘂禮裔詣譽豫醴銳隸霓預五伍俉傲午吾吳嗚塢墺奧娛寤悟惡懊敖旿晤梧汚澳"], +["e8a1","烏熬獒筽蜈誤鰲鼇屋沃獄玉鈺溫瑥瘟穩縕蘊兀壅擁瓮甕癰翁邕雍饔渦瓦窩窪臥蛙蝸訛婉完宛梡椀浣玩琓琬碗緩翫脘腕莞豌阮頑曰往旺枉汪王倭娃歪矮外嵬巍猥畏了僚僥凹堯夭妖姚寥寮尿嶢拗搖撓擾料曜樂橈燎燿瑤療"], +["e9a1","窈窯繇繞耀腰蓼蟯要謠遙遼邀饒慾欲浴縟褥辱俑傭冗勇埇墉容庸慂榕涌湧溶熔瑢用甬聳茸蓉踊鎔鏞龍于佑偶優又友右宇寓尤愚憂旴牛玗瑀盂祐禑禹紆羽芋藕虞迂遇郵釪隅雨雩勖彧旭昱栯煜稶郁頊云暈橒殞澐熉耘芸蕓"], +["eaa1","運隕雲韻蔚鬱亐熊雄元原員圓園垣媛嫄寃怨愿援沅洹湲源爰猿瑗苑袁轅遠阮院願鴛月越鉞位偉僞危圍委威尉慰暐渭爲瑋緯胃萎葦蔿蝟衛褘謂違韋魏乳侑儒兪劉唯喩孺宥幼幽庾悠惟愈愉揄攸有杻柔柚柳楡楢油洧流游溜"], +["eba1","濡猶猷琉瑜由留癒硫紐維臾萸裕誘諛諭踰蹂遊逾遺酉釉鍮類六堉戮毓肉育陸倫允奫尹崙淪潤玧胤贇輪鈗閏律慄栗率聿戎瀜絨融隆垠恩慇殷誾銀隱乙吟淫蔭陰音飮揖泣邑凝應膺鷹依倚儀宜意懿擬椅毅疑矣義艤薏蟻衣誼"], +["eca1","議醫二以伊利吏夷姨履已弛彛怡易李梨泥爾珥理異痍痢移罹而耳肄苡荑裏裡貽貳邇里離飴餌匿溺瀷益翊翌翼謚人仁刃印吝咽因姻寅引忍湮燐璘絪茵藺蚓認隣靭靷鱗麟一佚佾壹日溢逸鎰馹任壬妊姙恁林淋稔臨荏賃入卄"], +["eda1","立笠粒仍剩孕芿仔刺咨姉姿子字孜恣慈滋炙煮玆瓷疵磁紫者自茨蔗藉諮資雌作勺嚼斫昨灼炸爵綽芍酌雀鵲孱棧殘潺盞岑暫潛箴簪蠶雜丈仗匠場墻壯奬將帳庄張掌暲杖樟檣欌漿牆狀獐璋章粧腸臟臧莊葬蔣薔藏裝贓醬長"], +["eea1","障再哉在宰才材栽梓渽滓災縡裁財載齋齎爭箏諍錚佇低儲咀姐底抵杵楮樗沮渚狙猪疽箸紵苧菹著藷詛貯躇這邸雎齟勣吊嫡寂摘敵滴狄炙的積笛籍績翟荻謫賊赤跡蹟迪迹適鏑佃佺傳全典前剪塡塼奠專展廛悛戰栓殿氈澱"], +["efa1","煎琠田甸畑癲筌箋箭篆纏詮輾轉鈿銓錢鐫電顚顫餞切截折浙癤竊節絶占岾店漸点粘霑鮎點接摺蝶丁井亭停偵呈姃定幀庭廷征情挺政整旌晶晸柾楨檉正汀淀淨渟湞瀞炡玎珽町睛碇禎程穽精綎艇訂諪貞鄭酊釘鉦鋌錠霆靖"], +["f0a1","靜頂鼎制劑啼堤帝弟悌提梯濟祭第臍薺製諸蹄醍除際霽題齊俎兆凋助嘲弔彫措操早晁曺曹朝條棗槽漕潮照燥爪璪眺祖祚租稠窕粗糟組繰肇藻蚤詔調趙躁造遭釣阻雕鳥族簇足鏃存尊卒拙猝倧宗從悰慫棕淙琮種終綜縱腫"], +["f1a1","踪踵鍾鐘佐坐左座挫罪主住侏做姝胄呪周嗾奏宙州廚晝朱柱株注洲湊澍炷珠疇籌紂紬綢舟蛛註誅走躊輳週酎酒鑄駐竹粥俊儁准埈寯峻晙樽浚準濬焌畯竣蠢逡遵雋駿茁中仲衆重卽櫛楫汁葺增憎曾拯烝甑症繒蒸證贈之只"], +["f2a1","咫地址志持指摯支旨智枝枳止池沚漬知砥祉祗紙肢脂至芝芷蜘誌識贄趾遲直稙稷織職唇嗔塵振搢晉晋桭榛殄津溱珍瑨璡畛疹盡眞瞋秦縉縝臻蔯袗診賑軫辰進鎭陣陳震侄叱姪嫉帙桎瓆疾秩窒膣蛭質跌迭斟朕什執潗緝輯"], +["f3a1","鏶集徵懲澄且侘借叉嗟嵯差次此磋箚茶蹉車遮捉搾着窄錯鑿齪撰澯燦璨瓚竄簒纂粲纘讚贊鑽餐饌刹察擦札紮僭參塹慘慙懺斬站讒讖倉倡創唱娼廠彰愴敞昌昶暢槍滄漲猖瘡窓脹艙菖蒼債埰寀寨彩採砦綵菜蔡采釵冊柵策"], +["f4a1","責凄妻悽處倜刺剔尺慽戚拓擲斥滌瘠脊蹠陟隻仟千喘天川擅泉淺玔穿舛薦賤踐遷釧闡阡韆凸哲喆徹撤澈綴輟轍鐵僉尖沾添甛瞻簽籤詹諂堞妾帖捷牒疊睫諜貼輒廳晴淸聽菁請靑鯖切剃替涕滯締諦逮遞體初剿哨憔抄招梢"], +["f5a1","椒楚樵炒焦硝礁礎秒稍肖艸苕草蕉貂超酢醋醮促囑燭矗蜀觸寸忖村邨叢塚寵悤憁摠總聰蔥銃撮催崔最墜抽推椎楸樞湫皺秋芻萩諏趨追鄒酋醜錐錘鎚雛騶鰍丑畜祝竺筑築縮蓄蹙蹴軸逐春椿瑃出朮黜充忠沖蟲衝衷悴膵萃"], +["f6a1","贅取吹嘴娶就炊翠聚脆臭趣醉驟鷲側仄厠惻測層侈値嗤峙幟恥梔治淄熾痔痴癡稚穉緇緻置致蚩輜雉馳齒則勅飭親七柒漆侵寢枕沈浸琛砧針鍼蟄秤稱快他咤唾墮妥惰打拖朶楕舵陀馱駝倬卓啄坼度托拓擢晫柝濁濯琢琸託"], +["f7a1","鐸呑嘆坦彈憚歎灘炭綻誕奪脫探眈耽貪塔搭榻宕帑湯糖蕩兌台太怠態殆汰泰笞胎苔跆邰颱宅擇澤撑攄兎吐土討慟桶洞痛筒統通堆槌腿褪退頹偸套妬投透鬪慝特闖坡婆巴把播擺杷波派爬琶破罷芭跛頗判坂板版瓣販辦鈑"], +["f8a1","阪八叭捌佩唄悖敗沛浿牌狽稗覇貝彭澎烹膨愎便偏扁片篇編翩遍鞭騙貶坪平枰萍評吠嬖幣廢弊斃肺蔽閉陛佈包匍匏咆哺圃布怖抛抱捕暴泡浦疱砲胞脯苞葡蒲袍褒逋鋪飽鮑幅暴曝瀑爆輻俵剽彪慓杓標漂瓢票表豹飇飄驃"], +["f9a1","品稟楓諷豊風馮彼披疲皮被避陂匹弼必泌珌畢疋筆苾馝乏逼下何厦夏廈昰河瑕荷蝦賀遐霞鰕壑學虐謔鶴寒恨悍旱汗漢澣瀚罕翰閑閒限韓割轄函含咸啣喊檻涵緘艦銜陷鹹合哈盒蛤閤闔陜亢伉姮嫦巷恒抗杭桁沆港缸肛航"], +["faa1","行降項亥偕咳垓奚孩害懈楷海瀣蟹解該諧邂駭骸劾核倖幸杏荇行享向嚮珦鄕響餉饗香噓墟虛許憲櫶獻軒歇險驗奕爀赫革俔峴弦懸晛泫炫玄玹現眩睍絃絢縣舷衒見賢鉉顯孑穴血頁嫌俠協夾峽挾浹狹脅脇莢鋏頰亨兄刑型"], +["fba1","形泂滎瀅灐炯熒珩瑩荊螢衡逈邢鎣馨兮彗惠慧暳蕙蹊醯鞋乎互呼壕壺好岵弧戶扈昊晧毫浩淏湖滸澔濠濩灝狐琥瑚瓠皓祜糊縞胡芦葫蒿虎號蝴護豪鎬頀顥惑或酷婚昏混渾琿魂忽惚笏哄弘汞泓洪烘紅虹訌鴻化和嬅樺火畵"], +["fca1","禍禾花華話譁貨靴廓擴攫確碻穫丸喚奐宦幻患換歡晥桓渙煥環紈還驩鰥活滑猾豁闊凰幌徨恍惶愰慌晃晄榥況湟滉潢煌璜皇篁簧荒蝗遑隍黃匯回廻徊恢悔懷晦會檜淮澮灰獪繪膾茴蛔誨賄劃獲宖橫鐄哮嚆孝效斅曉梟涍淆"], +["fda1","爻肴酵驍侯候厚后吼喉嗅帿後朽煦珝逅勛勳塤壎焄熏燻薰訓暈薨喧暄煊萱卉喙毁彙徽揮暉煇諱輝麾休携烋畦虧恤譎鷸兇凶匈洶胸黑昕欣炘痕吃屹紇訖欠欽歆吸恰洽翕興僖凞喜噫囍姬嬉希憙憘戱晞曦熙熹熺犧禧稀羲詰"] +] diff --git a/backend/node_modules/iconv-lite/encodings/tables/cp950.json b/backend/node_modules/iconv-lite/encodings/tables/cp950.json new file mode 100644 index 0000000000000000000000000000000000000000..d8bc87178dd38fca1829b9e2109c6f71e9721bdf --- /dev/null +++ b/backend/node_modules/iconv-lite/encodings/tables/cp950.json @@ -0,0 +1,177 @@ +[ +["0","\u0000",127], +["a140"," ,、。.‧;:?!︰…‥﹐﹑﹒·﹔﹕﹖﹗|–︱—︳╴︴﹏()︵︶{}︷︸〔〕︹︺【】︻︼《》︽︾〈〉︿﹀「」﹁﹂『』﹃﹄﹙﹚"], +["a1a1","﹛﹜﹝﹞‘’“”〝〞‵′#&*※§〃○●△▲◎☆★◇◆□■▽▼㊣℅¯ ̄_ˍ﹉﹊﹍﹎﹋﹌﹟﹠﹡+-×÷±√<>=≦≧≠∞≒≡﹢",4,"~∩∪⊥∠∟⊿㏒㏑∫∮∵∴♀♂⊕⊙↑↓←→↖↗↙↘∥∣/"], +["a240","\∕﹨$¥〒¢£%@℃℉﹩﹪﹫㏕㎜㎝㎞㏎㎡㎎㎏㏄°兙兛兞兝兡兣嗧瓩糎▁",7,"▏▎▍▌▋▊▉┼┴┬┤├▔─│▕┌┐└┘╭"], +["a2a1","╮╰╯═╞╪╡◢◣◥◤╱╲╳0",9,"Ⅰ",9,"〡",8,"十卄卅A",25,"a",21], +["a340","wxyzΑ",16,"Σ",6,"α",16,"σ",6,"ㄅ",10], +["a3a1","ㄐ",25,"˙ˉˊˇˋ"], +["a3e1","€"], +["a440","一乙丁七乃九了二人儿入八几刀刁力匕十卜又三下丈上丫丸凡久么也乞于亡兀刃勺千叉口土士夕大女子孑孓寸小尢尸山川工己已巳巾干廾弋弓才"], +["a4a1","丑丐不中丰丹之尹予云井互五亢仁什仃仆仇仍今介仄元允內六兮公冗凶分切刈勻勾勿化匹午升卅卞厄友及反壬天夫太夭孔少尤尺屯巴幻廿弔引心戈戶手扎支文斗斤方日曰月木欠止歹毋比毛氏水火爪父爻片牙牛犬王丙"], +["a540","世丕且丘主乍乏乎以付仔仕他仗代令仙仞充兄冉冊冬凹出凸刊加功包匆北匝仟半卉卡占卯卮去可古右召叮叩叨叼司叵叫另只史叱台句叭叻四囚外"], +["a5a1","央失奴奶孕它尼巨巧左市布平幼弁弘弗必戊打扔扒扑斥旦朮本未末札正母民氐永汁汀氾犯玄玉瓜瓦甘生用甩田由甲申疋白皮皿目矛矢石示禾穴立丞丟乒乓乩亙交亦亥仿伉伙伊伕伍伐休伏仲件任仰仳份企伋光兇兆先全"], +["a640","共再冰列刑划刎刖劣匈匡匠印危吉吏同吊吐吁吋各向名合吃后吆吒因回囝圳地在圭圬圯圩夙多夷夸妄奸妃好她如妁字存宇守宅安寺尖屹州帆并年"], +["a6a1","式弛忙忖戎戌戍成扣扛托收早旨旬旭曲曳有朽朴朱朵次此死氖汝汗汙江池汐汕污汛汍汎灰牟牝百竹米糸缶羊羽老考而耒耳聿肉肋肌臣自至臼舌舛舟艮色艾虫血行衣西阡串亨位住佇佗佞伴佛何估佐佑伽伺伸佃佔似但佣"], +["a740","作你伯低伶余佝佈佚兌克免兵冶冷別判利刪刨劫助努劬匣即卵吝吭吞吾否呎吧呆呃吳呈呂君吩告吹吻吸吮吵吶吠吼呀吱含吟听囪困囤囫坊坑址坍"], +["a7a1","均坎圾坐坏圻壯夾妝妒妨妞妣妙妖妍妤妓妊妥孝孜孚孛完宋宏尬局屁尿尾岐岑岔岌巫希序庇床廷弄弟彤形彷役忘忌志忍忱快忸忪戒我抄抗抖技扶抉扭把扼找批扳抒扯折扮投抓抑抆改攻攸旱更束李杏材村杜杖杞杉杆杠"], +["a840","杓杗步每求汞沙沁沈沉沅沛汪決沐汰沌汨沖沒汽沃汲汾汴沆汶沍沔沘沂灶灼災灸牢牡牠狄狂玖甬甫男甸皂盯矣私秀禿究系罕肖肓肝肘肛肚育良芒"], +["a8a1","芋芍見角言谷豆豕貝赤走足身車辛辰迂迆迅迄巡邑邢邪邦那酉釆里防阮阱阪阬並乖乳事些亞享京佯依侍佳使佬供例來侃佰併侈佩佻侖佾侏侑佺兔兒兕兩具其典冽函刻券刷刺到刮制剁劾劻卒協卓卑卦卷卸卹取叔受味呵"], +["a940","咖呸咕咀呻呷咄咒咆呼咐呱呶和咚呢周咋命咎固垃坷坪坩坡坦坤坼夜奉奇奈奄奔妾妻委妹妮姑姆姐姍始姓姊妯妳姒姅孟孤季宗定官宜宙宛尚屈居"], +["a9a1","屆岷岡岸岩岫岱岳帘帚帖帕帛帑幸庚店府底庖延弦弧弩往征彿彼忝忠忽念忿怏怔怯怵怖怪怕怡性怩怫怛或戕房戾所承拉拌拄抿拂抹拒招披拓拔拋拈抨抽押拐拙拇拍抵拚抱拘拖拗拆抬拎放斧於旺昔易昌昆昂明昀昏昕昊"], +["aa40","昇服朋杭枋枕東果杳杷枇枝林杯杰板枉松析杵枚枓杼杪杲欣武歧歿氓氛泣注泳沱泌泥河沽沾沼波沫法泓沸泄油況沮泗泅泱沿治泡泛泊沬泯泜泖泠"], +["aaa1","炕炎炒炊炙爬爭爸版牧物狀狎狙狗狐玩玨玟玫玥甽疝疙疚的盂盲直知矽社祀祁秉秈空穹竺糾罔羌羋者肺肥肢肱股肫肩肴肪肯臥臾舍芳芝芙芭芽芟芹花芬芥芯芸芣芰芾芷虎虱初表軋迎返近邵邸邱邶采金長門阜陀阿阻附"], +["ab40","陂隹雨青非亟亭亮信侵侯便俠俑俏保促侶俘俟俊俗侮俐俄係俚俎俞侷兗冒冑冠剎剃削前剌剋則勇勉勃勁匍南卻厚叛咬哀咨哎哉咸咦咳哇哂咽咪品"], +["aba1","哄哈咯咫咱咻咩咧咿囿垂型垠垣垢城垮垓奕契奏奎奐姜姘姿姣姨娃姥姪姚姦威姻孩宣宦室客宥封屎屏屍屋峙峒巷帝帥帟幽庠度建弈弭彥很待徊律徇後徉怒思怠急怎怨恍恰恨恢恆恃恬恫恪恤扁拜挖按拼拭持拮拽指拱拷"], +["ac40","拯括拾拴挑挂政故斫施既春昭映昧是星昨昱昤曷柿染柱柔某柬架枯柵柩柯柄柑枴柚查枸柏柞柳枰柙柢柝柒歪殃殆段毒毗氟泉洋洲洪流津洌洱洞洗"], +["aca1","活洽派洶洛泵洹洧洸洩洮洵洎洫炫為炳炬炯炭炸炮炤爰牲牯牴狩狠狡玷珊玻玲珍珀玳甚甭畏界畎畋疫疤疥疢疣癸皆皇皈盈盆盃盅省盹相眉看盾盼眇矜砂研砌砍祆祉祈祇禹禺科秒秋穿突竿竽籽紂紅紀紉紇約紆缸美羿耄"], +["ad40","耐耍耑耶胖胥胚胃胄背胡胛胎胞胤胝致舢苧范茅苣苛苦茄若茂茉苒苗英茁苜苔苑苞苓苟苯茆虐虹虻虺衍衫要觔計訂訃貞負赴赳趴軍軌述迦迢迪迥"], +["ada1","迭迫迤迨郊郎郁郃酋酊重閂限陋陌降面革韋韭音頁風飛食首香乘亳倌倍倣俯倦倥俸倩倖倆值借倚倒們俺倀倔倨俱倡個候倘俳修倭倪俾倫倉兼冤冥冢凍凌准凋剖剜剔剛剝匪卿原厝叟哨唐唁唷哼哥哲唆哺唔哩哭員唉哮哪"], +["ae40","哦唧唇哽唏圃圄埂埔埋埃堉夏套奘奚娑娘娜娟娛娓姬娠娣娩娥娌娉孫屘宰害家宴宮宵容宸射屑展屐峭峽峻峪峨峰島崁峴差席師庫庭座弱徒徑徐恙"], +["aea1","恣恥恐恕恭恩息悄悟悚悍悔悌悅悖扇拳挈拿捎挾振捕捂捆捏捉挺捐挽挪挫挨捍捌效敉料旁旅時晉晏晃晒晌晅晁書朔朕朗校核案框桓根桂桔栩梳栗桌桑栽柴桐桀格桃株桅栓栘桁殊殉殷氣氧氨氦氤泰浪涕消涇浦浸海浙涓"], +["af40","浬涉浮浚浴浩涌涊浹涅浥涔烊烘烤烙烈烏爹特狼狹狽狸狷玆班琉珮珠珪珞畔畝畜畚留疾病症疲疳疽疼疹痂疸皋皰益盍盎眩真眠眨矩砰砧砸砝破砷"], +["afa1","砥砭砠砟砲祕祐祠祟祖神祝祗祚秤秣秧租秦秩秘窄窈站笆笑粉紡紗紋紊素索純紐紕級紜納紙紛缺罟羔翅翁耆耘耕耙耗耽耿胱脂胰脅胭胴脆胸胳脈能脊胼胯臭臬舀舐航舫舨般芻茫荒荔荊茸荐草茵茴荏茲茹茶茗荀茱茨荃"], +["b040","虔蚊蚪蚓蚤蚩蚌蚣蚜衰衷袁袂衽衹記訐討訌訕訊託訓訖訏訑豈豺豹財貢起躬軒軔軏辱送逆迷退迺迴逃追逅迸邕郡郝郢酒配酌釘針釗釜釙閃院陣陡"], +["b0a1","陛陝除陘陞隻飢馬骨高鬥鬲鬼乾偺偽停假偃偌做偉健偶偎偕偵側偷偏倏偯偭兜冕凰剪副勒務勘動匐匏匙匿區匾參曼商啪啦啄啞啡啃啊唱啖問啕唯啤唸售啜唬啣唳啁啗圈國圉域堅堊堆埠埤基堂堵執培夠奢娶婁婉婦婪婀"], +["b140","娼婢婚婆婊孰寇寅寄寂宿密尉專將屠屜屝崇崆崎崛崖崢崑崩崔崙崤崧崗巢常帶帳帷康庸庶庵庾張強彗彬彩彫得徙從徘御徠徜恿患悉悠您惋悴惦悽"], +["b1a1","情悻悵惜悼惘惕惆惟悸惚惇戚戛扈掠控捲掖探接捷捧掘措捱掩掉掃掛捫推掄授掙採掬排掏掀捻捩捨捺敝敖救教敗啟敏敘敕敔斜斛斬族旋旌旎晝晚晤晨晦晞曹勗望梁梯梢梓梵桿桶梱梧梗械梃棄梭梆梅梔條梨梟梡梂欲殺"], +["b240","毫毬氫涎涼淳淙液淡淌淤添淺清淇淋涯淑涮淞淹涸混淵淅淒渚涵淚淫淘淪深淮淨淆淄涪淬涿淦烹焉焊烽烯爽牽犁猜猛猖猓猙率琅琊球理現琍瓠瓶"], +["b2a1","瓷甜產略畦畢異疏痔痕疵痊痍皎盔盒盛眷眾眼眶眸眺硫硃硎祥票祭移窒窕笠笨笛第符笙笞笮粒粗粕絆絃統紮紹紼絀細紳組累終紲紱缽羞羚翌翎習耜聊聆脯脖脣脫脩脰脤舂舵舷舶船莎莞莘荸莢莖莽莫莒莊莓莉莠荷荻荼"], +["b340","莆莧處彪蛇蛀蚶蛄蚵蛆蛋蚱蚯蛉術袞袈被袒袖袍袋覓規訪訝訣訥許設訟訛訢豉豚販責貫貨貪貧赧赦趾趺軛軟這逍通逗連速逝逐逕逞造透逢逖逛途"], +["b3a1","部郭都酗野釵釦釣釧釭釩閉陪陵陳陸陰陴陶陷陬雀雪雩章竟頂頃魚鳥鹵鹿麥麻傢傍傅備傑傀傖傘傚最凱割剴創剩勞勝勛博厥啻喀喧啼喊喝喘喂喜喪喔喇喋喃喳單喟唾喲喚喻喬喱啾喉喫喙圍堯堪場堤堰報堡堝堠壹壺奠"], +["b440","婷媚婿媒媛媧孳孱寒富寓寐尊尋就嵌嵐崴嵇巽幅帽幀幃幾廊廁廂廄弼彭復循徨惑惡悲悶惠愜愣惺愕惰惻惴慨惱愎惶愉愀愒戟扉掣掌描揀揩揉揆揍"], +["b4a1","插揣提握揖揭揮捶援揪換摒揚揹敞敦敢散斑斐斯普晰晴晶景暑智晾晷曾替期朝棺棕棠棘棗椅棟棵森棧棹棒棲棣棋棍植椒椎棉棚楮棻款欺欽殘殖殼毯氮氯氬港游湔渡渲湧湊渠渥渣減湛湘渤湖湮渭渦湯渴湍渺測湃渝渾滋"], +["b540","溉渙湎湣湄湲湩湟焙焚焦焰無然煮焜牌犄犀猶猥猴猩琺琪琳琢琥琵琶琴琯琛琦琨甥甦畫番痢痛痣痙痘痞痠登發皖皓皴盜睏短硝硬硯稍稈程稅稀窘"], +["b5a1","窗窖童竣等策筆筐筒答筍筋筏筑粟粥絞結絨絕紫絮絲絡給絢絰絳善翔翕耋聒肅腕腔腋腑腎脹腆脾腌腓腴舒舜菩萃菸萍菠菅萋菁華菱菴著萊菰萌菌菽菲菊萸萎萄菜萇菔菟虛蛟蛙蛭蛔蛛蛤蛐蛞街裁裂袱覃視註詠評詞証詁"], +["b640","詔詛詐詆訴診訶詖象貂貯貼貳貽賁費賀貴買貶貿貸越超趁跎距跋跚跑跌跛跆軻軸軼辜逮逵週逸進逶鄂郵鄉郾酣酥量鈔鈕鈣鈉鈞鈍鈐鈇鈑閔閏開閑"], +["b6a1","間閒閎隊階隋陽隅隆隍陲隄雁雅雄集雇雯雲韌項順須飧飪飯飩飲飭馮馭黃黍黑亂傭債傲傳僅傾催傷傻傯僇剿剷剽募勦勤勢勣匯嗟嗨嗓嗦嗎嗜嗇嗑嗣嗤嗯嗚嗡嗅嗆嗥嗉園圓塞塑塘塗塚塔填塌塭塊塢塒塋奧嫁嫉嫌媾媽媼"], +["b740","媳嫂媲嵩嵯幌幹廉廈弒彙徬微愚意慈感想愛惹愁愈慎慌慄慍愾愴愧愍愆愷戡戢搓搾搞搪搭搽搬搏搜搔損搶搖搗搆敬斟新暗暉暇暈暖暄暘暍會榔業"], +["b7a1","楚楷楠楔極椰概楊楨楫楞楓楹榆楝楣楛歇歲毀殿毓毽溢溯滓溶滂源溝滇滅溥溘溼溺溫滑準溜滄滔溪溧溴煎煙煩煤煉照煜煬煦煌煥煞煆煨煖爺牒猷獅猿猾瑯瑚瑕瑟瑞瑁琿瑙瑛瑜當畸瘀痰瘁痲痱痺痿痴痳盞盟睛睫睦睞督"], +["b840","睹睪睬睜睥睨睢矮碎碰碗碘碌碉硼碑碓硿祺祿禁萬禽稜稚稠稔稟稞窟窠筷節筠筮筧粱粳粵經絹綑綁綏絛置罩罪署義羨群聖聘肆肄腱腰腸腥腮腳腫"], +["b8a1","腹腺腦舅艇蒂葷落萱葵葦葫葉葬葛萼萵葡董葩葭葆虞虜號蛹蜓蜈蜇蜀蛾蛻蜂蜃蜆蜊衙裟裔裙補裘裝裡裊裕裒覜解詫該詳試詩詰誇詼詣誠話誅詭詢詮詬詹詻訾詨豢貊貉賊資賈賄貲賃賂賅跡跟跨路跳跺跪跤跦躲較載軾輊"], +["b940","辟農運遊道遂達逼違遐遇遏過遍遑逾遁鄒鄗酬酪酩釉鈷鉗鈸鈽鉀鈾鉛鉋鉤鉑鈴鉉鉍鉅鈹鈿鉚閘隘隔隕雍雋雉雊雷電雹零靖靴靶預頑頓頊頒頌飼飴"], +["b9a1","飽飾馳馱馴髡鳩麂鼎鼓鼠僧僮僥僖僭僚僕像僑僱僎僩兢凳劃劂匱厭嗾嘀嘛嘗嗽嘔嘆嘉嘍嘎嗷嘖嘟嘈嘐嗶團圖塵塾境墓墊塹墅塽壽夥夢夤奪奩嫡嫦嫩嫗嫖嫘嫣孵寞寧寡寥實寨寢寤察對屢嶄嶇幛幣幕幗幔廓廖弊彆彰徹慇"], +["ba40","愿態慷慢慣慟慚慘慵截撇摘摔撤摸摟摺摑摧搴摭摻敲斡旗旖暢暨暝榜榨榕槁榮槓構榛榷榻榫榴槐槍榭槌榦槃榣歉歌氳漳演滾漓滴漩漾漠漬漏漂漢"], +["baa1","滿滯漆漱漸漲漣漕漫漯澈漪滬漁滲滌滷熔熙煽熊熄熒爾犒犖獄獐瑤瑣瑪瑰瑭甄疑瘧瘍瘋瘉瘓盡監瞄睽睿睡磁碟碧碳碩碣禎福禍種稱窪窩竭端管箕箋筵算箝箔箏箸箇箄粹粽精綻綰綜綽綾綠緊綴網綱綺綢綿綵綸維緒緇綬"], +["bb40","罰翠翡翟聞聚肇腐膀膏膈膊腿膂臧臺與舔舞艋蓉蒿蓆蓄蒙蒞蒲蒜蓋蒸蓀蓓蒐蒼蓑蓊蜿蜜蜻蜢蜥蜴蜘蝕蜷蜩裳褂裴裹裸製裨褚裯誦誌語誣認誡誓誤"], +["bba1","說誥誨誘誑誚誧豪貍貌賓賑賒赫趙趕跼輔輒輕輓辣遠遘遜遣遙遞遢遝遛鄙鄘鄞酵酸酷酴鉸銀銅銘銖鉻銓銜銨鉼銑閡閨閩閣閥閤隙障際雌雒需靼鞅韶頗領颯颱餃餅餌餉駁骯骰髦魁魂鳴鳶鳳麼鼻齊億儀僻僵價儂儈儉儅凜"], +["bc40","劇劈劉劍劊勰厲嘮嘻嘹嘲嘿嘴嘩噓噎噗噴嘶嘯嘰墀墟增墳墜墮墩墦奭嬉嫻嬋嫵嬌嬈寮寬審寫層履嶝嶔幢幟幡廢廚廟廝廣廠彈影德徵慶慧慮慝慕憂"], +["bca1","慼慰慫慾憧憐憫憎憬憚憤憔憮戮摩摯摹撞撲撈撐撰撥撓撕撩撒撮播撫撚撬撙撢撳敵敷數暮暫暴暱樣樟槨樁樞標槽模樓樊槳樂樅槭樑歐歎殤毅毆漿潼澄潑潦潔澆潭潛潸潮澎潺潰潤澗潘滕潯潠潟熟熬熱熨牖犛獎獗瑩璋璃"], +["bd40","瑾璀畿瘠瘩瘟瘤瘦瘡瘢皚皺盤瞎瞇瞌瞑瞋磋磅確磊碾磕碼磐稿稼穀稽稷稻窯窮箭箱範箴篆篇篁箠篌糊締練緯緻緘緬緝編緣線緞緩綞緙緲緹罵罷羯"], +["bda1","翩耦膛膜膝膠膚膘蔗蔽蔚蓮蔬蔭蔓蔑蔣蔡蔔蓬蔥蓿蔆螂蝴蝶蝠蝦蝸蝨蝙蝗蝌蝓衛衝褐複褒褓褕褊誼諒談諄誕請諸課諉諂調誰論諍誶誹諛豌豎豬賠賞賦賤賬賭賢賣賜質賡赭趟趣踫踐踝踢踏踩踟踡踞躺輝輛輟輩輦輪輜輞"], +["be40","輥適遮遨遭遷鄰鄭鄧鄱醇醉醋醃鋅銻銷鋪銬鋤鋁銳銼鋒鋇鋰銲閭閱霄霆震霉靠鞍鞋鞏頡頫頜颳養餓餒餘駝駐駟駛駑駕駒駙骷髮髯鬧魅魄魷魯鴆鴉"], +["bea1","鴃麩麾黎墨齒儒儘儔儐儕冀冪凝劑劓勳噙噫噹噩噤噸噪器噥噱噯噬噢噶壁墾壇壅奮嬝嬴學寰導彊憲憑憩憊懍憶憾懊懈戰擅擁擋撻撼據擄擇擂操撿擒擔撾整曆曉暹曄曇暸樽樸樺橙橫橘樹橄橢橡橋橇樵機橈歙歷氅濂澱澡"], +["bf40","濃澤濁澧澳激澹澶澦澠澴熾燉燐燒燈燕熹燎燙燜燃燄獨璜璣璘璟璞瓢甌甍瘴瘸瘺盧盥瞠瞞瞟瞥磨磚磬磧禦積穎穆穌穋窺篙簑築篤篛篡篩篦糕糖縊"], +["bfa1","縑縈縛縣縞縝縉縐罹羲翰翱翮耨膳膩膨臻興艘艙蕊蕙蕈蕨蕩蕃蕉蕭蕪蕞螃螟螞螢融衡褪褲褥褫褡親覦諦諺諫諱謀諜諧諮諾謁謂諷諭諳諶諼豫豭貓賴蹄踱踴蹂踹踵輻輯輸輳辨辦遵遴選遲遼遺鄴醒錠錶鋸錳錯錢鋼錫錄錚"], +["c040","錐錦錡錕錮錙閻隧隨險雕霎霑霖霍霓霏靛靜靦鞘頰頸頻頷頭頹頤餐館餞餛餡餚駭駢駱骸骼髻髭鬨鮑鴕鴣鴦鴨鴒鴛默黔龍龜優償儡儲勵嚎嚀嚐嚅嚇"], +["c0a1","嚏壕壓壑壎嬰嬪嬤孺尷屨嶼嶺嶽嶸幫彌徽應懂懇懦懋戲戴擎擊擘擠擰擦擬擱擢擭斂斃曙曖檀檔檄檢檜櫛檣橾檗檐檠歜殮毚氈濘濱濟濠濛濤濫濯澀濬濡濩濕濮濰燧營燮燦燥燭燬燴燠爵牆獰獲璩環璦璨癆療癌盪瞳瞪瞰瞬"], +["c140","瞧瞭矯磷磺磴磯礁禧禪穗窿簇簍篾篷簌篠糠糜糞糢糟糙糝縮績繆縷縲繃縫總縱繅繁縴縹繈縵縿縯罄翳翼聱聲聰聯聳臆臃膺臂臀膿膽臉膾臨舉艱薪"], +["c1a1","薄蕾薜薑薔薯薛薇薨薊虧蟀蟑螳蟒蟆螫螻螺蟈蟋褻褶襄褸褽覬謎謗謙講謊謠謝謄謐豁谿豳賺賽購賸賻趨蹉蹋蹈蹊轄輾轂轅輿避遽還邁邂邀鄹醣醞醜鍍鎂錨鍵鍊鍥鍋錘鍾鍬鍛鍰鍚鍔闊闋闌闈闆隱隸雖霜霞鞠韓顆颶餵騁"], +["c240","駿鮮鮫鮪鮭鴻鴿麋黏點黜黝黛鼾齋叢嚕嚮壙壘嬸彝懣戳擴擲擾攆擺擻擷斷曜朦檳檬櫃檻檸櫂檮檯歟歸殯瀉瀋濾瀆濺瀑瀏燻燼燾燸獷獵璧璿甕癖癘"], +["c2a1","癒瞽瞿瞻瞼礎禮穡穢穠竄竅簫簧簪簞簣簡糧織繕繞繚繡繒繙罈翹翻職聶臍臏舊藏薩藍藐藉薰薺薹薦蟯蟬蟲蟠覆覲觴謨謹謬謫豐贅蹙蹣蹦蹤蹟蹕軀轉轍邇邃邈醫醬釐鎔鎊鎖鎢鎳鎮鎬鎰鎘鎚鎗闔闖闐闕離雜雙雛雞霤鞣鞦"], +["c340","鞭韹額顏題顎顓颺餾餿餽餮馥騎髁鬃鬆魏魎魍鯊鯉鯽鯈鯀鵑鵝鵠黠鼕鼬儳嚥壞壟壢寵龐廬懲懷懶懵攀攏曠曝櫥櫝櫚櫓瀛瀟瀨瀚瀝瀕瀘爆爍牘犢獸"], +["c3a1","獺璽瓊瓣疇疆癟癡矇礙禱穫穩簾簿簸簽簷籀繫繭繹繩繪羅繳羶羹羸臘藩藝藪藕藤藥藷蟻蠅蠍蟹蟾襠襟襖襞譁譜識證譚譎譏譆譙贈贊蹼蹲躇蹶蹬蹺蹴轔轎辭邊邋醱醮鏡鏑鏟鏃鏈鏜鏝鏖鏢鏍鏘鏤鏗鏨關隴難霪霧靡韜韻類"], +["c440","願顛颼饅饉騖騙鬍鯨鯧鯖鯛鶉鵡鵲鵪鵬麒麗麓麴勸嚨嚷嚶嚴嚼壤孀孃孽寶巉懸懺攘攔攙曦朧櫬瀾瀰瀲爐獻瓏癢癥礦礪礬礫竇競籌籃籍糯糰辮繽繼"], +["c4a1","纂罌耀臚艦藻藹蘑藺蘆蘋蘇蘊蠔蠕襤覺觸議譬警譯譟譫贏贍躉躁躅躂醴釋鐘鐃鏽闡霰飄饒饑馨騫騰騷騵鰓鰍鹹麵黨鼯齟齣齡儷儸囁囀囂夔屬巍懼懾攝攜斕曩櫻欄櫺殲灌爛犧瓖瓔癩矓籐纏續羼蘗蘭蘚蠣蠢蠡蠟襪襬覽譴"], +["c540","護譽贓躊躍躋轟辯醺鐮鐳鐵鐺鐸鐲鐫闢霸霹露響顧顥饗驅驃驀騾髏魔魑鰭鰥鶯鶴鷂鶸麝黯鼙齜齦齧儼儻囈囊囉孿巔巒彎懿攤權歡灑灘玀瓤疊癮癬"], +["c5a1","禳籠籟聾聽臟襲襯觼讀贖贗躑躓轡酈鑄鑑鑒霽霾韃韁顫饕驕驍髒鬚鱉鰱鰾鰻鷓鷗鼴齬齪龔囌巖戀攣攫攪曬欐瓚竊籤籣籥纓纖纔臢蘸蘿蠱變邐邏鑣鑠鑤靨顯饜驚驛驗髓體髑鱔鱗鱖鷥麟黴囑壩攬灞癱癲矗罐羈蠶蠹衢讓讒"], +["c640","讖艷贛釀鑪靂靈靄韆顰驟鬢魘鱟鷹鷺鹼鹽鼇齷齲廳欖灣籬籮蠻觀躡釁鑲鑰顱饞髖鬣黌灤矚讚鑷韉驢驥纜讜躪釅鑽鑾鑼鱷鱸黷豔鑿鸚爨驪鬱鸛鸞籲"], +["c940","乂乜凵匚厂万丌乇亍囗兀屮彳丏冇与丮亓仂仉仈冘勼卬厹圠夃夬尐巿旡殳毌气爿丱丼仨仜仩仡仝仚刌匜卌圢圣夗夯宁宄尒尻屴屳帄庀庂忉戉扐氕"], +["c9a1","氶汃氿氻犮犰玊禸肊阞伎优伬仵伔仱伀价伈伝伂伅伢伓伄仴伒冱刓刉刐劦匢匟卍厊吇囡囟圮圪圴夼妀奼妅奻奾奷奿孖尕尥屼屺屻屾巟幵庄异弚彴忕忔忏扜扞扤扡扦扢扙扠扚扥旯旮朾朹朸朻机朿朼朳氘汆汒汜汏汊汔汋"], +["ca40","汌灱牞犴犵玎甪癿穵网艸艼芀艽艿虍襾邙邗邘邛邔阢阤阠阣佖伻佢佉体佤伾佧佒佟佁佘伭伳伿佡冏冹刜刞刡劭劮匉卣卲厎厏吰吷吪呔呅吙吜吥吘"], +["caa1","吽呏呁吨吤呇囮囧囥坁坅坌坉坋坒夆奀妦妘妠妗妎妢妐妏妧妡宎宒尨尪岍岏岈岋岉岒岊岆岓岕巠帊帎庋庉庌庈庍弅弝彸彶忒忑忐忭忨忮忳忡忤忣忺忯忷忻怀忴戺抃抌抎抏抔抇扱扻扺扰抁抈扷扽扲扴攷旰旴旳旲旵杅杇"], +["cb40","杙杕杌杈杝杍杚杋毐氙氚汸汧汫沄沋沏汱汯汩沚汭沇沕沜汦汳汥汻沎灴灺牣犿犽狃狆狁犺狅玕玗玓玔玒町甹疔疕皁礽耴肕肙肐肒肜芐芏芅芎芑芓"], +["cba1","芊芃芄豸迉辿邟邡邥邞邧邠阰阨阯阭丳侘佼侅佽侀侇佶佴侉侄佷佌侗佪侚佹侁佸侐侜侔侞侒侂侕佫佮冞冼冾刵刲刳剆刱劼匊匋匼厒厔咇呿咁咑咂咈呫呺呾呥呬呴呦咍呯呡呠咘呣呧呤囷囹坯坲坭坫坱坰坶垀坵坻坳坴坢"], +["cc40","坨坽夌奅妵妺姏姎妲姌姁妶妼姃姖妱妽姀姈妴姇孢孥宓宕屄屇岮岤岠岵岯岨岬岟岣岭岢岪岧岝岥岶岰岦帗帔帙弨弢弣弤彔徂彾彽忞忥怭怦怙怲怋"], +["cca1","怴怊怗怳怚怞怬怢怍怐怮怓怑怌怉怜戔戽抭抴拑抾抪抶拊抮抳抯抻抩抰抸攽斨斻昉旼昄昒昈旻昃昋昍昅旽昑昐曶朊枅杬枎枒杶杻枘枆构杴枍枌杺枟枑枙枃杽极杸杹枔欥殀歾毞氝沓泬泫泮泙沶泔沭泧沷泐泂沺泃泆泭泲"], +["cd40","泒泝沴沊沝沀泞泀洰泍泇沰泹泏泩泑炔炘炅炓炆炄炑炖炂炚炃牪狖狋狘狉狜狒狔狚狌狑玤玡玭玦玢玠玬玝瓝瓨甿畀甾疌疘皯盳盱盰盵矸矼矹矻矺"], +["cda1","矷祂礿秅穸穻竻籵糽耵肏肮肣肸肵肭舠芠苀芫芚芘芛芵芧芮芼芞芺芴芨芡芩苂芤苃芶芢虰虯虭虮豖迒迋迓迍迖迕迗邲邴邯邳邰阹阽阼阺陃俍俅俓侲俉俋俁俔俜俙侻侳俛俇俖侺俀侹俬剄剉勀勂匽卼厗厖厙厘咺咡咭咥哏"], +["ce40","哃茍咷咮哖咶哅哆咠呰咼咢咾呲哞咰垵垞垟垤垌垗垝垛垔垘垏垙垥垚垕壴复奓姡姞姮娀姱姝姺姽姼姶姤姲姷姛姩姳姵姠姾姴姭宨屌峐峘峌峗峋峛"], +["cea1","峞峚峉峇峊峖峓峔峏峈峆峎峟峸巹帡帢帣帠帤庰庤庢庛庣庥弇弮彖徆怷怹恔恲恞恅恓恇恉恛恌恀恂恟怤恄恘恦恮扂扃拏挍挋拵挎挃拫拹挏挌拸拶挀挓挔拺挕拻拰敁敃斪斿昶昡昲昵昜昦昢昳昫昺昝昴昹昮朏朐柁柲柈枺"], +["cf40","柜枻柸柘柀枷柅柫柤柟枵柍枳柷柶柮柣柂枹柎柧柰枲柼柆柭柌枮柦柛柺柉柊柃柪柋欨殂殄殶毖毘毠氠氡洨洴洭洟洼洿洒洊泚洳洄洙洺洚洑洀洝浂"], +["cfa1","洁洘洷洃洏浀洇洠洬洈洢洉洐炷炟炾炱炰炡炴炵炩牁牉牊牬牰牳牮狊狤狨狫狟狪狦狣玅珌珂珈珅玹玶玵玴珫玿珇玾珃珆玸珋瓬瓮甮畇畈疧疪癹盄眈眃眄眅眊盷盻盺矧矨砆砑砒砅砐砏砎砉砃砓祊祌祋祅祄秕种秏秖秎窀"], +["d040","穾竑笀笁籺籸籹籿粀粁紃紈紁罘羑羍羾耇耎耏耔耷胘胇胠胑胈胂胐胅胣胙胜胊胕胉胏胗胦胍臿舡芔苙苾苹茇苨茀苕茺苫苖苴苬苡苲苵茌苻苶苰苪"], +["d0a1","苤苠苺苳苭虷虴虼虳衁衎衧衪衩觓訄訇赲迣迡迮迠郱邽邿郕郅邾郇郋郈釔釓陔陏陑陓陊陎倞倅倇倓倢倰倛俵俴倳倷倬俶俷倗倜倠倧倵倯倱倎党冔冓凊凄凅凈凎剡剚剒剞剟剕剢勍匎厞唦哢唗唒哧哳哤唚哿唄唈哫唑唅哱"], +["d140","唊哻哷哸哠唎唃唋圁圂埌堲埕埒垺埆垽垼垸垶垿埇埐垹埁夎奊娙娖娭娮娕娏娗娊娞娳孬宧宭宬尃屖屔峬峿峮峱峷崀峹帩帨庨庮庪庬弳弰彧恝恚恧"], +["d1a1","恁悢悈悀悒悁悝悃悕悛悗悇悜悎戙扆拲挐捖挬捄捅挶捃揤挹捋捊挼挩捁挴捘捔捙挭捇挳捚捑挸捗捀捈敊敆旆旃旄旂晊晟晇晑朒朓栟栚桉栲栳栻桋桏栖栱栜栵栫栭栯桎桄栴栝栒栔栦栨栮桍栺栥栠欬欯欭欱欴歭肂殈毦毤"], +["d240","毨毣毢毧氥浺浣浤浶洍浡涒浘浢浭浯涑涍淯浿涆浞浧浠涗浰浼浟涂涘洯浨涋浾涀涄洖涃浻浽浵涐烜烓烑烝烋缹烢烗烒烞烠烔烍烅烆烇烚烎烡牂牸"], +["d2a1","牷牶猀狺狴狾狶狳狻猁珓珙珥珖玼珧珣珩珜珒珛珔珝珚珗珘珨瓞瓟瓴瓵甡畛畟疰痁疻痄痀疿疶疺皊盉眝眛眐眓眒眣眑眕眙眚眢眧砣砬砢砵砯砨砮砫砡砩砳砪砱祔祛祏祜祓祒祑秫秬秠秮秭秪秜秞秝窆窉窅窋窌窊窇竘笐"], +["d340","笄笓笅笏笈笊笎笉笒粄粑粊粌粈粍粅紞紝紑紎紘紖紓紟紒紏紌罜罡罞罠罝罛羖羒翃翂翀耖耾耹胺胲胹胵脁胻脀舁舯舥茳茭荄茙荑茥荖茿荁茦茜茢"], +["d3a1","荂荎茛茪茈茼荍茖茤茠茷茯茩荇荅荌荓茞茬荋茧荈虓虒蚢蚨蚖蚍蚑蚞蚇蚗蚆蚋蚚蚅蚥蚙蚡蚧蚕蚘蚎蚝蚐蚔衃衄衭衵衶衲袀衱衿衯袃衾衴衼訒豇豗豻貤貣赶赸趵趷趶軑軓迾迵适迿迻逄迼迶郖郠郙郚郣郟郥郘郛郗郜郤酐"], +["d440","酎酏釕釢釚陜陟隼飣髟鬯乿偰偪偡偞偠偓偋偝偲偈偍偁偛偊偢倕偅偟偩偫偣偤偆偀偮偳偗偑凐剫剭剬剮勖勓匭厜啵啶唼啍啐唴唪啑啢唶唵唰啒啅"], +["d4a1","唌唲啥啎唹啈唭唻啀啋圊圇埻堔埢埶埜埴堀埭埽堈埸堋埳埏堇埮埣埲埥埬埡堎埼堐埧堁堌埱埩埰堍堄奜婠婘婕婧婞娸娵婭婐婟婥婬婓婤婗婃婝婒婄婛婈媎娾婍娹婌婰婩婇婑婖婂婜孲孮寁寀屙崞崋崝崚崠崌崨崍崦崥崏"], +["d540","崰崒崣崟崮帾帴庱庴庹庲庳弶弸徛徖徟悊悐悆悾悰悺惓惔惏惤惙惝惈悱惛悷惊悿惃惍惀挲捥掊掂捽掽掞掭掝掗掫掎捯掇掐据掯捵掜捭掮捼掤挻掟"], +["d5a1","捸掅掁掑掍捰敓旍晥晡晛晙晜晢朘桹梇梐梜桭桮梮梫楖桯梣梬梩桵桴梲梏桷梒桼桫桲梪梀桱桾梛梖梋梠梉梤桸桻梑梌梊桽欶欳欷欸殑殏殍殎殌氪淀涫涴涳湴涬淩淢涷淶淔渀淈淠淟淖涾淥淜淝淛淴淊涽淭淰涺淕淂淏淉"], +["d640","淐淲淓淽淗淍淣涻烺焍烷焗烴焌烰焄烳焐烼烿焆焓焀烸烶焋焂焎牾牻牼牿猝猗猇猑猘猊猈狿猏猞玈珶珸珵琄琁珽琇琀珺珼珿琌琋珴琈畤畣痎痒痏"], +["d6a1","痋痌痑痐皏皉盓眹眯眭眱眲眴眳眽眥眻眵硈硒硉硍硊硌砦硅硐祤祧祩祪祣祫祡离秺秸秶秷窏窔窐笵筇笴笥笰笢笤笳笘笪笝笱笫笭笯笲笸笚笣粔粘粖粣紵紽紸紶紺絅紬紩絁絇紾紿絊紻紨罣羕羜羝羛翊翋翍翐翑翇翏翉耟"], +["d740","耞耛聇聃聈脘脥脙脛脭脟脬脞脡脕脧脝脢舑舸舳舺舴舲艴莐莣莨莍荺荳莤荴莏莁莕莙荵莔莩荽莃莌莝莛莪莋荾莥莯莈莗莰荿莦莇莮荶莚虙虖蚿蚷"], +["d7a1","蛂蛁蛅蚺蚰蛈蚹蚳蚸蛌蚴蚻蚼蛃蚽蚾衒袉袕袨袢袪袚袑袡袟袘袧袙袛袗袤袬袌袓袎覂觖觙觕訰訧訬訞谹谻豜豝豽貥赽赻赹趼跂趹趿跁軘軞軝軜軗軠軡逤逋逑逜逌逡郯郪郰郴郲郳郔郫郬郩酖酘酚酓酕釬釴釱釳釸釤釹釪"], +["d840","釫釷釨釮镺閆閈陼陭陫陱陯隿靪頄飥馗傛傕傔傞傋傣傃傌傎傝偨傜傒傂傇兟凔匒匑厤厧喑喨喥喭啷噅喢喓喈喏喵喁喣喒喤啽喌喦啿喕喡喎圌堩堷"], +["d8a1","堙堞堧堣堨埵塈堥堜堛堳堿堶堮堹堸堭堬堻奡媯媔媟婺媢媞婸媦婼媥媬媕媮娷媄媊媗媃媋媩婻婽媌媜媏媓媝寪寍寋寔寑寊寎尌尰崷嵃嵫嵁嵋崿崵嵑嵎嵕崳崺嵒崽崱嵙嵂崹嵉崸崼崲崶嵀嵅幄幁彘徦徥徫惉悹惌惢惎惄愔"], +["d940","惲愊愖愅惵愓惸惼惾惁愃愘愝愐惿愄愋扊掔掱掰揎揥揨揯揃撝揳揊揠揶揕揲揵摡揟掾揝揜揄揘揓揂揇揌揋揈揰揗揙攲敧敪敤敜敨敥斌斝斞斮旐旒"], +["d9a1","晼晬晻暀晱晹晪晲朁椌棓椄棜椪棬棪棱椏棖棷棫棤棶椓椐棳棡椇棌椈楰梴椑棯棆椔棸棐棽棼棨椋椊椗棎棈棝棞棦棴棑椆棔棩椕椥棇欹欻欿欼殔殗殙殕殽毰毲毳氰淼湆湇渟湉溈渼渽湅湢渫渿湁湝湳渜渳湋湀湑渻渃渮湞"], +["da40","湨湜湡渱渨湠湱湫渹渢渰湓湥渧湸湤湷湕湹湒湦渵渶湚焠焞焯烻焮焱焣焥焢焲焟焨焺焛牋牚犈犉犆犅犋猒猋猰猢猱猳猧猲猭猦猣猵猌琮琬琰琫琖"], +["daa1","琚琡琭琱琤琣琝琩琠琲瓻甯畯畬痧痚痡痦痝痟痤痗皕皒盚睆睇睄睍睅睊睎睋睌矞矬硠硤硥硜硭硱硪确硰硩硨硞硢祴祳祲祰稂稊稃稌稄窙竦竤筊笻筄筈筌筎筀筘筅粢粞粨粡絘絯絣絓絖絧絪絏絭絜絫絒絔絩絑絟絎缾缿罥"], +["db40","罦羢羠羡翗聑聏聐胾胔腃腊腒腏腇脽腍脺臦臮臷臸臹舄舼舽舿艵茻菏菹萣菀菨萒菧菤菼菶萐菆菈菫菣莿萁菝菥菘菿菡菋菎菖菵菉萉萏菞萑萆菂菳"], +["dba1","菕菺菇菑菪萓菃菬菮菄菻菗菢萛菛菾蛘蛢蛦蛓蛣蛚蛪蛝蛫蛜蛬蛩蛗蛨蛑衈衖衕袺裗袹袸裀袾袶袼袷袽袲褁裉覕覘覗觝觚觛詎詍訹詙詀詗詘詄詅詒詈詑詊詌詏豟貁貀貺貾貰貹貵趄趀趉跘跓跍跇跖跜跏跕跙跈跗跅軯軷軺"], +["dc40","軹軦軮軥軵軧軨軶軫軱軬軴軩逭逴逯鄆鄬鄄郿郼鄈郹郻鄁鄀鄇鄅鄃酡酤酟酢酠鈁鈊鈥鈃鈚鈦鈏鈌鈀鈒釿釽鈆鈄鈧鈂鈜鈤鈙鈗鈅鈖镻閍閌閐隇陾隈"], +["dca1","隉隃隀雂雈雃雱雰靬靰靮頇颩飫鳦黹亃亄亶傽傿僆傮僄僊傴僈僂傰僁傺傱僋僉傶傸凗剺剸剻剼嗃嗛嗌嗐嗋嗊嗝嗀嗔嗄嗩喿嗒喍嗏嗕嗢嗖嗈嗲嗍嗙嗂圔塓塨塤塏塍塉塯塕塎塝塙塥塛堽塣塱壼嫇嫄嫋媺媸媱媵媰媿嫈媻嫆"], +["dd40","媷嫀嫊媴媶嫍媹媐寖寘寙尟尳嵱嵣嵊嵥嵲嵬嵞嵨嵧嵢巰幏幎幊幍幋廅廌廆廋廇彀徯徭惷慉慊愫慅愶愲愮慆愯慏愩慀戠酨戣戥戤揅揱揫搐搒搉搠搤"], +["dda1","搳摃搟搕搘搹搷搢搣搌搦搰搨摁搵搯搊搚摀搥搧搋揧搛搮搡搎敯斒旓暆暌暕暐暋暊暙暔晸朠楦楟椸楎楢楱椿楅楪椹楂楗楙楺楈楉椵楬椳椽楥棰楸椴楩楀楯楄楶楘楁楴楌椻楋椷楜楏楑椲楒椯楻椼歆歅歃歂歈歁殛嗀毻毼"], +["de40","毹毷毸溛滖滈溏滀溟溓溔溠溱溹滆滒溽滁溞滉溷溰滍溦滏溲溾滃滜滘溙溒溎溍溤溡溿溳滐滊溗溮溣煇煔煒煣煠煁煝煢煲煸煪煡煂煘煃煋煰煟煐煓"], +["dea1","煄煍煚牏犍犌犑犐犎猼獂猻猺獀獊獉瑄瑊瑋瑒瑑瑗瑀瑏瑐瑎瑂瑆瑍瑔瓡瓿瓾瓽甝畹畷榃痯瘏瘃痷痾痼痹痸瘐痻痶痭痵痽皙皵盝睕睟睠睒睖睚睩睧睔睙睭矠碇碚碔碏碄碕碅碆碡碃硹碙碀碖硻祼禂祽祹稑稘稙稒稗稕稢稓"], +["df40","稛稐窣窢窞竫筦筤筭筴筩筲筥筳筱筰筡筸筶筣粲粴粯綈綆綀綍絿綅絺綎絻綃絼綌綔綄絽綒罭罫罧罨罬羦羥羧翛翜耡腤腠腷腜腩腛腢腲朡腞腶腧腯"], +["dfa1","腄腡舝艉艄艀艂艅蓱萿葖葶葹蒏蒍葥葑葀蒆葧萰葍葽葚葙葴葳葝蔇葞萷萺萴葺葃葸萲葅萩菙葋萯葂萭葟葰萹葎葌葒葯蓅蒎萻葇萶萳葨葾葄萫葠葔葮葐蜋蜄蛷蜌蛺蛖蛵蝍蛸蜎蜉蜁蛶蜍蜅裖裋裍裎裞裛裚裌裐覅覛觟觥觤"], +["e040","觡觠觢觜触詶誆詿詡訿詷誂誄詵誃誁詴詺谼豋豊豥豤豦貆貄貅賌赨赩趑趌趎趏趍趓趔趐趒跰跠跬跱跮跐跩跣跢跧跲跫跴輆軿輁輀輅輇輈輂輋遒逿"], +["e0a1","遄遉逽鄐鄍鄏鄑鄖鄔鄋鄎酮酯鉈鉒鈰鈺鉦鈳鉥鉞銃鈮鉊鉆鉭鉬鉏鉠鉧鉯鈶鉡鉰鈱鉔鉣鉐鉲鉎鉓鉌鉖鈲閟閜閞閛隒隓隑隗雎雺雽雸雵靳靷靸靲頏頍頎颬飶飹馯馲馰馵骭骫魛鳪鳭鳧麀黽僦僔僗僨僳僛僪僝僤僓僬僰僯僣僠"], +["e140","凘劀劁勩勫匰厬嘧嘕嘌嘒嗼嘏嘜嘁嘓嘂嗺嘝嘄嗿嗹墉塼墐墘墆墁塿塴墋塺墇墑墎塶墂墈塻墔墏壾奫嫜嫮嫥嫕嫪嫚嫭嫫嫳嫢嫠嫛嫬嫞嫝嫙嫨嫟孷寠"], +["e1a1","寣屣嶂嶀嵽嶆嵺嶁嵷嶊嶉嶈嵾嵼嶍嵹嵿幘幙幓廘廑廗廎廜廕廙廒廔彄彃彯徶愬愨慁慞慱慳慒慓慲慬憀慴慔慺慛慥愻慪慡慖戩戧戫搫摍摛摝摴摶摲摳摽摵摦撦摎撂摞摜摋摓摠摐摿搿摬摫摙摥摷敳斠暡暠暟朅朄朢榱榶槉"], +["e240","榠槎榖榰榬榼榑榙榎榧榍榩榾榯榿槄榽榤槔榹槊榚槏榳榓榪榡榞槙榗榐槂榵榥槆歊歍歋殞殟殠毃毄毾滎滵滱漃漥滸漷滻漮漉潎漙漚漧漘漻漒滭漊"], +["e2a1","漶潳滹滮漭潀漰漼漵滫漇漎潃漅滽滶漹漜滼漺漟漍漞漈漡熇熐熉熀熅熂熏煻熆熁熗牄牓犗犕犓獃獍獑獌瑢瑳瑱瑵瑲瑧瑮甀甂甃畽疐瘖瘈瘌瘕瘑瘊瘔皸瞁睼瞅瞂睮瞀睯睾瞃碲碪碴碭碨硾碫碞碥碠碬碢碤禘禊禋禖禕禔禓"], +["e340","禗禈禒禐稫穊稰稯稨稦窨窫窬竮箈箜箊箑箐箖箍箌箛箎箅箘劄箙箤箂粻粿粼粺綧綷緂綣綪緁緀緅綝緎緄緆緋緌綯綹綖綼綟綦綮綩綡緉罳翢翣翥翞"], +["e3a1","耤聝聜膉膆膃膇膍膌膋舕蒗蒤蒡蒟蒺蓎蓂蒬蒮蒫蒹蒴蓁蓍蒪蒚蒱蓐蒝蒧蒻蒢蒔蓇蓌蒛蒩蒯蒨蓖蒘蒶蓏蒠蓗蓔蓒蓛蒰蒑虡蜳蜣蜨蝫蝀蜮蜞蜡蜙蜛蝃蜬蝁蜾蝆蜠蜲蜪蜭蜼蜒蜺蜱蜵蝂蜦蜧蜸蜤蜚蜰蜑裷裧裱裲裺裾裮裼裶裻"], +["e440","裰裬裫覝覡覟覞觩觫觨誫誙誋誒誏誖谽豨豩賕賏賗趖踉踂跿踍跽踊踃踇踆踅跾踀踄輐輑輎輍鄣鄜鄠鄢鄟鄝鄚鄤鄡鄛酺酲酹酳銥銤鉶銛鉺銠銔銪銍"], +["e4a1","銦銚銫鉹銗鉿銣鋮銎銂銕銢鉽銈銡銊銆銌銙銧鉾銇銩銝銋鈭隞隡雿靘靽靺靾鞃鞀鞂靻鞄鞁靿韎韍頖颭颮餂餀餇馝馜駃馹馻馺駂馽駇骱髣髧鬾鬿魠魡魟鳱鳲鳵麧僿儃儰僸儆儇僶僾儋儌僽儊劋劌勱勯噈噂噌嘵噁噊噉噆噘"], +["e540","噚噀嘳嘽嘬嘾嘸嘪嘺圚墫墝墱墠墣墯墬墥墡壿嫿嫴嫽嫷嫶嬃嫸嬂嫹嬁嬇嬅嬏屧嶙嶗嶟嶒嶢嶓嶕嶠嶜嶡嶚嶞幩幝幠幜緳廛廞廡彉徲憋憃慹憱憰憢憉"], +["e5a1","憛憓憯憭憟憒憪憡憍慦憳戭摮摰撖撠撅撗撜撏撋撊撌撣撟摨撱撘敶敺敹敻斲斳暵暰暩暲暷暪暯樀樆樗槥槸樕槱槤樠槿槬槢樛樝槾樧槲槮樔槷槧橀樈槦槻樍槼槫樉樄樘樥樏槶樦樇槴樖歑殥殣殢殦氁氀毿氂潁漦潾澇濆澒"], +["e640","澍澉澌潢潏澅潚澖潶潬澂潕潲潒潐潗澔澓潝漀潡潫潽潧澐潓澋潩潿澕潣潷潪潻熲熯熛熰熠熚熩熵熝熥熞熤熡熪熜熧熳犘犚獘獒獞獟獠獝獛獡獚獙"], +["e6a1","獢璇璉璊璆璁瑽璅璈瑼瑹甈甇畾瘥瘞瘙瘝瘜瘣瘚瘨瘛皜皝皞皛瞍瞏瞉瞈磍碻磏磌磑磎磔磈磃磄磉禚禡禠禜禢禛歶稹窲窴窳箷篋箾箬篎箯箹篊箵糅糈糌糋緷緛緪緧緗緡縃緺緦緶緱緰緮緟罶羬羰羭翭翫翪翬翦翨聤聧膣膟"], +["e740","膞膕膢膙膗舖艏艓艒艐艎艑蔤蔻蔏蔀蔩蔎蔉蔍蔟蔊蔧蔜蓻蔫蓺蔈蔌蓴蔪蓲蔕蓷蓫蓳蓼蔒蓪蓩蔖蓾蔨蔝蔮蔂蓽蔞蓶蔱蔦蓧蓨蓰蓯蓹蔘蔠蔰蔋蔙蔯虢"], +["e7a1","蝖蝣蝤蝷蟡蝳蝘蝔蝛蝒蝡蝚蝑蝞蝭蝪蝐蝎蝟蝝蝯蝬蝺蝮蝜蝥蝏蝻蝵蝢蝧蝩衚褅褌褔褋褗褘褙褆褖褑褎褉覢覤覣觭觰觬諏諆誸諓諑諔諕誻諗誾諀諅諘諃誺誽諙谾豍貏賥賟賙賨賚賝賧趠趜趡趛踠踣踥踤踮踕踛踖踑踙踦踧"], +["e840","踔踒踘踓踜踗踚輬輤輘輚輠輣輖輗遳遰遯遧遫鄯鄫鄩鄪鄲鄦鄮醅醆醊醁醂醄醀鋐鋃鋄鋀鋙銶鋏鋱鋟鋘鋩鋗鋝鋌鋯鋂鋨鋊鋈鋎鋦鋍鋕鋉鋠鋞鋧鋑鋓"], +["e8a1","銵鋡鋆銴镼閬閫閮閰隤隢雓霅霈霂靚鞊鞎鞈韐韏頞頝頦頩頨頠頛頧颲餈飺餑餔餖餗餕駜駍駏駓駔駎駉駖駘駋駗駌骳髬髫髳髲髱魆魃魧魴魱魦魶魵魰魨魤魬鳼鳺鳽鳿鳷鴇鴀鳹鳻鴈鴅鴄麃黓鼏鼐儜儓儗儚儑凞匴叡噰噠噮"], +["e940","噳噦噣噭噲噞噷圜圛壈墽壉墿墺壂墼壆嬗嬙嬛嬡嬔嬓嬐嬖嬨嬚嬠嬞寯嶬嶱嶩嶧嶵嶰嶮嶪嶨嶲嶭嶯嶴幧幨幦幯廩廧廦廨廥彋徼憝憨憖懅憴懆懁懌憺"], +["e9a1","憿憸憌擗擖擐擏擉撽撉擃擛擳擙攳敿敼斢曈暾曀曊曋曏暽暻暺曌朣樴橦橉橧樲橨樾橝橭橶橛橑樨橚樻樿橁橪橤橐橏橔橯橩橠樼橞橖橕橍橎橆歕歔歖殧殪殫毈毇氄氃氆澭濋澣濇澼濎濈潞濄澽澞濊澨瀄澥澮澺澬澪濏澿澸"], +["ea40","澢濉澫濍澯澲澰燅燂熿熸燖燀燁燋燔燊燇燏熽燘熼燆燚燛犝犞獩獦獧獬獥獫獪瑿璚璠璔璒璕璡甋疀瘯瘭瘱瘽瘳瘼瘵瘲瘰皻盦瞚瞝瞡瞜瞛瞢瞣瞕瞙"], +["eaa1","瞗磝磩磥磪磞磣磛磡磢磭磟磠禤穄穈穇窶窸窵窱窷篞篣篧篝篕篥篚篨篹篔篪篢篜篫篘篟糒糔糗糐糑縒縡縗縌縟縠縓縎縜縕縚縢縋縏縖縍縔縥縤罃罻罼罺羱翯耪耩聬膱膦膮膹膵膫膰膬膴膲膷膧臲艕艖艗蕖蕅蕫蕍蕓蕡蕘"], +["eb40","蕀蕆蕤蕁蕢蕄蕑蕇蕣蔾蕛蕱蕎蕮蕵蕕蕧蕠薌蕦蕝蕔蕥蕬虣虥虤螛螏螗螓螒螈螁螖螘蝹螇螣螅螐螑螝螄螔螜螚螉褞褦褰褭褮褧褱褢褩褣褯褬褟觱諠"], +["eba1","諢諲諴諵諝謔諤諟諰諈諞諡諨諿諯諻貑貒貐賵賮賱賰賳赬赮趥趧踳踾踸蹀蹅踶踼踽蹁踰踿躽輶輮輵輲輹輷輴遶遹遻邆郺鄳鄵鄶醓醐醑醍醏錧錞錈錟錆錏鍺錸錼錛錣錒錁鍆錭錎錍鋋錝鋺錥錓鋹鋷錴錂錤鋿錩錹錵錪錔錌"], +["ec40","錋鋾錉錀鋻錖閼闍閾閹閺閶閿閵閽隩雔霋霒霐鞙鞗鞔韰韸頵頯頲餤餟餧餩馞駮駬駥駤駰駣駪駩駧骹骿骴骻髶髺髹髷鬳鮀鮅鮇魼魾魻鮂鮓鮒鮐魺鮕"], +["eca1","魽鮈鴥鴗鴠鴞鴔鴩鴝鴘鴢鴐鴙鴟麈麆麇麮麭黕黖黺鼒鼽儦儥儢儤儠儩勴嚓嚌嚍嚆嚄嚃噾嚂噿嚁壖壔壏壒嬭嬥嬲嬣嬬嬧嬦嬯嬮孻寱寲嶷幬幪徾徻懃憵憼懧懠懥懤懨懞擯擩擣擫擤擨斁斀斶旚曒檍檖檁檥檉檟檛檡檞檇檓檎"], +["ed40","檕檃檨檤檑橿檦檚檅檌檒歛殭氉濌澩濴濔濣濜濭濧濦濞濲濝濢濨燡燱燨燲燤燰燢獳獮獯璗璲璫璐璪璭璱璥璯甐甑甒甏疄癃癈癉癇皤盩瞵瞫瞲瞷瞶"], +["eda1","瞴瞱瞨矰磳磽礂磻磼磲礅磹磾礄禫禨穜穛穖穘穔穚窾竀竁簅簏篲簀篿篻簎篴簋篳簂簉簃簁篸篽簆篰篱簐簊糨縭縼繂縳顈縸縪繉繀繇縩繌縰縻縶繄縺罅罿罾罽翴翲耬膻臄臌臊臅臇膼臩艛艚艜薃薀薏薧薕薠薋薣蕻薤薚薞"], +["ee40","蕷蕼薉薡蕺蕸蕗薎薖薆薍薙薝薁薢薂薈薅蕹蕶薘薐薟虨螾螪螭蟅螰螬螹螵螼螮蟉蟃蟂蟌螷螯蟄蟊螴螶螿螸螽蟞螲褵褳褼褾襁襒褷襂覭覯覮觲觳謞"], +["eea1","謘謖謑謅謋謢謏謒謕謇謍謈謆謜謓謚豏豰豲豱豯貕貔賹赯蹎蹍蹓蹐蹌蹇轃轀邅遾鄸醚醢醛醙醟醡醝醠鎡鎃鎯鍤鍖鍇鍼鍘鍜鍶鍉鍐鍑鍠鍭鎏鍌鍪鍹鍗鍕鍒鍏鍱鍷鍻鍡鍞鍣鍧鎀鍎鍙闇闀闉闃闅閷隮隰隬霠霟霘霝霙鞚鞡鞜"], +["ef40","鞞鞝韕韔韱顁顄顊顉顅顃餥餫餬餪餳餲餯餭餱餰馘馣馡騂駺駴駷駹駸駶駻駽駾駼騃骾髾髽鬁髼魈鮚鮨鮞鮛鮦鮡鮥鮤鮆鮢鮠鮯鴳鵁鵧鴶鴮鴯鴱鴸鴰"], +["efa1","鵅鵂鵃鴾鴷鵀鴽翵鴭麊麉麍麰黈黚黻黿鼤鼣鼢齔龠儱儭儮嚘嚜嚗嚚嚝嚙奰嬼屩屪巀幭幮懘懟懭懮懱懪懰懫懖懩擿攄擽擸攁攃擼斔旛曚曛曘櫅檹檽櫡櫆檺檶檷櫇檴檭歞毉氋瀇瀌瀍瀁瀅瀔瀎濿瀀濻瀦濼濷瀊爁燿燹爃燽獶"], +["f040","璸瓀璵瓁璾璶璻瓂甔甓癜癤癙癐癓癗癚皦皽盬矂瞺磿礌礓礔礉礐礒礑禭禬穟簜簩簙簠簟簭簝簦簨簢簥簰繜繐繖繣繘繢繟繑繠繗繓羵羳翷翸聵臑臒"], +["f0a1","臐艟艞薴藆藀藃藂薳薵薽藇藄薿藋藎藈藅薱薶藒蘤薸薷薾虩蟧蟦蟢蟛蟫蟪蟥蟟蟳蟤蟔蟜蟓蟭蟘蟣螤蟗蟙蠁蟴蟨蟝襓襋襏襌襆襐襑襉謪謧謣謳謰謵譇謯謼謾謱謥謷謦謶謮謤謻謽謺豂豵貙貘貗賾贄贂贀蹜蹢蹠蹗蹖蹞蹥蹧"], +["f140","蹛蹚蹡蹝蹩蹔轆轇轈轋鄨鄺鄻鄾醨醥醧醯醪鎵鎌鎒鎷鎛鎝鎉鎧鎎鎪鎞鎦鎕鎈鎙鎟鎍鎱鎑鎲鎤鎨鎴鎣鎥闒闓闑隳雗雚巂雟雘雝霣霢霥鞬鞮鞨鞫鞤鞪"], +["f1a1","鞢鞥韗韙韖韘韺顐顑顒颸饁餼餺騏騋騉騍騄騑騊騅騇騆髀髜鬈鬄鬅鬩鬵魊魌魋鯇鯆鯃鮿鯁鮵鮸鯓鮶鯄鮹鮽鵜鵓鵏鵊鵛鵋鵙鵖鵌鵗鵒鵔鵟鵘鵚麎麌黟鼁鼀鼖鼥鼫鼪鼩鼨齌齕儴儵劖勷厴嚫嚭嚦嚧嚪嚬壚壝壛夒嬽嬾嬿巃幰"], +["f240","徿懻攇攐攍攉攌攎斄旞旝曞櫧櫠櫌櫑櫙櫋櫟櫜櫐櫫櫏櫍櫞歠殰氌瀙瀧瀠瀖瀫瀡瀢瀣瀩瀗瀤瀜瀪爌爊爇爂爅犥犦犤犣犡瓋瓅璷瓃甖癠矉矊矄矱礝礛"], +["f2a1","礡礜礗礞禰穧穨簳簼簹簬簻糬糪繶繵繸繰繷繯繺繲繴繨罋罊羃羆羷翽翾聸臗臕艤艡艣藫藱藭藙藡藨藚藗藬藲藸藘藟藣藜藑藰藦藯藞藢蠀蟺蠃蟶蟷蠉蠌蠋蠆蟼蠈蟿蠊蠂襢襚襛襗襡襜襘襝襙覈覷覶觶譐譈譊譀譓譖譔譋譕"], +["f340","譑譂譒譗豃豷豶貚贆贇贉趬趪趭趫蹭蹸蹳蹪蹯蹻軂轒轑轏轐轓辴酀鄿醰醭鏞鏇鏏鏂鏚鏐鏹鏬鏌鏙鎩鏦鏊鏔鏮鏣鏕鏄鏎鏀鏒鏧镽闚闛雡霩霫霬霨霦"], +["f3a1","鞳鞷鞶韝韞韟顜顙顝顗颿颽颻颾饈饇饃馦馧騚騕騥騝騤騛騢騠騧騣騞騜騔髂鬋鬊鬎鬌鬷鯪鯫鯠鯞鯤鯦鯢鯰鯔鯗鯬鯜鯙鯥鯕鯡鯚鵷鶁鶊鶄鶈鵱鶀鵸鶆鶋鶌鵽鵫鵴鵵鵰鵩鶅鵳鵻鶂鵯鵹鵿鶇鵨麔麑黀黼鼭齀齁齍齖齗齘匷嚲"], +["f440","嚵嚳壣孅巆巇廮廯忀忁懹攗攖攕攓旟曨曣曤櫳櫰櫪櫨櫹櫱櫮櫯瀼瀵瀯瀷瀴瀱灂瀸瀿瀺瀹灀瀻瀳灁爓爔犨獽獼璺皫皪皾盭矌矎矏矍矲礥礣礧礨礤礩"], +["f4a1","禲穮穬穭竷籉籈籊籇籅糮繻繾纁纀羺翿聹臛臙舋艨艩蘢藿蘁藾蘛蘀藶蘄蘉蘅蘌藽蠙蠐蠑蠗蠓蠖襣襦覹觷譠譪譝譨譣譥譧譭趮躆躈躄轙轖轗轕轘轚邍酃酁醷醵醲醳鐋鐓鏻鐠鐏鐔鏾鐕鐐鐨鐙鐍鏵鐀鏷鐇鐎鐖鐒鏺鐉鏸鐊鏿"], +["f540","鏼鐌鏶鐑鐆闞闠闟霮霯鞹鞻韽韾顠顢顣顟飁飂饐饎饙饌饋饓騲騴騱騬騪騶騩騮騸騭髇髊髆鬐鬒鬑鰋鰈鯷鰅鰒鯸鱀鰇鰎鰆鰗鰔鰉鶟鶙鶤鶝鶒鶘鶐鶛"], +["f5a1","鶠鶔鶜鶪鶗鶡鶚鶢鶨鶞鶣鶿鶩鶖鶦鶧麙麛麚黥黤黧黦鼰鼮齛齠齞齝齙龑儺儹劘劗囃嚽嚾孈孇巋巏廱懽攛欂櫼欃櫸欀灃灄灊灈灉灅灆爝爚爙獾甗癪矐礭礱礯籔籓糲纊纇纈纋纆纍罍羻耰臝蘘蘪蘦蘟蘣蘜蘙蘧蘮蘡蘠蘩蘞蘥"], +["f640","蠩蠝蠛蠠蠤蠜蠫衊襭襩襮襫觺譹譸譅譺譻贐贔趯躎躌轞轛轝酆酄酅醹鐿鐻鐶鐩鐽鐼鐰鐹鐪鐷鐬鑀鐱闥闤闣霵霺鞿韡顤飉飆飀饘饖騹騽驆驄驂驁騺"], +["f6a1","騿髍鬕鬗鬘鬖鬺魒鰫鰝鰜鰬鰣鰨鰩鰤鰡鶷鶶鶼鷁鷇鷊鷏鶾鷅鷃鶻鶵鷎鶹鶺鶬鷈鶱鶭鷌鶳鷍鶲鹺麜黫黮黭鼛鼘鼚鼱齎齥齤龒亹囆囅囋奱孋孌巕巑廲攡攠攦攢欋欈欉氍灕灖灗灒爞爟犩獿瓘瓕瓙瓗癭皭礵禴穰穱籗籜籙籛籚"], +["f740","糴糱纑罏羇臞艫蘴蘵蘳蘬蘲蘶蠬蠨蠦蠪蠥襱覿覾觻譾讄讂讆讅譿贕躕躔躚躒躐躖躗轠轢酇鑌鑐鑊鑋鑏鑇鑅鑈鑉鑆霿韣顪顩飋饔饛驎驓驔驌驏驈驊"], +["f7a1","驉驒驐髐鬙鬫鬻魖魕鱆鱈鰿鱄鰹鰳鱁鰼鰷鰴鰲鰽鰶鷛鷒鷞鷚鷋鷐鷜鷑鷟鷩鷙鷘鷖鷵鷕鷝麶黰鼵鼳鼲齂齫龕龢儽劙壨壧奲孍巘蠯彏戁戃戄攩攥斖曫欑欒欏毊灛灚爢玂玁玃癰矔籧籦纕艬蘺虀蘹蘼蘱蘻蘾蠰蠲蠮蠳襶襴襳觾"], +["f840","讌讎讋讈豅贙躘轤轣醼鑢鑕鑝鑗鑞韄韅頀驖驙鬞鬟鬠鱒鱘鱐鱊鱍鱋鱕鱙鱌鱎鷻鷷鷯鷣鷫鷸鷤鷶鷡鷮鷦鷲鷰鷢鷬鷴鷳鷨鷭黂黐黲黳鼆鼜鼸鼷鼶齃齏"], +["f8a1","齱齰齮齯囓囍孎屭攭曭曮欓灟灡灝灠爣瓛瓥矕礸禷禶籪纗羉艭虃蠸蠷蠵衋讔讕躞躟躠躝醾醽釂鑫鑨鑩雥靆靃靇韇韥驞髕魙鱣鱧鱦鱢鱞鱠鸂鷾鸇鸃鸆鸅鸀鸁鸉鷿鷽鸄麠鼞齆齴齵齶囔攮斸欘欙欗欚灢爦犪矘矙礹籩籫糶纚"], +["f940","纘纛纙臠臡虆虇虈襹襺襼襻觿讘讙躥躤躣鑮鑭鑯鑱鑳靉顲饟鱨鱮鱭鸋鸍鸐鸏鸒鸑麡黵鼉齇齸齻齺齹圞灦籯蠼趲躦釃鑴鑸鑶鑵驠鱴鱳鱱鱵鸔鸓黶鼊"], +["f9a1","龤灨灥糷虪蠾蠽蠿讞貜躩軉靋顳顴飌饡馫驤驦驧鬤鸕鸗齈戇欞爧虌躨钂钀钁驩驨鬮鸙爩虋讟钃鱹麷癵驫鱺鸝灩灪麤齾齉龘碁銹裏墻恒粧嫺╔╦╗╠╬╣╚╩╝╒╤╕╞╪╡╘╧╛╓╥╖╟╫╢╙╨╜║═╭╮╰╯▓"] +] diff --git a/backend/node_modules/iconv-lite/encodings/tables/eucjp.json b/backend/node_modules/iconv-lite/encodings/tables/eucjp.json new file mode 100644 index 0000000000000000000000000000000000000000..4fa61ca116009efc18ecbd1531538f31234ad103 --- /dev/null +++ b/backend/node_modules/iconv-lite/encodings/tables/eucjp.json @@ -0,0 +1,182 @@ +[ +["0","\u0000",127], +["8ea1","。",62], +["a1a1"," 、。,.・:;?!゛゜´`¨^ ̄_ヽヾゝゞ〃仝々〆〇ー―‐/\~∥|…‥‘’“”()〔〕[]{}〈",9,"+-±×÷=≠<>≦≧∞∴♂♀°′″℃¥$¢£%#&*@§☆★○●◎◇"], +["a2a1","◆□■△▲▽▼※〒→←↑↓〓"], +["a2ba","∈∋⊆⊇⊂⊃∪∩"], +["a2ca","∧∨¬⇒⇔∀∃"], +["a2dc","∠⊥⌒∂∇≡≒≪≫√∽∝∵∫∬"], +["a2f2","ʼn♯♭♪†‡¶"], +["a2fe","◯"], +["a3b0","0",9], +["a3c1","A",25], +["a3e1","a",25], +["a4a1","ぁ",82], +["a5a1","ァ",85], +["a6a1","Α",16,"Σ",6], +["a6c1","α",16,"σ",6], +["a7a1","А",5,"ЁЖ",25], +["a7d1","а",5,"ёж",25], +["a8a1","─│┌┐┘└├┬┤┴┼━┃┏┓┛┗┣┳┫┻╋┠┯┨┷┿┝┰┥┸╂"], +["ada1","①",19,"Ⅰ",9], +["adc0","㍉㌔㌢㍍㌘㌧㌃㌶㍑㍗㌍㌦㌣㌫㍊㌻㎜㎝㎞㎎㎏㏄㎡"], +["addf","㍻〝〟№㏍℡㊤",4,"㈱㈲㈹㍾㍽㍼≒≡∫∮∑√⊥∠∟⊿∵∩∪"], +["b0a1","亜唖娃阿哀愛挨姶逢葵茜穐悪握渥旭葦芦鯵梓圧斡扱宛姐虻飴絢綾鮎或粟袷安庵按暗案闇鞍杏以伊位依偉囲夷委威尉惟意慰易椅為畏異移維緯胃萎衣謂違遺医井亥域育郁磯一壱溢逸稲茨芋鰯允印咽員因姻引飲淫胤蔭"], +["b1a1","院陰隠韻吋右宇烏羽迂雨卯鵜窺丑碓臼渦嘘唄欝蔚鰻姥厩浦瓜閏噂云運雲荏餌叡営嬰影映曳栄永泳洩瑛盈穎頴英衛詠鋭液疫益駅悦謁越閲榎厭円園堰奄宴延怨掩援沿演炎焔煙燕猿縁艶苑薗遠鉛鴛塩於汚甥凹央奥往応"], +["b2a1","押旺横欧殴王翁襖鴬鴎黄岡沖荻億屋憶臆桶牡乙俺卸恩温穏音下化仮何伽価佳加可嘉夏嫁家寡科暇果架歌河火珂禍禾稼箇花苛茄荷華菓蝦課嘩貨迦過霞蚊俄峨我牙画臥芽蛾賀雅餓駕介会解回塊壊廻快怪悔恢懐戒拐改"], +["b3a1","魁晦械海灰界皆絵芥蟹開階貝凱劾外咳害崖慨概涯碍蓋街該鎧骸浬馨蛙垣柿蛎鈎劃嚇各廓拡撹格核殻獲確穫覚角赫較郭閣隔革学岳楽額顎掛笠樫橿梶鰍潟割喝恰括活渇滑葛褐轄且鰹叶椛樺鞄株兜竃蒲釜鎌噛鴨栢茅萱"], +["b4a1","粥刈苅瓦乾侃冠寒刊勘勧巻喚堪姦完官寛干幹患感慣憾換敢柑桓棺款歓汗漢澗潅環甘監看竿管簡緩缶翰肝艦莞観諌貫還鑑間閑関陥韓館舘丸含岸巌玩癌眼岩翫贋雁頑顔願企伎危喜器基奇嬉寄岐希幾忌揮机旗既期棋棄"], +["b5a1","機帰毅気汽畿祈季稀紀徽規記貴起軌輝飢騎鬼亀偽儀妓宜戯技擬欺犠疑祇義蟻誼議掬菊鞠吉吃喫桔橘詰砧杵黍却客脚虐逆丘久仇休及吸宮弓急救朽求汲泣灸球究窮笈級糾給旧牛去居巨拒拠挙渠虚許距鋸漁禦魚亨享京"], +["b6a1","供侠僑兇競共凶協匡卿叫喬境峡強彊怯恐恭挟教橋況狂狭矯胸脅興蕎郷鏡響饗驚仰凝尭暁業局曲極玉桐粁僅勤均巾錦斤欣欽琴禁禽筋緊芹菌衿襟謹近金吟銀九倶句区狗玖矩苦躯駆駈駒具愚虞喰空偶寓遇隅串櫛釧屑屈"], +["b7a1","掘窟沓靴轡窪熊隈粂栗繰桑鍬勲君薫訓群軍郡卦袈祁係傾刑兄啓圭珪型契形径恵慶慧憩掲携敬景桂渓畦稽系経継繋罫茎荊蛍計詣警軽頚鶏芸迎鯨劇戟撃激隙桁傑欠決潔穴結血訣月件倹倦健兼券剣喧圏堅嫌建憲懸拳捲"], +["b8a1","検権牽犬献研硯絹県肩見謙賢軒遣鍵険顕験鹸元原厳幻弦減源玄現絃舷言諺限乎個古呼固姑孤己庫弧戸故枯湖狐糊袴股胡菰虎誇跨鈷雇顧鼓五互伍午呉吾娯後御悟梧檎瑚碁語誤護醐乞鯉交佼侯候倖光公功効勾厚口向"], +["b9a1","后喉坑垢好孔孝宏工巧巷幸広庚康弘恒慌抗拘控攻昂晃更杭校梗構江洪浩港溝甲皇硬稿糠紅紘絞綱耕考肯肱腔膏航荒行衡講貢購郊酵鉱砿鋼閤降項香高鴻剛劫号合壕拷濠豪轟麹克刻告国穀酷鵠黒獄漉腰甑忽惚骨狛込"], +["baa1","此頃今困坤墾婚恨懇昏昆根梱混痕紺艮魂些佐叉唆嵯左差査沙瑳砂詐鎖裟坐座挫債催再最哉塞妻宰彩才採栽歳済災采犀砕砦祭斎細菜裁載際剤在材罪財冴坂阪堺榊肴咲崎埼碕鷺作削咋搾昨朔柵窄策索錯桜鮭笹匙冊刷"], +["bba1","察拶撮擦札殺薩雑皐鯖捌錆鮫皿晒三傘参山惨撒散桟燦珊産算纂蚕讃賛酸餐斬暫残仕仔伺使刺司史嗣四士始姉姿子屍市師志思指支孜斯施旨枝止死氏獅祉私糸紙紫肢脂至視詞詩試誌諮資賜雌飼歯事似侍児字寺慈持時"], +["bca1","次滋治爾璽痔磁示而耳自蒔辞汐鹿式識鴫竺軸宍雫七叱執失嫉室悉湿漆疾質実蔀篠偲柴芝屡蕊縞舎写射捨赦斜煮社紗者謝車遮蛇邪借勺尺杓灼爵酌釈錫若寂弱惹主取守手朱殊狩珠種腫趣酒首儒受呪寿授樹綬需囚収周"], +["bda1","宗就州修愁拾洲秀秋終繍習臭舟蒐衆襲讐蹴輯週酋酬集醜什住充十従戎柔汁渋獣縦重銃叔夙宿淑祝縮粛塾熟出術述俊峻春瞬竣舜駿准循旬楯殉淳準潤盾純巡遵醇順処初所暑曙渚庶緒署書薯藷諸助叙女序徐恕鋤除傷償"], +["bea1","勝匠升召哨商唱嘗奨妾娼宵将小少尚庄床廠彰承抄招掌捷昇昌昭晶松梢樟樵沼消渉湘焼焦照症省硝礁祥称章笑粧紹肖菖蒋蕉衝裳訟証詔詳象賞醤鉦鍾鐘障鞘上丈丞乗冗剰城場壌嬢常情擾条杖浄状畳穣蒸譲醸錠嘱埴飾"], +["bfa1","拭植殖燭織職色触食蝕辱尻伸信侵唇娠寝審心慎振新晋森榛浸深申疹真神秦紳臣芯薪親診身辛進針震人仁刃塵壬尋甚尽腎訊迅陣靭笥諏須酢図厨逗吹垂帥推水炊睡粋翠衰遂酔錐錘随瑞髄崇嵩数枢趨雛据杉椙菅頗雀裾"], +["c0a1","澄摺寸世瀬畝是凄制勢姓征性成政整星晴棲栖正清牲生盛精聖声製西誠誓請逝醒青静斉税脆隻席惜戚斥昔析石積籍績脊責赤跡蹟碩切拙接摂折設窃節説雪絶舌蝉仙先千占宣専尖川戦扇撰栓栴泉浅洗染潜煎煽旋穿箭線"], +["c1a1","繊羨腺舛船薦詮賎践選遷銭銑閃鮮前善漸然全禅繕膳糎噌塑岨措曾曽楚狙疏疎礎祖租粗素組蘇訴阻遡鼠僧創双叢倉喪壮奏爽宋層匝惣想捜掃挿掻操早曹巣槍槽漕燥争痩相窓糟総綜聡草荘葬蒼藻装走送遭鎗霜騒像増憎"], +["c2a1","臓蔵贈造促側則即息捉束測足速俗属賊族続卒袖其揃存孫尊損村遜他多太汰詑唾堕妥惰打柁舵楕陀駄騨体堆対耐岱帯待怠態戴替泰滞胎腿苔袋貸退逮隊黛鯛代台大第醍題鷹滝瀧卓啄宅托択拓沢濯琢託鐸濁諾茸凧蛸只"], +["c3a1","叩但達辰奪脱巽竪辿棚谷狸鱈樽誰丹単嘆坦担探旦歎淡湛炭短端箪綻耽胆蛋誕鍛団壇弾断暖檀段男談値知地弛恥智池痴稚置致蜘遅馳築畜竹筑蓄逐秩窒茶嫡着中仲宙忠抽昼柱注虫衷註酎鋳駐樗瀦猪苧著貯丁兆凋喋寵"], +["c4a1","帖帳庁弔張彫徴懲挑暢朝潮牒町眺聴脹腸蝶調諜超跳銚長頂鳥勅捗直朕沈珍賃鎮陳津墜椎槌追鎚痛通塚栂掴槻佃漬柘辻蔦綴鍔椿潰坪壷嬬紬爪吊釣鶴亭低停偵剃貞呈堤定帝底庭廷弟悌抵挺提梯汀碇禎程締艇訂諦蹄逓"], +["c5a1","邸鄭釘鼎泥摘擢敵滴的笛適鏑溺哲徹撤轍迭鉄典填天展店添纏甜貼転顛点伝殿澱田電兎吐堵塗妬屠徒斗杜渡登菟賭途都鍍砥砺努度土奴怒倒党冬凍刀唐塔塘套宕島嶋悼投搭東桃梼棟盗淘湯涛灯燈当痘祷等答筒糖統到"], +["c6a1","董蕩藤討謄豆踏逃透鐙陶頭騰闘働動同堂導憧撞洞瞳童胴萄道銅峠鴇匿得徳涜特督禿篤毒独読栃橡凸突椴届鳶苫寅酉瀞噸屯惇敦沌豚遁頓呑曇鈍奈那内乍凪薙謎灘捺鍋楢馴縄畷南楠軟難汝二尼弐迩匂賑肉虹廿日乳入"], +["c7a1","如尿韮任妊忍認濡禰祢寧葱猫熱年念捻撚燃粘乃廼之埜嚢悩濃納能脳膿農覗蚤巴把播覇杷波派琶破婆罵芭馬俳廃拝排敗杯盃牌背肺輩配倍培媒梅楳煤狽買売賠陪這蝿秤矧萩伯剥博拍柏泊白箔粕舶薄迫曝漠爆縛莫駁麦"], +["c8a1","函箱硲箸肇筈櫨幡肌畑畠八鉢溌発醗髪伐罰抜筏閥鳩噺塙蛤隼伴判半反叛帆搬斑板氾汎版犯班畔繁般藩販範釆煩頒飯挽晩番盤磐蕃蛮匪卑否妃庇彼悲扉批披斐比泌疲皮碑秘緋罷肥被誹費避非飛樋簸備尾微枇毘琵眉美"], +["c9a1","鼻柊稗匹疋髭彦膝菱肘弼必畢筆逼桧姫媛紐百謬俵彪標氷漂瓢票表評豹廟描病秒苗錨鋲蒜蛭鰭品彬斌浜瀕貧賓頻敏瓶不付埠夫婦富冨布府怖扶敷斧普浮父符腐膚芙譜負賦赴阜附侮撫武舞葡蕪部封楓風葺蕗伏副復幅服"], +["caa1","福腹複覆淵弗払沸仏物鮒分吻噴墳憤扮焚奮粉糞紛雰文聞丙併兵塀幣平弊柄並蔽閉陛米頁僻壁癖碧別瞥蔑箆偏変片篇編辺返遍便勉娩弁鞭保舗鋪圃捕歩甫補輔穂募墓慕戊暮母簿菩倣俸包呆報奉宝峰峯崩庖抱捧放方朋"], +["cba1","法泡烹砲縫胞芳萌蓬蜂褒訪豊邦鋒飽鳳鵬乏亡傍剖坊妨帽忘忙房暴望某棒冒紡肪膨謀貌貿鉾防吠頬北僕卜墨撲朴牧睦穆釦勃没殆堀幌奔本翻凡盆摩磨魔麻埋妹昧枚毎哩槙幕膜枕鮪柾鱒桝亦俣又抹末沫迄侭繭麿万慢満"], +["cca1","漫蔓味未魅巳箕岬密蜜湊蓑稔脈妙粍民眠務夢無牟矛霧鵡椋婿娘冥名命明盟迷銘鳴姪牝滅免棉綿緬面麺摸模茂妄孟毛猛盲網耗蒙儲木黙目杢勿餅尤戻籾貰問悶紋門匁也冶夜爺耶野弥矢厄役約薬訳躍靖柳薮鑓愉愈油癒"], +["cda1","諭輸唯佑優勇友宥幽悠憂揖有柚湧涌猶猷由祐裕誘遊邑郵雄融夕予余与誉輿預傭幼妖容庸揚揺擁曜楊様洋溶熔用窯羊耀葉蓉要謡踊遥陽養慾抑欲沃浴翌翼淀羅螺裸来莱頼雷洛絡落酪乱卵嵐欄濫藍蘭覧利吏履李梨理璃"], +["cea1","痢裏裡里離陸律率立葎掠略劉流溜琉留硫粒隆竜龍侶慮旅虜了亮僚両凌寮料梁涼猟療瞭稜糧良諒遼量陵領力緑倫厘林淋燐琳臨輪隣鱗麟瑠塁涙累類令伶例冷励嶺怜玲礼苓鈴隷零霊麗齢暦歴列劣烈裂廉恋憐漣煉簾練聯"], +["cfa1","蓮連錬呂魯櫓炉賂路露労婁廊弄朗楼榔浪漏牢狼篭老聾蝋郎六麓禄肋録論倭和話歪賄脇惑枠鷲亙亘鰐詫藁蕨椀湾碗腕"], +["d0a1","弌丐丕个丱丶丼丿乂乖乘亂亅豫亊舒弍于亞亟亠亢亰亳亶从仍仄仆仂仗仞仭仟价伉佚估佛佝佗佇佶侈侏侘佻佩佰侑佯來侖儘俔俟俎俘俛俑俚俐俤俥倚倨倔倪倥倅伜俶倡倩倬俾俯們倆偃假會偕偐偈做偖偬偸傀傚傅傴傲"], +["d1a1","僉僊傳僂僖僞僥僭僣僮價僵儉儁儂儖儕儔儚儡儺儷儼儻儿兀兒兌兔兢竸兩兪兮冀冂囘册冉冏冑冓冕冖冤冦冢冩冪冫决冱冲冰况冽凅凉凛几處凩凭凰凵凾刄刋刔刎刧刪刮刳刹剏剄剋剌剞剔剪剴剩剳剿剽劍劔劒剱劈劑辨"], +["d2a1","辧劬劭劼劵勁勍勗勞勣勦飭勠勳勵勸勹匆匈甸匍匐匏匕匚匣匯匱匳匸區卆卅丗卉卍凖卞卩卮夘卻卷厂厖厠厦厥厮厰厶參簒雙叟曼燮叮叨叭叺吁吽呀听吭吼吮吶吩吝呎咏呵咎呟呱呷呰咒呻咀呶咄咐咆哇咢咸咥咬哄哈咨"], +["d3a1","咫哂咤咾咼哘哥哦唏唔哽哮哭哺哢唹啀啣啌售啜啅啖啗唸唳啝喙喀咯喊喟啻啾喘喞單啼喃喩喇喨嗚嗅嗟嗄嗜嗤嗔嘔嗷嘖嗾嗽嘛嗹噎噐營嘴嘶嘲嘸噫噤嘯噬噪嚆嚀嚊嚠嚔嚏嚥嚮嚶嚴囂嚼囁囃囀囈囎囑囓囗囮囹圀囿圄圉"], +["d4a1","圈國圍圓團圖嗇圜圦圷圸坎圻址坏坩埀垈坡坿垉垓垠垳垤垪垰埃埆埔埒埓堊埖埣堋堙堝塲堡塢塋塰毀塒堽塹墅墹墟墫墺壞墻墸墮壅壓壑壗壙壘壥壜壤壟壯壺壹壻壼壽夂夊夐夛梦夥夬夭夲夸夾竒奕奐奎奚奘奢奠奧奬奩"], +["d5a1","奸妁妝佞侫妣妲姆姨姜妍姙姚娥娟娑娜娉娚婀婬婉娵娶婢婪媚媼媾嫋嫂媽嫣嫗嫦嫩嫖嫺嫻嬌嬋嬖嬲嫐嬪嬶嬾孃孅孀孑孕孚孛孥孩孰孳孵學斈孺宀它宦宸寃寇寉寔寐寤實寢寞寥寫寰寶寳尅將專對尓尠尢尨尸尹屁屆屎屓"], +["d6a1","屐屏孱屬屮乢屶屹岌岑岔妛岫岻岶岼岷峅岾峇峙峩峽峺峭嶌峪崋崕崗嵜崟崛崑崔崢崚崙崘嵌嵒嵎嵋嵬嵳嵶嶇嶄嶂嶢嶝嶬嶮嶽嶐嶷嶼巉巍巓巒巖巛巫已巵帋帚帙帑帛帶帷幄幃幀幎幗幔幟幢幤幇幵并幺麼广庠廁廂廈廐廏"], +["d7a1","廖廣廝廚廛廢廡廨廩廬廱廳廰廴廸廾弃弉彝彜弋弑弖弩弭弸彁彈彌彎弯彑彖彗彙彡彭彳彷徃徂彿徊很徑徇從徙徘徠徨徭徼忖忻忤忸忱忝悳忿怡恠怙怐怩怎怱怛怕怫怦怏怺恚恁恪恷恟恊恆恍恣恃恤恂恬恫恙悁悍惧悃悚"], +["d8a1","悄悛悖悗悒悧悋惡悸惠惓悴忰悽惆悵惘慍愕愆惶惷愀惴惺愃愡惻惱愍愎慇愾愨愧慊愿愼愬愴愽慂慄慳慷慘慙慚慫慴慯慥慱慟慝慓慵憙憖憇憬憔憚憊憑憫憮懌懊應懷懈懃懆憺懋罹懍懦懣懶懺懴懿懽懼懾戀戈戉戍戌戔戛"], +["d9a1","戞戡截戮戰戲戳扁扎扞扣扛扠扨扼抂抉找抒抓抖拔抃抔拗拑抻拏拿拆擔拈拜拌拊拂拇抛拉挌拮拱挧挂挈拯拵捐挾捍搜捏掖掎掀掫捶掣掏掉掟掵捫捩掾揩揀揆揣揉插揶揄搖搴搆搓搦搶攝搗搨搏摧摯摶摎攪撕撓撥撩撈撼"], +["daa1","據擒擅擇撻擘擂擱擧舉擠擡抬擣擯攬擶擴擲擺攀擽攘攜攅攤攣攫攴攵攷收攸畋效敖敕敍敘敞敝敲數斂斃變斛斟斫斷旃旆旁旄旌旒旛旙无旡旱杲昊昃旻杳昵昶昴昜晏晄晉晁晞晝晤晧晨晟晢晰暃暈暎暉暄暘暝曁暹曉暾暼"], +["dba1","曄暸曖曚曠昿曦曩曰曵曷朏朖朞朦朧霸朮朿朶杁朸朷杆杞杠杙杣杤枉杰枩杼杪枌枋枦枡枅枷柯枴柬枳柩枸柤柞柝柢柮枹柎柆柧檜栞框栩桀桍栲桎梳栫桙档桷桿梟梏梭梔條梛梃檮梹桴梵梠梺椏梍桾椁棊椈棘椢椦棡椌棍"], +["dca1","棔棧棕椶椒椄棗棣椥棹棠棯椨椪椚椣椡棆楹楷楜楸楫楔楾楮椹楴椽楙椰楡楞楝榁楪榲榮槐榿槁槓榾槎寨槊槝榻槃榧樮榑榠榜榕榴槞槨樂樛槿權槹槲槧樅榱樞槭樔槫樊樒櫁樣樓橄樌橲樶橸橇橢橙橦橈樸樢檐檍檠檄檢檣"], +["dda1","檗蘗檻櫃櫂檸檳檬櫞櫑櫟檪櫚櫪櫻欅蘖櫺欒欖鬱欟欸欷盜欹飮歇歃歉歐歙歔歛歟歡歸歹歿殀殄殃殍殘殕殞殤殪殫殯殲殱殳殷殼毆毋毓毟毬毫毳毯麾氈氓气氛氤氣汞汕汢汪沂沍沚沁沛汾汨汳沒沐泄泱泓沽泗泅泝沮沱沾"], +["dea1","沺泛泯泙泪洟衍洶洫洽洸洙洵洳洒洌浣涓浤浚浹浙涎涕濤涅淹渕渊涵淇淦涸淆淬淞淌淨淒淅淺淙淤淕淪淮渭湮渮渙湲湟渾渣湫渫湶湍渟湃渺湎渤滿渝游溂溪溘滉溷滓溽溯滄溲滔滕溏溥滂溟潁漑灌滬滸滾漿滲漱滯漲滌"], +["dfa1","漾漓滷澆潺潸澁澀潯潛濳潭澂潼潘澎澑濂潦澳澣澡澤澹濆澪濟濕濬濔濘濱濮濛瀉瀋濺瀑瀁瀏濾瀛瀚潴瀝瀘瀟瀰瀾瀲灑灣炙炒炯烱炬炸炳炮烟烋烝烙焉烽焜焙煥煕熈煦煢煌煖煬熏燻熄熕熨熬燗熹熾燒燉燔燎燠燬燧燵燼"], +["e0a1","燹燿爍爐爛爨爭爬爰爲爻爼爿牀牆牋牘牴牾犂犁犇犒犖犢犧犹犲狃狆狄狎狒狢狠狡狹狷倏猗猊猜猖猝猴猯猩猥猾獎獏默獗獪獨獰獸獵獻獺珈玳珎玻珀珥珮珞璢琅瑯琥珸琲琺瑕琿瑟瑙瑁瑜瑩瑰瑣瑪瑶瑾璋璞璧瓊瓏瓔珱"], +["e1a1","瓠瓣瓧瓩瓮瓲瓰瓱瓸瓷甄甃甅甌甎甍甕甓甞甦甬甼畄畍畊畉畛畆畚畩畤畧畫畭畸當疆疇畴疊疉疂疔疚疝疥疣痂疳痃疵疽疸疼疱痍痊痒痙痣痞痾痿痼瘁痰痺痲痳瘋瘍瘉瘟瘧瘠瘡瘢瘤瘴瘰瘻癇癈癆癜癘癡癢癨癩癪癧癬癰"], +["e2a1","癲癶癸發皀皃皈皋皎皖皓皙皚皰皴皸皹皺盂盍盖盒盞盡盥盧盪蘯盻眈眇眄眩眤眞眥眦眛眷眸睇睚睨睫睛睥睿睾睹瞎瞋瞑瞠瞞瞰瞶瞹瞿瞼瞽瞻矇矍矗矚矜矣矮矼砌砒礦砠礪硅碎硴碆硼碚碌碣碵碪碯磑磆磋磔碾碼磅磊磬"], +["e3a1","磧磚磽磴礇礒礑礙礬礫祀祠祗祟祚祕祓祺祿禊禝禧齋禪禮禳禹禺秉秕秧秬秡秣稈稍稘稙稠稟禀稱稻稾稷穃穗穉穡穢穩龝穰穹穽窈窗窕窘窖窩竈窰窶竅竄窿邃竇竊竍竏竕竓站竚竝竡竢竦竭竰笂笏笊笆笳笘笙笞笵笨笶筐"], +["e4a1","筺笄筍笋筌筅筵筥筴筧筰筱筬筮箝箘箟箍箜箚箋箒箏筝箙篋篁篌篏箴篆篝篩簑簔篦篥籠簀簇簓篳篷簗簍篶簣簧簪簟簷簫簽籌籃籔籏籀籐籘籟籤籖籥籬籵粃粐粤粭粢粫粡粨粳粲粱粮粹粽糀糅糂糘糒糜糢鬻糯糲糴糶糺紆"], +["e5a1","紂紜紕紊絅絋紮紲紿紵絆絳絖絎絲絨絮絏絣經綉絛綏絽綛綺綮綣綵緇綽綫總綢綯緜綸綟綰緘緝緤緞緻緲緡縅縊縣縡縒縱縟縉縋縢繆繦縻縵縹繃縷縲縺繧繝繖繞繙繚繹繪繩繼繻纃緕繽辮繿纈纉續纒纐纓纔纖纎纛纜缸缺"], +["e6a1","罅罌罍罎罐网罕罔罘罟罠罨罩罧罸羂羆羃羈羇羌羔羞羝羚羣羯羲羹羮羶羸譱翅翆翊翕翔翡翦翩翳翹飜耆耄耋耒耘耙耜耡耨耿耻聊聆聒聘聚聟聢聨聳聲聰聶聹聽聿肄肆肅肛肓肚肭冐肬胛胥胙胝胄胚胖脉胯胱脛脩脣脯腋"], +["e7a1","隋腆脾腓腑胼腱腮腥腦腴膃膈膊膀膂膠膕膤膣腟膓膩膰膵膾膸膽臀臂膺臉臍臑臙臘臈臚臟臠臧臺臻臾舁舂舅與舊舍舐舖舩舫舸舳艀艙艘艝艚艟艤艢艨艪艫舮艱艷艸艾芍芒芫芟芻芬苡苣苟苒苴苳苺莓范苻苹苞茆苜茉苙"], +["e8a1","茵茴茖茲茱荀茹荐荅茯茫茗茘莅莚莪莟莢莖茣莎莇莊荼莵荳荵莠莉莨菴萓菫菎菽萃菘萋菁菷萇菠菲萍萢萠莽萸蔆菻葭萪萼蕚蒄葷葫蒭葮蒂葩葆萬葯葹萵蓊葢蒹蒿蒟蓙蓍蒻蓚蓐蓁蓆蓖蒡蔡蓿蓴蔗蔘蔬蔟蔕蔔蓼蕀蕣蕘蕈"], +["e9a1","蕁蘂蕋蕕薀薤薈薑薊薨蕭薔薛藪薇薜蕷蕾薐藉薺藏薹藐藕藝藥藜藹蘊蘓蘋藾藺蘆蘢蘚蘰蘿虍乕虔號虧虱蚓蚣蚩蚪蚋蚌蚶蚯蛄蛆蚰蛉蠣蚫蛔蛞蛩蛬蛟蛛蛯蜒蜆蜈蜀蜃蛻蜑蜉蜍蛹蜊蜴蜿蜷蜻蜥蜩蜚蝠蝟蝸蝌蝎蝴蝗蝨蝮蝙"], +["eaa1","蝓蝣蝪蠅螢螟螂螯蟋螽蟀蟐雖螫蟄螳蟇蟆螻蟯蟲蟠蠏蠍蟾蟶蟷蠎蟒蠑蠖蠕蠢蠡蠱蠶蠹蠧蠻衄衂衒衙衞衢衫袁衾袞衵衽袵衲袂袗袒袮袙袢袍袤袰袿袱裃裄裔裘裙裝裹褂裼裴裨裲褄褌褊褓襃褞褥褪褫襁襄褻褶褸襌褝襠襞"], +["eba1","襦襤襭襪襯襴襷襾覃覈覊覓覘覡覩覦覬覯覲覺覽覿觀觚觜觝觧觴觸訃訖訐訌訛訝訥訶詁詛詒詆詈詼詭詬詢誅誂誄誨誡誑誥誦誚誣諄諍諂諚諫諳諧諤諱謔諠諢諷諞諛謌謇謚諡謖謐謗謠謳鞫謦謫謾謨譁譌譏譎證譖譛譚譫"], +["eca1","譟譬譯譴譽讀讌讎讒讓讖讙讚谺豁谿豈豌豎豐豕豢豬豸豺貂貉貅貊貍貎貔豼貘戝貭貪貽貲貳貮貶賈賁賤賣賚賽賺賻贄贅贊贇贏贍贐齎贓賍贔贖赧赭赱赳趁趙跂趾趺跏跚跖跌跛跋跪跫跟跣跼踈踉跿踝踞踐踟蹂踵踰踴蹊"], +["eda1","蹇蹉蹌蹐蹈蹙蹤蹠踪蹣蹕蹶蹲蹼躁躇躅躄躋躊躓躑躔躙躪躡躬躰軆躱躾軅軈軋軛軣軼軻軫軾輊輅輕輒輙輓輜輟輛輌輦輳輻輹轅轂輾轌轉轆轎轗轜轢轣轤辜辟辣辭辯辷迚迥迢迪迯邇迴逅迹迺逑逕逡逍逞逖逋逧逶逵逹迸"], +["eea1","遏遐遑遒逎遉逾遖遘遞遨遯遶隨遲邂遽邁邀邊邉邏邨邯邱邵郢郤扈郛鄂鄒鄙鄲鄰酊酖酘酣酥酩酳酲醋醉醂醢醫醯醪醵醴醺釀釁釉釋釐釖釟釡釛釼釵釶鈞釿鈔鈬鈕鈑鉞鉗鉅鉉鉤鉈銕鈿鉋鉐銜銖銓銛鉚鋏銹銷鋩錏鋺鍄錮"], +["efa1","錙錢錚錣錺錵錻鍜鍠鍼鍮鍖鎰鎬鎭鎔鎹鏖鏗鏨鏥鏘鏃鏝鏐鏈鏤鐚鐔鐓鐃鐇鐐鐶鐫鐵鐡鐺鑁鑒鑄鑛鑠鑢鑞鑪鈩鑰鑵鑷鑽鑚鑼鑾钁鑿閂閇閊閔閖閘閙閠閨閧閭閼閻閹閾闊濶闃闍闌闕闔闖關闡闥闢阡阨阮阯陂陌陏陋陷陜陞"], +["f0a1","陝陟陦陲陬隍隘隕隗險隧隱隲隰隴隶隸隹雎雋雉雍襍雜霍雕雹霄霆霈霓霎霑霏霖霙霤霪霰霹霽霾靄靆靈靂靉靜靠靤靦靨勒靫靱靹鞅靼鞁靺鞆鞋鞏鞐鞜鞨鞦鞣鞳鞴韃韆韈韋韜韭齏韲竟韶韵頏頌頸頤頡頷頽顆顏顋顫顯顰"], +["f1a1","顱顴顳颪颯颱颶飄飃飆飩飫餃餉餒餔餘餡餝餞餤餠餬餮餽餾饂饉饅饐饋饑饒饌饕馗馘馥馭馮馼駟駛駝駘駑駭駮駱駲駻駸騁騏騅駢騙騫騷驅驂驀驃騾驕驍驛驗驟驢驥驤驩驫驪骭骰骼髀髏髑髓體髞髟髢髣髦髯髫髮髴髱髷"], +["f2a1","髻鬆鬘鬚鬟鬢鬣鬥鬧鬨鬩鬪鬮鬯鬲魄魃魏魍魎魑魘魴鮓鮃鮑鮖鮗鮟鮠鮨鮴鯀鯊鮹鯆鯏鯑鯒鯣鯢鯤鯔鯡鰺鯲鯱鯰鰕鰔鰉鰓鰌鰆鰈鰒鰊鰄鰮鰛鰥鰤鰡鰰鱇鰲鱆鰾鱚鱠鱧鱶鱸鳧鳬鳰鴉鴈鳫鴃鴆鴪鴦鶯鴣鴟鵄鴕鴒鵁鴿鴾鵆鵈"], +["f3a1","鵝鵞鵤鵑鵐鵙鵲鶉鶇鶫鵯鵺鶚鶤鶩鶲鷄鷁鶻鶸鶺鷆鷏鷂鷙鷓鷸鷦鷭鷯鷽鸚鸛鸞鹵鹹鹽麁麈麋麌麒麕麑麝麥麩麸麪麭靡黌黎黏黐黔黜點黝黠黥黨黯黴黶黷黹黻黼黽鼇鼈皷鼕鼡鼬鼾齊齒齔齣齟齠齡齦齧齬齪齷齲齶龕龜龠"], +["f4a1","堯槇遙瑤凜熙"], +["f9a1","纊褜鍈銈蓜俉炻昱棈鋹曻彅丨仡仼伀伃伹佖侒侊侚侔俍偀倢俿倞偆偰偂傔僴僘兊兤冝冾凬刕劜劦勀勛匀匇匤卲厓厲叝﨎咜咊咩哿喆坙坥垬埈埇﨏塚增墲夋奓奛奝奣妤妺孖寀甯寘寬尞岦岺峵崧嵓﨑嵂嵭嶸嶹巐弡弴彧德"], +["faa1","忞恝悅悊惞惕愠惲愑愷愰憘戓抦揵摠撝擎敎昀昕昻昉昮昞昤晥晗晙晴晳暙暠暲暿曺朎朗杦枻桒柀栁桄棏﨓楨﨔榘槢樰橫橆橳橾櫢櫤毖氿汜沆汯泚洄涇浯涖涬淏淸淲淼渹湜渧渼溿澈澵濵瀅瀇瀨炅炫焏焄煜煆煇凞燁燾犱"], +["fba1","犾猤猪獷玽珉珖珣珒琇珵琦琪琩琮瑢璉璟甁畯皂皜皞皛皦益睆劯砡硎硤硺礰礼神祥禔福禛竑竧靖竫箞精絈絜綷綠緖繒罇羡羽茁荢荿菇菶葈蒴蕓蕙蕫﨟薰蘒﨡蠇裵訒訷詹誧誾諟諸諶譓譿賰賴贒赶﨣軏﨤逸遧郞都鄕鄧釚"], +["fca1","釗釞釭釮釤釥鈆鈐鈊鈺鉀鈼鉎鉙鉑鈹鉧銧鉷鉸鋧鋗鋙鋐﨧鋕鋠鋓錥錡鋻﨨錞鋿錝錂鍰鍗鎤鏆鏞鏸鐱鑅鑈閒隆﨩隝隯霳霻靃靍靏靑靕顗顥飯飼餧館馞驎髙髜魵魲鮏鮱鮻鰀鵰鵫鶴鸙黑"], +["fcf1","ⅰ",9,"¬¦'""], +["8fa2af","˘ˇ¸˙˝¯˛˚~΄΅"], +["8fa2c2","¡¦¿"], +["8fa2eb","ºª©®™¤№"], +["8fa6e1","ΆΈΉΊΪ"], +["8fa6e7","Ό"], +["8fa6e9","ΎΫ"], +["8fa6ec","Ώ"], +["8fa6f1","άέήίϊΐόςύϋΰώ"], +["8fa7c2","Ђ",10,"ЎЏ"], +["8fa7f2","ђ",10,"ўџ"], +["8fa9a1","ÆĐ"], +["8fa9a4","Ħ"], +["8fa9a6","IJ"], +["8fa9a8","ŁĿ"], +["8fa9ab","ŊØŒ"], +["8fa9af","ŦÞ"], +["8fa9c1","æđðħıijĸłŀʼnŋøœßŧþ"], +["8faaa1","ÁÀÄÂĂǍĀĄÅÃĆĈČÇĊĎÉÈËÊĚĖĒĘ"], +["8faaba","ĜĞĢĠĤÍÌÏÎǏİĪĮĨĴĶĹĽĻŃŇŅÑÓÒÖÔǑŐŌÕŔŘŖŚŜŠŞŤŢÚÙÜÛŬǓŰŪŲŮŨǗǛǙǕŴÝŸŶŹŽŻ"], +["8faba1","áàäâăǎāąåãćĉčçċďéèëêěėēęǵĝğ"], +["8fabbd","ġĥíìïîǐ"], +["8fabc5","īįĩĵķĺľļńňņñóòöôǒőōõŕřŗśŝšşťţúùüûŭǔűūųůũǘǜǚǖŵýÿŷźžż"], +["8fb0a1","丂丄丅丌丒丟丣两丨丫丮丯丰丵乀乁乄乇乑乚乜乣乨乩乴乵乹乿亍亖亗亝亯亹仃仐仚仛仠仡仢仨仯仱仳仵份仾仿伀伂伃伈伋伌伒伕伖众伙伮伱你伳伵伷伹伻伾佀佂佈佉佋佌佒佔佖佘佟佣佪佬佮佱佷佸佹佺佽佾侁侂侄"], +["8fb1a1","侅侉侊侌侎侐侒侓侔侗侙侚侞侟侲侷侹侻侼侽侾俀俁俅俆俈俉俋俌俍俏俒俜俠俢俰俲俼俽俿倀倁倄倇倊倌倎倐倓倗倘倛倜倝倞倢倧倮倰倲倳倵偀偁偂偅偆偊偌偎偑偒偓偗偙偟偠偢偣偦偧偪偭偰偱倻傁傃傄傆傊傎傏傐"], +["8fb2a1","傒傓傔傖傛傜傞",4,"傪傯傰傹傺傽僀僃僄僇僌僎僐僓僔僘僜僝僟僢僤僦僨僩僯僱僶僺僾儃儆儇儈儋儌儍儎僲儐儗儙儛儜儝儞儣儧儨儬儭儯儱儳儴儵儸儹兂兊兏兓兕兗兘兟兤兦兾冃冄冋冎冘冝冡冣冭冸冺冼冾冿凂"], +["8fb3a1","凈减凑凒凓凕凘凞凢凥凮凲凳凴凷刁刂刅划刓刕刖刘刢刨刱刲刵刼剅剉剕剗剘剚剜剟剠剡剦剮剷剸剹劀劂劅劊劌劓劕劖劗劘劚劜劤劥劦劧劯劰劶劷劸劺劻劽勀勄勆勈勌勏勑勔勖勛勜勡勥勨勩勪勬勰勱勴勶勷匀匃匊匋"], +["8fb4a1","匌匑匓匘匛匜匞匟匥匧匨匩匫匬匭匰匲匵匼匽匾卂卌卋卙卛卡卣卥卬卭卲卹卾厃厇厈厎厓厔厙厝厡厤厪厫厯厲厴厵厷厸厺厽叀叅叏叒叓叕叚叝叞叠另叧叵吂吓吚吡吧吨吪启吱吴吵呃呄呇呍呏呞呢呤呦呧呩呫呭呮呴呿"], +["8fb5a1","咁咃咅咈咉咍咑咕咖咜咟咡咦咧咩咪咭咮咱咷咹咺咻咿哆哊响哎哠哪哬哯哶哼哾哿唀唁唅唈唉唌唍唎唕唪唫唲唵唶唻唼唽啁啇啉啊啍啐啑啘啚啛啞啠啡啤啦啿喁喂喆喈喎喏喑喒喓喔喗喣喤喭喲喿嗁嗃嗆嗉嗋嗌嗎嗑嗒"], +["8fb6a1","嗓嗗嗘嗛嗞嗢嗩嗶嗿嘅嘈嘊嘍",5,"嘙嘬嘰嘳嘵嘷嘹嘻嘼嘽嘿噀噁噃噄噆噉噋噍噏噔噞噠噡噢噣噦噩噭噯噱噲噵嚄嚅嚈嚋嚌嚕嚙嚚嚝嚞嚟嚦嚧嚨嚩嚫嚬嚭嚱嚳嚷嚾囅囉囊囋囏囐囌囍囙囜囝囟囡囤",4,"囱囫园"], +["8fb7a1","囶囷圁圂圇圊圌圑圕圚圛圝圠圢圣圤圥圩圪圬圮圯圳圴圽圾圿坅坆坌坍坒坢坥坧坨坫坭",4,"坳坴坵坷坹坺坻坼坾垁垃垌垔垗垙垚垜垝垞垟垡垕垧垨垩垬垸垽埇埈埌埏埕埝埞埤埦埧埩埭埰埵埶埸埽埾埿堃堄堈堉埡"], +["8fb8a1","堌堍堛堞堟堠堦堧堭堲堹堿塉塌塍塏塐塕塟塡塤塧塨塸塼塿墀墁墇墈墉墊墌墍墏墐墔墖墝墠墡墢墦墩墱墲壄墼壂壈壍壎壐壒壔壖壚壝壡壢壩壳夅夆夋夌夒夓夔虁夝夡夣夤夨夯夰夳夵夶夿奃奆奒奓奙奛奝奞奟奡奣奫奭"], +["8fb9a1","奯奲奵奶她奻奼妋妌妎妒妕妗妟妤妧妭妮妯妰妳妷妺妼姁姃姄姈姊姍姒姝姞姟姣姤姧姮姯姱姲姴姷娀娄娌娍娎娒娓娞娣娤娧娨娪娭娰婄婅婇婈婌婐婕婞婣婥婧婭婷婺婻婾媋媐媓媖媙媜媞媟媠媢媧媬媱媲媳媵媸媺媻媿"], +["8fbaa1","嫄嫆嫈嫏嫚嫜嫠嫥嫪嫮嫵嫶嫽嬀嬁嬈嬗嬴嬙嬛嬝嬡嬥嬭嬸孁孋孌孒孖孞孨孮孯孼孽孾孿宁宄宆宊宎宐宑宓宔宖宨宩宬宭宯宱宲宷宺宼寀寁寍寏寖",4,"寠寯寱寴寽尌尗尞尟尣尦尩尫尬尮尰尲尵尶屙屚屜屢屣屧屨屩"], +["8fbba1","屭屰屴屵屺屻屼屽岇岈岊岏岒岝岟岠岢岣岦岪岲岴岵岺峉峋峒峝峗峮峱峲峴崁崆崍崒崫崣崤崦崧崱崴崹崽崿嵂嵃嵆嵈嵕嵑嵙嵊嵟嵠嵡嵢嵤嵪嵭嵰嵹嵺嵾嵿嶁嶃嶈嶊嶒嶓嶔嶕嶙嶛嶟嶠嶧嶫嶰嶴嶸嶹巃巇巋巐巎巘巙巠巤"], +["8fbca1","巩巸巹帀帇帍帒帔帕帘帟帠帮帨帲帵帾幋幐幉幑幖幘幛幜幞幨幪",4,"幰庀庋庎庢庤庥庨庪庬庱庳庽庾庿廆廌廋廎廑廒廔廕廜廞廥廫异弆弇弈弎弙弜弝弡弢弣弤弨弫弬弮弰弴弶弻弽弿彀彄彅彇彍彐彔彘彛彠彣彤彧"], +["8fbda1","彯彲彴彵彸彺彽彾徉徍徏徖徜徝徢徧徫徤徬徯徰徱徸忄忇忈忉忋忐",4,"忞忡忢忨忩忪忬忭忮忯忲忳忶忺忼怇怊怍怓怔怗怘怚怟怤怭怳怵恀恇恈恉恌恑恔恖恗恝恡恧恱恾恿悂悆悈悊悎悑悓悕悘悝悞悢悤悥您悰悱悷"], +["8fbea1","悻悾惂惄惈惉惊惋惎惏惔惕惙惛惝惞惢惥惲惵惸惼惽愂愇愊愌愐",4,"愖愗愙愜愞愢愪愫愰愱愵愶愷愹慁慅慆慉慞慠慬慲慸慻慼慿憀憁憃憄憋憍憒憓憗憘憜憝憟憠憥憨憪憭憸憹憼懀懁懂懎懏懕懜懝懞懟懡懢懧懩懥"], +["8fbfa1","懬懭懯戁戃戄戇戓戕戜戠戢戣戧戩戫戹戽扂扃扄扆扌扐扑扒扔扖扚扜扤扭扯扳扺扽抍抎抏抐抦抨抳抶抷抺抾抿拄拎拕拖拚拪拲拴拼拽挃挄挊挋挍挐挓挖挘挩挪挭挵挶挹挼捁捂捃捄捆捊捋捎捒捓捔捘捛捥捦捬捭捱捴捵"], +["8fc0a1","捸捼捽捿掂掄掇掊掐掔掕掙掚掞掤掦掭掮掯掽揁揅揈揎揑揓揔揕揜揠揥揪揬揲揳揵揸揹搉搊搐搒搔搘搞搠搢搤搥搩搪搯搰搵搽搿摋摏摑摒摓摔摚摛摜摝摟摠摡摣摭摳摴摻摽撅撇撏撐撑撘撙撛撝撟撡撣撦撨撬撳撽撾撿"], +["8fc1a1","擄擉擊擋擌擎擐擑擕擗擤擥擩擪擭擰擵擷擻擿攁攄攈攉攊攏攓攔攖攙攛攞攟攢攦攩攮攱攺攼攽敃敇敉敐敒敔敟敠敧敫敺敽斁斅斊斒斕斘斝斠斣斦斮斲斳斴斿旂旈旉旎旐旔旖旘旟旰旲旴旵旹旾旿昀昄昈昉昍昑昒昕昖昝"], +["8fc2a1","昞昡昢昣昤昦昩昪昫昬昮昰昱昳昹昷晀晅晆晊晌晑晎晗晘晙晛晜晠晡曻晪晫晬晾晳晵晿晷晸晹晻暀晼暋暌暍暐暒暙暚暛暜暟暠暤暭暱暲暵暻暿曀曂曃曈曌曎曏曔曛曟曨曫曬曮曺朅朇朎朓朙朜朠朢朳朾杅杇杈杌杔杕杝"], +["8fc3a1","杦杬杮杴杶杻极构枎枏枑枓枖枘枙枛枰枱枲枵枻枼枽柹柀柂柃柅柈柉柒柗柙柜柡柦柰柲柶柷桒栔栙栝栟栨栧栬栭栯栰栱栳栻栿桄桅桊桌桕桗桘桛桫桮",4,"桵桹桺桻桼梂梄梆梈梖梘梚梜梡梣梥梩梪梮梲梻棅棈棌棏"], +["8fc4a1","棐棑棓棖棙棜棝棥棨棪棫棬棭棰棱棵棶棻棼棽椆椉椊椐椑椓椖椗椱椳椵椸椻楂楅楉楎楗楛楣楤楥楦楨楩楬楰楱楲楺楻楿榀榍榒榖榘榡榥榦榨榫榭榯榷榸榺榼槅槈槑槖槗槢槥槮槯槱槳槵槾樀樁樃樏樑樕樚樝樠樤樨樰樲"], +["8fc5a1","樴樷樻樾樿橅橆橉橊橎橐橑橒橕橖橛橤橧橪橱橳橾檁檃檆檇檉檋檑檛檝檞檟檥檫檯檰檱檴檽檾檿櫆櫉櫈櫌櫐櫔櫕櫖櫜櫝櫤櫧櫬櫰櫱櫲櫼櫽欂欃欆欇欉欏欐欑欗欛欞欤欨欫欬欯欵欶欻欿歆歊歍歒歖歘歝歠歧歫歮歰歵歽"], +["8fc6a1","歾殂殅殗殛殟殠殢殣殨殩殬殭殮殰殸殹殽殾毃毄毉毌毖毚毡毣毦毧毮毱毷毹毿氂氄氅氉氍氎氐氒氙氟氦氧氨氬氮氳氵氶氺氻氿汊汋汍汏汒汔汙汛汜汫汭汯汴汶汸汹汻沅沆沇沉沔沕沗沘沜沟沰沲沴泂泆泍泏泐泑泒泔泖"], +["8fc7a1","泚泜泠泧泩泫泬泮泲泴洄洇洊洎洏洑洓洚洦洧洨汧洮洯洱洹洼洿浗浞浟浡浥浧浯浰浼涂涇涑涒涔涖涗涘涪涬涴涷涹涽涿淄淈淊淎淏淖淛淝淟淠淢淥淩淯淰淴淶淼渀渄渞渢渧渲渶渹渻渼湄湅湈湉湋湏湑湒湓湔湗湜湝湞"], +["8fc8a1","湢湣湨湳湻湽溍溓溙溠溧溭溮溱溳溻溿滀滁滃滇滈滊滍滎滏滫滭滮滹滻滽漄漈漊漌漍漖漘漚漛漦漩漪漯漰漳漶漻漼漭潏潑潒潓潗潙潚潝潞潡潢潨潬潽潾澃澇澈澋澌澍澐澒澓澔澖澚澟澠澥澦澧澨澮澯澰澵澶澼濅濇濈濊"], +["8fc9a1","濚濞濨濩濰濵濹濼濽瀀瀅瀆瀇瀍瀗瀠瀣瀯瀴瀷瀹瀼灃灄灈灉灊灋灔灕灝灞灎灤灥灬灮灵灶灾炁炅炆炔",4,"炛炤炫炰炱炴炷烊烑烓烔烕烖烘烜烤烺焃",4,"焋焌焏焞焠焫焭焯焰焱焸煁煅煆煇煊煋煐煒煗煚煜煞煠"], +["8fcaa1","煨煹熀熅熇熌熒熚熛熠熢熯熰熲熳熺熿燀燁燄燋燌燓燖燙燚燜燸燾爀爇爈爉爓爗爚爝爟爤爫爯爴爸爹牁牂牃牅牎牏牐牓牕牖牚牜牞牠牣牨牫牮牯牱牷牸牻牼牿犄犉犍犎犓犛犨犭犮犱犴犾狁狇狉狌狕狖狘狟狥狳狴狺狻"], +["8fcba1","狾猂猄猅猇猋猍猒猓猘猙猞猢猤猧猨猬猱猲猵猺猻猽獃獍獐獒獖獘獝獞獟獠獦獧獩獫獬獮獯獱獷獹獼玀玁玃玅玆玎玐玓玕玗玘玜玞玟玠玢玥玦玪玫玭玵玷玹玼玽玿珅珆珉珋珌珏珒珓珖珙珝珡珣珦珧珩珴珵珷珹珺珻珽"], +["8fcca1","珿琀琁琄琇琊琑琚琛琤琦琨",9,"琹瑀瑃瑄瑆瑇瑋瑍瑑瑒瑗瑝瑢瑦瑧瑨瑫瑭瑮瑱瑲璀璁璅璆璇璉璏璐璑璒璘璙璚璜璟璠璡璣璦璨璩璪璫璮璯璱璲璵璹璻璿瓈瓉瓌瓐瓓瓘瓚瓛瓞瓟瓤瓨瓪瓫瓯瓴瓺瓻瓼瓿甆"], +["8fcda1","甒甖甗甠甡甤甧甩甪甯甶甹甽甾甿畀畃畇畈畎畐畒畗畞畟畡畯畱畹",5,"疁疅疐疒疓疕疙疜疢疤疴疺疿痀痁痄痆痌痎痏痗痜痟痠痡痤痧痬痮痯痱痹瘀瘂瘃瘄瘇瘈瘊瘌瘏瘒瘓瘕瘖瘙瘛瘜瘝瘞瘣瘥瘦瘩瘭瘲瘳瘵瘸瘹"], +["8fcea1","瘺瘼癊癀癁癃癄癅癉癋癕癙癟癤癥癭癮癯癱癴皁皅皌皍皕皛皜皝皟皠皢",6,"皪皭皽盁盅盉盋盌盎盔盙盠盦盨盬盰盱盶盹盼眀眆眊眎眒眔眕眗眙眚眜眢眨眭眮眯眴眵眶眹眽眾睂睅睆睊睍睎睏睒睖睗睜睞睟睠睢"], +["8fcfa1","睤睧睪睬睰睲睳睴睺睽瞀瞄瞌瞍瞔瞕瞖瞚瞟瞢瞧瞪瞮瞯瞱瞵瞾矃矉矑矒矕矙矞矟矠矤矦矪矬矰矱矴矸矻砅砆砉砍砎砑砝砡砢砣砭砮砰砵砷硃硄硇硈硌硎硒硜硞硠硡硣硤硨硪确硺硾碊碏碔碘碡碝碞碟碤碨碬碭碰碱碲碳"], +["8fd0a1","碻碽碿磇磈磉磌磎磒磓磕磖磤磛磟磠磡磦磪磲磳礀磶磷磺磻磿礆礌礐礚礜礞礟礠礥礧礩礭礱礴礵礻礽礿祄祅祆祊祋祏祑祔祘祛祜祧祩祫祲祹祻祼祾禋禌禑禓禔禕禖禘禛禜禡禨禩禫禯禱禴禸离秂秄秇秈秊秏秔秖秚秝秞"], +["8fd1a1","秠秢秥秪秫秭秱秸秼稂稃稇稉稊稌稑稕稛稞稡稧稫稭稯稰稴稵稸稹稺穄穅穇穈穌穕穖穙穜穝穟穠穥穧穪穭穵穸穾窀窂窅窆窊窋窐窑窔窞窠窣窬窳窵窹窻窼竆竉竌竎竑竛竨竩竫竬竱竴竻竽竾笇笔笟笣笧笩笪笫笭笮笯笰"], +["8fd2a1","笱笴笽笿筀筁筇筎筕筠筤筦筩筪筭筯筲筳筷箄箉箎箐箑箖箛箞箠箥箬箯箰箲箵箶箺箻箼箽篂篅篈篊篔篖篗篙篚篛篨篪篲篴篵篸篹篺篼篾簁簂簃簄簆簉簋簌簎簏簙簛簠簥簦簨簬簱簳簴簶簹簺籆籊籕籑籒籓籙",5], +["8fd3a1","籡籣籧籩籭籮籰籲籹籼籽粆粇粏粔粞粠粦粰粶粷粺粻粼粿糄糇糈糉糍糏糓糔糕糗糙糚糝糦糩糫糵紃紇紈紉紏紑紒紓紖紝紞紣紦紪紭紱紼紽紾絀絁絇絈絍絑絓絗絙絚絜絝絥絧絪絰絸絺絻絿綁綂綃綅綆綈綋綌綍綑綖綗綝"], +["8fd4a1","綞綦綧綪綳綶綷綹緂",4,"緌緍緎緗緙縀緢緥緦緪緫緭緱緵緶緹緺縈縐縑縕縗縜縝縠縧縨縬縭縯縳縶縿繄繅繇繎繐繒繘繟繡繢繥繫繮繯繳繸繾纁纆纇纊纍纑纕纘纚纝纞缼缻缽缾缿罃罄罇罏罒罓罛罜罝罡罣罤罥罦罭"], +["8fd5a1","罱罽罾罿羀羋羍羏羐羑羖羗羜羡羢羦羪羭羴羼羿翀翃翈翎翏翛翟翣翥翨翬翮翯翲翺翽翾翿耇耈耊耍耎耏耑耓耔耖耝耞耟耠耤耦耬耮耰耴耵耷耹耺耼耾聀聄聠聤聦聭聱聵肁肈肎肜肞肦肧肫肸肹胈胍胏胒胔胕胗胘胠胭胮"], +["8fd6a1","胰胲胳胶胹胺胾脃脋脖脗脘脜脞脠脤脧脬脰脵脺脼腅腇腊腌腒腗腠腡腧腨腩腭腯腷膁膐膄膅膆膋膎膖膘膛膞膢膮膲膴膻臋臃臅臊臎臏臕臗臛臝臞臡臤臫臬臰臱臲臵臶臸臹臽臿舀舃舏舓舔舙舚舝舡舢舨舲舴舺艃艄艅艆"], +["8fd7a1","艋艎艏艑艖艜艠艣艧艭艴艻艽艿芀芁芃芄芇芉芊芎芑芔芖芘芚芛芠芡芣芤芧芨芩芪芮芰芲芴芷芺芼芾芿苆苐苕苚苠苢苤苨苪苭苯苶苷苽苾茀茁茇茈茊茋荔茛茝茞茟茡茢茬茭茮茰茳茷茺茼茽荂荃荄荇荍荎荑荕荖荗荰荸"], +["8fd8a1","荽荿莀莂莄莆莍莒莔莕莘莙莛莜莝莦莧莩莬莾莿菀菇菉菏菐菑菔菝荓菨菪菶菸菹菼萁萆萊萏萑萕萙莭萯萹葅葇葈葊葍葏葑葒葖葘葙葚葜葠葤葥葧葪葰葳葴葶葸葼葽蒁蒅蒒蒓蒕蒞蒦蒨蒩蒪蒯蒱蒴蒺蒽蒾蓀蓂蓇蓈蓌蓏蓓"], +["8fd9a1","蓜蓧蓪蓯蓰蓱蓲蓷蔲蓺蓻蓽蔂蔃蔇蔌蔎蔐蔜蔞蔢蔣蔤蔥蔧蔪蔫蔯蔳蔴蔶蔿蕆蕏",4,"蕖蕙蕜",6,"蕤蕫蕯蕹蕺蕻蕽蕿薁薅薆薉薋薌薏薓薘薝薟薠薢薥薧薴薶薷薸薼薽薾薿藂藇藊藋藎薭藘藚藟藠藦藨藭藳藶藼"], +["8fdaa1","藿蘀蘄蘅蘍蘎蘐蘑蘒蘘蘙蘛蘞蘡蘧蘩蘶蘸蘺蘼蘽虀虂虆虒虓虖虗虘虙虝虠",4,"虩虬虯虵虶虷虺蚍蚑蚖蚘蚚蚜蚡蚦蚧蚨蚭蚱蚳蚴蚵蚷蚸蚹蚿蛀蛁蛃蛅蛑蛒蛕蛗蛚蛜蛠蛣蛥蛧蚈蛺蛼蛽蜄蜅蜇蜋蜎蜏蜐蜓蜔蜙蜞蜟蜡蜣"], +["8fdba1","蜨蜮蜯蜱蜲蜹蜺蜼蜽蜾蝀蝃蝅蝍蝘蝝蝡蝤蝥蝯蝱蝲蝻螃",6,"螋螌螐螓螕螗螘螙螞螠螣螧螬螭螮螱螵螾螿蟁蟈蟉蟊蟎蟕蟖蟙蟚蟜蟟蟢蟣蟤蟪蟫蟭蟱蟳蟸蟺蟿蠁蠃蠆蠉蠊蠋蠐蠙蠒蠓蠔蠘蠚蠛蠜蠞蠟蠨蠭蠮蠰蠲蠵"], +["8fdca1","蠺蠼衁衃衅衈衉衊衋衎衑衕衖衘衚衜衟衠衤衩衱衹衻袀袘袚袛袜袟袠袨袪袺袽袾裀裊",4,"裑裒裓裛裞裧裯裰裱裵裷褁褆褍褎褏褕褖褘褙褚褜褠褦褧褨褰褱褲褵褹褺褾襀襂襅襆襉襏襒襗襚襛襜襡襢襣襫襮襰襳襵襺"], +["8fdda1","襻襼襽覉覍覐覔覕覛覜覟覠覥覰覴覵覶覷覼觔",4,"觥觩觫觭觱觳觶觹觽觿訄訅訇訏訑訒訔訕訞訠訢訤訦訫訬訯訵訷訽訾詀詃詅詇詉詍詎詓詖詗詘詜詝詡詥詧詵詶詷詹詺詻詾詿誀誃誆誋誏誐誒誖誗誙誟誧誩誮誯誳"], +["8fdea1","誶誷誻誾諃諆諈諉諊諑諓諔諕諗諝諟諬諰諴諵諶諼諿謅謆謋謑謜謞謟謊謭謰謷謼譂",4,"譈譒譓譔譙譍譞譣譭譶譸譹譼譾讁讄讅讋讍讏讔讕讜讞讟谸谹谽谾豅豇豉豋豏豑豓豔豗豘豛豝豙豣豤豦豨豩豭豳豵豶豻豾貆"], +["8fdfa1","貇貋貐貒貓貙貛貜貤貹貺賅賆賉賋賏賖賕賙賝賡賨賬賯賰賲賵賷賸賾賿贁贃贉贒贗贛赥赩赬赮赿趂趄趈趍趐趑趕趞趟趠趦趫趬趯趲趵趷趹趻跀跅跆跇跈跊跎跑跔跕跗跙跤跥跧跬跰趼跱跲跴跽踁踄踅踆踋踑踔踖踠踡踢"], +["8fe0a1","踣踦踧踱踳踶踷踸踹踽蹀蹁蹋蹍蹎蹏蹔蹛蹜蹝蹞蹡蹢蹩蹬蹭蹯蹰蹱蹹蹺蹻躂躃躉躐躒躕躚躛躝躞躢躧躩躭躮躳躵躺躻軀軁軃軄軇軏軑軔軜軨軮軰軱軷軹軺軭輀輂輇輈輏輐輖輗輘輞輠輡輣輥輧輨輬輭輮輴輵輶輷輺轀轁"], +["8fe1a1","轃轇轏轑",4,"轘轝轞轥辝辠辡辤辥辦辵辶辸达迀迁迆迊迋迍运迒迓迕迠迣迤迨迮迱迵迶迻迾适逄逈逌逘逛逨逩逯逪逬逭逳逴逷逿遃遄遌遛遝遢遦遧遬遰遴遹邅邈邋邌邎邐邕邗邘邙邛邠邡邢邥邰邲邳邴邶邽郌邾郃"], +["8fe2a1","郄郅郇郈郕郗郘郙郜郝郟郥郒郶郫郯郰郴郾郿鄀鄄鄅鄆鄈鄍鄐鄔鄖鄗鄘鄚鄜鄞鄠鄥鄢鄣鄧鄩鄮鄯鄱鄴鄶鄷鄹鄺鄼鄽酃酇酈酏酓酗酙酚酛酡酤酧酭酴酹酺酻醁醃醅醆醊醎醑醓醔醕醘醞醡醦醨醬醭醮醰醱醲醳醶醻醼醽醿"], +["8fe3a1","釂釃釅釓釔釗釙釚釞釤釥釩釪釬",5,"釷釹釻釽鈀鈁鈄鈅鈆鈇鈉鈊鈌鈐鈒鈓鈖鈘鈜鈝鈣鈤鈥鈦鈨鈮鈯鈰鈳鈵鈶鈸鈹鈺鈼鈾鉀鉂鉃鉆鉇鉊鉍鉎鉏鉑鉘鉙鉜鉝鉠鉡鉥鉧鉨鉩鉮鉯鉰鉵",4,"鉻鉼鉽鉿銈銉銊銍銎銒銗"], +["8fe4a1","銙銟銠銤銥銧銨銫銯銲銶銸銺銻銼銽銿",4,"鋅鋆鋇鋈鋋鋌鋍鋎鋐鋓鋕鋗鋘鋙鋜鋝鋟鋠鋡鋣鋥鋧鋨鋬鋮鋰鋹鋻鋿錀錂錈錍錑錔錕錜錝錞錟錡錤錥錧錩錪錳錴錶錷鍇鍈鍉鍐鍑鍒鍕鍗鍘鍚鍞鍤鍥鍧鍩鍪鍭鍯鍰鍱鍳鍴鍶"], +["8fe5a1","鍺鍽鍿鎀鎁鎂鎈鎊鎋鎍鎏鎒鎕鎘鎛鎞鎡鎣鎤鎦鎨鎫鎴鎵鎶鎺鎩鏁鏄鏅鏆鏇鏉",4,"鏓鏙鏜鏞鏟鏢鏦鏧鏹鏷鏸鏺鏻鏽鐁鐂鐄鐈鐉鐍鐎鐏鐕鐖鐗鐟鐮鐯鐱鐲鐳鐴鐻鐿鐽鑃鑅鑈鑊鑌鑕鑙鑜鑟鑡鑣鑨鑫鑭鑮鑯鑱鑲钄钃镸镹"], +["8fe6a1","镾閄閈閌閍閎閝閞閟閡閦閩閫閬閴閶閺閽閿闆闈闉闋闐闑闒闓闙闚闝闞闟闠闤闦阝阞阢阤阥阦阬阱阳阷阸阹阺阼阽陁陒陔陖陗陘陡陮陴陻陼陾陿隁隂隃隄隉隑隖隚隝隟隤隥隦隩隮隯隳隺雊雒嶲雘雚雝雞雟雩雯雱雺霂"], +["8fe7a1","霃霅霉霚霛霝霡霢霣霨霱霳靁靃靊靎靏靕靗靘靚靛靣靧靪靮靳靶靷靸靻靽靿鞀鞉鞕鞖鞗鞙鞚鞞鞟鞢鞬鞮鞱鞲鞵鞶鞸鞹鞺鞼鞾鞿韁韄韅韇韉韊韌韍韎韐韑韔韗韘韙韝韞韠韛韡韤韯韱韴韷韸韺頇頊頙頍頎頔頖頜頞頠頣頦"], +["8fe8a1","頫頮頯頰頲頳頵頥頾顄顇顊顑顒顓顖顗顙顚顢顣顥顦顪顬颫颭颮颰颴颷颸颺颻颿飂飅飈飌飡飣飥飦飧飪飳飶餂餇餈餑餕餖餗餚餛餜餟餢餦餧餫餱",4,"餹餺餻餼饀饁饆饇饈饍饎饔饘饙饛饜饞饟饠馛馝馟馦馰馱馲馵"], +["8fe9a1","馹馺馽馿駃駉駓駔駙駚駜駞駧駪駫駬駰駴駵駹駽駾騂騃騄騋騌騐騑騖騞騠騢騣騤騧騭騮騳騵騶騸驇驁驄驊驋驌驎驑驔驖驝骪骬骮骯骲骴骵骶骹骻骾骿髁髃髆髈髎髐髒髕髖髗髛髜髠髤髥髧髩髬髲髳髵髹髺髽髿",4], +["8feaa1","鬄鬅鬈鬉鬋鬌鬍鬎鬐鬒鬖鬙鬛鬜鬠鬦鬫鬭鬳鬴鬵鬷鬹鬺鬽魈魋魌魕魖魗魛魞魡魣魥魦魨魪",4,"魳魵魷魸魹魿鮀鮄鮅鮆鮇鮉鮊鮋鮍鮏鮐鮔鮚鮝鮞鮦鮧鮩鮬鮰鮱鮲鮷鮸鮻鮼鮾鮿鯁鯇鯈鯎鯐鯗鯘鯝鯟鯥鯧鯪鯫鯯鯳鯷鯸"], +["8feba1","鯹鯺鯽鯿鰀鰂鰋鰏鰑鰖鰘鰙鰚鰜鰞鰢鰣鰦",4,"鰱鰵鰶鰷鰽鱁鱃鱄鱅鱉鱊鱎鱏鱐鱓鱔鱖鱘鱛鱝鱞鱟鱣鱩鱪鱜鱫鱨鱮鱰鱲鱵鱷鱻鳦鳲鳷鳹鴋鴂鴑鴗鴘鴜鴝鴞鴯鴰鴲鴳鴴鴺鴼鵅鴽鵂鵃鵇鵊鵓鵔鵟鵣鵢鵥鵩鵪鵫鵰鵶鵷鵻"], +["8feca1","鵼鵾鶃鶄鶆鶊鶍鶎鶒鶓鶕鶖鶗鶘鶡鶪鶬鶮鶱鶵鶹鶼鶿鷃鷇鷉鷊鷔鷕鷖鷗鷚鷞鷟鷠鷥鷧鷩鷫鷮鷰鷳鷴鷾鸊鸂鸇鸎鸐鸑鸒鸕鸖鸙鸜鸝鹺鹻鹼麀麂麃麄麅麇麎麏麖麘麛麞麤麨麬麮麯麰麳麴麵黆黈黋黕黟黤黧黬黭黮黰黱黲黵"], +["8feda1","黸黿鼂鼃鼉鼏鼐鼑鼒鼔鼖鼗鼙鼚鼛鼟鼢鼦鼪鼫鼯鼱鼲鼴鼷鼹鼺鼼鼽鼿齁齃",4,"齓齕齖齗齘齚齝齞齨齩齭",4,"齳齵齺齽龏龐龑龒龔龖龗龞龡龢龣龥"] +] diff --git a/backend/node_modules/iconv-lite/encodings/tables/gb18030-ranges.json b/backend/node_modules/iconv-lite/encodings/tables/gb18030-ranges.json new file mode 100644 index 0000000000000000000000000000000000000000..85c6934757761e98580abf0c26c351b6fdfd6ad5 --- /dev/null +++ b/backend/node_modules/iconv-lite/encodings/tables/gb18030-ranges.json @@ -0,0 +1 @@ +{"uChars":[128,165,169,178,184,216,226,235,238,244,248,251,253,258,276,284,300,325,329,334,364,463,465,467,469,471,473,475,477,506,594,610,712,716,730,930,938,962,970,1026,1104,1106,8209,8215,8218,8222,8231,8241,8244,8246,8252,8365,8452,8454,8458,8471,8482,8556,8570,8596,8602,8713,8720,8722,8726,8731,8737,8740,8742,8748,8751,8760,8766,8777,8781,8787,8802,8808,8816,8854,8858,8870,8896,8979,9322,9372,9548,9588,9616,9622,9634,9652,9662,9672,9676,9680,9702,9735,9738,9793,9795,11906,11909,11913,11917,11928,11944,11947,11951,11956,11960,11964,11979,12284,12292,12312,12319,12330,12351,12436,12447,12535,12543,12586,12842,12850,12964,13200,13215,13218,13253,13263,13267,13270,13384,13428,13727,13839,13851,14617,14703,14801,14816,14964,15183,15471,15585,16471,16736,17208,17325,17330,17374,17623,17997,18018,18212,18218,18301,18318,18760,18811,18814,18820,18823,18844,18848,18872,19576,19620,19738,19887,40870,59244,59336,59367,59413,59417,59423,59431,59437,59443,59452,59460,59478,59493,63789,63866,63894,63976,63986,64016,64018,64021,64025,64034,64037,64042,65074,65093,65107,65112,65127,65132,65375,65510,65536],"gbChars":[0,36,38,45,50,81,89,95,96,100,103,104,105,109,126,133,148,172,175,179,208,306,307,308,309,310,311,312,313,341,428,443,544,545,558,741,742,749,750,805,819,820,7922,7924,7925,7927,7934,7943,7944,7945,7950,8062,8148,8149,8152,8164,8174,8236,8240,8262,8264,8374,8380,8381,8384,8388,8390,8392,8393,8394,8396,8401,8406,8416,8419,8424,8437,8439,8445,8482,8485,8496,8521,8603,8936,8946,9046,9050,9063,9066,9076,9092,9100,9108,9111,9113,9131,9162,9164,9218,9219,11329,11331,11334,11336,11346,11361,11363,11366,11370,11372,11375,11389,11682,11686,11687,11692,11694,11714,11716,11723,11725,11730,11736,11982,11989,12102,12336,12348,12350,12384,12393,12395,12397,12510,12553,12851,12962,12973,13738,13823,13919,13933,14080,14298,14585,14698,15583,15847,16318,16434,16438,16481,16729,17102,17122,17315,17320,17402,17418,17859,17909,17911,17915,17916,17936,17939,17961,18664,18703,18814,18962,19043,33469,33470,33471,33484,33485,33490,33497,33501,33505,33513,33520,33536,33550,37845,37921,37948,38029,38038,38064,38065,38066,38069,38075,38076,38078,39108,39109,39113,39114,39115,39116,39265,39394,189000]} \ No newline at end of file diff --git a/backend/node_modules/iconv-lite/encodings/tables/gbk-added.json b/backend/node_modules/iconv-lite/encodings/tables/gbk-added.json new file mode 100644 index 0000000000000000000000000000000000000000..8abfa9f7b987ad6effc35544dbc488d9c67e0c5e --- /dev/null +++ b/backend/node_modules/iconv-lite/encodings/tables/gbk-added.json @@ -0,0 +1,55 @@ +[ +["a140","",62], +["a180","",32], +["a240","",62], +["a280","",32], +["a2ab","",5], +["a2e3","€"], +["a2ef",""], +["a2fd",""], +["a340","",62], +["a380","",31," "], +["a440","",62], +["a480","",32], +["a4f4","",10], +["a540","",62], +["a580","",32], +["a5f7","",7], +["a640","",62], +["a680","",32], +["a6b9","",7], +["a6d9","",6], +["a6ec",""], +["a6f3",""], +["a6f6","",8], +["a740","",62], +["a780","",32], +["a7c2","",14], +["a7f2","",12], +["a896","",10], +["a8bc",""], +["a8bf","ǹ"], +["a8c1",""], +["a8ea","",20], +["a958",""], +["a95b",""], +["a95d",""], +["a989","〾⿰",11], +["a997","",12], +["a9f0","",14], +["aaa1","",93], +["aba1","",93], +["aca1","",93], +["ada1","",93], +["aea1","",93], +["afa1","",93], +["d7fa","",4], +["f8a1","",93], +["f9a1","",93], +["faa1","",93], +["fba1","",93], +["fca1","",93], +["fda1","",93], +["fe50","⺁⺄㑳㑇⺈⺋㖞㘚㘎⺌⺗㥮㤘㧏㧟㩳㧐㭎㱮㳠⺧⺪䁖䅟⺮䌷⺳⺶⺷䎱䎬⺻䏝䓖䙡䙌"], +["fe80","䜣䜩䝼䞍⻊䥇䥺䥽䦂䦃䦅䦆䦟䦛䦷䦶䲣䲟䲠䲡䱷䲢䴓",6,"䶮",93] +] diff --git a/backend/node_modules/iconv-lite/encodings/tables/shiftjis.json b/backend/node_modules/iconv-lite/encodings/tables/shiftjis.json new file mode 100644 index 0000000000000000000000000000000000000000..5a3a43cf8cf6d20324a49b75aff87d1bf902d108 --- /dev/null +++ b/backend/node_modules/iconv-lite/encodings/tables/shiftjis.json @@ -0,0 +1,125 @@ +[ +["0","\u0000",128], +["a1","。",62], +["8140"," 、。,.・:;?!゛゜´`¨^ ̄_ヽヾゝゞ〃仝々〆〇ー―‐/\~∥|…‥‘’“”()〔〕[]{}〈",9,"+-±×"], +["8180","÷=≠<>≦≧∞∴♂♀°′″℃¥$¢£%#&*@§☆★○●◎◇◆□■△▲▽▼※〒→←↑↓〓"], +["81b8","∈∋⊆⊇⊂⊃∪∩"], +["81c8","∧∨¬⇒⇔∀∃"], +["81da","∠⊥⌒∂∇≡≒≪≫√∽∝∵∫∬"], +["81f0","ʼn♯♭♪†‡¶"], +["81fc","◯"], +["824f","0",9], +["8260","A",25], +["8281","a",25], +["829f","ぁ",82], +["8340","ァ",62], +["8380","ム",22], +["839f","Α",16,"Σ",6], +["83bf","α",16,"σ",6], +["8440","А",5,"ЁЖ",25], +["8470","а",5,"ёж",7], +["8480","о",17], +["849f","─│┌┐┘└├┬┤┴┼━┃┏┓┛┗┣┳┫┻╋┠┯┨┷┿┝┰┥┸╂"], +["8740","①",19,"Ⅰ",9], +["875f","㍉㌔㌢㍍㌘㌧㌃㌶㍑㍗㌍㌦㌣㌫㍊㌻㎜㎝㎞㎎㎏㏄㎡"], +["877e","㍻"], +["8780","〝〟№㏍℡㊤",4,"㈱㈲㈹㍾㍽㍼≒≡∫∮∑√⊥∠∟⊿∵∩∪"], +["889f","亜唖娃阿哀愛挨姶逢葵茜穐悪握渥旭葦芦鯵梓圧斡扱宛姐虻飴絢綾鮎或粟袷安庵按暗案闇鞍杏以伊位依偉囲夷委威尉惟意慰易椅為畏異移維緯胃萎衣謂違遺医井亥域育郁磯一壱溢逸稲茨芋鰯允印咽員因姻引飲淫胤蔭"], +["8940","院陰隠韻吋右宇烏羽迂雨卯鵜窺丑碓臼渦嘘唄欝蔚鰻姥厩浦瓜閏噂云運雲荏餌叡営嬰影映曳栄永泳洩瑛盈穎頴英衛詠鋭液疫益駅悦謁越閲榎厭円"], +["8980","園堰奄宴延怨掩援沿演炎焔煙燕猿縁艶苑薗遠鉛鴛塩於汚甥凹央奥往応押旺横欧殴王翁襖鴬鴎黄岡沖荻億屋憶臆桶牡乙俺卸恩温穏音下化仮何伽価佳加可嘉夏嫁家寡科暇果架歌河火珂禍禾稼箇花苛茄荷華菓蝦課嘩貨迦過霞蚊俄峨我牙画臥芽蛾賀雅餓駕介会解回塊壊廻快怪悔恢懐戒拐改"], +["8a40","魁晦械海灰界皆絵芥蟹開階貝凱劾外咳害崖慨概涯碍蓋街該鎧骸浬馨蛙垣柿蛎鈎劃嚇各廓拡撹格核殻獲確穫覚角赫較郭閣隔革学岳楽額顎掛笠樫"], +["8a80","橿梶鰍潟割喝恰括活渇滑葛褐轄且鰹叶椛樺鞄株兜竃蒲釜鎌噛鴨栢茅萱粥刈苅瓦乾侃冠寒刊勘勧巻喚堪姦完官寛干幹患感慣憾換敢柑桓棺款歓汗漢澗潅環甘監看竿管簡緩缶翰肝艦莞観諌貫還鑑間閑関陥韓館舘丸含岸巌玩癌眼岩翫贋雁頑顔願企伎危喜器基奇嬉寄岐希幾忌揮机旗既期棋棄"], +["8b40","機帰毅気汽畿祈季稀紀徽規記貴起軌輝飢騎鬼亀偽儀妓宜戯技擬欺犠疑祇義蟻誼議掬菊鞠吉吃喫桔橘詰砧杵黍却客脚虐逆丘久仇休及吸宮弓急救"], +["8b80","朽求汲泣灸球究窮笈級糾給旧牛去居巨拒拠挙渠虚許距鋸漁禦魚亨享京供侠僑兇競共凶協匡卿叫喬境峡強彊怯恐恭挟教橋況狂狭矯胸脅興蕎郷鏡響饗驚仰凝尭暁業局曲極玉桐粁僅勤均巾錦斤欣欽琴禁禽筋緊芹菌衿襟謹近金吟銀九倶句区狗玖矩苦躯駆駈駒具愚虞喰空偶寓遇隅串櫛釧屑屈"], +["8c40","掘窟沓靴轡窪熊隈粂栗繰桑鍬勲君薫訓群軍郡卦袈祁係傾刑兄啓圭珪型契形径恵慶慧憩掲携敬景桂渓畦稽系経継繋罫茎荊蛍計詣警軽頚鶏芸迎鯨"], +["8c80","劇戟撃激隙桁傑欠決潔穴結血訣月件倹倦健兼券剣喧圏堅嫌建憲懸拳捲検権牽犬献研硯絹県肩見謙賢軒遣鍵険顕験鹸元原厳幻弦減源玄現絃舷言諺限乎個古呼固姑孤己庫弧戸故枯湖狐糊袴股胡菰虎誇跨鈷雇顧鼓五互伍午呉吾娯後御悟梧檎瑚碁語誤護醐乞鯉交佼侯候倖光公功効勾厚口向"], +["8d40","后喉坑垢好孔孝宏工巧巷幸広庚康弘恒慌抗拘控攻昂晃更杭校梗構江洪浩港溝甲皇硬稿糠紅紘絞綱耕考肯肱腔膏航荒行衡講貢購郊酵鉱砿鋼閤降"], +["8d80","項香高鴻剛劫号合壕拷濠豪轟麹克刻告国穀酷鵠黒獄漉腰甑忽惚骨狛込此頃今困坤墾婚恨懇昏昆根梱混痕紺艮魂些佐叉唆嵯左差査沙瑳砂詐鎖裟坐座挫債催再最哉塞妻宰彩才採栽歳済災采犀砕砦祭斎細菜裁載際剤在材罪財冴坂阪堺榊肴咲崎埼碕鷺作削咋搾昨朔柵窄策索錯桜鮭笹匙冊刷"], +["8e40","察拶撮擦札殺薩雑皐鯖捌錆鮫皿晒三傘参山惨撒散桟燦珊産算纂蚕讃賛酸餐斬暫残仕仔伺使刺司史嗣四士始姉姿子屍市師志思指支孜斯施旨枝止"], +["8e80","死氏獅祉私糸紙紫肢脂至視詞詩試誌諮資賜雌飼歯事似侍児字寺慈持時次滋治爾璽痔磁示而耳自蒔辞汐鹿式識鴫竺軸宍雫七叱執失嫉室悉湿漆疾質実蔀篠偲柴芝屡蕊縞舎写射捨赦斜煮社紗者謝車遮蛇邪借勺尺杓灼爵酌釈錫若寂弱惹主取守手朱殊狩珠種腫趣酒首儒受呪寿授樹綬需囚収周"], +["8f40","宗就州修愁拾洲秀秋終繍習臭舟蒐衆襲讐蹴輯週酋酬集醜什住充十従戎柔汁渋獣縦重銃叔夙宿淑祝縮粛塾熟出術述俊峻春瞬竣舜駿准循旬楯殉淳"], +["8f80","準潤盾純巡遵醇順処初所暑曙渚庶緒署書薯藷諸助叙女序徐恕鋤除傷償勝匠升召哨商唱嘗奨妾娼宵将小少尚庄床廠彰承抄招掌捷昇昌昭晶松梢樟樵沼消渉湘焼焦照症省硝礁祥称章笑粧紹肖菖蒋蕉衝裳訟証詔詳象賞醤鉦鍾鐘障鞘上丈丞乗冗剰城場壌嬢常情擾条杖浄状畳穣蒸譲醸錠嘱埴飾"], +["9040","拭植殖燭織職色触食蝕辱尻伸信侵唇娠寝審心慎振新晋森榛浸深申疹真神秦紳臣芯薪親診身辛進針震人仁刃塵壬尋甚尽腎訊迅陣靭笥諏須酢図厨"], +["9080","逗吹垂帥推水炊睡粋翠衰遂酔錐錘随瑞髄崇嵩数枢趨雛据杉椙菅頗雀裾澄摺寸世瀬畝是凄制勢姓征性成政整星晴棲栖正清牲生盛精聖声製西誠誓請逝醒青静斉税脆隻席惜戚斥昔析石積籍績脊責赤跡蹟碩切拙接摂折設窃節説雪絶舌蝉仙先千占宣専尖川戦扇撰栓栴泉浅洗染潜煎煽旋穿箭線"], +["9140","繊羨腺舛船薦詮賎践選遷銭銑閃鮮前善漸然全禅繕膳糎噌塑岨措曾曽楚狙疏疎礎祖租粗素組蘇訴阻遡鼠僧創双叢倉喪壮奏爽宋層匝惣想捜掃挿掻"], +["9180","操早曹巣槍槽漕燥争痩相窓糟総綜聡草荘葬蒼藻装走送遭鎗霜騒像増憎臓蔵贈造促側則即息捉束測足速俗属賊族続卒袖其揃存孫尊損村遜他多太汰詑唾堕妥惰打柁舵楕陀駄騨体堆対耐岱帯待怠態戴替泰滞胎腿苔袋貸退逮隊黛鯛代台大第醍題鷹滝瀧卓啄宅托択拓沢濯琢託鐸濁諾茸凧蛸只"], +["9240","叩但達辰奪脱巽竪辿棚谷狸鱈樽誰丹単嘆坦担探旦歎淡湛炭短端箪綻耽胆蛋誕鍛団壇弾断暖檀段男談値知地弛恥智池痴稚置致蜘遅馳築畜竹筑蓄"], +["9280","逐秩窒茶嫡着中仲宙忠抽昼柱注虫衷註酎鋳駐樗瀦猪苧著貯丁兆凋喋寵帖帳庁弔張彫徴懲挑暢朝潮牒町眺聴脹腸蝶調諜超跳銚長頂鳥勅捗直朕沈珍賃鎮陳津墜椎槌追鎚痛通塚栂掴槻佃漬柘辻蔦綴鍔椿潰坪壷嬬紬爪吊釣鶴亭低停偵剃貞呈堤定帝底庭廷弟悌抵挺提梯汀碇禎程締艇訂諦蹄逓"], +["9340","邸鄭釘鼎泥摘擢敵滴的笛適鏑溺哲徹撤轍迭鉄典填天展店添纏甜貼転顛点伝殿澱田電兎吐堵塗妬屠徒斗杜渡登菟賭途都鍍砥砺努度土奴怒倒党冬"], +["9380","凍刀唐塔塘套宕島嶋悼投搭東桃梼棟盗淘湯涛灯燈当痘祷等答筒糖統到董蕩藤討謄豆踏逃透鐙陶頭騰闘働動同堂導憧撞洞瞳童胴萄道銅峠鴇匿得徳涜特督禿篤毒独読栃橡凸突椴届鳶苫寅酉瀞噸屯惇敦沌豚遁頓呑曇鈍奈那内乍凪薙謎灘捺鍋楢馴縄畷南楠軟難汝二尼弐迩匂賑肉虹廿日乳入"], +["9440","如尿韮任妊忍認濡禰祢寧葱猫熱年念捻撚燃粘乃廼之埜嚢悩濃納能脳膿農覗蚤巴把播覇杷波派琶破婆罵芭馬俳廃拝排敗杯盃牌背肺輩配倍培媒梅"], +["9480","楳煤狽買売賠陪這蝿秤矧萩伯剥博拍柏泊白箔粕舶薄迫曝漠爆縛莫駁麦函箱硲箸肇筈櫨幡肌畑畠八鉢溌発醗髪伐罰抜筏閥鳩噺塙蛤隼伴判半反叛帆搬斑板氾汎版犯班畔繁般藩販範釆煩頒飯挽晩番盤磐蕃蛮匪卑否妃庇彼悲扉批披斐比泌疲皮碑秘緋罷肥被誹費避非飛樋簸備尾微枇毘琵眉美"], +["9540","鼻柊稗匹疋髭彦膝菱肘弼必畢筆逼桧姫媛紐百謬俵彪標氷漂瓢票表評豹廟描病秒苗錨鋲蒜蛭鰭品彬斌浜瀕貧賓頻敏瓶不付埠夫婦富冨布府怖扶敷"], +["9580","斧普浮父符腐膚芙譜負賦赴阜附侮撫武舞葡蕪部封楓風葺蕗伏副復幅服福腹複覆淵弗払沸仏物鮒分吻噴墳憤扮焚奮粉糞紛雰文聞丙併兵塀幣平弊柄並蔽閉陛米頁僻壁癖碧別瞥蔑箆偏変片篇編辺返遍便勉娩弁鞭保舗鋪圃捕歩甫補輔穂募墓慕戊暮母簿菩倣俸包呆報奉宝峰峯崩庖抱捧放方朋"], +["9640","法泡烹砲縫胞芳萌蓬蜂褒訪豊邦鋒飽鳳鵬乏亡傍剖坊妨帽忘忙房暴望某棒冒紡肪膨謀貌貿鉾防吠頬北僕卜墨撲朴牧睦穆釦勃没殆堀幌奔本翻凡盆"], +["9680","摩磨魔麻埋妹昧枚毎哩槙幕膜枕鮪柾鱒桝亦俣又抹末沫迄侭繭麿万慢満漫蔓味未魅巳箕岬密蜜湊蓑稔脈妙粍民眠務夢無牟矛霧鵡椋婿娘冥名命明盟迷銘鳴姪牝滅免棉綿緬面麺摸模茂妄孟毛猛盲網耗蒙儲木黙目杢勿餅尤戻籾貰問悶紋門匁也冶夜爺耶野弥矢厄役約薬訳躍靖柳薮鑓愉愈油癒"], +["9740","諭輸唯佑優勇友宥幽悠憂揖有柚湧涌猶猷由祐裕誘遊邑郵雄融夕予余与誉輿預傭幼妖容庸揚揺擁曜楊様洋溶熔用窯羊耀葉蓉要謡踊遥陽養慾抑欲"], +["9780","沃浴翌翼淀羅螺裸来莱頼雷洛絡落酪乱卵嵐欄濫藍蘭覧利吏履李梨理璃痢裏裡里離陸律率立葎掠略劉流溜琉留硫粒隆竜龍侶慮旅虜了亮僚両凌寮料梁涼猟療瞭稜糧良諒遼量陵領力緑倫厘林淋燐琳臨輪隣鱗麟瑠塁涙累類令伶例冷励嶺怜玲礼苓鈴隷零霊麗齢暦歴列劣烈裂廉恋憐漣煉簾練聯"], +["9840","蓮連錬呂魯櫓炉賂路露労婁廊弄朗楼榔浪漏牢狼篭老聾蝋郎六麓禄肋録論倭和話歪賄脇惑枠鷲亙亘鰐詫藁蕨椀湾碗腕"], +["989f","弌丐丕个丱丶丼丿乂乖乘亂亅豫亊舒弍于亞亟亠亢亰亳亶从仍仄仆仂仗仞仭仟价伉佚估佛佝佗佇佶侈侏侘佻佩佰侑佯來侖儘俔俟俎俘俛俑俚俐俤俥倚倨倔倪倥倅伜俶倡倩倬俾俯們倆偃假會偕偐偈做偖偬偸傀傚傅傴傲"], +["9940","僉僊傳僂僖僞僥僭僣僮價僵儉儁儂儖儕儔儚儡儺儷儼儻儿兀兒兌兔兢竸兩兪兮冀冂囘册冉冏冑冓冕冖冤冦冢冩冪冫决冱冲冰况冽凅凉凛几處凩凭"], +["9980","凰凵凾刄刋刔刎刧刪刮刳刹剏剄剋剌剞剔剪剴剩剳剿剽劍劔劒剱劈劑辨辧劬劭劼劵勁勍勗勞勣勦飭勠勳勵勸勹匆匈甸匍匐匏匕匚匣匯匱匳匸區卆卅丗卉卍凖卞卩卮夘卻卷厂厖厠厦厥厮厰厶參簒雙叟曼燮叮叨叭叺吁吽呀听吭吼吮吶吩吝呎咏呵咎呟呱呷呰咒呻咀呶咄咐咆哇咢咸咥咬哄哈咨"], +["9a40","咫哂咤咾咼哘哥哦唏唔哽哮哭哺哢唹啀啣啌售啜啅啖啗唸唳啝喙喀咯喊喟啻啾喘喞單啼喃喩喇喨嗚嗅嗟嗄嗜嗤嗔嘔嗷嘖嗾嗽嘛嗹噎噐營嘴嘶嘲嘸"], +["9a80","噫噤嘯噬噪嚆嚀嚊嚠嚔嚏嚥嚮嚶嚴囂嚼囁囃囀囈囎囑囓囗囮囹圀囿圄圉圈國圍圓團圖嗇圜圦圷圸坎圻址坏坩埀垈坡坿垉垓垠垳垤垪垰埃埆埔埒埓堊埖埣堋堙堝塲堡塢塋塰毀塒堽塹墅墹墟墫墺壞墻墸墮壅壓壑壗壙壘壥壜壤壟壯壺壹壻壼壽夂夊夐夛梦夥夬夭夲夸夾竒奕奐奎奚奘奢奠奧奬奩"], +["9b40","奸妁妝佞侫妣妲姆姨姜妍姙姚娥娟娑娜娉娚婀婬婉娵娶婢婪媚媼媾嫋嫂媽嫣嫗嫦嫩嫖嫺嫻嬌嬋嬖嬲嫐嬪嬶嬾孃孅孀孑孕孚孛孥孩孰孳孵學斈孺宀"], +["9b80","它宦宸寃寇寉寔寐寤實寢寞寥寫寰寶寳尅將專對尓尠尢尨尸尹屁屆屎屓屐屏孱屬屮乢屶屹岌岑岔妛岫岻岶岼岷峅岾峇峙峩峽峺峭嶌峪崋崕崗嵜崟崛崑崔崢崚崙崘嵌嵒嵎嵋嵬嵳嵶嶇嶄嶂嶢嶝嶬嶮嶽嶐嶷嶼巉巍巓巒巖巛巫已巵帋帚帙帑帛帶帷幄幃幀幎幗幔幟幢幤幇幵并幺麼广庠廁廂廈廐廏"], +["9c40","廖廣廝廚廛廢廡廨廩廬廱廳廰廴廸廾弃弉彝彜弋弑弖弩弭弸彁彈彌彎弯彑彖彗彙彡彭彳彷徃徂彿徊很徑徇從徙徘徠徨徭徼忖忻忤忸忱忝悳忿怡恠"], +["9c80","怙怐怩怎怱怛怕怫怦怏怺恚恁恪恷恟恊恆恍恣恃恤恂恬恫恙悁悍惧悃悚悄悛悖悗悒悧悋惡悸惠惓悴忰悽惆悵惘慍愕愆惶惷愀惴惺愃愡惻惱愍愎慇愾愨愧慊愿愼愬愴愽慂慄慳慷慘慙慚慫慴慯慥慱慟慝慓慵憙憖憇憬憔憚憊憑憫憮懌懊應懷懈懃懆憺懋罹懍懦懣懶懺懴懿懽懼懾戀戈戉戍戌戔戛"], +["9d40","戞戡截戮戰戲戳扁扎扞扣扛扠扨扼抂抉找抒抓抖拔抃抔拗拑抻拏拿拆擔拈拜拌拊拂拇抛拉挌拮拱挧挂挈拯拵捐挾捍搜捏掖掎掀掫捶掣掏掉掟掵捫"], +["9d80","捩掾揩揀揆揣揉插揶揄搖搴搆搓搦搶攝搗搨搏摧摯摶摎攪撕撓撥撩撈撼據擒擅擇撻擘擂擱擧舉擠擡抬擣擯攬擶擴擲擺攀擽攘攜攅攤攣攫攴攵攷收攸畋效敖敕敍敘敞敝敲數斂斃變斛斟斫斷旃旆旁旄旌旒旛旙无旡旱杲昊昃旻杳昵昶昴昜晏晄晉晁晞晝晤晧晨晟晢晰暃暈暎暉暄暘暝曁暹曉暾暼"], +["9e40","曄暸曖曚曠昿曦曩曰曵曷朏朖朞朦朧霸朮朿朶杁朸朷杆杞杠杙杣杤枉杰枩杼杪枌枋枦枡枅枷柯枴柬枳柩枸柤柞柝柢柮枹柎柆柧檜栞框栩桀桍栲桎"], +["9e80","梳栫桙档桷桿梟梏梭梔條梛梃檮梹桴梵梠梺椏梍桾椁棊椈棘椢椦棡椌棍棔棧棕椶椒椄棗棣椥棹棠棯椨椪椚椣椡棆楹楷楜楸楫楔楾楮椹楴椽楙椰楡楞楝榁楪榲榮槐榿槁槓榾槎寨槊槝榻槃榧樮榑榠榜榕榴槞槨樂樛槿權槹槲槧樅榱樞槭樔槫樊樒櫁樣樓橄樌橲樶橸橇橢橙橦橈樸樢檐檍檠檄檢檣"], +["9f40","檗蘗檻櫃櫂檸檳檬櫞櫑櫟檪櫚櫪櫻欅蘖櫺欒欖鬱欟欸欷盜欹飮歇歃歉歐歙歔歛歟歡歸歹歿殀殄殃殍殘殕殞殤殪殫殯殲殱殳殷殼毆毋毓毟毬毫毳毯"], +["9f80","麾氈氓气氛氤氣汞汕汢汪沂沍沚沁沛汾汨汳沒沐泄泱泓沽泗泅泝沮沱沾沺泛泯泙泪洟衍洶洫洽洸洙洵洳洒洌浣涓浤浚浹浙涎涕濤涅淹渕渊涵淇淦涸淆淬淞淌淨淒淅淺淙淤淕淪淮渭湮渮渙湲湟渾渣湫渫湶湍渟湃渺湎渤滿渝游溂溪溘滉溷滓溽溯滄溲滔滕溏溥滂溟潁漑灌滬滸滾漿滲漱滯漲滌"], +["e040","漾漓滷澆潺潸澁澀潯潛濳潭澂潼潘澎澑濂潦澳澣澡澤澹濆澪濟濕濬濔濘濱濮濛瀉瀋濺瀑瀁瀏濾瀛瀚潴瀝瀘瀟瀰瀾瀲灑灣炙炒炯烱炬炸炳炮烟烋烝"], +["e080","烙焉烽焜焙煥煕熈煦煢煌煖煬熏燻熄熕熨熬燗熹熾燒燉燔燎燠燬燧燵燼燹燿爍爐爛爨爭爬爰爲爻爼爿牀牆牋牘牴牾犂犁犇犒犖犢犧犹犲狃狆狄狎狒狢狠狡狹狷倏猗猊猜猖猝猴猯猩猥猾獎獏默獗獪獨獰獸獵獻獺珈玳珎玻珀珥珮珞璢琅瑯琥珸琲琺瑕琿瑟瑙瑁瑜瑩瑰瑣瑪瑶瑾璋璞璧瓊瓏瓔珱"], +["e140","瓠瓣瓧瓩瓮瓲瓰瓱瓸瓷甄甃甅甌甎甍甕甓甞甦甬甼畄畍畊畉畛畆畚畩畤畧畫畭畸當疆疇畴疊疉疂疔疚疝疥疣痂疳痃疵疽疸疼疱痍痊痒痙痣痞痾痿"], +["e180","痼瘁痰痺痲痳瘋瘍瘉瘟瘧瘠瘡瘢瘤瘴瘰瘻癇癈癆癜癘癡癢癨癩癪癧癬癰癲癶癸發皀皃皈皋皎皖皓皙皚皰皴皸皹皺盂盍盖盒盞盡盥盧盪蘯盻眈眇眄眩眤眞眥眦眛眷眸睇睚睨睫睛睥睿睾睹瞎瞋瞑瞠瞞瞰瞶瞹瞿瞼瞽瞻矇矍矗矚矜矣矮矼砌砒礦砠礪硅碎硴碆硼碚碌碣碵碪碯磑磆磋磔碾碼磅磊磬"], +["e240","磧磚磽磴礇礒礑礙礬礫祀祠祗祟祚祕祓祺祿禊禝禧齋禪禮禳禹禺秉秕秧秬秡秣稈稍稘稙稠稟禀稱稻稾稷穃穗穉穡穢穩龝穰穹穽窈窗窕窘窖窩竈窰"], +["e280","窶竅竄窿邃竇竊竍竏竕竓站竚竝竡竢竦竭竰笂笏笊笆笳笘笙笞笵笨笶筐筺笄筍笋筌筅筵筥筴筧筰筱筬筮箝箘箟箍箜箚箋箒箏筝箙篋篁篌篏箴篆篝篩簑簔篦篥籠簀簇簓篳篷簗簍篶簣簧簪簟簷簫簽籌籃籔籏籀籐籘籟籤籖籥籬籵粃粐粤粭粢粫粡粨粳粲粱粮粹粽糀糅糂糘糒糜糢鬻糯糲糴糶糺紆"], +["e340","紂紜紕紊絅絋紮紲紿紵絆絳絖絎絲絨絮絏絣經綉絛綏絽綛綺綮綣綵緇綽綫總綢綯緜綸綟綰緘緝緤緞緻緲緡縅縊縣縡縒縱縟縉縋縢繆繦縻縵縹繃縷"], +["e380","縲縺繧繝繖繞繙繚繹繪繩繼繻纃緕繽辮繿纈纉續纒纐纓纔纖纎纛纜缸缺罅罌罍罎罐网罕罔罘罟罠罨罩罧罸羂羆羃羈羇羌羔羞羝羚羣羯羲羹羮羶羸譱翅翆翊翕翔翡翦翩翳翹飜耆耄耋耒耘耙耜耡耨耿耻聊聆聒聘聚聟聢聨聳聲聰聶聹聽聿肄肆肅肛肓肚肭冐肬胛胥胙胝胄胚胖脉胯胱脛脩脣脯腋"], +["e440","隋腆脾腓腑胼腱腮腥腦腴膃膈膊膀膂膠膕膤膣腟膓膩膰膵膾膸膽臀臂膺臉臍臑臙臘臈臚臟臠臧臺臻臾舁舂舅與舊舍舐舖舩舫舸舳艀艙艘艝艚艟艤"], +["e480","艢艨艪艫舮艱艷艸艾芍芒芫芟芻芬苡苣苟苒苴苳苺莓范苻苹苞茆苜茉苙茵茴茖茲茱荀茹荐荅茯茫茗茘莅莚莪莟莢莖茣莎莇莊荼莵荳荵莠莉莨菴萓菫菎菽萃菘萋菁菷萇菠菲萍萢萠莽萸蔆菻葭萪萼蕚蒄葷葫蒭葮蒂葩葆萬葯葹萵蓊葢蒹蒿蒟蓙蓍蒻蓚蓐蓁蓆蓖蒡蔡蓿蓴蔗蔘蔬蔟蔕蔔蓼蕀蕣蕘蕈"], +["e540","蕁蘂蕋蕕薀薤薈薑薊薨蕭薔薛藪薇薜蕷蕾薐藉薺藏薹藐藕藝藥藜藹蘊蘓蘋藾藺蘆蘢蘚蘰蘿虍乕虔號虧虱蚓蚣蚩蚪蚋蚌蚶蚯蛄蛆蚰蛉蠣蚫蛔蛞蛩蛬"], +["e580","蛟蛛蛯蜒蜆蜈蜀蜃蛻蜑蜉蜍蛹蜊蜴蜿蜷蜻蜥蜩蜚蝠蝟蝸蝌蝎蝴蝗蝨蝮蝙蝓蝣蝪蠅螢螟螂螯蟋螽蟀蟐雖螫蟄螳蟇蟆螻蟯蟲蟠蠏蠍蟾蟶蟷蠎蟒蠑蠖蠕蠢蠡蠱蠶蠹蠧蠻衄衂衒衙衞衢衫袁衾袞衵衽袵衲袂袗袒袮袙袢袍袤袰袿袱裃裄裔裘裙裝裹褂裼裴裨裲褄褌褊褓襃褞褥褪褫襁襄褻褶褸襌褝襠襞"], +["e640","襦襤襭襪襯襴襷襾覃覈覊覓覘覡覩覦覬覯覲覺覽覿觀觚觜觝觧觴觸訃訖訐訌訛訝訥訶詁詛詒詆詈詼詭詬詢誅誂誄誨誡誑誥誦誚誣諄諍諂諚諫諳諧"], +["e680","諤諱謔諠諢諷諞諛謌謇謚諡謖謐謗謠謳鞫謦謫謾謨譁譌譏譎證譖譛譚譫譟譬譯譴譽讀讌讎讒讓讖讙讚谺豁谿豈豌豎豐豕豢豬豸豺貂貉貅貊貍貎貔豼貘戝貭貪貽貲貳貮貶賈賁賤賣賚賽賺賻贄贅贊贇贏贍贐齎贓賍贔贖赧赭赱赳趁趙跂趾趺跏跚跖跌跛跋跪跫跟跣跼踈踉跿踝踞踐踟蹂踵踰踴蹊"], +["e740","蹇蹉蹌蹐蹈蹙蹤蹠踪蹣蹕蹶蹲蹼躁躇躅躄躋躊躓躑躔躙躪躡躬躰軆躱躾軅軈軋軛軣軼軻軫軾輊輅輕輒輙輓輜輟輛輌輦輳輻輹轅轂輾轌轉轆轎轗轜"], +["e780","轢轣轤辜辟辣辭辯辷迚迥迢迪迯邇迴逅迹迺逑逕逡逍逞逖逋逧逶逵逹迸遏遐遑遒逎遉逾遖遘遞遨遯遶隨遲邂遽邁邀邊邉邏邨邯邱邵郢郤扈郛鄂鄒鄙鄲鄰酊酖酘酣酥酩酳酲醋醉醂醢醫醯醪醵醴醺釀釁釉釋釐釖釟釡釛釼釵釶鈞釿鈔鈬鈕鈑鉞鉗鉅鉉鉤鉈銕鈿鉋鉐銜銖銓銛鉚鋏銹銷鋩錏鋺鍄錮"], +["e840","錙錢錚錣錺錵錻鍜鍠鍼鍮鍖鎰鎬鎭鎔鎹鏖鏗鏨鏥鏘鏃鏝鏐鏈鏤鐚鐔鐓鐃鐇鐐鐶鐫鐵鐡鐺鑁鑒鑄鑛鑠鑢鑞鑪鈩鑰鑵鑷鑽鑚鑼鑾钁鑿閂閇閊閔閖閘閙"], +["e880","閠閨閧閭閼閻閹閾闊濶闃闍闌闕闔闖關闡闥闢阡阨阮阯陂陌陏陋陷陜陞陝陟陦陲陬隍隘隕隗險隧隱隲隰隴隶隸隹雎雋雉雍襍雜霍雕雹霄霆霈霓霎霑霏霖霙霤霪霰霹霽霾靄靆靈靂靉靜靠靤靦靨勒靫靱靹鞅靼鞁靺鞆鞋鞏鞐鞜鞨鞦鞣鞳鞴韃韆韈韋韜韭齏韲竟韶韵頏頌頸頤頡頷頽顆顏顋顫顯顰"], +["e940","顱顴顳颪颯颱颶飄飃飆飩飫餃餉餒餔餘餡餝餞餤餠餬餮餽餾饂饉饅饐饋饑饒饌饕馗馘馥馭馮馼駟駛駝駘駑駭駮駱駲駻駸騁騏騅駢騙騫騷驅驂驀驃"], +["e980","騾驕驍驛驗驟驢驥驤驩驫驪骭骰骼髀髏髑髓體髞髟髢髣髦髯髫髮髴髱髷髻鬆鬘鬚鬟鬢鬣鬥鬧鬨鬩鬪鬮鬯鬲魄魃魏魍魎魑魘魴鮓鮃鮑鮖鮗鮟鮠鮨鮴鯀鯊鮹鯆鯏鯑鯒鯣鯢鯤鯔鯡鰺鯲鯱鯰鰕鰔鰉鰓鰌鰆鰈鰒鰊鰄鰮鰛鰥鰤鰡鰰鱇鰲鱆鰾鱚鱠鱧鱶鱸鳧鳬鳰鴉鴈鳫鴃鴆鴪鴦鶯鴣鴟鵄鴕鴒鵁鴿鴾鵆鵈"], +["ea40","鵝鵞鵤鵑鵐鵙鵲鶉鶇鶫鵯鵺鶚鶤鶩鶲鷄鷁鶻鶸鶺鷆鷏鷂鷙鷓鷸鷦鷭鷯鷽鸚鸛鸞鹵鹹鹽麁麈麋麌麒麕麑麝麥麩麸麪麭靡黌黎黏黐黔黜點黝黠黥黨黯"], +["ea80","黴黶黷黹黻黼黽鼇鼈皷鼕鼡鼬鼾齊齒齔齣齟齠齡齦齧齬齪齷齲齶龕龜龠堯槇遙瑤凜熙"], +["ed40","纊褜鍈銈蓜俉炻昱棈鋹曻彅丨仡仼伀伃伹佖侒侊侚侔俍偀倢俿倞偆偰偂傔僴僘兊兤冝冾凬刕劜劦勀勛匀匇匤卲厓厲叝﨎咜咊咩哿喆坙坥垬埈埇﨏"], +["ed80","塚增墲夋奓奛奝奣妤妺孖寀甯寘寬尞岦岺峵崧嵓﨑嵂嵭嶸嶹巐弡弴彧德忞恝悅悊惞惕愠惲愑愷愰憘戓抦揵摠撝擎敎昀昕昻昉昮昞昤晥晗晙晴晳暙暠暲暿曺朎朗杦枻桒柀栁桄棏﨓楨﨔榘槢樰橫橆橳橾櫢櫤毖氿汜沆汯泚洄涇浯涖涬淏淸淲淼渹湜渧渼溿澈澵濵瀅瀇瀨炅炫焏焄煜煆煇凞燁燾犱"], +["ee40","犾猤猪獷玽珉珖珣珒琇珵琦琪琩琮瑢璉璟甁畯皂皜皞皛皦益睆劯砡硎硤硺礰礼神祥禔福禛竑竧靖竫箞精絈絜綷綠緖繒罇羡羽茁荢荿菇菶葈蒴蕓蕙"], +["ee80","蕫﨟薰蘒﨡蠇裵訒訷詹誧誾諟諸諶譓譿賰賴贒赶﨣軏﨤逸遧郞都鄕鄧釚釗釞釭釮釤釥鈆鈐鈊鈺鉀鈼鉎鉙鉑鈹鉧銧鉷鉸鋧鋗鋙鋐﨧鋕鋠鋓錥錡鋻﨨錞鋿錝錂鍰鍗鎤鏆鏞鏸鐱鑅鑈閒隆﨩隝隯霳霻靃靍靏靑靕顗顥飯飼餧館馞驎髙髜魵魲鮏鮱鮻鰀鵰鵫鶴鸙黑"], +["eeef","ⅰ",9,"¬¦'""], +["f040","",62], +["f080","",124], +["f140","",62], +["f180","",124], +["f240","",62], +["f280","",124], +["f340","",62], +["f380","",124], +["f440","",62], +["f480","",124], +["f540","",62], +["f580","",124], +["f640","",62], +["f680","",124], +["f740","",62], +["f780","",124], +["f840","",62], +["f880","",124], +["f940",""], +["fa40","ⅰ",9,"Ⅰ",9,"¬¦'"㈱№℡∵纊褜鍈銈蓜俉炻昱棈鋹曻彅丨仡仼伀伃伹佖侒侊侚侔俍偀倢俿倞偆偰偂傔僴僘兊"], +["fa80","兤冝冾凬刕劜劦勀勛匀匇匤卲厓厲叝﨎咜咊咩哿喆坙坥垬埈埇﨏塚增墲夋奓奛奝奣妤妺孖寀甯寘寬尞岦岺峵崧嵓﨑嵂嵭嶸嶹巐弡弴彧德忞恝悅悊惞惕愠惲愑愷愰憘戓抦揵摠撝擎敎昀昕昻昉昮昞昤晥晗晙晴晳暙暠暲暿曺朎朗杦枻桒柀栁桄棏﨓楨﨔榘槢樰橫橆橳橾櫢櫤毖氿汜沆汯泚洄涇浯"], +["fb40","涖涬淏淸淲淼渹湜渧渼溿澈澵濵瀅瀇瀨炅炫焏焄煜煆煇凞燁燾犱犾猤猪獷玽珉珖珣珒琇珵琦琪琩琮瑢璉璟甁畯皂皜皞皛皦益睆劯砡硎硤硺礰礼神"], +["fb80","祥禔福禛竑竧靖竫箞精絈絜綷綠緖繒罇羡羽茁荢荿菇菶葈蒴蕓蕙蕫﨟薰蘒﨡蠇裵訒訷詹誧誾諟諸諶譓譿賰賴贒赶﨣軏﨤逸遧郞都鄕鄧釚釗釞釭釮釤釥鈆鈐鈊鈺鉀鈼鉎鉙鉑鈹鉧銧鉷鉸鋧鋗鋙鋐﨧鋕鋠鋓錥錡鋻﨨錞鋿錝錂鍰鍗鎤鏆鏞鏸鐱鑅鑈閒隆﨩隝隯霳霻靃靍靏靑靕顗顥飯飼餧館馞驎髙"], +["fc40","髜魵魲鮏鮱鮻鰀鵰鵫鶴鸙黑"] +] diff --git a/backend/node_modules/iconv-lite/encodings/utf16.js b/backend/node_modules/iconv-lite/encodings/utf16.js new file mode 100644 index 0000000000000000000000000000000000000000..54765aeee2f11ec423c0b719cd424bed876d6402 --- /dev/null +++ b/backend/node_modules/iconv-lite/encodings/utf16.js @@ -0,0 +1,177 @@ +"use strict"; +var Buffer = require("safer-buffer").Buffer; + +// Note: UTF16-LE (or UCS2) codec is Node.js native. See encodings/internal.js + +// == UTF16-BE codec. ========================================================== + +exports.utf16be = Utf16BECodec; +function Utf16BECodec() { +} + +Utf16BECodec.prototype.encoder = Utf16BEEncoder; +Utf16BECodec.prototype.decoder = Utf16BEDecoder; +Utf16BECodec.prototype.bomAware = true; + + +// -- Encoding + +function Utf16BEEncoder() { +} + +Utf16BEEncoder.prototype.write = function(str) { + var buf = Buffer.from(str, 'ucs2'); + for (var i = 0; i < buf.length; i += 2) { + var tmp = buf[i]; buf[i] = buf[i+1]; buf[i+1] = tmp; + } + return buf; +} + +Utf16BEEncoder.prototype.end = function() { +} + + +// -- Decoding + +function Utf16BEDecoder() { + this.overflowByte = -1; +} + +Utf16BEDecoder.prototype.write = function(buf) { + if (buf.length == 0) + return ''; + + var buf2 = Buffer.alloc(buf.length + 1), + i = 0, j = 0; + + if (this.overflowByte !== -1) { + buf2[0] = buf[0]; + buf2[1] = this.overflowByte; + i = 1; j = 2; + } + + for (; i < buf.length-1; i += 2, j+= 2) { + buf2[j] = buf[i+1]; + buf2[j+1] = buf[i]; + } + + this.overflowByte = (i == buf.length-1) ? buf[buf.length-1] : -1; + + return buf2.slice(0, j).toString('ucs2'); +} + +Utf16BEDecoder.prototype.end = function() { +} + + +// == UTF-16 codec ============================================================= +// Decoder chooses automatically from UTF-16LE and UTF-16BE using BOM and space-based heuristic. +// Defaults to UTF-16LE, as it's prevalent and default in Node. +// http://en.wikipedia.org/wiki/UTF-16 and http://encoding.spec.whatwg.org/#utf-16le +// Decoder default can be changed: iconv.decode(buf, 'utf16', {defaultEncoding: 'utf-16be'}); + +// Encoder uses UTF-16LE and prepends BOM (which can be overridden with addBOM: false). + +exports.utf16 = Utf16Codec; +function Utf16Codec(codecOptions, iconv) { + this.iconv = iconv; +} + +Utf16Codec.prototype.encoder = Utf16Encoder; +Utf16Codec.prototype.decoder = Utf16Decoder; + + +// -- Encoding (pass-through) + +function Utf16Encoder(options, codec) { + options = options || {}; + if (options.addBOM === undefined) + options.addBOM = true; + this.encoder = codec.iconv.getEncoder('utf-16le', options); +} + +Utf16Encoder.prototype.write = function(str) { + return this.encoder.write(str); +} + +Utf16Encoder.prototype.end = function() { + return this.encoder.end(); +} + + +// -- Decoding + +function Utf16Decoder(options, codec) { + this.decoder = null; + this.initialBytes = []; + this.initialBytesLen = 0; + + this.options = options || {}; + this.iconv = codec.iconv; +} + +Utf16Decoder.prototype.write = function(buf) { + if (!this.decoder) { + // Codec is not chosen yet. Accumulate initial bytes. + this.initialBytes.push(buf); + this.initialBytesLen += buf.length; + + if (this.initialBytesLen < 16) // We need more bytes to use space heuristic (see below) + return ''; + + // We have enough bytes -> detect endianness. + var buf = Buffer.concat(this.initialBytes), + encoding = detectEncoding(buf, this.options.defaultEncoding); + this.decoder = this.iconv.getDecoder(encoding, this.options); + this.initialBytes.length = this.initialBytesLen = 0; + } + + return this.decoder.write(buf); +} + +Utf16Decoder.prototype.end = function() { + if (!this.decoder) { + var buf = Buffer.concat(this.initialBytes), + encoding = detectEncoding(buf, this.options.defaultEncoding); + this.decoder = this.iconv.getDecoder(encoding, this.options); + + var res = this.decoder.write(buf), + trail = this.decoder.end(); + + return trail ? (res + trail) : res; + } + return this.decoder.end(); +} + +function detectEncoding(buf, defaultEncoding) { + var enc = defaultEncoding || 'utf-16le'; + + if (buf.length >= 2) { + // Check BOM. + if (buf[0] == 0xFE && buf[1] == 0xFF) // UTF-16BE BOM + enc = 'utf-16be'; + else if (buf[0] == 0xFF && buf[1] == 0xFE) // UTF-16LE BOM + enc = 'utf-16le'; + else { + // No BOM found. Try to deduce encoding from initial content. + // Most of the time, the content has ASCII chars (U+00**), but the opposite (U+**00) is uncommon. + // So, we count ASCII as if it was LE or BE, and decide from that. + var asciiCharsLE = 0, asciiCharsBE = 0, // Counts of chars in both positions + _len = Math.min(buf.length - (buf.length % 2), 64); // Len is always even. + + for (var i = 0; i < _len; i += 2) { + if (buf[i] === 0 && buf[i+1] !== 0) asciiCharsBE++; + if (buf[i] !== 0 && buf[i+1] === 0) asciiCharsLE++; + } + + if (asciiCharsBE > asciiCharsLE) + enc = 'utf-16be'; + else if (asciiCharsBE < asciiCharsLE) + enc = 'utf-16le'; + } + } + + return enc; +} + + diff --git a/backend/node_modules/iconv-lite/encodings/utf7.js b/backend/node_modules/iconv-lite/encodings/utf7.js new file mode 100644 index 0000000000000000000000000000000000000000..b7631c23a801b0275c1f12a9d1a8fe00d8f51f0c --- /dev/null +++ b/backend/node_modules/iconv-lite/encodings/utf7.js @@ -0,0 +1,290 @@ +"use strict"; +var Buffer = require("safer-buffer").Buffer; + +// UTF-7 codec, according to https://tools.ietf.org/html/rfc2152 +// See also below a UTF-7-IMAP codec, according to http://tools.ietf.org/html/rfc3501#section-5.1.3 + +exports.utf7 = Utf7Codec; +exports.unicode11utf7 = 'utf7'; // Alias UNICODE-1-1-UTF-7 +function Utf7Codec(codecOptions, iconv) { + this.iconv = iconv; +}; + +Utf7Codec.prototype.encoder = Utf7Encoder; +Utf7Codec.prototype.decoder = Utf7Decoder; +Utf7Codec.prototype.bomAware = true; + + +// -- Encoding + +var nonDirectChars = /[^A-Za-z0-9'\(\),-\.\/:\? \n\r\t]+/g; + +function Utf7Encoder(options, codec) { + this.iconv = codec.iconv; +} + +Utf7Encoder.prototype.write = function(str) { + // Naive implementation. + // Non-direct chars are encoded as "+-"; single "+" char is encoded as "+-". + return Buffer.from(str.replace(nonDirectChars, function(chunk) { + return "+" + (chunk === '+' ? '' : + this.iconv.encode(chunk, 'utf16-be').toString('base64').replace(/=+$/, '')) + + "-"; + }.bind(this))); +} + +Utf7Encoder.prototype.end = function() { +} + + +// -- Decoding + +function Utf7Decoder(options, codec) { + this.iconv = codec.iconv; + this.inBase64 = false; + this.base64Accum = ''; +} + +var base64Regex = /[A-Za-z0-9\/+]/; +var base64Chars = []; +for (var i = 0; i < 256; i++) + base64Chars[i] = base64Regex.test(String.fromCharCode(i)); + +var plusChar = '+'.charCodeAt(0), + minusChar = '-'.charCodeAt(0), + andChar = '&'.charCodeAt(0); + +Utf7Decoder.prototype.write = function(buf) { + var res = "", lastI = 0, + inBase64 = this.inBase64, + base64Accum = this.base64Accum; + + // The decoder is more involved as we must handle chunks in stream. + + for (var i = 0; i < buf.length; i++) { + if (!inBase64) { // We're in direct mode. + // Write direct chars until '+' + if (buf[i] == plusChar) { + res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars. + lastI = i+1; + inBase64 = true; + } + } else { // We decode base64. + if (!base64Chars[buf[i]]) { // Base64 ended. + if (i == lastI && buf[i] == minusChar) {// "+-" -> "+" + res += "+"; + } else { + var b64str = base64Accum + buf.slice(lastI, i).toString(); + res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); + } + + if (buf[i] != minusChar) // Minus is absorbed after base64. + i--; + + lastI = i+1; + inBase64 = false; + base64Accum = ''; + } + } + } + + if (!inBase64) { + res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars. + } else { + var b64str = base64Accum + buf.slice(lastI).toString(); + + var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars. + base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future. + b64str = b64str.slice(0, canBeDecoded); + + res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); + } + + this.inBase64 = inBase64; + this.base64Accum = base64Accum; + + return res; +} + +Utf7Decoder.prototype.end = function() { + var res = ""; + if (this.inBase64 && this.base64Accum.length > 0) + res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be"); + + this.inBase64 = false; + this.base64Accum = ''; + return res; +} + + +// UTF-7-IMAP codec. +// RFC3501 Sec. 5.1.3 Modified UTF-7 (http://tools.ietf.org/html/rfc3501#section-5.1.3) +// Differences: +// * Base64 part is started by "&" instead of "+" +// * Direct characters are 0x20-0x7E, except "&" (0x26) +// * In Base64, "," is used instead of "/" +// * Base64 must not be used to represent direct characters. +// * No implicit shift back from Base64 (should always end with '-') +// * String must end in non-shifted position. +// * "-&" while in base64 is not allowed. + + +exports.utf7imap = Utf7IMAPCodec; +function Utf7IMAPCodec(codecOptions, iconv) { + this.iconv = iconv; +}; + +Utf7IMAPCodec.prototype.encoder = Utf7IMAPEncoder; +Utf7IMAPCodec.prototype.decoder = Utf7IMAPDecoder; +Utf7IMAPCodec.prototype.bomAware = true; + + +// -- Encoding + +function Utf7IMAPEncoder(options, codec) { + this.iconv = codec.iconv; + this.inBase64 = false; + this.base64Accum = Buffer.alloc(6); + this.base64AccumIdx = 0; +} + +Utf7IMAPEncoder.prototype.write = function(str) { + var inBase64 = this.inBase64, + base64Accum = this.base64Accum, + base64AccumIdx = this.base64AccumIdx, + buf = Buffer.alloc(str.length*5 + 10), bufIdx = 0; + + for (var i = 0; i < str.length; i++) { + var uChar = str.charCodeAt(i); + if (0x20 <= uChar && uChar <= 0x7E) { // Direct character or '&'. + if (inBase64) { + if (base64AccumIdx > 0) { + bufIdx += buf.write(base64Accum.slice(0, base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx); + base64AccumIdx = 0; + } + + buf[bufIdx++] = minusChar; // Write '-', then go to direct mode. + inBase64 = false; + } + + if (!inBase64) { + buf[bufIdx++] = uChar; // Write direct character + + if (uChar === andChar) // Ampersand -> '&-' + buf[bufIdx++] = minusChar; + } + + } else { // Non-direct character + if (!inBase64) { + buf[bufIdx++] = andChar; // Write '&', then go to base64 mode. + inBase64 = true; + } + if (inBase64) { + base64Accum[base64AccumIdx++] = uChar >> 8; + base64Accum[base64AccumIdx++] = uChar & 0xFF; + + if (base64AccumIdx == base64Accum.length) { + bufIdx += buf.write(base64Accum.toString('base64').replace(/\//g, ','), bufIdx); + base64AccumIdx = 0; + } + } + } + } + + this.inBase64 = inBase64; + this.base64AccumIdx = base64AccumIdx; + + return buf.slice(0, bufIdx); +} + +Utf7IMAPEncoder.prototype.end = function() { + var buf = Buffer.alloc(10), bufIdx = 0; + if (this.inBase64) { + if (this.base64AccumIdx > 0) { + bufIdx += buf.write(this.base64Accum.slice(0, this.base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx); + this.base64AccumIdx = 0; + } + + buf[bufIdx++] = minusChar; // Write '-', then go to direct mode. + this.inBase64 = false; + } + + return buf.slice(0, bufIdx); +} + + +// -- Decoding + +function Utf7IMAPDecoder(options, codec) { + this.iconv = codec.iconv; + this.inBase64 = false; + this.base64Accum = ''; +} + +var base64IMAPChars = base64Chars.slice(); +base64IMAPChars[','.charCodeAt(0)] = true; + +Utf7IMAPDecoder.prototype.write = function(buf) { + var res = "", lastI = 0, + inBase64 = this.inBase64, + base64Accum = this.base64Accum; + + // The decoder is more involved as we must handle chunks in stream. + // It is forgiving, closer to standard UTF-7 (for example, '-' is optional at the end). + + for (var i = 0; i < buf.length; i++) { + if (!inBase64) { // We're in direct mode. + // Write direct chars until '&' + if (buf[i] == andChar) { + res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars. + lastI = i+1; + inBase64 = true; + } + } else { // We decode base64. + if (!base64IMAPChars[buf[i]]) { // Base64 ended. + if (i == lastI && buf[i] == minusChar) { // "&-" -> "&" + res += "&"; + } else { + var b64str = base64Accum + buf.slice(lastI, i).toString().replace(/,/g, '/'); + res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); + } + + if (buf[i] != minusChar) // Minus may be absorbed after base64. + i--; + + lastI = i+1; + inBase64 = false; + base64Accum = ''; + } + } + } + + if (!inBase64) { + res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars. + } else { + var b64str = base64Accum + buf.slice(lastI).toString().replace(/,/g, '/'); + + var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars. + base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future. + b64str = b64str.slice(0, canBeDecoded); + + res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); + } + + this.inBase64 = inBase64; + this.base64Accum = base64Accum; + + return res; +} + +Utf7IMAPDecoder.prototype.end = function() { + var res = ""; + if (this.inBase64 && this.base64Accum.length > 0) + res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be"); + + this.inBase64 = false; + this.base64Accum = ''; + return res; +} + + diff --git a/backend/node_modules/iconv-lite/lib/bom-handling.js b/backend/node_modules/iconv-lite/lib/bom-handling.js new file mode 100644 index 0000000000000000000000000000000000000000..1050872385c7f96b4f54d50ebc873b1031e2528c --- /dev/null +++ b/backend/node_modules/iconv-lite/lib/bom-handling.js @@ -0,0 +1,52 @@ +"use strict"; + +var BOMChar = '\uFEFF'; + +exports.PrependBOM = PrependBOMWrapper +function PrependBOMWrapper(encoder, options) { + this.encoder = encoder; + this.addBOM = true; +} + +PrependBOMWrapper.prototype.write = function(str) { + if (this.addBOM) { + str = BOMChar + str; + this.addBOM = false; + } + + return this.encoder.write(str); +} + +PrependBOMWrapper.prototype.end = function() { + return this.encoder.end(); +} + + +//------------------------------------------------------------------------------ + +exports.StripBOM = StripBOMWrapper; +function StripBOMWrapper(decoder, options) { + this.decoder = decoder; + this.pass = false; + this.options = options || {}; +} + +StripBOMWrapper.prototype.write = function(buf) { + var res = this.decoder.write(buf); + if (this.pass || !res) + return res; + + if (res[0] === BOMChar) { + res = res.slice(1); + if (typeof this.options.stripBOM === 'function') + this.options.stripBOM(); + } + + this.pass = true; + return res; +} + +StripBOMWrapper.prototype.end = function() { + return this.decoder.end(); +} + diff --git a/backend/node_modules/iconv-lite/lib/extend-node.js b/backend/node_modules/iconv-lite/lib/extend-node.js new file mode 100644 index 0000000000000000000000000000000000000000..87f5394a4b3966eca00c9a01a2ef0b2f2f27f5c6 --- /dev/null +++ b/backend/node_modules/iconv-lite/lib/extend-node.js @@ -0,0 +1,217 @@ +"use strict"; +var Buffer = require("buffer").Buffer; +// Note: not polyfilled with safer-buffer on a purpose, as overrides Buffer + +// == Extend Node primitives to use iconv-lite ================================= + +module.exports = function (iconv) { + var original = undefined; // Place to keep original methods. + + // Node authors rewrote Buffer internals to make it compatible with + // Uint8Array and we cannot patch key functions since then. + // Note: this does use older Buffer API on a purpose + iconv.supportsNodeEncodingsExtension = !(Buffer.from || new Buffer(0) instanceof Uint8Array); + + iconv.extendNodeEncodings = function extendNodeEncodings() { + if (original) return; + original = {}; + + if (!iconv.supportsNodeEncodingsExtension) { + console.error("ACTION NEEDED: require('iconv-lite').extendNodeEncodings() is not supported in your version of Node"); + console.error("See more info at https://github.com/ashtuchkin/iconv-lite/wiki/Node-v4-compatibility"); + return; + } + + var nodeNativeEncodings = { + 'hex': true, 'utf8': true, 'utf-8': true, 'ascii': true, 'binary': true, + 'base64': true, 'ucs2': true, 'ucs-2': true, 'utf16le': true, 'utf-16le': true, + }; + + Buffer.isNativeEncoding = function(enc) { + return enc && nodeNativeEncodings[enc.toLowerCase()]; + } + + // -- SlowBuffer ----------------------------------------------------------- + var SlowBuffer = require('buffer').SlowBuffer; + + original.SlowBufferToString = SlowBuffer.prototype.toString; + SlowBuffer.prototype.toString = function(encoding, start, end) { + encoding = String(encoding || 'utf8').toLowerCase(); + + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.SlowBufferToString.call(this, encoding, start, end); + + // Otherwise, use our decoding method. + if (typeof start == 'undefined') start = 0; + if (typeof end == 'undefined') end = this.length; + return iconv.decode(this.slice(start, end), encoding); + } + + original.SlowBufferWrite = SlowBuffer.prototype.write; + SlowBuffer.prototype.write = function(string, offset, length, encoding) { + // Support both (string, offset, length, encoding) + // and the legacy (string, encoding, offset, length) + if (isFinite(offset)) { + if (!isFinite(length)) { + encoding = length; + length = undefined; + } + } else { // legacy + var swap = encoding; + encoding = offset; + offset = length; + length = swap; + } + + offset = +offset || 0; + var remaining = this.length - offset; + if (!length) { + length = remaining; + } else { + length = +length; + if (length > remaining) { + length = remaining; + } + } + encoding = String(encoding || 'utf8').toLowerCase(); + + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.SlowBufferWrite.call(this, string, offset, length, encoding); + + if (string.length > 0 && (length < 0 || offset < 0)) + throw new RangeError('attempt to write beyond buffer bounds'); + + // Otherwise, use our encoding method. + var buf = iconv.encode(string, encoding); + if (buf.length < length) length = buf.length; + buf.copy(this, offset, 0, length); + return length; + } + + // -- Buffer --------------------------------------------------------------- + + original.BufferIsEncoding = Buffer.isEncoding; + Buffer.isEncoding = function(encoding) { + return Buffer.isNativeEncoding(encoding) || iconv.encodingExists(encoding); + } + + original.BufferByteLength = Buffer.byteLength; + Buffer.byteLength = SlowBuffer.byteLength = function(str, encoding) { + encoding = String(encoding || 'utf8').toLowerCase(); + + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.BufferByteLength.call(this, str, encoding); + + // Slow, I know, but we don't have a better way yet. + return iconv.encode(str, encoding).length; + } + + original.BufferToString = Buffer.prototype.toString; + Buffer.prototype.toString = function(encoding, start, end) { + encoding = String(encoding || 'utf8').toLowerCase(); + + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.BufferToString.call(this, encoding, start, end); + + // Otherwise, use our decoding method. + if (typeof start == 'undefined') start = 0; + if (typeof end == 'undefined') end = this.length; + return iconv.decode(this.slice(start, end), encoding); + } + + original.BufferWrite = Buffer.prototype.write; + Buffer.prototype.write = function(string, offset, length, encoding) { + var _offset = offset, _length = length, _encoding = encoding; + // Support both (string, offset, length, encoding) + // and the legacy (string, encoding, offset, length) + if (isFinite(offset)) { + if (!isFinite(length)) { + encoding = length; + length = undefined; + } + } else { // legacy + var swap = encoding; + encoding = offset; + offset = length; + length = swap; + } + + encoding = String(encoding || 'utf8').toLowerCase(); + + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.BufferWrite.call(this, string, _offset, _length, _encoding); + + offset = +offset || 0; + var remaining = this.length - offset; + if (!length) { + length = remaining; + } else { + length = +length; + if (length > remaining) { + length = remaining; + } + } + + if (string.length > 0 && (length < 0 || offset < 0)) + throw new RangeError('attempt to write beyond buffer bounds'); + + // Otherwise, use our encoding method. + var buf = iconv.encode(string, encoding); + if (buf.length < length) length = buf.length; + buf.copy(this, offset, 0, length); + return length; + + // TODO: Set _charsWritten. + } + + + // -- Readable ------------------------------------------------------------- + if (iconv.supportsStreams) { + var Readable = require('stream').Readable; + + original.ReadableSetEncoding = Readable.prototype.setEncoding; + Readable.prototype.setEncoding = function setEncoding(enc, options) { + // Use our own decoder, it has the same interface. + // We cannot use original function as it doesn't handle BOM-s. + this._readableState.decoder = iconv.getDecoder(enc, options); + this._readableState.encoding = enc; + } + + Readable.prototype.collect = iconv._collect; + } + } + + // Remove iconv-lite Node primitive extensions. + iconv.undoExtendNodeEncodings = function undoExtendNodeEncodings() { + if (!iconv.supportsNodeEncodingsExtension) + return; + if (!original) + throw new Error("require('iconv-lite').undoExtendNodeEncodings(): Nothing to undo; extendNodeEncodings() is not called.") + + delete Buffer.isNativeEncoding; + + var SlowBuffer = require('buffer').SlowBuffer; + + SlowBuffer.prototype.toString = original.SlowBufferToString; + SlowBuffer.prototype.write = original.SlowBufferWrite; + + Buffer.isEncoding = original.BufferIsEncoding; + Buffer.byteLength = original.BufferByteLength; + Buffer.prototype.toString = original.BufferToString; + Buffer.prototype.write = original.BufferWrite; + + if (iconv.supportsStreams) { + var Readable = require('stream').Readable; + + Readable.prototype.setEncoding = original.ReadableSetEncoding; + delete Readable.prototype.collect; + } + + original = undefined; + } +} diff --git a/backend/node_modules/iconv-lite/lib/index.d.ts b/backend/node_modules/iconv-lite/lib/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0547eb346b24f470e041bdf67e15f5861e6c8d14 --- /dev/null +++ b/backend/node_modules/iconv-lite/lib/index.d.ts @@ -0,0 +1,24 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + * REQUIREMENT: This definition is dependent on the @types/node definition. + * Install with `npm install @types/node --save-dev` + *--------------------------------------------------------------------------------------------*/ + +declare module 'iconv-lite' { + export function decode(buffer: Buffer, encoding: string, options?: Options): string; + + export function encode(content: string, encoding: string, options?: Options): Buffer; + + export function encodingExists(encoding: string): boolean; + + export function decodeStream(encoding: string, options?: Options): NodeJS.ReadWriteStream; + + export function encodeStream(encoding: string, options?: Options): NodeJS.ReadWriteStream; +} + +export interface Options { + stripBOM?: boolean; + addBOM?: boolean; + defaultEncoding?: string; +} diff --git a/backend/node_modules/iconv-lite/lib/index.js b/backend/node_modules/iconv-lite/lib/index.js new file mode 100644 index 0000000000000000000000000000000000000000..5391919ca2c6314bdd7c246e4d00ae1cec42c98d --- /dev/null +++ b/backend/node_modules/iconv-lite/lib/index.js @@ -0,0 +1,153 @@ +"use strict"; + +// Some environments don't have global Buffer (e.g. React Native). +// Solution would be installing npm modules "buffer" and "stream" explicitly. +var Buffer = require("safer-buffer").Buffer; + +var bomHandling = require("./bom-handling"), + iconv = module.exports; + +// All codecs and aliases are kept here, keyed by encoding name/alias. +// They are lazy loaded in `iconv.getCodec` from `encodings/index.js`. +iconv.encodings = null; + +// Characters emitted in case of error. +iconv.defaultCharUnicode = '�'; +iconv.defaultCharSingleByte = '?'; + +// Public API. +iconv.encode = function encode(str, encoding, options) { + str = "" + (str || ""); // Ensure string. + + var encoder = iconv.getEncoder(encoding, options); + + var res = encoder.write(str); + var trail = encoder.end(); + + return (trail && trail.length > 0) ? Buffer.concat([res, trail]) : res; +} + +iconv.decode = function decode(buf, encoding, options) { + if (typeof buf === 'string') { + if (!iconv.skipDecodeWarning) { + console.error('Iconv-lite warning: decode()-ing strings is deprecated. Refer to https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding'); + iconv.skipDecodeWarning = true; + } + + buf = Buffer.from("" + (buf || ""), "binary"); // Ensure buffer. + } + + var decoder = iconv.getDecoder(encoding, options); + + var res = decoder.write(buf); + var trail = decoder.end(); + + return trail ? (res + trail) : res; +} + +iconv.encodingExists = function encodingExists(enc) { + try { + iconv.getCodec(enc); + return true; + } catch (e) { + return false; + } +} + +// Legacy aliases to convert functions +iconv.toEncoding = iconv.encode; +iconv.fromEncoding = iconv.decode; + +// Search for a codec in iconv.encodings. Cache codec data in iconv._codecDataCache. +iconv._codecDataCache = {}; +iconv.getCodec = function getCodec(encoding) { + if (!iconv.encodings) + iconv.encodings = require("../encodings"); // Lazy load all encoding definitions. + + // Canonicalize encoding name: strip all non-alphanumeric chars and appended year. + var enc = iconv._canonicalizeEncoding(encoding); + + // Traverse iconv.encodings to find actual codec. + var codecOptions = {}; + while (true) { + var codec = iconv._codecDataCache[enc]; + if (codec) + return codec; + + var codecDef = iconv.encodings[enc]; + + switch (typeof codecDef) { + case "string": // Direct alias to other encoding. + enc = codecDef; + break; + + case "object": // Alias with options. Can be layered. + for (var key in codecDef) + codecOptions[key] = codecDef[key]; + + if (!codecOptions.encodingName) + codecOptions.encodingName = enc; + + enc = codecDef.type; + break; + + case "function": // Codec itself. + if (!codecOptions.encodingName) + codecOptions.encodingName = enc; + + // The codec function must load all tables and return object with .encoder and .decoder methods. + // It'll be called only once (for each different options object). + codec = new codecDef(codecOptions, iconv); + + iconv._codecDataCache[codecOptions.encodingName] = codec; // Save it to be reused later. + return codec; + + default: + throw new Error("Encoding not recognized: '" + encoding + "' (searched as: '"+enc+"')"); + } + } +} + +iconv._canonicalizeEncoding = function(encoding) { + // Canonicalize encoding name: strip all non-alphanumeric chars and appended year. + return (''+encoding).toLowerCase().replace(/:\d{4}$|[^0-9a-z]/g, ""); +} + +iconv.getEncoder = function getEncoder(encoding, options) { + var codec = iconv.getCodec(encoding), + encoder = new codec.encoder(options, codec); + + if (codec.bomAware && options && options.addBOM) + encoder = new bomHandling.PrependBOM(encoder, options); + + return encoder; +} + +iconv.getDecoder = function getDecoder(encoding, options) { + var codec = iconv.getCodec(encoding), + decoder = new codec.decoder(options, codec); + + if (codec.bomAware && !(options && options.stripBOM === false)) + decoder = new bomHandling.StripBOM(decoder, options); + + return decoder; +} + + +// Load extensions in Node. All of them are omitted in Browserify build via 'browser' field in package.json. +var nodeVer = typeof process !== 'undefined' && process.versions && process.versions.node; +if (nodeVer) { + + // Load streaming support in Node v0.10+ + var nodeVerArr = nodeVer.split(".").map(Number); + if (nodeVerArr[0] > 0 || nodeVerArr[1] >= 10) { + require("./streams")(iconv); + } + + // Load Node primitive extensions. + require("./extend-node")(iconv); +} + +if ("Ā" != "\u0100") { + console.error("iconv-lite warning: javascript files use encoding different from utf-8. See https://github.com/ashtuchkin/iconv-lite/wiki/Javascript-source-file-encodings for more info."); +} diff --git a/backend/node_modules/iconv-lite/lib/streams.js b/backend/node_modules/iconv-lite/lib/streams.js new file mode 100644 index 0000000000000000000000000000000000000000..4409552958edca1b2eb6b30742759ddf1bb5f3c8 --- /dev/null +++ b/backend/node_modules/iconv-lite/lib/streams.js @@ -0,0 +1,121 @@ +"use strict"; + +var Buffer = require("buffer").Buffer, + Transform = require("stream").Transform; + + +// == Exports ================================================================== +module.exports = function(iconv) { + + // Additional Public API. + iconv.encodeStream = function encodeStream(encoding, options) { + return new IconvLiteEncoderStream(iconv.getEncoder(encoding, options), options); + } + + iconv.decodeStream = function decodeStream(encoding, options) { + return new IconvLiteDecoderStream(iconv.getDecoder(encoding, options), options); + } + + iconv.supportsStreams = true; + + + // Not published yet. + iconv.IconvLiteEncoderStream = IconvLiteEncoderStream; + iconv.IconvLiteDecoderStream = IconvLiteDecoderStream; + iconv._collect = IconvLiteDecoderStream.prototype.collect; +}; + + +// == Encoder stream ======================================================= +function IconvLiteEncoderStream(conv, options) { + this.conv = conv; + options = options || {}; + options.decodeStrings = false; // We accept only strings, so we don't need to decode them. + Transform.call(this, options); +} + +IconvLiteEncoderStream.prototype = Object.create(Transform.prototype, { + constructor: { value: IconvLiteEncoderStream } +}); + +IconvLiteEncoderStream.prototype._transform = function(chunk, encoding, done) { + if (typeof chunk != 'string') + return done(new Error("Iconv encoding stream needs strings as its input.")); + try { + var res = this.conv.write(chunk); + if (res && res.length) this.push(res); + done(); + } + catch (e) { + done(e); + } +} + +IconvLiteEncoderStream.prototype._flush = function(done) { + try { + var res = this.conv.end(); + if (res && res.length) this.push(res); + done(); + } + catch (e) { + done(e); + } +} + +IconvLiteEncoderStream.prototype.collect = function(cb) { + var chunks = []; + this.on('error', cb); + this.on('data', function(chunk) { chunks.push(chunk); }); + this.on('end', function() { + cb(null, Buffer.concat(chunks)); + }); + return this; +} + + +// == Decoder stream ======================================================= +function IconvLiteDecoderStream(conv, options) { + this.conv = conv; + options = options || {}; + options.encoding = this.encoding = 'utf8'; // We output strings. + Transform.call(this, options); +} + +IconvLiteDecoderStream.prototype = Object.create(Transform.prototype, { + constructor: { value: IconvLiteDecoderStream } +}); + +IconvLiteDecoderStream.prototype._transform = function(chunk, encoding, done) { + if (!Buffer.isBuffer(chunk)) + return done(new Error("Iconv decoding stream needs buffers as its input.")); + try { + var res = this.conv.write(chunk); + if (res && res.length) this.push(res, this.encoding); + done(); + } + catch (e) { + done(e); + } +} + +IconvLiteDecoderStream.prototype._flush = function(done) { + try { + var res = this.conv.end(); + if (res && res.length) this.push(res, this.encoding); + done(); + } + catch (e) { + done(e); + } +} + +IconvLiteDecoderStream.prototype.collect = function(cb) { + var res = ''; + this.on('error', cb); + this.on('data', function(chunk) { res += chunk; }); + this.on('end', function() { + cb(null, res); + }); + return this; +} + diff --git a/backend/node_modules/iconv-lite/package.json b/backend/node_modules/iconv-lite/package.json new file mode 100644 index 0000000000000000000000000000000000000000..a7c74fcc299d744ce6cec7dc79023475d29f4673 --- /dev/null +++ b/backend/node_modules/iconv-lite/package.json @@ -0,0 +1,46 @@ +{ + "name": "iconv-lite", + "description": "Convert character encodings in pure javascript.", + "version": "0.4.24", + "license": "MIT", + "keywords": [ + "iconv", + "convert", + "charset", + "icu" + ], + "author": "Alexander Shtuchkin ", + "main": "./lib/index.js", + "typings": "./lib/index.d.ts", + "homepage": "https://github.com/ashtuchkin/iconv-lite", + "bugs": "https://github.com/ashtuchkin/iconv-lite/issues", + "repository": { + "type": "git", + "url": "git://github.com/ashtuchkin/iconv-lite.git" + }, + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "coverage": "istanbul cover _mocha -- --grep .", + "coverage-open": "open coverage/lcov-report/index.html", + "test": "mocha --reporter spec --grep ." + }, + "browser": { + "./lib/extend-node": false, + "./lib/streams": false + }, + "devDependencies": { + "mocha": "^3.1.0", + "request": "~2.87.0", + "unorm": "*", + "errto": "*", + "async": "*", + "istanbul": "*", + "semver": "*", + "iconv": "*" + }, + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3" + } +} diff --git a/backend/node_modules/inherits/LICENSE b/backend/node_modules/inherits/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..dea3013d6710ee273f49ac606a65d5211d480c88 --- /dev/null +++ b/backend/node_modules/inherits/LICENSE @@ -0,0 +1,16 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +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. + diff --git a/backend/node_modules/inherits/README.md b/backend/node_modules/inherits/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b1c56658557b8162aa9f5ba8610ed03a5e558d9d --- /dev/null +++ b/backend/node_modules/inherits/README.md @@ -0,0 +1,42 @@ +Browser-friendly inheritance fully compatible with standard node.js +[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor). + +This package exports standard `inherits` from node.js `util` module in +node environment, but also provides alternative browser-friendly +implementation through [browser +field](https://gist.github.com/shtylman/4339901). Alternative +implementation is a literal copy of standard one located in standalone +module to avoid requiring of `util`. It also has a shim for old +browsers with no `Object.create` support. + +While keeping you sure you are using standard `inherits` +implementation in node.js environment, it allows bundlers such as +[browserify](https://github.com/substack/node-browserify) to not +include full `util` package to your client code if all you need is +just `inherits` function. It worth, because browser shim for `util` +package is large and `inherits` is often the single function you need +from it. + +It's recommended to use this package instead of +`require('util').inherits` for any code that has chances to be used +not only in node.js but in browser too. + +## usage + +```js +var inherits = require('inherits'); +// then use exactly as the standard one +``` + +## note on version ~1.0 + +Version ~1.0 had completely different motivation and is not compatible +neither with 2.0 nor with standard node.js `inherits`. + +If you are using version ~1.0 and planning to switch to ~2.0, be +careful: + +* new version uses `super_` instead of `super` for referencing + superclass +* new version overwrites current prototype while old one preserves any + existing fields on it diff --git a/backend/node_modules/inherits/inherits.js b/backend/node_modules/inherits/inherits.js new file mode 100644 index 0000000000000000000000000000000000000000..f71f2d93294a67ad5d9300aae07973e259f26068 --- /dev/null +++ b/backend/node_modules/inherits/inherits.js @@ -0,0 +1,9 @@ +try { + var util = require('util'); + /* istanbul ignore next */ + if (typeof util.inherits !== 'function') throw ''; + module.exports = util.inherits; +} catch (e) { + /* istanbul ignore next */ + module.exports = require('./inherits_browser.js'); +} diff --git a/backend/node_modules/inherits/inherits_browser.js b/backend/node_modules/inherits/inherits_browser.js new file mode 100644 index 0000000000000000000000000000000000000000..86bbb3dc29e4847df14de2c2b4b168e065184643 --- /dev/null +++ b/backend/node_modules/inherits/inherits_browser.js @@ -0,0 +1,27 @@ +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }) + } + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } + } +} diff --git a/backend/node_modules/inherits/package.json b/backend/node_modules/inherits/package.json new file mode 100644 index 0000000000000000000000000000000000000000..37b4366b83e63e037cd447090ec25b39fce27e01 --- /dev/null +++ b/backend/node_modules/inherits/package.json @@ -0,0 +1,29 @@ +{ + "name": "inherits", + "description": "Browser-friendly inheritance fully compatible with standard node.js inherits()", + "version": "2.0.4", + "keywords": [ + "inheritance", + "class", + "klass", + "oop", + "object-oriented", + "inherits", + "browser", + "browserify" + ], + "main": "./inherits.js", + "browser": "./inherits_browser.js", + "repository": "git://github.com/isaacs/inherits", + "license": "ISC", + "scripts": { + "test": "tap" + }, + "devDependencies": { + "tap": "^14.2.4" + }, + "files": [ + "inherits.js", + "inherits_browser.js" + ] +} diff --git a/backend/node_modules/ipaddr.js/LICENSE b/backend/node_modules/ipaddr.js/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..f6b37b52dec6faa7f48b9d1be5da2ad9b883be2f --- /dev/null +++ b/backend/node_modules/ipaddr.js/LICENSE @@ -0,0 +1,19 @@ +Copyright (C) 2011-2017 whitequark + +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/backend/node_modules/ipaddr.js/README.md b/backend/node_modules/ipaddr.js/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f57725b0fed3b74b2ed13d99c0fe8ee65ab29f3c --- /dev/null +++ b/backend/node_modules/ipaddr.js/README.md @@ -0,0 +1,233 @@ +# ipaddr.js — an IPv6 and IPv4 address manipulation library [![Build Status](https://travis-ci.org/whitequark/ipaddr.js.svg)](https://travis-ci.org/whitequark/ipaddr.js) + +ipaddr.js is a small (1.9K minified and gzipped) library for manipulating +IP addresses in JavaScript environments. It runs on both CommonJS runtimes +(e.g. [nodejs]) and in a web browser. + +ipaddr.js allows you to verify and parse string representation of an IP +address, match it against a CIDR range or range list, determine if it falls +into some reserved ranges (examples include loopback and private ranges), +and convert between IPv4 and IPv4-mapped IPv6 addresses. + +[nodejs]: http://nodejs.org + +## Installation + +`npm install ipaddr.js` + +or + +`bower install ipaddr.js` + +## API + +ipaddr.js defines one object in the global scope: `ipaddr`. In CommonJS, +it is exported from the module: + +```js +var ipaddr = require('ipaddr.js'); +``` + +The API consists of several global methods and two classes: ipaddr.IPv6 and ipaddr.IPv4. + +### Global methods + +There are three global methods defined: `ipaddr.isValid`, `ipaddr.parse` and +`ipaddr.process`. All of them receive a string as a single parameter. + +The `ipaddr.isValid` method returns `true` if the address is a valid IPv4 or +IPv6 address, and `false` otherwise. It does not throw any exceptions. + +The `ipaddr.parse` method returns an object representing the IP address, +or throws an `Error` if the passed string is not a valid representation of an +IP address. + +The `ipaddr.process` method works just like the `ipaddr.parse` one, but it +automatically converts IPv4-mapped IPv6 addresses to their IPv4 counterparts +before returning. It is useful when you have a Node.js instance listening +on an IPv6 socket, and the `net.ivp6.bindv6only` sysctl parameter (or its +equivalent on non-Linux OS) is set to 0. In this case, you can accept IPv4 +connections on your IPv6-only socket, but the remote address will be mangled. +Use `ipaddr.process` method to automatically demangle it. + +### Object representation + +Parsing methods return an object which descends from `ipaddr.IPv6` or +`ipaddr.IPv4`. These objects share some properties, but most of them differ. + +#### Shared properties + +One can determine the type of address by calling `addr.kind()`. It will return +either `"ipv6"` or `"ipv4"`. + +An address can be converted back to its string representation with `addr.toString()`. +Note that this method: + * does not return the original string used to create the object (in fact, there is + no way of getting that string) + * returns a compact representation (when it is applicable) + +A `match(range, bits)` method can be used to check if the address falls into a +certain CIDR range. +Note that an address can be (obviously) matched only against an address of the same type. + +For example: + +```js +var addr = ipaddr.parse("2001:db8:1234::1"); +var range = ipaddr.parse("2001:db8::"); + +addr.match(range, 32); // => true +``` + +Alternatively, `match` can also be called as `match([range, bits])`. In this way, +it can be used together with the `parseCIDR(string)` method, which parses an IP +address together with a CIDR range. + +For example: + +```js +var addr = ipaddr.parse("2001:db8:1234::1"); + +addr.match(ipaddr.parseCIDR("2001:db8::/32")); // => true +``` + +A `range()` method returns one of predefined names for several special ranges defined +by IP protocols. The exact names (and their respective CIDR ranges) can be looked up +in the source: [IPv6 ranges] and [IPv4 ranges]. Some common ones include `"unicast"` +(the default one) and `"reserved"`. + +You can match against your own range list by using +`ipaddr.subnetMatch(address, rangeList, defaultName)` method. It can work with a mix of IPv6 or IPv4 addresses, and accepts a name-to-subnet map as the range list. For example: + +```js +var rangeList = { + documentationOnly: [ ipaddr.parse('2001:db8::'), 32 ], + tunnelProviders: [ + [ ipaddr.parse('2001:470::'), 32 ], // he.net + [ ipaddr.parse('2001:5c0::'), 32 ] // freenet6 + ] +}; +ipaddr.subnetMatch(ipaddr.parse('2001:470:8:66::1'), rangeList, 'unknown'); // => "tunnelProviders" +``` + +The addresses can be converted to their byte representation with `toByteArray()`. +(Actually, JavaScript mostly does not know about byte buffers. They are emulated with +arrays of numbers, each in range of 0..255.) + +```js +var bytes = ipaddr.parse('2a00:1450:8007::68').toByteArray(); // ipv6.google.com +bytes // => [42, 0x00, 0x14, 0x50, 0x80, 0x07, 0x00, , 0x00, 0x68 ] +``` + +The `ipaddr.IPv4` and `ipaddr.IPv6` objects have some methods defined, too. All of them +have the same interface for both protocols, and are similar to global methods. + +`ipaddr.IPvX.isValid(string)` can be used to check if the string is a valid address +for particular protocol, and `ipaddr.IPvX.parse(string)` is the error-throwing parser. + +`ipaddr.IPvX.isValid(string)` uses the same format for parsing as the POSIX `inet_ntoa` function, which accepts unusual formats like `0xc0.168.1.1` or `0x10000000`. The function `ipaddr.IPv4.isValidFourPartDecimal(string)` validates the IPv4 address and also ensures that it is written in four-part decimal format. + +[IPv6 ranges]: https://github.com/whitequark/ipaddr.js/blob/master/src/ipaddr.coffee#L186 +[IPv4 ranges]: https://github.com/whitequark/ipaddr.js/blob/master/src/ipaddr.coffee#L71 + +#### IPv6 properties + +Sometimes you will want to convert IPv6 not to a compact string representation (with +the `::` substitution); the `toNormalizedString()` method will return an address where +all zeroes are explicit. + +For example: + +```js +var addr = ipaddr.parse("2001:0db8::0001"); +addr.toString(); // => "2001:db8::1" +addr.toNormalizedString(); // => "2001:db8:0:0:0:0:0:1" +``` + +The `isIPv4MappedAddress()` method will return `true` if this address is an IPv4-mapped +one, and `toIPv4Address()` will return an IPv4 object address. + +To access the underlying binary representation of the address, use `addr.parts`. + +```js +var addr = ipaddr.parse("2001:db8:10::1234:DEAD"); +addr.parts // => [0x2001, 0xdb8, 0x10, 0, 0, 0, 0x1234, 0xdead] +``` + +A IPv6 zone index can be accessed via `addr.zoneId`: + +```js +var addr = ipaddr.parse("2001:db8::%eth0"); +addr.zoneId // => 'eth0' +``` + +#### IPv4 properties + +`toIPv4MappedAddress()` will return a corresponding IPv4-mapped IPv6 address. + +To access the underlying representation of the address, use `addr.octets`. + +```js +var addr = ipaddr.parse("192.168.1.1"); +addr.octets // => [192, 168, 1, 1] +``` + +`prefixLengthFromSubnetMask()` will return a CIDR prefix length for a valid IPv4 netmask or +null if the netmask is not valid. + +```js +ipaddr.IPv4.parse('255.255.255.240').prefixLengthFromSubnetMask() == 28 +ipaddr.IPv4.parse('255.192.164.0').prefixLengthFromSubnetMask() == null +``` + +`subnetMaskFromPrefixLength()` will return an IPv4 netmask for a valid CIDR prefix length. + +```js +ipaddr.IPv4.subnetMaskFromPrefixLength(24) == "255.255.255.0" +ipaddr.IPv4.subnetMaskFromPrefixLength(29) == "255.255.255.248" +``` + +`broadcastAddressFromCIDR()` will return the broadcast address for a given IPv4 interface and netmask in CIDR notation. +```js +ipaddr.IPv4.broadcastAddressFromCIDR("172.0.0.1/24") == "172.0.0.255" +``` +`networkAddressFromCIDR()` will return the network address for a given IPv4 interface and netmask in CIDR notation. +```js +ipaddr.IPv4.networkAddressFromCIDR("172.0.0.1/24") == "172.0.0.0" +``` + +#### Conversion + +IPv4 and IPv6 can be converted bidirectionally to and from network byte order (MSB) byte arrays. + +The `fromByteArray()` method will take an array and create an appropriate IPv4 or IPv6 object +if the input satisfies the requirements. For IPv4 it has to be an array of four 8-bit values, +while for IPv6 it has to be an array of sixteen 8-bit values. + +For example: +```js +var addr = ipaddr.fromByteArray([0x7f, 0, 0, 1]); +addr.toString(); // => "127.0.0.1" +``` + +or + +```js +var addr = ipaddr.fromByteArray([0x20, 1, 0xd, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]) +addr.toString(); // => "2001:db8::1" +``` + +Both objects also offer a `toByteArray()` method, which returns an array in network byte order (MSB). + +For example: +```js +var addr = ipaddr.parse("127.0.0.1"); +addr.toByteArray(); // => [0x7f, 0, 0, 1] +``` + +or + +```js +var addr = ipaddr.parse("2001:db8::1"); +addr.toByteArray(); // => [0x20, 1, 0xd, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1] +``` diff --git a/backend/node_modules/ipaddr.js/ipaddr.min.js b/backend/node_modules/ipaddr.js/ipaddr.min.js new file mode 100644 index 0000000000000000000000000000000000000000..b54a7cc42ac48524d2de2fa43979367e09fbe385 --- /dev/null +++ b/backend/node_modules/ipaddr.js/ipaddr.min.js @@ -0,0 +1 @@ +(function(){var r,t,n,e,i,o,a,s;t={},s=this,"undefined"!=typeof module&&null!==module&&module.exports?module.exports=t:s.ipaddr=t,a=function(r,t,n,e){var i,o;if(r.length!==t.length)throw new Error("ipaddr: cannot match CIDR for objects with different lengths");for(i=0;e>0;){if((o=n-e)<0&&(o=0),r[i]>>o!=t[i]>>o)return!1;e-=n,i+=1}return!0},t.subnetMatch=function(r,t,n){var e,i,o,a,s;null==n&&(n="unicast");for(o in t)for(!(a=t[o])[0]||a[0]instanceof Array||(a=[a]),e=0,i=a.length;e=0;t=n+=-1){if(!((e=this.octets[t])in a))return null;if(o=a[e],i&&0!==o)return null;8!==o&&(i=!0),r+=o}return 32-r},r}(),n="(0?\\d+|0x[a-f0-9]+)",e={fourOctet:new RegExp("^"+n+"\\."+n+"\\."+n+"\\."+n+"$","i"),longValue:new RegExp("^"+n+"$","i")},t.IPv4.parser=function(r){var t,n,i,o,a;if(n=function(r){return"0"===r[0]&&"x"!==r[1]?parseInt(r,8):parseInt(r)},t=r.match(e.fourOctet))return function(){var r,e,o,a;for(a=[],r=0,e=(o=t.slice(1,6)).length;r4294967295||a<0)throw new Error("ipaddr: address outside defined range");return function(){var r,t;for(t=[],o=r=0;r<=24;o=r+=8)t.push(a>>o&255);return t}().reverse()}return null},t.IPv6=function(){function r(r,t){var n,e,i,o,a,s;if(16===r.length)for(this.parts=[],n=e=0;e<=14;n=e+=2)this.parts.push(r[n]<<8|r[n+1]);else{if(8!==r.length)throw new Error("ipaddr: ipv6 part count should be 8 or 16");this.parts=r}for(i=0,o=(s=this.parts).length;it&&(r=n.index,t=n[0].length);return t<0?i:i.substring(0,r)+"::"+i.substring(r+t)},r.prototype.toByteArray=function(){var r,t,n,e,i;for(r=[],t=0,n=(i=this.parts).length;t>8),r.push(255&e);return r},r.prototype.toNormalizedString=function(){var r,t,n;return r=function(){var r,n,e,i;for(i=[],r=0,n=(e=this.parts).length;r>8,255&r,n>>8,255&n])},r.prototype.prefixLengthFromSubnetMask=function(){var r,t,n,e,i,o,a;for(a={0:16,32768:15,49152:14,57344:13,61440:12,63488:11,64512:10,65024:9,65280:8,65408:7,65472:6,65504:5,65520:4,65528:3,65532:2,65534:1,65535:0},r=0,i=!1,t=n=7;n>=0;t=n+=-1){if(!((e=this.parts[t])in a))return null;if(o=a[e],i&&0!==o)return null;16!==o&&(i=!0),r+=o}return 128-r},r}(),i="(?:[0-9a-f]+::?)+",o={zoneIndex:new RegExp("%[0-9a-z]{1,}","i"),native:new RegExp("^(::)?("+i+")?([0-9a-f]+)?(::)?(%[0-9a-z]{1,})?$","i"),transitional:new RegExp("^((?:"+i+")|(?:::)(?:"+i+")?)"+n+"\\."+n+"\\."+n+"\\."+n+"(%[0-9a-z]{1,})?$","i")},r=function(r,t){var n,e,i,a,s,p;if(r.indexOf("::")!==r.lastIndexOf("::"))return null;for((p=(r.match(o.zoneIndex)||[])[0])&&(p=p.substring(1),r=r.replace(/%.+$/,"")),n=0,e=-1;(e=r.indexOf(":",e+1))>=0;)n++;if("::"===r.substr(0,2)&&n--,"::"===r.substr(-2,2)&&n--,n>t)return null;for(s=t-n,a=":";s--;)a+="0:";return":"===(r=r.replace("::",a))[0]&&(r=r.slice(1)),":"===r[r.length-1]&&(r=r.slice(0,-1)),t=function(){var t,n,e,o;for(o=[],t=0,n=(e=r.split(":")).length;t=0&&t<=32)return e=[this.parse(n[1]),t],Object.defineProperty(e,"toString",{value:function(){return this.join("/")}}),e;throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range")},t.IPv4.subnetMaskFromPrefixLength=function(r){var t,n,e;if((r=parseInt(r))<0||r>32)throw new Error("ipaddr: invalid IPv4 prefix length");for(e=[0,0,0,0],n=0,t=Math.floor(r/8);n=0&&t<=128)return e=[this.parse(n[1]),t],Object.defineProperty(e,"toString",{value:function(){return this.join("/")}}),e;throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range")},t.isValid=function(r){return t.IPv6.isValid(r)||t.IPv4.isValid(r)},t.parse=function(r){if(t.IPv6.isValid(r))return t.IPv6.parse(r);if(t.IPv4.isValid(r))return t.IPv4.parse(r);throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format")},t.parseCIDR=function(r){try{return t.IPv6.parseCIDR(r)}catch(n){n;try{return t.IPv4.parseCIDR(r)}catch(r){throw r,new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format")}}},t.fromByteArray=function(r){var n;if(4===(n=r.length))return new t.IPv4(r);if(16===n)return new t.IPv6(r);throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address")},t.process=function(r){var t;return t=this.parse(r),"ipv6"===t.kind()&&t.isIPv4MappedAddress()?t.toIPv4Address():t}}).call(this); \ No newline at end of file diff --git a/backend/node_modules/ipaddr.js/lib/ipaddr.js b/backend/node_modules/ipaddr.js/lib/ipaddr.js new file mode 100644 index 0000000000000000000000000000000000000000..18bd93b5e6dfd2af35147a656b913b952cfc7043 --- /dev/null +++ b/backend/node_modules/ipaddr.js/lib/ipaddr.js @@ -0,0 +1,673 @@ +(function() { + var expandIPv6, ipaddr, ipv4Part, ipv4Regexes, ipv6Part, ipv6Regexes, matchCIDR, root, zoneIndex; + + ipaddr = {}; + + root = this; + + if ((typeof module !== "undefined" && module !== null) && module.exports) { + module.exports = ipaddr; + } else { + root['ipaddr'] = ipaddr; + } + + matchCIDR = function(first, second, partSize, cidrBits) { + var part, shift; + if (first.length !== second.length) { + throw new Error("ipaddr: cannot match CIDR for objects with different lengths"); + } + part = 0; + while (cidrBits > 0) { + shift = partSize - cidrBits; + if (shift < 0) { + shift = 0; + } + if (first[part] >> shift !== second[part] >> shift) { + return false; + } + cidrBits -= partSize; + part += 1; + } + return true; + }; + + ipaddr.subnetMatch = function(address, rangeList, defaultName) { + var k, len, rangeName, rangeSubnets, subnet; + if (defaultName == null) { + defaultName = 'unicast'; + } + for (rangeName in rangeList) { + rangeSubnets = rangeList[rangeName]; + if (rangeSubnets[0] && !(rangeSubnets[0] instanceof Array)) { + rangeSubnets = [rangeSubnets]; + } + for (k = 0, len = rangeSubnets.length; k < len; k++) { + subnet = rangeSubnets[k]; + if (address.kind() === subnet[0].kind()) { + if (address.match.apply(address, subnet)) { + return rangeName; + } + } + } + } + return defaultName; + }; + + ipaddr.IPv4 = (function() { + function IPv4(octets) { + var k, len, octet; + if (octets.length !== 4) { + throw new Error("ipaddr: ipv4 octet count should be 4"); + } + for (k = 0, len = octets.length; k < len; k++) { + octet = octets[k]; + if (!((0 <= octet && octet <= 255))) { + throw new Error("ipaddr: ipv4 octet should fit in 8 bits"); + } + } + this.octets = octets; + } + + IPv4.prototype.kind = function() { + return 'ipv4'; + }; + + IPv4.prototype.toString = function() { + return this.octets.join("."); + }; + + IPv4.prototype.toNormalizedString = function() { + return this.toString(); + }; + + IPv4.prototype.toByteArray = function() { + return this.octets.slice(0); + }; + + IPv4.prototype.match = function(other, cidrRange) { + var ref; + if (cidrRange === void 0) { + ref = other, other = ref[0], cidrRange = ref[1]; + } + if (other.kind() !== 'ipv4') { + throw new Error("ipaddr: cannot match ipv4 address with non-ipv4 one"); + } + return matchCIDR(this.octets, other.octets, 8, cidrRange); + }; + + IPv4.prototype.SpecialRanges = { + unspecified: [[new IPv4([0, 0, 0, 0]), 8]], + broadcast: [[new IPv4([255, 255, 255, 255]), 32]], + multicast: [[new IPv4([224, 0, 0, 0]), 4]], + linkLocal: [[new IPv4([169, 254, 0, 0]), 16]], + loopback: [[new IPv4([127, 0, 0, 0]), 8]], + carrierGradeNat: [[new IPv4([100, 64, 0, 0]), 10]], + "private": [[new IPv4([10, 0, 0, 0]), 8], [new IPv4([172, 16, 0, 0]), 12], [new IPv4([192, 168, 0, 0]), 16]], + reserved: [[new IPv4([192, 0, 0, 0]), 24], [new IPv4([192, 0, 2, 0]), 24], [new IPv4([192, 88, 99, 0]), 24], [new IPv4([198, 51, 100, 0]), 24], [new IPv4([203, 0, 113, 0]), 24], [new IPv4([240, 0, 0, 0]), 4]] + }; + + IPv4.prototype.range = function() { + return ipaddr.subnetMatch(this, this.SpecialRanges); + }; + + IPv4.prototype.toIPv4MappedAddress = function() { + return ipaddr.IPv6.parse("::ffff:" + (this.toString())); + }; + + IPv4.prototype.prefixLengthFromSubnetMask = function() { + var cidr, i, k, octet, stop, zeros, zerotable; + zerotable = { + 0: 8, + 128: 7, + 192: 6, + 224: 5, + 240: 4, + 248: 3, + 252: 2, + 254: 1, + 255: 0 + }; + cidr = 0; + stop = false; + for (i = k = 3; k >= 0; i = k += -1) { + octet = this.octets[i]; + if (octet in zerotable) { + zeros = zerotable[octet]; + if (stop && zeros !== 0) { + return null; + } + if (zeros !== 8) { + stop = true; + } + cidr += zeros; + } else { + return null; + } + } + return 32 - cidr; + }; + + return IPv4; + + })(); + + ipv4Part = "(0?\\d+|0x[a-f0-9]+)"; + + ipv4Regexes = { + fourOctet: new RegExp("^" + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "$", 'i'), + longValue: new RegExp("^" + ipv4Part + "$", 'i') + }; + + ipaddr.IPv4.parser = function(string) { + var match, parseIntAuto, part, shift, value; + parseIntAuto = function(string) { + if (string[0] === "0" && string[1] !== "x") { + return parseInt(string, 8); + } else { + return parseInt(string); + } + }; + if (match = string.match(ipv4Regexes.fourOctet)) { + return (function() { + var k, len, ref, results; + ref = match.slice(1, 6); + results = []; + for (k = 0, len = ref.length; k < len; k++) { + part = ref[k]; + results.push(parseIntAuto(part)); + } + return results; + })(); + } else if (match = string.match(ipv4Regexes.longValue)) { + value = parseIntAuto(match[1]); + if (value > 0xffffffff || value < 0) { + throw new Error("ipaddr: address outside defined range"); + } + return ((function() { + var k, results; + results = []; + for (shift = k = 0; k <= 24; shift = k += 8) { + results.push((value >> shift) & 0xff); + } + return results; + })()).reverse(); + } else { + return null; + } + }; + + ipaddr.IPv6 = (function() { + function IPv6(parts, zoneId) { + var i, k, l, len, part, ref; + if (parts.length === 16) { + this.parts = []; + for (i = k = 0; k <= 14; i = k += 2) { + this.parts.push((parts[i] << 8) | parts[i + 1]); + } + } else if (parts.length === 8) { + this.parts = parts; + } else { + throw new Error("ipaddr: ipv6 part count should be 8 or 16"); + } + ref = this.parts; + for (l = 0, len = ref.length; l < len; l++) { + part = ref[l]; + if (!((0 <= part && part <= 0xffff))) { + throw new Error("ipaddr: ipv6 part should fit in 16 bits"); + } + } + if (zoneId) { + this.zoneId = zoneId; + } + } + + IPv6.prototype.kind = function() { + return 'ipv6'; + }; + + IPv6.prototype.toString = function() { + return this.toNormalizedString().replace(/((^|:)(0(:|$))+)/, '::'); + }; + + IPv6.prototype.toRFC5952String = function() { + var bestMatchIndex, bestMatchLength, match, regex, string; + regex = /((^|:)(0(:|$)){2,})/g; + string = this.toNormalizedString(); + bestMatchIndex = 0; + bestMatchLength = -1; + while ((match = regex.exec(string))) { + if (match[0].length > bestMatchLength) { + bestMatchIndex = match.index; + bestMatchLength = match[0].length; + } + } + if (bestMatchLength < 0) { + return string; + } + return string.substring(0, bestMatchIndex) + '::' + string.substring(bestMatchIndex + bestMatchLength); + }; + + IPv6.prototype.toByteArray = function() { + var bytes, k, len, part, ref; + bytes = []; + ref = this.parts; + for (k = 0, len = ref.length; k < len; k++) { + part = ref[k]; + bytes.push(part >> 8); + bytes.push(part & 0xff); + } + return bytes; + }; + + IPv6.prototype.toNormalizedString = function() { + var addr, part, suffix; + addr = ((function() { + var k, len, ref, results; + ref = this.parts; + results = []; + for (k = 0, len = ref.length; k < len; k++) { + part = ref[k]; + results.push(part.toString(16)); + } + return results; + }).call(this)).join(":"); + suffix = ''; + if (this.zoneId) { + suffix = '%' + this.zoneId; + } + return addr + suffix; + }; + + IPv6.prototype.toFixedLengthString = function() { + var addr, part, suffix; + addr = ((function() { + var k, len, ref, results; + ref = this.parts; + results = []; + for (k = 0, len = ref.length; k < len; k++) { + part = ref[k]; + results.push(part.toString(16).padStart(4, '0')); + } + return results; + }).call(this)).join(":"); + suffix = ''; + if (this.zoneId) { + suffix = '%' + this.zoneId; + } + return addr + suffix; + }; + + IPv6.prototype.match = function(other, cidrRange) { + var ref; + if (cidrRange === void 0) { + ref = other, other = ref[0], cidrRange = ref[1]; + } + if (other.kind() !== 'ipv6') { + throw new Error("ipaddr: cannot match ipv6 address with non-ipv6 one"); + } + return matchCIDR(this.parts, other.parts, 16, cidrRange); + }; + + IPv6.prototype.SpecialRanges = { + unspecified: [new IPv6([0, 0, 0, 0, 0, 0, 0, 0]), 128], + linkLocal: [new IPv6([0xfe80, 0, 0, 0, 0, 0, 0, 0]), 10], + multicast: [new IPv6([0xff00, 0, 0, 0, 0, 0, 0, 0]), 8], + loopback: [new IPv6([0, 0, 0, 0, 0, 0, 0, 1]), 128], + uniqueLocal: [new IPv6([0xfc00, 0, 0, 0, 0, 0, 0, 0]), 7], + ipv4Mapped: [new IPv6([0, 0, 0, 0, 0, 0xffff, 0, 0]), 96], + rfc6145: [new IPv6([0, 0, 0, 0, 0xffff, 0, 0, 0]), 96], + rfc6052: [new IPv6([0x64, 0xff9b, 0, 0, 0, 0, 0, 0]), 96], + '6to4': [new IPv6([0x2002, 0, 0, 0, 0, 0, 0, 0]), 16], + teredo: [new IPv6([0x2001, 0, 0, 0, 0, 0, 0, 0]), 32], + reserved: [[new IPv6([0x2001, 0xdb8, 0, 0, 0, 0, 0, 0]), 32]] + }; + + IPv6.prototype.range = function() { + return ipaddr.subnetMatch(this, this.SpecialRanges); + }; + + IPv6.prototype.isIPv4MappedAddress = function() { + return this.range() === 'ipv4Mapped'; + }; + + IPv6.prototype.toIPv4Address = function() { + var high, low, ref; + if (!this.isIPv4MappedAddress()) { + throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4"); + } + ref = this.parts.slice(-2), high = ref[0], low = ref[1]; + return new ipaddr.IPv4([high >> 8, high & 0xff, low >> 8, low & 0xff]); + }; + + IPv6.prototype.prefixLengthFromSubnetMask = function() { + var cidr, i, k, part, stop, zeros, zerotable; + zerotable = { + 0: 16, + 32768: 15, + 49152: 14, + 57344: 13, + 61440: 12, + 63488: 11, + 64512: 10, + 65024: 9, + 65280: 8, + 65408: 7, + 65472: 6, + 65504: 5, + 65520: 4, + 65528: 3, + 65532: 2, + 65534: 1, + 65535: 0 + }; + cidr = 0; + stop = false; + for (i = k = 7; k >= 0; i = k += -1) { + part = this.parts[i]; + if (part in zerotable) { + zeros = zerotable[part]; + if (stop && zeros !== 0) { + return null; + } + if (zeros !== 16) { + stop = true; + } + cidr += zeros; + } else { + return null; + } + } + return 128 - cidr; + }; + + return IPv6; + + })(); + + ipv6Part = "(?:[0-9a-f]+::?)+"; + + zoneIndex = "%[0-9a-z]{1,}"; + + ipv6Regexes = { + zoneIndex: new RegExp(zoneIndex, 'i'), + "native": new RegExp("^(::)?(" + ipv6Part + ")?([0-9a-f]+)?(::)?(" + zoneIndex + ")?$", 'i'), + transitional: new RegExp(("^((?:" + ipv6Part + ")|(?:::)(?:" + ipv6Part + ")?)") + (ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part) + ("(" + zoneIndex + ")?$"), 'i') + }; + + expandIPv6 = function(string, parts) { + var colonCount, lastColon, part, replacement, replacementCount, zoneId; + if (string.indexOf('::') !== string.lastIndexOf('::')) { + return null; + } + zoneId = (string.match(ipv6Regexes['zoneIndex']) || [])[0]; + if (zoneId) { + zoneId = zoneId.substring(1); + string = string.replace(/%.+$/, ''); + } + colonCount = 0; + lastColon = -1; + while ((lastColon = string.indexOf(':', lastColon + 1)) >= 0) { + colonCount++; + } + if (string.substr(0, 2) === '::') { + colonCount--; + } + if (string.substr(-2, 2) === '::') { + colonCount--; + } + if (colonCount > parts) { + return null; + } + replacementCount = parts - colonCount; + replacement = ':'; + while (replacementCount--) { + replacement += '0:'; + } + string = string.replace('::', replacement); + if (string[0] === ':') { + string = string.slice(1); + } + if (string[string.length - 1] === ':') { + string = string.slice(0, -1); + } + parts = (function() { + var k, len, ref, results; + ref = string.split(":"); + results = []; + for (k = 0, len = ref.length; k < len; k++) { + part = ref[k]; + results.push(parseInt(part, 16)); + } + return results; + })(); + return { + parts: parts, + zoneId: zoneId + }; + }; + + ipaddr.IPv6.parser = function(string) { + var addr, k, len, match, octet, octets, zoneId; + if (ipv6Regexes['native'].test(string)) { + return expandIPv6(string, 8); + } else if (match = string.match(ipv6Regexes['transitional'])) { + zoneId = match[6] || ''; + addr = expandIPv6(match[1].slice(0, -1) + zoneId, 6); + if (addr.parts) { + octets = [parseInt(match[2]), parseInt(match[3]), parseInt(match[4]), parseInt(match[5])]; + for (k = 0, len = octets.length; k < len; k++) { + octet = octets[k]; + if (!((0 <= octet && octet <= 255))) { + return null; + } + } + addr.parts.push(octets[0] << 8 | octets[1]); + addr.parts.push(octets[2] << 8 | octets[3]); + return { + parts: addr.parts, + zoneId: addr.zoneId + }; + } + } + return null; + }; + + ipaddr.IPv4.isIPv4 = ipaddr.IPv6.isIPv6 = function(string) { + return this.parser(string) !== null; + }; + + ipaddr.IPv4.isValid = function(string) { + var e; + try { + new this(this.parser(string)); + return true; + } catch (error1) { + e = error1; + return false; + } + }; + + ipaddr.IPv4.isValidFourPartDecimal = function(string) { + if (ipaddr.IPv4.isValid(string) && string.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/)) { + return true; + } else { + return false; + } + }; + + ipaddr.IPv6.isValid = function(string) { + var addr, e; + if (typeof string === "string" && string.indexOf(":") === -1) { + return false; + } + try { + addr = this.parser(string); + new this(addr.parts, addr.zoneId); + return true; + } catch (error1) { + e = error1; + return false; + } + }; + + ipaddr.IPv4.parse = function(string) { + var parts; + parts = this.parser(string); + if (parts === null) { + throw new Error("ipaddr: string is not formatted like ip address"); + } + return new this(parts); + }; + + ipaddr.IPv6.parse = function(string) { + var addr; + addr = this.parser(string); + if (addr.parts === null) { + throw new Error("ipaddr: string is not formatted like ip address"); + } + return new this(addr.parts, addr.zoneId); + }; + + ipaddr.IPv4.parseCIDR = function(string) { + var maskLength, match, parsed; + if (match = string.match(/^(.+)\/(\d+)$/)) { + maskLength = parseInt(match[2]); + if (maskLength >= 0 && maskLength <= 32) { + parsed = [this.parse(match[1]), maskLength]; + Object.defineProperty(parsed, 'toString', { + value: function() { + return this.join('/'); + } + }); + return parsed; + } + } + throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range"); + }; + + ipaddr.IPv4.subnetMaskFromPrefixLength = function(prefix) { + var filledOctetCount, j, octets; + prefix = parseInt(prefix); + if (prefix < 0 || prefix > 32) { + throw new Error('ipaddr: invalid IPv4 prefix length'); + } + octets = [0, 0, 0, 0]; + j = 0; + filledOctetCount = Math.floor(prefix / 8); + while (j < filledOctetCount) { + octets[j] = 255; + j++; + } + if (filledOctetCount < 4) { + octets[filledOctetCount] = Math.pow(2, prefix % 8) - 1 << 8 - (prefix % 8); + } + return new this(octets); + }; + + ipaddr.IPv4.broadcastAddressFromCIDR = function(string) { + var cidr, error, i, ipInterfaceOctets, octets, subnetMaskOctets; + try { + cidr = this.parseCIDR(string); + ipInterfaceOctets = cidr[0].toByteArray(); + subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray(); + octets = []; + i = 0; + while (i < 4) { + octets.push(parseInt(ipInterfaceOctets[i], 10) | parseInt(subnetMaskOctets[i], 10) ^ 255); + i++; + } + return new this(octets); + } catch (error1) { + error = error1; + throw new Error('ipaddr: the address does not have IPv4 CIDR format'); + } + }; + + ipaddr.IPv4.networkAddressFromCIDR = function(string) { + var cidr, error, i, ipInterfaceOctets, octets, subnetMaskOctets; + try { + cidr = this.parseCIDR(string); + ipInterfaceOctets = cidr[0].toByteArray(); + subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray(); + octets = []; + i = 0; + while (i < 4) { + octets.push(parseInt(ipInterfaceOctets[i], 10) & parseInt(subnetMaskOctets[i], 10)); + i++; + } + return new this(octets); + } catch (error1) { + error = error1; + throw new Error('ipaddr: the address does not have IPv4 CIDR format'); + } + }; + + ipaddr.IPv6.parseCIDR = function(string) { + var maskLength, match, parsed; + if (match = string.match(/^(.+)\/(\d+)$/)) { + maskLength = parseInt(match[2]); + if (maskLength >= 0 && maskLength <= 128) { + parsed = [this.parse(match[1]), maskLength]; + Object.defineProperty(parsed, 'toString', { + value: function() { + return this.join('/'); + } + }); + return parsed; + } + } + throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range"); + }; + + ipaddr.isValid = function(string) { + return ipaddr.IPv6.isValid(string) || ipaddr.IPv4.isValid(string); + }; + + ipaddr.parse = function(string) { + if (ipaddr.IPv6.isValid(string)) { + return ipaddr.IPv6.parse(string); + } else if (ipaddr.IPv4.isValid(string)) { + return ipaddr.IPv4.parse(string); + } else { + throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format"); + } + }; + + ipaddr.parseCIDR = function(string) { + var e; + try { + return ipaddr.IPv6.parseCIDR(string); + } catch (error1) { + e = error1; + try { + return ipaddr.IPv4.parseCIDR(string); + } catch (error1) { + e = error1; + throw new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format"); + } + } + }; + + ipaddr.fromByteArray = function(bytes) { + var length; + length = bytes.length; + if (length === 4) { + return new ipaddr.IPv4(bytes); + } else if (length === 16) { + return new ipaddr.IPv6(bytes); + } else { + throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address"); + } + }; + + ipaddr.process = function(string) { + var addr; + addr = this.parse(string); + if (addr.kind() === 'ipv6' && addr.isIPv4MappedAddress()) { + return addr.toIPv4Address(); + } else { + return addr; + } + }; + +}).call(this); diff --git a/backend/node_modules/ipaddr.js/lib/ipaddr.js.d.ts b/backend/node_modules/ipaddr.js/lib/ipaddr.js.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..52174b6b6b28411c03f230e779c6f1edf93f9423 --- /dev/null +++ b/backend/node_modules/ipaddr.js/lib/ipaddr.js.d.ts @@ -0,0 +1,68 @@ +declare module "ipaddr.js" { + type IPv4Range = 'unicast' | 'unspecified' | 'broadcast' | 'multicast' | 'linkLocal' | 'loopback' | 'carrierGradeNat' | 'private' | 'reserved'; + type IPv6Range = 'unicast' | 'unspecified' | 'linkLocal' | 'multicast' | 'loopback' | 'uniqueLocal' | 'ipv4Mapped' | 'rfc6145' | 'rfc6052' | '6to4' | 'teredo' | 'reserved'; + + interface RangeList { + [name: string]: [T, number] | [T, number][]; + } + + // Common methods/properties for IPv4 and IPv6 classes. + class IP { + prefixLengthFromSubnetMask(): number | null; + toByteArray(): number[]; + toNormalizedString(): string; + toString(): string; + } + + namespace Address { + export function isValid(addr: string): boolean; + export function fromByteArray(bytes: number[]): IPv4 | IPv6; + export function parse(addr: string): IPv4 | IPv6; + export function parseCIDR(mask: string): [IPv4 | IPv6, number]; + export function process(addr: string): IPv4 | IPv6; + export function subnetMatch(addr: IPv4, rangeList: RangeList, defaultName?: string): string; + export function subnetMatch(addr: IPv6, rangeList: RangeList, defaultName?: string): string; + + export class IPv4 extends IP { + static broadcastAddressFromCIDR(addr: string): IPv4; + static isIPv4(addr: string): boolean; + static isValidFourPartDecimal(addr: string): boolean; + static isValid(addr: string): boolean; + static networkAddressFromCIDR(addr: string): IPv4; + static parse(addr: string): IPv4; + static parseCIDR(addr: string): [IPv4, number]; + static subnetMaskFromPrefixLength(prefix: number): IPv4; + constructor(octets: number[]); + octets: number[] + + kind(): 'ipv4'; + match(addr: IPv4, bits: number): boolean; + match(mask: [IPv4, number]): boolean; + range(): IPv4Range; + subnetMatch(rangeList: RangeList, defaultName?: string): string; + toIPv4MappedAddress(): IPv6; + } + + export class IPv6 extends IP { + static broadcastAddressFromCIDR(addr: string): IPv6; + static isIPv6(addr: string): boolean; + static isValid(addr: string): boolean; + static parse(addr: string): IPv6; + static parseCIDR(addr: string): [IPv6, number]; + static subnetMaskFromPrefixLength(prefix: number): IPv6; + constructor(parts: number[]); + parts: number[] + zoneId?: string + + isIPv4MappedAddress(): boolean; + kind(): 'ipv6'; + match(addr: IPv6, bits: number): boolean; + match(mask: [IPv6, number]): boolean; + range(): IPv6Range; + subnetMatch(rangeList: RangeList, defaultName?: string): string; + toIPv4Address(): IPv4; + } + } + + export = Address; +} diff --git a/backend/node_modules/ipaddr.js/package.json b/backend/node_modules/ipaddr.js/package.json new file mode 100644 index 0000000000000000000000000000000000000000..f4d35475d17abd96f03b0e1133258703b284c785 --- /dev/null +++ b/backend/node_modules/ipaddr.js/package.json @@ -0,0 +1,35 @@ +{ + "name": "ipaddr.js", + "description": "A library for manipulating IPv4 and IPv6 addresses in JavaScript.", + "version": "1.9.1", + "author": "whitequark ", + "directories": { + "lib": "./lib" + }, + "dependencies": {}, + "devDependencies": { + "coffee-script": "~1.12.6", + "nodeunit": "^0.11.3", + "uglify-js": "~3.0.19" + }, + "scripts": { + "test": "cake build test" + }, + "files": [ + "lib/", + "LICENSE", + "ipaddr.min.js" + ], + "keywords": [ + "ip", + "ipv4", + "ipv6" + ], + "repository": "git://github.com/whitequark/ipaddr.js", + "main": "./lib/ipaddr.js", + "engines": { + "node": ">= 0.10" + }, + "license": "MIT", + "types": "./lib/ipaddr.js.d.ts" +} diff --git a/backend/node_modules/isarray/.npmignore b/backend/node_modules/isarray/.npmignore new file mode 100644 index 0000000000000000000000000000000000000000..3c3629e647f5ddf82548912e337bea9826b434af --- /dev/null +++ b/backend/node_modules/isarray/.npmignore @@ -0,0 +1 @@ +node_modules diff --git a/backend/node_modules/isarray/.travis.yml b/backend/node_modules/isarray/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..cc4dba29d959a2da7b97f9edd3c7c91384b2ee5b --- /dev/null +++ b/backend/node_modules/isarray/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - "0.8" + - "0.10" diff --git a/backend/node_modules/isarray/Makefile b/backend/node_modules/isarray/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..787d56e1e982e48588bc199f36f0d50cb4724066 --- /dev/null +++ b/backend/node_modules/isarray/Makefile @@ -0,0 +1,6 @@ + +test: + @node_modules/.bin/tape test.js + +.PHONY: test + diff --git a/backend/node_modules/isarray/README.md b/backend/node_modules/isarray/README.md new file mode 100644 index 0000000000000000000000000000000000000000..16d2c59c6195f9a1ac9af37cb9d75f1a6b85ab01 --- /dev/null +++ b/backend/node_modules/isarray/README.md @@ -0,0 +1,60 @@ + +# isarray + +`Array#isArray` for older browsers. + +[![build status](https://secure.travis-ci.org/juliangruber/isarray.svg)](http://travis-ci.org/juliangruber/isarray) +[![downloads](https://img.shields.io/npm/dm/isarray.svg)](https://www.npmjs.org/package/isarray) + +[![browser support](https://ci.testling.com/juliangruber/isarray.png) +](https://ci.testling.com/juliangruber/isarray) + +## Usage + +```js +var isArray = require('isarray'); + +console.log(isArray([])); // => true +console.log(isArray({})); // => false +``` + +## Installation + +With [npm](http://npmjs.org) do + +```bash +$ npm install isarray +``` + +Then bundle for the browser with +[browserify](https://github.com/substack/browserify). + +With [component](http://component.io) do + +```bash +$ component install juliangruber/isarray +``` + +## License + +(MIT) + +Copyright (c) 2013 Julian Gruber <julian@juliangruber.com> + +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/backend/node_modules/isarray/component.json b/backend/node_modules/isarray/component.json new file mode 100644 index 0000000000000000000000000000000000000000..9e31b6838890159e397063bdd2ea7de80b4e4a42 --- /dev/null +++ b/backend/node_modules/isarray/component.json @@ -0,0 +1,19 @@ +{ + "name" : "isarray", + "description" : "Array#isArray for older browsers", + "version" : "0.0.1", + "repository" : "juliangruber/isarray", + "homepage": "https://github.com/juliangruber/isarray", + "main" : "index.js", + "scripts" : [ + "index.js" + ], + "dependencies" : {}, + "keywords": ["browser","isarray","array"], + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "license": "MIT" +} diff --git a/backend/node_modules/isarray/index.js b/backend/node_modules/isarray/index.js new file mode 100644 index 0000000000000000000000000000000000000000..a57f63495943a07b3b08d17e0f9ef6793548c801 --- /dev/null +++ b/backend/node_modules/isarray/index.js @@ -0,0 +1,5 @@ +var toString = {}.toString; + +module.exports = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; +}; diff --git a/backend/node_modules/isarray/package.json b/backend/node_modules/isarray/package.json new file mode 100644 index 0000000000000000000000000000000000000000..1a4317a9c41c73d52934337143b974a35074e6f2 --- /dev/null +++ b/backend/node_modules/isarray/package.json @@ -0,0 +1,45 @@ +{ + "name": "isarray", + "description": "Array#isArray for older browsers", + "version": "1.0.0", + "repository": { + "type": "git", + "url": "git://github.com/juliangruber/isarray.git" + }, + "homepage": "https://github.com/juliangruber/isarray", + "main": "index.js", + "dependencies": {}, + "devDependencies": { + "tape": "~2.13.4" + }, + "keywords": [ + "browser", + "isarray", + "array" + ], + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "license": "MIT", + "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" + ] + }, + "scripts": { + "test": "tape test.js" + } +} diff --git a/backend/node_modules/isarray/test.js b/backend/node_modules/isarray/test.js new file mode 100644 index 0000000000000000000000000000000000000000..e0c3444d85d5c799bd70b2ee9df62ef56d9763ea --- /dev/null +++ b/backend/node_modules/isarray/test.js @@ -0,0 +1,20 @@ +var isArray = require('./'); +var test = require('tape'); + +test('is array', function(t){ + t.ok(isArray([])); + t.notOk(isArray({})); + t.notOk(isArray(null)); + t.notOk(isArray(false)); + + var obj = {}; + obj[0] = true; + t.notOk(isArray(obj)); + + var arr = []; + arr.foo = 'bar'; + t.ok(isArray(arr)); + + t.end(); +}); + diff --git a/backend/node_modules/media-typer/HISTORY.md b/backend/node_modules/media-typer/HISTORY.md new file mode 100644 index 0000000000000000000000000000000000000000..62c2003168f588b4d470470278a2319c5950edc2 --- /dev/null +++ b/backend/node_modules/media-typer/HISTORY.md @@ -0,0 +1,22 @@ +0.3.0 / 2014-09-07 +================== + + * Support Node.js 0.6 + * Throw error when parameter format invalid on parse + +0.2.0 / 2014-06-18 +================== + + * Add `typer.format()` to format media types + +0.1.0 / 2014-06-17 +================== + + * Accept `req` as argument to `parse` + * Accept `res` as argument to `parse` + * Parse media type with extra LWS between type and first parameter + +0.0.0 / 2014-06-13 +================== + + * Initial implementation diff --git a/backend/node_modules/media-typer/LICENSE b/backend/node_modules/media-typer/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..b7dce6cf9a0edc74d1d1624b04cb7b2182b856a6 --- /dev/null +++ b/backend/node_modules/media-typer/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014 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/backend/node_modules/media-typer/README.md b/backend/node_modules/media-typer/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d8df62347a6fff095c753754b0a3dd30b6591b33 --- /dev/null +++ b/backend/node_modules/media-typer/README.md @@ -0,0 +1,81 @@ +# media-typer + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Simple RFC 6838 media type parser + +## Installation + +```sh +$ npm install media-typer +``` + +## API + +```js +var typer = require('media-typer') +``` + +### typer.parse(string) + +```js +var obj = typer.parse('image/svg+xml; charset=utf-8') +``` + +Parse a media type string. This will return an object with the following +properties (examples are shown for the string `'image/svg+xml; charset=utf-8'`): + + - `type`: The type of the media type (always lower case). Example: `'image'` + + - `subtype`: The subtype of the media type (always lower case). Example: `'svg'` + + - `suffix`: The suffix of the media type (always lower case). Example: `'xml'` + + - `parameters`: An object of the parameters in the media type (name of parameter always lower case). Example: `{charset: 'utf-8'}` + +### typer.parse(req) + +```js +var obj = typer.parse(req) +``` + +Parse the `content-type` header from the given `req`. Short-cut for +`typer.parse(req.headers['content-type'])`. + +### typer.parse(res) + +```js +var obj = typer.parse(res) +``` + +Parse the `content-type` header set on the given `res`. Short-cut for +`typer.parse(res.getHeader('content-type'))`. + +### typer.format(obj) + +```js +var obj = typer.format({type: 'image', subtype: 'svg', suffix: 'xml'}) +``` + +Format an object into a media type string. This will return a string of the +mime type for the given object. For the properties of the object, see the +documentation for `typer.parse(string)`. + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/media-typer.svg?style=flat +[npm-url]: https://npmjs.org/package/media-typer +[node-version-image]: https://img.shields.io/badge/node.js-%3E%3D_0.6-brightgreen.svg?style=flat +[node-version-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/jshttp/media-typer.svg?style=flat +[travis-url]: https://travis-ci.org/jshttp/media-typer +[coveralls-image]: https://img.shields.io/coveralls/jshttp/media-typer.svg?style=flat +[coveralls-url]: https://coveralls.io/r/jshttp/media-typer +[downloads-image]: https://img.shields.io/npm/dm/media-typer.svg?style=flat +[downloads-url]: https://npmjs.org/package/media-typer diff --git a/backend/node_modules/media-typer/index.js b/backend/node_modules/media-typer/index.js new file mode 100644 index 0000000000000000000000000000000000000000..07f7295ee780fbfb881b953e92f79e49fe00f08c --- /dev/null +++ b/backend/node_modules/media-typer/index.js @@ -0,0 +1,270 @@ +/*! + * media-typer + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * RegExp to match *( ";" parameter ) in RFC 2616 sec 3.7 + * + * 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 = + * SHT = + * CTL = + * OCTET = + */ +var paramRegExp = /; *([!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+) *= *("(?:[ !\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u0020-\u007e])*"|[!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+) */g; +var textRegExp = /^[\u0020-\u007e\u0080-\u00ff]+$/ +var tokenRegExp = /^[!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+$/ + +/** + * RegExp to match quoted-pair in RFC 2616 + * + * quoted-pair = "\" CHAR + * CHAR = + */ +var qescRegExp = /\\([\u0000-\u007f])/g; + +/** + * RegExp to match chars that must be quoted-pair in RFC 2616 + */ +var quoteRegExp = /([\\"])/g; + +/** + * RegExp to match type in RFC 6838 + * + * type-name = restricted-name + * subtype-name = restricted-name + * restricted-name = restricted-name-first *126restricted-name-chars + * restricted-name-first = ALPHA / DIGIT + * restricted-name-chars = ALPHA / DIGIT / "!" / "#" / + * "$" / "&" / "-" / "^" / "_" + * restricted-name-chars =/ "." ; Characters before first dot always + * ; specify a facet name + * restricted-name-chars =/ "+" ; Characters after last plus always + * ; specify a structured syntax suffix + * ALPHA = %x41-5A / %x61-7A ; A-Z / a-z + * DIGIT = %x30-39 ; 0-9 + */ +var subtypeNameRegExp = /^[A-Za-z0-9][A-Za-z0-9!#$&^_.-]{0,126}$/ +var typeNameRegExp = /^[A-Za-z0-9][A-Za-z0-9!#$&^_-]{0,126}$/ +var typeRegExp = /^ *([A-Za-z0-9][A-Za-z0-9!#$&^_-]{0,126})\/([A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}) *$/; + +/** + * Module exports. + */ + +exports.format = format +exports.parse = parse + +/** + * Format object to media type. + * + * @param {object} obj + * @return {string} + * @api public + */ + +function format(obj) { + if (!obj || typeof obj !== 'object') { + throw new TypeError('argument obj is required') + } + + var parameters = obj.parameters + var subtype = obj.subtype + var suffix = obj.suffix + var type = obj.type + + if (!type || !typeNameRegExp.test(type)) { + throw new TypeError('invalid type') + } + + if (!subtype || !subtypeNameRegExp.test(subtype)) { + throw new TypeError('invalid subtype') + } + + // format as type/subtype + var string = type + '/' + subtype + + // append +suffix + if (suffix) { + if (!typeNameRegExp.test(suffix)) { + throw new TypeError('invalid suffix') + } + + string += '+' + suffix + } + + // 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 (!tokenRegExp.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} + * @api public + */ + +function parse(string) { + if (!string) { + throw new TypeError('argument string is required') + } + + // support req/res-like objects as argument + if (typeof string === 'object') { + string = getcontenttype(string) + } + + if (typeof string !== 'string') { + throw new TypeError('argument string is required to be a string') + } + + var index = string.indexOf(';') + var type = index !== -1 + ? string.substr(0, index) + : string + + var key + var match + var obj = splitType(type) + var params = {} + var value + + paramRegExp.lastIndex = index + + while (match = paramRegExp.exec(string)) { + if (match.index !== index) { + throw new TypeError('invalid parameter format') + } + + index += match[0].length + key = match[1].toLowerCase() + value = match[2] + + if (value[0] === '"') { + // remove quotes and escapes + value = value + .substr(1, value.length - 2) + .replace(qescRegExp, '$1') + } + + params[key] = value + } + + if (index !== -1 && index !== string.length) { + throw new TypeError('invalid parameter format') + } + + obj.parameters = params + + return obj +} + +/** + * Get content-type from req/res objects. + * + * @param {object} + * @return {Object} + * @api private + */ + +function getcontenttype(obj) { + if (typeof obj.getHeader === 'function') { + // res-like + return obj.getHeader('content-type') + } + + if (typeof obj.headers === 'object') { + // req-like + return obj.headers && obj.headers['content-type'] + } +} + +/** + * Quote a string if necessary. + * + * @param {string} val + * @return {string} + * @api private + */ + +function qstring(val) { + var str = String(val) + + // no need to quote tokens + if (tokenRegExp.test(str)) { + return str + } + + if (str.length > 0 && !textRegExp.test(str)) { + throw new TypeError('invalid parameter value') + } + + return '"' + str.replace(quoteRegExp, '\\$1') + '"' +} + +/** + * Simply "type/subtype+siffx" into parts. + * + * @param {string} string + * @return {Object} + * @api private + */ + +function splitType(string) { + var match = typeRegExp.exec(string.toLowerCase()) + + if (!match) { + throw new TypeError('invalid media type') + } + + var type = match[1] + var subtype = match[2] + var suffix + + // suffix after last + + var index = subtype.lastIndexOf('+') + if (index !== -1) { + suffix = subtype.substr(index + 1) + subtype = subtype.substr(0, index) + } + + var obj = { + type: type, + subtype: subtype, + suffix: suffix + } + + return obj +} diff --git a/backend/node_modules/media-typer/package.json b/backend/node_modules/media-typer/package.json new file mode 100644 index 0000000000000000000000000000000000000000..8cf3ebcd775f0f5977bd2f590c5e91893e58c733 --- /dev/null +++ b/backend/node_modules/media-typer/package.json @@ -0,0 +1,26 @@ +{ + "name": "media-typer", + "description": "Simple RFC 6838 media type parser and formatter", + "version": "0.3.0", + "author": "Douglas Christopher Wilson ", + "license": "MIT", + "repository": "jshttp/media-typer", + "devDependencies": { + "istanbul": "0.3.2", + "mocha": "~1.21.4", + "should": "~4.0.4" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "test": "mocha --reporter spec --check-leaks --bail test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + } +} diff --git a/backend/node_modules/merge-descriptors/HISTORY.md b/backend/node_modules/merge-descriptors/HISTORY.md new file mode 100644 index 0000000000000000000000000000000000000000..486771f08bcb1c31a5f6cf0125ad8c422a2b2fcc --- /dev/null +++ b/backend/node_modules/merge-descriptors/HISTORY.md @@ -0,0 +1,21 @@ +1.0.1 / 2016-01-17 +================== + + * perf: enable strict mode + +1.0.0 / 2015-03-01 +================== + + * Add option to only add new descriptors + * Add simple argument validation + * Add jsdoc to source file + +0.0.2 / 2013-12-14 +================== + + * Move repository to `component` organization + +0.0.1 / 2013-10-29 +================== + + * Initial release diff --git a/backend/node_modules/merge-descriptors/LICENSE b/backend/node_modules/merge-descriptors/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..274bfd82b2e075c7a264f01c10324d91d636403f --- /dev/null +++ b/backend/node_modules/merge-descriptors/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2013 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/backend/node_modules/merge-descriptors/README.md b/backend/node_modules/merge-descriptors/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d593c0ebd7c15b5749e913412ab3b729d114b81e --- /dev/null +++ b/backend/node_modules/merge-descriptors/README.md @@ -0,0 +1,48 @@ +# Merge Descriptors + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Merge objects using descriptors. + +```js +var thing = { + get name() { + return 'jon' + } +} + +var animal = { + +} + +merge(animal, thing) + +animal.name === 'jon' +``` + +## API + +### merge(destination, source) + +Redefines `destination`'s descriptors with `source`'s. + +### merge(destination, source, false) + +Defines `source`'s descriptors on `destination` if `destination` does not have +a descriptor by the same name. + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/merge-descriptors.svg +[npm-url]: https://npmjs.org/package/merge-descriptors +[travis-image]: https://img.shields.io/travis/component/merge-descriptors/master.svg +[travis-url]: https://travis-ci.org/component/merge-descriptors +[coveralls-image]: https://img.shields.io/coveralls/component/merge-descriptors/master.svg +[coveralls-url]: https://coveralls.io/r/component/merge-descriptors?branch=master +[downloads-image]: https://img.shields.io/npm/dm/merge-descriptors.svg +[downloads-url]: https://npmjs.org/package/merge-descriptors diff --git a/backend/node_modules/merge-descriptors/index.js b/backend/node_modules/merge-descriptors/index.js new file mode 100644 index 0000000000000000000000000000000000000000..573b132eb2ba40bd26ffc8360e814d5beb4bc50f --- /dev/null +++ b/backend/node_modules/merge-descriptors/index.js @@ -0,0 +1,60 @@ +/*! + * merge-descriptors + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = merge + +/** + * Module variables. + * @private + */ + +var hasOwnProperty = Object.prototype.hasOwnProperty + +/** + * Merge the property descriptors of `src` into `dest` + * + * @param {object} dest Object to add descriptors to + * @param {object} src Object to clone descriptors from + * @param {boolean} [redefine=true] Redefine `dest` properties with `src` properties + * @returns {object} Reference to dest + * @public + */ + +function merge(dest, src, redefine) { + if (!dest) { + throw new TypeError('argument dest is required') + } + + if (!src) { + throw new TypeError('argument src is required') + } + + if (redefine === undefined) { + // Default to true + redefine = true + } + + Object.getOwnPropertyNames(src).forEach(function forEachOwnPropertyName(name) { + if (!redefine && hasOwnProperty.call(dest, name)) { + // Skip desriptor + return + } + + // Copy descriptor + var descriptor = Object.getOwnPropertyDescriptor(src, name) + Object.defineProperty(dest, name, descriptor) + }) + + return dest +} diff --git a/backend/node_modules/merge-descriptors/package.json b/backend/node_modules/merge-descriptors/package.json new file mode 100644 index 0000000000000000000000000000000000000000..514cdbd814cdd4709ccad66d059a8e66ff134c25 --- /dev/null +++ b/backend/node_modules/merge-descriptors/package.json @@ -0,0 +1,32 @@ +{ + "name": "merge-descriptors", + "description": "Merge objects using descriptors", + "version": "1.0.1", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com", + "twitter": "https://twitter.com/jongleberry" + }, + "contributors": [ + "Douglas Christopher Wilson ", + "Mike Grabowski " + ], + "license": "MIT", + "repository": "component/merge-descriptors", + "devDependencies": { + "istanbul": "0.4.1", + "mocha": "1.21.5" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "index.js" + ], + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-ci": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/" + } +} diff --git a/backend/node_modules/methods/HISTORY.md b/backend/node_modules/methods/HISTORY.md new file mode 100644 index 0000000000000000000000000000000000000000..c0ecf072db3f9809c46c83f5641b5df99c686bbf --- /dev/null +++ b/backend/node_modules/methods/HISTORY.md @@ -0,0 +1,29 @@ +1.1.2 / 2016-01-17 +================== + + * perf: enable strict mode + +1.1.1 / 2014-12-30 +================== + + * Improve `browserify` support + +1.1.0 / 2014-07-05 +================== + + * Add `CONNECT` method + +1.0.1 / 2014-06-02 +================== + + * Fix module to work with harmony transform + +1.0.0 / 2014-05-08 +================== + + * Add `PURGE` method + +0.1.0 / 2013-10-28 +================== + + * Add `http.METHODS` support diff --git a/backend/node_modules/methods/LICENSE b/backend/node_modules/methods/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..220dc1a247943ef3837b65754455dfb179260070 --- /dev/null +++ b/backend/node_modules/methods/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2013-2014 TJ Holowaychuk +Copyright (c) 2015-2016 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/backend/node_modules/methods/README.md b/backend/node_modules/methods/README.md new file mode 100644 index 0000000000000000000000000000000000000000..672a32bfe5d685306f18b7a81a15af9fbbd00a0f --- /dev/null +++ b/backend/node_modules/methods/README.md @@ -0,0 +1,51 @@ +# Methods + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +HTTP verbs that Node.js core's HTTP parser supports. + +This module provides an export that is just like `http.METHODS` from Node.js core, +with the following differences: + + * All method names are lower-cased. + * Contains a fallback list of methods for Node.js versions that do not have a + `http.METHODS` export (0.10 and lower). + * Provides the fallback list when using tools like `browserify` without pulling + in the `http` shim module. + +## Install + +```bash +$ npm install methods +``` + +## API + +```js +var methods = require('methods') +``` + +### methods + +This is an array of lower-cased method names that Node.js supports. If Node.js +provides the `http.METHODS` export, then this is the same array lower-cased, +otherwise it is a snapshot of the verbs from Node.js 0.10. + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/methods.svg?style=flat +[npm-url]: https://npmjs.org/package/methods +[node-version-image]: https://img.shields.io/node/v/methods.svg?style=flat +[node-version-url]: https://nodejs.org/en/download/ +[travis-image]: https://img.shields.io/travis/jshttp/methods.svg?style=flat +[travis-url]: https://travis-ci.org/jshttp/methods +[coveralls-image]: https://img.shields.io/coveralls/jshttp/methods.svg?style=flat +[coveralls-url]: https://coveralls.io/r/jshttp/methods?branch=master +[downloads-image]: https://img.shields.io/npm/dm/methods.svg?style=flat +[downloads-url]: https://npmjs.org/package/methods diff --git a/backend/node_modules/methods/index.js b/backend/node_modules/methods/index.js new file mode 100644 index 0000000000000000000000000000000000000000..667a50bde7d852359b1ebd9fa8ea8b8582bc64ac --- /dev/null +++ b/backend/node_modules/methods/index.js @@ -0,0 +1,69 @@ +/*! + * methods + * Copyright(c) 2013-2014 TJ Holowaychuk + * Copyright(c) 2015-2016 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var http = require('http'); + +/** + * Module exports. + * @public + */ + +module.exports = getCurrentNodeMethods() || getBasicNodeMethods(); + +/** + * Get the current Node.js methods. + * @private + */ + +function getCurrentNodeMethods() { + return http.METHODS && http.METHODS.map(function lowerCaseMethod(method) { + return method.toLowerCase(); + }); +} + +/** + * Get the "basic" Node.js methods, a snapshot from Node.js 0.10. + * @private + */ + +function getBasicNodeMethods() { + return [ + 'get', + 'post', + 'put', + 'head', + 'delete', + 'options', + 'trace', + 'copy', + 'lock', + 'mkcol', + 'move', + 'purge', + 'propfind', + 'proppatch', + 'unlock', + 'report', + 'mkactivity', + 'checkout', + 'merge', + 'm-search', + 'notify', + 'subscribe', + 'unsubscribe', + 'patch', + 'search', + 'connect' + ]; +} diff --git a/backend/node_modules/methods/package.json b/backend/node_modules/methods/package.json new file mode 100644 index 0000000000000000000000000000000000000000..c4ce6f053c68581068898fd2a4be53a861e5b1b5 --- /dev/null +++ b/backend/node_modules/methods/package.json @@ -0,0 +1,36 @@ +{ + "name": "methods", + "description": "HTTP methods that node supports", + "version": "1.1.2", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)", + "TJ Holowaychuk (http://tjholowaychuk.com)" + ], + "license": "MIT", + "repository": "jshttp/methods", + "devDependencies": { + "istanbul": "0.4.1", + "mocha": "1.21.5" + }, + "files": [ + "index.js", + "HISTORY.md", + "LICENSE" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "browser": { + "http": false + }, + "keywords": [ + "http", + "methods" + ] +} diff --git a/backend/node_modules/mime-db/HISTORY.md b/backend/node_modules/mime-db/HISTORY.md new file mode 100644 index 0000000000000000000000000000000000000000..7436f64146e87d2ebe6cacac33af0aeedcc798fb --- /dev/null +++ b/backend/node_modules/mime-db/HISTORY.md @@ -0,0 +1,507 @@ +1.52.0 / 2022-02-21 +=================== + + * Add extensions from IANA for more `image/*` types + * Add extension `.asc` to `application/pgp-keys` + * Add extensions to various XML types + * Add new upstream MIME types + +1.51.0 / 2021-11-08 +=================== + + * Add new upstream MIME types + * Mark `image/vnd.microsoft.icon` as compressible + * Mark `image/vnd.ms-dds` as compressible + +1.50.0 / 2021-09-15 +=================== + + * Add deprecated iWorks mime types and extensions + * Add new upstream MIME types + +1.49.0 / 2021-07-26 +=================== + + * Add extension `.trig` to `application/trig` + * Add new upstream MIME types + +1.48.0 / 2021-05-30 +=================== + + * Add extension `.mvt` to `application/vnd.mapbox-vector-tile` + * Add new upstream MIME types + * Mark `text/yaml` as compressible + +1.47.0 / 2021-04-01 +=================== + + * Add new upstream MIME types + * Remove ambigious extensions from IANA for `application/*+xml` types + * Update primary extension to `.es` for `application/ecmascript` + +1.46.0 / 2021-02-13 +=================== + + * Add extension `.amr` to `audio/amr` + * Add extension `.m4s` to `video/iso.segment` + * Add extension `.opus` to `audio/ogg` + * Add new upstream MIME types + +1.45.0 / 2020-09-22 +=================== + + * Add `application/ubjson` with extension `.ubj` + * Add `image/avif` with extension `.avif` + * Add `image/ktx2` with extension `.ktx2` + * Add extension `.dbf` to `application/vnd.dbf` + * Add extension `.rar` to `application/vnd.rar` + * Add extension `.td` to `application/urc-targetdesc+xml` + * Add new upstream MIME types + * Fix extension of `application/vnd.apple.keynote` to be `.key` + +1.44.0 / 2020-04-22 +=================== + + * Add charsets from IANA + * Add extension `.cjs` to `application/node` + * Add new upstream MIME types + +1.43.0 / 2020-01-05 +=================== + + * Add `application/x-keepass2` with extension `.kdbx` + * Add extension `.mxmf` to `audio/mobile-xmf` + * Add extensions from IANA for `application/*+xml` types + * Add new upstream MIME types + +1.42.0 / 2019-09-25 +=================== + + * Add `image/vnd.ms-dds` with extension `.dds` + * Add new upstream MIME types + * Remove compressible from `multipart/mixed` + +1.41.0 / 2019-08-30 +=================== + + * Add new upstream MIME types + * Add `application/toml` with extension `.toml` + * Mark `font/ttf` as compressible + +1.40.0 / 2019-04-20 +=================== + + * Add extensions from IANA for `model/*` types + * Add `text/mdx` with extension `.mdx` + +1.39.0 / 2019-04-04 +=================== + + * Add extensions `.siv` and `.sieve` to `application/sieve` + * Add new upstream MIME types + +1.38.0 / 2019-02-04 +=================== + + * Add extension `.nq` to `application/n-quads` + * Add extension `.nt` to `application/n-triples` + * Add new upstream MIME types + * Mark `text/less` as compressible + +1.37.0 / 2018-10-19 +=================== + + * Add extensions to HEIC image types + * Add new upstream MIME types + +1.36.0 / 2018-08-20 +=================== + + * Add Apple file extensions from IANA + * Add extensions from IANA for `image/*` types + * Add new upstream MIME types + +1.35.0 / 2018-07-15 +=================== + + * Add extension `.owl` to `application/rdf+xml` + * Add new upstream MIME types + - Removes extension `.woff` from `application/font-woff` + +1.34.0 / 2018-06-03 +=================== + + * Add extension `.csl` to `application/vnd.citationstyles.style+xml` + * Add extension `.es` to `application/ecmascript` + * Add new upstream MIME types + * Add `UTF-8` as default charset for `text/turtle` + * Mark all XML-derived types as compressible + +1.33.0 / 2018-02-15 +=================== + + * Add extensions from IANA for `message/*` types + * Add new upstream MIME types + * Fix some incorrect OOXML types + * Remove `application/font-woff2` + +1.32.0 / 2017-11-29 +=================== + + * Add new upstream MIME types + * Update `text/hjson` to registered `application/hjson` + * Add `text/shex` with extension `.shex` + +1.31.0 / 2017-10-25 +=================== + + * Add `application/raml+yaml` with extension `.raml` + * Add `application/wasm` with extension `.wasm` + * Add new `font` type from IANA + * Add new upstream font extensions + * Add new upstream MIME types + * Add extensions for JPEG-2000 images + +1.30.0 / 2017-08-27 +=================== + + * Add `application/vnd.ms-outlook` + * Add `application/x-arj` + * Add extension `.mjs` to `application/javascript` + * Add glTF types and extensions + * Add new upstream MIME types + * Add `text/x-org` + * Add VirtualBox MIME types + * Fix `source` records for `video/*` types that are IANA + * Update `font/opentype` to registered `font/otf` + +1.29.0 / 2017-07-10 +=================== + + * Add `application/fido.trusted-apps+json` + * Add extension `.wadl` to `application/vnd.sun.wadl+xml` + * Add new upstream MIME types + * Add `UTF-8` as default charset for `text/css` + +1.28.0 / 2017-05-14 +=================== + + * Add new upstream MIME types + * Add extension `.gz` to `application/gzip` + * Update extensions `.md` and `.markdown` to be `text/markdown` + +1.27.0 / 2017-03-16 +=================== + + * Add new upstream MIME types + * Add `image/apng` with extension `.apng` + +1.26.0 / 2017-01-14 +=================== + + * Add new upstream MIME types + * Add extension `.geojson` to `application/geo+json` + +1.25.0 / 2016-11-11 +=================== + + * Add new upstream MIME types + +1.24.0 / 2016-09-18 +=================== + + * Add `audio/mp3` + * Add new upstream MIME types + +1.23.0 / 2016-05-01 +=================== + + * Add new upstream MIME types + * Add extension `.3gpp` to `audio/3gpp` + +1.22.0 / 2016-02-15 +=================== + + * Add `text/slim` + * Add extension `.rng` to `application/xml` + * Add new upstream MIME types + * Fix extension of `application/dash+xml` to be `.mpd` + * Update primary extension to `.m4a` for `audio/mp4` + +1.21.0 / 2016-01-06 +=================== + + * Add Google document types + * Add new upstream MIME types + +1.20.0 / 2015-11-10 +=================== + + * Add `text/x-suse-ymp` + * Add new upstream MIME types + +1.19.0 / 2015-09-17 +=================== + + * Add `application/vnd.apple.pkpass` + * Add new upstream MIME types + +1.18.0 / 2015-09-03 +=================== + + * Add new upstream MIME types + +1.17.0 / 2015-08-13 +=================== + + * Add `application/x-msdos-program` + * Add `audio/g711-0` + * Add `image/vnd.mozilla.apng` + * Add extension `.exe` to `application/x-msdos-program` + +1.16.0 / 2015-07-29 +=================== + + * Add `application/vnd.uri-map` + +1.15.0 / 2015-07-13 +=================== + + * Add `application/x-httpd-php` + +1.14.0 / 2015-06-25 +=================== + + * Add `application/scim+json` + * Add `application/vnd.3gpp.ussd+xml` + * Add `application/vnd.biopax.rdf+xml` + * Add `text/x-processing` + +1.13.0 / 2015-06-07 +=================== + + * Add nginx as a source + * Add `application/x-cocoa` + * Add `application/x-java-archive-diff` + * Add `application/x-makeself` + * Add `application/x-perl` + * Add `application/x-pilot` + * Add `application/x-redhat-package-manager` + * Add `application/x-sea` + * Add `audio/x-m4a` + * Add `audio/x-realaudio` + * Add `image/x-jng` + * Add `text/mathml` + +1.12.0 / 2015-06-05 +=================== + + * Add `application/bdoc` + * Add `application/vnd.hyperdrive+json` + * Add `application/x-bdoc` + * Add extension `.rtf` to `text/rtf` + +1.11.0 / 2015-05-31 +=================== + + * Add `audio/wav` + * Add `audio/wave` + * Add extension `.litcoffee` to `text/coffeescript` + * Add extension `.sfd-hdstx` to `application/vnd.hydrostatix.sof-data` + * Add extension `.n-gage` to `application/vnd.nokia.n-gage.symbian.install` + +1.10.0 / 2015-05-19 +=================== + + * Add `application/vnd.balsamiq.bmpr` + * Add `application/vnd.microsoft.portable-executable` + * Add `application/x-ns-proxy-autoconfig` + +1.9.1 / 2015-04-19 +================== + + * Remove `.json` extension from `application/manifest+json` + - This is causing bugs downstream + +1.9.0 / 2015-04-19 +================== + + * Add `application/manifest+json` + * Add `application/vnd.micro+json` + * Add `image/vnd.zbrush.pcx` + * Add `image/x-ms-bmp` + +1.8.0 / 2015-03-13 +================== + + * Add `application/vnd.citationstyles.style+xml` + * Add `application/vnd.fastcopy-disk-image` + * Add `application/vnd.gov.sk.xmldatacontainer+xml` + * Add extension `.jsonld` to `application/ld+json` + +1.7.0 / 2015-02-08 +================== + + * Add `application/vnd.gerber` + * Add `application/vnd.msa-disk-image` + +1.6.1 / 2015-02-05 +================== + + * Community extensions ownership transferred from `node-mime` + +1.6.0 / 2015-01-29 +================== + + * Add `application/jose` + * Add `application/jose+json` + * Add `application/json-seq` + * Add `application/jwk+json` + * Add `application/jwk-set+json` + * Add `application/jwt` + * Add `application/rdap+json` + * Add `application/vnd.gov.sk.e-form+xml` + * Add `application/vnd.ims.imsccv1p3` + +1.5.0 / 2014-12-30 +================== + + * Add `application/vnd.oracle.resource+json` + * Fix various invalid MIME type entries + - `application/mbox+xml` + - `application/oscp-response` + - `application/vwg-multiplexed` + - `audio/g721` + +1.4.0 / 2014-12-21 +================== + + * Add `application/vnd.ims.imsccv1p2` + * Fix various invalid MIME type entries + - `application/vnd-acucobol` + - `application/vnd-curl` + - `application/vnd-dart` + - `application/vnd-dxr` + - `application/vnd-fdf` + - `application/vnd-mif` + - `application/vnd-sema` + - `application/vnd-wap-wmlc` + - `application/vnd.adobe.flash-movie` + - `application/vnd.dece-zip` + - `application/vnd.dvb_service` + - `application/vnd.micrografx-igx` + - `application/vnd.sealed-doc` + - `application/vnd.sealed-eml` + - `application/vnd.sealed-mht` + - `application/vnd.sealed-ppt` + - `application/vnd.sealed-tiff` + - `application/vnd.sealed-xls` + - `application/vnd.sealedmedia.softseal-html` + - `application/vnd.sealedmedia.softseal-pdf` + - `application/vnd.wap-slc` + - `application/vnd.wap-wbxml` + - `audio/vnd.sealedmedia.softseal-mpeg` + - `image/vnd-djvu` + - `image/vnd-svf` + - `image/vnd-wap-wbmp` + - `image/vnd.sealed-png` + - `image/vnd.sealedmedia.softseal-gif` + - `image/vnd.sealedmedia.softseal-jpg` + - `model/vnd-dwf` + - `model/vnd.parasolid.transmit-binary` + - `model/vnd.parasolid.transmit-text` + - `text/vnd-a` + - `text/vnd-curl` + - `text/vnd.wap-wml` + * Remove example template MIME types + - `application/example` + - `audio/example` + - `image/example` + - `message/example` + - `model/example` + - `multipart/example` + - `text/example` + - `video/example` + +1.3.1 / 2014-12-16 +================== + + * Fix missing extensions + - `application/json5` + - `text/hjson` + +1.3.0 / 2014-12-07 +================== + + * Add `application/a2l` + * Add `application/aml` + * Add `application/atfx` + * Add `application/atxml` + * Add `application/cdfx+xml` + * Add `application/dii` + * Add `application/json5` + * Add `application/lxf` + * Add `application/mf4` + * Add `application/vnd.apache.thrift.compact` + * Add `application/vnd.apache.thrift.json` + * Add `application/vnd.coffeescript` + * Add `application/vnd.enphase.envoy` + * Add `application/vnd.ims.imsccv1p1` + * Add `text/csv-schema` + * Add `text/hjson` + * Add `text/markdown` + * Add `text/yaml` + +1.2.0 / 2014-11-09 +================== + + * Add `application/cea` + * Add `application/dit` + * Add `application/vnd.gov.sk.e-form+zip` + * Add `application/vnd.tmd.mediaflex.api+xml` + * Type `application/epub+zip` is now IANA-registered + +1.1.2 / 2014-10-23 +================== + + * Rebuild database for `application/x-www-form-urlencoded` change + +1.1.1 / 2014-10-20 +================== + + * Mark `application/x-www-form-urlencoded` as compressible. + +1.1.0 / 2014-09-28 +================== + + * Add `application/font-woff2` + +1.0.3 / 2014-09-25 +================== + + * Fix engine requirement in package + +1.0.2 / 2014-09-25 +================== + + * Add `application/coap-group+json` + * Add `application/dcd` + * Add `application/vnd.apache.thrift.binary` + * Add `image/vnd.tencent.tap` + * Mark all JSON-derived types as compressible + * Update `text/vtt` data + +1.0.1 / 2014-08-30 +================== + + * Fix extension ordering + +1.0.0 / 2014-08-30 +================== + + * Add `application/atf` + * Add `application/merge-patch+json` + * Add `multipart/x-mixed-replace` + * Add `source: 'apache'` metadata + * Add `source: 'iana'` metadata + * Remove badly-assumed charset data diff --git a/backend/node_modules/mime-db/LICENSE b/backend/node_modules/mime-db/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..0751cb10e94972be9a07b44cc261447bac726a7f --- /dev/null +++ b/backend/node_modules/mime-db/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2015-2022 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/backend/node_modules/mime-db/README.md b/backend/node_modules/mime-db/README.md new file mode 100644 index 0000000000000000000000000000000000000000..5a8fcfe4d0d813c4608765b31342fe5297e5867f --- /dev/null +++ b/backend/node_modules/mime-db/README.md @@ -0,0 +1,100 @@ +# mime-db + +[![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] + +This is a large database of mime types and information about them. +It consists of a single, public JSON file and does not include any logic, +allowing it to remain as un-opinionated as possible with an API. +It aggregates data from the following sources: + +- http://www.iana.org/assignments/media-types/media-types.xhtml +- http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types +- http://hg.nginx.org/nginx/raw-file/default/conf/mime.types + +## Installation + +```bash +npm install mime-db +``` + +### Database Download + +If you're crazy enough to use this in the browser, you can just grab the +JSON file using [jsDelivr](https://www.jsdelivr.com/). It is recommended to +replace `master` with [a release tag](https://github.com/jshttp/mime-db/tags) +as the JSON format may change in the future. + +``` +https://cdn.jsdelivr.net/gh/jshttp/mime-db@master/db.json +``` + +## Usage + +```js +var db = require('mime-db') + +// grab data on .js files +var data = db['application/javascript'] +``` + +## Data Structure + +The JSON file is a map lookup for lowercased mime types. +Each mime type has the following properties: + +- `.source` - where the mime type is defined. + If not set, it's probably a custom media type. + - `apache` - [Apache common media types](http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types) + - `iana` - [IANA-defined media types](http://www.iana.org/assignments/media-types/media-types.xhtml) + - `nginx` - [nginx media types](http://hg.nginx.org/nginx/raw-file/default/conf/mime.types) +- `.extensions[]` - known extensions associated with this mime type. +- `.compressible` - whether a file of this type can be gzipped. +- `.charset` - the default charset associated with this type, if any. + +If unknown, every property could be `undefined`. + +## Contributing + +To edit the database, only make PRs against `src/custom-types.json` or +`src/custom-suffix.json`. + +The `src/custom-types.json` file is a JSON object with the MIME type as the +keys and the values being an object with the following keys: + +- `compressible` - leave out if you don't know, otherwise `true`/`false` to + indicate whether the data represented by the type is typically compressible. +- `extensions` - include an array of file extensions that are associated with + the type. +- `notes` - human-readable notes about the type, typically what the type is. +- `sources` - include an array of URLs of where the MIME type and the associated + extensions are sourced from. This needs to be a [primary source](https://en.wikipedia.org/wiki/Primary_source); + links to type aggregating sites and Wikipedia are _not acceptable_. + +To update the build, run `npm run build`. + +### Adding Custom Media Types + +The best way to get new media types included in this library is to register +them with the IANA. The community registration procedure is outlined in +[RFC 6838 section 5](http://tools.ietf.org/html/rfc6838#section-5). Types +registered with the IANA are automatically pulled into this library. + +If that is not possible / feasible, they can be added directly here as a +"custom" type. To do this, it is required to have a primary source that +definitively lists the media type. If an extension is going to be listed as +associateed with this media type, the source must definitively link the +media type and extension as well. + +[ci-image]: https://badgen.net/github/checks/jshttp/mime-db/master?label=ci +[ci-url]: https://github.com/jshttp/mime-db/actions?query=workflow%3Aci +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/mime-db/master +[coveralls-url]: https://coveralls.io/r/jshttp/mime-db?branch=master +[node-image]: https://badgen.net/npm/node/mime-db +[node-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/mime-db +[npm-url]: https://npmjs.org/package/mime-db +[npm-version-image]: https://badgen.net/npm/v/mime-db diff --git a/backend/node_modules/mime-db/db.json b/backend/node_modules/mime-db/db.json new file mode 100644 index 0000000000000000000000000000000000000000..eb9c42c457a3b42f3af43e37ed62de4d704c413a --- /dev/null +++ b/backend/node_modules/mime-db/db.json @@ -0,0 +1,8519 @@ +{ + "application/1d-interleaved-parityfec": { + "source": "iana" + }, + "application/3gpdash-qoe-report+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/3gpp-ims+xml": { + "source": "iana", + "compressible": true + }, + "application/3gpphal+json": { + "source": "iana", + "compressible": true + }, + "application/3gpphalforms+json": { + "source": "iana", + "compressible": true + }, + "application/a2l": { + "source": "iana" + }, + "application/ace+cbor": { + "source": "iana" + }, + "application/activemessage": { + "source": "iana" + }, + "application/activity+json": { + "source": "iana", + "compressible": true + }, + "application/alto-costmap+json": { + "source": "iana", + "compressible": true + }, + "application/alto-costmapfilter+json": { + "source": "iana", + "compressible": true + }, + "application/alto-directory+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointcost+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointcostparams+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointprop+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointpropparams+json": { + "source": "iana", + "compressible": true + }, + "application/alto-error+json": { + "source": "iana", + "compressible": true + }, + "application/alto-networkmap+json": { + "source": "iana", + "compressible": true + }, + "application/alto-networkmapfilter+json": { + "source": "iana", + "compressible": true + }, + "application/alto-updatestreamcontrol+json": { + "source": "iana", + "compressible": true + }, + "application/alto-updatestreamparams+json": { + "source": "iana", + "compressible": true + }, + "application/aml": { + "source": "iana" + }, + "application/andrew-inset": { + "source": "iana", + "extensions": ["ez"] + }, + "application/applefile": { + "source": "iana" + }, + "application/applixware": { + "source": "apache", + "extensions": ["aw"] + }, + "application/at+jwt": { + "source": "iana" + }, + "application/atf": { + "source": "iana" + }, + "application/atfx": { + "source": "iana" + }, + "application/atom+xml": { + "source": "iana", + "compressible": true, + "extensions": ["atom"] + }, + "application/atomcat+xml": { + "source": "iana", + "compressible": true, + "extensions": ["atomcat"] + }, + "application/atomdeleted+xml": { + "source": "iana", + "compressible": true, + "extensions": ["atomdeleted"] + }, + "application/atomicmail": { + "source": "iana" + }, + "application/atomsvc+xml": { + "source": "iana", + "compressible": true, + "extensions": ["atomsvc"] + }, + "application/atsc-dwd+xml": { + "source": "iana", + "compressible": true, + "extensions": ["dwd"] + }, + "application/atsc-dynamic-event-message": { + "source": "iana" + }, + "application/atsc-held+xml": { + "source": "iana", + "compressible": true, + "extensions": ["held"] + }, + "application/atsc-rdt+json": { + "source": "iana", + "compressible": true + }, + "application/atsc-rsat+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rsat"] + }, + "application/atxml": { + "source": "iana" + }, + "application/auth-policy+xml": { + "source": "iana", + "compressible": true + }, + "application/bacnet-xdd+zip": { + "source": "iana", + "compressible": false + }, + "application/batch-smtp": { + "source": "iana" + }, + "application/bdoc": { + "compressible": false, + "extensions": ["bdoc"] + }, + "application/beep+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/calendar+json": { + "source": "iana", + "compressible": true + }, + "application/calendar+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xcs"] + }, + "application/call-completion": { + "source": "iana" + }, + "application/cals-1840": { + "source": "iana" + }, + "application/captive+json": { + "source": "iana", + "compressible": true + }, + "application/cbor": { + "source": "iana" + }, + "application/cbor-seq": { + "source": "iana" + }, + "application/cccex": { + "source": "iana" + }, + "application/ccmp+xml": { + "source": "iana", + "compressible": true + }, + "application/ccxml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["ccxml"] + }, + "application/cdfx+xml": { + "source": "iana", + "compressible": true, + "extensions": ["cdfx"] + }, + "application/cdmi-capability": { + "source": "iana", + "extensions": ["cdmia"] + }, + "application/cdmi-container": { + "source": "iana", + "extensions": ["cdmic"] + }, + "application/cdmi-domain": { + "source": "iana", + "extensions": ["cdmid"] + }, + "application/cdmi-object": { + "source": "iana", + "extensions": ["cdmio"] + }, + "application/cdmi-queue": { + "source": "iana", + "extensions": ["cdmiq"] + }, + "application/cdni": { + "source": "iana" + }, + "application/cea": { + "source": "iana" + }, + "application/cea-2018+xml": { + "source": "iana", + "compressible": true + }, + "application/cellml+xml": { + "source": "iana", + "compressible": true + }, + "application/cfw": { + "source": "iana" + }, + "application/city+json": { + "source": "iana", + "compressible": true + }, + "application/clr": { + "source": "iana" + }, + "application/clue+xml": { + "source": "iana", + "compressible": true + }, + "application/clue_info+xml": { + "source": "iana", + "compressible": true + }, + "application/cms": { + "source": "iana" + }, + "application/cnrp+xml": { + "source": "iana", + "compressible": true + }, + "application/coap-group+json": { + "source": "iana", + "compressible": true + }, + "application/coap-payload": { + "source": "iana" + }, + "application/commonground": { + "source": "iana" + }, + "application/conference-info+xml": { + "source": "iana", + "compressible": true + }, + "application/cose": { + "source": "iana" + }, + "application/cose-key": { + "source": "iana" + }, + "application/cose-key-set": { + "source": "iana" + }, + "application/cpl+xml": { + "source": "iana", + "compressible": true, + "extensions": ["cpl"] + }, + "application/csrattrs": { + "source": "iana" + }, + "application/csta+xml": { + "source": "iana", + "compressible": true + }, + "application/cstadata+xml": { + "source": "iana", + "compressible": true + }, + "application/csvm+json": { + "source": "iana", + "compressible": true + }, + "application/cu-seeme": { + "source": "apache", + "extensions": ["cu"] + }, + "application/cwt": { + "source": "iana" + }, + "application/cybercash": { + "source": "iana" + }, + "application/dart": { + "compressible": true + }, + "application/dash+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mpd"] + }, + "application/dash-patch+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mpp"] + }, + "application/dashdelta": { + "source": "iana" + }, + "application/davmount+xml": { + "source": "iana", + "compressible": true, + "extensions": ["davmount"] + }, + "application/dca-rft": { + "source": "iana" + }, + "application/dcd": { + "source": "iana" + }, + "application/dec-dx": { + "source": "iana" + }, + "application/dialog-info+xml": { + "source": "iana", + "compressible": true + }, + "application/dicom": { + "source": "iana" + }, + "application/dicom+json": { + "source": "iana", + "compressible": true + }, + "application/dicom+xml": { + "source": "iana", + "compressible": true + }, + "application/dii": { + "source": "iana" + }, + "application/dit": { + "source": "iana" + }, + "application/dns": { + "source": "iana" + }, + "application/dns+json": { + "source": "iana", + "compressible": true + }, + "application/dns-message": { + "source": "iana" + }, + "application/docbook+xml": { + "source": "apache", + "compressible": true, + "extensions": ["dbk"] + }, + "application/dots+cbor": { + "source": "iana" + }, + "application/dskpp+xml": { + "source": "iana", + "compressible": true + }, + "application/dssc+der": { + "source": "iana", + "extensions": ["dssc"] + }, + "application/dssc+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xdssc"] + }, + "application/dvcs": { + "source": "iana" + }, + "application/ecmascript": { + "source": "iana", + "compressible": true, + "extensions": ["es","ecma"] + }, + "application/edi-consent": { + "source": "iana" + }, + "application/edi-x12": { + "source": "iana", + "compressible": false + }, + "application/edifact": { + "source": "iana", + "compressible": false + }, + "application/efi": { + "source": "iana" + }, + "application/elm+json": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/elm+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.cap+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/emergencycalldata.comment+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.control+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.deviceinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.ecall.msd": { + "source": "iana" + }, + "application/emergencycalldata.providerinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.serviceinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.subscriberinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.veds+xml": { + "source": "iana", + "compressible": true + }, + "application/emma+xml": { + "source": "iana", + "compressible": true, + "extensions": ["emma"] + }, + "application/emotionml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["emotionml"] + }, + "application/encaprtp": { + "source": "iana" + }, + "application/epp+xml": { + "source": "iana", + "compressible": true + }, + "application/epub+zip": { + "source": "iana", + "compressible": false, + "extensions": ["epub"] + }, + "application/eshop": { + "source": "iana" + }, + "application/exi": { + "source": "iana", + "extensions": ["exi"] + }, + "application/expect-ct-report+json": { + "source": "iana", + "compressible": true + }, + "application/express": { + "source": "iana", + "extensions": ["exp"] + }, + "application/fastinfoset": { + "source": "iana" + }, + "application/fastsoap": { + "source": "iana" + }, + "application/fdt+xml": { + "source": "iana", + "compressible": true, + "extensions": ["fdt"] + }, + "application/fhir+json": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/fhir+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/fido.trusted-apps+json": { + "compressible": true + }, + "application/fits": { + "source": "iana" + }, + "application/flexfec": { + "source": "iana" + }, + "application/font-sfnt": { + "source": "iana" + }, + "application/font-tdpfr": { + "source": "iana", + "extensions": ["pfr"] + }, + "application/font-woff": { + "source": "iana", + "compressible": false + }, + "application/framework-attributes+xml": { + "source": "iana", + "compressible": true + }, + "application/geo+json": { + "source": "iana", + "compressible": true, + "extensions": ["geojson"] + }, + "application/geo+json-seq": { + "source": "iana" + }, + "application/geopackage+sqlite3": { + "source": "iana" + }, + "application/geoxacml+xml": { + "source": "iana", + "compressible": true + }, + "application/gltf-buffer": { + "source": "iana" + }, + "application/gml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["gml"] + }, + "application/gpx+xml": { + "source": "apache", + "compressible": true, + "extensions": ["gpx"] + }, + "application/gxf": { + "source": "apache", + "extensions": ["gxf"] + }, + "application/gzip": { + "source": "iana", + "compressible": false, + "extensions": ["gz"] + }, + "application/h224": { + "source": "iana" + }, + "application/held+xml": { + "source": "iana", + "compressible": true + }, + "application/hjson": { + "extensions": ["hjson"] + }, + "application/http": { + "source": "iana" + }, + "application/hyperstudio": { + "source": "iana", + "extensions": ["stk"] + }, + "application/ibe-key-request+xml": { + "source": "iana", + "compressible": true + }, + "application/ibe-pkg-reply+xml": { + "source": "iana", + "compressible": true + }, + "application/ibe-pp-data": { + "source": "iana" + }, + "application/iges": { + "source": "iana" + }, + "application/im-iscomposing+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/index": { + "source": "iana" + }, + "application/index.cmd": { + "source": "iana" + }, + "application/index.obj": { + "source": "iana" + }, + "application/index.response": { + "source": "iana" + }, + "application/index.vnd": { + "source": "iana" + }, + "application/inkml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["ink","inkml"] + }, + "application/iotp": { + "source": "iana" + }, + "application/ipfix": { + "source": "iana", + "extensions": ["ipfix"] + }, + "application/ipp": { + "source": "iana" + }, + "application/isup": { + "source": "iana" + }, + "application/its+xml": { + "source": "iana", + "compressible": true, + "extensions": ["its"] + }, + "application/java-archive": { + "source": "apache", + "compressible": false, + "extensions": ["jar","war","ear"] + }, + "application/java-serialized-object": { + "source": "apache", + "compressible": false, + "extensions": ["ser"] + }, + "application/java-vm": { + "source": "apache", + "compressible": false, + "extensions": ["class"] + }, + "application/javascript": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["js","mjs"] + }, + "application/jf2feed+json": { + "source": "iana", + "compressible": true + }, + "application/jose": { + "source": "iana" + }, + "application/jose+json": { + "source": "iana", + "compressible": true + }, + "application/jrd+json": { + "source": "iana", + "compressible": true + }, + "application/jscalendar+json": { + "source": "iana", + "compressible": true + }, + "application/json": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["json","map"] + }, + "application/json-patch+json": { + "source": "iana", + "compressible": true + }, + "application/json-seq": { + "source": "iana" + }, + "application/json5": { + "extensions": ["json5"] + }, + "application/jsonml+json": { + "source": "apache", + "compressible": true, + "extensions": ["jsonml"] + }, + "application/jwk+json": { + "source": "iana", + "compressible": true + }, + "application/jwk-set+json": { + "source": "iana", + "compressible": true + }, + "application/jwt": { + "source": "iana" + }, + "application/kpml-request+xml": { + "source": "iana", + "compressible": true + }, + "application/kpml-response+xml": { + "source": "iana", + "compressible": true + }, + "application/ld+json": { + "source": "iana", + "compressible": true, + "extensions": ["jsonld"] + }, + "application/lgr+xml": { + "source": "iana", + "compressible": true, + "extensions": ["lgr"] + }, + "application/link-format": { + "source": "iana" + }, + "application/load-control+xml": { + "source": "iana", + "compressible": true + }, + "application/lost+xml": { + "source": "iana", + "compressible": true, + "extensions": ["lostxml"] + }, + "application/lostsync+xml": { + "source": "iana", + "compressible": true + }, + "application/lpf+zip": { + "source": "iana", + "compressible": false + }, + "application/lxf": { + "source": "iana" + }, + "application/mac-binhex40": { + "source": "iana", + "extensions": ["hqx"] + }, + "application/mac-compactpro": { + "source": "apache", + "extensions": ["cpt"] + }, + "application/macwriteii": { + "source": "iana" + }, + "application/mads+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mads"] + }, + "application/manifest+json": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["webmanifest"] + }, + "application/marc": { + "source": "iana", + "extensions": ["mrc"] + }, + "application/marcxml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mrcx"] + }, + "application/mathematica": { + "source": "iana", + "extensions": ["ma","nb","mb"] + }, + "application/mathml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mathml"] + }, + "application/mathml-content+xml": { + "source": "iana", + "compressible": true + }, + "application/mathml-presentation+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-associated-procedure-description+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-deregister+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-envelope+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-msk+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-msk-response+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-protection-description+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-reception-report+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-register+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-register-response+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-schedule+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-user-service-description+xml": { + "source": "iana", + "compressible": true + }, + "application/mbox": { + "source": "iana", + "extensions": ["mbox"] + }, + "application/media-policy-dataset+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mpf"] + }, + "application/media_control+xml": { + "source": "iana", + "compressible": true + }, + "application/mediaservercontrol+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mscml"] + }, + "application/merge-patch+json": { + "source": "iana", + "compressible": true + }, + "application/metalink+xml": { + "source": "apache", + "compressible": true, + "extensions": ["metalink"] + }, + "application/metalink4+xml": { + "source": "iana", + "compressible": true, + "extensions": ["meta4"] + }, + "application/mets+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mets"] + }, + "application/mf4": { + "source": "iana" + }, + "application/mikey": { + "source": "iana" + }, + "application/mipc": { + "source": "iana" + }, + "application/missing-blocks+cbor-seq": { + "source": "iana" + }, + "application/mmt-aei+xml": { + "source": "iana", + "compressible": true, + "extensions": ["maei"] + }, + "application/mmt-usd+xml": { + "source": "iana", + "compressible": true, + "extensions": ["musd"] + }, + "application/mods+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mods"] + }, + "application/moss-keys": { + "source": "iana" + }, + "application/moss-signature": { + "source": "iana" + }, + "application/mosskey-data": { + "source": "iana" + }, + "application/mosskey-request": { + "source": "iana" + }, + "application/mp21": { + "source": "iana", + "extensions": ["m21","mp21"] + }, + "application/mp4": { + "source": "iana", + "extensions": ["mp4s","m4p"] + }, + "application/mpeg4-generic": { + "source": "iana" + }, + "application/mpeg4-iod": { + "source": "iana" + }, + "application/mpeg4-iod-xmt": { + "source": "iana" + }, + "application/mrb-consumer+xml": { + "source": "iana", + "compressible": true + }, + "application/mrb-publish+xml": { + "source": "iana", + "compressible": true + }, + "application/msc-ivr+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/msc-mixer+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/msword": { + "source": "iana", + "compressible": false, + "extensions": ["doc","dot"] + }, + "application/mud+json": { + "source": "iana", + "compressible": true + }, + "application/multipart-core": { + "source": "iana" + }, + "application/mxf": { + "source": "iana", + "extensions": ["mxf"] + }, + "application/n-quads": { + "source": "iana", + "extensions": ["nq"] + }, + "application/n-triples": { + "source": "iana", + "extensions": ["nt"] + }, + "application/nasdata": { + "source": "iana" + }, + "application/news-checkgroups": { + "source": "iana", + "charset": "US-ASCII" + }, + "application/news-groupinfo": { + "source": "iana", + "charset": "US-ASCII" + }, + "application/news-transmission": { + "source": "iana" + }, + "application/nlsml+xml": { + "source": "iana", + "compressible": true + }, + "application/node": { + "source": "iana", + "extensions": ["cjs"] + }, + "application/nss": { + "source": "iana" + }, + "application/oauth-authz-req+jwt": { + "source": "iana" + }, + "application/oblivious-dns-message": { + "source": "iana" + }, + "application/ocsp-request": { + "source": "iana" + }, + "application/ocsp-response": { + "source": "iana" + }, + "application/octet-stream": { + "source": "iana", + "compressible": false, + "extensions": ["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"] + }, + "application/oda": { + "source": "iana", + "extensions": ["oda"] + }, + "application/odm+xml": { + "source": "iana", + "compressible": true + }, + "application/odx": { + "source": "iana" + }, + "application/oebps-package+xml": { + "source": "iana", + "compressible": true, + "extensions": ["opf"] + }, + "application/ogg": { + "source": "iana", + "compressible": false, + "extensions": ["ogx"] + }, + "application/omdoc+xml": { + "source": "apache", + "compressible": true, + "extensions": ["omdoc"] + }, + "application/onenote": { + "source": "apache", + "extensions": ["onetoc","onetoc2","onetmp","onepkg"] + }, + "application/opc-nodeset+xml": { + "source": "iana", + "compressible": true + }, + "application/oscore": { + "source": "iana" + }, + "application/oxps": { + "source": "iana", + "extensions": ["oxps"] + }, + "application/p21": { + "source": "iana" + }, + "application/p21+zip": { + "source": "iana", + "compressible": false + }, + "application/p2p-overlay+xml": { + "source": "iana", + "compressible": true, + "extensions": ["relo"] + }, + "application/parityfec": { + "source": "iana" + }, + "application/passport": { + "source": "iana" + }, + "application/patch-ops-error+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xer"] + }, + "application/pdf": { + "source": "iana", + "compressible": false, + "extensions": ["pdf"] + }, + "application/pdx": { + "source": "iana" + }, + "application/pem-certificate-chain": { + "source": "iana" + }, + "application/pgp-encrypted": { + "source": "iana", + "compressible": false, + "extensions": ["pgp"] + }, + "application/pgp-keys": { + "source": "iana", + "extensions": ["asc"] + }, + "application/pgp-signature": { + "source": "iana", + "extensions": ["asc","sig"] + }, + "application/pics-rules": { + "source": "apache", + "extensions": ["prf"] + }, + "application/pidf+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/pidf-diff+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/pkcs10": { + "source": "iana", + "extensions": ["p10"] + }, + "application/pkcs12": { + "source": "iana" + }, + "application/pkcs7-mime": { + "source": "iana", + "extensions": ["p7m","p7c"] + }, + "application/pkcs7-signature": { + "source": "iana", + "extensions": ["p7s"] + }, + "application/pkcs8": { + "source": "iana", + "extensions": ["p8"] + }, + "application/pkcs8-encrypted": { + "source": "iana" + }, + "application/pkix-attr-cert": { + "source": "iana", + "extensions": ["ac"] + }, + "application/pkix-cert": { + "source": "iana", + "extensions": ["cer"] + }, + "application/pkix-crl": { + "source": "iana", + "extensions": ["crl"] + }, + "application/pkix-pkipath": { + "source": "iana", + "extensions": ["pkipath"] + }, + "application/pkixcmp": { + "source": "iana", + "extensions": ["pki"] + }, + "application/pls+xml": { + "source": "iana", + "compressible": true, + "extensions": ["pls"] + }, + "application/poc-settings+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/postscript": { + "source": "iana", + "compressible": true, + "extensions": ["ai","eps","ps"] + }, + "application/ppsp-tracker+json": { + "source": "iana", + "compressible": true + }, + "application/problem+json": { + "source": "iana", + "compressible": true + }, + "application/problem+xml": { + "source": "iana", + "compressible": true + }, + "application/provenance+xml": { + "source": "iana", + "compressible": true, + "extensions": ["provx"] + }, + "application/prs.alvestrand.titrax-sheet": { + "source": "iana" + }, + "application/prs.cww": { + "source": "iana", + "extensions": ["cww"] + }, + "application/prs.cyn": { + "source": "iana", + "charset": "7-BIT" + }, + "application/prs.hpub+zip": { + "source": "iana", + "compressible": false + }, + "application/prs.nprend": { + "source": "iana" + }, + "application/prs.plucker": { + "source": "iana" + }, + "application/prs.rdf-xml-crypt": { + "source": "iana" + }, + "application/prs.xsf+xml": { + "source": "iana", + "compressible": true + }, + "application/pskc+xml": { + "source": "iana", + "compressible": true, + "extensions": ["pskcxml"] + }, + "application/pvd+json": { + "source": "iana", + "compressible": true + }, + "application/qsig": { + "source": "iana" + }, + "application/raml+yaml": { + "compressible": true, + "extensions": ["raml"] + }, + "application/raptorfec": { + "source": "iana" + }, + "application/rdap+json": { + "source": "iana", + "compressible": true + }, + "application/rdf+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rdf","owl"] + }, + "application/reginfo+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rif"] + }, + "application/relax-ng-compact-syntax": { + "source": "iana", + "extensions": ["rnc"] + }, + "application/remote-printing": { + "source": "iana" + }, + "application/reputon+json": { + "source": "iana", + "compressible": true + }, + "application/resource-lists+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rl"] + }, + "application/resource-lists-diff+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rld"] + }, + "application/rfc+xml": { + "source": "iana", + "compressible": true + }, + "application/riscos": { + "source": "iana" + }, + "application/rlmi+xml": { + "source": "iana", + "compressible": true + }, + "application/rls-services+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rs"] + }, + "application/route-apd+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rapd"] + }, + "application/route-s-tsid+xml": { + "source": "iana", + "compressible": true, + "extensions": ["sls"] + }, + "application/route-usd+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rusd"] + }, + "application/rpki-ghostbusters": { + "source": "iana", + "extensions": ["gbr"] + }, + "application/rpki-manifest": { + "source": "iana", + "extensions": ["mft"] + }, + "application/rpki-publication": { + "source": "iana" + }, + "application/rpki-roa": { + "source": "iana", + "extensions": ["roa"] + }, + "application/rpki-updown": { + "source": "iana" + }, + "application/rsd+xml": { + "source": "apache", + "compressible": true, + "extensions": ["rsd"] + }, + "application/rss+xml": { + "source": "apache", + "compressible": true, + "extensions": ["rss"] + }, + "application/rtf": { + "source": "iana", + "compressible": true, + "extensions": ["rtf"] + }, + "application/rtploopback": { + "source": "iana" + }, + "application/rtx": { + "source": "iana" + }, + "application/samlassertion+xml": { + "source": "iana", + "compressible": true + }, + "application/samlmetadata+xml": { + "source": "iana", + "compressible": true + }, + "application/sarif+json": { + "source": "iana", + "compressible": true + }, + "application/sarif-external-properties+json": { + "source": "iana", + "compressible": true + }, + "application/sbe": { + "source": "iana" + }, + "application/sbml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["sbml"] + }, + "application/scaip+xml": { + "source": "iana", + "compressible": true + }, + "application/scim+json": { + "source": "iana", + "compressible": true + }, + "application/scvp-cv-request": { + "source": "iana", + "extensions": ["scq"] + }, + "application/scvp-cv-response": { + "source": "iana", + "extensions": ["scs"] + }, + "application/scvp-vp-request": { + "source": "iana", + "extensions": ["spq"] + }, + "application/scvp-vp-response": { + "source": "iana", + "extensions": ["spp"] + }, + "application/sdp": { + "source": "iana", + "extensions": ["sdp"] + }, + "application/secevent+jwt": { + "source": "iana" + }, + "application/senml+cbor": { + "source": "iana" + }, + "application/senml+json": { + "source": "iana", + "compressible": true + }, + "application/senml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["senmlx"] + }, + "application/senml-etch+cbor": { + "source": "iana" + }, + "application/senml-etch+json": { + "source": "iana", + "compressible": true + }, + "application/senml-exi": { + "source": "iana" + }, + "application/sensml+cbor": { + "source": "iana" + }, + "application/sensml+json": { + "source": "iana", + "compressible": true + }, + "application/sensml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["sensmlx"] + }, + "application/sensml-exi": { + "source": "iana" + }, + "application/sep+xml": { + "source": "iana", + "compressible": true + }, + "application/sep-exi": { + "source": "iana" + }, + "application/session-info": { + "source": "iana" + }, + "application/set-payment": { + "source": "iana" + }, + "application/set-payment-initiation": { + "source": "iana", + "extensions": ["setpay"] + }, + "application/set-registration": { + "source": "iana" + }, + "application/set-registration-initiation": { + "source": "iana", + "extensions": ["setreg"] + }, + "application/sgml": { + "source": "iana" + }, + "application/sgml-open-catalog": { + "source": "iana" + }, + "application/shf+xml": { + "source": "iana", + "compressible": true, + "extensions": ["shf"] + }, + "application/sieve": { + "source": "iana", + "extensions": ["siv","sieve"] + }, + "application/simple-filter+xml": { + "source": "iana", + "compressible": true + }, + "application/simple-message-summary": { + "source": "iana" + }, + "application/simplesymbolcontainer": { + "source": "iana" + }, + "application/sipc": { + "source": "iana" + }, + "application/slate": { + "source": "iana" + }, + "application/smil": { + "source": "iana" + }, + "application/smil+xml": { + "source": "iana", + "compressible": true, + "extensions": ["smi","smil"] + }, + "application/smpte336m": { + "source": "iana" + }, + "application/soap+fastinfoset": { + "source": "iana" + }, + "application/soap+xml": { + "source": "iana", + "compressible": true + }, + "application/sparql-query": { + "source": "iana", + "extensions": ["rq"] + }, + "application/sparql-results+xml": { + "source": "iana", + "compressible": true, + "extensions": ["srx"] + }, + "application/spdx+json": { + "source": "iana", + "compressible": true + }, + "application/spirits-event+xml": { + "source": "iana", + "compressible": true + }, + "application/sql": { + "source": "iana" + }, + "application/srgs": { + "source": "iana", + "extensions": ["gram"] + }, + "application/srgs+xml": { + "source": "iana", + "compressible": true, + "extensions": ["grxml"] + }, + "application/sru+xml": { + "source": "iana", + "compressible": true, + "extensions": ["sru"] + }, + "application/ssdl+xml": { + "source": "apache", + "compressible": true, + "extensions": ["ssdl"] + }, + "application/ssml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["ssml"] + }, + "application/stix+json": { + "source": "iana", + "compressible": true + }, + "application/swid+xml": { + "source": "iana", + "compressible": true, + "extensions": ["swidtag"] + }, + "application/tamp-apex-update": { + "source": "iana" + }, + "application/tamp-apex-update-confirm": { + "source": "iana" + }, + "application/tamp-community-update": { + "source": "iana" + }, + "application/tamp-community-update-confirm": { + "source": "iana" + }, + "application/tamp-error": { + "source": "iana" + }, + "application/tamp-sequence-adjust": { + "source": "iana" + }, + "application/tamp-sequence-adjust-confirm": { + "source": "iana" + }, + "application/tamp-status-query": { + "source": "iana" + }, + "application/tamp-status-response": { + "source": "iana" + }, + "application/tamp-update": { + "source": "iana" + }, + "application/tamp-update-confirm": { + "source": "iana" + }, + "application/tar": { + "compressible": true + }, + "application/taxii+json": { + "source": "iana", + "compressible": true + }, + "application/td+json": { + "source": "iana", + "compressible": true + }, + "application/tei+xml": { + "source": "iana", + "compressible": true, + "extensions": ["tei","teicorpus"] + }, + "application/tetra_isi": { + "source": "iana" + }, + "application/thraud+xml": { + "source": "iana", + "compressible": true, + "extensions": ["tfi"] + }, + "application/timestamp-query": { + "source": "iana" + }, + "application/timestamp-reply": { + "source": "iana" + }, + "application/timestamped-data": { + "source": "iana", + "extensions": ["tsd"] + }, + "application/tlsrpt+gzip": { + "source": "iana" + }, + "application/tlsrpt+json": { + "source": "iana", + "compressible": true + }, + "application/tnauthlist": { + "source": "iana" + }, + "application/token-introspection+jwt": { + "source": "iana" + }, + "application/toml": { + "compressible": true, + "extensions": ["toml"] + }, + "application/trickle-ice-sdpfrag": { + "source": "iana" + }, + "application/trig": { + "source": "iana", + "extensions": ["trig"] + }, + "application/ttml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["ttml"] + }, + "application/tve-trigger": { + "source": "iana" + }, + "application/tzif": { + "source": "iana" + }, + "application/tzif-leap": { + "source": "iana" + }, + "application/ubjson": { + "compressible": false, + "extensions": ["ubj"] + }, + "application/ulpfec": { + "source": "iana" + }, + "application/urc-grpsheet+xml": { + "source": "iana", + "compressible": true + }, + "application/urc-ressheet+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rsheet"] + }, + "application/urc-targetdesc+xml": { + "source": "iana", + "compressible": true, + "extensions": ["td"] + }, + "application/urc-uisocketdesc+xml": { + "source": "iana", + "compressible": true + }, + "application/vcard+json": { + "source": "iana", + "compressible": true + }, + "application/vcard+xml": { + "source": "iana", + "compressible": true + }, + "application/vemmi": { + "source": "iana" + }, + "application/vividence.scriptfile": { + "source": "apache" + }, + "application/vnd.1000minds.decision-model+xml": { + "source": "iana", + "compressible": true, + "extensions": ["1km"] + }, + "application/vnd.3gpp-prose+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp-prose-pc3ch+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp-v2x-local-service-information": { + "source": "iana" + }, + "application/vnd.3gpp.5gnas": { + "source": "iana" + }, + "application/vnd.3gpp.access-transfer-events+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.bsf+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.gmop+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.gtpc": { + "source": "iana" + }, + "application/vnd.3gpp.interworking-data": { + "source": "iana" + }, + "application/vnd.3gpp.lpp": { + "source": "iana" + }, + "application/vnd.3gpp.mc-signalling-ear": { + "source": "iana" + }, + "application/vnd.3gpp.mcdata-affiliation-command+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcdata-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcdata-payload": { + "source": "iana" + }, + "application/vnd.3gpp.mcdata-service-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcdata-signalling": { + "source": "iana" + }, + "application/vnd.3gpp.mcdata-ue-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcdata-user-profile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-affiliation-command+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-floor-request+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-location-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-mbms-usage-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-service-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-signed+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-ue-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-ue-init-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-user-profile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-affiliation-command+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-affiliation-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-location-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-mbms-usage-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-service-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-transmission-request+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-ue-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-user-profile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mid-call+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.ngap": { + "source": "iana" + }, + "application/vnd.3gpp.pfcp": { + "source": "iana" + }, + "application/vnd.3gpp.pic-bw-large": { + "source": "iana", + "extensions": ["plb"] + }, + "application/vnd.3gpp.pic-bw-small": { + "source": "iana", + "extensions": ["psb"] + }, + "application/vnd.3gpp.pic-bw-var": { + "source": "iana", + "extensions": ["pvb"] + }, + "application/vnd.3gpp.s1ap": { + "source": "iana" + }, + "application/vnd.3gpp.sms": { + "source": "iana" + }, + "application/vnd.3gpp.sms+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.srvcc-ext+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.srvcc-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.state-and-event-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.ussd+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp2.bcmcsinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp2.sms": { + "source": "iana" + }, + "application/vnd.3gpp2.tcap": { + "source": "iana", + "extensions": ["tcap"] + }, + "application/vnd.3lightssoftware.imagescal": { + "source": "iana" + }, + "application/vnd.3m.post-it-notes": { + "source": "iana", + "extensions": ["pwn"] + }, + "application/vnd.accpac.simply.aso": { + "source": "iana", + "extensions": ["aso"] + }, + "application/vnd.accpac.simply.imp": { + "source": "iana", + "extensions": ["imp"] + }, + "application/vnd.acucobol": { + "source": "iana", + "extensions": ["acu"] + }, + "application/vnd.acucorp": { + "source": "iana", + "extensions": ["atc","acutc"] + }, + "application/vnd.adobe.air-application-installer-package+zip": { + "source": "apache", + "compressible": false, + "extensions": ["air"] + }, + "application/vnd.adobe.flash.movie": { + "source": "iana" + }, + "application/vnd.adobe.formscentral.fcdt": { + "source": "iana", + "extensions": ["fcdt"] + }, + "application/vnd.adobe.fxp": { + "source": "iana", + "extensions": ["fxp","fxpl"] + }, + "application/vnd.adobe.partial-upload": { + "source": "iana" + }, + "application/vnd.adobe.xdp+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xdp"] + }, + "application/vnd.adobe.xfdf": { + "source": "iana", + "extensions": ["xfdf"] + }, + "application/vnd.aether.imp": { + "source": "iana" + }, + "application/vnd.afpc.afplinedata": { + "source": "iana" + }, + "application/vnd.afpc.afplinedata-pagedef": { + "source": "iana" + }, + "application/vnd.afpc.cmoca-cmresource": { + "source": "iana" + }, + "application/vnd.afpc.foca-charset": { + "source": "iana" + }, + "application/vnd.afpc.foca-codedfont": { + "source": "iana" + }, + "application/vnd.afpc.foca-codepage": { + "source": "iana" + }, + "application/vnd.afpc.modca": { + "source": "iana" + }, + "application/vnd.afpc.modca-cmtable": { + "source": "iana" + }, + "application/vnd.afpc.modca-formdef": { + "source": "iana" + }, + "application/vnd.afpc.modca-mediummap": { + "source": "iana" + }, + "application/vnd.afpc.modca-objectcontainer": { + "source": "iana" + }, + "application/vnd.afpc.modca-overlay": { + "source": "iana" + }, + "application/vnd.afpc.modca-pagesegment": { + "source": "iana" + }, + "application/vnd.age": { + "source": "iana", + "extensions": ["age"] + }, + "application/vnd.ah-barcode": { + "source": "iana" + }, + "application/vnd.ahead.space": { + "source": "iana", + "extensions": ["ahead"] + }, + "application/vnd.airzip.filesecure.azf": { + "source": "iana", + "extensions": ["azf"] + }, + "application/vnd.airzip.filesecure.azs": { + "source": "iana", + "extensions": ["azs"] + }, + "application/vnd.amadeus+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.amazon.ebook": { + "source": "apache", + "extensions": ["azw"] + }, + "application/vnd.amazon.mobi8-ebook": { + "source": "iana" + }, + "application/vnd.americandynamics.acc": { + "source": "iana", + "extensions": ["acc"] + }, + "application/vnd.amiga.ami": { + "source": "iana", + "extensions": ["ami"] + }, + "application/vnd.amundsen.maze+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.android.ota": { + "source": "iana" + }, + "application/vnd.android.package-archive": { + "source": "apache", + "compressible": false, + "extensions": ["apk"] + }, + "application/vnd.anki": { + "source": "iana" + }, + "application/vnd.anser-web-certificate-issue-initiation": { + "source": "iana", + "extensions": ["cii"] + }, + "application/vnd.anser-web-funds-transfer-initiation": { + "source": "apache", + "extensions": ["fti"] + }, + "application/vnd.antix.game-component": { + "source": "iana", + "extensions": ["atx"] + }, + "application/vnd.apache.arrow.file": { + "source": "iana" + }, + "application/vnd.apache.arrow.stream": { + "source": "iana" + }, + "application/vnd.apache.thrift.binary": { + "source": "iana" + }, + "application/vnd.apache.thrift.compact": { + "source": "iana" + }, + "application/vnd.apache.thrift.json": { + "source": "iana" + }, + "application/vnd.api+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.aplextor.warrp+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.apothekende.reservation+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.apple.installer+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mpkg"] + }, + "application/vnd.apple.keynote": { + "source": "iana", + "extensions": ["key"] + }, + "application/vnd.apple.mpegurl": { + "source": "iana", + "extensions": ["m3u8"] + }, + "application/vnd.apple.numbers": { + "source": "iana", + "extensions": ["numbers"] + }, + "application/vnd.apple.pages": { + "source": "iana", + "extensions": ["pages"] + }, + "application/vnd.apple.pkpass": { + "compressible": false, + "extensions": ["pkpass"] + }, + "application/vnd.arastra.swi": { + "source": "iana" + }, + "application/vnd.aristanetworks.swi": { + "source": "iana", + "extensions": ["swi"] + }, + "application/vnd.artisan+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.artsquare": { + "source": "iana" + }, + "application/vnd.astraea-software.iota": { + "source": "iana", + "extensions": ["iota"] + }, + "application/vnd.audiograph": { + "source": "iana", + "extensions": ["aep"] + }, + "application/vnd.autopackage": { + "source": "iana" + }, + "application/vnd.avalon+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.avistar+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.balsamiq.bmml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["bmml"] + }, + "application/vnd.balsamiq.bmpr": { + "source": "iana" + }, + "application/vnd.banana-accounting": { + "source": "iana" + }, + "application/vnd.bbf.usp.error": { + "source": "iana" + }, + "application/vnd.bbf.usp.msg": { + "source": "iana" + }, + "application/vnd.bbf.usp.msg+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.bekitzur-stech+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.bint.med-content": { + "source": "iana" + }, + "application/vnd.biopax.rdf+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.blink-idb-value-wrapper": { + "source": "iana" + }, + "application/vnd.blueice.multipass": { + "source": "iana", + "extensions": ["mpm"] + }, + "application/vnd.bluetooth.ep.oob": { + "source": "iana" + }, + "application/vnd.bluetooth.le.oob": { + "source": "iana" + }, + "application/vnd.bmi": { + "source": "iana", + "extensions": ["bmi"] + }, + "application/vnd.bpf": { + "source": "iana" + }, + "application/vnd.bpf3": { + "source": "iana" + }, + "application/vnd.businessobjects": { + "source": "iana", + "extensions": ["rep"] + }, + "application/vnd.byu.uapi+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.cab-jscript": { + "source": "iana" + }, + "application/vnd.canon-cpdl": { + "source": "iana" + }, + "application/vnd.canon-lips": { + "source": "iana" + }, + "application/vnd.capasystems-pg+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.cendio.thinlinc.clientconf": { + "source": "iana" + }, + "application/vnd.century-systems.tcp_stream": { + "source": "iana" + }, + "application/vnd.chemdraw+xml": { + "source": "iana", + "compressible": true, + "extensions": ["cdxml"] + }, + "application/vnd.chess-pgn": { + "source": "iana" + }, + "application/vnd.chipnuts.karaoke-mmd": { + "source": "iana", + "extensions": ["mmd"] + }, + "application/vnd.ciedi": { + "source": "iana" + }, + "application/vnd.cinderella": { + "source": "iana", + "extensions": ["cdy"] + }, + "application/vnd.cirpack.isdn-ext": { + "source": "iana" + }, + "application/vnd.citationstyles.style+xml": { + "source": "iana", + "compressible": true, + "extensions": ["csl"] + }, + "application/vnd.claymore": { + "source": "iana", + "extensions": ["cla"] + }, + "application/vnd.cloanto.rp9": { + "source": "iana", + "extensions": ["rp9"] + }, + "application/vnd.clonk.c4group": { + "source": "iana", + "extensions": ["c4g","c4d","c4f","c4p","c4u"] + }, + "application/vnd.cluetrust.cartomobile-config": { + "source": "iana", + "extensions": ["c11amc"] + }, + "application/vnd.cluetrust.cartomobile-config-pkg": { + "source": "iana", + "extensions": ["c11amz"] + }, + "application/vnd.coffeescript": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.document": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.document-template": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.presentation": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.presentation-template": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.spreadsheet": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.spreadsheet-template": { + "source": "iana" + }, + "application/vnd.collection+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.collection.doc+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.collection.next+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.comicbook+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.comicbook-rar": { + "source": "iana" + }, + "application/vnd.commerce-battelle": { + "source": "iana" + }, + "application/vnd.commonspace": { + "source": "iana", + "extensions": ["csp"] + }, + "application/vnd.contact.cmsg": { + "source": "iana", + "extensions": ["cdbcmsg"] + }, + "application/vnd.coreos.ignition+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.cosmocaller": { + "source": "iana", + "extensions": ["cmc"] + }, + "application/vnd.crick.clicker": { + "source": "iana", + "extensions": ["clkx"] + }, + "application/vnd.crick.clicker.keyboard": { + "source": "iana", + "extensions": ["clkk"] + }, + "application/vnd.crick.clicker.palette": { + "source": "iana", + "extensions": ["clkp"] + }, + "application/vnd.crick.clicker.template": { + "source": "iana", + "extensions": ["clkt"] + }, + "application/vnd.crick.clicker.wordbank": { + "source": "iana", + "extensions": ["clkw"] + }, + "application/vnd.criticaltools.wbs+xml": { + "source": "iana", + "compressible": true, + "extensions": ["wbs"] + }, + "application/vnd.cryptii.pipe+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.crypto-shade-file": { + "source": "iana" + }, + "application/vnd.cryptomator.encrypted": { + "source": "iana" + }, + "application/vnd.cryptomator.vault": { + "source": "iana" + }, + "application/vnd.ctc-posml": { + "source": "iana", + "extensions": ["pml"] + }, + "application/vnd.ctct.ws+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.cups-pdf": { + "source": "iana" + }, + "application/vnd.cups-postscript": { + "source": "iana" + }, + "application/vnd.cups-ppd": { + "source": "iana", + "extensions": ["ppd"] + }, + "application/vnd.cups-raster": { + "source": "iana" + }, + "application/vnd.cups-raw": { + "source": "iana" + }, + "application/vnd.curl": { + "source": "iana" + }, + "application/vnd.curl.car": { + "source": "apache", + "extensions": ["car"] + }, + "application/vnd.curl.pcurl": { + "source": "apache", + "extensions": ["pcurl"] + }, + "application/vnd.cyan.dean.root+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.cybank": { + "source": "iana" + }, + "application/vnd.cyclonedx+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.cyclonedx+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.d2l.coursepackage1p0+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.d3m-dataset": { + "source": "iana" + }, + "application/vnd.d3m-problem": { + "source": "iana" + }, + "application/vnd.dart": { + "source": "iana", + "compressible": true, + "extensions": ["dart"] + }, + "application/vnd.data-vision.rdz": { + "source": "iana", + "extensions": ["rdz"] + }, + "application/vnd.datapackage+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.dataresource+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.dbf": { + "source": "iana", + "extensions": ["dbf"] + }, + "application/vnd.debian.binary-package": { + "source": "iana" + }, + "application/vnd.dece.data": { + "source": "iana", + "extensions": ["uvf","uvvf","uvd","uvvd"] + }, + "application/vnd.dece.ttml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["uvt","uvvt"] + }, + "application/vnd.dece.unspecified": { + "source": "iana", + "extensions": ["uvx","uvvx"] + }, + "application/vnd.dece.zip": { + "source": "iana", + "extensions": ["uvz","uvvz"] + }, + "application/vnd.denovo.fcselayout-link": { + "source": "iana", + "extensions": ["fe_launch"] + }, + "application/vnd.desmume.movie": { + "source": "iana" + }, + "application/vnd.dir-bi.plate-dl-nosuffix": { + "source": "iana" + }, + "application/vnd.dm.delegation+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dna": { + "source": "iana", + "extensions": ["dna"] + }, + "application/vnd.document+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.dolby.mlp": { + "source": "apache", + "extensions": ["mlp"] + }, + "application/vnd.dolby.mobile.1": { + "source": "iana" + }, + "application/vnd.dolby.mobile.2": { + "source": "iana" + }, + "application/vnd.doremir.scorecloud-binary-document": { + "source": "iana" + }, + "application/vnd.dpgraph": { + "source": "iana", + "extensions": ["dpg"] + }, + "application/vnd.dreamfactory": { + "source": "iana", + "extensions": ["dfac"] + }, + "application/vnd.drive+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ds-keypoint": { + "source": "apache", + "extensions": ["kpxx"] + }, + "application/vnd.dtg.local": { + "source": "iana" + }, + "application/vnd.dtg.local.flash": { + "source": "iana" + }, + "application/vnd.dtg.local.html": { + "source": "iana" + }, + "application/vnd.dvb.ait": { + "source": "iana", + "extensions": ["ait"] + }, + "application/vnd.dvb.dvbisl+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.dvbj": { + "source": "iana" + }, + "application/vnd.dvb.esgcontainer": { + "source": "iana" + }, + "application/vnd.dvb.ipdcdftnotifaccess": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgaccess": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgaccess2": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgpdd": { + "source": "iana" + }, + "application/vnd.dvb.ipdcroaming": { + "source": "iana" + }, + "application/vnd.dvb.iptv.alfec-base": { + "source": "iana" + }, + "application/vnd.dvb.iptv.alfec-enhancement": { + "source": "iana" + }, + "application/vnd.dvb.notif-aggregate-root+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-container+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-generic+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-ia-msglist+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-ia-registration-request+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-ia-registration-response+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-init+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.pfr": { + "source": "iana" + }, + "application/vnd.dvb.service": { + "source": "iana", + "extensions": ["svc"] + }, + "application/vnd.dxr": { + "source": "iana" + }, + "application/vnd.dynageo": { + "source": "iana", + "extensions": ["geo"] + }, + "application/vnd.dzr": { + "source": "iana" + }, + "application/vnd.easykaraoke.cdgdownload": { + "source": "iana" + }, + "application/vnd.ecdis-update": { + "source": "iana" + }, + "application/vnd.ecip.rlp": { + "source": "iana" + }, + "application/vnd.eclipse.ditto+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ecowin.chart": { + "source": "iana", + "extensions": ["mag"] + }, + "application/vnd.ecowin.filerequest": { + "source": "iana" + }, + "application/vnd.ecowin.fileupdate": { + "source": "iana" + }, + "application/vnd.ecowin.series": { + "source": "iana" + }, + "application/vnd.ecowin.seriesrequest": { + "source": "iana" + }, + "application/vnd.ecowin.seriesupdate": { + "source": "iana" + }, + "application/vnd.efi.img": { + "source": "iana" + }, + "application/vnd.efi.iso": { + "source": "iana" + }, + "application/vnd.emclient.accessrequest+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.enliven": { + "source": "iana", + "extensions": ["nml"] + }, + "application/vnd.enphase.envoy": { + "source": "iana" + }, + "application/vnd.eprints.data+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.epson.esf": { + "source": "iana", + "extensions": ["esf"] + }, + "application/vnd.epson.msf": { + "source": "iana", + "extensions": ["msf"] + }, + "application/vnd.epson.quickanime": { + "source": "iana", + "extensions": ["qam"] + }, + "application/vnd.epson.salt": { + "source": "iana", + "extensions": ["slt"] + }, + "application/vnd.epson.ssf": { + "source": "iana", + "extensions": ["ssf"] + }, + "application/vnd.ericsson.quickcall": { + "source": "iana" + }, + "application/vnd.espass-espass+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.eszigno3+xml": { + "source": "iana", + "compressible": true, + "extensions": ["es3","et3"] + }, + "application/vnd.etsi.aoc+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.asic-e+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.etsi.asic-s+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.etsi.cug+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvcommand+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvdiscovery+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvprofile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvsad-bc+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvsad-cod+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvsad-npvr+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvservice+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvsync+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvueprofile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.mcid+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.mheg5": { + "source": "iana" + }, + "application/vnd.etsi.overload-control-policy-dataset+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.pstn+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.sci+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.simservs+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.timestamp-token": { + "source": "iana" + }, + "application/vnd.etsi.tsl+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.tsl.der": { + "source": "iana" + }, + "application/vnd.eu.kasparian.car+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.eudora.data": { + "source": "iana" + }, + "application/vnd.evolv.ecig.profile": { + "source": "iana" + }, + "application/vnd.evolv.ecig.settings": { + "source": "iana" + }, + "application/vnd.evolv.ecig.theme": { + "source": "iana" + }, + "application/vnd.exstream-empower+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.exstream-package": { + "source": "iana" + }, + "application/vnd.ezpix-album": { + "source": "iana", + "extensions": ["ez2"] + }, + "application/vnd.ezpix-package": { + "source": "iana", + "extensions": ["ez3"] + }, + "application/vnd.f-secure.mobile": { + "source": "iana" + }, + "application/vnd.familysearch.gedcom+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.fastcopy-disk-image": { + "source": "iana" + }, + "application/vnd.fdf": { + "source": "iana", + "extensions": ["fdf"] + }, + "application/vnd.fdsn.mseed": { + "source": "iana", + "extensions": ["mseed"] + }, + "application/vnd.fdsn.seed": { + "source": "iana", + "extensions": ["seed","dataless"] + }, + "application/vnd.ffsns": { + "source": "iana" + }, + "application/vnd.ficlab.flb+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.filmit.zfc": { + "source": "iana" + }, + "application/vnd.fints": { + "source": "iana" + }, + "application/vnd.firemonkeys.cloudcell": { + "source": "iana" + }, + "application/vnd.flographit": { + "source": "iana", + "extensions": ["gph"] + }, + "application/vnd.fluxtime.clip": { + "source": "iana", + "extensions": ["ftc"] + }, + "application/vnd.font-fontforge-sfd": { + "source": "iana" + }, + "application/vnd.framemaker": { + "source": "iana", + "extensions": ["fm","frame","maker","book"] + }, + "application/vnd.frogans.fnc": { + "source": "iana", + "extensions": ["fnc"] + }, + "application/vnd.frogans.ltf": { + "source": "iana", + "extensions": ["ltf"] + }, + "application/vnd.fsc.weblaunch": { + "source": "iana", + "extensions": ["fsc"] + }, + "application/vnd.fujifilm.fb.docuworks": { + "source": "iana" + }, + "application/vnd.fujifilm.fb.docuworks.binder": { + "source": "iana" + }, + "application/vnd.fujifilm.fb.docuworks.container": { + "source": "iana" + }, + "application/vnd.fujifilm.fb.jfi+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.fujitsu.oasys": { + "source": "iana", + "extensions": ["oas"] + }, + "application/vnd.fujitsu.oasys2": { + "source": "iana", + "extensions": ["oa2"] + }, + "application/vnd.fujitsu.oasys3": { + "source": "iana", + "extensions": ["oa3"] + }, + "application/vnd.fujitsu.oasysgp": { + "source": "iana", + "extensions": ["fg5"] + }, + "application/vnd.fujitsu.oasysprs": { + "source": "iana", + "extensions": ["bh2"] + }, + "application/vnd.fujixerox.art-ex": { + "source": "iana" + }, + "application/vnd.fujixerox.art4": { + "source": "iana" + }, + "application/vnd.fujixerox.ddd": { + "source": "iana", + "extensions": ["ddd"] + }, + "application/vnd.fujixerox.docuworks": { + "source": "iana", + "extensions": ["xdw"] + }, + "application/vnd.fujixerox.docuworks.binder": { + "source": "iana", + "extensions": ["xbd"] + }, + "application/vnd.fujixerox.docuworks.container": { + "source": "iana" + }, + "application/vnd.fujixerox.hbpl": { + "source": "iana" + }, + "application/vnd.fut-misnet": { + "source": "iana" + }, + "application/vnd.futoin+cbor": { + "source": "iana" + }, + "application/vnd.futoin+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.fuzzysheet": { + "source": "iana", + "extensions": ["fzs"] + }, + "application/vnd.genomatix.tuxedo": { + "source": "iana", + "extensions": ["txd"] + }, + "application/vnd.gentics.grd+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.geo+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.geocube+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.geogebra.file": { + "source": "iana", + "extensions": ["ggb"] + }, + "application/vnd.geogebra.slides": { + "source": "iana" + }, + "application/vnd.geogebra.tool": { + "source": "iana", + "extensions": ["ggt"] + }, + "application/vnd.geometry-explorer": { + "source": "iana", + "extensions": ["gex","gre"] + }, + "application/vnd.geonext": { + "source": "iana", + "extensions": ["gxt"] + }, + "application/vnd.geoplan": { + "source": "iana", + "extensions": ["g2w"] + }, + "application/vnd.geospace": { + "source": "iana", + "extensions": ["g3w"] + }, + "application/vnd.gerber": { + "source": "iana" + }, + "application/vnd.globalplatform.card-content-mgt": { + "source": "iana" + }, + "application/vnd.globalplatform.card-content-mgt-response": { + "source": "iana" + }, + "application/vnd.gmx": { + "source": "iana", + "extensions": ["gmx"] + }, + "application/vnd.google-apps.document": { + "compressible": false, + "extensions": ["gdoc"] + }, + "application/vnd.google-apps.presentation": { + "compressible": false, + "extensions": ["gslides"] + }, + "application/vnd.google-apps.spreadsheet": { + "compressible": false, + "extensions": ["gsheet"] + }, + "application/vnd.google-earth.kml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["kml"] + }, + "application/vnd.google-earth.kmz": { + "source": "iana", + "compressible": false, + "extensions": ["kmz"] + }, + "application/vnd.gov.sk.e-form+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.gov.sk.e-form+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.gov.sk.xmldatacontainer+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.grafeq": { + "source": "iana", + "extensions": ["gqf","gqs"] + }, + "application/vnd.gridmp": { + "source": "iana" + }, + "application/vnd.groove-account": { + "source": "iana", + "extensions": ["gac"] + }, + "application/vnd.groove-help": { + "source": "iana", + "extensions": ["ghf"] + }, + "application/vnd.groove-identity-message": { + "source": "iana", + "extensions": ["gim"] + }, + "application/vnd.groove-injector": { + "source": "iana", + "extensions": ["grv"] + }, + "application/vnd.groove-tool-message": { + "source": "iana", + "extensions": ["gtm"] + }, + "application/vnd.groove-tool-template": { + "source": "iana", + "extensions": ["tpl"] + }, + "application/vnd.groove-vcard": { + "source": "iana", + "extensions": ["vcg"] + }, + "application/vnd.hal+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hal+xml": { + "source": "iana", + "compressible": true, + "extensions": ["hal"] + }, + "application/vnd.handheld-entertainment+xml": { + "source": "iana", + "compressible": true, + "extensions": ["zmm"] + }, + "application/vnd.hbci": { + "source": "iana", + "extensions": ["hbci"] + }, + "application/vnd.hc+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hcl-bireports": { + "source": "iana" + }, + "application/vnd.hdt": { + "source": "iana" + }, + "application/vnd.heroku+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hhe.lesson-player": { + "source": "iana", + "extensions": ["les"] + }, + "application/vnd.hl7cda+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/vnd.hl7v2+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/vnd.hp-hpgl": { + "source": "iana", + "extensions": ["hpgl"] + }, + "application/vnd.hp-hpid": { + "source": "iana", + "extensions": ["hpid"] + }, + "application/vnd.hp-hps": { + "source": "iana", + "extensions": ["hps"] + }, + "application/vnd.hp-jlyt": { + "source": "iana", + "extensions": ["jlt"] + }, + "application/vnd.hp-pcl": { + "source": "iana", + "extensions": ["pcl"] + }, + "application/vnd.hp-pclxl": { + "source": "iana", + "extensions": ["pclxl"] + }, + "application/vnd.httphone": { + "source": "iana" + }, + "application/vnd.hydrostatix.sof-data": { + "source": "iana", + "extensions": ["sfd-hdstx"] + }, + "application/vnd.hyper+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hyper-item+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hyperdrive+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hzn-3d-crossword": { + "source": "iana" + }, + "application/vnd.ibm.afplinedata": { + "source": "iana" + }, + "application/vnd.ibm.electronic-media": { + "source": "iana" + }, + "application/vnd.ibm.minipay": { + "source": "iana", + "extensions": ["mpy"] + }, + "application/vnd.ibm.modcap": { + "source": "iana", + "extensions": ["afp","listafp","list3820"] + }, + "application/vnd.ibm.rights-management": { + "source": "iana", + "extensions": ["irm"] + }, + "application/vnd.ibm.secure-container": { + "source": "iana", + "extensions": ["sc"] + }, + "application/vnd.iccprofile": { + "source": "iana", + "extensions": ["icc","icm"] + }, + "application/vnd.ieee.1905": { + "source": "iana" + }, + "application/vnd.igloader": { + "source": "iana", + "extensions": ["igl"] + }, + "application/vnd.imagemeter.folder+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.imagemeter.image+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.immervision-ivp": { + "source": "iana", + "extensions": ["ivp"] + }, + "application/vnd.immervision-ivu": { + "source": "iana", + "extensions": ["ivu"] + }, + "application/vnd.ims.imsccv1p1": { + "source": "iana" + }, + "application/vnd.ims.imsccv1p2": { + "source": "iana" + }, + "application/vnd.ims.imsccv1p3": { + "source": "iana" + }, + "application/vnd.ims.lis.v2.result+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolconsumerprofile+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolproxy+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolproxy.id+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolsettings+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolsettings.simple+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.informedcontrol.rms+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.informix-visionary": { + "source": "iana" + }, + "application/vnd.infotech.project": { + "source": "iana" + }, + "application/vnd.infotech.project+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.innopath.wamp.notification": { + "source": "iana" + }, + "application/vnd.insors.igm": { + "source": "iana", + "extensions": ["igm"] + }, + "application/vnd.intercon.formnet": { + "source": "iana", + "extensions": ["xpw","xpx"] + }, + "application/vnd.intergeo": { + "source": "iana", + "extensions": ["i2g"] + }, + "application/vnd.intertrust.digibox": { + "source": "iana" + }, + "application/vnd.intertrust.nncp": { + "source": "iana" + }, + "application/vnd.intu.qbo": { + "source": "iana", + "extensions": ["qbo"] + }, + "application/vnd.intu.qfx": { + "source": "iana", + "extensions": ["qfx"] + }, + "application/vnd.iptc.g2.catalogitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.conceptitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.knowledgeitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.newsitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.newsmessage+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.packageitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.planningitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.ipunplugged.rcprofile": { + "source": "iana", + "extensions": ["rcprofile"] + }, + "application/vnd.irepository.package+xml": { + "source": "iana", + "compressible": true, + "extensions": ["irp"] + }, + "application/vnd.is-xpr": { + "source": "iana", + "extensions": ["xpr"] + }, + "application/vnd.isac.fcs": { + "source": "iana", + "extensions": ["fcs"] + }, + "application/vnd.iso11783-10+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.jam": { + "source": "iana", + "extensions": ["jam"] + }, + "application/vnd.japannet-directory-service": { + "source": "iana" + }, + "application/vnd.japannet-jpnstore-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-payment-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-registration": { + "source": "iana" + }, + "application/vnd.japannet-registration-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-setstore-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-verification": { + "source": "iana" + }, + "application/vnd.japannet-verification-wakeup": { + "source": "iana" + }, + "application/vnd.jcp.javame.midlet-rms": { + "source": "iana", + "extensions": ["rms"] + }, + "application/vnd.jisp": { + "source": "iana", + "extensions": ["jisp"] + }, + "application/vnd.joost.joda-archive": { + "source": "iana", + "extensions": ["joda"] + }, + "application/vnd.jsk.isdn-ngn": { + "source": "iana" + }, + "application/vnd.kahootz": { + "source": "iana", + "extensions": ["ktz","ktr"] + }, + "application/vnd.kde.karbon": { + "source": "iana", + "extensions": ["karbon"] + }, + "application/vnd.kde.kchart": { + "source": "iana", + "extensions": ["chrt"] + }, + "application/vnd.kde.kformula": { + "source": "iana", + "extensions": ["kfo"] + }, + "application/vnd.kde.kivio": { + "source": "iana", + "extensions": ["flw"] + }, + "application/vnd.kde.kontour": { + "source": "iana", + "extensions": ["kon"] + }, + "application/vnd.kde.kpresenter": { + "source": "iana", + "extensions": ["kpr","kpt"] + }, + "application/vnd.kde.kspread": { + "source": "iana", + "extensions": ["ksp"] + }, + "application/vnd.kde.kword": { + "source": "iana", + "extensions": ["kwd","kwt"] + }, + "application/vnd.kenameaapp": { + "source": "iana", + "extensions": ["htke"] + }, + "application/vnd.kidspiration": { + "source": "iana", + "extensions": ["kia"] + }, + "application/vnd.kinar": { + "source": "iana", + "extensions": ["kne","knp"] + }, + "application/vnd.koan": { + "source": "iana", + "extensions": ["skp","skd","skt","skm"] + }, + "application/vnd.kodak-descriptor": { + "source": "iana", + "extensions": ["sse"] + }, + "application/vnd.las": { + "source": "iana" + }, + "application/vnd.las.las+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.las.las+xml": { + "source": "iana", + "compressible": true, + "extensions": ["lasxml"] + }, + "application/vnd.laszip": { + "source": "iana" + }, + "application/vnd.leap+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.liberty-request+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.llamagraphics.life-balance.desktop": { + "source": "iana", + "extensions": ["lbd"] + }, + "application/vnd.llamagraphics.life-balance.exchange+xml": { + "source": "iana", + "compressible": true, + "extensions": ["lbe"] + }, + "application/vnd.logipipe.circuit+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.loom": { + "source": "iana" + }, + "application/vnd.lotus-1-2-3": { + "source": "iana", + "extensions": ["123"] + }, + "application/vnd.lotus-approach": { + "source": "iana", + "extensions": ["apr"] + }, + "application/vnd.lotus-freelance": { + "source": "iana", + "extensions": ["pre"] + }, + "application/vnd.lotus-notes": { + "source": "iana", + "extensions": ["nsf"] + }, + "application/vnd.lotus-organizer": { + "source": "iana", + "extensions": ["org"] + }, + "application/vnd.lotus-screencam": { + "source": "iana", + "extensions": ["scm"] + }, + "application/vnd.lotus-wordpro": { + "source": "iana", + "extensions": ["lwp"] + }, + "application/vnd.macports.portpkg": { + "source": "iana", + "extensions": ["portpkg"] + }, + "application/vnd.mapbox-vector-tile": { + "source": "iana", + "extensions": ["mvt"] + }, + "application/vnd.marlin.drm.actiontoken+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.marlin.drm.conftoken+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.marlin.drm.license+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.marlin.drm.mdcf": { + "source": "iana" + }, + "application/vnd.mason+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.maxar.archive.3tz+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.maxmind.maxmind-db": { + "source": "iana" + }, + "application/vnd.mcd": { + "source": "iana", + "extensions": ["mcd"] + }, + "application/vnd.medcalcdata": { + "source": "iana", + "extensions": ["mc1"] + }, + "application/vnd.mediastation.cdkey": { + "source": "iana", + "extensions": ["cdkey"] + }, + "application/vnd.meridian-slingshot": { + "source": "iana" + }, + "application/vnd.mfer": { + "source": "iana", + "extensions": ["mwf"] + }, + "application/vnd.mfmp": { + "source": "iana", + "extensions": ["mfm"] + }, + "application/vnd.micro+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.micrografx.flo": { + "source": "iana", + "extensions": ["flo"] + }, + "application/vnd.micrografx.igx": { + "source": "iana", + "extensions": ["igx"] + }, + "application/vnd.microsoft.portable-executable": { + "source": "iana" + }, + "application/vnd.microsoft.windows.thumbnail-cache": { + "source": "iana" + }, + "application/vnd.miele+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.mif": { + "source": "iana", + "extensions": ["mif"] + }, + "application/vnd.minisoft-hp3000-save": { + "source": "iana" + }, + "application/vnd.mitsubishi.misty-guard.trustweb": { + "source": "iana" + }, + "application/vnd.mobius.daf": { + "source": "iana", + "extensions": ["daf"] + }, + "application/vnd.mobius.dis": { + "source": "iana", + "extensions": ["dis"] + }, + "application/vnd.mobius.mbk": { + "source": "iana", + "extensions": ["mbk"] + }, + "application/vnd.mobius.mqy": { + "source": "iana", + "extensions": ["mqy"] + }, + "application/vnd.mobius.msl": { + "source": "iana", + "extensions": ["msl"] + }, + "application/vnd.mobius.plc": { + "source": "iana", + "extensions": ["plc"] + }, + "application/vnd.mobius.txf": { + "source": "iana", + "extensions": ["txf"] + }, + "application/vnd.mophun.application": { + "source": "iana", + "extensions": ["mpn"] + }, + "application/vnd.mophun.certificate": { + "source": "iana", + "extensions": ["mpc"] + }, + "application/vnd.motorola.flexsuite": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.adsi": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.fis": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.gotap": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.kmr": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.ttc": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.wem": { + "source": "iana" + }, + "application/vnd.motorola.iprm": { + "source": "iana" + }, + "application/vnd.mozilla.xul+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xul"] + }, + "application/vnd.ms-3mfdocument": { + "source": "iana" + }, + "application/vnd.ms-artgalry": { + "source": "iana", + "extensions": ["cil"] + }, + "application/vnd.ms-asf": { + "source": "iana" + }, + "application/vnd.ms-cab-compressed": { + "source": "iana", + "extensions": ["cab"] + }, + "application/vnd.ms-color.iccprofile": { + "source": "apache" + }, + "application/vnd.ms-excel": { + "source": "iana", + "compressible": false, + "extensions": ["xls","xlm","xla","xlc","xlt","xlw"] + }, + "application/vnd.ms-excel.addin.macroenabled.12": { + "source": "iana", + "extensions": ["xlam"] + }, + "application/vnd.ms-excel.sheet.binary.macroenabled.12": { + "source": "iana", + "extensions": ["xlsb"] + }, + "application/vnd.ms-excel.sheet.macroenabled.12": { + "source": "iana", + "extensions": ["xlsm"] + }, + "application/vnd.ms-excel.template.macroenabled.12": { + "source": "iana", + "extensions": ["xltm"] + }, + "application/vnd.ms-fontobject": { + "source": "iana", + "compressible": true, + "extensions": ["eot"] + }, + "application/vnd.ms-htmlhelp": { + "source": "iana", + "extensions": ["chm"] + }, + "application/vnd.ms-ims": { + "source": "iana", + "extensions": ["ims"] + }, + "application/vnd.ms-lrm": { + "source": "iana", + "extensions": ["lrm"] + }, + "application/vnd.ms-office.activex+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.ms-officetheme": { + "source": "iana", + "extensions": ["thmx"] + }, + "application/vnd.ms-opentype": { + "source": "apache", + "compressible": true + }, + "application/vnd.ms-outlook": { + "compressible": false, + "extensions": ["msg"] + }, + "application/vnd.ms-package.obfuscated-opentype": { + "source": "apache" + }, + "application/vnd.ms-pki.seccat": { + "source": "apache", + "extensions": ["cat"] + }, + "application/vnd.ms-pki.stl": { + "source": "apache", + "extensions": ["stl"] + }, + "application/vnd.ms-playready.initiator+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.ms-powerpoint": { + "source": "iana", + "compressible": false, + "extensions": ["ppt","pps","pot"] + }, + "application/vnd.ms-powerpoint.addin.macroenabled.12": { + "source": "iana", + "extensions": ["ppam"] + }, + "application/vnd.ms-powerpoint.presentation.macroenabled.12": { + "source": "iana", + "extensions": ["pptm"] + }, + "application/vnd.ms-powerpoint.slide.macroenabled.12": { + "source": "iana", + "extensions": ["sldm"] + }, + "application/vnd.ms-powerpoint.slideshow.macroenabled.12": { + "source": "iana", + "extensions": ["ppsm"] + }, + "application/vnd.ms-powerpoint.template.macroenabled.12": { + "source": "iana", + "extensions": ["potm"] + }, + "application/vnd.ms-printdevicecapabilities+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.ms-printing.printticket+xml": { + "source": "apache", + "compressible": true + }, + "application/vnd.ms-printschematicket+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.ms-project": { + "source": "iana", + "extensions": ["mpp","mpt"] + }, + "application/vnd.ms-tnef": { + "source": "iana" + }, + "application/vnd.ms-windows.devicepairing": { + "source": "iana" + }, + "application/vnd.ms-windows.nwprinting.oob": { + "source": "iana" + }, + "application/vnd.ms-windows.printerpairing": { + "source": "iana" + }, + "application/vnd.ms-windows.wsd.oob": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.lic-chlg-req": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.lic-resp": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.meter-chlg-req": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.meter-resp": { + "source": "iana" + }, + "application/vnd.ms-word.document.macroenabled.12": { + "source": "iana", + "extensions": ["docm"] + }, + "application/vnd.ms-word.template.macroenabled.12": { + "source": "iana", + "extensions": ["dotm"] + }, + "application/vnd.ms-works": { + "source": "iana", + "extensions": ["wps","wks","wcm","wdb"] + }, + "application/vnd.ms-wpl": { + "source": "iana", + "extensions": ["wpl"] + }, + "application/vnd.ms-xpsdocument": { + "source": "iana", + "compressible": false, + "extensions": ["xps"] + }, + "application/vnd.msa-disk-image": { + "source": "iana" + }, + "application/vnd.mseq": { + "source": "iana", + "extensions": ["mseq"] + }, + "application/vnd.msign": { + "source": "iana" + }, + "application/vnd.multiad.creator": { + "source": "iana" + }, + "application/vnd.multiad.creator.cif": { + "source": "iana" + }, + "application/vnd.music-niff": { + "source": "iana" + }, + "application/vnd.musician": { + "source": "iana", + "extensions": ["mus"] + }, + "application/vnd.muvee.style": { + "source": "iana", + "extensions": ["msty"] + }, + "application/vnd.mynfc": { + "source": "iana", + "extensions": ["taglet"] + }, + "application/vnd.nacamar.ybrid+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ncd.control": { + "source": "iana" + }, + "application/vnd.ncd.reference": { + "source": "iana" + }, + "application/vnd.nearst.inv+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.nebumind.line": { + "source": "iana" + }, + "application/vnd.nervana": { + "source": "iana" + }, + "application/vnd.netfpx": { + "source": "iana" + }, + "application/vnd.neurolanguage.nlu": { + "source": "iana", + "extensions": ["nlu"] + }, + "application/vnd.nimn": { + "source": "iana" + }, + "application/vnd.nintendo.nitro.rom": { + "source": "iana" + }, + "application/vnd.nintendo.snes.rom": { + "source": "iana" + }, + "application/vnd.nitf": { + "source": "iana", + "extensions": ["ntf","nitf"] + }, + "application/vnd.noblenet-directory": { + "source": "iana", + "extensions": ["nnd"] + }, + "application/vnd.noblenet-sealer": { + "source": "iana", + "extensions": ["nns"] + }, + "application/vnd.noblenet-web": { + "source": "iana", + "extensions": ["nnw"] + }, + "application/vnd.nokia.catalogs": { + "source": "iana" + }, + "application/vnd.nokia.conml+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.conml+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.iptv.config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.isds-radio-presets": { + "source": "iana" + }, + "application/vnd.nokia.landmark+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.landmark+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.landmarkcollection+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.n-gage.ac+xml": { + "source": "iana", + "compressible": true, + "extensions": ["ac"] + }, + "application/vnd.nokia.n-gage.data": { + "source": "iana", + "extensions": ["ngdat"] + }, + "application/vnd.nokia.n-gage.symbian.install": { + "source": "iana", + "extensions": ["n-gage"] + }, + "application/vnd.nokia.ncd": { + "source": "iana" + }, + "application/vnd.nokia.pcd+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.pcd+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.radio-preset": { + "source": "iana", + "extensions": ["rpst"] + }, + "application/vnd.nokia.radio-presets": { + "source": "iana", + "extensions": ["rpss"] + }, + "application/vnd.novadigm.edm": { + "source": "iana", + "extensions": ["edm"] + }, + "application/vnd.novadigm.edx": { + "source": "iana", + "extensions": ["edx"] + }, + "application/vnd.novadigm.ext": { + "source": "iana", + "extensions": ["ext"] + }, + "application/vnd.ntt-local.content-share": { + "source": "iana" + }, + "application/vnd.ntt-local.file-transfer": { + "source": "iana" + }, + "application/vnd.ntt-local.ogw_remote-access": { + "source": "iana" + }, + "application/vnd.ntt-local.sip-ta_remote": { + "source": "iana" + }, + "application/vnd.ntt-local.sip-ta_tcp_stream": { + "source": "iana" + }, + "application/vnd.oasis.opendocument.chart": { + "source": "iana", + "extensions": ["odc"] + }, + "application/vnd.oasis.opendocument.chart-template": { + "source": "iana", + "extensions": ["otc"] + }, + "application/vnd.oasis.opendocument.database": { + "source": "iana", + "extensions": ["odb"] + }, + "application/vnd.oasis.opendocument.formula": { + "source": "iana", + "extensions": ["odf"] + }, + "application/vnd.oasis.opendocument.formula-template": { + "source": "iana", + "extensions": ["odft"] + }, + "application/vnd.oasis.opendocument.graphics": { + "source": "iana", + "compressible": false, + "extensions": ["odg"] + }, + "application/vnd.oasis.opendocument.graphics-template": { + "source": "iana", + "extensions": ["otg"] + }, + "application/vnd.oasis.opendocument.image": { + "source": "iana", + "extensions": ["odi"] + }, + "application/vnd.oasis.opendocument.image-template": { + "source": "iana", + "extensions": ["oti"] + }, + "application/vnd.oasis.opendocument.presentation": { + "source": "iana", + "compressible": false, + "extensions": ["odp"] + }, + "application/vnd.oasis.opendocument.presentation-template": { + "source": "iana", + "extensions": ["otp"] + }, + "application/vnd.oasis.opendocument.spreadsheet": { + "source": "iana", + "compressible": false, + "extensions": ["ods"] + }, + "application/vnd.oasis.opendocument.spreadsheet-template": { + "source": "iana", + "extensions": ["ots"] + }, + "application/vnd.oasis.opendocument.text": { + "source": "iana", + "compressible": false, + "extensions": ["odt"] + }, + "application/vnd.oasis.opendocument.text-master": { + "source": "iana", + "extensions": ["odm"] + }, + "application/vnd.oasis.opendocument.text-template": { + "source": "iana", + "extensions": ["ott"] + }, + "application/vnd.oasis.opendocument.text-web": { + "source": "iana", + "extensions": ["oth"] + }, + "application/vnd.obn": { + "source": "iana" + }, + "application/vnd.ocf+cbor": { + "source": "iana" + }, + "application/vnd.oci.image.manifest.v1+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.oftn.l10n+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.contentaccessdownload+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.contentaccessstreaming+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.cspg-hexbinary": { + "source": "iana" + }, + "application/vnd.oipf.dae.svg+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.dae.xhtml+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.mippvcontrolmessage+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.pae.gem": { + "source": "iana" + }, + "application/vnd.oipf.spdiscovery+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.spdlist+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.ueprofile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.userprofile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.olpc-sugar": { + "source": "iana", + "extensions": ["xo"] + }, + "application/vnd.oma-scws-config": { + "source": "iana" + }, + "application/vnd.oma-scws-http-request": { + "source": "iana" + }, + "application/vnd.oma-scws-http-response": { + "source": "iana" + }, + "application/vnd.oma.bcast.associated-procedure-parameter+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.drm-trigger+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.imd+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.ltkm": { + "source": "iana" + }, + "application/vnd.oma.bcast.notification+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.provisioningtrigger": { + "source": "iana" + }, + "application/vnd.oma.bcast.sgboot": { + "source": "iana" + }, + "application/vnd.oma.bcast.sgdd+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.sgdu": { + "source": "iana" + }, + "application/vnd.oma.bcast.simple-symbol-container": { + "source": "iana" + }, + "application/vnd.oma.bcast.smartcard-trigger+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.sprov+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.stkm": { + "source": "iana" + }, + "application/vnd.oma.cab-address-book+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.cab-feature-handler+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.cab-pcc+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.cab-subs-invite+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.cab-user-prefs+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.dcd": { + "source": "iana" + }, + "application/vnd.oma.dcdc": { + "source": "iana" + }, + "application/vnd.oma.dd2+xml": { + "source": "iana", + "compressible": true, + "extensions": ["dd2"] + }, + "application/vnd.oma.drm.risd+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.group-usage-list+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.lwm2m+cbor": { + "source": "iana" + }, + "application/vnd.oma.lwm2m+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.lwm2m+tlv": { + "source": "iana" + }, + "application/vnd.oma.pal+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.poc.detailed-progress-report+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.poc.final-report+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.poc.groups+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.poc.invocation-descriptor+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.poc.optimized-progress-report+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.push": { + "source": "iana" + }, + "application/vnd.oma.scidm.messages+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.xcap-directory+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.omads-email+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/vnd.omads-file+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/vnd.omads-folder+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/vnd.omaloc-supl-init": { + "source": "iana" + }, + "application/vnd.onepager": { + "source": "iana" + }, + "application/vnd.onepagertamp": { + "source": "iana" + }, + "application/vnd.onepagertamx": { + "source": "iana" + }, + "application/vnd.onepagertat": { + "source": "iana" + }, + "application/vnd.onepagertatp": { + "source": "iana" + }, + "application/vnd.onepagertatx": { + "source": "iana" + }, + "application/vnd.openblox.game+xml": { + "source": "iana", + "compressible": true, + "extensions": ["obgx"] + }, + "application/vnd.openblox.game-binary": { + "source": "iana" + }, + "application/vnd.openeye.oeb": { + "source": "iana" + }, + "application/vnd.openofficeorg.extension": { + "source": "apache", + "extensions": ["oxt"] + }, + "application/vnd.openstreetmap.data+xml": { + "source": "iana", + "compressible": true, + "extensions": ["osm"] + }, + "application/vnd.opentimestamps.ots": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.custom-properties+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.customxmlproperties+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawing+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.extended-properties+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.comments+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.presentation": { + "source": "iana", + "compressible": false, + "extensions": ["pptx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.presprops+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slide": { + "source": "iana", + "extensions": ["sldx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.slide+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideshow": { + "source": "iana", + "extensions": ["ppsx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.tags+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.template": { + "source": "iana", + "extensions": ["potx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.template.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": { + "source": "iana", + "compressible": false, + "extensions": ["xlsx"] + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.template": { + "source": "iana", + "extensions": ["xltx"] + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.theme+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.themeoverride+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.vmldrawing": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document": { + "source": "iana", + "compressible": false, + "extensions": ["docx"] + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.template": { + "source": "iana", + "extensions": ["dotx"] + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-package.core-properties+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-package.relationships+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oracle.resource+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.orange.indata": { + "source": "iana" + }, + "application/vnd.osa.netdeploy": { + "source": "iana" + }, + "application/vnd.osgeo.mapguide.package": { + "source": "iana", + "extensions": ["mgp"] + }, + "application/vnd.osgi.bundle": { + "source": "iana" + }, + "application/vnd.osgi.dp": { + "source": "iana", + "extensions": ["dp"] + }, + "application/vnd.osgi.subsystem": { + "source": "iana", + "extensions": ["esa"] + }, + "application/vnd.otps.ct-kip+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oxli.countgraph": { + "source": "iana" + }, + "application/vnd.pagerduty+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.palm": { + "source": "iana", + "extensions": ["pdb","pqa","oprc"] + }, + "application/vnd.panoply": { + "source": "iana" + }, + "application/vnd.paos.xml": { + "source": "iana" + }, + "application/vnd.patentdive": { + "source": "iana" + }, + "application/vnd.patientecommsdoc": { + "source": "iana" + }, + "application/vnd.pawaafile": { + "source": "iana", + "extensions": ["paw"] + }, + "application/vnd.pcos": { + "source": "iana" + }, + "application/vnd.pg.format": { + "source": "iana", + "extensions": ["str"] + }, + "application/vnd.pg.osasli": { + "source": "iana", + "extensions": ["ei6"] + }, + "application/vnd.piaccess.application-licence": { + "source": "iana" + }, + "application/vnd.picsel": { + "source": "iana", + "extensions": ["efif"] + }, + "application/vnd.pmi.widget": { + "source": "iana", + "extensions": ["wg"] + }, + "application/vnd.poc.group-advertisement+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.pocketlearn": { + "source": "iana", + "extensions": ["plf"] + }, + "application/vnd.powerbuilder6": { + "source": "iana", + "extensions": ["pbd"] + }, + "application/vnd.powerbuilder6-s": { + "source": "iana" + }, + "application/vnd.powerbuilder7": { + "source": "iana" + }, + "application/vnd.powerbuilder7-s": { + "source": "iana" + }, + "application/vnd.powerbuilder75": { + "source": "iana" + }, + "application/vnd.powerbuilder75-s": { + "source": "iana" + }, + "application/vnd.preminet": { + "source": "iana" + }, + "application/vnd.previewsystems.box": { + "source": "iana", + "extensions": ["box"] + }, + "application/vnd.proteus.magazine": { + "source": "iana", + "extensions": ["mgz"] + }, + "application/vnd.psfs": { + "source": "iana" + }, + "application/vnd.publishare-delta-tree": { + "source": "iana", + "extensions": ["qps"] + }, + "application/vnd.pvi.ptid1": { + "source": "iana", + "extensions": ["ptid"] + }, + "application/vnd.pwg-multiplexed": { + "source": "iana" + }, + "application/vnd.pwg-xhtml-print+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.qualcomm.brew-app-res": { + "source": "iana" + }, + "application/vnd.quarantainenet": { + "source": "iana" + }, + "application/vnd.quark.quarkxpress": { + "source": "iana", + "extensions": ["qxd","qxt","qwd","qwt","qxl","qxb"] + }, + "application/vnd.quobject-quoxdocument": { + "source": "iana" + }, + "application/vnd.radisys.moml+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-audit+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-audit-conf+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-audit-conn+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-audit-dialog+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-audit-stream+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-conf+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-base+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-fax-detect+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-fax-sendrecv+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-group+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-speech+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-transform+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.rainstor.data": { + "source": "iana" + }, + "application/vnd.rapid": { + "source": "iana" + }, + "application/vnd.rar": { + "source": "iana", + "extensions": ["rar"] + }, + "application/vnd.realvnc.bed": { + "source": "iana", + "extensions": ["bed"] + }, + "application/vnd.recordare.musicxml": { + "source": "iana", + "extensions": ["mxl"] + }, + "application/vnd.recordare.musicxml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["musicxml"] + }, + "application/vnd.renlearn.rlprint": { + "source": "iana" + }, + "application/vnd.resilient.logic": { + "source": "iana" + }, + "application/vnd.restful+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.rig.cryptonote": { + "source": "iana", + "extensions": ["cryptonote"] + }, + "application/vnd.rim.cod": { + "source": "apache", + "extensions": ["cod"] + }, + "application/vnd.rn-realmedia": { + "source": "apache", + "extensions": ["rm"] + }, + "application/vnd.rn-realmedia-vbr": { + "source": "apache", + "extensions": ["rmvb"] + }, + "application/vnd.route66.link66+xml": { + "source": "iana", + "compressible": true, + "extensions": ["link66"] + }, + "application/vnd.rs-274x": { + "source": "iana" + }, + "application/vnd.ruckus.download": { + "source": "iana" + }, + "application/vnd.s3sms": { + "source": "iana" + }, + "application/vnd.sailingtracker.track": { + "source": "iana", + "extensions": ["st"] + }, + "application/vnd.sar": { + "source": "iana" + }, + "application/vnd.sbm.cid": { + "source": "iana" + }, + "application/vnd.sbm.mid2": { + "source": "iana" + }, + "application/vnd.scribus": { + "source": "iana" + }, + "application/vnd.sealed.3df": { + "source": "iana" + }, + "application/vnd.sealed.csf": { + "source": "iana" + }, + "application/vnd.sealed.doc": { + "source": "iana" + }, + "application/vnd.sealed.eml": { + "source": "iana" + }, + "application/vnd.sealed.mht": { + "source": "iana" + }, + "application/vnd.sealed.net": { + "source": "iana" + }, + "application/vnd.sealed.ppt": { + "source": "iana" + }, + "application/vnd.sealed.tiff": { + "source": "iana" + }, + "application/vnd.sealed.xls": { + "source": "iana" + }, + "application/vnd.sealedmedia.softseal.html": { + "source": "iana" + }, + "application/vnd.sealedmedia.softseal.pdf": { + "source": "iana" + }, + "application/vnd.seemail": { + "source": "iana", + "extensions": ["see"] + }, + "application/vnd.seis+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.sema": { + "source": "iana", + "extensions": ["sema"] + }, + "application/vnd.semd": { + "source": "iana", + "extensions": ["semd"] + }, + "application/vnd.semf": { + "source": "iana", + "extensions": ["semf"] + }, + "application/vnd.shade-save-file": { + "source": "iana" + }, + "application/vnd.shana.informed.formdata": { + "source": "iana", + "extensions": ["ifm"] + }, + "application/vnd.shana.informed.formtemplate": { + "source": "iana", + "extensions": ["itp"] + }, + "application/vnd.shana.informed.interchange": { + "source": "iana", + "extensions": ["iif"] + }, + "application/vnd.shana.informed.package": { + "source": "iana", + "extensions": ["ipk"] + }, + "application/vnd.shootproof+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.shopkick+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.shp": { + "source": "iana" + }, + "application/vnd.shx": { + "source": "iana" + }, + "application/vnd.sigrok.session": { + "source": "iana" + }, + "application/vnd.simtech-mindmapper": { + "source": "iana", + "extensions": ["twd","twds"] + }, + "application/vnd.siren+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.smaf": { + "source": "iana", + "extensions": ["mmf"] + }, + "application/vnd.smart.notebook": { + "source": "iana" + }, + "application/vnd.smart.teacher": { + "source": "iana", + "extensions": ["teacher"] + }, + "application/vnd.snesdev-page-table": { + "source": "iana" + }, + "application/vnd.software602.filler.form+xml": { + "source": "iana", + "compressible": true, + "extensions": ["fo"] + }, + "application/vnd.software602.filler.form-xml-zip": { + "source": "iana" + }, + "application/vnd.solent.sdkm+xml": { + "source": "iana", + "compressible": true, + "extensions": ["sdkm","sdkd"] + }, + "application/vnd.spotfire.dxp": { + "source": "iana", + "extensions": ["dxp"] + }, + "application/vnd.spotfire.sfs": { + "source": "iana", + "extensions": ["sfs"] + }, + "application/vnd.sqlite3": { + "source": "iana" + }, + "application/vnd.sss-cod": { + "source": "iana" + }, + "application/vnd.sss-dtf": { + "source": "iana" + }, + "application/vnd.sss-ntf": { + "source": "iana" + }, + "application/vnd.stardivision.calc": { + "source": "apache", + "extensions": ["sdc"] + }, + "application/vnd.stardivision.draw": { + "source": "apache", + "extensions": ["sda"] + }, + "application/vnd.stardivision.impress": { + "source": "apache", + "extensions": ["sdd"] + }, + "application/vnd.stardivision.math": { + "source": "apache", + "extensions": ["smf"] + }, + "application/vnd.stardivision.writer": { + "source": "apache", + "extensions": ["sdw","vor"] + }, + "application/vnd.stardivision.writer-global": { + "source": "apache", + "extensions": ["sgl"] + }, + "application/vnd.stepmania.package": { + "source": "iana", + "extensions": ["smzip"] + }, + "application/vnd.stepmania.stepchart": { + "source": "iana", + "extensions": ["sm"] + }, + "application/vnd.street-stream": { + "source": "iana" + }, + "application/vnd.sun.wadl+xml": { + "source": "iana", + "compressible": true, + "extensions": ["wadl"] + }, + "application/vnd.sun.xml.calc": { + "source": "apache", + "extensions": ["sxc"] + }, + "application/vnd.sun.xml.calc.template": { + "source": "apache", + "extensions": ["stc"] + }, + "application/vnd.sun.xml.draw": { + "source": "apache", + "extensions": ["sxd"] + }, + "application/vnd.sun.xml.draw.template": { + "source": "apache", + "extensions": ["std"] + }, + "application/vnd.sun.xml.impress": { + "source": "apache", + "extensions": ["sxi"] + }, + "application/vnd.sun.xml.impress.template": { + "source": "apache", + "extensions": ["sti"] + }, + "application/vnd.sun.xml.math": { + "source": "apache", + "extensions": ["sxm"] + }, + "application/vnd.sun.xml.writer": { + "source": "apache", + "extensions": ["sxw"] + }, + "application/vnd.sun.xml.writer.global": { + "source": "apache", + "extensions": ["sxg"] + }, + "application/vnd.sun.xml.writer.template": { + "source": "apache", + "extensions": ["stw"] + }, + "application/vnd.sus-calendar": { + "source": "iana", + "extensions": ["sus","susp"] + }, + "application/vnd.svd": { + "source": "iana", + "extensions": ["svd"] + }, + "application/vnd.swiftview-ics": { + "source": "iana" + }, + "application/vnd.sycle+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.syft+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.symbian.install": { + "source": "apache", + "extensions": ["sis","sisx"] + }, + "application/vnd.syncml+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["xsm"] + }, + "application/vnd.syncml.dm+wbxml": { + "source": "iana", + "charset": "UTF-8", + "extensions": ["bdm"] + }, + "application/vnd.syncml.dm+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["xdm"] + }, + "application/vnd.syncml.dm.notification": { + "source": "iana" + }, + "application/vnd.syncml.dmddf+wbxml": { + "source": "iana" + }, + "application/vnd.syncml.dmddf+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["ddf"] + }, + "application/vnd.syncml.dmtnds+wbxml": { + "source": "iana" + }, + "application/vnd.syncml.dmtnds+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/vnd.syncml.ds.notification": { + "source": "iana" + }, + "application/vnd.tableschema+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.tao.intent-module-archive": { + "source": "iana", + "extensions": ["tao"] + }, + "application/vnd.tcpdump.pcap": { + "source": "iana", + "extensions": ["pcap","cap","dmp"] + }, + "application/vnd.think-cell.ppttc+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.tmd.mediaflex.api+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.tml": { + "source": "iana" + }, + "application/vnd.tmobile-livetv": { + "source": "iana", + "extensions": ["tmo"] + }, + "application/vnd.tri.onesource": { + "source": "iana" + }, + "application/vnd.trid.tpt": { + "source": "iana", + "extensions": ["tpt"] + }, + "application/vnd.triscape.mxs": { + "source": "iana", + "extensions": ["mxs"] + }, + "application/vnd.trueapp": { + "source": "iana", + "extensions": ["tra"] + }, + "application/vnd.truedoc": { + "source": "iana" + }, + "application/vnd.ubisoft.webplayer": { + "source": "iana" + }, + "application/vnd.ufdl": { + "source": "iana", + "extensions": ["ufd","ufdl"] + }, + "application/vnd.uiq.theme": { + "source": "iana", + "extensions": ["utz"] + }, + "application/vnd.umajin": { + "source": "iana", + "extensions": ["umj"] + }, + "application/vnd.unity": { + "source": "iana", + "extensions": ["unityweb"] + }, + "application/vnd.uoml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["uoml"] + }, + "application/vnd.uplanet.alert": { + "source": "iana" + }, + "application/vnd.uplanet.alert-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.bearer-choice": { + "source": "iana" + }, + "application/vnd.uplanet.bearer-choice-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.cacheop": { + "source": "iana" + }, + "application/vnd.uplanet.cacheop-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.channel": { + "source": "iana" + }, + "application/vnd.uplanet.channel-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.list": { + "source": "iana" + }, + "application/vnd.uplanet.list-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.listcmd": { + "source": "iana" + }, + "application/vnd.uplanet.listcmd-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.signal": { + "source": "iana" + }, + "application/vnd.uri-map": { + "source": "iana" + }, + "application/vnd.valve.source.material": { + "source": "iana" + }, + "application/vnd.vcx": { + "source": "iana", + "extensions": ["vcx"] + }, + "application/vnd.vd-study": { + "source": "iana" + }, + "application/vnd.vectorworks": { + "source": "iana" + }, + "application/vnd.vel+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.verimatrix.vcas": { + "source": "iana" + }, + "application/vnd.veritone.aion+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.veryant.thin": { + "source": "iana" + }, + "application/vnd.ves.encrypted": { + "source": "iana" + }, + "application/vnd.vidsoft.vidconference": { + "source": "iana" + }, + "application/vnd.visio": { + "source": "iana", + "extensions": ["vsd","vst","vss","vsw"] + }, + "application/vnd.visionary": { + "source": "iana", + "extensions": ["vis"] + }, + "application/vnd.vividence.scriptfile": { + "source": "iana" + }, + "application/vnd.vsf": { + "source": "iana", + "extensions": ["vsf"] + }, + "application/vnd.wap.sic": { + "source": "iana" + }, + "application/vnd.wap.slc": { + "source": "iana" + }, + "application/vnd.wap.wbxml": { + "source": "iana", + "charset": "UTF-8", + "extensions": ["wbxml"] + }, + "application/vnd.wap.wmlc": { + "source": "iana", + "extensions": ["wmlc"] + }, + "application/vnd.wap.wmlscriptc": { + "source": "iana", + "extensions": ["wmlsc"] + }, + "application/vnd.webturbo": { + "source": "iana", + "extensions": ["wtb"] + }, + "application/vnd.wfa.dpp": { + "source": "iana" + }, + "application/vnd.wfa.p2p": { + "source": "iana" + }, + "application/vnd.wfa.wsc": { + "source": "iana" + }, + "application/vnd.windows.devicepairing": { + "source": "iana" + }, + "application/vnd.wmc": { + "source": "iana" + }, + "application/vnd.wmf.bootstrap": { + "source": "iana" + }, + "application/vnd.wolfram.mathematica": { + "source": "iana" + }, + "application/vnd.wolfram.mathematica.package": { + "source": "iana" + }, + "application/vnd.wolfram.player": { + "source": "iana", + "extensions": ["nbp"] + }, + "application/vnd.wordperfect": { + "source": "iana", + "extensions": ["wpd"] + }, + "application/vnd.wqd": { + "source": "iana", + "extensions": ["wqd"] + }, + "application/vnd.wrq-hp3000-labelled": { + "source": "iana" + }, + "application/vnd.wt.stf": { + "source": "iana", + "extensions": ["stf"] + }, + "application/vnd.wv.csp+wbxml": { + "source": "iana" + }, + "application/vnd.wv.csp+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.wv.ssp+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.xacml+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.xara": { + "source": "iana", + "extensions": ["xar"] + }, + "application/vnd.xfdl": { + "source": "iana", + "extensions": ["xfdl"] + }, + "application/vnd.xfdl.webform": { + "source": "iana" + }, + "application/vnd.xmi+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.xmpie.cpkg": { + "source": "iana" + }, + "application/vnd.xmpie.dpkg": { + "source": "iana" + }, + "application/vnd.xmpie.plan": { + "source": "iana" + }, + "application/vnd.xmpie.ppkg": { + "source": "iana" + }, + "application/vnd.xmpie.xlim": { + "source": "iana" + }, + "application/vnd.yamaha.hv-dic": { + "source": "iana", + "extensions": ["hvd"] + }, + "application/vnd.yamaha.hv-script": { + "source": "iana", + "extensions": ["hvs"] + }, + "application/vnd.yamaha.hv-voice": { + "source": "iana", + "extensions": ["hvp"] + }, + "application/vnd.yamaha.openscoreformat": { + "source": "iana", + "extensions": ["osf"] + }, + "application/vnd.yamaha.openscoreformat.osfpvg+xml": { + "source": "iana", + "compressible": true, + "extensions": ["osfpvg"] + }, + "application/vnd.yamaha.remote-setup": { + "source": "iana" + }, + "application/vnd.yamaha.smaf-audio": { + "source": "iana", + "extensions": ["saf"] + }, + "application/vnd.yamaha.smaf-phrase": { + "source": "iana", + "extensions": ["spf"] + }, + "application/vnd.yamaha.through-ngn": { + "source": "iana" + }, + "application/vnd.yamaha.tunnel-udpencap": { + "source": "iana" + }, + "application/vnd.yaoweme": { + "source": "iana" + }, + "application/vnd.yellowriver-custom-menu": { + "source": "iana", + "extensions": ["cmp"] + }, + "application/vnd.youtube.yt": { + "source": "iana" + }, + "application/vnd.zul": { + "source": "iana", + "extensions": ["zir","zirz"] + }, + "application/vnd.zzazz.deck+xml": { + "source": "iana", + "compressible": true, + "extensions": ["zaz"] + }, + "application/voicexml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["vxml"] + }, + "application/voucher-cms+json": { + "source": "iana", + "compressible": true + }, + "application/vq-rtcpxr": { + "source": "iana" + }, + "application/wasm": { + "source": "iana", + "compressible": true, + "extensions": ["wasm"] + }, + "application/watcherinfo+xml": { + "source": "iana", + "compressible": true, + "extensions": ["wif"] + }, + "application/webpush-options+json": { + "source": "iana", + "compressible": true + }, + "application/whoispp-query": { + "source": "iana" + }, + "application/whoispp-response": { + "source": "iana" + }, + "application/widget": { + "source": "iana", + "extensions": ["wgt"] + }, + "application/winhlp": { + "source": "apache", + "extensions": ["hlp"] + }, + "application/wita": { + "source": "iana" + }, + "application/wordperfect5.1": { + "source": "iana" + }, + "application/wsdl+xml": { + "source": "iana", + "compressible": true, + "extensions": ["wsdl"] + }, + "application/wspolicy+xml": { + "source": "iana", + "compressible": true, + "extensions": ["wspolicy"] + }, + "application/x-7z-compressed": { + "source": "apache", + "compressible": false, + "extensions": ["7z"] + }, + "application/x-abiword": { + "source": "apache", + "extensions": ["abw"] + }, + "application/x-ace-compressed": { + "source": "apache", + "extensions": ["ace"] + }, + "application/x-amf": { + "source": "apache" + }, + "application/x-apple-diskimage": { + "source": "apache", + "extensions": ["dmg"] + }, + "application/x-arj": { + "compressible": false, + "extensions": ["arj"] + }, + "application/x-authorware-bin": { + "source": "apache", + "extensions": ["aab","x32","u32","vox"] + }, + "application/x-authorware-map": { + "source": "apache", + "extensions": ["aam"] + }, + "application/x-authorware-seg": { + "source": "apache", + "extensions": ["aas"] + }, + "application/x-bcpio": { + "source": "apache", + "extensions": ["bcpio"] + }, + "application/x-bdoc": { + "compressible": false, + "extensions": ["bdoc"] + }, + "application/x-bittorrent": { + "source": "apache", + "extensions": ["torrent"] + }, + "application/x-blorb": { + "source": "apache", + "extensions": ["blb","blorb"] + }, + "application/x-bzip": { + "source": "apache", + "compressible": false, + "extensions": ["bz"] + }, + "application/x-bzip2": { + "source": "apache", + "compressible": false, + "extensions": ["bz2","boz"] + }, + "application/x-cbr": { + "source": "apache", + "extensions": ["cbr","cba","cbt","cbz","cb7"] + }, + "application/x-cdlink": { + "source": "apache", + "extensions": ["vcd"] + }, + "application/x-cfs-compressed": { + "source": "apache", + "extensions": ["cfs"] + }, + "application/x-chat": { + "source": "apache", + "extensions": ["chat"] + }, + "application/x-chess-pgn": { + "source": "apache", + "extensions": ["pgn"] + }, + "application/x-chrome-extension": { + "extensions": ["crx"] + }, + "application/x-cocoa": { + "source": "nginx", + "extensions": ["cco"] + }, + "application/x-compress": { + "source": "apache" + }, + "application/x-conference": { + "source": "apache", + "extensions": ["nsc"] + }, + "application/x-cpio": { + "source": "apache", + "extensions": ["cpio"] + }, + "application/x-csh": { + "source": "apache", + "extensions": ["csh"] + }, + "application/x-deb": { + "compressible": false + }, + "application/x-debian-package": { + "source": "apache", + "extensions": ["deb","udeb"] + }, + "application/x-dgc-compressed": { + "source": "apache", + "extensions": ["dgc"] + }, + "application/x-director": { + "source": "apache", + "extensions": ["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"] + }, + "application/x-doom": { + "source": "apache", + "extensions": ["wad"] + }, + "application/x-dtbncx+xml": { + "source": "apache", + "compressible": true, + "extensions": ["ncx"] + }, + "application/x-dtbook+xml": { + "source": "apache", + "compressible": true, + "extensions": ["dtb"] + }, + "application/x-dtbresource+xml": { + "source": "apache", + "compressible": true, + "extensions": ["res"] + }, + "application/x-dvi": { + "source": "apache", + "compressible": false, + "extensions": ["dvi"] + }, + "application/x-envoy": { + "source": "apache", + "extensions": ["evy"] + }, + "application/x-eva": { + "source": "apache", + "extensions": ["eva"] + }, + "application/x-font-bdf": { + "source": "apache", + "extensions": ["bdf"] + }, + "application/x-font-dos": { + "source": "apache" + }, + "application/x-font-framemaker": { + "source": "apache" + }, + "application/x-font-ghostscript": { + "source": "apache", + "extensions": ["gsf"] + }, + "application/x-font-libgrx": { + "source": "apache" + }, + "application/x-font-linux-psf": { + "source": "apache", + "extensions": ["psf"] + }, + "application/x-font-pcf": { + "source": "apache", + "extensions": ["pcf"] + }, + "application/x-font-snf": { + "source": "apache", + "extensions": ["snf"] + }, + "application/x-font-speedo": { + "source": "apache" + }, + "application/x-font-sunos-news": { + "source": "apache" + }, + "application/x-font-type1": { + "source": "apache", + "extensions": ["pfa","pfb","pfm","afm"] + }, + "application/x-font-vfont": { + "source": "apache" + }, + "application/x-freearc": { + "source": "apache", + "extensions": ["arc"] + }, + "application/x-futuresplash": { + "source": "apache", + "extensions": ["spl"] + }, + "application/x-gca-compressed": { + "source": "apache", + "extensions": ["gca"] + }, + "application/x-glulx": { + "source": "apache", + "extensions": ["ulx"] + }, + "application/x-gnumeric": { + "source": "apache", + "extensions": ["gnumeric"] + }, + "application/x-gramps-xml": { + "source": "apache", + "extensions": ["gramps"] + }, + "application/x-gtar": { + "source": "apache", + "extensions": ["gtar"] + }, + "application/x-gzip": { + "source": "apache" + }, + "application/x-hdf": { + "source": "apache", + "extensions": ["hdf"] + }, + "application/x-httpd-php": { + "compressible": true, + "extensions": ["php"] + }, + "application/x-install-instructions": { + "source": "apache", + "extensions": ["install"] + }, + "application/x-iso9660-image": { + "source": "apache", + "extensions": ["iso"] + }, + "application/x-iwork-keynote-sffkey": { + "extensions": ["key"] + }, + "application/x-iwork-numbers-sffnumbers": { + "extensions": ["numbers"] + }, + "application/x-iwork-pages-sffpages": { + "extensions": ["pages"] + }, + "application/x-java-archive-diff": { + "source": "nginx", + "extensions": ["jardiff"] + }, + "application/x-java-jnlp-file": { + "source": "apache", + "compressible": false, + "extensions": ["jnlp"] + }, + "application/x-javascript": { + "compressible": true + }, + "application/x-keepass2": { + "extensions": ["kdbx"] + }, + "application/x-latex": { + "source": "apache", + "compressible": false, + "extensions": ["latex"] + }, + "application/x-lua-bytecode": { + "extensions": ["luac"] + }, + "application/x-lzh-compressed": { + "source": "apache", + "extensions": ["lzh","lha"] + }, + "application/x-makeself": { + "source": "nginx", + "extensions": ["run"] + }, + "application/x-mie": { + "source": "apache", + "extensions": ["mie"] + }, + "application/x-mobipocket-ebook": { + "source": "apache", + "extensions": ["prc","mobi"] + }, + "application/x-mpegurl": { + "compressible": false + }, + "application/x-ms-application": { + "source": "apache", + "extensions": ["application"] + }, + "application/x-ms-shortcut": { + "source": "apache", + "extensions": ["lnk"] + }, + "application/x-ms-wmd": { + "source": "apache", + "extensions": ["wmd"] + }, + "application/x-ms-wmz": { + "source": "apache", + "extensions": ["wmz"] + }, + "application/x-ms-xbap": { + "source": "apache", + "extensions": ["xbap"] + }, + "application/x-msaccess": { + "source": "apache", + "extensions": ["mdb"] + }, + "application/x-msbinder": { + "source": "apache", + "extensions": ["obd"] + }, + "application/x-mscardfile": { + "source": "apache", + "extensions": ["crd"] + }, + "application/x-msclip": { + "source": "apache", + "extensions": ["clp"] + }, + "application/x-msdos-program": { + "extensions": ["exe"] + }, + "application/x-msdownload": { + "source": "apache", + "extensions": ["exe","dll","com","bat","msi"] + }, + "application/x-msmediaview": { + "source": "apache", + "extensions": ["mvb","m13","m14"] + }, + "application/x-msmetafile": { + "source": "apache", + "extensions": ["wmf","wmz","emf","emz"] + }, + "application/x-msmoney": { + "source": "apache", + "extensions": ["mny"] + }, + "application/x-mspublisher": { + "source": "apache", + "extensions": ["pub"] + }, + "application/x-msschedule": { + "source": "apache", + "extensions": ["scd"] + }, + "application/x-msterminal": { + "source": "apache", + "extensions": ["trm"] + }, + "application/x-mswrite": { + "source": "apache", + "extensions": ["wri"] + }, + "application/x-netcdf": { + "source": "apache", + "extensions": ["nc","cdf"] + }, + "application/x-ns-proxy-autoconfig": { + "compressible": true, + "extensions": ["pac"] + }, + "application/x-nzb": { + "source": "apache", + "extensions": ["nzb"] + }, + "application/x-perl": { + "source": "nginx", + "extensions": ["pl","pm"] + }, + "application/x-pilot": { + "source": "nginx", + "extensions": ["prc","pdb"] + }, + "application/x-pkcs12": { + "source": "apache", + "compressible": false, + "extensions": ["p12","pfx"] + }, + "application/x-pkcs7-certificates": { + "source": "apache", + "extensions": ["p7b","spc"] + }, + "application/x-pkcs7-certreqresp": { + "source": "apache", + "extensions": ["p7r"] + }, + "application/x-pki-message": { + "source": "iana" + }, + "application/x-rar-compressed": { + "source": "apache", + "compressible": false, + "extensions": ["rar"] + }, + "application/x-redhat-package-manager": { + "source": "nginx", + "extensions": ["rpm"] + }, + "application/x-research-info-systems": { + "source": "apache", + "extensions": ["ris"] + }, + "application/x-sea": { + "source": "nginx", + "extensions": ["sea"] + }, + "application/x-sh": { + "source": "apache", + "compressible": true, + "extensions": ["sh"] + }, + "application/x-shar": { + "source": "apache", + "extensions": ["shar"] + }, + "application/x-shockwave-flash": { + "source": "apache", + "compressible": false, + "extensions": ["swf"] + }, + "application/x-silverlight-app": { + "source": "apache", + "extensions": ["xap"] + }, + "application/x-sql": { + "source": "apache", + "extensions": ["sql"] + }, + "application/x-stuffit": { + "source": "apache", + "compressible": false, + "extensions": ["sit"] + }, + "application/x-stuffitx": { + "source": "apache", + "extensions": ["sitx"] + }, + "application/x-subrip": { + "source": "apache", + "extensions": ["srt"] + }, + "application/x-sv4cpio": { + "source": "apache", + "extensions": ["sv4cpio"] + }, + "application/x-sv4crc": { + "source": "apache", + "extensions": ["sv4crc"] + }, + "application/x-t3vm-image": { + "source": "apache", + "extensions": ["t3"] + }, + "application/x-tads": { + "source": "apache", + "extensions": ["gam"] + }, + "application/x-tar": { + "source": "apache", + "compressible": true, + "extensions": ["tar"] + }, + "application/x-tcl": { + "source": "apache", + "extensions": ["tcl","tk"] + }, + "application/x-tex": { + "source": "apache", + "extensions": ["tex"] + }, + "application/x-tex-tfm": { + "source": "apache", + "extensions": ["tfm"] + }, + "application/x-texinfo": { + "source": "apache", + "extensions": ["texinfo","texi"] + }, + "application/x-tgif": { + "source": "apache", + "extensions": ["obj"] + }, + "application/x-ustar": { + "source": "apache", + "extensions": ["ustar"] + }, + "application/x-virtualbox-hdd": { + "compressible": true, + "extensions": ["hdd"] + }, + "application/x-virtualbox-ova": { + "compressible": true, + "extensions": ["ova"] + }, + "application/x-virtualbox-ovf": { + "compressible": true, + "extensions": ["ovf"] + }, + "application/x-virtualbox-vbox": { + "compressible": true, + "extensions": ["vbox"] + }, + "application/x-virtualbox-vbox-extpack": { + "compressible": false, + "extensions": ["vbox-extpack"] + }, + "application/x-virtualbox-vdi": { + "compressible": true, + "extensions": ["vdi"] + }, + "application/x-virtualbox-vhd": { + "compressible": true, + "extensions": ["vhd"] + }, + "application/x-virtualbox-vmdk": { + "compressible": true, + "extensions": ["vmdk"] + }, + "application/x-wais-source": { + "source": "apache", + "extensions": ["src"] + }, + "application/x-web-app-manifest+json": { + "compressible": true, + "extensions": ["webapp"] + }, + "application/x-www-form-urlencoded": { + "source": "iana", + "compressible": true + }, + "application/x-x509-ca-cert": { + "source": "iana", + "extensions": ["der","crt","pem"] + }, + "application/x-x509-ca-ra-cert": { + "source": "iana" + }, + "application/x-x509-next-ca-cert": { + "source": "iana" + }, + "application/x-xfig": { + "source": "apache", + "extensions": ["fig"] + }, + "application/x-xliff+xml": { + "source": "apache", + "compressible": true, + "extensions": ["xlf"] + }, + "application/x-xpinstall": { + "source": "apache", + "compressible": false, + "extensions": ["xpi"] + }, + "application/x-xz": { + "source": "apache", + "extensions": ["xz"] + }, + "application/x-zmachine": { + "source": "apache", + "extensions": ["z1","z2","z3","z4","z5","z6","z7","z8"] + }, + "application/x400-bp": { + "source": "iana" + }, + "application/xacml+xml": { + "source": "iana", + "compressible": true + }, + "application/xaml+xml": { + "source": "apache", + "compressible": true, + "extensions": ["xaml"] + }, + "application/xcap-att+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xav"] + }, + "application/xcap-caps+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xca"] + }, + "application/xcap-diff+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xdf"] + }, + "application/xcap-el+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xel"] + }, + "application/xcap-error+xml": { + "source": "iana", + "compressible": true + }, + "application/xcap-ns+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xns"] + }, + "application/xcon-conference-info+xml": { + "source": "iana", + "compressible": true + }, + "application/xcon-conference-info-diff+xml": { + "source": "iana", + "compressible": true + }, + "application/xenc+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xenc"] + }, + "application/xhtml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xhtml","xht"] + }, + "application/xhtml-voice+xml": { + "source": "apache", + "compressible": true + }, + "application/xliff+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xlf"] + }, + "application/xml": { + "source": "iana", + "compressible": true, + "extensions": ["xml","xsl","xsd","rng"] + }, + "application/xml-dtd": { + "source": "iana", + "compressible": true, + "extensions": ["dtd"] + }, + "application/xml-external-parsed-entity": { + "source": "iana" + }, + "application/xml-patch+xml": { + "source": "iana", + "compressible": true + }, + "application/xmpp+xml": { + "source": "iana", + "compressible": true + }, + "application/xop+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xop"] + }, + "application/xproc+xml": { + "source": "apache", + "compressible": true, + "extensions": ["xpl"] + }, + "application/xslt+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xsl","xslt"] + }, + "application/xspf+xml": { + "source": "apache", + "compressible": true, + "extensions": ["xspf"] + }, + "application/xv+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mxml","xhvml","xvml","xvm"] + }, + "application/yang": { + "source": "iana", + "extensions": ["yang"] + }, + "application/yang-data+json": { + "source": "iana", + "compressible": true + }, + "application/yang-data+xml": { + "source": "iana", + "compressible": true + }, + "application/yang-patch+json": { + "source": "iana", + "compressible": true + }, + "application/yang-patch+xml": { + "source": "iana", + "compressible": true + }, + "application/yin+xml": { + "source": "iana", + "compressible": true, + "extensions": ["yin"] + }, + "application/zip": { + "source": "iana", + "compressible": false, + "extensions": ["zip"] + }, + "application/zlib": { + "source": "iana" + }, + "application/zstd": { + "source": "iana" + }, + "audio/1d-interleaved-parityfec": { + "source": "iana" + }, + "audio/32kadpcm": { + "source": "iana" + }, + "audio/3gpp": { + "source": "iana", + "compressible": false, + "extensions": ["3gpp"] + }, + "audio/3gpp2": { + "source": "iana" + }, + "audio/aac": { + "source": "iana" + }, + "audio/ac3": { + "source": "iana" + }, + "audio/adpcm": { + "source": "apache", + "extensions": ["adp"] + }, + "audio/amr": { + "source": "iana", + "extensions": ["amr"] + }, + "audio/amr-wb": { + "source": "iana" + }, + "audio/amr-wb+": { + "source": "iana" + }, + "audio/aptx": { + "source": "iana" + }, + "audio/asc": { + "source": "iana" + }, + "audio/atrac-advanced-lossless": { + "source": "iana" + }, + "audio/atrac-x": { + "source": "iana" + }, + "audio/atrac3": { + "source": "iana" + }, + "audio/basic": { + "source": "iana", + "compressible": false, + "extensions": ["au","snd"] + }, + "audio/bv16": { + "source": "iana" + }, + "audio/bv32": { + "source": "iana" + }, + "audio/clearmode": { + "source": "iana" + }, + "audio/cn": { + "source": "iana" + }, + "audio/dat12": { + "source": "iana" + }, + "audio/dls": { + "source": "iana" + }, + "audio/dsr-es201108": { + "source": "iana" + }, + "audio/dsr-es202050": { + "source": "iana" + }, + "audio/dsr-es202211": { + "source": "iana" + }, + "audio/dsr-es202212": { + "source": "iana" + }, + "audio/dv": { + "source": "iana" + }, + "audio/dvi4": { + "source": "iana" + }, + "audio/eac3": { + "source": "iana" + }, + "audio/encaprtp": { + "source": "iana" + }, + "audio/evrc": { + "source": "iana" + }, + "audio/evrc-qcp": { + "source": "iana" + }, + "audio/evrc0": { + "source": "iana" + }, + "audio/evrc1": { + "source": "iana" + }, + "audio/evrcb": { + "source": "iana" + }, + "audio/evrcb0": { + "source": "iana" + }, + "audio/evrcb1": { + "source": "iana" + }, + "audio/evrcnw": { + "source": "iana" + }, + "audio/evrcnw0": { + "source": "iana" + }, + "audio/evrcnw1": { + "source": "iana" + }, + "audio/evrcwb": { + "source": "iana" + }, + "audio/evrcwb0": { + "source": "iana" + }, + "audio/evrcwb1": { + "source": "iana" + }, + "audio/evs": { + "source": "iana" + }, + "audio/flexfec": { + "source": "iana" + }, + "audio/fwdred": { + "source": "iana" + }, + "audio/g711-0": { + "source": "iana" + }, + "audio/g719": { + "source": "iana" + }, + "audio/g722": { + "source": "iana" + }, + "audio/g7221": { + "source": "iana" + }, + "audio/g723": { + "source": "iana" + }, + "audio/g726-16": { + "source": "iana" + }, + "audio/g726-24": { + "source": "iana" + }, + "audio/g726-32": { + "source": "iana" + }, + "audio/g726-40": { + "source": "iana" + }, + "audio/g728": { + "source": "iana" + }, + "audio/g729": { + "source": "iana" + }, + "audio/g7291": { + "source": "iana" + }, + "audio/g729d": { + "source": "iana" + }, + "audio/g729e": { + "source": "iana" + }, + "audio/gsm": { + "source": "iana" + }, + "audio/gsm-efr": { + "source": "iana" + }, + "audio/gsm-hr-08": { + "source": "iana" + }, + "audio/ilbc": { + "source": "iana" + }, + "audio/ip-mr_v2.5": { + "source": "iana" + }, + "audio/isac": { + "source": "apache" + }, + "audio/l16": { + "source": "iana" + }, + "audio/l20": { + "source": "iana" + }, + "audio/l24": { + "source": "iana", + "compressible": false + }, + "audio/l8": { + "source": "iana" + }, + "audio/lpc": { + "source": "iana" + }, + "audio/melp": { + "source": "iana" + }, + "audio/melp1200": { + "source": "iana" + }, + "audio/melp2400": { + "source": "iana" + }, + "audio/melp600": { + "source": "iana" + }, + "audio/mhas": { + "source": "iana" + }, + "audio/midi": { + "source": "apache", + "extensions": ["mid","midi","kar","rmi"] + }, + "audio/mobile-xmf": { + "source": "iana", + "extensions": ["mxmf"] + }, + "audio/mp3": { + "compressible": false, + "extensions": ["mp3"] + }, + "audio/mp4": { + "source": "iana", + "compressible": false, + "extensions": ["m4a","mp4a"] + }, + "audio/mp4a-latm": { + "source": "iana" + }, + "audio/mpa": { + "source": "iana" + }, + "audio/mpa-robust": { + "source": "iana" + }, + "audio/mpeg": { + "source": "iana", + "compressible": false, + "extensions": ["mpga","mp2","mp2a","mp3","m2a","m3a"] + }, + "audio/mpeg4-generic": { + "source": "iana" + }, + "audio/musepack": { + "source": "apache" + }, + "audio/ogg": { + "source": "iana", + "compressible": false, + "extensions": ["oga","ogg","spx","opus"] + }, + "audio/opus": { + "source": "iana" + }, + "audio/parityfec": { + "source": "iana" + }, + "audio/pcma": { + "source": "iana" + }, + "audio/pcma-wb": { + "source": "iana" + }, + "audio/pcmu": { + "source": "iana" + }, + "audio/pcmu-wb": { + "source": "iana" + }, + "audio/prs.sid": { + "source": "iana" + }, + "audio/qcelp": { + "source": "iana" + }, + "audio/raptorfec": { + "source": "iana" + }, + "audio/red": { + "source": "iana" + }, + "audio/rtp-enc-aescm128": { + "source": "iana" + }, + "audio/rtp-midi": { + "source": "iana" + }, + "audio/rtploopback": { + "source": "iana" + }, + "audio/rtx": { + "source": "iana" + }, + "audio/s3m": { + "source": "apache", + "extensions": ["s3m"] + }, + "audio/scip": { + "source": "iana" + }, + "audio/silk": { + "source": "apache", + "extensions": ["sil"] + }, + "audio/smv": { + "source": "iana" + }, + "audio/smv-qcp": { + "source": "iana" + }, + "audio/smv0": { + "source": "iana" + }, + "audio/sofa": { + "source": "iana" + }, + "audio/sp-midi": { + "source": "iana" + }, + "audio/speex": { + "source": "iana" + }, + "audio/t140c": { + "source": "iana" + }, + "audio/t38": { + "source": "iana" + }, + "audio/telephone-event": { + "source": "iana" + }, + "audio/tetra_acelp": { + "source": "iana" + }, + "audio/tetra_acelp_bb": { + "source": "iana" + }, + "audio/tone": { + "source": "iana" + }, + "audio/tsvcis": { + "source": "iana" + }, + "audio/uemclip": { + "source": "iana" + }, + "audio/ulpfec": { + "source": "iana" + }, + "audio/usac": { + "source": "iana" + }, + "audio/vdvi": { + "source": "iana" + }, + "audio/vmr-wb": { + "source": "iana" + }, + "audio/vnd.3gpp.iufp": { + "source": "iana" + }, + "audio/vnd.4sb": { + "source": "iana" + }, + "audio/vnd.audiokoz": { + "source": "iana" + }, + "audio/vnd.celp": { + "source": "iana" + }, + "audio/vnd.cisco.nse": { + "source": "iana" + }, + "audio/vnd.cmles.radio-events": { + "source": "iana" + }, + "audio/vnd.cns.anp1": { + "source": "iana" + }, + "audio/vnd.cns.inf1": { + "source": "iana" + }, + "audio/vnd.dece.audio": { + "source": "iana", + "extensions": ["uva","uvva"] + }, + "audio/vnd.digital-winds": { + "source": "iana", + "extensions": ["eol"] + }, + "audio/vnd.dlna.adts": { + "source": "iana" + }, + "audio/vnd.dolby.heaac.1": { + "source": "iana" + }, + "audio/vnd.dolby.heaac.2": { + "source": "iana" + }, + "audio/vnd.dolby.mlp": { + "source": "iana" + }, + "audio/vnd.dolby.mps": { + "source": "iana" + }, + "audio/vnd.dolby.pl2": { + "source": "iana" + }, + "audio/vnd.dolby.pl2x": { + "source": "iana" + }, + "audio/vnd.dolby.pl2z": { + "source": "iana" + }, + "audio/vnd.dolby.pulse.1": { + "source": "iana" + }, + "audio/vnd.dra": { + "source": "iana", + "extensions": ["dra"] + }, + "audio/vnd.dts": { + "source": "iana", + "extensions": ["dts"] + }, + "audio/vnd.dts.hd": { + "source": "iana", + "extensions": ["dtshd"] + }, + "audio/vnd.dts.uhd": { + "source": "iana" + }, + "audio/vnd.dvb.file": { + "source": "iana" + }, + "audio/vnd.everad.plj": { + "source": "iana" + }, + "audio/vnd.hns.audio": { + "source": "iana" + }, + "audio/vnd.lucent.voice": { + "source": "iana", + "extensions": ["lvp"] + }, + "audio/vnd.ms-playready.media.pya": { + "source": "iana", + "extensions": ["pya"] + }, + "audio/vnd.nokia.mobile-xmf": { + "source": "iana" + }, + "audio/vnd.nortel.vbk": { + "source": "iana" + }, + "audio/vnd.nuera.ecelp4800": { + "source": "iana", + "extensions": ["ecelp4800"] + }, + "audio/vnd.nuera.ecelp7470": { + "source": "iana", + "extensions": ["ecelp7470"] + }, + "audio/vnd.nuera.ecelp9600": { + "source": "iana", + "extensions": ["ecelp9600"] + }, + "audio/vnd.octel.sbc": { + "source": "iana" + }, + "audio/vnd.presonus.multitrack": { + "source": "iana" + }, + "audio/vnd.qcelp": { + "source": "iana" + }, + "audio/vnd.rhetorex.32kadpcm": { + "source": "iana" + }, + "audio/vnd.rip": { + "source": "iana", + "extensions": ["rip"] + }, + "audio/vnd.rn-realaudio": { + "compressible": false + }, + "audio/vnd.sealedmedia.softseal.mpeg": { + "source": "iana" + }, + "audio/vnd.vmx.cvsd": { + "source": "iana" + }, + "audio/vnd.wave": { + "compressible": false + }, + "audio/vorbis": { + "source": "iana", + "compressible": false + }, + "audio/vorbis-config": { + "source": "iana" + }, + "audio/wav": { + "compressible": false, + "extensions": ["wav"] + }, + "audio/wave": { + "compressible": false, + "extensions": ["wav"] + }, + "audio/webm": { + "source": "apache", + "compressible": false, + "extensions": ["weba"] + }, + "audio/x-aac": { + "source": "apache", + "compressible": false, + "extensions": ["aac"] + }, + "audio/x-aiff": { + "source": "apache", + "extensions": ["aif","aiff","aifc"] + }, + "audio/x-caf": { + "source": "apache", + "compressible": false, + "extensions": ["caf"] + }, + "audio/x-flac": { + "source": "apache", + "extensions": ["flac"] + }, + "audio/x-m4a": { + "source": "nginx", + "extensions": ["m4a"] + }, + "audio/x-matroska": { + "source": "apache", + "extensions": ["mka"] + }, + "audio/x-mpegurl": { + "source": "apache", + "extensions": ["m3u"] + }, + "audio/x-ms-wax": { + "source": "apache", + "extensions": ["wax"] + }, + "audio/x-ms-wma": { + "source": "apache", + "extensions": ["wma"] + }, + "audio/x-pn-realaudio": { + "source": "apache", + "extensions": ["ram","ra"] + }, + "audio/x-pn-realaudio-plugin": { + "source": "apache", + "extensions": ["rmp"] + }, + "audio/x-realaudio": { + "source": "nginx", + "extensions": ["ra"] + }, + "audio/x-tta": { + "source": "apache" + }, + "audio/x-wav": { + "source": "apache", + "extensions": ["wav"] + }, + "audio/xm": { + "source": "apache", + "extensions": ["xm"] + }, + "chemical/x-cdx": { + "source": "apache", + "extensions": ["cdx"] + }, + "chemical/x-cif": { + "source": "apache", + "extensions": ["cif"] + }, + "chemical/x-cmdf": { + "source": "apache", + "extensions": ["cmdf"] + }, + "chemical/x-cml": { + "source": "apache", + "extensions": ["cml"] + }, + "chemical/x-csml": { + "source": "apache", + "extensions": ["csml"] + }, + "chemical/x-pdb": { + "source": "apache" + }, + "chemical/x-xyz": { + "source": "apache", + "extensions": ["xyz"] + }, + "font/collection": { + "source": "iana", + "extensions": ["ttc"] + }, + "font/otf": { + "source": "iana", + "compressible": true, + "extensions": ["otf"] + }, + "font/sfnt": { + "source": "iana" + }, + "font/ttf": { + "source": "iana", + "compressible": true, + "extensions": ["ttf"] + }, + "font/woff": { + "source": "iana", + "extensions": ["woff"] + }, + "font/woff2": { + "source": "iana", + "extensions": ["woff2"] + }, + "image/aces": { + "source": "iana", + "extensions": ["exr"] + }, + "image/apng": { + "compressible": false, + "extensions": ["apng"] + }, + "image/avci": { + "source": "iana", + "extensions": ["avci"] + }, + "image/avcs": { + "source": "iana", + "extensions": ["avcs"] + }, + "image/avif": { + "source": "iana", + "compressible": false, + "extensions": ["avif"] + }, + "image/bmp": { + "source": "iana", + "compressible": true, + "extensions": ["bmp"] + }, + "image/cgm": { + "source": "iana", + "extensions": ["cgm"] + }, + "image/dicom-rle": { + "source": "iana", + "extensions": ["drle"] + }, + "image/emf": { + "source": "iana", + "extensions": ["emf"] + }, + "image/fits": { + "source": "iana", + "extensions": ["fits"] + }, + "image/g3fax": { + "source": "iana", + "extensions": ["g3"] + }, + "image/gif": { + "source": "iana", + "compressible": false, + "extensions": ["gif"] + }, + "image/heic": { + "source": "iana", + "extensions": ["heic"] + }, + "image/heic-sequence": { + "source": "iana", + "extensions": ["heics"] + }, + "image/heif": { + "source": "iana", + "extensions": ["heif"] + }, + "image/heif-sequence": { + "source": "iana", + "extensions": ["heifs"] + }, + "image/hej2k": { + "source": "iana", + "extensions": ["hej2"] + }, + "image/hsj2": { + "source": "iana", + "extensions": ["hsj2"] + }, + "image/ief": { + "source": "iana", + "extensions": ["ief"] + }, + "image/jls": { + "source": "iana", + "extensions": ["jls"] + }, + "image/jp2": { + "source": "iana", + "compressible": false, + "extensions": ["jp2","jpg2"] + }, + "image/jpeg": { + "source": "iana", + "compressible": false, + "extensions": ["jpeg","jpg","jpe"] + }, + "image/jph": { + "source": "iana", + "extensions": ["jph"] + }, + "image/jphc": { + "source": "iana", + "extensions": ["jhc"] + }, + "image/jpm": { + "source": "iana", + "compressible": false, + "extensions": ["jpm"] + }, + "image/jpx": { + "source": "iana", + "compressible": false, + "extensions": ["jpx","jpf"] + }, + "image/jxr": { + "source": "iana", + "extensions": ["jxr"] + }, + "image/jxra": { + "source": "iana", + "extensions": ["jxra"] + }, + "image/jxrs": { + "source": "iana", + "extensions": ["jxrs"] + }, + "image/jxs": { + "source": "iana", + "extensions": ["jxs"] + }, + "image/jxsc": { + "source": "iana", + "extensions": ["jxsc"] + }, + "image/jxsi": { + "source": "iana", + "extensions": ["jxsi"] + }, + "image/jxss": { + "source": "iana", + "extensions": ["jxss"] + }, + "image/ktx": { + "source": "iana", + "extensions": ["ktx"] + }, + "image/ktx2": { + "source": "iana", + "extensions": ["ktx2"] + }, + "image/naplps": { + "source": "iana" + }, + "image/pjpeg": { + "compressible": false + }, + "image/png": { + "source": "iana", + "compressible": false, + "extensions": ["png"] + }, + "image/prs.btif": { + "source": "iana", + "extensions": ["btif"] + }, + "image/prs.pti": { + "source": "iana", + "extensions": ["pti"] + }, + "image/pwg-raster": { + "source": "iana" + }, + "image/sgi": { + "source": "apache", + "extensions": ["sgi"] + }, + "image/svg+xml": { + "source": "iana", + "compressible": true, + "extensions": ["svg","svgz"] + }, + "image/t38": { + "source": "iana", + "extensions": ["t38"] + }, + "image/tiff": { + "source": "iana", + "compressible": false, + "extensions": ["tif","tiff"] + }, + "image/tiff-fx": { + "source": "iana", + "extensions": ["tfx"] + }, + "image/vnd.adobe.photoshop": { + "source": "iana", + "compressible": true, + "extensions": ["psd"] + }, + "image/vnd.airzip.accelerator.azv": { + "source": "iana", + "extensions": ["azv"] + }, + "image/vnd.cns.inf2": { + "source": "iana" + }, + "image/vnd.dece.graphic": { + "source": "iana", + "extensions": ["uvi","uvvi","uvg","uvvg"] + }, + "image/vnd.djvu": { + "source": "iana", + "extensions": ["djvu","djv"] + }, + "image/vnd.dvb.subtitle": { + "source": "iana", + "extensions": ["sub"] + }, + "image/vnd.dwg": { + "source": "iana", + "extensions": ["dwg"] + }, + "image/vnd.dxf": { + "source": "iana", + "extensions": ["dxf"] + }, + "image/vnd.fastbidsheet": { + "source": "iana", + "extensions": ["fbs"] + }, + "image/vnd.fpx": { + "source": "iana", + "extensions": ["fpx"] + }, + "image/vnd.fst": { + "source": "iana", + "extensions": ["fst"] + }, + "image/vnd.fujixerox.edmics-mmr": { + "source": "iana", + "extensions": ["mmr"] + }, + "image/vnd.fujixerox.edmics-rlc": { + "source": "iana", + "extensions": ["rlc"] + }, + "image/vnd.globalgraphics.pgb": { + "source": "iana" + }, + "image/vnd.microsoft.icon": { + "source": "iana", + "compressible": true, + "extensions": ["ico"] + }, + "image/vnd.mix": { + "source": "iana" + }, + "image/vnd.mozilla.apng": { + "source": "iana" + }, + "image/vnd.ms-dds": { + "compressible": true, + "extensions": ["dds"] + }, + "image/vnd.ms-modi": { + "source": "iana", + "extensions": ["mdi"] + }, + "image/vnd.ms-photo": { + "source": "apache", + "extensions": ["wdp"] + }, + "image/vnd.net-fpx": { + "source": "iana", + "extensions": ["npx"] + }, + "image/vnd.pco.b16": { + "source": "iana", + "extensions": ["b16"] + }, + "image/vnd.radiance": { + "source": "iana" + }, + "image/vnd.sealed.png": { + "source": "iana" + }, + "image/vnd.sealedmedia.softseal.gif": { + "source": "iana" + }, + "image/vnd.sealedmedia.softseal.jpg": { + "source": "iana" + }, + "image/vnd.svf": { + "source": "iana" + }, + "image/vnd.tencent.tap": { + "source": "iana", + "extensions": ["tap"] + }, + "image/vnd.valve.source.texture": { + "source": "iana", + "extensions": ["vtf"] + }, + "image/vnd.wap.wbmp": { + "source": "iana", + "extensions": ["wbmp"] + }, + "image/vnd.xiff": { + "source": "iana", + "extensions": ["xif"] + }, + "image/vnd.zbrush.pcx": { + "source": "iana", + "extensions": ["pcx"] + }, + "image/webp": { + "source": "apache", + "extensions": ["webp"] + }, + "image/wmf": { + "source": "iana", + "extensions": ["wmf"] + }, + "image/x-3ds": { + "source": "apache", + "extensions": ["3ds"] + }, + "image/x-cmu-raster": { + "source": "apache", + "extensions": ["ras"] + }, + "image/x-cmx": { + "source": "apache", + "extensions": ["cmx"] + }, + "image/x-freehand": { + "source": "apache", + "extensions": ["fh","fhc","fh4","fh5","fh7"] + }, + "image/x-icon": { + "source": "apache", + "compressible": true, + "extensions": ["ico"] + }, + "image/x-jng": { + "source": "nginx", + "extensions": ["jng"] + }, + "image/x-mrsid-image": { + "source": "apache", + "extensions": ["sid"] + }, + "image/x-ms-bmp": { + "source": "nginx", + "compressible": true, + "extensions": ["bmp"] + }, + "image/x-pcx": { + "source": "apache", + "extensions": ["pcx"] + }, + "image/x-pict": { + "source": "apache", + "extensions": ["pic","pct"] + }, + "image/x-portable-anymap": { + "source": "apache", + "extensions": ["pnm"] + }, + "image/x-portable-bitmap": { + "source": "apache", + "extensions": ["pbm"] + }, + "image/x-portable-graymap": { + "source": "apache", + "extensions": ["pgm"] + }, + "image/x-portable-pixmap": { + "source": "apache", + "extensions": ["ppm"] + }, + "image/x-rgb": { + "source": "apache", + "extensions": ["rgb"] + }, + "image/x-tga": { + "source": "apache", + "extensions": ["tga"] + }, + "image/x-xbitmap": { + "source": "apache", + "extensions": ["xbm"] + }, + "image/x-xcf": { + "compressible": false + }, + "image/x-xpixmap": { + "source": "apache", + "extensions": ["xpm"] + }, + "image/x-xwindowdump": { + "source": "apache", + "extensions": ["xwd"] + }, + "message/cpim": { + "source": "iana" + }, + "message/delivery-status": { + "source": "iana" + }, + "message/disposition-notification": { + "source": "iana", + "extensions": [ + "disposition-notification" + ] + }, + "message/external-body": { + "source": "iana" + }, + "message/feedback-report": { + "source": "iana" + }, + "message/global": { + "source": "iana", + "extensions": ["u8msg"] + }, + "message/global-delivery-status": { + "source": "iana", + "extensions": ["u8dsn"] + }, + "message/global-disposition-notification": { + "source": "iana", + "extensions": ["u8mdn"] + }, + "message/global-headers": { + "source": "iana", + "extensions": ["u8hdr"] + }, + "message/http": { + "source": "iana", + "compressible": false + }, + "message/imdn+xml": { + "source": "iana", + "compressible": true + }, + "message/news": { + "source": "iana" + }, + "message/partial": { + "source": "iana", + "compressible": false + }, + "message/rfc822": { + "source": "iana", + "compressible": true, + "extensions": ["eml","mime"] + }, + "message/s-http": { + "source": "iana" + }, + "message/sip": { + "source": "iana" + }, + "message/sipfrag": { + "source": "iana" + }, + "message/tracking-status": { + "source": "iana" + }, + "message/vnd.si.simp": { + "source": "iana" + }, + "message/vnd.wfa.wsc": { + "source": "iana", + "extensions": ["wsc"] + }, + "model/3mf": { + "source": "iana", + "extensions": ["3mf"] + }, + "model/e57": { + "source": "iana" + }, + "model/gltf+json": { + "source": "iana", + "compressible": true, + "extensions": ["gltf"] + }, + "model/gltf-binary": { + "source": "iana", + "compressible": true, + "extensions": ["glb"] + }, + "model/iges": { + "source": "iana", + "compressible": false, + "extensions": ["igs","iges"] + }, + "model/mesh": { + "source": "iana", + "compressible": false, + "extensions": ["msh","mesh","silo"] + }, + "model/mtl": { + "source": "iana", + "extensions": ["mtl"] + }, + "model/obj": { + "source": "iana", + "extensions": ["obj"] + }, + "model/step": { + "source": "iana" + }, + "model/step+xml": { + "source": "iana", + "compressible": true, + "extensions": ["stpx"] + }, + "model/step+zip": { + "source": "iana", + "compressible": false, + "extensions": ["stpz"] + }, + "model/step-xml+zip": { + "source": "iana", + "compressible": false, + "extensions": ["stpxz"] + }, + "model/stl": { + "source": "iana", + "extensions": ["stl"] + }, + "model/vnd.collada+xml": { + "source": "iana", + "compressible": true, + "extensions": ["dae"] + }, + "model/vnd.dwf": { + "source": "iana", + "extensions": ["dwf"] + }, + "model/vnd.flatland.3dml": { + "source": "iana" + }, + "model/vnd.gdl": { + "source": "iana", + "extensions": ["gdl"] + }, + "model/vnd.gs-gdl": { + "source": "apache" + }, + "model/vnd.gs.gdl": { + "source": "iana" + }, + "model/vnd.gtw": { + "source": "iana", + "extensions": ["gtw"] + }, + "model/vnd.moml+xml": { + "source": "iana", + "compressible": true + }, + "model/vnd.mts": { + "source": "iana", + "extensions": ["mts"] + }, + "model/vnd.opengex": { + "source": "iana", + "extensions": ["ogex"] + }, + "model/vnd.parasolid.transmit.binary": { + "source": "iana", + "extensions": ["x_b"] + }, + "model/vnd.parasolid.transmit.text": { + "source": "iana", + "extensions": ["x_t"] + }, + "model/vnd.pytha.pyox": { + "source": "iana" + }, + "model/vnd.rosette.annotated-data-model": { + "source": "iana" + }, + "model/vnd.sap.vds": { + "source": "iana", + "extensions": ["vds"] + }, + "model/vnd.usdz+zip": { + "source": "iana", + "compressible": false, + "extensions": ["usdz"] + }, + "model/vnd.valve.source.compiled-map": { + "source": "iana", + "extensions": ["bsp"] + }, + "model/vnd.vtu": { + "source": "iana", + "extensions": ["vtu"] + }, + "model/vrml": { + "source": "iana", + "compressible": false, + "extensions": ["wrl","vrml"] + }, + "model/x3d+binary": { + "source": "apache", + "compressible": false, + "extensions": ["x3db","x3dbz"] + }, + "model/x3d+fastinfoset": { + "source": "iana", + "extensions": ["x3db"] + }, + "model/x3d+vrml": { + "source": "apache", + "compressible": false, + "extensions": ["x3dv","x3dvz"] + }, + "model/x3d+xml": { + "source": "iana", + "compressible": true, + "extensions": ["x3d","x3dz"] + }, + "model/x3d-vrml": { + "source": "iana", + "extensions": ["x3dv"] + }, + "multipart/alternative": { + "source": "iana", + "compressible": false + }, + "multipart/appledouble": { + "source": "iana" + }, + "multipart/byteranges": { + "source": "iana" + }, + "multipart/digest": { + "source": "iana" + }, + "multipart/encrypted": { + "source": "iana", + "compressible": false + }, + "multipart/form-data": { + "source": "iana", + "compressible": false + }, + "multipart/header-set": { + "source": "iana" + }, + "multipart/mixed": { + "source": "iana" + }, + "multipart/multilingual": { + "source": "iana" + }, + "multipart/parallel": { + "source": "iana" + }, + "multipart/related": { + "source": "iana", + "compressible": false + }, + "multipart/report": { + "source": "iana" + }, + "multipart/signed": { + "source": "iana", + "compressible": false + }, + "multipart/vnd.bint.med-plus": { + "source": "iana" + }, + "multipart/voice-message": { + "source": "iana" + }, + "multipart/x-mixed-replace": { + "source": "iana" + }, + "text/1d-interleaved-parityfec": { + "source": "iana" + }, + "text/cache-manifest": { + "source": "iana", + "compressible": true, + "extensions": ["appcache","manifest"] + }, + "text/calendar": { + "source": "iana", + "extensions": ["ics","ifb"] + }, + "text/calender": { + "compressible": true + }, + "text/cmd": { + "compressible": true + }, + "text/coffeescript": { + "extensions": ["coffee","litcoffee"] + }, + "text/cql": { + "source": "iana" + }, + "text/cql-expression": { + "source": "iana" + }, + "text/cql-identifier": { + "source": "iana" + }, + "text/css": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["css"] + }, + "text/csv": { + "source": "iana", + "compressible": true, + "extensions": ["csv"] + }, + "text/csv-schema": { + "source": "iana" + }, + "text/directory": { + "source": "iana" + }, + "text/dns": { + "source": "iana" + }, + "text/ecmascript": { + "source": "iana" + }, + "text/encaprtp": { + "source": "iana" + }, + "text/enriched": { + "source": "iana" + }, + "text/fhirpath": { + "source": "iana" + }, + "text/flexfec": { + "source": "iana" + }, + "text/fwdred": { + "source": "iana" + }, + "text/gff3": { + "source": "iana" + }, + "text/grammar-ref-list": { + "source": "iana" + }, + "text/html": { + "source": "iana", + "compressible": true, + "extensions": ["html","htm","shtml"] + }, + "text/jade": { + "extensions": ["jade"] + }, + "text/javascript": { + "source": "iana", + "compressible": true + }, + "text/jcr-cnd": { + "source": "iana" + }, + "text/jsx": { + "compressible": true, + "extensions": ["jsx"] + }, + "text/less": { + "compressible": true, + "extensions": ["less"] + }, + "text/markdown": { + "source": "iana", + "compressible": true, + "extensions": ["markdown","md"] + }, + "text/mathml": { + "source": "nginx", + "extensions": ["mml"] + }, + "text/mdx": { + "compressible": true, + "extensions": ["mdx"] + }, + "text/mizar": { + "source": "iana" + }, + "text/n3": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["n3"] + }, + "text/parameters": { + "source": "iana", + "charset": "UTF-8" + }, + "text/parityfec": { + "source": "iana" + }, + "text/plain": { + "source": "iana", + "compressible": true, + "extensions": ["txt","text","conf","def","list","log","in","ini"] + }, + "text/provenance-notation": { + "source": "iana", + "charset": "UTF-8" + }, + "text/prs.fallenstein.rst": { + "source": "iana" + }, + "text/prs.lines.tag": { + "source": "iana", + "extensions": ["dsc"] + }, + "text/prs.prop.logic": { + "source": "iana" + }, + "text/raptorfec": { + "source": "iana" + }, + "text/red": { + "source": "iana" + }, + "text/rfc822-headers": { + "source": "iana" + }, + "text/richtext": { + "source": "iana", + "compressible": true, + "extensions": ["rtx"] + }, + "text/rtf": { + "source": "iana", + "compressible": true, + "extensions": ["rtf"] + }, + "text/rtp-enc-aescm128": { + "source": "iana" + }, + "text/rtploopback": { + "source": "iana" + }, + "text/rtx": { + "source": "iana" + }, + "text/sgml": { + "source": "iana", + "extensions": ["sgml","sgm"] + }, + "text/shaclc": { + "source": "iana" + }, + "text/shex": { + "source": "iana", + "extensions": ["shex"] + }, + "text/slim": { + "extensions": ["slim","slm"] + }, + "text/spdx": { + "source": "iana", + "extensions": ["spdx"] + }, + "text/strings": { + "source": "iana" + }, + "text/stylus": { + "extensions": ["stylus","styl"] + }, + "text/t140": { + "source": "iana" + }, + "text/tab-separated-values": { + "source": "iana", + "compressible": true, + "extensions": ["tsv"] + }, + "text/troff": { + "source": "iana", + "extensions": ["t","tr","roff","man","me","ms"] + }, + "text/turtle": { + "source": "iana", + "charset": "UTF-8", + "extensions": ["ttl"] + }, + "text/ulpfec": { + "source": "iana" + }, + "text/uri-list": { + "source": "iana", + "compressible": true, + "extensions": ["uri","uris","urls"] + }, + "text/vcard": { + "source": "iana", + "compressible": true, + "extensions": ["vcard"] + }, + "text/vnd.a": { + "source": "iana" + }, + "text/vnd.abc": { + "source": "iana" + }, + "text/vnd.ascii-art": { + "source": "iana" + }, + "text/vnd.curl": { + "source": "iana", + "extensions": ["curl"] + }, + "text/vnd.curl.dcurl": { + "source": "apache", + "extensions": ["dcurl"] + }, + "text/vnd.curl.mcurl": { + "source": "apache", + "extensions": ["mcurl"] + }, + "text/vnd.curl.scurl": { + "source": "apache", + "extensions": ["scurl"] + }, + "text/vnd.debian.copyright": { + "source": "iana", + "charset": "UTF-8" + }, + "text/vnd.dmclientscript": { + "source": "iana" + }, + "text/vnd.dvb.subtitle": { + "source": "iana", + "extensions": ["sub"] + }, + "text/vnd.esmertec.theme-descriptor": { + "source": "iana", + "charset": "UTF-8" + }, + "text/vnd.familysearch.gedcom": { + "source": "iana", + "extensions": ["ged"] + }, + "text/vnd.ficlab.flt": { + "source": "iana" + }, + "text/vnd.fly": { + "source": "iana", + "extensions": ["fly"] + }, + "text/vnd.fmi.flexstor": { + "source": "iana", + "extensions": ["flx"] + }, + "text/vnd.gml": { + "source": "iana" + }, + "text/vnd.graphviz": { + "source": "iana", + "extensions": ["gv"] + }, + "text/vnd.hans": { + "source": "iana" + }, + "text/vnd.hgl": { + "source": "iana" + }, + "text/vnd.in3d.3dml": { + "source": "iana", + "extensions": ["3dml"] + }, + "text/vnd.in3d.spot": { + "source": "iana", + "extensions": ["spot"] + }, + "text/vnd.iptc.newsml": { + "source": "iana" + }, + "text/vnd.iptc.nitf": { + "source": "iana" + }, + "text/vnd.latex-z": { + "source": "iana" + }, + "text/vnd.motorola.reflex": { + "source": "iana" + }, + "text/vnd.ms-mediapackage": { + "source": "iana" + }, + "text/vnd.net2phone.commcenter.command": { + "source": "iana" + }, + "text/vnd.radisys.msml-basic-layout": { + "source": "iana" + }, + "text/vnd.senx.warpscript": { + "source": "iana" + }, + "text/vnd.si.uricatalogue": { + "source": "iana" + }, + "text/vnd.sosi": { + "source": "iana" + }, + "text/vnd.sun.j2me.app-descriptor": { + "source": "iana", + "charset": "UTF-8", + "extensions": ["jad"] + }, + "text/vnd.trolltech.linguist": { + "source": "iana", + "charset": "UTF-8" + }, + "text/vnd.wap.si": { + "source": "iana" + }, + "text/vnd.wap.sl": { + "source": "iana" + }, + "text/vnd.wap.wml": { + "source": "iana", + "extensions": ["wml"] + }, + "text/vnd.wap.wmlscript": { + "source": "iana", + "extensions": ["wmls"] + }, + "text/vtt": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["vtt"] + }, + "text/x-asm": { + "source": "apache", + "extensions": ["s","asm"] + }, + "text/x-c": { + "source": "apache", + "extensions": ["c","cc","cxx","cpp","h","hh","dic"] + }, + "text/x-component": { + "source": "nginx", + "extensions": ["htc"] + }, + "text/x-fortran": { + "source": "apache", + "extensions": ["f","for","f77","f90"] + }, + "text/x-gwt-rpc": { + "compressible": true + }, + "text/x-handlebars-template": { + "extensions": ["hbs"] + }, + "text/x-java-source": { + "source": "apache", + "extensions": ["java"] + }, + "text/x-jquery-tmpl": { + "compressible": true + }, + "text/x-lua": { + "extensions": ["lua"] + }, + "text/x-markdown": { + "compressible": true, + "extensions": ["mkd"] + }, + "text/x-nfo": { + "source": "apache", + "extensions": ["nfo"] + }, + "text/x-opml": { + "source": "apache", + "extensions": ["opml"] + }, + "text/x-org": { + "compressible": true, + "extensions": ["org"] + }, + "text/x-pascal": { + "source": "apache", + "extensions": ["p","pas"] + }, + "text/x-processing": { + "compressible": true, + "extensions": ["pde"] + }, + "text/x-sass": { + "extensions": ["sass"] + }, + "text/x-scss": { + "extensions": ["scss"] + }, + "text/x-setext": { + "source": "apache", + "extensions": ["etx"] + }, + "text/x-sfv": { + "source": "apache", + "extensions": ["sfv"] + }, + "text/x-suse-ymp": { + "compressible": true, + "extensions": ["ymp"] + }, + "text/x-uuencode": { + "source": "apache", + "extensions": ["uu"] + }, + "text/x-vcalendar": { + "source": "apache", + "extensions": ["vcs"] + }, + "text/x-vcard": { + "source": "apache", + "extensions": ["vcf"] + }, + "text/xml": { + "source": "iana", + "compressible": true, + "extensions": ["xml"] + }, + "text/xml-external-parsed-entity": { + "source": "iana" + }, + "text/yaml": { + "compressible": true, + "extensions": ["yaml","yml"] + }, + "video/1d-interleaved-parityfec": { + "source": "iana" + }, + "video/3gpp": { + "source": "iana", + "extensions": ["3gp","3gpp"] + }, + "video/3gpp-tt": { + "source": "iana" + }, + "video/3gpp2": { + "source": "iana", + "extensions": ["3g2"] + }, + "video/av1": { + "source": "iana" + }, + "video/bmpeg": { + "source": "iana" + }, + "video/bt656": { + "source": "iana" + }, + "video/celb": { + "source": "iana" + }, + "video/dv": { + "source": "iana" + }, + "video/encaprtp": { + "source": "iana" + }, + "video/ffv1": { + "source": "iana" + }, + "video/flexfec": { + "source": "iana" + }, + "video/h261": { + "source": "iana", + "extensions": ["h261"] + }, + "video/h263": { + "source": "iana", + "extensions": ["h263"] + }, + "video/h263-1998": { + "source": "iana" + }, + "video/h263-2000": { + "source": "iana" + }, + "video/h264": { + "source": "iana", + "extensions": ["h264"] + }, + "video/h264-rcdo": { + "source": "iana" + }, + "video/h264-svc": { + "source": "iana" + }, + "video/h265": { + "source": "iana" + }, + "video/iso.segment": { + "source": "iana", + "extensions": ["m4s"] + }, + "video/jpeg": { + "source": "iana", + "extensions": ["jpgv"] + }, + "video/jpeg2000": { + "source": "iana" + }, + "video/jpm": { + "source": "apache", + "extensions": ["jpm","jpgm"] + }, + "video/jxsv": { + "source": "iana" + }, + "video/mj2": { + "source": "iana", + "extensions": ["mj2","mjp2"] + }, + "video/mp1s": { + "source": "iana" + }, + "video/mp2p": { + "source": "iana" + }, + "video/mp2t": { + "source": "iana", + "extensions": ["ts"] + }, + "video/mp4": { + "source": "iana", + "compressible": false, + "extensions": ["mp4","mp4v","mpg4"] + }, + "video/mp4v-es": { + "source": "iana" + }, + "video/mpeg": { + "source": "iana", + "compressible": false, + "extensions": ["mpeg","mpg","mpe","m1v","m2v"] + }, + "video/mpeg4-generic": { + "source": "iana" + }, + "video/mpv": { + "source": "iana" + }, + "video/nv": { + "source": "iana" + }, + "video/ogg": { + "source": "iana", + "compressible": false, + "extensions": ["ogv"] + }, + "video/parityfec": { + "source": "iana" + }, + "video/pointer": { + "source": "iana" + }, + "video/quicktime": { + "source": "iana", + "compressible": false, + "extensions": ["qt","mov"] + }, + "video/raptorfec": { + "source": "iana" + }, + "video/raw": { + "source": "iana" + }, + "video/rtp-enc-aescm128": { + "source": "iana" + }, + "video/rtploopback": { + "source": "iana" + }, + "video/rtx": { + "source": "iana" + }, + "video/scip": { + "source": "iana" + }, + "video/smpte291": { + "source": "iana" + }, + "video/smpte292m": { + "source": "iana" + }, + "video/ulpfec": { + "source": "iana" + }, + "video/vc1": { + "source": "iana" + }, + "video/vc2": { + "source": "iana" + }, + "video/vnd.cctv": { + "source": "iana" + }, + "video/vnd.dece.hd": { + "source": "iana", + "extensions": ["uvh","uvvh"] + }, + "video/vnd.dece.mobile": { + "source": "iana", + "extensions": ["uvm","uvvm"] + }, + "video/vnd.dece.mp4": { + "source": "iana" + }, + "video/vnd.dece.pd": { + "source": "iana", + "extensions": ["uvp","uvvp"] + }, + "video/vnd.dece.sd": { + "source": "iana", + "extensions": ["uvs","uvvs"] + }, + "video/vnd.dece.video": { + "source": "iana", + "extensions": ["uvv","uvvv"] + }, + "video/vnd.directv.mpeg": { + "source": "iana" + }, + "video/vnd.directv.mpeg-tts": { + "source": "iana" + }, + "video/vnd.dlna.mpeg-tts": { + "source": "iana" + }, + "video/vnd.dvb.file": { + "source": "iana", + "extensions": ["dvb"] + }, + "video/vnd.fvt": { + "source": "iana", + "extensions": ["fvt"] + }, + "video/vnd.hns.video": { + "source": "iana" + }, + "video/vnd.iptvforum.1dparityfec-1010": { + "source": "iana" + }, + "video/vnd.iptvforum.1dparityfec-2005": { + "source": "iana" + }, + "video/vnd.iptvforum.2dparityfec-1010": { + "source": "iana" + }, + "video/vnd.iptvforum.2dparityfec-2005": { + "source": "iana" + }, + "video/vnd.iptvforum.ttsavc": { + "source": "iana" + }, + "video/vnd.iptvforum.ttsmpeg2": { + "source": "iana" + }, + "video/vnd.motorola.video": { + "source": "iana" + }, + "video/vnd.motorola.videop": { + "source": "iana" + }, + "video/vnd.mpegurl": { + "source": "iana", + "extensions": ["mxu","m4u"] + }, + "video/vnd.ms-playready.media.pyv": { + "source": "iana", + "extensions": ["pyv"] + }, + "video/vnd.nokia.interleaved-multimedia": { + "source": "iana" + }, + "video/vnd.nokia.mp4vr": { + "source": "iana" + }, + "video/vnd.nokia.videovoip": { + "source": "iana" + }, + "video/vnd.objectvideo": { + "source": "iana" + }, + "video/vnd.radgamettools.bink": { + "source": "iana" + }, + "video/vnd.radgamettools.smacker": { + "source": "iana" + }, + "video/vnd.sealed.mpeg1": { + "source": "iana" + }, + "video/vnd.sealed.mpeg4": { + "source": "iana" + }, + "video/vnd.sealed.swf": { + "source": "iana" + }, + "video/vnd.sealedmedia.softseal.mov": { + "source": "iana" + }, + "video/vnd.uvvu.mp4": { + "source": "iana", + "extensions": ["uvu","uvvu"] + }, + "video/vnd.vivo": { + "source": "iana", + "extensions": ["viv"] + }, + "video/vnd.youtube.yt": { + "source": "iana" + }, + "video/vp8": { + "source": "iana" + }, + "video/vp9": { + "source": "iana" + }, + "video/webm": { + "source": "apache", + "compressible": false, + "extensions": ["webm"] + }, + "video/x-f4v": { + "source": "apache", + "extensions": ["f4v"] + }, + "video/x-fli": { + "source": "apache", + "extensions": ["fli"] + }, + "video/x-flv": { + "source": "apache", + "compressible": false, + "extensions": ["flv"] + }, + "video/x-m4v": { + "source": "apache", + "extensions": ["m4v"] + }, + "video/x-matroska": { + "source": "apache", + "compressible": false, + "extensions": ["mkv","mk3d","mks"] + }, + "video/x-mng": { + "source": "apache", + "extensions": ["mng"] + }, + "video/x-ms-asf": { + "source": "apache", + "extensions": ["asf","asx"] + }, + "video/x-ms-vob": { + "source": "apache", + "extensions": ["vob"] + }, + "video/x-ms-wm": { + "source": "apache", + "extensions": ["wm"] + }, + "video/x-ms-wmv": { + "source": "apache", + "compressible": false, + "extensions": ["wmv"] + }, + "video/x-ms-wmx": { + "source": "apache", + "extensions": ["wmx"] + }, + "video/x-ms-wvx": { + "source": "apache", + "extensions": ["wvx"] + }, + "video/x-msvideo": { + "source": "apache", + "extensions": ["avi"] + }, + "video/x-sgi-movie": { + "source": "apache", + "extensions": ["movie"] + }, + "video/x-smv": { + "source": "apache", + "extensions": ["smv"] + }, + "x-conference/x-cooltalk": { + "source": "apache", + "extensions": ["ice"] + }, + "x-shader/x-fragment": { + "compressible": true + }, + "x-shader/x-vertex": { + "compressible": true + } +} diff --git a/backend/node_modules/mime-db/index.js b/backend/node_modules/mime-db/index.js new file mode 100644 index 0000000000000000000000000000000000000000..ec2be30de1663c20ea2166f33a583c9c0b84d029 --- /dev/null +++ b/backend/node_modules/mime-db/index.js @@ -0,0 +1,12 @@ +/*! + * mime-db + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015-2022 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * Module exports. + */ + +module.exports = require('./db.json') diff --git a/backend/node_modules/mime-db/package.json b/backend/node_modules/mime-db/package.json new file mode 100644 index 0000000000000000000000000000000000000000..32c14b846848a5627421f0fb4fb3108ad5183d76 --- /dev/null +++ b/backend/node_modules/mime-db/package.json @@ -0,0 +1,60 @@ +{ + "name": "mime-db", + "description": "Media Type Database", + "version": "1.52.0", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)", + "Robert Kieffer (http://github.com/broofa)" + ], + "license": "MIT", + "keywords": [ + "mime", + "db", + "type", + "types", + "database", + "charset", + "charsets" + ], + "repository": "jshttp/mime-db", + "devDependencies": { + "bluebird": "3.7.2", + "co": "4.6.0", + "cogent": "1.0.1", + "csv-parse": "4.16.3", + "eslint": "7.32.0", + "eslint-config-standard": "15.0.1", + "eslint-plugin-import": "2.25.4", + "eslint-plugin-markdown": "2.2.1", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "5.1.1", + "eslint-plugin-standard": "4.1.0", + "gnode": "0.1.2", + "media-typer": "1.1.0", + "mocha": "9.2.1", + "nyc": "15.1.0", + "raw-body": "2.5.0", + "stream-to-array": "2.3.0" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "db.json", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "build": "node scripts/build", + "fetch": "node scripts/fetch-apache && gnode scripts/fetch-iana && node scripts/fetch-nginx", + "lint": "eslint .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test", + "update": "npm run fetch && npm run build", + "version": "node scripts/version-history.js && git add HISTORY.md" + } +} diff --git a/backend/node_modules/mime-types/HISTORY.md b/backend/node_modules/mime-types/HISTORY.md new file mode 100644 index 0000000000000000000000000000000000000000..c5043b75b958766a3880805dc4f19d70a4f167dd --- /dev/null +++ b/backend/node_modules/mime-types/HISTORY.md @@ -0,0 +1,397 @@ +2.1.35 / 2022-03-12 +=================== + + * deps: mime-db@1.52.0 + - Add extensions from IANA for more `image/*` types + - Add extension `.asc` to `application/pgp-keys` + - Add extensions to various XML types + - Add new upstream MIME types + +2.1.34 / 2021-11-08 +=================== + + * deps: mime-db@1.51.0 + - Add new upstream MIME types + +2.1.33 / 2021-10-01 +=================== + + * deps: mime-db@1.50.0 + - Add deprecated iWorks mime types and extensions + - Add new upstream MIME types + +2.1.32 / 2021-07-27 +=================== + + * deps: mime-db@1.49.0 + - Add extension `.trig` to `application/trig` + - Add new upstream MIME types + +2.1.31 / 2021-06-01 +=================== + + * deps: mime-db@1.48.0 + - Add extension `.mvt` to `application/vnd.mapbox-vector-tile` + - Add new upstream MIME types + +2.1.30 / 2021-04-02 +=================== + + * deps: mime-db@1.47.0 + - Add extension `.amr` to `audio/amr` + - Remove ambigious extensions from IANA for `application/*+xml` types + - Update primary extension to `.es` for `application/ecmascript` + +2.1.29 / 2021-02-17 +=================== + + * deps: mime-db@1.46.0 + - Add extension `.amr` to `audio/amr` + - Add extension `.m4s` to `video/iso.segment` + - Add extension `.opus` to `audio/ogg` + - Add new upstream MIME types + +2.1.28 / 2021-01-01 +=================== + + * deps: mime-db@1.45.0 + - Add `application/ubjson` with extension `.ubj` + - Add `image/avif` with extension `.avif` + - Add `image/ktx2` with extension `.ktx2` + - Add extension `.dbf` to `application/vnd.dbf` + - Add extension `.rar` to `application/vnd.rar` + - Add extension `.td` to `application/urc-targetdesc+xml` + - Add new upstream MIME types + - Fix extension of `application/vnd.apple.keynote` to be `.key` + +2.1.27 / 2020-04-23 +=================== + + * deps: mime-db@1.44.0 + - Add charsets from IANA + - Add extension `.cjs` to `application/node` + - Add new upstream MIME types + +2.1.26 / 2020-01-05 +=================== + + * deps: mime-db@1.43.0 + - Add `application/x-keepass2` with extension `.kdbx` + - Add extension `.mxmf` to `audio/mobile-xmf` + - Add extensions from IANA for `application/*+xml` types + - Add new upstream MIME types + +2.1.25 / 2019-11-12 +=================== + + * deps: mime-db@1.42.0 + - Add new upstream MIME types + - Add `application/toml` with extension `.toml` + - Add `image/vnd.ms-dds` with extension `.dds` + +2.1.24 / 2019-04-20 +=================== + + * deps: mime-db@1.40.0 + - Add extensions from IANA for `model/*` types + - Add `text/mdx` with extension `.mdx` + +2.1.23 / 2019-04-17 +=================== + + * deps: mime-db@~1.39.0 + - Add extensions `.siv` and `.sieve` to `application/sieve` + - Add new upstream MIME types + +2.1.22 / 2019-02-14 +=================== + + * deps: mime-db@~1.38.0 + - Add extension `.nq` to `application/n-quads` + - Add extension `.nt` to `application/n-triples` + - Add new upstream MIME types + +2.1.21 / 2018-10-19 +=================== + + * deps: mime-db@~1.37.0 + - Add extensions to HEIC image types + - Add new upstream MIME types + +2.1.20 / 2018-08-26 +=================== + + * deps: mime-db@~1.36.0 + - Add Apple file extensions from IANA + - Add extensions from IANA for `image/*` types + - Add new upstream MIME types + +2.1.19 / 2018-07-17 +=================== + + * deps: mime-db@~1.35.0 + - Add extension `.csl` to `application/vnd.citationstyles.style+xml` + - Add extension `.es` to `application/ecmascript` + - Add extension `.owl` to `application/rdf+xml` + - Add new upstream MIME types + - Add UTF-8 as default charset for `text/turtle` + +2.1.18 / 2018-02-16 +=================== + + * deps: mime-db@~1.33.0 + - Add `application/raml+yaml` with extension `.raml` + - Add `application/wasm` with extension `.wasm` + - Add `text/shex` with extension `.shex` + - Add extensions for JPEG-2000 images + - Add extensions from IANA for `message/*` types + - Add new upstream MIME types + - Update font MIME types + - Update `text/hjson` to registered `application/hjson` + +2.1.17 / 2017-09-01 +=================== + + * deps: mime-db@~1.30.0 + - Add `application/vnd.ms-outlook` + - Add `application/x-arj` + - Add extension `.mjs` to `application/javascript` + - Add glTF types and extensions + - Add new upstream MIME types + - Add `text/x-org` + - Add VirtualBox MIME types + - Fix `source` records for `video/*` types that are IANA + - Update `font/opentype` to registered `font/otf` + +2.1.16 / 2017-07-24 +=================== + + * deps: mime-db@~1.29.0 + - Add `application/fido.trusted-apps+json` + - Add extension `.wadl` to `application/vnd.sun.wadl+xml` + - Add extension `.gz` to `application/gzip` + - Add new upstream MIME types + - Update extensions `.md` and `.markdown` to be `text/markdown` + +2.1.15 / 2017-03-23 +=================== + + * deps: mime-db@~1.27.0 + - Add new mime types + - Add `image/apng` + +2.1.14 / 2017-01-14 +=================== + + * deps: mime-db@~1.26.0 + - Add new mime types + +2.1.13 / 2016-11-18 +=================== + + * deps: mime-db@~1.25.0 + - Add new mime types + +2.1.12 / 2016-09-18 +=================== + + * deps: mime-db@~1.24.0 + - Add new mime types + - Add `audio/mp3` + +2.1.11 / 2016-05-01 +=================== + + * deps: mime-db@~1.23.0 + - Add new mime types + +2.1.10 / 2016-02-15 +=================== + + * deps: mime-db@~1.22.0 + - Add new mime types + - Fix extension of `application/dash+xml` + - Update primary extension for `audio/mp4` + +2.1.9 / 2016-01-06 +================== + + * deps: mime-db@~1.21.0 + - Add new mime types + +2.1.8 / 2015-11-30 +================== + + * deps: mime-db@~1.20.0 + - Add new mime types + +2.1.7 / 2015-09-20 +================== + + * deps: mime-db@~1.19.0 + - Add new mime types + +2.1.6 / 2015-09-03 +================== + + * deps: mime-db@~1.18.0 + - Add new mime types + +2.1.5 / 2015-08-20 +================== + + * deps: mime-db@~1.17.0 + - Add new mime types + +2.1.4 / 2015-07-30 +================== + + * deps: mime-db@~1.16.0 + - Add new mime types + +2.1.3 / 2015-07-13 +================== + + * deps: mime-db@~1.15.0 + - Add new mime types + +2.1.2 / 2015-06-25 +================== + + * deps: mime-db@~1.14.0 + - Add new mime types + +2.1.1 / 2015-06-08 +================== + + * perf: fix deopt during mapping + +2.1.0 / 2015-06-07 +================== + + * Fix incorrectly treating extension-less file name as extension + - i.e. `'path/to/json'` will no longer return `application/json` + * Fix `.charset(type)` to accept parameters + * Fix `.charset(type)` to match case-insensitive + * Improve generation of extension to MIME mapping + * Refactor internals for readability and no argument reassignment + * Prefer `application/*` MIME types from the same source + * Prefer any type over `application/octet-stream` + * deps: mime-db@~1.13.0 + - Add nginx as a source + - Add new mime types + +2.0.14 / 2015-06-06 +=================== + + * deps: mime-db@~1.12.0 + - Add new mime types + +2.0.13 / 2015-05-31 +=================== + + * deps: mime-db@~1.11.0 + - Add new mime types + +2.0.12 / 2015-05-19 +=================== + + * deps: mime-db@~1.10.0 + - Add new mime types + +2.0.11 / 2015-05-05 +=================== + + * deps: mime-db@~1.9.1 + - Add new mime types + +2.0.10 / 2015-03-13 +=================== + + * deps: mime-db@~1.8.0 + - Add new mime types + +2.0.9 / 2015-02-09 +================== + + * deps: mime-db@~1.7.0 + - Add new mime types + - Community extensions ownership transferred from `node-mime` + +2.0.8 / 2015-01-29 +================== + + * deps: mime-db@~1.6.0 + - Add new mime types + +2.0.7 / 2014-12-30 +================== + + * deps: mime-db@~1.5.0 + - Add new mime types + - Fix various invalid MIME type entries + +2.0.6 / 2014-12-30 +================== + + * deps: mime-db@~1.4.0 + - Add new mime types + - Fix various invalid MIME type entries + - Remove example template MIME types + +2.0.5 / 2014-12-29 +================== + + * deps: mime-db@~1.3.1 + - Fix missing extensions + +2.0.4 / 2014-12-10 +================== + + * deps: mime-db@~1.3.0 + - Add new mime types + +2.0.3 / 2014-11-09 +================== + + * deps: mime-db@~1.2.0 + - Add new mime types + +2.0.2 / 2014-09-28 +================== + + * deps: mime-db@~1.1.0 + - Add new mime types + - Update charsets + +2.0.1 / 2014-09-07 +================== + + * Support Node.js 0.6 + +2.0.0 / 2014-09-02 +================== + + * Use `mime-db` + * Remove `.define()` + +1.0.2 / 2014-08-04 +================== + + * Set charset=utf-8 for `text/javascript` + +1.0.1 / 2014-06-24 +================== + + * Add `text/jsx` type + +1.0.0 / 2014-05-12 +================== + + * Return `false` for unknown types + * Set charset=utf-8 for `application/json` + +0.1.0 / 2014-05-02 +================== + + * Initial release diff --git a/backend/node_modules/mime-types/LICENSE b/backend/node_modules/mime-types/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..06166077be4d1f620d89b9eb33c76d89e75857da --- /dev/null +++ b/backend/node_modules/mime-types/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/backend/node_modules/mime-types/README.md b/backend/node_modules/mime-types/README.md new file mode 100644 index 0000000000000000000000000000000000000000..48d2fb477241e837c6e8d349777aac312746029b --- /dev/null +++ b/backend/node_modules/mime-types/README.md @@ -0,0 +1,113 @@ +# mime-types + +[![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][ci-image]][ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +The ultimate javascript content-type utility. + +Similar to [the `mime@1.x` module](https://www.npmjs.com/package/mime), except: + +- __No fallbacks.__ Instead of naively returning the first available type, + `mime-types` simply returns `false`, so do + `var type = mime.lookup('unrecognized') || 'application/octet-stream'`. +- No `new Mime()` business, so you could do `var lookup = require('mime-types').lookup`. +- No `.define()` functionality +- Bug fixes for `.lookup(path)` + +Otherwise, the API is compatible with `mime` 1.x. + +## Install + +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 mime-types +``` + +## Adding Types + +All mime types are based on [mime-db](https://www.npmjs.com/package/mime-db), +so open a PR there if you'd like to add mime types. + +## API + +```js +var mime = require('mime-types') +``` + +All functions return `false` if input is invalid or not found. + +### mime.lookup(path) + +Lookup the content-type associated with a file. + +```js +mime.lookup('json') // 'application/json' +mime.lookup('.md') // 'text/markdown' +mime.lookup('file.html') // 'text/html' +mime.lookup('folder/file.js') // 'application/javascript' +mime.lookup('folder/.htaccess') // false + +mime.lookup('cats') // false +``` + +### mime.contentType(type) + +Create a full content-type header given a content-type or extension. +When given an extension, `mime.lookup` is used to get the matching +content-type, otherwise the given content-type is used. Then if the +content-type does not already have a `charset` parameter, `mime.charset` +is used to get the default charset and add to the returned content-type. + +```js +mime.contentType('markdown') // 'text/x-markdown; charset=utf-8' +mime.contentType('file.json') // 'application/json; charset=utf-8' +mime.contentType('text/html') // 'text/html; charset=utf-8' +mime.contentType('text/html; charset=iso-8859-1') // 'text/html; charset=iso-8859-1' + +// from a full path +mime.contentType(path.extname('/path/to/file.json')) // 'application/json; charset=utf-8' +``` + +### mime.extension(type) + +Get the default extension for a content-type. + +```js +mime.extension('application/octet-stream') // 'bin' +``` + +### mime.charset(type) + +Lookup the implied default charset of a content-type. + +```js +mime.charset('text/markdown') // 'UTF-8' +``` + +### var type = mime.types[extension] + +A map of content-types by extension. + +### [extensions...] = mime.extensions[type] + +A map of extensions by content-type. + +## License + +[MIT](LICENSE) + +[ci-image]: https://badgen.net/github/checks/jshttp/mime-types/master?label=ci +[ci-url]: https://github.com/jshttp/mime-types/actions/workflows/ci.yml +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/mime-types/master +[coveralls-url]: https://coveralls.io/r/jshttp/mime-types?branch=master +[node-version-image]: https://badgen.net/npm/node/mime-types +[node-version-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/mime-types +[npm-url]: https://npmjs.org/package/mime-types +[npm-version-image]: https://badgen.net/npm/v/mime-types diff --git a/backend/node_modules/mime-types/index.js b/backend/node_modules/mime-types/index.js new file mode 100644 index 0000000000000000000000000000000000000000..b9f34d5991077fe9fadc7d9187a7225db7e58fca --- /dev/null +++ b/backend/node_modules/mime-types/index.js @@ -0,0 +1,188 @@ +/*! + * mime-types + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var db = require('mime-db') +var extname = require('path').extname + +/** + * Module variables. + * @private + */ + +var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/ +var TEXT_TYPE_REGEXP = /^text\//i + +/** + * Module exports. + * @public + */ + +exports.charset = charset +exports.charsets = { lookup: charset } +exports.contentType = contentType +exports.extension = extension +exports.extensions = Object.create(null) +exports.lookup = lookup +exports.types = Object.create(null) + +// Populate the extensions/types maps +populateMaps(exports.extensions, exports.types) + +/** + * Get the default charset for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ + +function charset (type) { + if (!type || typeof type !== 'string') { + return false + } + + // TODO: use media-typer + var match = EXTRACT_TYPE_REGEXP.exec(type) + var mime = match && db[match[1].toLowerCase()] + + if (mime && mime.charset) { + return mime.charset + } + + // default text/* to utf-8 + if (match && TEXT_TYPE_REGEXP.test(match[1])) { + return 'UTF-8' + } + + return false +} + +/** + * Create a full Content-Type header given a MIME type or extension. + * + * @param {string} str + * @return {boolean|string} + */ + +function contentType (str) { + // TODO: should this even be in this module? + if (!str || typeof str !== 'string') { + return false + } + + var mime = str.indexOf('/') === -1 + ? exports.lookup(str) + : str + + if (!mime) { + return false + } + + // TODO: use content-type or other module + if (mime.indexOf('charset') === -1) { + var charset = exports.charset(mime) + if (charset) mime += '; charset=' + charset.toLowerCase() + } + + return mime +} + +/** + * Get the default extension for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ + +function extension (type) { + if (!type || typeof type !== 'string') { + return false + } + + // TODO: use media-typer + var match = EXTRACT_TYPE_REGEXP.exec(type) + + // get extensions + var exts = match && exports.extensions[match[1].toLowerCase()] + + if (!exts || !exts.length) { + return false + } + + return exts[0] +} + +/** + * Lookup the MIME type for a file path/extension. + * + * @param {string} path + * @return {boolean|string} + */ + +function lookup (path) { + if (!path || typeof path !== 'string') { + return false + } + + // get the extension ("ext" or ".ext" or full path) + var extension = extname('x.' + path) + .toLowerCase() + .substr(1) + + if (!extension) { + return false + } + + return exports.types[extension] || false +} + +/** + * Populate the extensions and types maps. + * @private + */ + +function populateMaps (extensions, types) { + // source preference (least -> most) + var preference = ['nginx', 'apache', undefined, 'iana'] + + Object.keys(db).forEach(function forEachMimeType (type) { + var mime = db[type] + var exts = mime.extensions + + if (!exts || !exts.length) { + return + } + + // mime -> extensions + extensions[type] = exts + + // extension -> mime + for (var i = 0; i < exts.length; i++) { + var extension = exts[i] + + if (types[extension]) { + var from = preference.indexOf(db[types[extension]].source) + var to = preference.indexOf(mime.source) + + if (types[extension] !== 'application/octet-stream' && + (from > to || (from === to && types[extension].substr(0, 12) === 'application/'))) { + // skip the remapping + continue + } + } + + // set the extension -> mime + types[extension] = type + } + }) +} diff --git a/backend/node_modules/mime-types/package.json b/backend/node_modules/mime-types/package.json new file mode 100644 index 0000000000000000000000000000000000000000..bbef6964509e73f95e5b390b3923f919c72b6528 --- /dev/null +++ b/backend/node_modules/mime-types/package.json @@ -0,0 +1,44 @@ +{ + "name": "mime-types", + "description": "The ultimate javascript content-type utility.", + "version": "2.1.35", + "contributors": [ + "Douglas Christopher Wilson ", + "Jeremiah Senkpiel (https://searchbeam.jit.su)", + "Jonathan Ong (http://jongleberry.com)" + ], + "license": "MIT", + "keywords": [ + "mime", + "types" + ], + "repository": "jshttp/mime-types", + "dependencies": { + "mime-db": "1.52.0" + }, + "devDependencies": { + "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": "5.2.0", + "eslint-plugin-standard": "4.1.0", + "mocha": "9.2.2", + "nyc": "15.1.0" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --reporter spec test/test.js", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test" + } +} diff --git a/backend/node_modules/mime/.npmignore b/backend/node_modules/mime/.npmignore new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/backend/node_modules/mime/CHANGELOG.md b/backend/node_modules/mime/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..f1275350531d30ca6dd665cbb5fe78fc5e702948 --- /dev/null +++ b/backend/node_modules/mime/CHANGELOG.md @@ -0,0 +1,164 @@ +# Changelog + +## v1.6.0 (24/11/2017) +*No changelog for this release.* + +--- + +## v2.0.4 (24/11/2017) +- [**closed**] Switch to mime-score module for resolving extension contention issues. [#182](https://github.com/broofa/node-mime/issues/182) +- [**closed**] Update mime-db to 1.31.0 in v1.x branch [#181](https://github.com/broofa/node-mime/issues/181) + +--- + +## v1.5.0 (22/11/2017) +- [**closed**] need ES5 version ready in npm package [#179](https://github.com/broofa/node-mime/issues/179) +- [**closed**] mime-db no trace of iWork - pages / numbers / etc. [#178](https://github.com/broofa/node-mime/issues/178) +- [**closed**] How it works in brownser ? [#176](https://github.com/broofa/node-mime/issues/176) +- [**closed**] Missing `./Mime` [#175](https://github.com/broofa/node-mime/issues/175) +- [**closed**] Vulnerable Regular Expression [#167](https://github.com/broofa/node-mime/issues/167) + +--- + +## v2.0.3 (25/09/2017) +*No changelog for this release.* + +--- + +## v1.4.1 (25/09/2017) +- [**closed**] Issue when bundling with webpack [#172](https://github.com/broofa/node-mime/issues/172) + +--- + +## v2.0.2 (15/09/2017) +- [**V2**] fs.readFileSync is not a function [#165](https://github.com/broofa/node-mime/issues/165) +- [**closed**] The extension for video/quicktime should map to .mov, not .qt [#164](https://github.com/broofa/node-mime/issues/164) +- [**V2**] [v2 Feedback request] Mime class API [#163](https://github.com/broofa/node-mime/issues/163) +- [**V2**] [v2 Feedback request] Resolving conflicts over extensions [#162](https://github.com/broofa/node-mime/issues/162) +- [**V2**] Allow callers to load module with official, full, or no defined types. [#161](https://github.com/broofa/node-mime/issues/161) +- [**V2**] Use "facets" to resolve extension conflicts [#160](https://github.com/broofa/node-mime/issues/160) +- [**V2**] Remove fs and path dependencies [#152](https://github.com/broofa/node-mime/issues/152) +- [**V2**] Default content-type should not be application/octet-stream [#139](https://github.com/broofa/node-mime/issues/139) +- [**V2**] reset mime-types [#124](https://github.com/broofa/node-mime/issues/124) +- [**V2**] Extensionless paths should return null or false [#113](https://github.com/broofa/node-mime/issues/113) + +--- + +## v2.0.1 (14/09/2017) +- [**closed**] Changelog for v2.0 does not mention breaking changes [#171](https://github.com/broofa/node-mime/issues/171) +- [**closed**] MIME breaking with 'class' declaration as it is without 'use strict mode' [#170](https://github.com/broofa/node-mime/issues/170) + +--- + +## v2.0.0 (12/09/2017) +- [**closed**] woff and woff2 [#168](https://github.com/broofa/node-mime/issues/168) + +--- + +## v1.4.0 (28/08/2017) +- [**closed**] support for ac3 voc files [#159](https://github.com/broofa/node-mime/issues/159) +- [**closed**] Help understanding change from application/xml to text/xml [#158](https://github.com/broofa/node-mime/issues/158) +- [**closed**] no longer able to override mimetype [#157](https://github.com/broofa/node-mime/issues/157) +- [**closed**] application/vnd.adobe.photoshop [#147](https://github.com/broofa/node-mime/issues/147) +- [**closed**] Directories should appear as something other than application/octet-stream [#135](https://github.com/broofa/node-mime/issues/135) +- [**closed**] requested features [#131](https://github.com/broofa/node-mime/issues/131) +- [**closed**] Make types.json loading optional? [#129](https://github.com/broofa/node-mime/issues/129) +- [**closed**] Cannot find module './types.json' [#120](https://github.com/broofa/node-mime/issues/120) +- [**V2**] .wav files show up as "audio/x-wav" instead of "audio/x-wave" [#118](https://github.com/broofa/node-mime/issues/118) +- [**closed**] Don't be a pain in the ass for node community [#108](https://github.com/broofa/node-mime/issues/108) +- [**closed**] don't make default_type global [#78](https://github.com/broofa/node-mime/issues/78) +- [**closed**] mime.extension() fails if the content-type is parameterized [#74](https://github.com/broofa/node-mime/issues/74) + +--- + +## v1.3.6 (11/05/2017) +- [**closed**] .md should be text/markdown as of March 2016 [#154](https://github.com/broofa/node-mime/issues/154) +- [**closed**] Error while installing mime [#153](https://github.com/broofa/node-mime/issues/153) +- [**closed**] application/manifest+json [#149](https://github.com/broofa/node-mime/issues/149) +- [**closed**] Dynamic adaptive streaming over HTTP (DASH) file extension typo [#141](https://github.com/broofa/node-mime/issues/141) +- [**closed**] charsets image/png undefined [#140](https://github.com/broofa/node-mime/issues/140) +- [**closed**] Mime-db dependency out of date [#130](https://github.com/broofa/node-mime/issues/130) +- [**closed**] how to support plist? [#126](https://github.com/broofa/node-mime/issues/126) +- [**closed**] how does .types file format look like? [#123](https://github.com/broofa/node-mime/issues/123) +- [**closed**] Feature: support for expanding MIME patterns [#121](https://github.com/broofa/node-mime/issues/121) +- [**closed**] DEBUG_MIME doesn't work [#117](https://github.com/broofa/node-mime/issues/117) + +--- + +## v1.3.4 (06/02/2015) +*No changelog for this release.* + +--- + +## v1.3.3 (06/02/2015) +*No changelog for this release.* + +--- + +## v1.3.1 (05/02/2015) +- [**closed**] Consider adding support for Handlebars .hbs file ending [#111](https://github.com/broofa/node-mime/issues/111) +- [**closed**] Consider adding support for hjson. [#110](https://github.com/broofa/node-mime/issues/110) +- [**closed**] Add mime type for Opus audio files [#94](https://github.com/broofa/node-mime/issues/94) +- [**closed**] Consider making the `Requesting New Types` information more visible [#77](https://github.com/broofa/node-mime/issues/77) + +--- + +## v1.3.0 (05/02/2015) +- [**closed**] Add common name? [#114](https://github.com/broofa/node-mime/issues/114) +- [**closed**] application/x-yaml [#104](https://github.com/broofa/node-mime/issues/104) +- [**closed**] Add mime type for WOFF file format 2.0 [#102](https://github.com/broofa/node-mime/issues/102) +- [**closed**] application/x-msi for .msi [#99](https://github.com/broofa/node-mime/issues/99) +- [**closed**] Add mimetype for gettext translation files [#98](https://github.com/broofa/node-mime/issues/98) +- [**closed**] collaborators [#88](https://github.com/broofa/node-mime/issues/88) +- [**closed**] getting errot in installation of mime module...any1 can help? [#87](https://github.com/broofa/node-mime/issues/87) +- [**closed**] should application/json's charset be utf8? [#86](https://github.com/broofa/node-mime/issues/86) +- [**closed**] Add "license" and "licenses" to package.json [#81](https://github.com/broofa/node-mime/issues/81) +- [**closed**] lookup with extension-less file on Windows returns wrong type [#68](https://github.com/broofa/node-mime/issues/68) + +--- + +## v1.2.11 (15/08/2013) +- [**closed**] Update mime.types [#65](https://github.com/broofa/node-mime/issues/65) +- [**closed**] Publish a new version [#63](https://github.com/broofa/node-mime/issues/63) +- [**closed**] README should state upfront that "application/octet-stream" is default for unknown extension [#55](https://github.com/broofa/node-mime/issues/55) +- [**closed**] Suggested improvement to the charset API [#52](https://github.com/broofa/node-mime/issues/52) + +--- + +## v1.2.10 (25/07/2013) +- [**closed**] Mime type for woff files should be application/font-woff and not application/x-font-woff [#62](https://github.com/broofa/node-mime/issues/62) +- [**closed**] node.types in conflict with mime.types [#51](https://github.com/broofa/node-mime/issues/51) + +--- + +## v1.2.9 (17/01/2013) +- [**closed**] Please update "mime" NPM [#49](https://github.com/broofa/node-mime/issues/49) +- [**closed**] Please add semicolon [#46](https://github.com/broofa/node-mime/issues/46) +- [**closed**] parse full mime types [#43](https://github.com/broofa/node-mime/issues/43) + +--- + +## v1.2.8 (10/01/2013) +- [**closed**] /js directory mime is application/javascript. Is it correct? [#47](https://github.com/broofa/node-mime/issues/47) +- [**closed**] Add mime types for lua code. [#45](https://github.com/broofa/node-mime/issues/45) + +--- + +## v1.2.7 (19/10/2012) +- [**closed**] cannot install 1.2.7 via npm [#41](https://github.com/broofa/node-mime/issues/41) +- [**closed**] Transfer ownership to @broofa [#36](https://github.com/broofa/node-mime/issues/36) +- [**closed**] it's wrong to set charset to UTF-8 for text [#30](https://github.com/broofa/node-mime/issues/30) +- [**closed**] Allow multiple instances of MIME types container [#27](https://github.com/broofa/node-mime/issues/27) + +--- + +## v1.2.5 (16/02/2012) +- [**closed**] When looking up a types, check hasOwnProperty [#23](https://github.com/broofa/node-mime/issues/23) +- [**closed**] Bump version to 1.2.2 [#18](https://github.com/broofa/node-mime/issues/18) +- [**closed**] No license [#16](https://github.com/broofa/node-mime/issues/16) +- [**closed**] Some types missing that are used by html5/css3 [#13](https://github.com/broofa/node-mime/issues/13) +- [**closed**] npm install fails for 1.2.1 [#12](https://github.com/broofa/node-mime/issues/12) +- [**closed**] image/pjpeg + image/x-png [#10](https://github.com/broofa/node-mime/issues/10) +- [**closed**] symlink [#8](https://github.com/broofa/node-mime/issues/8) +- [**closed**] gzip [#2](https://github.com/broofa/node-mime/issues/2) +- [**closed**] ALL CAPS filenames return incorrect mime type [#1](https://github.com/broofa/node-mime/issues/1) diff --git a/backend/node_modules/mime/LICENSE b/backend/node_modules/mime/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d3f46f7e145990dad5954d78c5da9a2c2bdcbe36 --- /dev/null +++ b/backend/node_modules/mime/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2010 Benjamin Thomas, Robert Kieffer + +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/backend/node_modules/mime/README.md b/backend/node_modules/mime/README.md new file mode 100644 index 0000000000000000000000000000000000000000..506fbe550a8dee9f0bde702fda6a040dfed3aba8 --- /dev/null +++ b/backend/node_modules/mime/README.md @@ -0,0 +1,90 @@ +# mime + +Comprehensive MIME type mapping API based on mime-db module. + +## Install + +Install with [npm](http://github.com/isaacs/npm): + + npm install mime + +## Contributing / Testing + + npm run test + +## Command Line + + mime [path_string] + +E.g. + + > mime scripts/jquery.js + application/javascript + +## API - Queries + +### mime.lookup(path) +Get the mime type associated with a file, if no mime type is found `application/octet-stream` is returned. Performs a case-insensitive lookup using the extension in `path` (the substring after the last '/' or '.'). E.g. + +```js +var mime = require('mime'); + +mime.lookup('/path/to/file.txt'); // => 'text/plain' +mime.lookup('file.txt'); // => 'text/plain' +mime.lookup('.TXT'); // => 'text/plain' +mime.lookup('htm'); // => 'text/html' +``` + +### mime.default_type +Sets the mime type returned when `mime.lookup` fails to find the extension searched for. (Default is `application/octet-stream`.) + +### mime.extension(type) +Get the default extension for `type` + +```js +mime.extension('text/html'); // => 'html' +mime.extension('application/octet-stream'); // => 'bin' +``` + +### mime.charsets.lookup() + +Map mime-type to charset + +```js +mime.charsets.lookup('text/plain'); // => 'UTF-8' +``` + +(The logic for charset lookups is pretty rudimentary. Feel free to suggest improvements.) + +## API - Defining Custom Types + +Custom type mappings can be added on a per-project basis via the following APIs. + +### mime.define() + +Add custom mime/extension mappings + +```js +mime.define({ + 'text/x-some-format': ['x-sf', 'x-sft', 'x-sfml'], + 'application/x-my-type': ['x-mt', 'x-mtt'], + // etc ... +}); + +mime.lookup('x-sft'); // => 'text/x-some-format' +``` + +The first entry in the extensions array is returned by `mime.extension()`. E.g. + +```js +mime.extension('text/x-some-format'); // => 'x-sf' +``` + +### mime.load(filepath) + +Load mappings from an Apache ".types" format file + +```js +mime.load('./my_project.types'); +``` +The .types file format is simple - See the `types` dir for examples. diff --git a/backend/node_modules/mime/cli.js b/backend/node_modules/mime/cli.js new file mode 100755 index 0000000000000000000000000000000000000000..20b1ffeb2f97648e0faa7e022c98ed9e6a8e9a0d --- /dev/null +++ b/backend/node_modules/mime/cli.js @@ -0,0 +1,8 @@ +#!/usr/bin/env node + +var mime = require('./mime.js'); +var file = process.argv[2]; +var type = mime.lookup(file); + +process.stdout.write(type + '\n'); + diff --git a/backend/node_modules/mime/mime.js b/backend/node_modules/mime/mime.js new file mode 100644 index 0000000000000000000000000000000000000000..d7efbde70b8e95fb7f67da9c8cfed11ce8ce4133 --- /dev/null +++ b/backend/node_modules/mime/mime.js @@ -0,0 +1,108 @@ +var path = require('path'); +var fs = require('fs'); + +function Mime() { + // Map of extension -> mime type + this.types = Object.create(null); + + // Map of mime type -> extension + this.extensions = Object.create(null); +} + +/** + * Define mimetype -> extension mappings. Each key is a mime-type that maps + * to an array of extensions associated with the type. The first extension is + * used as the default extension for the type. + * + * e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']}); + * + * @param map (Object) type definitions + */ +Mime.prototype.define = function (map) { + for (var type in map) { + var exts = map[type]; + for (var i = 0; i < exts.length; i++) { + if (process.env.DEBUG_MIME && this.types[exts[i]]) { + console.warn((this._loading || "define()").replace(/.*\//, ''), 'changes "' + exts[i] + '" extension type from ' + + this.types[exts[i]] + ' to ' + type); + } + + this.types[exts[i]] = type; + } + + // Default extension is the first one we encounter + if (!this.extensions[type]) { + this.extensions[type] = exts[0]; + } + } +}; + +/** + * Load an Apache2-style ".types" file + * + * This may be called multiple times (it's expected). Where files declare + * overlapping types/extensions, the last file wins. + * + * @param file (String) path of file to load. + */ +Mime.prototype.load = function(file) { + this._loading = file; + // Read file and split into lines + var map = {}, + content = fs.readFileSync(file, 'ascii'), + lines = content.split(/[\r\n]+/); + + lines.forEach(function(line) { + // Clean up whitespace/comments, and split into fields + var fields = line.replace(/\s*#.*|^\s*|\s*$/g, '').split(/\s+/); + map[fields.shift()] = fields; + }); + + this.define(map); + + this._loading = null; +}; + +/** + * Lookup a mime type based on extension + */ +Mime.prototype.lookup = function(path, fallback) { + var ext = path.replace(/^.*[\.\/\\]/, '').toLowerCase(); + + return this.types[ext] || fallback || this.default_type; +}; + +/** + * Return file extension associated with a mime type + */ +Mime.prototype.extension = function(mimeType) { + var type = mimeType.match(/^\s*([^;\s]*)(?:;|\s|$)/)[1].toLowerCase(); + return this.extensions[type]; +}; + +// Default instance +var mime = new Mime(); + +// Define built-in types +mime.define(require('./types.json')); + +// Default type +mime.default_type = mime.lookup('bin'); + +// +// Additional API specific to the default instance +// + +mime.Mime = Mime; + +/** + * Lookup a charset based on mime type. + */ +mime.charsets = { + lookup: function(mimeType, fallback) { + // Assume text types are utf8 + return (/^text\/|^application\/(javascript|json)/).test(mimeType) ? 'UTF-8' : fallback; + } +}; + +module.exports = mime; diff --git a/backend/node_modules/mime/package.json b/backend/node_modules/mime/package.json new file mode 100644 index 0000000000000000000000000000000000000000..6bd24bc53c1a7067b60f43e559d1739d138b987f --- /dev/null +++ b/backend/node_modules/mime/package.json @@ -0,0 +1,44 @@ +{ + "author": { + "name": "Robert Kieffer", + "url": "http://github.com/broofa", + "email": "robert@broofa.com" + }, + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4" + }, + "contributors": [ + { + "name": "Benjamin Thomas", + "url": "http://github.com/bentomas", + "email": "benjamin@benjaminthomas.org" + } + ], + "description": "A comprehensive library for mime-type mapping", + "license": "MIT", + "dependencies": {}, + "devDependencies": { + "github-release-notes": "0.13.1", + "mime-db": "1.31.0", + "mime-score": "1.1.0" + }, + "scripts": { + "prepare": "node src/build.js", + "changelog": "gren changelog --tags=all --generate --override", + "test": "node src/test.js" + }, + "keywords": [ + "util", + "mime" + ], + "main": "mime.js", + "name": "mime", + "repository": { + "url": "https://github.com/broofa/node-mime", + "type": "git" + }, + "version": "1.6.0" +} diff --git a/backend/node_modules/mime/src/build.js b/backend/node_modules/mime/src/build.js new file mode 100755 index 0000000000000000000000000000000000000000..4928e48bcd5db783074ca4d842ba24931645e1f6 --- /dev/null +++ b/backend/node_modules/mime/src/build.js @@ -0,0 +1,53 @@ +#!/usr/bin/env node + +'use strict'; + +const fs = require('fs'); +const path = require('path'); +const mimeScore = require('mime-score'); + +let db = require('mime-db'); +let chalk = require('chalk'); + +const STANDARD_FACET_SCORE = 900; + +const byExtension = {}; + +// Clear out any conflict extensions in mime-db +for (let type in db) { + let entry = db[type]; + entry.type = type; + + if (!entry.extensions) continue; + + entry.extensions.forEach(ext => { + if (ext in byExtension) { + const e0 = entry; + const e1 = byExtension[ext]; + e0.pri = mimeScore(e0.type, e0.source); + e1.pri = mimeScore(e1.type, e1.source); + + let drop = e0.pri < e1.pri ? e0 : e1; + let keep = e0.pri >= e1.pri ? e0 : e1; + drop.extensions = drop.extensions.filter(e => e !== ext); + + console.log(`${ext}: Keeping ${chalk.green(keep.type)} (${keep.pri}), dropping ${chalk.red(drop.type)} (${drop.pri})`); + } + byExtension[ext] = entry; + }); +} + +function writeTypesFile(types, path) { + fs.writeFileSync(path, JSON.stringify(types)); +} + +// Segregate into standard and non-standard types based on facet per +// https://tools.ietf.org/html/rfc6838#section-3.1 +const types = {}; + +Object.keys(db).sort().forEach(k => { + const entry = db[k]; + types[entry.type] = entry.extensions; +}); + +writeTypesFile(types, path.join(__dirname, '..', 'types.json')); diff --git a/backend/node_modules/mime/src/test.js b/backend/node_modules/mime/src/test.js new file mode 100644 index 0000000000000000000000000000000000000000..42958a20d5bdbae6a4724c6a8cc99f292b00b265 --- /dev/null +++ b/backend/node_modules/mime/src/test.js @@ -0,0 +1,60 @@ +/** + * Usage: node test.js + */ + +var mime = require('../mime'); +var assert = require('assert'); +var path = require('path'); + +// +// Test mime lookups +// + +assert.equal('text/plain', mime.lookup('text.txt')); // normal file +assert.equal('text/plain', mime.lookup('TEXT.TXT')); // uppercase +assert.equal('text/plain', mime.lookup('dir/text.txt')); // dir + file +assert.equal('text/plain', mime.lookup('.text.txt')); // hidden file +assert.equal('text/plain', mime.lookup('.txt')); // nameless +assert.equal('text/plain', mime.lookup('txt')); // extension-only +assert.equal('text/plain', mime.lookup('/txt')); // extension-less () +assert.equal('text/plain', mime.lookup('\\txt')); // Windows, extension-less +assert.equal('application/octet-stream', mime.lookup('text.nope')); // unrecognized +assert.equal('fallback', mime.lookup('text.fallback', 'fallback')); // alternate default + +// +// Test extensions +// + +assert.equal('txt', mime.extension(mime.types.text)); +assert.equal('html', mime.extension(mime.types.htm)); +assert.equal('bin', mime.extension('application/octet-stream')); +assert.equal('bin', mime.extension('application/octet-stream ')); +assert.equal('html', mime.extension(' text/html; charset=UTF-8')); +assert.equal('html', mime.extension('text/html; charset=UTF-8 ')); +assert.equal('html', mime.extension('text/html; charset=UTF-8')); +assert.equal('html', mime.extension('text/html ; charset=UTF-8')); +assert.equal('html', mime.extension('text/html;charset=UTF-8')); +assert.equal('html', mime.extension('text/Html;charset=UTF-8')); +assert.equal(undefined, mime.extension('unrecognized')); + +// +// Test node.types lookups +// + +assert.equal('font/woff', mime.lookup('file.woff')); +assert.equal('application/octet-stream', mime.lookup('file.buffer')); +// TODO: Uncomment once #157 is resolved +// assert.equal('audio/mp4', mime.lookup('file.m4a')); +assert.equal('font/otf', mime.lookup('file.otf')); + +// +// Test charsets +// + +assert.equal('UTF-8', mime.charsets.lookup('text/plain')); +assert.equal('UTF-8', mime.charsets.lookup(mime.types.js)); +assert.equal('UTF-8', mime.charsets.lookup(mime.types.json)); +assert.equal(undefined, mime.charsets.lookup(mime.types.bin)); +assert.equal('fallback', mime.charsets.lookup('application/octet-stream', 'fallback')); + +console.log('\nAll tests passed'); diff --git a/backend/node_modules/mime/types.json b/backend/node_modules/mime/types.json new file mode 100644 index 0000000000000000000000000000000000000000..bec78abd491e093599b2615533687a6b3c360526 --- /dev/null +++ b/backend/node_modules/mime/types.json @@ -0,0 +1 @@ +{"application/andrew-inset":["ez"],"application/applixware":["aw"],"application/atom+xml":["atom"],"application/atomcat+xml":["atomcat"],"application/atomsvc+xml":["atomsvc"],"application/bdoc":["bdoc"],"application/ccxml+xml":["ccxml"],"application/cdmi-capability":["cdmia"],"application/cdmi-container":["cdmic"],"application/cdmi-domain":["cdmid"],"application/cdmi-object":["cdmio"],"application/cdmi-queue":["cdmiq"],"application/cu-seeme":["cu"],"application/dash+xml":["mpd"],"application/davmount+xml":["davmount"],"application/docbook+xml":["dbk"],"application/dssc+der":["dssc"],"application/dssc+xml":["xdssc"],"application/ecmascript":["ecma"],"application/emma+xml":["emma"],"application/epub+zip":["epub"],"application/exi":["exi"],"application/font-tdpfr":["pfr"],"application/font-woff":[],"application/font-woff2":[],"application/geo+json":["geojson"],"application/gml+xml":["gml"],"application/gpx+xml":["gpx"],"application/gxf":["gxf"],"application/gzip":["gz"],"application/hyperstudio":["stk"],"application/inkml+xml":["ink","inkml"],"application/ipfix":["ipfix"],"application/java-archive":["jar","war","ear"],"application/java-serialized-object":["ser"],"application/java-vm":["class"],"application/javascript":["js","mjs"],"application/json":["json","map"],"application/json5":["json5"],"application/jsonml+json":["jsonml"],"application/ld+json":["jsonld"],"application/lost+xml":["lostxml"],"application/mac-binhex40":["hqx"],"application/mac-compactpro":["cpt"],"application/mads+xml":["mads"],"application/manifest+json":["webmanifest"],"application/marc":["mrc"],"application/marcxml+xml":["mrcx"],"application/mathematica":["ma","nb","mb"],"application/mathml+xml":["mathml"],"application/mbox":["mbox"],"application/mediaservercontrol+xml":["mscml"],"application/metalink+xml":["metalink"],"application/metalink4+xml":["meta4"],"application/mets+xml":["mets"],"application/mods+xml":["mods"],"application/mp21":["m21","mp21"],"application/mp4":["mp4s","m4p"],"application/msword":["doc","dot"],"application/mxf":["mxf"],"application/octet-stream":["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"],"application/oda":["oda"],"application/oebps-package+xml":["opf"],"application/ogg":["ogx"],"application/omdoc+xml":["omdoc"],"application/onenote":["onetoc","onetoc2","onetmp","onepkg"],"application/oxps":["oxps"],"application/patch-ops-error+xml":["xer"],"application/pdf":["pdf"],"application/pgp-encrypted":["pgp"],"application/pgp-signature":["asc","sig"],"application/pics-rules":["prf"],"application/pkcs10":["p10"],"application/pkcs7-mime":["p7m","p7c"],"application/pkcs7-signature":["p7s"],"application/pkcs8":["p8"],"application/pkix-attr-cert":["ac"],"application/pkix-cert":["cer"],"application/pkix-crl":["crl"],"application/pkix-pkipath":["pkipath"],"application/pkixcmp":["pki"],"application/pls+xml":["pls"],"application/postscript":["ai","eps","ps"],"application/prs.cww":["cww"],"application/pskc+xml":["pskcxml"],"application/raml+yaml":["raml"],"application/rdf+xml":["rdf"],"application/reginfo+xml":["rif"],"application/relax-ng-compact-syntax":["rnc"],"application/resource-lists+xml":["rl"],"application/resource-lists-diff+xml":["rld"],"application/rls-services+xml":["rs"],"application/rpki-ghostbusters":["gbr"],"application/rpki-manifest":["mft"],"application/rpki-roa":["roa"],"application/rsd+xml":["rsd"],"application/rss+xml":["rss"],"application/rtf":["rtf"],"application/sbml+xml":["sbml"],"application/scvp-cv-request":["scq"],"application/scvp-cv-response":["scs"],"application/scvp-vp-request":["spq"],"application/scvp-vp-response":["spp"],"application/sdp":["sdp"],"application/set-payment-initiation":["setpay"],"application/set-registration-initiation":["setreg"],"application/shf+xml":["shf"],"application/smil+xml":["smi","smil"],"application/sparql-query":["rq"],"application/sparql-results+xml":["srx"],"application/srgs":["gram"],"application/srgs+xml":["grxml"],"application/sru+xml":["sru"],"application/ssdl+xml":["ssdl"],"application/ssml+xml":["ssml"],"application/tei+xml":["tei","teicorpus"],"application/thraud+xml":["tfi"],"application/timestamped-data":["tsd"],"application/vnd.3gpp.pic-bw-large":["plb"],"application/vnd.3gpp.pic-bw-small":["psb"],"application/vnd.3gpp.pic-bw-var":["pvb"],"application/vnd.3gpp2.tcap":["tcap"],"application/vnd.3m.post-it-notes":["pwn"],"application/vnd.accpac.simply.aso":["aso"],"application/vnd.accpac.simply.imp":["imp"],"application/vnd.acucobol":["acu"],"application/vnd.acucorp":["atc","acutc"],"application/vnd.adobe.air-application-installer-package+zip":["air"],"application/vnd.adobe.formscentral.fcdt":["fcdt"],"application/vnd.adobe.fxp":["fxp","fxpl"],"application/vnd.adobe.xdp+xml":["xdp"],"application/vnd.adobe.xfdf":["xfdf"],"application/vnd.ahead.space":["ahead"],"application/vnd.airzip.filesecure.azf":["azf"],"application/vnd.airzip.filesecure.azs":["azs"],"application/vnd.amazon.ebook":["azw"],"application/vnd.americandynamics.acc":["acc"],"application/vnd.amiga.ami":["ami"],"application/vnd.android.package-archive":["apk"],"application/vnd.anser-web-certificate-issue-initiation":["cii"],"application/vnd.anser-web-funds-transfer-initiation":["fti"],"application/vnd.antix.game-component":["atx"],"application/vnd.apple.installer+xml":["mpkg"],"application/vnd.apple.mpegurl":["m3u8"],"application/vnd.apple.pkpass":["pkpass"],"application/vnd.aristanetworks.swi":["swi"],"application/vnd.astraea-software.iota":["iota"],"application/vnd.audiograph":["aep"],"application/vnd.blueice.multipass":["mpm"],"application/vnd.bmi":["bmi"],"application/vnd.businessobjects":["rep"],"application/vnd.chemdraw+xml":["cdxml"],"application/vnd.chipnuts.karaoke-mmd":["mmd"],"application/vnd.cinderella":["cdy"],"application/vnd.claymore":["cla"],"application/vnd.cloanto.rp9":["rp9"],"application/vnd.clonk.c4group":["c4g","c4d","c4f","c4p","c4u"],"application/vnd.cluetrust.cartomobile-config":["c11amc"],"application/vnd.cluetrust.cartomobile-config-pkg":["c11amz"],"application/vnd.commonspace":["csp"],"application/vnd.contact.cmsg":["cdbcmsg"],"application/vnd.cosmocaller":["cmc"],"application/vnd.crick.clicker":["clkx"],"application/vnd.crick.clicker.keyboard":["clkk"],"application/vnd.crick.clicker.palette":["clkp"],"application/vnd.crick.clicker.template":["clkt"],"application/vnd.crick.clicker.wordbank":["clkw"],"application/vnd.criticaltools.wbs+xml":["wbs"],"application/vnd.ctc-posml":["pml"],"application/vnd.cups-ppd":["ppd"],"application/vnd.curl.car":["car"],"application/vnd.curl.pcurl":["pcurl"],"application/vnd.dart":["dart"],"application/vnd.data-vision.rdz":["rdz"],"application/vnd.dece.data":["uvf","uvvf","uvd","uvvd"],"application/vnd.dece.ttml+xml":["uvt","uvvt"],"application/vnd.dece.unspecified":["uvx","uvvx"],"application/vnd.dece.zip":["uvz","uvvz"],"application/vnd.denovo.fcselayout-link":["fe_launch"],"application/vnd.dna":["dna"],"application/vnd.dolby.mlp":["mlp"],"application/vnd.dpgraph":["dpg"],"application/vnd.dreamfactory":["dfac"],"application/vnd.ds-keypoint":["kpxx"],"application/vnd.dvb.ait":["ait"],"application/vnd.dvb.service":["svc"],"application/vnd.dynageo":["geo"],"application/vnd.ecowin.chart":["mag"],"application/vnd.enliven":["nml"],"application/vnd.epson.esf":["esf"],"application/vnd.epson.msf":["msf"],"application/vnd.epson.quickanime":["qam"],"application/vnd.epson.salt":["slt"],"application/vnd.epson.ssf":["ssf"],"application/vnd.eszigno3+xml":["es3","et3"],"application/vnd.ezpix-album":["ez2"],"application/vnd.ezpix-package":["ez3"],"application/vnd.fdf":["fdf"],"application/vnd.fdsn.mseed":["mseed"],"application/vnd.fdsn.seed":["seed","dataless"],"application/vnd.flographit":["gph"],"application/vnd.fluxtime.clip":["ftc"],"application/vnd.framemaker":["fm","frame","maker","book"],"application/vnd.frogans.fnc":["fnc"],"application/vnd.frogans.ltf":["ltf"],"application/vnd.fsc.weblaunch":["fsc"],"application/vnd.fujitsu.oasys":["oas"],"application/vnd.fujitsu.oasys2":["oa2"],"application/vnd.fujitsu.oasys3":["oa3"],"application/vnd.fujitsu.oasysgp":["fg5"],"application/vnd.fujitsu.oasysprs":["bh2"],"application/vnd.fujixerox.ddd":["ddd"],"application/vnd.fujixerox.docuworks":["xdw"],"application/vnd.fujixerox.docuworks.binder":["xbd"],"application/vnd.fuzzysheet":["fzs"],"application/vnd.genomatix.tuxedo":["txd"],"application/vnd.geogebra.file":["ggb"],"application/vnd.geogebra.tool":["ggt"],"application/vnd.geometry-explorer":["gex","gre"],"application/vnd.geonext":["gxt"],"application/vnd.geoplan":["g2w"],"application/vnd.geospace":["g3w"],"application/vnd.gmx":["gmx"],"application/vnd.google-apps.document":["gdoc"],"application/vnd.google-apps.presentation":["gslides"],"application/vnd.google-apps.spreadsheet":["gsheet"],"application/vnd.google-earth.kml+xml":["kml"],"application/vnd.google-earth.kmz":["kmz"],"application/vnd.grafeq":["gqf","gqs"],"application/vnd.groove-account":["gac"],"application/vnd.groove-help":["ghf"],"application/vnd.groove-identity-message":["gim"],"application/vnd.groove-injector":["grv"],"application/vnd.groove-tool-message":["gtm"],"application/vnd.groove-tool-template":["tpl"],"application/vnd.groove-vcard":["vcg"],"application/vnd.hal+xml":["hal"],"application/vnd.handheld-entertainment+xml":["zmm"],"application/vnd.hbci":["hbci"],"application/vnd.hhe.lesson-player":["les"],"application/vnd.hp-hpgl":["hpgl"],"application/vnd.hp-hpid":["hpid"],"application/vnd.hp-hps":["hps"],"application/vnd.hp-jlyt":["jlt"],"application/vnd.hp-pcl":["pcl"],"application/vnd.hp-pclxl":["pclxl"],"application/vnd.hydrostatix.sof-data":["sfd-hdstx"],"application/vnd.ibm.minipay":["mpy"],"application/vnd.ibm.modcap":["afp","listafp","list3820"],"application/vnd.ibm.rights-management":["irm"],"application/vnd.ibm.secure-container":["sc"],"application/vnd.iccprofile":["icc","icm"],"application/vnd.igloader":["igl"],"application/vnd.immervision-ivp":["ivp"],"application/vnd.immervision-ivu":["ivu"],"application/vnd.insors.igm":["igm"],"application/vnd.intercon.formnet":["xpw","xpx"],"application/vnd.intergeo":["i2g"],"application/vnd.intu.qbo":["qbo"],"application/vnd.intu.qfx":["qfx"],"application/vnd.ipunplugged.rcprofile":["rcprofile"],"application/vnd.irepository.package+xml":["irp"],"application/vnd.is-xpr":["xpr"],"application/vnd.isac.fcs":["fcs"],"application/vnd.jam":["jam"],"application/vnd.jcp.javame.midlet-rms":["rms"],"application/vnd.jisp":["jisp"],"application/vnd.joost.joda-archive":["joda"],"application/vnd.kahootz":["ktz","ktr"],"application/vnd.kde.karbon":["karbon"],"application/vnd.kde.kchart":["chrt"],"application/vnd.kde.kformula":["kfo"],"application/vnd.kde.kivio":["flw"],"application/vnd.kde.kontour":["kon"],"application/vnd.kde.kpresenter":["kpr","kpt"],"application/vnd.kde.kspread":["ksp"],"application/vnd.kde.kword":["kwd","kwt"],"application/vnd.kenameaapp":["htke"],"application/vnd.kidspiration":["kia"],"application/vnd.kinar":["kne","knp"],"application/vnd.koan":["skp","skd","skt","skm"],"application/vnd.kodak-descriptor":["sse"],"application/vnd.las.las+xml":["lasxml"],"application/vnd.llamagraphics.life-balance.desktop":["lbd"],"application/vnd.llamagraphics.life-balance.exchange+xml":["lbe"],"application/vnd.lotus-1-2-3":["123"],"application/vnd.lotus-approach":["apr"],"application/vnd.lotus-freelance":["pre"],"application/vnd.lotus-notes":["nsf"],"application/vnd.lotus-organizer":["org"],"application/vnd.lotus-screencam":["scm"],"application/vnd.lotus-wordpro":["lwp"],"application/vnd.macports.portpkg":["portpkg"],"application/vnd.mcd":["mcd"],"application/vnd.medcalcdata":["mc1"],"application/vnd.mediastation.cdkey":["cdkey"],"application/vnd.mfer":["mwf"],"application/vnd.mfmp":["mfm"],"application/vnd.micrografx.flo":["flo"],"application/vnd.micrografx.igx":["igx"],"application/vnd.mif":["mif"],"application/vnd.mobius.daf":["daf"],"application/vnd.mobius.dis":["dis"],"application/vnd.mobius.mbk":["mbk"],"application/vnd.mobius.mqy":["mqy"],"application/vnd.mobius.msl":["msl"],"application/vnd.mobius.plc":["plc"],"application/vnd.mobius.txf":["txf"],"application/vnd.mophun.application":["mpn"],"application/vnd.mophun.certificate":["mpc"],"application/vnd.mozilla.xul+xml":["xul"],"application/vnd.ms-artgalry":["cil"],"application/vnd.ms-cab-compressed":["cab"],"application/vnd.ms-excel":["xls","xlm","xla","xlc","xlt","xlw"],"application/vnd.ms-excel.addin.macroenabled.12":["xlam"],"application/vnd.ms-excel.sheet.binary.macroenabled.12":["xlsb"],"application/vnd.ms-excel.sheet.macroenabled.12":["xlsm"],"application/vnd.ms-excel.template.macroenabled.12":["xltm"],"application/vnd.ms-fontobject":["eot"],"application/vnd.ms-htmlhelp":["chm"],"application/vnd.ms-ims":["ims"],"application/vnd.ms-lrm":["lrm"],"application/vnd.ms-officetheme":["thmx"],"application/vnd.ms-outlook":["msg"],"application/vnd.ms-pki.seccat":["cat"],"application/vnd.ms-pki.stl":["stl"],"application/vnd.ms-powerpoint":["ppt","pps","pot"],"application/vnd.ms-powerpoint.addin.macroenabled.12":["ppam"],"application/vnd.ms-powerpoint.presentation.macroenabled.12":["pptm"],"application/vnd.ms-powerpoint.slide.macroenabled.12":["sldm"],"application/vnd.ms-powerpoint.slideshow.macroenabled.12":["ppsm"],"application/vnd.ms-powerpoint.template.macroenabled.12":["potm"],"application/vnd.ms-project":["mpp","mpt"],"application/vnd.ms-word.document.macroenabled.12":["docm"],"application/vnd.ms-word.template.macroenabled.12":["dotm"],"application/vnd.ms-works":["wps","wks","wcm","wdb"],"application/vnd.ms-wpl":["wpl"],"application/vnd.ms-xpsdocument":["xps"],"application/vnd.mseq":["mseq"],"application/vnd.musician":["mus"],"application/vnd.muvee.style":["msty"],"application/vnd.mynfc":["taglet"],"application/vnd.neurolanguage.nlu":["nlu"],"application/vnd.nitf":["ntf","nitf"],"application/vnd.noblenet-directory":["nnd"],"application/vnd.noblenet-sealer":["nns"],"application/vnd.noblenet-web":["nnw"],"application/vnd.nokia.n-gage.data":["ngdat"],"application/vnd.nokia.n-gage.symbian.install":["n-gage"],"application/vnd.nokia.radio-preset":["rpst"],"application/vnd.nokia.radio-presets":["rpss"],"application/vnd.novadigm.edm":["edm"],"application/vnd.novadigm.edx":["edx"],"application/vnd.novadigm.ext":["ext"],"application/vnd.oasis.opendocument.chart":["odc"],"application/vnd.oasis.opendocument.chart-template":["otc"],"application/vnd.oasis.opendocument.database":["odb"],"application/vnd.oasis.opendocument.formula":["odf"],"application/vnd.oasis.opendocument.formula-template":["odft"],"application/vnd.oasis.opendocument.graphics":["odg"],"application/vnd.oasis.opendocument.graphics-template":["otg"],"application/vnd.oasis.opendocument.image":["odi"],"application/vnd.oasis.opendocument.image-template":["oti"],"application/vnd.oasis.opendocument.presentation":["odp"],"application/vnd.oasis.opendocument.presentation-template":["otp"],"application/vnd.oasis.opendocument.spreadsheet":["ods"],"application/vnd.oasis.opendocument.spreadsheet-template":["ots"],"application/vnd.oasis.opendocument.text":["odt"],"application/vnd.oasis.opendocument.text-master":["odm"],"application/vnd.oasis.opendocument.text-template":["ott"],"application/vnd.oasis.opendocument.text-web":["oth"],"application/vnd.olpc-sugar":["xo"],"application/vnd.oma.dd2+xml":["dd2"],"application/vnd.openofficeorg.extension":["oxt"],"application/vnd.openxmlformats-officedocument.presentationml.presentation":["pptx"],"application/vnd.openxmlformats-officedocument.presentationml.slide":["sldx"],"application/vnd.openxmlformats-officedocument.presentationml.slideshow":["ppsx"],"application/vnd.openxmlformats-officedocument.presentationml.template":["potx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":["xlsx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.template":["xltx"],"application/vnd.openxmlformats-officedocument.wordprocessingml.document":["docx"],"application/vnd.openxmlformats-officedocument.wordprocessingml.template":["dotx"],"application/vnd.osgeo.mapguide.package":["mgp"],"application/vnd.osgi.dp":["dp"],"application/vnd.osgi.subsystem":["esa"],"application/vnd.palm":["pdb","pqa","oprc"],"application/vnd.pawaafile":["paw"],"application/vnd.pg.format":["str"],"application/vnd.pg.osasli":["ei6"],"application/vnd.picsel":["efif"],"application/vnd.pmi.widget":["wg"],"application/vnd.pocketlearn":["plf"],"application/vnd.powerbuilder6":["pbd"],"application/vnd.previewsystems.box":["box"],"application/vnd.proteus.magazine":["mgz"],"application/vnd.publishare-delta-tree":["qps"],"application/vnd.pvi.ptid1":["ptid"],"application/vnd.quark.quarkxpress":["qxd","qxt","qwd","qwt","qxl","qxb"],"application/vnd.realvnc.bed":["bed"],"application/vnd.recordare.musicxml":["mxl"],"application/vnd.recordare.musicxml+xml":["musicxml"],"application/vnd.rig.cryptonote":["cryptonote"],"application/vnd.rim.cod":["cod"],"application/vnd.rn-realmedia":["rm"],"application/vnd.rn-realmedia-vbr":["rmvb"],"application/vnd.route66.link66+xml":["link66"],"application/vnd.sailingtracker.track":["st"],"application/vnd.seemail":["see"],"application/vnd.sema":["sema"],"application/vnd.semd":["semd"],"application/vnd.semf":["semf"],"application/vnd.shana.informed.formdata":["ifm"],"application/vnd.shana.informed.formtemplate":["itp"],"application/vnd.shana.informed.interchange":["iif"],"application/vnd.shana.informed.package":["ipk"],"application/vnd.simtech-mindmapper":["twd","twds"],"application/vnd.smaf":["mmf"],"application/vnd.smart.teacher":["teacher"],"application/vnd.solent.sdkm+xml":["sdkm","sdkd"],"application/vnd.spotfire.dxp":["dxp"],"application/vnd.spotfire.sfs":["sfs"],"application/vnd.stardivision.calc":["sdc"],"application/vnd.stardivision.draw":["sda"],"application/vnd.stardivision.impress":["sdd"],"application/vnd.stardivision.math":["smf"],"application/vnd.stardivision.writer":["sdw","vor"],"application/vnd.stardivision.writer-global":["sgl"],"application/vnd.stepmania.package":["smzip"],"application/vnd.stepmania.stepchart":["sm"],"application/vnd.sun.wadl+xml":["wadl"],"application/vnd.sun.xml.calc":["sxc"],"application/vnd.sun.xml.calc.template":["stc"],"application/vnd.sun.xml.draw":["sxd"],"application/vnd.sun.xml.draw.template":["std"],"application/vnd.sun.xml.impress":["sxi"],"application/vnd.sun.xml.impress.template":["sti"],"application/vnd.sun.xml.math":["sxm"],"application/vnd.sun.xml.writer":["sxw"],"application/vnd.sun.xml.writer.global":["sxg"],"application/vnd.sun.xml.writer.template":["stw"],"application/vnd.sus-calendar":["sus","susp"],"application/vnd.svd":["svd"],"application/vnd.symbian.install":["sis","sisx"],"application/vnd.syncml+xml":["xsm"],"application/vnd.syncml.dm+wbxml":["bdm"],"application/vnd.syncml.dm+xml":["xdm"],"application/vnd.tao.intent-module-archive":["tao"],"application/vnd.tcpdump.pcap":["pcap","cap","dmp"],"application/vnd.tmobile-livetv":["tmo"],"application/vnd.trid.tpt":["tpt"],"application/vnd.triscape.mxs":["mxs"],"application/vnd.trueapp":["tra"],"application/vnd.ufdl":["ufd","ufdl"],"application/vnd.uiq.theme":["utz"],"application/vnd.umajin":["umj"],"application/vnd.unity":["unityweb"],"application/vnd.uoml+xml":["uoml"],"application/vnd.vcx":["vcx"],"application/vnd.visio":["vsd","vst","vss","vsw"],"application/vnd.visionary":["vis"],"application/vnd.vsf":["vsf"],"application/vnd.wap.wbxml":["wbxml"],"application/vnd.wap.wmlc":["wmlc"],"application/vnd.wap.wmlscriptc":["wmlsc"],"application/vnd.webturbo":["wtb"],"application/vnd.wolfram.player":["nbp"],"application/vnd.wordperfect":["wpd"],"application/vnd.wqd":["wqd"],"application/vnd.wt.stf":["stf"],"application/vnd.xara":["xar"],"application/vnd.xfdl":["xfdl"],"application/vnd.yamaha.hv-dic":["hvd"],"application/vnd.yamaha.hv-script":["hvs"],"application/vnd.yamaha.hv-voice":["hvp"],"application/vnd.yamaha.openscoreformat":["osf"],"application/vnd.yamaha.openscoreformat.osfpvg+xml":["osfpvg"],"application/vnd.yamaha.smaf-audio":["saf"],"application/vnd.yamaha.smaf-phrase":["spf"],"application/vnd.yellowriver-custom-menu":["cmp"],"application/vnd.zul":["zir","zirz"],"application/vnd.zzazz.deck+xml":["zaz"],"application/voicexml+xml":["vxml"],"application/wasm":["wasm"],"application/widget":["wgt"],"application/winhlp":["hlp"],"application/wsdl+xml":["wsdl"],"application/wspolicy+xml":["wspolicy"],"application/x-7z-compressed":["7z"],"application/x-abiword":["abw"],"application/x-ace-compressed":["ace"],"application/x-apple-diskimage":[],"application/x-arj":["arj"],"application/x-authorware-bin":["aab","x32","u32","vox"],"application/x-authorware-map":["aam"],"application/x-authorware-seg":["aas"],"application/x-bcpio":["bcpio"],"application/x-bdoc":[],"application/x-bittorrent":["torrent"],"application/x-blorb":["blb","blorb"],"application/x-bzip":["bz"],"application/x-bzip2":["bz2","boz"],"application/x-cbr":["cbr","cba","cbt","cbz","cb7"],"application/x-cdlink":["vcd"],"application/x-cfs-compressed":["cfs"],"application/x-chat":["chat"],"application/x-chess-pgn":["pgn"],"application/x-chrome-extension":["crx"],"application/x-cocoa":["cco"],"application/x-conference":["nsc"],"application/x-cpio":["cpio"],"application/x-csh":["csh"],"application/x-debian-package":["udeb"],"application/x-dgc-compressed":["dgc"],"application/x-director":["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"],"application/x-doom":["wad"],"application/x-dtbncx+xml":["ncx"],"application/x-dtbook+xml":["dtb"],"application/x-dtbresource+xml":["res"],"application/x-dvi":["dvi"],"application/x-envoy":["evy"],"application/x-eva":["eva"],"application/x-font-bdf":["bdf"],"application/x-font-ghostscript":["gsf"],"application/x-font-linux-psf":["psf"],"application/x-font-pcf":["pcf"],"application/x-font-snf":["snf"],"application/x-font-type1":["pfa","pfb","pfm","afm"],"application/x-freearc":["arc"],"application/x-futuresplash":["spl"],"application/x-gca-compressed":["gca"],"application/x-glulx":["ulx"],"application/x-gnumeric":["gnumeric"],"application/x-gramps-xml":["gramps"],"application/x-gtar":["gtar"],"application/x-hdf":["hdf"],"application/x-httpd-php":["php"],"application/x-install-instructions":["install"],"application/x-iso9660-image":[],"application/x-java-archive-diff":["jardiff"],"application/x-java-jnlp-file":["jnlp"],"application/x-latex":["latex"],"application/x-lua-bytecode":["luac"],"application/x-lzh-compressed":["lzh","lha"],"application/x-makeself":["run"],"application/x-mie":["mie"],"application/x-mobipocket-ebook":["prc","mobi"],"application/x-ms-application":["application"],"application/x-ms-shortcut":["lnk"],"application/x-ms-wmd":["wmd"],"application/x-ms-wmz":["wmz"],"application/x-ms-xbap":["xbap"],"application/x-msaccess":["mdb"],"application/x-msbinder":["obd"],"application/x-mscardfile":["crd"],"application/x-msclip":["clp"],"application/x-msdos-program":[],"application/x-msdownload":["com","bat"],"application/x-msmediaview":["mvb","m13","m14"],"application/x-msmetafile":["wmf","emf","emz"],"application/x-msmoney":["mny"],"application/x-mspublisher":["pub"],"application/x-msschedule":["scd"],"application/x-msterminal":["trm"],"application/x-mswrite":["wri"],"application/x-netcdf":["nc","cdf"],"application/x-ns-proxy-autoconfig":["pac"],"application/x-nzb":["nzb"],"application/x-perl":["pl","pm"],"application/x-pilot":[],"application/x-pkcs12":["p12","pfx"],"application/x-pkcs7-certificates":["p7b","spc"],"application/x-pkcs7-certreqresp":["p7r"],"application/x-rar-compressed":["rar"],"application/x-redhat-package-manager":["rpm"],"application/x-research-info-systems":["ris"],"application/x-sea":["sea"],"application/x-sh":["sh"],"application/x-shar":["shar"],"application/x-shockwave-flash":["swf"],"application/x-silverlight-app":["xap"],"application/x-sql":["sql"],"application/x-stuffit":["sit"],"application/x-stuffitx":["sitx"],"application/x-subrip":["srt"],"application/x-sv4cpio":["sv4cpio"],"application/x-sv4crc":["sv4crc"],"application/x-t3vm-image":["t3"],"application/x-tads":["gam"],"application/x-tar":["tar"],"application/x-tcl":["tcl","tk"],"application/x-tex":["tex"],"application/x-tex-tfm":["tfm"],"application/x-texinfo":["texinfo","texi"],"application/x-tgif":["obj"],"application/x-ustar":["ustar"],"application/x-virtualbox-hdd":["hdd"],"application/x-virtualbox-ova":["ova"],"application/x-virtualbox-ovf":["ovf"],"application/x-virtualbox-vbox":["vbox"],"application/x-virtualbox-vbox-extpack":["vbox-extpack"],"application/x-virtualbox-vdi":["vdi"],"application/x-virtualbox-vhd":["vhd"],"application/x-virtualbox-vmdk":["vmdk"],"application/x-wais-source":["src"],"application/x-web-app-manifest+json":["webapp"],"application/x-x509-ca-cert":["der","crt","pem"],"application/x-xfig":["fig"],"application/x-xliff+xml":["xlf"],"application/x-xpinstall":["xpi"],"application/x-xz":["xz"],"application/x-zmachine":["z1","z2","z3","z4","z5","z6","z7","z8"],"application/xaml+xml":["xaml"],"application/xcap-diff+xml":["xdf"],"application/xenc+xml":["xenc"],"application/xhtml+xml":["xhtml","xht"],"application/xml":["xml","xsl","xsd","rng"],"application/xml-dtd":["dtd"],"application/xop+xml":["xop"],"application/xproc+xml":["xpl"],"application/xslt+xml":["xslt"],"application/xspf+xml":["xspf"],"application/xv+xml":["mxml","xhvml","xvml","xvm"],"application/yang":["yang"],"application/yin+xml":["yin"],"application/zip":["zip"],"audio/3gpp":[],"audio/adpcm":["adp"],"audio/basic":["au","snd"],"audio/midi":["mid","midi","kar","rmi"],"audio/mp3":[],"audio/mp4":["m4a","mp4a"],"audio/mpeg":["mpga","mp2","mp2a","mp3","m2a","m3a"],"audio/ogg":["oga","ogg","spx"],"audio/s3m":["s3m"],"audio/silk":["sil"],"audio/vnd.dece.audio":["uva","uvva"],"audio/vnd.digital-winds":["eol"],"audio/vnd.dra":["dra"],"audio/vnd.dts":["dts"],"audio/vnd.dts.hd":["dtshd"],"audio/vnd.lucent.voice":["lvp"],"audio/vnd.ms-playready.media.pya":["pya"],"audio/vnd.nuera.ecelp4800":["ecelp4800"],"audio/vnd.nuera.ecelp7470":["ecelp7470"],"audio/vnd.nuera.ecelp9600":["ecelp9600"],"audio/vnd.rip":["rip"],"audio/wav":["wav"],"audio/wave":[],"audio/webm":["weba"],"audio/x-aac":["aac"],"audio/x-aiff":["aif","aiff","aifc"],"audio/x-caf":["caf"],"audio/x-flac":["flac"],"audio/x-m4a":[],"audio/x-matroska":["mka"],"audio/x-mpegurl":["m3u"],"audio/x-ms-wax":["wax"],"audio/x-ms-wma":["wma"],"audio/x-pn-realaudio":["ram","ra"],"audio/x-pn-realaudio-plugin":["rmp"],"audio/x-realaudio":[],"audio/x-wav":[],"audio/xm":["xm"],"chemical/x-cdx":["cdx"],"chemical/x-cif":["cif"],"chemical/x-cmdf":["cmdf"],"chemical/x-cml":["cml"],"chemical/x-csml":["csml"],"chemical/x-xyz":["xyz"],"font/collection":["ttc"],"font/otf":["otf"],"font/ttf":["ttf"],"font/woff":["woff"],"font/woff2":["woff2"],"image/apng":["apng"],"image/bmp":["bmp"],"image/cgm":["cgm"],"image/g3fax":["g3"],"image/gif":["gif"],"image/ief":["ief"],"image/jp2":["jp2","jpg2"],"image/jpeg":["jpeg","jpg","jpe"],"image/jpm":["jpm"],"image/jpx":["jpx","jpf"],"image/ktx":["ktx"],"image/png":["png"],"image/prs.btif":["btif"],"image/sgi":["sgi"],"image/svg+xml":["svg","svgz"],"image/tiff":["tiff","tif"],"image/vnd.adobe.photoshop":["psd"],"image/vnd.dece.graphic":["uvi","uvvi","uvg","uvvg"],"image/vnd.djvu":["djvu","djv"],"image/vnd.dvb.subtitle":[],"image/vnd.dwg":["dwg"],"image/vnd.dxf":["dxf"],"image/vnd.fastbidsheet":["fbs"],"image/vnd.fpx":["fpx"],"image/vnd.fst":["fst"],"image/vnd.fujixerox.edmics-mmr":["mmr"],"image/vnd.fujixerox.edmics-rlc":["rlc"],"image/vnd.ms-modi":["mdi"],"image/vnd.ms-photo":["wdp"],"image/vnd.net-fpx":["npx"],"image/vnd.wap.wbmp":["wbmp"],"image/vnd.xiff":["xif"],"image/webp":["webp"],"image/x-3ds":["3ds"],"image/x-cmu-raster":["ras"],"image/x-cmx":["cmx"],"image/x-freehand":["fh","fhc","fh4","fh5","fh7"],"image/x-icon":["ico"],"image/x-jng":["jng"],"image/x-mrsid-image":["sid"],"image/x-ms-bmp":[],"image/x-pcx":["pcx"],"image/x-pict":["pic","pct"],"image/x-portable-anymap":["pnm"],"image/x-portable-bitmap":["pbm"],"image/x-portable-graymap":["pgm"],"image/x-portable-pixmap":["ppm"],"image/x-rgb":["rgb"],"image/x-tga":["tga"],"image/x-xbitmap":["xbm"],"image/x-xpixmap":["xpm"],"image/x-xwindowdump":["xwd"],"message/rfc822":["eml","mime"],"model/gltf+json":["gltf"],"model/gltf-binary":["glb"],"model/iges":["igs","iges"],"model/mesh":["msh","mesh","silo"],"model/vnd.collada+xml":["dae"],"model/vnd.dwf":["dwf"],"model/vnd.gdl":["gdl"],"model/vnd.gtw":["gtw"],"model/vnd.mts":["mts"],"model/vnd.vtu":["vtu"],"model/vrml":["wrl","vrml"],"model/x3d+binary":["x3db","x3dbz"],"model/x3d+vrml":["x3dv","x3dvz"],"model/x3d+xml":["x3d","x3dz"],"text/cache-manifest":["appcache","manifest"],"text/calendar":["ics","ifb"],"text/coffeescript":["coffee","litcoffee"],"text/css":["css"],"text/csv":["csv"],"text/hjson":["hjson"],"text/html":["html","htm","shtml"],"text/jade":["jade"],"text/jsx":["jsx"],"text/less":["less"],"text/markdown":["markdown","md"],"text/mathml":["mml"],"text/n3":["n3"],"text/plain":["txt","text","conf","def","list","log","in","ini"],"text/prs.lines.tag":["dsc"],"text/richtext":["rtx"],"text/rtf":[],"text/sgml":["sgml","sgm"],"text/slim":["slim","slm"],"text/stylus":["stylus","styl"],"text/tab-separated-values":["tsv"],"text/troff":["t","tr","roff","man","me","ms"],"text/turtle":["ttl"],"text/uri-list":["uri","uris","urls"],"text/vcard":["vcard"],"text/vnd.curl":["curl"],"text/vnd.curl.dcurl":["dcurl"],"text/vnd.curl.mcurl":["mcurl"],"text/vnd.curl.scurl":["scurl"],"text/vnd.dvb.subtitle":["sub"],"text/vnd.fly":["fly"],"text/vnd.fmi.flexstor":["flx"],"text/vnd.graphviz":["gv"],"text/vnd.in3d.3dml":["3dml"],"text/vnd.in3d.spot":["spot"],"text/vnd.sun.j2me.app-descriptor":["jad"],"text/vnd.wap.wml":["wml"],"text/vnd.wap.wmlscript":["wmls"],"text/vtt":["vtt"],"text/x-asm":["s","asm"],"text/x-c":["c","cc","cxx","cpp","h","hh","dic"],"text/x-component":["htc"],"text/x-fortran":["f","for","f77","f90"],"text/x-handlebars-template":["hbs"],"text/x-java-source":["java"],"text/x-lua":["lua"],"text/x-markdown":["mkd"],"text/x-nfo":["nfo"],"text/x-opml":["opml"],"text/x-org":[],"text/x-pascal":["p","pas"],"text/x-processing":["pde"],"text/x-sass":["sass"],"text/x-scss":["scss"],"text/x-setext":["etx"],"text/x-sfv":["sfv"],"text/x-suse-ymp":["ymp"],"text/x-uuencode":["uu"],"text/x-vcalendar":["vcs"],"text/x-vcard":["vcf"],"text/xml":[],"text/yaml":["yaml","yml"],"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/h261":["h261"],"video/h263":["h263"],"video/h264":["h264"],"video/jpeg":["jpgv"],"video/jpm":["jpgm"],"video/mj2":["mj2","mjp2"],"video/mp2t":["ts"],"video/mp4":["mp4","mp4v","mpg4"],"video/mpeg":["mpeg","mpg","mpe","m1v","m2v"],"video/ogg":["ogv"],"video/quicktime":["qt","mov"],"video/vnd.dece.hd":["uvh","uvvh"],"video/vnd.dece.mobile":["uvm","uvvm"],"video/vnd.dece.pd":["uvp","uvvp"],"video/vnd.dece.sd":["uvs","uvvs"],"video/vnd.dece.video":["uvv","uvvv"],"video/vnd.dvb.file":["dvb"],"video/vnd.fvt":["fvt"],"video/vnd.mpegurl":["mxu","m4u"],"video/vnd.ms-playready.media.pyv":["pyv"],"video/vnd.uvvu.mp4":["uvu","uvvu"],"video/vnd.vivo":["viv"],"video/webm":["webm"],"video/x-f4v":["f4v"],"video/x-fli":["fli"],"video/x-flv":["flv"],"video/x-m4v":["m4v"],"video/x-matroska":["mkv","mk3d","mks"],"video/x-mng":["mng"],"video/x-ms-asf":["asf","asx"],"video/x-ms-vob":["vob"],"video/x-ms-wm":["wm"],"video/x-ms-wmv":["wmv"],"video/x-ms-wmx":["wmx"],"video/x-ms-wvx":["wvx"],"video/x-msvideo":["avi"],"video/x-sgi-movie":["movie"],"video/x-smv":["smv"],"x-conference/x-cooltalk":["ice"]} \ No newline at end of file diff --git a/backend/node_modules/minimist/.eslintrc b/backend/node_modules/minimist/.eslintrc new file mode 100644 index 0000000000000000000000000000000000000000..bd1a5e046b4148dfc6bfd15c8aa69c81ae809a28 --- /dev/null +++ b/backend/node_modules/minimist/.eslintrc @@ -0,0 +1,29 @@ +{ + "root": true, + + "extends": "@ljharb/eslint-config/node/0.4", + + "rules": { + "array-element-newline": 0, + "complexity": 0, + "func-style": [2, "declaration"], + "max-lines-per-function": 0, + "max-nested-callbacks": 1, + "max-statements-per-line": 1, + "max-statements": 0, + "multiline-comment-style": 0, + "no-continue": 1, + "no-param-reassign": 1, + "no-restricted-syntax": 1, + "object-curly-newline": 0, + }, + + "overrides": [ + { + "files": "test/**", + "rules": { + "camelcase": 0, + }, + }, + ] +} diff --git a/backend/node_modules/minimist/.github/FUNDING.yml b/backend/node_modules/minimist/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..a9366222e92a9f9a7a2a4c4cf7cf0f011510924d --- /dev/null +++ b/backend/node_modules/minimist/.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/minimist +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/backend/node_modules/minimist/.nycrc b/backend/node_modules/minimist/.nycrc new file mode 100644 index 0000000000000000000000000000000000000000..55c3d29367a4216abea3dc5eaa48b59826da355b --- /dev/null +++ b/backend/node_modules/minimist/.nycrc @@ -0,0 +1,14 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "example", + "test" + ] +} diff --git a/backend/node_modules/minimist/CHANGELOG.md b/backend/node_modules/minimist/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..c9a1e15e6c2fe73a0ebf35040fef031b46437ba6 --- /dev/null +++ b/backend/node_modules/minimist/CHANGELOG.md @@ -0,0 +1,298 @@ +# 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.2.8](https://github.com/minimistjs/minimist/compare/v1.2.7...v1.2.8) - 2023-02-09 + +### Merged + +- [Fix] Fix long option followed by single dash [`#17`](https://github.com/minimistjs/minimist/pull/17) +- [Tests] Remove duplicate test [`#12`](https://github.com/minimistjs/minimist/pull/12) +- [Fix] opt.string works with multiple aliases [`#10`](https://github.com/minimistjs/minimist/pull/10) + +### Fixed + +- [Fix] Fix long option followed by single dash (#17) [`#15`](https://github.com/minimistjs/minimist/issues/15) +- [Tests] Remove duplicate test (#12) [`#8`](https://github.com/minimistjs/minimist/issues/8) +- [Fix] Fix long option followed by single dash [`#15`](https://github.com/minimistjs/minimist/issues/15) +- [Fix] opt.string works with multiple aliases (#10) [`#9`](https://github.com/minimistjs/minimist/issues/9) +- [Fix] Fix handling of short option with non-trivial equals [`#5`](https://github.com/minimistjs/minimist/issues/5) +- [Tests] Remove duplicate test [`#8`](https://github.com/minimistjs/minimist/issues/8) +- [Fix] opt.string works with multiple aliases [`#9`](https://github.com/minimistjs/minimist/issues/9) + +### Commits + +- Merge tag 'v0.2.3' [`a026794`](https://github.com/minimistjs/minimist/commit/a0267947c7870fc5847cf2d437fbe33f392767da) +- [eslint] fix indentation and whitespace [`5368ca4`](https://github.com/minimistjs/minimist/commit/5368ca4147e974138a54cc0dc4cea8f756546b70) +- [eslint] fix indentation and whitespace [`e5f5067`](https://github.com/minimistjs/minimist/commit/e5f5067259ceeaf0b098d14bec910f87e58708c7) +- [eslint] more cleanup [`62fde7d`](https://github.com/minimistjs/minimist/commit/62fde7d935f83417fb046741531a9e2346a36976) +- [eslint] more cleanup [`36ac5d0`](https://github.com/minimistjs/minimist/commit/36ac5d0d95e4947d074e5737d94814034ca335d1) +- [meta] add `auto-changelog` [`73923d2`](https://github.com/minimistjs/minimist/commit/73923d223553fca08b1ba77e3fbc2a492862ae4c) +- [actions] add reusable workflows [`d80727d`](https://github.com/minimistjs/minimist/commit/d80727df77bfa9e631044d7f16368d8f09242c91) +- [eslint] add eslint; rules to enable later are warnings [`48bc06a`](https://github.com/minimistjs/minimist/commit/48bc06a1b41f00e9cdf183db34f7a51ba70e98d4) +- [eslint] fix indentation [`34b0f1c`](https://github.com/minimistjs/minimist/commit/34b0f1ccaa45183c3c4f06a91f9b405180a6f982) +- [readme] rename and add badges [`5df0fe4`](https://github.com/minimistjs/minimist/commit/5df0fe49211bd09a3636f8686a7cb3012c3e98f0) +- [Dev Deps] switch from `covert` to `nyc` [`a48b128`](https://github.com/minimistjs/minimist/commit/a48b128fdb8d427dfb20a15273f83e38d97bef07) +- [Dev Deps] update `covert`, `tape`; remove unnecessary `tap` [`f0fb958`](https://github.com/minimistjs/minimist/commit/f0fb958e9a1fe980cdffc436a211b0bda58f621b) +- [meta] create FUNDING.yml; add `funding` in package.json [`3639e0c`](https://github.com/minimistjs/minimist/commit/3639e0c819359a366387e425ab6eabf4c78d3caa) +- [meta] use `npmignore` to autogenerate an npmignore file [`be2e038`](https://github.com/minimistjs/minimist/commit/be2e038c342d8333b32f0fde67a0026b79c8150e) +- Only apps should have lockfiles [`282b570`](https://github.com/minimistjs/minimist/commit/282b570e7489d01b03f2d6d3dabf79cd3e5f84cf) +- isConstructorOrProto adapted from PR [`ef9153f`](https://github.com/minimistjs/minimist/commit/ef9153fc52b6cea0744b2239921c5dcae4697f11) +- [Dev Deps] update `@ljharb/eslint-config`, `aud` [`098873c`](https://github.com/minimistjs/minimist/commit/098873c213cdb7c92e55ae1ef5aa1af3a8192a79) +- [Dev Deps] update `@ljharb/eslint-config`, `aud` [`3124ed3`](https://github.com/minimistjs/minimist/commit/3124ed3e46306301ebb3c834874ce0241555c2c4) +- [meta] add `safe-publish-latest` [`4b927de`](https://github.com/minimistjs/minimist/commit/4b927de696d561c636b4f43bf49d4597cb36d6d6) +- [Tests] add `aud` in `posttest` [`b32d9bd`](https://github.com/minimistjs/minimist/commit/b32d9bd0ab340f4e9f8c3a97ff2a4424f25fab8c) +- [meta] update repo URLs [`f9fdfc0`](https://github.com/minimistjs/minimist/commit/f9fdfc032c54884d9a9996a390c63cd0719bbe1a) +- [actions] Avoid 0.6 tests due to build failures [`ba92fe6`](https://github.com/minimistjs/minimist/commit/ba92fe6ebbdc0431cca9a2ea8f27beb492f5e4ec) +- [Dev Deps] update `tape` [`950eaa7`](https://github.com/minimistjs/minimist/commit/950eaa74f112e04d23e9c606c67472c46739b473) +- [Dev Deps] add missing `npmignore` dev dep [`3226afa`](https://github.com/minimistjs/minimist/commit/3226afaf09e9d127ca369742437fe6e88f752d6b) +- Merge tag 'v0.2.2' [`980d7ac`](https://github.com/minimistjs/minimist/commit/980d7ac61a0b4bd552711251ac107d506b23e41f) + +## [v1.2.7](https://github.com/minimistjs/minimist/compare/v1.2.6...v1.2.7) - 2022-10-10 + +### Commits + +- [meta] add `auto-changelog` [`0ebf4eb`](https://github.com/minimistjs/minimist/commit/0ebf4ebcd5f7787a5524d31a849ef41316b83c3c) +- [actions] add reusable workflows [`e115b63`](https://github.com/minimistjs/minimist/commit/e115b63fa9d3909f33b00a2db647ff79068388de) +- [eslint] add eslint; rules to enable later are warnings [`f58745b`](https://github.com/minimistjs/minimist/commit/f58745b9bb84348e1be72af7dbba5840c7c13013) +- [Dev Deps] switch from `covert` to `nyc` [`ab03356`](https://github.com/minimistjs/minimist/commit/ab033567b9c8b31117cb026dc7f1e592ce455c65) +- [readme] rename and add badges [`236f4a0`](https://github.com/minimistjs/minimist/commit/236f4a07e4ebe5ee44f1496ec6974991ab293ffd) +- [meta] create FUNDING.yml; add `funding` in package.json [`783a49b`](https://github.com/minimistjs/minimist/commit/783a49bfd47e8335d3098a8cac75662cf71eb32a) +- [meta] use `npmignore` to autogenerate an npmignore file [`f81ece6`](https://github.com/minimistjs/minimist/commit/f81ece6aaec2fa14e69ff4f1e0407a8c4e2635a2) +- Only apps should have lockfiles [`56cad44`](https://github.com/minimistjs/minimist/commit/56cad44c7f879b9bb5ec18fcc349308024a89bfc) +- [Dev Deps] update `covert`, `tape`; remove unnecessary `tap` [`49c5f9f`](https://github.com/minimistjs/minimist/commit/49c5f9fb7e6a92db9eb340cc679de92fb3aacded) +- [Tests] add `aud` in `posttest` [`228ae93`](https://github.com/minimistjs/minimist/commit/228ae938f3cd9db9dfd8bd7458b076a7b2aef280) +- [meta] add `safe-publish-latest` [`01fc23f`](https://github.com/minimistjs/minimist/commit/01fc23f5104f85c75059972e01dd33796ab529ff) +- [meta] update repo URLs [`6b164c7`](https://github.com/minimistjs/minimist/commit/6b164c7d68e0b6bf32f894699effdfb7c63041dd) + +## [v1.2.6](https://github.com/minimistjs/minimist/compare/v1.2.5...v1.2.6) - 2022-03-21 + +### Commits + +- test from prototype pollution PR [`bc8ecee`](https://github.com/minimistjs/minimist/commit/bc8ecee43875261f4f17eb20b1243d3ed15e70eb) +- isConstructorOrProto adapted from PR [`c2b9819`](https://github.com/minimistjs/minimist/commit/c2b981977fa834b223b408cfb860f933c9811e4d) +- security notice for additional prototype pollution issue [`ef88b93`](https://github.com/minimistjs/minimist/commit/ef88b9325f77b5ee643ccfc97e2ebda577e4c4e2) + +## [v1.2.5](https://github.com/minimistjs/minimist/compare/v1.2.4...v1.2.5) - 2020-03-12 + +## [v1.2.4](https://github.com/minimistjs/minimist/compare/v1.2.3...v1.2.4) - 2020-03-11 + +### Commits + +- security notice [`4cf1354`](https://github.com/minimistjs/minimist/commit/4cf1354839cb972e38496d35e12f806eea92c11f) +- additional test for constructor prototype pollution [`1043d21`](https://github.com/minimistjs/minimist/commit/1043d212c3caaf871966e710f52cfdf02f9eea4b) + +## [v1.2.3](https://github.com/minimistjs/minimist/compare/v1.2.2...v1.2.3) - 2020-03-10 + +### Commits + +- more failing proto pollution tests [`13c01a5`](https://github.com/minimistjs/minimist/commit/13c01a5327736903704984b7f65616b8476850cc) +- even more aggressive checks for protocol pollution [`38a4d1c`](https://github.com/minimistjs/minimist/commit/38a4d1caead72ef99e824bb420a2528eec03d9ab) + +## [v1.2.2](https://github.com/minimistjs/minimist/compare/v1.2.1...v1.2.2) - 2020-03-10 + +### Commits + +- failing test for protocol pollution [`0efed03`](https://github.com/minimistjs/minimist/commit/0efed0340ec8433638758f7ca0c77cb20a0bfbab) +- cleanup [`67d3722`](https://github.com/minimistjs/minimist/commit/67d3722413448d00a62963d2d30c34656a92d7e2) +- console.dir -> console.log [`47acf72`](https://github.com/minimistjs/minimist/commit/47acf72c715a630bf9ea013867f47f1dd69dfc54) +- don't assign onto __proto__ [`63e7ed0`](https://github.com/minimistjs/minimist/commit/63e7ed05aa4b1889ec2f3b196426db4500cbda94) + +## [v1.2.1](https://github.com/minimistjs/minimist/compare/v1.2.0...v1.2.1) - 2020-03-10 + +### Merged + +- move the `opts['--']` example back where it belongs [`#63`](https://github.com/minimistjs/minimist/pull/63) + +### Commits + +- add test [`6be5dae`](https://github.com/minimistjs/minimist/commit/6be5dae35a32a987bcf4137fcd6c19c5200ee909) +- fix bad boolean regexp [`ac3fc79`](https://github.com/minimistjs/minimist/commit/ac3fc796e63b95128fdbdf67ea7fad71bd59aa76) + +## [v1.2.0](https://github.com/minimistjs/minimist/compare/v1.1.3...v1.2.0) - 2015-08-24 + +### Commits + +- failing -k=v short test [`63416b8`](https://github.com/minimistjs/minimist/commit/63416b8cd1d0d70e4714564cce465a36e4dd26d7) +- kv short fix [`6bbe145`](https://github.com/minimistjs/minimist/commit/6bbe14529166245e86424f220a2321442fe88dc3) +- failing kv short test [`f72ab7f`](https://github.com/minimistjs/minimist/commit/f72ab7f4572adc52902c9b6873cc969192f01b10) +- fixed kv test [`f5a48c3`](https://github.com/minimistjs/minimist/commit/f5a48c3e50e40ca54f00c8e84de4b4d6e9897fa8) +- enforce space between arg key and value [`86b321a`](https://github.com/minimistjs/minimist/commit/86b321affe648a8e016c095a4f0efa9d9074f502) + +## [v1.1.3](https://github.com/minimistjs/minimist/compare/v1.1.2...v1.1.3) - 2015-08-06 + +### Commits + +- add failing test - boolean alias array [`0fa3c5b`](https://github.com/minimistjs/minimist/commit/0fa3c5b3dd98551ddecf5392831b4c21211743fc) +- fix boolean values with multiple aliases [`9c0a6e7`](https://github.com/minimistjs/minimist/commit/9c0a6e7de25a273b11bbf9a7464f0bd833779795) + +## [v1.1.2](https://github.com/minimistjs/minimist/compare/v1.1.1...v1.1.2) - 2015-07-22 + +### Commits + +- Convert boolean arguments to boolean values [`8f3dc27`](https://github.com/minimistjs/minimist/commit/8f3dc27cf833f1d54671b6d0bcb55c2fe19672a9) +- use non-ancient npm, node 0.12 and iojs [`61ed1d0`](https://github.com/minimistjs/minimist/commit/61ed1d034b9ec7282764ce76f3992b1a0b4906ae) +- an older npm for 0.8 [`25cf778`](https://github.com/minimistjs/minimist/commit/25cf778b1220e7838a526832ad6972f75244054f) + +## [v1.1.1](https://github.com/minimistjs/minimist/compare/v1.1.0...v1.1.1) - 2015-03-10 + +### Commits + +- check that they type of a value is a boolean, not just that it is currently set to a boolean [`6863198`](https://github.com/minimistjs/minimist/commit/6863198e36139830ff1f20ffdceaddd93f2c1db9) +- upgrade tape, fix type issues from old tape version [`806712d`](https://github.com/minimistjs/minimist/commit/806712df91604ed02b8e39aa372b84aea659ee34) +- test for setting a boolean to a null default [`8c444fe`](https://github.com/minimistjs/minimist/commit/8c444fe89384ded7d441c120915ea60620b01dd3) +- if the previous value was a boolean, without an default (or with an alias) don't make an array either [`e5f419a`](https://github.com/minimistjs/minimist/commit/e5f419a3b5b3bc3f9e5ac71b7040621af70ed2dd) + +## [v1.1.0](https://github.com/minimistjs/minimist/compare/v1.0.0...v1.1.0) - 2014-08-10 + +### Commits + +- add support for handling "unknown" options not registered with the parser. [`6f3cc5d`](https://github.com/minimistjs/minimist/commit/6f3cc5d4e84524932a6ef2ce3592acc67cdd4383) +- reformat package.json [`02ed371`](https://github.com/minimistjs/minimist/commit/02ed37115194d3697ff358e8e25e5e66bab1d9f8) +- coverage script [`e5531ba`](https://github.com/minimistjs/minimist/commit/e5531ba0479da3b8138d3d8cac545d84ccb1c8df) +- extra fn to get 100% coverage again [`a6972da`](https://github.com/minimistjs/minimist/commit/a6972da89e56bf77642f8ec05a13b6558db93498) + +## [v1.0.0](https://github.com/minimistjs/minimist/compare/v0.2.3...v1.0.0) - 2014-08-10 + +### Commits + +- added stopEarly option [`471c7e4`](https://github.com/minimistjs/minimist/commit/471c7e4a7e910fc7ad8f9df850a186daf32c64e9) +- fix list [`fef6ae7`](https://github.com/minimistjs/minimist/commit/fef6ae79c38b9dc1c49569abb7cd04eb965eac5e) + +## [v0.2.3](https://github.com/minimistjs/minimist/compare/v0.2.2...v0.2.3) - 2023-02-09 + +### Merged + +- [Fix] Fix long option followed by single dash [`#17`](https://github.com/minimistjs/minimist/pull/17) +- [Tests] Remove duplicate test [`#12`](https://github.com/minimistjs/minimist/pull/12) +- [Fix] opt.string works with multiple aliases [`#10`](https://github.com/minimistjs/minimist/pull/10) + +### Fixed + +- [Fix] Fix long option followed by single dash (#17) [`#15`](https://github.com/minimistjs/minimist/issues/15) +- [Tests] Remove duplicate test (#12) [`#8`](https://github.com/minimistjs/minimist/issues/8) +- [Fix] opt.string works with multiple aliases (#10) [`#9`](https://github.com/minimistjs/minimist/issues/9) + +### Commits + +- [eslint] fix indentation and whitespace [`e5f5067`](https://github.com/minimistjs/minimist/commit/e5f5067259ceeaf0b098d14bec910f87e58708c7) +- [eslint] more cleanup [`36ac5d0`](https://github.com/minimistjs/minimist/commit/36ac5d0d95e4947d074e5737d94814034ca335d1) +- [eslint] fix indentation [`34b0f1c`](https://github.com/minimistjs/minimist/commit/34b0f1ccaa45183c3c4f06a91f9b405180a6f982) +- isConstructorOrProto adapted from PR [`ef9153f`](https://github.com/minimistjs/minimist/commit/ef9153fc52b6cea0744b2239921c5dcae4697f11) +- [Dev Deps] update `@ljharb/eslint-config`, `aud` [`098873c`](https://github.com/minimistjs/minimist/commit/098873c213cdb7c92e55ae1ef5aa1af3a8192a79) +- [Dev Deps] add missing `npmignore` dev dep [`3226afa`](https://github.com/minimistjs/minimist/commit/3226afaf09e9d127ca369742437fe6e88f752d6b) + +## [v0.2.2](https://github.com/minimistjs/minimist/compare/v0.2.1...v0.2.2) - 2022-10-10 + +### Commits + +- [meta] add `auto-changelog` [`73923d2`](https://github.com/minimistjs/minimist/commit/73923d223553fca08b1ba77e3fbc2a492862ae4c) +- [actions] add reusable workflows [`d80727d`](https://github.com/minimistjs/minimist/commit/d80727df77bfa9e631044d7f16368d8f09242c91) +- [eslint] add eslint; rules to enable later are warnings [`48bc06a`](https://github.com/minimistjs/minimist/commit/48bc06a1b41f00e9cdf183db34f7a51ba70e98d4) +- [readme] rename and add badges [`5df0fe4`](https://github.com/minimistjs/minimist/commit/5df0fe49211bd09a3636f8686a7cb3012c3e98f0) +- [Dev Deps] switch from `covert` to `nyc` [`a48b128`](https://github.com/minimistjs/minimist/commit/a48b128fdb8d427dfb20a15273f83e38d97bef07) +- [Dev Deps] update `covert`, `tape`; remove unnecessary `tap` [`f0fb958`](https://github.com/minimistjs/minimist/commit/f0fb958e9a1fe980cdffc436a211b0bda58f621b) +- [meta] create FUNDING.yml; add `funding` in package.json [`3639e0c`](https://github.com/minimistjs/minimist/commit/3639e0c819359a366387e425ab6eabf4c78d3caa) +- [meta] use `npmignore` to autogenerate an npmignore file [`be2e038`](https://github.com/minimistjs/minimist/commit/be2e038c342d8333b32f0fde67a0026b79c8150e) +- Only apps should have lockfiles [`282b570`](https://github.com/minimistjs/minimist/commit/282b570e7489d01b03f2d6d3dabf79cd3e5f84cf) +- [meta] add `safe-publish-latest` [`4b927de`](https://github.com/minimistjs/minimist/commit/4b927de696d561c636b4f43bf49d4597cb36d6d6) +- [Tests] add `aud` in `posttest` [`b32d9bd`](https://github.com/minimistjs/minimist/commit/b32d9bd0ab340f4e9f8c3a97ff2a4424f25fab8c) +- [meta] update repo URLs [`f9fdfc0`](https://github.com/minimistjs/minimist/commit/f9fdfc032c54884d9a9996a390c63cd0719bbe1a) + +## [v0.2.1](https://github.com/minimistjs/minimist/compare/v0.2.0...v0.2.1) - 2020-03-12 + +## [v0.2.0](https://github.com/minimistjs/minimist/compare/v0.1.0...v0.2.0) - 2014-06-19 + +### Commits + +- support all-boolean mode [`450a97f`](https://github.com/minimistjs/minimist/commit/450a97f6e2bc85c7a4a13185c19a818d9a5ebe69) + +## [v0.1.0](https://github.com/minimistjs/minimist/compare/v0.0.10...v0.1.0) - 2014-05-12 + +### Commits + +- Provide a mechanism to segregate -- arguments [`ce4a1e6`](https://github.com/minimistjs/minimist/commit/ce4a1e63a7e8d5ab88d2a3768adefa6af98a445a) +- documented argv['--'] [`14db0e6`](https://github.com/minimistjs/minimist/commit/14db0e6dbc6d2b9e472adaa54dad7004b364634f) +- Adding a test-case for notFlags segregation [`715c1e3`](https://github.com/minimistjs/minimist/commit/715c1e3714be223f998f6c537af6b505f0236c16) + +## [v0.0.10](https://github.com/minimistjs/minimist/compare/v0.0.9...v0.0.10) - 2014-05-11 + +### Commits + +- dedicated boolean test [`46e448f`](https://github.com/minimistjs/minimist/commit/46e448f9f513cfeb2bcc8b688b9b47ba1e515c2b) +- dedicated num test [`9bf2d36`](https://github.com/minimistjs/minimist/commit/9bf2d36f1d3b8795be90b8f7de0a937f098aa394) +- aliased values treated as strings [`1ab743b`](https://github.com/minimistjs/minimist/commit/1ab743bad4484d69f1259bed42f9531de01119de) +- cover the case of already numbers, at 100% coverage [`b2bb044`](https://github.com/minimistjs/minimist/commit/b2bb04436599d77a2ce029e8e555e25b3aa55d13) +- another test for higher coverage [`3662624`](https://github.com/minimistjs/minimist/commit/3662624be976d5489d486a856849c048d13be903) + +## [v0.0.9](https://github.com/minimistjs/minimist/compare/v0.0.8...v0.0.9) - 2014-05-08 + +### Commits + +- Eliminate `longest` fn. [`824f642`](https://github.com/minimistjs/minimist/commit/824f642038d1b02ede68b6261d1d65163390929a) + +## [v0.0.8](https://github.com/minimistjs/minimist/compare/v0.0.7...v0.0.8) - 2014-02-20 + +### Commits + +- return '' if flag is string and empty [`fa63ed4`](https://github.com/minimistjs/minimist/commit/fa63ed4651a4ef4eefddce34188e0d98d745a263) +- handle joined single letters [`66c248f`](https://github.com/minimistjs/minimist/commit/66c248f0241d4d421d193b022e9e365f11178534) + +## [v0.0.7](https://github.com/minimistjs/minimist/compare/v0.0.6...v0.0.7) - 2014-02-08 + +### Commits + +- another swap of .test for .match [`d1da408`](https://github.com/minimistjs/minimist/commit/d1da40819acbe846d89a5c02721211e3c1260dde) + +## [v0.0.6](https://github.com/minimistjs/minimist/compare/v0.0.5...v0.0.6) - 2014-02-08 + +### Commits + +- use .test() instead of .match() to not crash on non-string values in the arguments array [`7e0d1ad`](https://github.com/minimistjs/minimist/commit/7e0d1add8c9e5b9b20a4d3d0f9a94d824c578da1) + +## [v0.0.5](https://github.com/minimistjs/minimist/compare/v0.0.4...v0.0.5) - 2013-09-18 + +### Commits + +- Improve '--' handling. [`b11822c`](https://github.com/minimistjs/minimist/commit/b11822c09cc9d2460f30384d12afc0b953c037a4) + +## [v0.0.4](https://github.com/minimistjs/minimist/compare/v0.0.3...v0.0.4) - 2013-09-17 + +## [v0.0.3](https://github.com/minimistjs/minimist/compare/v0.0.2...v0.0.3) - 2013-09-12 + +### Commits + +- failing test for single dash preceeding a double dash [`b465514`](https://github.com/minimistjs/minimist/commit/b465514b82c9ae28972d714facd951deb2ad762b) +- fix for the dot test [`6a095f1`](https://github.com/minimistjs/minimist/commit/6a095f1d364c8fab2d6753d2291a0649315d297a) + +## [v0.0.2](https://github.com/minimistjs/minimist/compare/v0.0.1...v0.0.2) - 2013-08-28 + +### Commits + +- allow dotted aliases & defaults [`321c33e`](https://github.com/minimistjs/minimist/commit/321c33e755485faaeb44eeb1c05d33b2e0a5a7c4) +- use a better version of ff [`e40f611`](https://github.com/minimistjs/minimist/commit/e40f61114cf7be6f7947f7b3eed345853a67dbbb) + +## [v0.0.1](https://github.com/minimistjs/minimist/compare/v0.0.0...v0.0.1) - 2013-06-25 + +### Commits + +- remove trailing commas [`6ff0fa0`](https://github.com/minimistjs/minimist/commit/6ff0fa055064f15dbe06d50b89d5173a6796e1db) + +## v0.0.0 - 2013-06-25 + +### Commits + +- half of the parse test ported [`3079326`](https://github.com/minimistjs/minimist/commit/307932601325087de6cf94188eb798ffc4f3088a) +- stripped down code and a passing test from optimist [`7cced88`](https://github.com/minimistjs/minimist/commit/7cced88d82e399d1a03ed23eb667f04d3f320d10) +- ported parse tests completely over [`9448754`](https://github.com/minimistjs/minimist/commit/944875452e0820df6830b1408c26a0f7d3e1db04) +- docs, package.json [`a5bf46a`](https://github.com/minimistjs/minimist/commit/a5bf46ac9bb3bd114a9c340276c62c1091e538d5) +- move more short tests into short.js [`503edb5`](https://github.com/minimistjs/minimist/commit/503edb5c41d89c0d40831ee517154fc13b0f18b9) +- default bool test was wrong, not the code [`1b9f5db`](https://github.com/minimistjs/minimist/commit/1b9f5db4741b49962846081b68518de824992097) +- passing long tests ripped out of parse.js [`7972c4a`](https://github.com/minimistjs/minimist/commit/7972c4aff1f4803079e1668006658e2a761a0428) +- badges [`84c0370`](https://github.com/minimistjs/minimist/commit/84c037063664d42878aace715fe6572ce01b6f3b) +- all the tests now ported, some failures [`64239ed`](https://github.com/minimistjs/minimist/commit/64239edfe92c711c4eb0da254fcdfad2a5fdb605) +- failing short test [`f8a5341`](https://github.com/minimistjs/minimist/commit/f8a534112dd1138d2fad722def56a848480c446f) +- fixed the numeric test [`6b034f3`](https://github.com/minimistjs/minimist/commit/6b034f37c79342c60083ed97fd222e16928aac51) diff --git a/backend/node_modules/minimist/LICENSE b/backend/node_modules/minimist/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..ee27ba4b4412b0e4a05af5e3d8a005bc6681fdf3 --- /dev/null +++ b/backend/node_modules/minimist/LICENSE @@ -0,0 +1,18 @@ +This software is released under the MIT license: + +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/backend/node_modules/minimist/README.md b/backend/node_modules/minimist/README.md new file mode 100644 index 0000000000000000000000000000000000000000..74da3234b4844a2d381a0c6f29f893beee5591bd --- /dev/null +++ b/backend/node_modules/minimist/README.md @@ -0,0 +1,121 @@ +# minimist [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +parse argument options + +This module is the guts of optimist's argument parser without all the +fanciful decoration. + +# example + +``` js +var argv = require('minimist')(process.argv.slice(2)); +console.log(argv); +``` + +``` +$ node example/parse.js -a beep -b boop +{ _: [], a: 'beep', b: 'boop' } +``` + +``` +$ node example/parse.js -x 3 -y 4 -n5 -abc --beep=boop foo bar baz +{ + _: ['foo', 'bar', 'baz'], + x: 3, + y: 4, + n: 5, + a: true, + b: true, + c: true, + beep: 'boop' +} +``` + +# security + +Previous versions had a prototype pollution bug that could cause privilege +escalation in some circumstances when handling untrusted user input. + +Please use version 1.2.6 or later: + +* https://security.snyk.io/vuln/SNYK-JS-MINIMIST-2429795 (version <=1.2.5) +* https://snyk.io/vuln/SNYK-JS-MINIMIST-559764 (version <=1.2.3) + +# methods + +``` js +var parseArgs = require('minimist') +``` + +## var argv = parseArgs(args, opts={}) + +Return an argument object `argv` populated with the array arguments from `args`. + +`argv._` contains all the arguments that didn't have an option associated with +them. + +Numeric-looking arguments will be returned as numbers unless `opts.string` or +`opts.boolean` is set for that argument name. + +Any arguments after `'--'` will not be parsed and will end up in `argv._`. + +options can be: + +* `opts.string` - a string or array of strings argument names to always treat as +strings +* `opts.boolean` - a boolean, string or array of strings to always treat as +booleans. if `true` will treat all double hyphenated arguments without equal signs +as boolean (e.g. affects `--foo`, not `-f` or `--foo=bar`) +* `opts.alias` - an object mapping string names to strings or arrays of string +argument names to use as aliases +* `opts.default` - an object mapping string argument names to default values +* `opts.stopEarly` - when true, populate `argv._` with everything after the +first non-option +* `opts['--']` - when true, populate `argv._` with everything before the `--` +and `argv['--']` with everything after the `--`. Here's an example: + + ``` + > require('./')('one two three -- four five --six'.split(' '), { '--': true }) + { + _: ['one', 'two', 'three'], + '--': ['four', 'five', '--six'] + } + ``` + + Note that with `opts['--']` set, parsing for arguments still stops after the + `--`. + +* `opts.unknown` - a function which is invoked with a command line parameter not +defined in the `opts` configuration object. If the function returns `false`, the +unknown option is not added to `argv`. + +# install + +With [npm](https://npmjs.org) do: + +``` +npm install minimist +``` + +# license + +MIT + +[package-url]: https://npmjs.org/package/minimist +[npm-version-svg]: https://versionbadg.es/minimistjs/minimist.svg +[npm-badge-png]: https://nodei.co/npm/minimist.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/minimist.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/minimist.svg +[downloads-url]: https://npm-stat.com/charts.html?package=minimist +[codecov-image]: https://codecov.io/gh/minimistjs/minimist/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/minimistjs/minimist/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/minimistjs/minimist +[actions-url]: https://github.com/minimistjs/minimist/actions diff --git a/backend/node_modules/minimist/example/parse.js b/backend/node_modules/minimist/example/parse.js new file mode 100644 index 0000000000000000000000000000000000000000..9d90ffb2642b4caddde1ec6fb0cff2e78192bb09 --- /dev/null +++ b/backend/node_modules/minimist/example/parse.js @@ -0,0 +1,4 @@ +'use strict'; + +var argv = require('../')(process.argv.slice(2)); +console.log(argv); diff --git a/backend/node_modules/minimist/index.js b/backend/node_modules/minimist/index.js new file mode 100644 index 0000000000000000000000000000000000000000..f020f3940e129c361dc89226efaf8775a4af8752 --- /dev/null +++ b/backend/node_modules/minimist/index.js @@ -0,0 +1,263 @@ +'use strict'; + +function hasKey(obj, keys) { + var o = obj; + keys.slice(0, -1).forEach(function (key) { + o = o[key] || {}; + }); + + var key = keys[keys.length - 1]; + return key in o; +} + +function isNumber(x) { + if (typeof x === 'number') { return true; } + if ((/^0x[0-9a-f]+$/i).test(x)) { return true; } + return (/^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/).test(x); +} + +function isConstructorOrProto(obj, key) { + return (key === 'constructor' && typeof obj[key] === 'function') || key === '__proto__'; +} + +module.exports = function (args, opts) { + if (!opts) { opts = {}; } + + var flags = { + bools: {}, + strings: {}, + unknownFn: null, + }; + + if (typeof opts.unknown === 'function') { + flags.unknownFn = opts.unknown; + } + + if (typeof opts.boolean === 'boolean' && opts.boolean) { + flags.allBools = true; + } else { + [].concat(opts.boolean).filter(Boolean).forEach(function (key) { + flags.bools[key] = true; + }); + } + + var aliases = {}; + + function aliasIsBoolean(key) { + return aliases[key].some(function (x) { + return flags.bools[x]; + }); + } + + Object.keys(opts.alias || {}).forEach(function (key) { + aliases[key] = [].concat(opts.alias[key]); + aliases[key].forEach(function (x) { + aliases[x] = [key].concat(aliases[key].filter(function (y) { + return x !== y; + })); + }); + }); + + [].concat(opts.string).filter(Boolean).forEach(function (key) { + flags.strings[key] = true; + if (aliases[key]) { + [].concat(aliases[key]).forEach(function (k) { + flags.strings[k] = true; + }); + } + }); + + var defaults = opts.default || {}; + + var argv = { _: [] }; + + function argDefined(key, arg) { + return (flags.allBools && (/^--[^=]+$/).test(arg)) + || flags.strings[key] + || flags.bools[key] + || aliases[key]; + } + + function setKey(obj, keys, value) { + var o = obj; + for (var i = 0; i < keys.length - 1; i++) { + var key = keys[i]; + if (isConstructorOrProto(o, key)) { return; } + if (o[key] === undefined) { o[key] = {}; } + if ( + o[key] === Object.prototype + || o[key] === Number.prototype + || o[key] === String.prototype + ) { + o[key] = {}; + } + if (o[key] === Array.prototype) { o[key] = []; } + o = o[key]; + } + + var lastKey = keys[keys.length - 1]; + if (isConstructorOrProto(o, lastKey)) { return; } + if ( + o === Object.prototype + || o === Number.prototype + || o === String.prototype + ) { + o = {}; + } + if (o === Array.prototype) { o = []; } + if (o[lastKey] === undefined || flags.bools[lastKey] || typeof o[lastKey] === 'boolean') { + o[lastKey] = value; + } else if (Array.isArray(o[lastKey])) { + o[lastKey].push(value); + } else { + o[lastKey] = [o[lastKey], value]; + } + } + + function setArg(key, val, arg) { + if (arg && flags.unknownFn && !argDefined(key, arg)) { + if (flags.unknownFn(arg) === false) { return; } + } + + var value = !flags.strings[key] && isNumber(val) + ? Number(val) + : val; + setKey(argv, key.split('.'), value); + + (aliases[key] || []).forEach(function (x) { + setKey(argv, x.split('.'), value); + }); + } + + Object.keys(flags.bools).forEach(function (key) { + setArg(key, defaults[key] === undefined ? false : defaults[key]); + }); + + var notFlags = []; + + if (args.indexOf('--') !== -1) { + notFlags = args.slice(args.indexOf('--') + 1); + args = args.slice(0, args.indexOf('--')); + } + + for (var i = 0; i < args.length; i++) { + var arg = args[i]; + var key; + var next; + + if ((/^--.+=/).test(arg)) { + // Using [\s\S] instead of . because js doesn't support the + // 'dotall' regex modifier. See: + // http://stackoverflow.com/a/1068308/13216 + var m = arg.match(/^--([^=]+)=([\s\S]*)$/); + key = m[1]; + var value = m[2]; + if (flags.bools[key]) { + value = value !== 'false'; + } + setArg(key, value, arg); + } else if ((/^--no-.+/).test(arg)) { + key = arg.match(/^--no-(.+)/)[1]; + setArg(key, false, arg); + } else if ((/^--.+/).test(arg)) { + key = arg.match(/^--(.+)/)[1]; + next = args[i + 1]; + if ( + next !== undefined + && !(/^(-|--)[^-]/).test(next) + && !flags.bools[key] + && !flags.allBools + && (aliases[key] ? !aliasIsBoolean(key) : true) + ) { + setArg(key, next, arg); + i += 1; + } else if ((/^(true|false)$/).test(next)) { + setArg(key, next === 'true', arg); + i += 1; + } else { + setArg(key, flags.strings[key] ? '' : true, arg); + } + } else if ((/^-[^-]+/).test(arg)) { + var letters = arg.slice(1, -1).split(''); + + var broken = false; + for (var j = 0; j < letters.length; j++) { + next = arg.slice(j + 2); + + if (next === '-') { + setArg(letters[j], next, arg); + continue; + } + + if ((/[A-Za-z]/).test(letters[j]) && next[0] === '=') { + setArg(letters[j], next.slice(1), arg); + broken = true; + break; + } + + if ( + (/[A-Za-z]/).test(letters[j]) + && (/-?\d+(\.\d*)?(e-?\d+)?$/).test(next) + ) { + setArg(letters[j], next, arg); + broken = true; + break; + } + + if (letters[j + 1] && letters[j + 1].match(/\W/)) { + setArg(letters[j], arg.slice(j + 2), arg); + broken = true; + break; + } else { + setArg(letters[j], flags.strings[letters[j]] ? '' : true, arg); + } + } + + key = arg.slice(-1)[0]; + if (!broken && key !== '-') { + if ( + args[i + 1] + && !(/^(-|--)[^-]/).test(args[i + 1]) + && !flags.bools[key] + && (aliases[key] ? !aliasIsBoolean(key) : true) + ) { + setArg(key, args[i + 1], arg); + i += 1; + } else if (args[i + 1] && (/^(true|false)$/).test(args[i + 1])) { + setArg(key, args[i + 1] === 'true', arg); + i += 1; + } else { + setArg(key, flags.strings[key] ? '' : true, arg); + } + } + } else { + if (!flags.unknownFn || flags.unknownFn(arg) !== false) { + argv._.push(flags.strings._ || !isNumber(arg) ? arg : Number(arg)); + } + if (opts.stopEarly) { + argv._.push.apply(argv._, args.slice(i + 1)); + break; + } + } + } + + Object.keys(defaults).forEach(function (k) { + if (!hasKey(argv, k.split('.'))) { + setKey(argv, k.split('.'), defaults[k]); + + (aliases[k] || []).forEach(function (x) { + setKey(argv, x.split('.'), defaults[k]); + }); + } + }); + + if (opts['--']) { + argv['--'] = notFlags.slice(); + } else { + notFlags.forEach(function (k) { + argv._.push(k); + }); + } + + return argv; +}; diff --git a/backend/node_modules/minimist/package.json b/backend/node_modules/minimist/package.json new file mode 100644 index 0000000000000000000000000000000000000000..c10a3344411197a716883caad07f0319f5d69b89 --- /dev/null +++ b/backend/node_modules/minimist/package.json @@ -0,0 +1,75 @@ +{ + "name": "minimist", + "version": "1.2.8", + "description": "parse argument options", + "main": "index.js", + "devDependencies": { + "@ljharb/eslint-config": "^21.0.1", + "aud": "^2.0.2", + "auto-changelog": "^2.4.0", + "eslint": "=8.8.0", + "in-publish": "^2.0.1", + "npmignore": "^0.3.0", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.6.3" + }, + "scripts": { + "prepack": "npmignore --auto --commentLines=auto", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "lint": "eslint --ext=js,mjs .", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "aud --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)\")\"" + }, + "testling": { + "files": "test/*.js", + "browsers": [ + "ie/6..latest", + "ff/5", + "firefox/latest", + "chrome/10", + "chrome/latest", + "safari/5.1", + "safari/latest", + "opera/12" + ] + }, + "repository": { + "type": "git", + "url": "git://github.com/minimistjs/minimist.git" + }, + "homepage": "https://github.com/minimistjs/minimist", + "keywords": [ + "argv", + "getopt", + "parser", + "optimist" + ], + "author": { + "name": "James Halliday", + "email": "mail@substack.net", + "url": "http://substack.net" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + } +} diff --git a/backend/node_modules/minimist/test/all_bool.js b/backend/node_modules/minimist/test/all_bool.js new file mode 100644 index 0000000000000000000000000000000000000000..befa0c99769080972260dac9e4a77630857000f2 --- /dev/null +++ b/backend/node_modules/minimist/test/all_bool.js @@ -0,0 +1,34 @@ +'use strict'; + +var parse = require('../'); +var test = require('tape'); + +test('flag boolean true (default all --args to boolean)', function (t) { + var argv = parse(['moo', '--honk', 'cow'], { + boolean: true, + }); + + t.deepEqual(argv, { + honk: true, + _: ['moo', 'cow'], + }); + + t.deepEqual(typeof argv.honk, 'boolean'); + t.end(); +}); + +test('flag boolean true only affects double hyphen arguments without equals signs', function (t) { + var argv = parse(['moo', '--honk', 'cow', '-p', '55', '--tacos=good'], { + boolean: true, + }); + + t.deepEqual(argv, { + honk: true, + tacos: 'good', + p: 55, + _: ['moo', 'cow'], + }); + + t.deepEqual(typeof argv.honk, 'boolean'); + t.end(); +}); diff --git a/backend/node_modules/minimist/test/bool.js b/backend/node_modules/minimist/test/bool.js new file mode 100644 index 0000000000000000000000000000000000000000..e58d47e442ce127bfe5703b6b64d14c3e4511223 --- /dev/null +++ b/backend/node_modules/minimist/test/bool.js @@ -0,0 +1,177 @@ +'use strict'; + +var parse = require('../'); +var test = require('tape'); + +test('flag boolean default false', function (t) { + var argv = parse(['moo'], { + boolean: ['t', 'verbose'], + default: { verbose: false, t: false }, + }); + + t.deepEqual(argv, { + verbose: false, + t: false, + _: ['moo'], + }); + + t.deepEqual(typeof argv.verbose, 'boolean'); + t.deepEqual(typeof argv.t, 'boolean'); + t.end(); + +}); + +test('boolean groups', function (t) { + var argv = parse(['-x', '-z', 'one', 'two', 'three'], { + boolean: ['x', 'y', 'z'], + }); + + t.deepEqual(argv, { + x: true, + y: false, + z: true, + _: ['one', 'two', 'three'], + }); + + t.deepEqual(typeof argv.x, 'boolean'); + t.deepEqual(typeof argv.y, 'boolean'); + t.deepEqual(typeof argv.z, 'boolean'); + t.end(); +}); +test('boolean and alias with chainable api', function (t) { + var aliased = ['-h', 'derp']; + var regular = ['--herp', 'derp']; + var aliasedArgv = parse(aliased, { + boolean: 'herp', + alias: { h: 'herp' }, + }); + var propertyArgv = parse(regular, { + boolean: 'herp', + alias: { h: 'herp' }, + }); + var expected = { + herp: true, + h: true, + _: ['derp'], + }; + + t.same(aliasedArgv, expected); + t.same(propertyArgv, expected); + t.end(); +}); + +test('boolean and alias with options hash', function (t) { + var aliased = ['-h', 'derp']; + var regular = ['--herp', 'derp']; + var opts = { + alias: { h: 'herp' }, + boolean: 'herp', + }; + var aliasedArgv = parse(aliased, opts); + var propertyArgv = parse(regular, opts); + var expected = { + herp: true, + h: true, + _: ['derp'], + }; + t.same(aliasedArgv, expected); + t.same(propertyArgv, expected); + t.end(); +}); + +test('boolean and alias array with options hash', function (t) { + var aliased = ['-h', 'derp']; + var regular = ['--herp', 'derp']; + var alt = ['--harp', 'derp']; + var opts = { + alias: { h: ['herp', 'harp'] }, + boolean: 'h', + }; + var aliasedArgv = parse(aliased, opts); + var propertyArgv = parse(regular, opts); + var altPropertyArgv = parse(alt, opts); + var expected = { + harp: true, + herp: true, + h: true, + _: ['derp'], + }; + t.same(aliasedArgv, expected); + t.same(propertyArgv, expected); + t.same(altPropertyArgv, expected); + t.end(); +}); + +test('boolean and alias using explicit true', function (t) { + var aliased = ['-h', 'true']; + var regular = ['--herp', 'true']; + var opts = { + alias: { h: 'herp' }, + boolean: 'h', + }; + var aliasedArgv = parse(aliased, opts); + var propertyArgv = parse(regular, opts); + var expected = { + herp: true, + h: true, + _: [], + }; + + t.same(aliasedArgv, expected); + t.same(propertyArgv, expected); + t.end(); +}); + +// regression, see https://github.com/substack/node-optimist/issues/71 +test('boolean and --x=true', function (t) { + var parsed = parse(['--boool', '--other=true'], { + boolean: 'boool', + }); + + t.same(parsed.boool, true); + t.same(parsed.other, 'true'); + + parsed = parse(['--boool', '--other=false'], { + boolean: 'boool', + }); + + t.same(parsed.boool, true); + t.same(parsed.other, 'false'); + t.end(); +}); + +test('boolean --boool=true', function (t) { + var parsed = parse(['--boool=true'], { + default: { + boool: false, + }, + boolean: ['boool'], + }); + + t.same(parsed.boool, true); + t.end(); +}); + +test('boolean --boool=false', function (t) { + var parsed = parse(['--boool=false'], { + default: { + boool: true, + }, + boolean: ['boool'], + }); + + t.same(parsed.boool, false); + t.end(); +}); + +test('boolean using something similar to true', function (t) { + var opts = { boolean: 'h' }; + var result = parse(['-h', 'true.txt'], opts); + var expected = { + h: true, + _: ['true.txt'], + }; + + t.same(result, expected); + t.end(); +}); diff --git a/backend/node_modules/minimist/test/dash.js b/backend/node_modules/minimist/test/dash.js new file mode 100644 index 0000000000000000000000000000000000000000..707881771e275240a0e0d6d4d2fb8d31a564d74f --- /dev/null +++ b/backend/node_modules/minimist/test/dash.js @@ -0,0 +1,43 @@ +'use strict'; + +var parse = require('../'); +var test = require('tape'); + +test('-', function (t) { + t.plan(6); + t.deepEqual(parse(['-n', '-']), { n: '-', _: [] }); + t.deepEqual(parse(['--nnn', '-']), { nnn: '-', _: [] }); + t.deepEqual(parse(['-']), { _: ['-'] }); + t.deepEqual(parse(['-f-']), { f: '-', _: [] }); + t.deepEqual( + parse(['-b', '-'], { boolean: 'b' }), + { b: true, _: ['-'] } + ); + t.deepEqual( + parse(['-s', '-'], { string: 's' }), + { s: '-', _: [] } + ); +}); + +test('-a -- b', function (t) { + t.plan(2); + t.deepEqual(parse(['-a', '--', 'b']), { a: true, _: ['b'] }); + t.deepEqual(parse(['--a', '--', 'b']), { a: true, _: ['b'] }); +}); + +test('move arguments after the -- into their own `--` array', function (t) { + t.plan(1); + t.deepEqual( + parse(['--name', 'John', 'before', '--', 'after'], { '--': true }), + { name: 'John', _: ['before'], '--': ['after'] } + ); +}); + +test('--- option value', function (t) { + // A multi-dash value is largely an edge case, but check the behaviour is as expected, + // and in particular the same for short option and long option (as made consistent in Jan 2023). + t.plan(2); + t.deepEqual(parse(['-n', '---']), { n: '---', _: [] }); + t.deepEqual(parse(['--nnn', '---']), { nnn: '---', _: [] }); +}); + diff --git a/backend/node_modules/minimist/test/default_bool.js b/backend/node_modules/minimist/test/default_bool.js new file mode 100644 index 0000000000000000000000000000000000000000..4e9f6250f08ea8e005b66729630660a3db195566 --- /dev/null +++ b/backend/node_modules/minimist/test/default_bool.js @@ -0,0 +1,37 @@ +'use strict'; + +var test = require('tape'); +var parse = require('../'); + +test('boolean default true', function (t) { + var argv = parse([], { + boolean: 'sometrue', + default: { sometrue: true }, + }); + t.equal(argv.sometrue, true); + t.end(); +}); + +test('boolean default false', function (t) { + var argv = parse([], { + boolean: 'somefalse', + default: { somefalse: false }, + }); + t.equal(argv.somefalse, false); + t.end(); +}); + +test('boolean default to null', function (t) { + var argv = parse([], { + boolean: 'maybe', + default: { maybe: null }, + }); + t.equal(argv.maybe, null); + + var argvLong = parse(['--maybe'], { + boolean: 'maybe', + default: { maybe: null }, + }); + t.equal(argvLong.maybe, true); + t.end(); +}); diff --git a/backend/node_modules/minimist/test/dotted.js b/backend/node_modules/minimist/test/dotted.js new file mode 100644 index 0000000000000000000000000000000000000000..126ff033b4237334be18dafed9f2b4636f684d2d --- /dev/null +++ b/backend/node_modules/minimist/test/dotted.js @@ -0,0 +1,24 @@ +'use strict'; + +var parse = require('../'); +var test = require('tape'); + +test('dotted alias', function (t) { + var argv = parse(['--a.b', '22'], { default: { 'a.b': 11 }, alias: { 'a.b': 'aa.bb' } }); + t.equal(argv.a.b, 22); + t.equal(argv.aa.bb, 22); + t.end(); +}); + +test('dotted default', function (t) { + var argv = parse('', { default: { 'a.b': 11 }, alias: { 'a.b': 'aa.bb' } }); + t.equal(argv.a.b, 11); + t.equal(argv.aa.bb, 11); + t.end(); +}); + +test('dotted default with no alias', function (t) { + var argv = parse('', { default: { 'a.b': 11 } }); + t.equal(argv.a.b, 11); + t.end(); +}); diff --git a/backend/node_modules/minimist/test/kv_short.js b/backend/node_modules/minimist/test/kv_short.js new file mode 100644 index 0000000000000000000000000000000000000000..6d1b53a7a7ee1fcbeb9b12c9804f83ff90f46ccd --- /dev/null +++ b/backend/node_modules/minimist/test/kv_short.js @@ -0,0 +1,32 @@ +'use strict'; + +var parse = require('../'); +var test = require('tape'); + +test('short -k=v', function (t) { + t.plan(1); + + var argv = parse(['-b=123']); + t.deepEqual(argv, { b: 123, _: [] }); +}); + +test('multi short -k=v', function (t) { + t.plan(1); + + var argv = parse(['-a=whatever', '-b=robots']); + t.deepEqual(argv, { a: 'whatever', b: 'robots', _: [] }); +}); + +test('short with embedded equals -k=a=b', function (t) { + t.plan(1); + + var argv = parse(['-k=a=b']); + t.deepEqual(argv, { k: 'a=b', _: [] }); +}); + +test('short with later equals like -ab=c', function (t) { + t.plan(1); + + var argv = parse(['-ab=c']); + t.deepEqual(argv, { a: true, b: 'c', _: [] }); +}); diff --git a/backend/node_modules/minimist/test/long.js b/backend/node_modules/minimist/test/long.js new file mode 100644 index 0000000000000000000000000000000000000000..9fef51f1fa8d9bf8ef9e92ad2ce5742f009ab941 --- /dev/null +++ b/backend/node_modules/minimist/test/long.js @@ -0,0 +1,33 @@ +'use strict'; + +var test = require('tape'); +var parse = require('../'); + +test('long opts', function (t) { + t.deepEqual( + parse(['--bool']), + { bool: true, _: [] }, + 'long boolean' + ); + t.deepEqual( + parse(['--pow', 'xixxle']), + { pow: 'xixxle', _: [] }, + 'long capture sp' + ); + t.deepEqual( + parse(['--pow=xixxle']), + { pow: 'xixxle', _: [] }, + 'long capture eq' + ); + t.deepEqual( + parse(['--host', 'localhost', '--port', '555']), + { host: 'localhost', port: 555, _: [] }, + 'long captures sp' + ); + t.deepEqual( + parse(['--host=localhost', '--port=555']), + { host: 'localhost', port: 555, _: [] }, + 'long captures eq' + ); + t.end(); +}); diff --git a/backend/node_modules/minimist/test/num.js b/backend/node_modules/minimist/test/num.js new file mode 100644 index 0000000000000000000000000000000000000000..074393ecaf1705b9a6170c35ad23d55df943f306 --- /dev/null +++ b/backend/node_modules/minimist/test/num.js @@ -0,0 +1,38 @@ +'use strict'; + +var parse = require('../'); +var test = require('tape'); + +test('nums', function (t) { + var argv = parse([ + '-x', '1234', + '-y', '5.67', + '-z', '1e7', + '-w', '10f', + '--hex', '0xdeadbeef', + '789', + ]); + t.deepEqual(argv, { + x: 1234, + y: 5.67, + z: 1e7, + w: '10f', + hex: 0xdeadbeef, + _: [789], + }); + t.deepEqual(typeof argv.x, 'number'); + t.deepEqual(typeof argv.y, 'number'); + t.deepEqual(typeof argv.z, 'number'); + t.deepEqual(typeof argv.w, 'string'); + t.deepEqual(typeof argv.hex, 'number'); + t.deepEqual(typeof argv._[0], 'number'); + t.end(); +}); + +test('already a number', function (t) { + var argv = parse(['-x', 1234, 789]); + t.deepEqual(argv, { x: 1234, _: [789] }); + t.deepEqual(typeof argv.x, 'number'); + t.deepEqual(typeof argv._[0], 'number'); + t.end(); +}); diff --git a/backend/node_modules/minimist/test/parse.js b/backend/node_modules/minimist/test/parse.js new file mode 100644 index 0000000000000000000000000000000000000000..65d9d90927b91baa152a32e1485479307f1acf44 --- /dev/null +++ b/backend/node_modules/minimist/test/parse.js @@ -0,0 +1,209 @@ +'use strict'; + +var parse = require('../'); +var test = require('tape'); + +test('parse args', function (t) { + t.deepEqual( + parse(['--no-moo']), + { moo: false, _: [] }, + 'no' + ); + t.deepEqual( + parse(['-v', 'a', '-v', 'b', '-v', 'c']), + { v: ['a', 'b', 'c'], _: [] }, + 'multi' + ); + t.end(); +}); + +test('comprehensive', function (t) { + t.deepEqual( + parse([ + '--name=meowmers', 'bare', '-cats', 'woo', + '-h', 'awesome', '--multi=quux', + '--key', 'value', + '-b', '--bool', '--no-meep', '--multi=baz', + '--', '--not-a-flag', 'eek', + ]), + { + c: true, + a: true, + t: true, + s: 'woo', + h: 'awesome', + b: true, + bool: true, + key: 'value', + multi: ['quux', 'baz'], + meep: false, + name: 'meowmers', + _: ['bare', '--not-a-flag', 'eek'], + } + ); + t.end(); +}); + +test('flag boolean', function (t) { + var argv = parse(['-t', 'moo'], { boolean: 't' }); + t.deepEqual(argv, { t: true, _: ['moo'] }); + t.deepEqual(typeof argv.t, 'boolean'); + t.end(); +}); + +test('flag boolean value', function (t) { + var argv = parse(['--verbose', 'false', 'moo', '-t', 'true'], { + boolean: ['t', 'verbose'], + default: { verbose: true }, + }); + + t.deepEqual(argv, { + verbose: false, + t: true, + _: ['moo'], + }); + + t.deepEqual(typeof argv.verbose, 'boolean'); + t.deepEqual(typeof argv.t, 'boolean'); + t.end(); +}); + +test('newlines in params', function (t) { + var args = parse(['-s', 'X\nX']); + t.deepEqual(args, { _: [], s: 'X\nX' }); + + // reproduce in bash: + // VALUE="new + // line" + // node program.js --s="$VALUE" + args = parse(['--s=X\nX']); + t.deepEqual(args, { _: [], s: 'X\nX' }); + t.end(); +}); + +test('strings', function (t) { + var s = parse(['-s', '0001234'], { string: 's' }).s; + t.equal(s, '0001234'); + t.equal(typeof s, 'string'); + + var x = parse(['-x', '56'], { string: 'x' }).x; + t.equal(x, '56'); + t.equal(typeof x, 'string'); + t.end(); +}); + +test('stringArgs', function (t) { + var s = parse([' ', ' '], { string: '_' })._; + t.same(s.length, 2); + t.same(typeof s[0], 'string'); + t.same(s[0], ' '); + t.same(typeof s[1], 'string'); + t.same(s[1], ' '); + t.end(); +}); + +test('empty strings', function (t) { + var s = parse(['-s'], { string: 's' }).s; + t.equal(s, ''); + t.equal(typeof s, 'string'); + + var str = parse(['--str'], { string: 'str' }).str; + t.equal(str, ''); + t.equal(typeof str, 'string'); + + var letters = parse(['-art'], { + string: ['a', 't'], + }); + + t.equal(letters.a, ''); + t.equal(letters.r, true); + t.equal(letters.t, ''); + + t.end(); +}); + +test('string and alias', function (t) { + var x = parse(['--str', '000123'], { + string: 's', + alias: { s: 'str' }, + }); + + t.equal(x.str, '000123'); + t.equal(typeof x.str, 'string'); + t.equal(x.s, '000123'); + t.equal(typeof x.s, 'string'); + + var y = parse(['-s', '000123'], { + string: 'str', + alias: { str: 's' }, + }); + + t.equal(y.str, '000123'); + t.equal(typeof y.str, 'string'); + t.equal(y.s, '000123'); + t.equal(typeof y.s, 'string'); + + var z = parse(['-s123'], { + alias: { str: ['s', 'S'] }, + string: ['str'], + }); + + t.deepEqual( + z, + { _: [], s: '123', S: '123', str: '123' }, + 'opt.string works with multiple aliases' + ); + t.end(); +}); + +test('slashBreak', function (t) { + t.same( + parse(['-I/foo/bar/baz']), + { I: '/foo/bar/baz', _: [] } + ); + t.same( + parse(['-xyz/foo/bar/baz']), + { x: true, y: true, z: '/foo/bar/baz', _: [] } + ); + t.end(); +}); + +test('alias', function (t) { + var argv = parse(['-f', '11', '--zoom', '55'], { + alias: { z: 'zoom' }, + }); + t.equal(argv.zoom, 55); + t.equal(argv.z, argv.zoom); + t.equal(argv.f, 11); + t.end(); +}); + +test('multiAlias', function (t) { + var argv = parse(['-f', '11', '--zoom', '55'], { + alias: { z: ['zm', 'zoom'] }, + }); + t.equal(argv.zoom, 55); + t.equal(argv.z, argv.zoom); + t.equal(argv.z, argv.zm); + t.equal(argv.f, 11); + t.end(); +}); + +test('nested dotted objects', function (t) { + var argv = parse([ + '--foo.bar', '3', '--foo.baz', '4', + '--foo.quux.quibble', '5', '--foo.quux.o_O', + '--beep.boop', + ]); + + t.same(argv.foo, { + bar: 3, + baz: 4, + quux: { + quibble: 5, + o_O: true, + }, + }); + t.same(argv.beep, { boop: true }); + t.end(); +}); diff --git a/backend/node_modules/minimist/test/parse_modified.js b/backend/node_modules/minimist/test/parse_modified.js new file mode 100644 index 0000000000000000000000000000000000000000..32965d130fbd4f59b9a6e12488cf18901004d1f8 --- /dev/null +++ b/backend/node_modules/minimist/test/parse_modified.js @@ -0,0 +1,11 @@ +'use strict'; + +var parse = require('../'); +var test = require('tape'); + +test('parse with modifier functions', function (t) { + t.plan(1); + + var argv = parse(['-b', '123'], { boolean: 'b' }); + t.deepEqual(argv, { b: true, _: [123] }); +}); diff --git a/backend/node_modules/minimist/test/proto.js b/backend/node_modules/minimist/test/proto.js new file mode 100644 index 0000000000000000000000000000000000000000..6e629dd34ef0942c19c4d124542f5f030c228ae4 --- /dev/null +++ b/backend/node_modules/minimist/test/proto.js @@ -0,0 +1,64 @@ +'use strict'; + +/* eslint no-proto: 0 */ + +var parse = require('../'); +var test = require('tape'); + +test('proto pollution', function (t) { + var argv = parse(['--__proto__.x', '123']); + t.equal({}.x, undefined); + t.equal(argv.__proto__.x, undefined); + t.equal(argv.x, undefined); + t.end(); +}); + +test('proto pollution (array)', function (t) { + var argv = parse(['--x', '4', '--x', '5', '--x.__proto__.z', '789']); + t.equal({}.z, undefined); + t.deepEqual(argv.x, [4, 5]); + t.equal(argv.x.z, undefined); + t.equal(argv.x.__proto__.z, undefined); + t.end(); +}); + +test('proto pollution (number)', function (t) { + var argv = parse(['--x', '5', '--x.__proto__.z', '100']); + t.equal({}.z, undefined); + t.equal((4).z, undefined); + t.equal(argv.x, 5); + t.equal(argv.x.z, undefined); + t.end(); +}); + +test('proto pollution (string)', function (t) { + var argv = parse(['--x', 'abc', '--x.__proto__.z', 'def']); + t.equal({}.z, undefined); + t.equal('...'.z, undefined); + t.equal(argv.x, 'abc'); + t.equal(argv.x.z, undefined); + t.end(); +}); + +test('proto pollution (constructor)', function (t) { + var argv = parse(['--constructor.prototype.y', '123']); + t.equal({}.y, undefined); + t.equal(argv.y, undefined); + t.end(); +}); + +test('proto pollution (constructor function)', function (t) { + var argv = parse(['--_.concat.constructor.prototype.y', '123']); + function fnToBeTested() {} + t.equal(fnToBeTested.y, undefined); + t.equal(argv.y, undefined); + t.end(); +}); + +// powered by snyk - https://github.com/backstage/backstage/issues/10343 +test('proto pollution (constructor function) snyk', function (t) { + var argv = parse('--_.constructor.constructor.prototype.foo bar'.split(' ')); + t.equal(function () {}.foo, undefined); + t.equal(argv.y, undefined); + t.end(); +}); diff --git a/backend/node_modules/minimist/test/short.js b/backend/node_modules/minimist/test/short.js new file mode 100644 index 0000000000000000000000000000000000000000..4a7b84385bbfdc74314f5e8f7cc4c36afd52b8bd --- /dev/null +++ b/backend/node_modules/minimist/test/short.js @@ -0,0 +1,69 @@ +'use strict'; + +var parse = require('../'); +var test = require('tape'); + +test('numeric short args', function (t) { + t.plan(2); + t.deepEqual(parse(['-n123']), { n: 123, _: [] }); + t.deepEqual( + parse(['-123', '456']), + { 1: true, 2: true, 3: 456, _: [] } + ); +}); + +test('short', function (t) { + t.deepEqual( + parse(['-b']), + { b: true, _: [] }, + 'short boolean' + ); + t.deepEqual( + parse(['foo', 'bar', 'baz']), + { _: ['foo', 'bar', 'baz'] }, + 'bare' + ); + t.deepEqual( + parse(['-cats']), + { c: true, a: true, t: true, s: true, _: [] }, + 'group' + ); + t.deepEqual( + parse(['-cats', 'meow']), + { c: true, a: true, t: true, s: 'meow', _: [] }, + 'short group next' + ); + t.deepEqual( + parse(['-h', 'localhost']), + { h: 'localhost', _: [] }, + 'short capture' + ); + t.deepEqual( + parse(['-h', 'localhost', '-p', '555']), + { h: 'localhost', p: 555, _: [] }, + 'short captures' + ); + t.end(); +}); + +test('mixed short bool and capture', function (t) { + t.same( + parse(['-h', 'localhost', '-fp', '555', 'script.js']), + { + f: true, p: 555, h: 'localhost', + _: ['script.js'], + } + ); + t.end(); +}); + +test('short and long', function (t) { + t.deepEqual( + parse(['-h', 'localhost', '-fp', '555', 'script.js']), + { + f: true, p: 555, h: 'localhost', + _: ['script.js'], + } + ); + t.end(); +}); diff --git a/backend/node_modules/minimist/test/stop_early.js b/backend/node_modules/minimist/test/stop_early.js new file mode 100644 index 0000000000000000000000000000000000000000..52a6a91903028d5230729df63afcdb80d79b0c68 --- /dev/null +++ b/backend/node_modules/minimist/test/stop_early.js @@ -0,0 +1,17 @@ +'use strict'; + +var parse = require('../'); +var test = require('tape'); + +test('stops parsing on the first non-option when stopEarly is set', function (t) { + var argv = parse(['--aaa', 'bbb', 'ccc', '--ddd'], { + stopEarly: true, + }); + + t.deepEqual(argv, { + aaa: 'bbb', + _: ['ccc', '--ddd'], + }); + + t.end(); +}); diff --git a/backend/node_modules/minimist/test/unknown.js b/backend/node_modules/minimist/test/unknown.js new file mode 100644 index 0000000000000000000000000000000000000000..4f2e0ca447f4ccc2fb7ba4df3876bf45d3f0423a --- /dev/null +++ b/backend/node_modules/minimist/test/unknown.js @@ -0,0 +1,104 @@ +'use strict'; + +var parse = require('../'); +var test = require('tape'); + +test('boolean and alias is not unknown', function (t) { + var unknown = []; + function unknownFn(arg) { + unknown.push(arg); + return false; + } + var aliased = ['-h', 'true', '--derp', 'true']; + var regular = ['--herp', 'true', '-d', 'true']; + var opts = { + alias: { h: 'herp' }, + boolean: 'h', + unknown: unknownFn, + }; + parse(aliased, opts); + parse(regular, opts); + + t.same(unknown, ['--derp', '-d']); + t.end(); +}); + +test('flag boolean true any double hyphen argument is not unknown', function (t) { + var unknown = []; + function unknownFn(arg) { + unknown.push(arg); + return false; + } + var argv = parse(['--honk', '--tacos=good', 'cow', '-p', '55'], { + boolean: true, + unknown: unknownFn, + }); + t.same(unknown, ['--tacos=good', 'cow', '-p']); + t.same(argv, { + honk: true, + _: [], + }); + t.end(); +}); + +test('string and alias is not unknown', function (t) { + var unknown = []; + function unknownFn(arg) { + unknown.push(arg); + return false; + } + var aliased = ['-h', 'hello', '--derp', 'goodbye']; + var regular = ['--herp', 'hello', '-d', 'moon']; + var opts = { + alias: { h: 'herp' }, + string: 'h', + unknown: unknownFn, + }; + parse(aliased, opts); + parse(regular, opts); + + t.same(unknown, ['--derp', '-d']); + t.end(); +}); + +test('default and alias is not unknown', function (t) { + var unknown = []; + function unknownFn(arg) { + unknown.push(arg); + return false; + } + var aliased = ['-h', 'hello']; + var regular = ['--herp', 'hello']; + var opts = { + default: { h: 'bar' }, + alias: { h: 'herp' }, + unknown: unknownFn, + }; + parse(aliased, opts); + parse(regular, opts); + + t.same(unknown, []); + t.end(); + unknownFn(); // exercise fn for 100% coverage +}); + +test('value following -- is not unknown', function (t) { + var unknown = []; + function unknownFn(arg) { + unknown.push(arg); + return false; + } + var aliased = ['--bad', '--', 'good', 'arg']; + var opts = { + '--': true, + unknown: unknownFn, + }; + var argv = parse(aliased, opts); + + t.same(unknown, ['--bad']); + t.same(argv, { + '--': ['good', 'arg'], + _: [], + }); + t.end(); +}); diff --git a/backend/node_modules/minimist/test/whitespace.js b/backend/node_modules/minimist/test/whitespace.js new file mode 100644 index 0000000000000000000000000000000000000000..4fdaf1d3943f5a16b9d76af9cd7bbc82f2f54b54 --- /dev/null +++ b/backend/node_modules/minimist/test/whitespace.js @@ -0,0 +1,10 @@ +'use strict'; + +var parse = require('../'); +var test = require('tape'); + +test('whitespace should be whitespace', function (t) { + t.plan(1); + var x = parse(['-x', '\t']).x; + t.equal(x, '\t'); +}); diff --git a/backend/node_modules/mkdirp/LICENSE b/backend/node_modules/mkdirp/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..432d1aeb01df666910230893f78e0d1ee7635a61 --- /dev/null +++ b/backend/node_modules/mkdirp/LICENSE @@ -0,0 +1,21 @@ +Copyright 2010 James Halliday (mail@substack.net) + +This project is free software released under the MIT/X11 license: + +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/backend/node_modules/mkdirp/bin/cmd.js b/backend/node_modules/mkdirp/bin/cmd.js new file mode 100755 index 0000000000000000000000000000000000000000..d95de15ae9743fc3b9e901d6fa6e8e1876c630cf --- /dev/null +++ b/backend/node_modules/mkdirp/bin/cmd.js @@ -0,0 +1,33 @@ +#!/usr/bin/env node + +var mkdirp = require('../'); +var minimist = require('minimist'); +var fs = require('fs'); + +var argv = minimist(process.argv.slice(2), { + alias: { m: 'mode', h: 'help' }, + string: [ 'mode' ] +}); +if (argv.help) { + fs.createReadStream(__dirname + '/usage.txt').pipe(process.stdout); + return; +} + +var paths = argv._.slice(); +var mode = argv.mode ? parseInt(argv.mode, 8) : undefined; + +(function next () { + if (paths.length === 0) return; + var p = paths.shift(); + + if (mode === undefined) mkdirp(p, cb) + else mkdirp(p, mode, cb) + + function cb (err) { + if (err) { + console.error(err.message); + process.exit(1); + } + else next(); + } +})(); diff --git a/backend/node_modules/mkdirp/bin/usage.txt b/backend/node_modules/mkdirp/bin/usage.txt new file mode 100644 index 0000000000000000000000000000000000000000..f952aa2c7a979e7ccb2ef81b7b5010b26b6b9e53 --- /dev/null +++ b/backend/node_modules/mkdirp/bin/usage.txt @@ -0,0 +1,12 @@ +usage: mkdirp [DIR1,DIR2..] {OPTIONS} + + Create each supplied directory including any necessary parent directories that + don't yet exist. + + If the directory already exists, do nothing. + +OPTIONS are: + + -m, --mode If a directory needs to be created, set the mode as an octal + permission string. + diff --git a/backend/node_modules/mkdirp/index.js b/backend/node_modules/mkdirp/index.js new file mode 100644 index 0000000000000000000000000000000000000000..0890ac3bd6a8833dad7e8e8926cb69b3a54a2a47 --- /dev/null +++ b/backend/node_modules/mkdirp/index.js @@ -0,0 +1,102 @@ +var path = require('path'); +var fs = require('fs'); +var _0777 = parseInt('0777', 8); + +module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP; + +function mkdirP (p, opts, f, made) { + if (typeof opts === 'function') { + f = opts; + opts = {}; + } + else if (!opts || typeof opts !== 'object') { + opts = { mode: opts }; + } + + var mode = opts.mode; + var xfs = opts.fs || fs; + + if (mode === undefined) { + mode = _0777 + } + if (!made) made = null; + + var cb = f || /* istanbul ignore next */ function () {}; + p = path.resolve(p); + + xfs.mkdir(p, mode, function (er) { + if (!er) { + made = made || p; + return cb(null, made); + } + switch (er.code) { + case 'ENOENT': + /* istanbul ignore if */ + if (path.dirname(p) === p) return cb(er); + mkdirP(path.dirname(p), opts, function (er, made) { + /* istanbul ignore if */ + if (er) cb(er, made); + else mkdirP(p, opts, cb, made); + }); + break; + + // In the case of any other error, just see if there's a dir + // there already. If so, then hooray! If not, then something + // is borked. + default: + xfs.stat(p, function (er2, stat) { + // if the stat fails, then that's super weird. + // let the original error be the failure reason. + if (er2 || !stat.isDirectory()) cb(er, made) + else cb(null, made); + }); + break; + } + }); +} + +mkdirP.sync = function sync (p, opts, made) { + if (!opts || typeof opts !== 'object') { + opts = { mode: opts }; + } + + var mode = opts.mode; + var xfs = opts.fs || fs; + + if (mode === undefined) { + mode = _0777 + } + if (!made) made = null; + + p = path.resolve(p); + + try { + xfs.mkdirSync(p, mode); + made = made || p; + } + catch (err0) { + switch (err0.code) { + case 'ENOENT' : + made = sync(path.dirname(p), opts, made); + sync(p, opts, made); + break; + + // In the case of any other error, just see if there's a dir + // there already. If so, then hooray! If not, then something + // is borked. + default: + var stat; + try { + stat = xfs.statSync(p); + } + catch (err1) /* istanbul ignore next */ { + throw err0; + } + /* istanbul ignore if */ + if (!stat.isDirectory()) throw err0; + break; + } + } + + return made; +}; diff --git a/backend/node_modules/mkdirp/package.json b/backend/node_modules/mkdirp/package.json new file mode 100644 index 0000000000000000000000000000000000000000..951e58da975ee9aca80b40e40ae9a3d1047d1b66 --- /dev/null +++ b/backend/node_modules/mkdirp/package.json @@ -0,0 +1,33 @@ +{ + "name": "mkdirp", + "description": "Recursively mkdir, like `mkdir -p`", + "version": "0.5.6", + "publishConfig": { + "tag": "legacy" + }, + "author": "James Halliday (http://substack.net)", + "main": "index.js", + "keywords": [ + "mkdir", + "directory" + ], + "repository": { + "type": "git", + "url": "https://github.com/substack/node-mkdirp.git" + }, + "scripts": { + "test": "tap test/*.js" + }, + "dependencies": { + "minimist": "^1.2.6" + }, + "devDependencies": { + "tap": "^16.0.1" + }, + "bin": "bin/cmd.js", + "license": "MIT", + "files": [ + "bin", + "index.js" + ] +} diff --git a/backend/node_modules/mkdirp/readme.markdown b/backend/node_modules/mkdirp/readme.markdown new file mode 100644 index 0000000000000000000000000000000000000000..fc314bfbd662cf9bb8a7290c77765b3f824d5ac8 --- /dev/null +++ b/backend/node_modules/mkdirp/readme.markdown @@ -0,0 +1,100 @@ +# mkdirp + +Like `mkdir -p`, but in node.js! + +[![build status](https://secure.travis-ci.org/substack/node-mkdirp.png)](http://travis-ci.org/substack/node-mkdirp) + +# example + +## pow.js + +```js +var mkdirp = require('mkdirp'); + +mkdirp('/tmp/foo/bar/baz', function (err) { + if (err) console.error(err) + else console.log('pow!') +}); +``` + +Output + +``` +pow! +``` + +And now /tmp/foo/bar/baz exists, huzzah! + +# methods + +```js +var mkdirp = require('mkdirp'); +``` + +## mkdirp(dir, opts, cb) + +Create a new directory and any necessary subdirectories at `dir` with octal +permission string `opts.mode`. If `opts` is a non-object, it will be treated as +the `opts.mode`. + +If `opts.mode` isn't specified, it defaults to `0777`. + +`cb(err, made)` fires with the error or the first directory `made` +that had to be created, if any. + +You can optionally pass in an alternate `fs` implementation by passing in +`opts.fs`. Your implementation should have `opts.fs.mkdir(path, mode, cb)` and +`opts.fs.stat(path, cb)`. + +## mkdirp.sync(dir, opts) + +Synchronously create a new directory and any necessary subdirectories at `dir` +with octal permission string `opts.mode`. If `opts` is a non-object, it will be +treated as the `opts.mode`. + +If `opts.mode` isn't specified, it defaults to `0777`. + +Returns the first directory that had to be created, if any. + +You can optionally pass in an alternate `fs` implementation by passing in +`opts.fs`. Your implementation should have `opts.fs.mkdirSync(path, mode)` and +`opts.fs.statSync(path)`. + +# usage + +This package also ships with a `mkdirp` command. + +``` +usage: mkdirp [DIR1,DIR2..] {OPTIONS} + + Create each supplied directory including any necessary parent directories that + don't yet exist. + + If the directory already exists, do nothing. + +OPTIONS are: + + -m, --mode If a directory needs to be created, set the mode as an octal + permission string. + +``` + +# install + +With [npm](http://npmjs.org) do: + +``` +npm install mkdirp +``` + +to get the library, or + +``` +npm install -g mkdirp +``` + +to get the command. + +# license + +MIT diff --git a/backend/node_modules/ms/index.js b/backend/node_modules/ms/index.js new file mode 100644 index 0000000000000000000000000000000000000000..6a522b16b3a3bf5e93aa5b8bf485f866ff71c5c2 --- /dev/null +++ b/backend/node_modules/ms/index.js @@ -0,0 +1,152 @@ +/** + * Helpers. + */ + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var y = d * 365.25; + +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ + +module.exports = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isNaN(val) === false) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; + +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + +function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } +} + +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtShort(ms) { + if (ms >= d) { + return Math.round(ms / d) + 'd'; + } + if (ms >= h) { + return Math.round(ms / h) + 'h'; + } + if (ms >= m) { + return Math.round(ms / m) + 'm'; + } + if (ms >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; +} + +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtLong(ms) { + return plural(ms, d, 'day') || + plural(ms, h, 'hour') || + plural(ms, m, 'minute') || + plural(ms, s, 'second') || + ms + ' ms'; +} + +/** + * Pluralization helper. + */ + +function plural(ms, n, name) { + if (ms < n) { + return; + } + if (ms < n * 1.5) { + return Math.floor(ms / n) + ' ' + name; + } + return Math.ceil(ms / n) + ' ' + name + 's'; +} diff --git a/backend/node_modules/ms/license.md b/backend/node_modules/ms/license.md new file mode 100644 index 0000000000000000000000000000000000000000..69b61253a38926757b7de1d4df4880fc2105c2c9 --- /dev/null +++ b/backend/node_modules/ms/license.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Zeit, Inc. + +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/backend/node_modules/ms/package.json b/backend/node_modules/ms/package.json new file mode 100644 index 0000000000000000000000000000000000000000..6a31c81fac435ac31d4a802a275128f6a49c4c0c --- /dev/null +++ b/backend/node_modules/ms/package.json @@ -0,0 +1,37 @@ +{ + "name": "ms", + "version": "2.0.0", + "description": "Tiny milisecond conversion utility", + "repository": "zeit/ms", + "main": "./index", + "files": [ + "index.js" + ], + "scripts": { + "precommit": "lint-staged", + "lint": "eslint lib/* bin/*", + "test": "mocha tests.js" + }, + "eslintConfig": { + "extends": "eslint:recommended", + "env": { + "node": true, + "es6": true + } + }, + "lint-staged": { + "*.js": [ + "npm run lint", + "prettier --single-quote --write", + "git add" + ] + }, + "license": "MIT", + "devDependencies": { + "eslint": "3.19.0", + "expect.js": "0.3.1", + "husky": "0.13.3", + "lint-staged": "3.4.1", + "mocha": "3.4.1" + } +} diff --git a/backend/node_modules/ms/readme.md b/backend/node_modules/ms/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..84a9974cccd81f9296b7d3c77f2b0d2765dfe181 --- /dev/null +++ b/backend/node_modules/ms/readme.md @@ -0,0 +1,51 @@ +# ms + +[![Build Status](https://travis-ci.org/zeit/ms.svg?branch=master)](https://travis-ci.org/zeit/ms) +[![Slack Channel](http://zeit-slackin.now.sh/badge.svg)](https://zeit.chat/) + +Use this package to easily convert various time formats to milliseconds. + +## Examples + +```js +ms('2 days') // 172800000 +ms('1d') // 86400000 +ms('10h') // 36000000 +ms('2.5 hrs') // 9000000 +ms('2h') // 7200000 +ms('1m') // 60000 +ms('5s') // 5000 +ms('1y') // 31557600000 +ms('100') // 100 +``` + +### Convert from milliseconds + +```js +ms(60000) // "1m" +ms(2 * 60000) // "2m" +ms(ms('10 hours')) // "10h" +``` + +### Time format written-out + +```js +ms(60000, { long: true }) // "1 minute" +ms(2 * 60000, { long: true }) // "2 minutes" +ms(ms('10 hours'), { long: true }) // "10 hours" +``` + +## Features + +- Works both in [node](https://nodejs.org) and in the browser. +- If a number is supplied to `ms`, a string with a unit is returned. +- If a string that contains the number is supplied, it returns it as a number (e.g.: it returns `100` for `'100'`). +- If you pass a string with a number and a valid unit, the number of equivalent ms is returned. + +## Caught a bug? + +1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device +2. Link the package to the global module directory: `npm link` +3. Within the module you want to test your local development instance of ms, just link it to the dependencies: `npm link ms`. Instead of the default one from npm, node will now use your clone of ms! + +As always, you can run the tests using: `npm test` diff --git a/backend/node_modules/multer/LICENSE b/backend/node_modules/multer/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..6c011b18fa16e456f63b662d75047e376306874b --- /dev/null +++ b/backend/node_modules/multer/LICENSE @@ -0,0 +1,17 @@ +Copyright (c) 2014 Hage Yaapa <[http://www.hacksparrow.com](http://www.hacksparrow.com)> + +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/backend/node_modules/multer/README.md b/backend/node_modules/multer/README.md new file mode 100644 index 0000000000000000000000000000000000000000..7f5d08071cae3afc6a9547e2381ec59f13cfc9f8 --- /dev/null +++ b/backend/node_modules/multer/README.md @@ -0,0 +1,333 @@ +# Multer [![Build Status](https://travis-ci.org/expressjs/multer.svg?branch=master)](https://travis-ci.org/expressjs/multer) [![NPM version](https://badge.fury.io/js/multer.svg)](https://badge.fury.io/js/multer) [![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat)](https://github.com/feross/standard) + +Multer is a node.js middleware for handling `multipart/form-data`, which is primarily used for uploading files. It is written +on top of [busboy](https://github.com/mscdex/busboy) for maximum efficiency. + +**NOTE**: Multer will not process any form which is not multipart (`multipart/form-data`). + +## Translations + +This README is also available in other languages: + +- [Español](https://github.com/expressjs/multer/blob/master/doc/README-es.md) (Spanish) +- [简体中文](https://github.com/expressjs/multer/blob/master/doc/README-zh-cn.md) (Chinese) +- [한국어](https://github.com/expressjs/multer/blob/master/doc/README-ko.md) (Korean) +- [Русский язык](https://github.com/expressjs/multer/blob/master/doc/README-ru.md) (Russian) +- [Việt Nam](https://github.com/expressjs/multer/blob/master/doc/README-vi.md) (Vietnam) +- [Português](https://github.com/expressjs/multer/blob/master/doc/README-pt-br.md) (Portuguese Brazil) + +## Installation + +```sh +$ npm install --save multer +``` + +## Usage + +Multer adds a `body` object and a `file` or `files` object to the `request` object. The `body` object contains the values of the text fields of the form, the `file` or `files` object contains the files uploaded via the form. + +Basic usage example: + +Don't forget the `enctype="multipart/form-data"` in your form. + +```html +
+ +
+``` + +```javascript +const express = require('express') +const multer = require('multer') +const upload = multer({ dest: 'uploads/' }) + +const app = express() + +app.post('/profile', upload.single('avatar'), function (req, res, next) { + // req.file is the `avatar` file + // req.body will hold the text fields, if there were any +}) + +app.post('/photos/upload', upload.array('photos', 12), function (req, res, next) { + // req.files is array of `photos` files + // req.body will contain the text fields, if there were any +}) + +const cpUpload = upload.fields([{ name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }]) +app.post('/cool-profile', cpUpload, function (req, res, next) { + // req.files is an object (String -> Array) where fieldname is the key, and the value is array of files + // + // e.g. + // req.files['avatar'][0] -> File + // req.files['gallery'] -> Array + // + // req.body will contain the text fields, if there were any +}) +``` + +In case you need to handle a text-only multipart form, you should use the `.none()` method: + +```javascript +const express = require('express') +const app = express() +const multer = require('multer') +const upload = multer() + +app.post('/profile', upload.none(), function (req, res, next) { + // req.body contains the text fields +}) +``` + +Here's an example on how multer is used an HTML form. Take special note of the `enctype="multipart/form-data"` and `name="uploaded_file"` fields: + +```html +
+
+ + + +
+
+``` + +Then in your javascript file you would add these lines to access both the file and the body. It is important that you use the `name` field value from the form in your upload function. This tells multer which field on the request it should look for the files in. If these fields aren't the same in the HTML form and on your server, your upload will fail: + +```javascript +const multer = require('multer') +const upload = multer({ dest: './public/data/uploads/' }) +app.post('/stats', upload.single('uploaded_file'), function (req, res) { + // req.file is the name of your file in the form above, here 'uploaded_file' + // req.body will hold the text fields, if there were any + console.log(req.file, req.body) +}); +``` + + + +## API + +### File information + +Each file contains the following information: + +Key | Description | Note +--- | --- | --- +`fieldname` | Field name specified in the form | +`originalname` | Name of the file on the user's computer | +`encoding` | Encoding type of the file | +`mimetype` | Mime type of the file | +`size` | Size of the file in bytes | +`destination` | The folder to which the file has been saved | `DiskStorage` +`filename` | The name of the file within the `destination` | `DiskStorage` +`path` | The full path to the uploaded file | `DiskStorage` +`buffer` | A `Buffer` of the entire file | `MemoryStorage` + +### `multer(opts)` + +Multer accepts an options object, the most basic of which is the `dest` +property, which tells Multer where to upload the files. In case you omit the +options object, the files will be kept in memory and never written to disk. + +By default, Multer will rename the files so as to avoid naming conflicts. The +renaming function can be customized according to your needs. + +The following are the options that can be passed to Multer. + +Key | Description +--- | --- +`dest` or `storage` | Where to store the files +`fileFilter` | Function to control which files are accepted +`limits` | Limits of the uploaded data +`preservePath` | Keep the full path of files instead of just the base name + +In an average web app, only `dest` might be required, and configured as shown in +the following example. + +```javascript +const upload = multer({ dest: 'uploads/' }) +``` + +If you want more control over your uploads, you'll want to use the `storage` +option instead of `dest`. Multer ships with storage engines `DiskStorage` +and `MemoryStorage`; More engines are available from third parties. + +#### `.single(fieldname)` + +Accept a single file with the name `fieldname`. The single file will be stored +in `req.file`. + +#### `.array(fieldname[, maxCount])` + +Accept an array of files, all with the name `fieldname`. Optionally error out if +more than `maxCount` files are uploaded. The array of files will be stored in +`req.files`. + +#### `.fields(fields)` + +Accept a mix of files, specified by `fields`. An object with arrays of files +will be stored in `req.files`. + +`fields` should be an array of objects with `name` and optionally a `maxCount`. +Example: + +```javascript +[ + { name: 'avatar', maxCount: 1 }, + { name: 'gallery', maxCount: 8 } +] +``` + +#### `.none()` + +Accept only text fields. If any file upload is made, error with code +"LIMIT\_UNEXPECTED\_FILE" will be issued. + +#### `.any()` + +Accepts all files that comes over the wire. An array of files will be stored in +`req.files`. + +**WARNING:** Make sure that you always handle the files that a user uploads. +Never add multer as a global middleware since a malicious user could upload +files to a route that you didn't anticipate. Only use this function on routes +where you are handling the uploaded files. + +### `storage` + +#### `DiskStorage` + +The disk storage engine gives you full control on storing files to disk. + +```javascript +const storage = multer.diskStorage({ + destination: function (req, file, cb) { + cb(null, '/tmp/my-uploads') + }, + filename: function (req, file, cb) { + const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9) + cb(null, file.fieldname + '-' + uniqueSuffix) + } +}) + +const upload = multer({ storage: storage }) +``` + +There are two options available, `destination` and `filename`. They are both +functions that determine where the file should be stored. + +`destination` is used to determine within which folder the uploaded files should +be stored. This can also be given as a `string` (e.g. `'/tmp/uploads'`). If no +`destination` is given, the operating system's default directory for temporary +files is used. + +**Note:** You are responsible for creating the directory when providing +`destination` as a function. When passing a string, multer will make sure that +the directory is created for you. + +`filename` is used to determine what the file should be named inside the folder. +If no `filename` is given, each file will be given a random name that doesn't +include any file extension. + +**Note:** Multer will not append any file extension for you, your function +should return a filename complete with an file extension. + +Each function gets passed both the request (`req`) and some information about +the file (`file`) to aid with the decision. + +Note that `req.body` might not have been fully populated yet. It depends on the +order that the client transmits fields and files to the server. + +For understanding the calling convention used in the callback (needing to pass +null as the first param), refer to +[Node.js error handling](https://www.joyent.com/node-js/production/design/errors) + +#### `MemoryStorage` + +The memory storage engine stores the files in memory as `Buffer` objects. It +doesn't have any options. + +```javascript +const storage = multer.memoryStorage() +const upload = multer({ storage: storage }) +``` + +When using memory storage, the file info will contain a field called +`buffer` that contains the entire file. + +**WARNING**: Uploading very large files, or relatively small files in large +numbers very quickly, can cause your application to run out of memory when +memory storage is used. + +### `limits` + +An object specifying the size limits of the following optional properties. Multer passes this object into busboy directly, and the details of the properties can be found on [busboy's page](https://github.com/mscdex/busboy#busboy-methods). + +The following integer values are available: + +Key | Description | Default +--- | --- | --- +`fieldNameSize` | Max field name size | 100 bytes +`fieldSize` | Max field value size (in bytes) | 1MB +`fields` | Max number of non-file fields | Infinity +`fileSize` | For multipart forms, the max file size (in bytes) | Infinity +`files` | For multipart forms, the max number of file fields | Infinity +`parts` | For multipart forms, the max number of parts (fields + files) | Infinity +`headerPairs` | For multipart forms, the max number of header key=>value pairs to parse | 2000 + +Specifying the limits can help protect your site against denial of service (DoS) attacks. + +### `fileFilter` + +Set this to a function to control which files should be uploaded and which +should be skipped. The function should look like this: + +```javascript +function fileFilter (req, file, cb) { + + // The function should call `cb` with a boolean + // to indicate if the file should be accepted + + // To reject this file pass `false`, like so: + cb(null, false) + + // To accept the file pass `true`, like so: + cb(null, true) + + // You can always pass an error if something goes wrong: + cb(new Error('I don\'t have a clue!')) + +} +``` + +## Error handling + +When encountering an error, Multer will delegate the error to Express. You can +display a nice error page using [the standard express way](http://expressjs.com/guide/error-handling.html). + +If you want to catch errors specifically from Multer, you can call the +middleware function by yourself. Also, if you want to catch only [the Multer errors](https://github.com/expressjs/multer/blob/master/lib/multer-error.js), you can use the `MulterError` class that is attached to the `multer` object itself (e.g. `err instanceof multer.MulterError`). + +```javascript +const multer = require('multer') +const upload = multer().single('avatar') + +app.post('/profile', function (req, res) { + upload(req, res, function (err) { + if (err instanceof multer.MulterError) { + // A Multer error occurred when uploading. + } else if (err) { + // An unknown error occurred when uploading. + } + + // Everything went fine. + }) +}) +``` + +## Custom storage engine + +For information on how to build your own storage engine, see [Multer Storage Engine](https://github.com/expressjs/multer/blob/master/StorageEngine.md). + +## License + +[MIT](LICENSE) diff --git a/backend/node_modules/multer/index.js b/backend/node_modules/multer/index.js new file mode 100644 index 0000000000000000000000000000000000000000..d5b67eba3a7d9b37840270102aa78486b0e8376b --- /dev/null +++ b/backend/node_modules/multer/index.js @@ -0,0 +1,104 @@ +var makeMiddleware = require('./lib/make-middleware') + +var diskStorage = require('./storage/disk') +var memoryStorage = require('./storage/memory') +var MulterError = require('./lib/multer-error') + +function allowAll (req, file, cb) { + cb(null, true) +} + +function Multer (options) { + if (options.storage) { + this.storage = options.storage + } else if (options.dest) { + this.storage = diskStorage({ destination: options.dest }) + } else { + this.storage = memoryStorage() + } + + this.limits = options.limits + this.preservePath = options.preservePath + this.fileFilter = options.fileFilter || allowAll +} + +Multer.prototype._makeMiddleware = function (fields, fileStrategy) { + function setup () { + var fileFilter = this.fileFilter + var filesLeft = Object.create(null) + + fields.forEach(function (field) { + if (typeof field.maxCount === 'number') { + filesLeft[field.name] = field.maxCount + } else { + filesLeft[field.name] = Infinity + } + }) + + function wrappedFileFilter (req, file, cb) { + if ((filesLeft[file.fieldname] || 0) <= 0) { + return cb(new MulterError('LIMIT_UNEXPECTED_FILE', file.fieldname)) + } + + filesLeft[file.fieldname] -= 1 + fileFilter(req, file, cb) + } + + return { + limits: this.limits, + preservePath: this.preservePath, + storage: this.storage, + fileFilter: wrappedFileFilter, + fileStrategy: fileStrategy + } + } + + return makeMiddleware(setup.bind(this)) +} + +Multer.prototype.single = function (name) { + return this._makeMiddleware([{ name: name, maxCount: 1 }], 'VALUE') +} + +Multer.prototype.array = function (name, maxCount) { + return this._makeMiddleware([{ name: name, maxCount: maxCount }], 'ARRAY') +} + +Multer.prototype.fields = function (fields) { + return this._makeMiddleware(fields, 'OBJECT') +} + +Multer.prototype.none = function () { + return this._makeMiddleware([], 'NONE') +} + +Multer.prototype.any = function () { + function setup () { + return { + limits: this.limits, + preservePath: this.preservePath, + storage: this.storage, + fileFilter: this.fileFilter, + fileStrategy: 'ARRAY' + } + } + + return makeMiddleware(setup.bind(this)) +} + +function multer (options) { + if (options === undefined) { + return new Multer({}) + } + + if (typeof options === 'object' && options !== null) { + return new Multer(options) + } + + throw new TypeError('Expected object for argument options') +} + +module.exports = multer +module.exports.diskStorage = diskStorage +module.exports.memoryStorage = memoryStorage +module.exports.MulterError = MulterError diff --git a/backend/node_modules/multer/lib/counter.js b/backend/node_modules/multer/lib/counter.js new file mode 100644 index 0000000000000000000000000000000000000000..29c410c7b4850d2640fef61629508a534fc98a74 --- /dev/null +++ b/backend/node_modules/multer/lib/counter.js @@ -0,0 +1,28 @@ +var EventEmitter = require('events').EventEmitter + +function Counter () { + EventEmitter.call(this) + this.value = 0 +} + +Counter.prototype = Object.create(EventEmitter.prototype) + +Counter.prototype.increment = function increment () { + this.value++ +} + +Counter.prototype.decrement = function decrement () { + if (--this.value === 0) this.emit('zero') +} + +Counter.prototype.isZero = function isZero () { + return (this.value === 0) +} + +Counter.prototype.onceZero = function onceZero (fn) { + if (this.isZero()) return fn() + + this.once('zero', fn) +} + +module.exports = Counter diff --git a/backend/node_modules/multer/lib/file-appender.js b/backend/node_modules/multer/lib/file-appender.js new file mode 100644 index 0000000000000000000000000000000000000000..1a2c5e76e98c539fc855924111c054d3df943857 --- /dev/null +++ b/backend/node_modules/multer/lib/file-appender.js @@ -0,0 +1,67 @@ +var objectAssign = require('object-assign') + +function arrayRemove (arr, item) { + var idx = arr.indexOf(item) + if (~idx) arr.splice(idx, 1) +} + +function FileAppender (strategy, req) { + this.strategy = strategy + this.req = req + + switch (strategy) { + case 'NONE': break + case 'VALUE': break + case 'ARRAY': req.files = []; break + case 'OBJECT': req.files = Object.create(null); break + default: throw new Error('Unknown file strategy: ' + strategy) + } +} + +FileAppender.prototype.insertPlaceholder = function (file) { + var placeholder = { + fieldname: file.fieldname + } + + switch (this.strategy) { + case 'NONE': break + case 'VALUE': break + case 'ARRAY': this.req.files.push(placeholder); break + case 'OBJECT': + if (this.req.files[file.fieldname]) { + this.req.files[file.fieldname].push(placeholder) + } else { + this.req.files[file.fieldname] = [placeholder] + } + break + } + + return placeholder +} + +FileAppender.prototype.removePlaceholder = function (placeholder) { + switch (this.strategy) { + case 'NONE': break + case 'VALUE': break + case 'ARRAY': arrayRemove(this.req.files, placeholder); break + case 'OBJECT': + if (this.req.files[placeholder.fieldname].length === 1) { + delete this.req.files[placeholder.fieldname] + } else { + arrayRemove(this.req.files[placeholder.fieldname], placeholder) + } + break + } +} + +FileAppender.prototype.replacePlaceholder = function (placeholder, file) { + if (this.strategy === 'VALUE') { + this.req.file = file + return + } + + delete placeholder.fieldname + objectAssign(placeholder, file) +} + +module.exports = FileAppender diff --git a/backend/node_modules/multer/lib/make-middleware.js b/backend/node_modules/multer/lib/make-middleware.js new file mode 100644 index 0000000000000000000000000000000000000000..6627cf4c335f38bb777b868a13047a145a13d81a --- /dev/null +++ b/backend/node_modules/multer/lib/make-middleware.js @@ -0,0 +1,173 @@ +var is = require('type-is') +var Busboy = require('busboy') +var extend = require('xtend') +var appendField = require('append-field') + +var Counter = require('./counter') +var MulterError = require('./multer-error') +var FileAppender = require('./file-appender') +var removeUploadedFiles = require('./remove-uploaded-files') + +function makeMiddleware (setup) { + return function multerMiddleware (req, res, next) { + if (!is(req, ['multipart'])) return next() + + var options = setup() + + var limits = options.limits + var storage = options.storage + var fileFilter = options.fileFilter + var fileStrategy = options.fileStrategy + var preservePath = options.preservePath + + req.body = Object.create(null) + + var busboy + + try { + busboy = Busboy({ headers: req.headers, limits: limits, preservePath: preservePath }) + } catch (err) { + return next(err) + } + + var appender = new FileAppender(fileStrategy, req) + var isDone = false + var readFinished = false + var errorOccured = false + var pendingWrites = new Counter() + var uploadedFiles = [] + + function done (err) { + if (isDone) return + isDone = true + req.unpipe(busboy) + busboy.removeAllListeners() + next(err) + } + + function indicateDone () { + if (readFinished && pendingWrites.isZero() && !errorOccured) done() + } + + function abortWithError (uploadError) { + if (errorOccured) return + errorOccured = true + + pendingWrites.onceZero(function () { + function remove (file, cb) { + storage._removeFile(req, file, cb) + } + + removeUploadedFiles(uploadedFiles, remove, function (err, storageErrors) { + if (err) return done(err) + + uploadError.storageErrors = storageErrors + done(uploadError) + }) + }) + } + + function abortWithCode (code, optionalField) { + abortWithError(new MulterError(code, optionalField)) + } + + // handle text field data + busboy.on('field', function (fieldname, value, { nameTruncated, valueTruncated }) { + if (fieldname == null) return abortWithCode('MISSING_FIELD_NAME') + if (nameTruncated) return abortWithCode('LIMIT_FIELD_KEY') + if (valueTruncated) return abortWithCode('LIMIT_FIELD_VALUE', fieldname) + + // Work around bug in Busboy (https://github.com/mscdex/busboy/issues/6) + if (limits && Object.prototype.hasOwnProperty.call(limits, 'fieldNameSize')) { + if (fieldname.length > limits.fieldNameSize) return abortWithCode('LIMIT_FIELD_KEY') + } + + appendField(req.body, fieldname, value) + }) + + // handle files + busboy.on('file', function (fieldname, fileStream, { filename, encoding, mimeType }) { + // don't attach to the files object, if there is no file + if (!filename) return fileStream.resume() + + // Work around bug in Busboy (https://github.com/mscdex/busboy/issues/6) + if (limits && Object.prototype.hasOwnProperty.call(limits, 'fieldNameSize')) { + if (fieldname.length > limits.fieldNameSize) return abortWithCode('LIMIT_FIELD_KEY') + } + + var file = { + fieldname: fieldname, + originalname: filename, + encoding: encoding, + mimetype: mimeType + } + + var placeholder = appender.insertPlaceholder(file) + + fileFilter(req, file, function (err, includeFile) { + if (err) { + appender.removePlaceholder(placeholder) + return abortWithError(err) + } + + if (!includeFile) { + appender.removePlaceholder(placeholder) + return fileStream.resume() + } + + var aborting = false + pendingWrites.increment() + + Object.defineProperty(file, 'stream', { + configurable: true, + enumerable: false, + value: fileStream + }) + + fileStream.on('error', function (err) { + pendingWrites.decrement() + abortWithError(err) + }) + + fileStream.on('limit', function () { + aborting = true + abortWithCode('LIMIT_FILE_SIZE', fieldname) + }) + + storage._handleFile(req, file, function (err, info) { + if (aborting) { + appender.removePlaceholder(placeholder) + uploadedFiles.push(extend(file, info)) + return pendingWrites.decrement() + } + + if (err) { + appender.removePlaceholder(placeholder) + pendingWrites.decrement() + return abortWithError(err) + } + + var fileInfo = extend(file, info) + + appender.replacePlaceholder(placeholder, fileInfo) + uploadedFiles.push(fileInfo) + pendingWrites.decrement() + indicateDone() + }) + }) + }) + + busboy.on('error', function (err) { abortWithError(err) }) + busboy.on('partsLimit', function () { abortWithCode('LIMIT_PART_COUNT') }) + busboy.on('filesLimit', function () { abortWithCode('LIMIT_FILE_COUNT') }) + busboy.on('fieldsLimit', function () { abortWithCode('LIMIT_FIELD_COUNT') }) + busboy.on('close', function () { + readFinished = true + indicateDone() + }) + + req.pipe(busboy) + } +} + +module.exports = makeMiddleware diff --git a/backend/node_modules/multer/lib/multer-error.js b/backend/node_modules/multer/lib/multer-error.js new file mode 100644 index 0000000000000000000000000000000000000000..d56b00e88cc59deb83a5cfec9d7bea3de29400ed --- /dev/null +++ b/backend/node_modules/multer/lib/multer-error.js @@ -0,0 +1,24 @@ +var util = require('util') + +var errorMessages = { + LIMIT_PART_COUNT: 'Too many parts', + LIMIT_FILE_SIZE: 'File too large', + LIMIT_FILE_COUNT: 'Too many files', + LIMIT_FIELD_KEY: 'Field name too long', + LIMIT_FIELD_VALUE: 'Field value too long', + LIMIT_FIELD_COUNT: 'Too many fields', + LIMIT_UNEXPECTED_FILE: 'Unexpected field', + MISSING_FIELD_NAME: 'Field name missing' +} + +function MulterError (code, field) { + Error.captureStackTrace(this, this.constructor) + this.name = this.constructor.name + this.message = errorMessages[code] + this.code = code + if (field) this.field = field +} + +util.inherits(MulterError, Error) + +module.exports = MulterError diff --git a/backend/node_modules/multer/lib/remove-uploaded-files.js b/backend/node_modules/multer/lib/remove-uploaded-files.js new file mode 100644 index 0000000000000000000000000000000000000000..f0b16ea506ad69bc1b5f5b37f143a20b21f44569 --- /dev/null +++ b/backend/node_modules/multer/lib/remove-uploaded-files.js @@ -0,0 +1,28 @@ +function removeUploadedFiles (uploadedFiles, remove, cb) { + var length = uploadedFiles.length + var errors = [] + + if (length === 0) return cb(null, errors) + + function handleFile (idx) { + var file = uploadedFiles[idx] + + remove(file, function (err) { + if (err) { + err.file = file + err.field = file.fieldname + errors.push(err) + } + + if (idx < length - 1) { + handleFile(idx + 1) + } else { + cb(null, errors) + } + }) + } + + handleFile(0) +} + +module.exports = removeUploadedFiles diff --git a/backend/node_modules/multer/package.json b/backend/node_modules/multer/package.json new file mode 100644 index 0000000000000000000000000000000000000000..8545a73d304da06d58bde7243faba96b8d71224e --- /dev/null +++ b/backend/node_modules/multer/package.json @@ -0,0 +1,52 @@ +{ + "name": "multer", + "description": "Middleware for handling `multipart/form-data`.", + "version": "1.4.5-lts.1", + "contributors": [ + "Hage Yaapa (http://www.hacksparrow.com)", + "Jaret Pfluger ", + "Linus Unnebäck " + ], + "license": "MIT", + "repository": "expressjs/multer", + "keywords": [ + "form", + "post", + "multipart", + "form-data", + "formdata", + "express", + "middleware" + ], + "dependencies": { + "append-field": "^1.0.0", + "busboy": "^1.0.0", + "concat-stream": "^1.5.2", + "mkdirp": "^0.5.4", + "object-assign": "^4.1.1", + "type-is": "^1.6.4", + "xtend": "^4.0.0" + }, + "devDependencies": { + "deep-equal": "^2.0.3", + "express": "^4.13.1", + "form-data": "^1.0.0-rc1", + "fs-temp": "^1.1.2", + "mocha": "^3.5.3", + "rimraf": "^2.4.1", + "standard": "^14.3.3", + "testdata-w3c-json-form": "^1.0.0" + }, + "engines": { + "node": ">= 6.0.0" + }, + "files": [ + "LICENSE", + "index.js", + "storage/", + "lib/" + ], + "scripts": { + "test": "standard && mocha" + } +} diff --git a/backend/node_modules/multer/storage/disk.js b/backend/node_modules/multer/storage/disk.js new file mode 100644 index 0000000000000000000000000000000000000000..2f77c9f133c9fd21662fd07e9ef546dae19bc53c --- /dev/null +++ b/backend/node_modules/multer/storage/disk.js @@ -0,0 +1,66 @@ +var fs = require('fs') +var os = require('os') +var path = require('path') +var crypto = require('crypto') +var mkdirp = require('mkdirp') + +function getFilename (req, file, cb) { + crypto.randomBytes(16, function (err, raw) { + cb(err, err ? undefined : raw.toString('hex')) + }) +} + +function getDestination (req, file, cb) { + cb(null, os.tmpdir()) +} + +function DiskStorage (opts) { + this.getFilename = (opts.filename || getFilename) + + if (typeof opts.destination === 'string') { + mkdirp.sync(opts.destination) + this.getDestination = function ($0, $1, cb) { cb(null, opts.destination) } + } else { + this.getDestination = (opts.destination || getDestination) + } +} + +DiskStorage.prototype._handleFile = function _handleFile (req, file, cb) { + var that = this + + that.getDestination(req, file, function (err, destination) { + if (err) return cb(err) + + that.getFilename(req, file, function (err, filename) { + if (err) return cb(err) + + var finalPath = path.join(destination, filename) + var outStream = fs.createWriteStream(finalPath) + + file.stream.pipe(outStream) + outStream.on('error', cb) + outStream.on('finish', function () { + cb(null, { + destination: destination, + filename: filename, + path: finalPath, + size: outStream.bytesWritten + }) + }) + }) + }) +} + +DiskStorage.prototype._removeFile = function _removeFile (req, file, cb) { + var path = file.path + + delete file.destination + delete file.filename + delete file.path + + fs.unlink(path, cb) +} + +module.exports = function (opts) { + return new DiskStorage(opts) +} diff --git a/backend/node_modules/multer/storage/memory.js b/backend/node_modules/multer/storage/memory.js new file mode 100644 index 0000000000000000000000000000000000000000..f953ded15a2baf5cf59d3c2a716a8d5576db086c --- /dev/null +++ b/backend/node_modules/multer/storage/memory.js @@ -0,0 +1,21 @@ +var concat = require('concat-stream') + +function MemoryStorage (opts) {} + +MemoryStorage.prototype._handleFile = function _handleFile (req, file, cb) { + file.stream.pipe(concat({ encoding: 'buffer' }, function (data) { + cb(null, { + buffer: data, + size: data.length + }) + })) +} + +MemoryStorage.prototype._removeFile = function _removeFile (req, file, cb) { + delete file.buffer + cb(null) +} + +module.exports = function (opts) { + return new MemoryStorage(opts) +} diff --git a/backend/node_modules/negotiator/HISTORY.md b/backend/node_modules/negotiator/HISTORY.md new file mode 100644 index 0000000000000000000000000000000000000000..a9a544914c43bb8927b9ee9ff02aa2c2c7277fdb --- /dev/null +++ b/backend/node_modules/negotiator/HISTORY.md @@ -0,0 +1,108 @@ +0.6.3 / 2022-01-22 +================== + + * Revert "Lazy-load modules from main entry point" + +0.6.2 / 2019-04-29 +================== + + * Fix sorting charset, encoding, and language with extra parameters + +0.6.1 / 2016-05-02 +================== + + * perf: improve `Accept` parsing speed + * perf: improve `Accept-Charset` parsing speed + * perf: improve `Accept-Encoding` parsing speed + * perf: improve `Accept-Language` parsing speed + +0.6.0 / 2015-09-29 +================== + + * 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 + +0.5.3 / 2015-05-10 +================== + + * Fix media type parameter matching to be case-insensitive + +0.5.2 / 2015-05-06 +================== + + * Fix comparing media types with quoted values + * Fix splitting media types with quoted commas + +0.5.1 / 2015-02-14 +================== + + * Fix preference sorting to be stable for long acceptable lists + +0.5.0 / 2014-12-18 +================== + + * Fix list return order when large accepted list + * Fix missing identity encoding when q=0 exists + * Remove dynamic building of Negotiator class + +0.4.9 / 2014-10-14 +================== + + * Fix error when media type has invalid parameter + +0.4.8 / 2014-09-28 +================== + + * Fix all negotiations to be case-insensitive + * Stable sort preferences of same quality according to client order + * Support Node.js 0.6 + +0.4.7 / 2014-06-24 +================== + + * Handle invalid provided languages + * Handle invalid provided media types + +0.4.6 / 2014-06-11 +================== + + * Order by specificity when quality is the same + +0.4.5 / 2014-05-29 +================== + + * Fix regression in empty header handling + +0.4.4 / 2014-05-29 +================== + + * Fix behaviors when headers are not present + +0.4.3 / 2014-04-16 +================== + + * Handle slashes on media params correctly + +0.4.2 / 2014-02-28 +================== + + * Fix media type sorting + * Handle media types params strictly + +0.4.1 / 2014-01-16 +================== + + * Use most specific matches + +0.4.0 / 2014-01-09 +================== + + * Remove preferred prefix from methods diff --git a/backend/node_modules/negotiator/LICENSE b/backend/node_modules/negotiator/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..ea6b9e2e9ac251526c95df2dd995cf5f1e861854 --- /dev/null +++ b/backend/node_modules/negotiator/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2012-2014 Federico Romero +Copyright (c) 2012-2014 Isaac Z. Schlueter +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/backend/node_modules/negotiator/README.md b/backend/node_modules/negotiator/README.md new file mode 100644 index 0000000000000000000000000000000000000000..82915e521b4d321d90111316c6193706f1d7b8bf --- /dev/null +++ b/backend/node_modules/negotiator/README.md @@ -0,0 +1,203 @@ +# negotiator + +[![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] + +An HTTP content negotiator for Node.js + +## Installation + +```sh +$ npm install negotiator +``` + +## API + +```js +var Negotiator = require('negotiator') +``` + +### Accept Negotiation + +```js +availableMediaTypes = ['text/html', 'text/plain', 'application/json'] + +// The negotiator constructor receives a request object +negotiator = new Negotiator(request) + +// Let's say Accept header is 'text/html, application/*;q=0.2, image/jpeg;q=0.8' + +negotiator.mediaTypes() +// -> ['text/html', 'image/jpeg', 'application/*'] + +negotiator.mediaTypes(availableMediaTypes) +// -> ['text/html', 'application/json'] + +negotiator.mediaType(availableMediaTypes) +// -> 'text/html' +``` + +You can check a working example at `examples/accept.js`. + +#### Methods + +##### mediaType() + +Returns the most preferred media type from the client. + +##### mediaType(availableMediaType) + +Returns the most preferred media type from a list of available media types. + +##### mediaTypes() + +Returns an array of preferred media types ordered by the client preference. + +##### mediaTypes(availableMediaTypes) + +Returns an array of preferred media types ordered by priority from a list of +available media types. + +### Accept-Language Negotiation + +```js +negotiator = new Negotiator(request) + +availableLanguages = ['en', 'es', 'fr'] + +// Let's say Accept-Language header is 'en;q=0.8, es, pt' + +negotiator.languages() +// -> ['es', 'pt', 'en'] + +negotiator.languages(availableLanguages) +// -> ['es', 'en'] + +language = negotiator.language(availableLanguages) +// -> 'es' +``` + +You can check a working example at `examples/language.js`. + +#### Methods + +##### language() + +Returns the most preferred language from the client. + +##### language(availableLanguages) + +Returns the most preferred language from a list of available languages. + +##### languages() + +Returns an array of preferred languages ordered by the client preference. + +##### languages(availableLanguages) + +Returns an array of preferred languages ordered by priority from a list of +available languages. + +### Accept-Charset Negotiation + +```js +availableCharsets = ['utf-8', 'iso-8859-1', 'iso-8859-5'] + +negotiator = new Negotiator(request) + +// Let's say Accept-Charset header is 'utf-8, iso-8859-1;q=0.8, utf-7;q=0.2' + +negotiator.charsets() +// -> ['utf-8', 'iso-8859-1', 'utf-7'] + +negotiator.charsets(availableCharsets) +// -> ['utf-8', 'iso-8859-1'] + +negotiator.charset(availableCharsets) +// -> 'utf-8' +``` + +You can check a working example at `examples/charset.js`. + +#### Methods + +##### charset() + +Returns the most preferred charset from the client. + +##### charset(availableCharsets) + +Returns the most preferred charset from a list of available charsets. + +##### charsets() + +Returns an array of preferred charsets ordered by the client preference. + +##### charsets(availableCharsets) + +Returns an array of preferred charsets ordered by priority from a list of +available charsets. + +### Accept-Encoding Negotiation + +```js +availableEncodings = ['identity', 'gzip'] + +negotiator = new Negotiator(request) + +// Let's say Accept-Encoding header is 'gzip, compress;q=0.2, identity;q=0.5' + +negotiator.encodings() +// -> ['gzip', 'identity', 'compress'] + +negotiator.encodings(availableEncodings) +// -> ['gzip', 'identity'] + +negotiator.encoding(availableEncodings) +// -> 'gzip' +``` + +You can check a working example at `examples/encoding.js`. + +#### Methods + +##### encoding() + +Returns the most preferred encoding from the client. + +##### encoding(availableEncodings) + +Returns the most preferred encoding from a list of available encodings. + +##### encodings() + +Returns an array of preferred encodings ordered by the client preference. + +##### encodings(availableEncodings) + +Returns an array of preferred encodings ordered by priority from a list of +available encodings. + +## See Also + +The [accepts](https://npmjs.org/package/accepts#readme) module builds on +this module and provides an alternative interface, mime type validation, +and more. + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/negotiator.svg +[npm-url]: https://npmjs.org/package/negotiator +[node-version-image]: https://img.shields.io/node/v/negotiator.svg +[node-version-url]: https://nodejs.org/en/download/ +[coveralls-image]: https://img.shields.io/coveralls/jshttp/negotiator/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/negotiator?branch=master +[downloads-image]: https://img.shields.io/npm/dm/negotiator.svg +[downloads-url]: https://npmjs.org/package/negotiator +[github-actions-ci-image]: https://img.shields.io/github/workflow/status/jshttp/negotiator/ci/master?label=ci +[github-actions-ci-url]: https://github.com/jshttp/negotiator/actions/workflows/ci.yml diff --git a/backend/node_modules/negotiator/index.js b/backend/node_modules/negotiator/index.js new file mode 100644 index 0000000000000000000000000000000000000000..4788264b16c9f2282bba539529577ed31920425d --- /dev/null +++ b/backend/node_modules/negotiator/index.js @@ -0,0 +1,82 @@ +/*! + * negotiator + * Copyright(c) 2012 Federico Romero + * Copyright(c) 2012-2014 Isaac Z. Schlueter + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +var preferredCharsets = require('./lib/charset') +var preferredEncodings = require('./lib/encoding') +var preferredLanguages = require('./lib/language') +var preferredMediaTypes = require('./lib/mediaType') + +/** + * Module exports. + * @public + */ + +module.exports = Negotiator; +module.exports.Negotiator = Negotiator; + +/** + * Create a Negotiator instance from a request. + * @param {object} request + * @public + */ + +function Negotiator(request) { + if (!(this instanceof Negotiator)) { + return new Negotiator(request); + } + + this.request = request; +} + +Negotiator.prototype.charset = function charset(available) { + var set = this.charsets(available); + return set && set[0]; +}; + +Negotiator.prototype.charsets = function charsets(available) { + return preferredCharsets(this.request.headers['accept-charset'], available); +}; + +Negotiator.prototype.encoding = function encoding(available) { + var set = this.encodings(available); + return set && set[0]; +}; + +Negotiator.prototype.encodings = function encodings(available) { + return preferredEncodings(this.request.headers['accept-encoding'], available); +}; + +Negotiator.prototype.language = function language(available) { + var set = this.languages(available); + return set && set[0]; +}; + +Negotiator.prototype.languages = function languages(available) { + return preferredLanguages(this.request.headers['accept-language'], available); +}; + +Negotiator.prototype.mediaType = function mediaType(available) { + var set = this.mediaTypes(available); + return set && set[0]; +}; + +Negotiator.prototype.mediaTypes = function mediaTypes(available) { + return preferredMediaTypes(this.request.headers.accept, available); +}; + +// Backwards compatibility +Negotiator.prototype.preferredCharset = Negotiator.prototype.charset; +Negotiator.prototype.preferredCharsets = Negotiator.prototype.charsets; +Negotiator.prototype.preferredEncoding = Negotiator.prototype.encoding; +Negotiator.prototype.preferredEncodings = Negotiator.prototype.encodings; +Negotiator.prototype.preferredLanguage = Negotiator.prototype.language; +Negotiator.prototype.preferredLanguages = Negotiator.prototype.languages; +Negotiator.prototype.preferredMediaType = Negotiator.prototype.mediaType; +Negotiator.prototype.preferredMediaTypes = Negotiator.prototype.mediaTypes; diff --git a/backend/node_modules/negotiator/lib/charset.js b/backend/node_modules/negotiator/lib/charset.js new file mode 100644 index 0000000000000000000000000000000000000000..cdd014803474a4b76b981c475a32ebcaa81a36e5 --- /dev/null +++ b/backend/node_modules/negotiator/lib/charset.js @@ -0,0 +1,169 @@ +/** + * negotiator + * Copyright(c) 2012 Isaac Z. Schlueter + * Copyright(c) 2014 Federico Romero + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + * @public + */ + +module.exports = preferredCharsets; +module.exports.preferredCharsets = preferredCharsets; + +/** + * Module variables. + * @private + */ + +var simpleCharsetRegExp = /^\s*([^\s;]+)\s*(?:;(.*))?$/; + +/** + * Parse the Accept-Charset header. + * @private + */ + +function parseAcceptCharset(accept) { + var accepts = accept.split(','); + + for (var i = 0, j = 0; i < accepts.length; i++) { + var charset = parseCharset(accepts[i].trim(), i); + + if (charset) { + accepts[j++] = charset; + } + } + + // trim accepts + accepts.length = j; + + return accepts; +} + +/** + * Parse a charset from the Accept-Charset header. + * @private + */ + +function parseCharset(str, i) { + var match = simpleCharsetRegExp.exec(str); + if (!match) return null; + + var charset = match[1]; + var q = 1; + if (match[2]) { + var params = match[2].split(';') + for (var j = 0; j < params.length; j++) { + var p = params[j].trim().split('='); + if (p[0] === 'q') { + q = parseFloat(p[1]); + break; + } + } + } + + return { + charset: charset, + q: q, + i: i + }; +} + +/** + * Get the priority of a charset. + * @private + */ + +function getCharsetPriority(charset, accepted, index) { + var priority = {o: -1, q: 0, s: 0}; + + for (var i = 0; i < accepted.length; i++) { + var spec = specify(charset, accepted[i], index); + + if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { + priority = spec; + } + } + + return priority; +} + +/** + * Get the specificity of the charset. + * @private + */ + +function specify(charset, spec, index) { + var s = 0; + if(spec.charset.toLowerCase() === charset.toLowerCase()){ + s |= 1; + } else if (spec.charset !== '*' ) { + return null + } + + return { + i: index, + o: spec.i, + q: spec.q, + s: s + } +} + +/** + * Get the preferred charsets from an Accept-Charset header. + * @public + */ + +function preferredCharsets(accept, provided) { + // RFC 2616 sec 14.2: no header = * + var accepts = parseAcceptCharset(accept === undefined ? '*' : accept || ''); + + if (!provided) { + // sorted list of all charsets + return accepts + .filter(isQuality) + .sort(compareSpecs) + .map(getFullCharset); + } + + var priorities = provided.map(function getPriority(type, index) { + return getCharsetPriority(type, accepts, index); + }); + + // sorted list of accepted charsets + return priorities.filter(isQuality).sort(compareSpecs).map(function getCharset(priority) { + return provided[priorities.indexOf(priority)]; + }); +} + +/** + * Compare two specs. + * @private + */ + +function compareSpecs(a, b) { + return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; +} + +/** + * Get full charset string. + * @private + */ + +function getFullCharset(spec) { + return spec.charset; +} + +/** + * Check if a spec has any quality. + * @private + */ + +function isQuality(spec) { + return spec.q > 0; +} diff --git a/backend/node_modules/negotiator/lib/encoding.js b/backend/node_modules/negotiator/lib/encoding.js new file mode 100644 index 0000000000000000000000000000000000000000..8432cd77b8a96940b87d747dbb30ee9c2d065a31 --- /dev/null +++ b/backend/node_modules/negotiator/lib/encoding.js @@ -0,0 +1,184 @@ +/** + * negotiator + * Copyright(c) 2012 Isaac Z. Schlueter + * Copyright(c) 2014 Federico Romero + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + * @public + */ + +module.exports = preferredEncodings; +module.exports.preferredEncodings = preferredEncodings; + +/** + * Module variables. + * @private + */ + +var simpleEncodingRegExp = /^\s*([^\s;]+)\s*(?:;(.*))?$/; + +/** + * Parse the Accept-Encoding header. + * @private + */ + +function parseAcceptEncoding(accept) { + var accepts = accept.split(','); + var hasIdentity = false; + var minQuality = 1; + + for (var i = 0, j = 0; i < accepts.length; i++) { + var encoding = parseEncoding(accepts[i].trim(), i); + + if (encoding) { + accepts[j++] = encoding; + hasIdentity = hasIdentity || specify('identity', encoding); + minQuality = Math.min(minQuality, encoding.q || 1); + } + } + + if (!hasIdentity) { + /* + * If identity doesn't explicitly appear in the accept-encoding header, + * it's added to the list of acceptable encoding with the lowest q + */ + accepts[j++] = { + encoding: 'identity', + q: minQuality, + i: i + }; + } + + // trim accepts + accepts.length = j; + + return accepts; +} + +/** + * Parse an encoding from the Accept-Encoding header. + * @private + */ + +function parseEncoding(str, i) { + var match = simpleEncodingRegExp.exec(str); + if (!match) return null; + + var encoding = match[1]; + var q = 1; + if (match[2]) { + var params = match[2].split(';'); + for (var j = 0; j < params.length; j++) { + var p = params[j].trim().split('='); + if (p[0] === 'q') { + q = parseFloat(p[1]); + break; + } + } + } + + return { + encoding: encoding, + q: q, + i: i + }; +} + +/** + * Get the priority of an encoding. + * @private + */ + +function getEncodingPriority(encoding, accepted, index) { + var priority = {o: -1, q: 0, s: 0}; + + for (var i = 0; i < accepted.length; i++) { + var spec = specify(encoding, accepted[i], index); + + if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { + priority = spec; + } + } + + return priority; +} + +/** + * Get the specificity of the encoding. + * @private + */ + +function specify(encoding, spec, index) { + var s = 0; + if(spec.encoding.toLowerCase() === encoding.toLowerCase()){ + s |= 1; + } else if (spec.encoding !== '*' ) { + return null + } + + return { + i: index, + o: spec.i, + q: spec.q, + s: s + } +}; + +/** + * Get the preferred encodings from an Accept-Encoding header. + * @public + */ + +function preferredEncodings(accept, provided) { + var accepts = parseAcceptEncoding(accept || ''); + + if (!provided) { + // sorted list of all encodings + return accepts + .filter(isQuality) + .sort(compareSpecs) + .map(getFullEncoding); + } + + var priorities = provided.map(function getPriority(type, index) { + return getEncodingPriority(type, accepts, index); + }); + + // sorted list of accepted encodings + return priorities.filter(isQuality).sort(compareSpecs).map(function getEncoding(priority) { + return provided[priorities.indexOf(priority)]; + }); +} + +/** + * Compare two specs. + * @private + */ + +function compareSpecs(a, b) { + return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; +} + +/** + * Get full encoding string. + * @private + */ + +function getFullEncoding(spec) { + return spec.encoding; +} + +/** + * Check if a spec has any quality. + * @private + */ + +function isQuality(spec) { + return spec.q > 0; +} diff --git a/backend/node_modules/negotiator/lib/language.js b/backend/node_modules/negotiator/lib/language.js new file mode 100644 index 0000000000000000000000000000000000000000..a23167252719be841ad570eb655a703a4ae8fe9e --- /dev/null +++ b/backend/node_modules/negotiator/lib/language.js @@ -0,0 +1,179 @@ +/** + * negotiator + * Copyright(c) 2012 Isaac Z. Schlueter + * Copyright(c) 2014 Federico Romero + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + * @public + */ + +module.exports = preferredLanguages; +module.exports.preferredLanguages = preferredLanguages; + +/** + * Module variables. + * @private + */ + +var simpleLanguageRegExp = /^\s*([^\s\-;]+)(?:-([^\s;]+))?\s*(?:;(.*))?$/; + +/** + * Parse the Accept-Language header. + * @private + */ + +function parseAcceptLanguage(accept) { + var accepts = accept.split(','); + + for (var i = 0, j = 0; i < accepts.length; i++) { + var language = parseLanguage(accepts[i].trim(), i); + + if (language) { + accepts[j++] = language; + } + } + + // trim accepts + accepts.length = j; + + return accepts; +} + +/** + * Parse a language from the Accept-Language header. + * @private + */ + +function parseLanguage(str, i) { + var match = simpleLanguageRegExp.exec(str); + if (!match) return null; + + var prefix = match[1] + var suffix = match[2] + var full = prefix + + if (suffix) full += "-" + suffix; + + var q = 1; + if (match[3]) { + var params = match[3].split(';') + for (var j = 0; j < params.length; j++) { + var p = params[j].split('='); + if (p[0] === 'q') q = parseFloat(p[1]); + } + } + + return { + prefix: prefix, + suffix: suffix, + q: q, + i: i, + full: full + }; +} + +/** + * Get the priority of a language. + * @private + */ + +function getLanguagePriority(language, accepted, index) { + var priority = {o: -1, q: 0, s: 0}; + + for (var i = 0; i < accepted.length; i++) { + var spec = specify(language, accepted[i], index); + + if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { + priority = spec; + } + } + + return priority; +} + +/** + * Get the specificity of the language. + * @private + */ + +function specify(language, spec, index) { + var p = parseLanguage(language) + if (!p) return null; + var s = 0; + if(spec.full.toLowerCase() === p.full.toLowerCase()){ + s |= 4; + } else if (spec.prefix.toLowerCase() === p.full.toLowerCase()) { + s |= 2; + } else if (spec.full.toLowerCase() === p.prefix.toLowerCase()) { + s |= 1; + } else if (spec.full !== '*' ) { + return null + } + + return { + i: index, + o: spec.i, + q: spec.q, + s: s + } +}; + +/** + * Get the preferred languages from an Accept-Language header. + * @public + */ + +function preferredLanguages(accept, provided) { + // RFC 2616 sec 14.4: no header = * + var accepts = parseAcceptLanguage(accept === undefined ? '*' : accept || ''); + + if (!provided) { + // sorted list of all languages + return accepts + .filter(isQuality) + .sort(compareSpecs) + .map(getFullLanguage); + } + + var priorities = provided.map(function getPriority(type, index) { + return getLanguagePriority(type, accepts, index); + }); + + // sorted list of accepted languages + return priorities.filter(isQuality).sort(compareSpecs).map(function getLanguage(priority) { + return provided[priorities.indexOf(priority)]; + }); +} + +/** + * Compare two specs. + * @private + */ + +function compareSpecs(a, b) { + return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; +} + +/** + * Get full language string. + * @private + */ + +function getFullLanguage(spec) { + return spec.full; +} + +/** + * Check if a spec has any quality. + * @private + */ + +function isQuality(spec) { + return spec.q > 0; +} diff --git a/backend/node_modules/negotiator/lib/mediaType.js b/backend/node_modules/negotiator/lib/mediaType.js new file mode 100644 index 0000000000000000000000000000000000000000..67309dd75f1b62cfe90bfa622919fdae8b80bc0b --- /dev/null +++ b/backend/node_modules/negotiator/lib/mediaType.js @@ -0,0 +1,294 @@ +/** + * negotiator + * Copyright(c) 2012 Isaac Z. Schlueter + * Copyright(c) 2014 Federico Romero + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + * @public + */ + +module.exports = preferredMediaTypes; +module.exports.preferredMediaTypes = preferredMediaTypes; + +/** + * Module variables. + * @private + */ + +var simpleMediaTypeRegExp = /^\s*([^\s\/;]+)\/([^;\s]+)\s*(?:;(.*))?$/; + +/** + * Parse the Accept header. + * @private + */ + +function parseAccept(accept) { + var accepts = splitMediaTypes(accept); + + for (var i = 0, j = 0; i < accepts.length; i++) { + var mediaType = parseMediaType(accepts[i].trim(), i); + + if (mediaType) { + accepts[j++] = mediaType; + } + } + + // trim accepts + accepts.length = j; + + return accepts; +} + +/** + * Parse a media type from the Accept header. + * @private + */ + +function parseMediaType(str, i) { + var match = simpleMediaTypeRegExp.exec(str); + if (!match) return null; + + var params = Object.create(null); + var q = 1; + var subtype = match[2]; + var type = match[1]; + + if (match[3]) { + var kvps = splitParameters(match[3]).map(splitKeyValuePair); + + for (var j = 0; j < kvps.length; j++) { + var pair = kvps[j]; + var key = pair[0].toLowerCase(); + var val = pair[1]; + + // get the value, unwrapping quotes + var value = val && val[0] === '"' && val[val.length - 1] === '"' + ? val.substr(1, val.length - 2) + : val; + + if (key === 'q') { + q = parseFloat(value); + break; + } + + // store parameter + params[key] = value; + } + } + + return { + type: type, + subtype: subtype, + params: params, + q: q, + i: i + }; +} + +/** + * Get the priority of a media type. + * @private + */ + +function getMediaTypePriority(type, accepted, index) { + var priority = {o: -1, q: 0, s: 0}; + + for (var i = 0; i < accepted.length; i++) { + var spec = specify(type, accepted[i], index); + + if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { + priority = spec; + } + } + + return priority; +} + +/** + * Get the specificity of the media type. + * @private + */ + +function specify(type, spec, index) { + var p = parseMediaType(type); + var s = 0; + + if (!p) { + return null; + } + + if(spec.type.toLowerCase() == p.type.toLowerCase()) { + s |= 4 + } else if(spec.type != '*') { + return null; + } + + if(spec.subtype.toLowerCase() == p.subtype.toLowerCase()) { + s |= 2 + } else if(spec.subtype != '*') { + return null; + } + + var keys = Object.keys(spec.params); + if (keys.length > 0) { + if (keys.every(function (k) { + return spec.params[k] == '*' || (spec.params[k] || '').toLowerCase() == (p.params[k] || '').toLowerCase(); + })) { + s |= 1 + } else { + return null + } + } + + return { + i: index, + o: spec.i, + q: spec.q, + s: s, + } +} + +/** + * Get the preferred media types from an Accept header. + * @public + */ + +function preferredMediaTypes(accept, provided) { + // RFC 2616 sec 14.2: no header = */* + var accepts = parseAccept(accept === undefined ? '*/*' : accept || ''); + + if (!provided) { + // sorted list of all types + return accepts + .filter(isQuality) + .sort(compareSpecs) + .map(getFullType); + } + + var priorities = provided.map(function getPriority(type, index) { + return getMediaTypePriority(type, accepts, index); + }); + + // sorted list of accepted types + return priorities.filter(isQuality).sort(compareSpecs).map(function getType(priority) { + return provided[priorities.indexOf(priority)]; + }); +} + +/** + * Compare two specs. + * @private + */ + +function compareSpecs(a, b) { + return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; +} + +/** + * Get full type string. + * @private + */ + +function getFullType(spec) { + return spec.type + '/' + spec.subtype; +} + +/** + * Check if a spec has any quality. + * @private + */ + +function isQuality(spec) { + return spec.q > 0; +} + +/** + * Count the number of quotes in a string. + * @private + */ + +function quoteCount(string) { + var count = 0; + var index = 0; + + while ((index = string.indexOf('"', index)) !== -1) { + count++; + index++; + } + + return count; +} + +/** + * Split a key value pair. + * @private + */ + +function splitKeyValuePair(str) { + var index = str.indexOf('='); + var key; + var val; + + if (index === -1) { + key = str; + } else { + key = str.substr(0, index); + val = str.substr(index + 1); + } + + return [key, val]; +} + +/** + * Split an Accept header into media types. + * @private + */ + +function splitMediaTypes(accept) { + var accepts = accept.split(','); + + for (var i = 1, j = 0; i < accepts.length; i++) { + if (quoteCount(accepts[j]) % 2 == 0) { + accepts[++j] = accepts[i]; + } else { + accepts[j] += ',' + accepts[i]; + } + } + + // trim accepts + accepts.length = j + 1; + + return accepts; +} + +/** + * Split a string of parameters. + * @private + */ + +function splitParameters(str) { + var parameters = str.split(';'); + + for (var i = 1, j = 0; i < parameters.length; i++) { + if (quoteCount(parameters[j]) % 2 == 0) { + parameters[++j] = parameters[i]; + } else { + parameters[j] += ';' + parameters[i]; + } + } + + // trim parameters + parameters.length = j + 1; + + for (var i = 0; i < parameters.length; i++) { + parameters[i] = parameters[i].trim(); + } + + return parameters; +} diff --git a/backend/node_modules/negotiator/package.json b/backend/node_modules/negotiator/package.json new file mode 100644 index 0000000000000000000000000000000000000000..297635f6d34177956186df7c6a7e502ebb576da2 --- /dev/null +++ b/backend/node_modules/negotiator/package.json @@ -0,0 +1,42 @@ +{ + "name": "negotiator", + "description": "HTTP content negotiation", + "version": "0.6.3", + "contributors": [ + "Douglas Christopher Wilson ", + "Federico Romero ", + "Isaac Z. Schlueter (http://blog.izs.me/)" + ], + "license": "MIT", + "keywords": [ + "http", + "content negotiation", + "accept", + "accept-language", + "accept-encoding", + "accept-charset" + ], + "repository": "jshttp/negotiator", + "devDependencies": { + "eslint": "7.32.0", + "eslint-plugin-markdown": "2.2.1", + "mocha": "9.1.3", + "nyc": "15.1.0" + }, + "files": [ + "lib/", + "HISTORY.md", + "LICENSE", + "index.js", + "README.md" + ], + "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" + } +} diff --git a/backend/node_modules/node-domexception/.history/README_20210527203617.md b/backend/node_modules/node-domexception/.history/README_20210527203617.md new file mode 100644 index 0000000000000000000000000000000000000000..38d8f85613989fa44d37fb74e7cf37319de66c2e --- /dev/null +++ b/backend/node_modules/node-domexception/.history/README_20210527203617.md @@ -0,0 +1,2 @@ +# node-domexception +An implementation of the DOMException class from NodeJS diff --git a/backend/node_modules/node-domexception/.history/README_20210527212714.md b/backend/node_modules/node-domexception/.history/README_20210527212714.md new file mode 100644 index 0000000000000000000000000000000000000000..eed1d13bedf96b2fe4cb33d7896b482f968db30d --- /dev/null +++ b/backend/node_modules/node-domexception/.history/README_20210527212714.md @@ -0,0 +1,41 @@ +# DOMException +An implementation of the DOMException class from NodeJS + +This package implements the [`DOMException`](https://developer.mozilla.org/en-US/docs/Web/API/DOMException) class, from NodeJS itself. +NodeJS has DOMException built in, but it's not globally available, and you can't require/import it from somewhere. + +The only possible way is to use some web-ish tools that have been introduced into NodeJS that throws an error and catch the constructor. +This way you will have the same class that NodeJS has and you can check if the error is a instance of DOMException. +The instanceof check would not have worked with a custom class such as the DOMexception provided by domenic which also is much larger in size. + +```js +import DOMException from 'node-domexception' + +hello().catch(err => { + if (err instanceof DOMException) { + ... + } +}) + +const e1 = new DOMException("Something went wrong", "BadThingsError"); +console.assert(e1.name === "BadThingsError"); +console.assert(e1.code === 0); + +const e2 = new DOMException("Another exciting error message", "NoModificationAllowedError"); +console.assert(e2.name === "NoModificationAllowedError"); +console.assert(e2.code === 7); + +console.assert(DOMException.INUSE_ATTRIBUTE_ERR === 10); +``` + +## APIs + +This package exposes two flavors of the `DOMException` interface depending on the imported module. + +### `domexception` module + +This module default-exports the `DOMException` interface constructor. + +### `domexception/webidl2js-wrapper` module + +This module exports the `DOMException` [interface wrapper API](https://github.com/jsdom/webidl2js#for-interfaces) generated by [webidl2js](https://github.com/jsdom/webidl2js). diff --git a/backend/node_modules/node-domexception/.history/README_20210527213345.md b/backend/node_modules/node-domexception/.history/README_20210527213345.md new file mode 100644 index 0000000000000000000000000000000000000000..582541679b782bf3958fca1a47159addb78d177a --- /dev/null +++ b/backend/node_modules/node-domexception/.history/README_20210527213345.md @@ -0,0 +1,36 @@ +# DOMException +An implementation of the DOMException class from NodeJS + +This package implements the [`DOMException`](https://developer.mozilla.org/en-US/docs/Web/API/DOMException) class, from NodeJS itself. (including the legacy codes) +NodeJS has DOMException built in, but it's not globally available, and you can't require/import it from somewhere. + +The only possible way is to use some web-ish tools that have been introduced into NodeJS that throws an error and catch the constructor. +This way you will have the same class that NodeJS has and you can check if the error is a instance of DOMException. +The instanceof check would not have worked with a custom class such as the DOMException provided by domenic which also is much larger in size. + +```js +import DOMException from 'node-domexception' +import { MessageChannel } from 'worker_threads' + +async function hello() { + const port = new MessageChannel().port1 + const ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) +} + +hello().catch(err => { + console.assert(err.name === 'DataCloneError') + console.assert(err.code === 25) + console.assert(err instanceof DOMException) +}) + +const e1 = new DOMException('Something went wrong', 'BadThingsError') +console.assert(e1.name === 'BadThingsError') +console.assert(e1.code === 0) + +const e2 = new DOMException('Another exciting error message', 'NoModificationAllowedError') +console.assert(e2.name === 'NoModificationAllowedError') +console.assert(e2.code === 7) + +console.assert(DOMException.INUSE_ATTRIBUTE_ERR === 10) +``` diff --git a/backend/node_modules/node-domexception/.history/README_20210527213411.md b/backend/node_modules/node-domexception/.history/README_20210527213411.md new file mode 100644 index 0000000000000000000000000000000000000000..4c21ec8fda5c5fb82ba15d47d55a58405ac5a44e --- /dev/null +++ b/backend/node_modules/node-domexception/.history/README_20210527213411.md @@ -0,0 +1,36 @@ +# DOMException +An implementation of the DOMException class from NodeJS + +This package implements the [`DOMException`](https://developer.mozilla.org/en-US/docs/Web/API/DOMException) class that comes from NodeJS itself. (including the legacy codes) +NodeJS has DOMException built in, but it's not globally available, and you can't require/import it from somewhere. + +The only possible way is to use some web-ish tools that have been introduced into NodeJS that throws an error and catch the constructor. +This way you will have the same class that NodeJS has and you can check if the error is a instance of DOMException. +The instanceof check would not have worked with a custom class such as the DOMException provided by domenic which also is much larger in size. + +```js +import DOMException from 'node-domexception' +import { MessageChannel } from 'worker_threads' + +async function hello() { + const port = new MessageChannel().port1 + const ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) +} + +hello().catch(err => { + console.assert(err.name === 'DataCloneError') + console.assert(err.code === 25) + console.assert(err instanceof DOMException) +}) + +const e1 = new DOMException('Something went wrong', 'BadThingsError') +console.assert(e1.name === 'BadThingsError') +console.assert(e1.code === 0) + +const e2 = new DOMException('Another exciting error message', 'NoModificationAllowedError') +console.assert(e2.name === 'NoModificationAllowedError') +console.assert(e2.code === 7) + +console.assert(DOMException.INUSE_ATTRIBUTE_ERR === 10) +``` diff --git a/backend/node_modules/node-domexception/.history/README_20210527213803.md b/backend/node_modules/node-domexception/.history/README_20210527213803.md new file mode 100644 index 0000000000000000000000000000000000000000..4cb85717f9560c558c407456d065789d85ca30a7 --- /dev/null +++ b/backend/node_modules/node-domexception/.history/README_20210527213803.md @@ -0,0 +1,36 @@ +# DOMException +An implementation of the DOMException class from NodeJS + +This package exposes the [`DOMException`](https://developer.mozilla.org/en-US/docs/Web/API/DOMException) class that comes from NodeJS itself. (including all of the deprecated legacy codes) +NodeJS has it built in, but it's not globally available, and you can't require/import it from somewhere. + +The only possible way is to use some web-ish tools that have been introduced into NodeJS that throws an error and catch the constructor. +This way you will have the same class that NodeJS has and you can check if the error is a instance of DOMException. +The instanceof check would not have worked with a custom class such as the DOMException provided by domenic which also is much larger in size since it has to re-construct the hole class from the ground up. + +```js +import DOMException from 'node-domexception' +import { MessageChannel } from 'worker_threads' + +async function hello() { + const port = new MessageChannel().port1 + const ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) +} + +hello().catch(err => { + console.assert(err.name === 'DataCloneError') + console.assert(err.code === 25) + console.assert(err instanceof DOMException) +}) + +const e1 = new DOMException('Something went wrong', 'BadThingsError') +console.assert(e1.name === 'BadThingsError') +console.assert(e1.code === 0) + +const e2 = new DOMException('Another exciting error message', 'NoModificationAllowedError') +console.assert(e2.name === 'NoModificationAllowedError') +console.assert(e2.code === 7) + +console.assert(DOMException.INUSE_ATTRIBUTE_ERR === 10) +``` diff --git a/backend/node_modules/node-domexception/.history/README_20210527214323.md b/backend/node_modules/node-domexception/.history/README_20210527214323.md new file mode 100644 index 0000000000000000000000000000000000000000..a32a91b167dbbedfdf34e456cd067ce0ef382752 --- /dev/null +++ b/backend/node_modules/node-domexception/.history/README_20210527214323.md @@ -0,0 +1,38 @@ +# DOMException +An implementation of the DOMException class from NodeJS + +This package exposes the [`DOMException`](https://developer.mozilla.org/en-US/docs/Web/API/DOMException) class that comes from NodeJS itself. (including all of the deprecated legacy codes) +NodeJS has it built in, but it's not globally available, and you can't require/import it from somewhere. + +The only possible way is to use some web-ish tools that have been introduced into NodeJS that throws an error and catch the constructor. +This way you will have the same class that NodeJS has and you can check if the error is a instance of DOMException. +The instanceof check would not have worked with a custom class such as the DOMException provided by domenic which also is much larger in size since it has to re-construct the hole class from the ground up. + +(plz don't depend on this package in any other environment other than node >=10.5) + +```js +import DOMException from 'node-domexception' +import { MessageChannel } from 'worker_threads' + +async function hello() { + const port = new MessageChannel().port1 + const ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) +} + +hello().catch(err => { + console.assert(err.name === 'DataCloneError') + console.assert(err.code === 25) + console.assert(err instanceof DOMException) +}) + +const e1 = new DOMException('Something went wrong', 'BadThingsError') +console.assert(e1.name === 'BadThingsError') +console.assert(e1.code === 0) + +const e2 = new DOMException('Another exciting error message', 'NoModificationAllowedError') +console.assert(e2.name === 'NoModificationAllowedError') +console.assert(e2.code === 7) + +console.assert(DOMException.INUSE_ATTRIBUTE_ERR === 10) +``` diff --git a/backend/node_modules/node-domexception/.history/README_20210527214408.md b/backend/node_modules/node-domexception/.history/README_20210527214408.md new file mode 100644 index 0000000000000000000000000000000000000000..a32a91b167dbbedfdf34e456cd067ce0ef382752 --- /dev/null +++ b/backend/node_modules/node-domexception/.history/README_20210527214408.md @@ -0,0 +1,38 @@ +# DOMException +An implementation of the DOMException class from NodeJS + +This package exposes the [`DOMException`](https://developer.mozilla.org/en-US/docs/Web/API/DOMException) class that comes from NodeJS itself. (including all of the deprecated legacy codes) +NodeJS has it built in, but it's not globally available, and you can't require/import it from somewhere. + +The only possible way is to use some web-ish tools that have been introduced into NodeJS that throws an error and catch the constructor. +This way you will have the same class that NodeJS has and you can check if the error is a instance of DOMException. +The instanceof check would not have worked with a custom class such as the DOMException provided by domenic which also is much larger in size since it has to re-construct the hole class from the ground up. + +(plz don't depend on this package in any other environment other than node >=10.5) + +```js +import DOMException from 'node-domexception' +import { MessageChannel } from 'worker_threads' + +async function hello() { + const port = new MessageChannel().port1 + const ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) +} + +hello().catch(err => { + console.assert(err.name === 'DataCloneError') + console.assert(err.code === 25) + console.assert(err instanceof DOMException) +}) + +const e1 = new DOMException('Something went wrong', 'BadThingsError') +console.assert(e1.name === 'BadThingsError') +console.assert(e1.code === 0) + +const e2 = new DOMException('Another exciting error message', 'NoModificationAllowedError') +console.assert(e2.name === 'NoModificationAllowedError') +console.assert(e2.code === 7) + +console.assert(DOMException.INUSE_ATTRIBUTE_ERR === 10) +``` diff --git a/backend/node_modules/node-domexception/.history/index_20210527203842.js b/backend/node_modules/node-domexception/.history/index_20210527203842.js new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/backend/node_modules/node-domexception/.history/index_20210527203947.js b/backend/node_modules/node-domexception/.history/index_20210527203947.js new file mode 100644 index 0000000000000000000000000000000000000000..b9a8b76546b41219c619e9c0bff9cedface179a1 --- /dev/null +++ b/backend/node_modules/node-domexception/.history/index_20210527203947.js @@ -0,0 +1,8 @@ +const { MessageChannel } = require('worker_threads') + +if (!globalThis.DOMException) { + const port = new MessageChannel().port1 + const ab = new ArrayBuffer() + try { port.postMessage(ab, [ab, ab]) } + catch (err) { globalThis.DOMException = err.constructor } +} diff --git a/backend/node_modules/node-domexception/.history/index_20210527204259.js b/backend/node_modules/node-domexception/.history/index_20210527204259.js new file mode 100644 index 0000000000000000000000000000000000000000..e9332a8d0f3f6ef2993c5330a7f29654b0d1df12 --- /dev/null +++ b/backend/node_modules/node-domexception/.history/index_20210527204259.js @@ -0,0 +1,9 @@ +if (!globalThis.DOMException) { + const { MessageChannel } = require('worker_threads') + const port = new MessageChannel().port1 + const ab = new ArrayBuffer() + try { port.postMessage(ab, [ab, ab]) } + catch (err) { globalThis.DOMException = err.constructor } +} + +module.exports diff --git a/backend/node_modules/node-domexception/.history/index_20210527204418.js b/backend/node_modules/node-domexception/.history/index_20210527204418.js new file mode 100644 index 0000000000000000000000000000000000000000..cb362cc78a5692c309dd3f8f25a14b1b15356889 --- /dev/null +++ b/backend/node_modules/node-domexception/.history/index_20210527204418.js @@ -0,0 +1,9 @@ +if (!globalThis.DOMException) { + const { MessageChannel } = require('worker_threads') + const port = new MessageChannel().port1 + const ab = new ArrayBuffer() + try { port.postMessage(ab, [ab, ab]) } + catch (err) { globalThis.DOMException = err.constructor } +} + +module.exports = globalThis.DOMException diff --git a/backend/node_modules/node-domexception/.history/index_20210527204756.js b/backend/node_modules/node-domexception/.history/index_20210527204756.js new file mode 100644 index 0000000000000000000000000000000000000000..87d26554fc7b990d796fabbe89fa004a776dfed7 --- /dev/null +++ b/backend/node_modules/node-domexception/.history/index_20210527204756.js @@ -0,0 +1,11 @@ +/*! blob-to-buffer. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + const { MessageChannel } = require('worker_threads') + const port = new MessageChannel().port1 + const ab = new ArrayBuffer() + try { port.postMessage(ab, [ab, ab]) } + catch (err) { globalThis.DOMException = err.constructor } +} + +module.exports = globalThis.DOMException diff --git a/backend/node_modules/node-domexception/.history/index_20210527204833.js b/backend/node_modules/node-domexception/.history/index_20210527204833.js new file mode 100644 index 0000000000000000000000000000000000000000..837ebdad0b596caea502a4562725e147d5dd4165 --- /dev/null +++ b/backend/node_modules/node-domexception/.history/index_20210527204833.js @@ -0,0 +1,11 @@ +/*! blob-to-buffer. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + const { MessageChannel } = require('worker_threads') + const port = new MessageChannel().port1 + const ab = new ArrayBuffer() + try { port.postMessage(ab, [ab, ab]) } + catch (err) { globalThis.DOMException = err.constructor } +} + +module.exports = globalThis.DOMException diff --git a/backend/node_modules/node-domexception/.history/index_20210527211208.js b/backend/node_modules/node-domexception/.history/index_20210527211208.js new file mode 100644 index 0000000000000000000000000000000000000000..ba215ce862287f4deeddcc3dcb4dde287e24af21 --- /dev/null +++ b/backend/node_modules/node-domexception/.history/index_20210527211208.js @@ -0,0 +1,15 @@ +/*! blob-to-buffer. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + var { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + try { port.postMessage(ab, [ab, ab]) } + catch (err) { + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException diff --git a/backend/node_modules/node-domexception/.history/index_20210527211248.js b/backend/node_modules/node-domexception/.history/index_20210527211248.js new file mode 100644 index 0000000000000000000000000000000000000000..f5c434eec0df083379e14b16bd4550af0dc81352 --- /dev/null +++ b/backend/node_modules/node-domexception/.history/index_20210527211248.js @@ -0,0 +1,15 @@ +/*! blob-to-buffer. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + const { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + try { port.postMessage(ab, [ab, ab]) } + catch (err) { + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException diff --git a/backend/node_modules/node-domexception/.history/index_20210527212722.js b/backend/node_modules/node-domexception/.history/index_20210527212722.js new file mode 100644 index 0000000000000000000000000000000000000000..91b3b526aa6ca35d8d5a66fefbc0cace4e161e05 --- /dev/null +++ b/backend/node_modules/node-domexception/.history/index_20210527212722.js @@ -0,0 +1,23 @@ +/*! blob-to-buffer. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + const { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + try { port.postMessage(ab, [ab, ab]) } + catch (err) { + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException + +const e1 = new DOMException("Something went wrong", "BadThingsError"); +console.assert(e1.name === "BadThingsError"); +console.assert(e1.code === 0); + +const e2 = new DOMException("Another exciting error message", "NoModificationAllowedError"); +console.assert(e2.name === "NoModificationAllowedError"); +console.assert(e2.code === 7); diff --git a/backend/node_modules/node-domexception/.history/index_20210527212731.js b/backend/node_modules/node-domexception/.history/index_20210527212731.js new file mode 100644 index 0000000000000000000000000000000000000000..cf2886438492c636eed949b44d31c48a5d441840 --- /dev/null +++ b/backend/node_modules/node-domexception/.history/index_20210527212731.js @@ -0,0 +1,23 @@ +/*! blob-to-buffer. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + const { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + try { port.postMessage(ab, [ab, ab]) } + catch (err) { + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException + +const e1 = new DOMException("Something went wrong", "BadThingsError"); +console.assert(e1.name === "BadThingsError"); +console.assert(e1.code === 0); + +const e2 = new DOMException("Another exciting error message", "NoModificationAllowedError"); +console.assert(e2.name === "NoModificationAllowedError"); +console.assert(e2.code === 2); diff --git a/backend/node_modules/node-domexception/.history/index_20210527212746.js b/backend/node_modules/node-domexception/.history/index_20210527212746.js new file mode 100644 index 0000000000000000000000000000000000000000..f5c434eec0df083379e14b16bd4550af0dc81352 --- /dev/null +++ b/backend/node_modules/node-domexception/.history/index_20210527212746.js @@ -0,0 +1,15 @@ +/*! blob-to-buffer. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + const { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + try { port.postMessage(ab, [ab, ab]) } + catch (err) { + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException diff --git a/backend/node_modules/node-domexception/.history/index_20210527212900.js b/backend/node_modules/node-domexception/.history/index_20210527212900.js new file mode 100644 index 0000000000000000000000000000000000000000..efa2442c0d2d89ad42afb8f36a1072ed8fc18aaf --- /dev/null +++ b/backend/node_modules/node-domexception/.history/index_20210527212900.js @@ -0,0 +1,16 @@ +/*! blob-to-buffer. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + const { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + try { port.postMessage(ab, [ab, ab]) } + catch (err) { + console.log(err.code) + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException diff --git a/backend/node_modules/node-domexception/.history/index_20210527213022.js b/backend/node_modules/node-domexception/.history/index_20210527213022.js new file mode 100644 index 0000000000000000000000000000000000000000..e59f047bd461a4c0d7a221cfd16ac662c11cffb5 --- /dev/null +++ b/backend/node_modules/node-domexception/.history/index_20210527213022.js @@ -0,0 +1,16 @@ +/*! blob-to-buffer. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + const { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + try { port.postMessage(ab, [ab, ab]) } + catch (err) { + console.log(err.code, err.name, err.message) + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException diff --git a/backend/node_modules/node-domexception/.history/index_20210527213822.js b/backend/node_modules/node-domexception/.history/index_20210527213822.js new file mode 100644 index 0000000000000000000000000000000000000000..7f4e13dcc5d41a85052a6d46ce989adcc8ec074f --- /dev/null +++ b/backend/node_modules/node-domexception/.history/index_20210527213822.js @@ -0,0 +1,16 @@ +/*! node-DOMException. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + const { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + try { port.postMessage(ab, [ab, ab]) } + catch (err) { + console.log(err.code, err.name, err.message) + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException diff --git a/backend/node_modules/node-domexception/.history/index_20210527213843.js b/backend/node_modules/node-domexception/.history/index_20210527213843.js new file mode 100644 index 0000000000000000000000000000000000000000..ee75b730d0afe7e77474fae0ac178ba533297d21 --- /dev/null +++ b/backend/node_modules/node-domexception/.history/index_20210527213843.js @@ -0,0 +1,17 @@ +/*! node-DOMException. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + try { + const { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) + catch (err) { + console.log(err.code, err.name, err.message) + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException diff --git a/backend/node_modules/node-domexception/.history/index_20210527213852.js b/backend/node_modules/node-domexception/.history/index_20210527213852.js new file mode 100644 index 0000000000000000000000000000000000000000..a82bee3a339925a2db2a39d26399e0c0decc07b8 --- /dev/null +++ b/backend/node_modules/node-domexception/.history/index_20210527213852.js @@ -0,0 +1,17 @@ +/*! node-DOMException. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + try { + const { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) + } catch (err) { + console.log(err.code, err.name, err.message) + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException diff --git a/backend/node_modules/node-domexception/.history/index_20210527213910.js b/backend/node_modules/node-domexception/.history/index_20210527213910.js new file mode 100644 index 0000000000000000000000000000000000000000..1e1ca29b1cf39eea3b0e2e9a179220679d5664fc --- /dev/null +++ b/backend/node_modules/node-domexception/.history/index_20210527213910.js @@ -0,0 +1,16 @@ +/*! node-DOMException. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + try { + const { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) + } catch (err) { + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException diff --git a/backend/node_modules/node-domexception/.history/index_20210527214034.js b/backend/node_modules/node-domexception/.history/index_20210527214034.js new file mode 100644 index 0000000000000000000000000000000000000000..b7bbe951938adfde643d88ea8da70c414c0b362e --- /dev/null +++ b/backend/node_modules/node-domexception/.history/index_20210527214034.js @@ -0,0 +1,16 @@ +/*! node-domexception. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + try { + const { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) + } catch (err) { + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException diff --git a/backend/node_modules/node-domexception/.history/index_20210527214643.js b/backend/node_modules/node-domexception/.history/index_20210527214643.js new file mode 100644 index 0000000000000000000000000000000000000000..92ed8477b307bbd541f3fb2c7588de5d37d54537 --- /dev/null +++ b/backend/node_modules/node-domexception/.history/index_20210527214643.js @@ -0,0 +1,41 @@ +/*! node-domexception. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + try { + const { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) + } catch (err) { + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException + + +const { MessageChannel } = require('worker_threads') + +async function hello() { + const port = new MessageChannel().port1 + const ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) +} + +hello().catch(err => { + console.assert(err.name === 'DataCloneError') + console.assert(err.code === 25) + console.assert(err instanceof DOMException) +}) + +const e1 = new DOMException('Something went wrong', 'BadThingsError') +console.assert(e1.name === 'BadThingsError') +console.assert(e1.code === 0) + +const e2 = new DOMException('Another exciting error message', 'NoModificationAllowedError') +console.assert(e2.name === 'NoModificationAllowedError') +console.assert(e2.code === 7) + +console.assert(DOMException.INUSE_ATTRIBUTE_ERR === 10) diff --git a/backend/node_modules/node-domexception/.history/index_20210527214654.js b/backend/node_modules/node-domexception/.history/index_20210527214654.js new file mode 100644 index 0000000000000000000000000000000000000000..6d5cb8e5b477c205fcb17ef5d91639e311873fcf --- /dev/null +++ b/backend/node_modules/node-domexception/.history/index_20210527214654.js @@ -0,0 +1,41 @@ +/*! node-domexception. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + try { + const { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) + } catch (err) { + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException + + +const { MessageChannel } = require('worker_threads') + +async function hello() { + const port = new MessageChannel().port1 + const ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) +} + +hello().catch(err => { + console.assert(err.name === 'DataCloneError') + console.assert(err.code === 21) + console.assert(err instanceof DOMException) +}) + +const e1 = new DOMException('Something went wrong', 'BadThingsError') +console.assert(e1.name === 'BadThingsError') +console.assert(e1.code === 0) + +const e2 = new DOMException('Another exciting error message', 'NoModificationAllowedError') +console.assert(e2.name === 'NoModificationAllowedError') +console.assert(e2.code === 7) + +console.assert(DOMException.INUSE_ATTRIBUTE_ERR === 10) diff --git a/backend/node_modules/node-domexception/.history/index_20210527214700.js b/backend/node_modules/node-domexception/.history/index_20210527214700.js new file mode 100644 index 0000000000000000000000000000000000000000..b7bbe951938adfde643d88ea8da70c414c0b362e --- /dev/null +++ b/backend/node_modules/node-domexception/.history/index_20210527214700.js @@ -0,0 +1,16 @@ +/*! node-domexception. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + try { + const { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) + } catch (err) { + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException diff --git a/backend/node_modules/node-domexception/.history/package_20210527203733.json b/backend/node_modules/node-domexception/.history/package_20210527203733.json new file mode 100644 index 0000000000000000000000000000000000000000..5eeb306d2a21ce5854a78ac329ab422b0c2b7524 --- /dev/null +++ b/backend/node_modules/node-domexception/.history/package_20210527203733.json @@ -0,0 +1,19 @@ +{ + "name": "domexception", + "version": "1.0.0", + "description": "An implementation of the DOMException class from NodeJS", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/jimmywarting/node-domexception.git" + }, + "author": "", + "license": "ISC", + "bugs": { + "url": "https://github.com/jimmywarting/node-domexception/issues" + }, + "homepage": "https://github.com/jimmywarting/node-domexception#readme" +} diff --git a/backend/node_modules/node-domexception/.history/package_20210527203825.json b/backend/node_modules/node-domexception/.history/package_20210527203825.json new file mode 100644 index 0000000000000000000000000000000000000000..4ca171350a4aebc837955c0a7e18bfc9c39bf9c5 --- /dev/null +++ b/backend/node_modules/node-domexception/.history/package_20210527203825.json @@ -0,0 +1,16 @@ +{ + "name": "node-domexception", + "version": "1.0.0", + "description": "An implementation of the DOMException class from NodeJS", + "main": "index.js", + "repository": { + "type": "git", + "url": "git+https://github.com/jimmywarting/node-domexception.git" + }, + "author": "Jimmy Wärting", + "license": "MIT", + "bugs": { + "url": "https://github.com/jimmywarting/node-domexception/issues" + }, + "homepage": "https://github.com/jimmywarting/node-domexception#readme" +} diff --git a/backend/node_modules/node-domexception/.history/package_20210527204621.json b/backend/node_modules/node-domexception/.history/package_20210527204621.json new file mode 100644 index 0000000000000000000000000000000000000000..3c414e93c3201ff6a786005d7538dab80ed53beb --- /dev/null +++ b/backend/node_modules/node-domexception/.history/package_20210527204621.json @@ -0,0 +1,19 @@ +{ + "name": "node-domexception", + "version": "1.0.0", + "description": "An implementation of the DOMException class from NodeJS", + "main": "index.js", + "repository": { + "type": "git", + "url": "git+https://github.com/jimmywarting/node-domexception.git" + }, + "engines": { + "node": ">=10.5.0" + }, + "author": "Jimmy Wärting", + "license": "MIT", + "bugs": { + "url": "https://github.com/jimmywarting/node-domexception/issues" + }, + "homepage": "https://github.com/jimmywarting/node-domexception#readme" +} diff --git a/backend/node_modules/node-domexception/.history/package_20210527204913.json b/backend/node_modules/node-domexception/.history/package_20210527204913.json new file mode 100644 index 0000000000000000000000000000000000000000..dbbb5d2429ff41c42178bb3fb2c5a5b3eee1d5b7 --- /dev/null +++ b/backend/node_modules/node-domexception/.history/package_20210527204913.json @@ -0,0 +1,25 @@ +{ + "name": "node-domexception", + "version": "1.0.0", + "description": "An implementation of the DOMException class from NodeJS", + "main": "index.js", + "repository": { + "type": "git", + "url": "git+https://github.com/jimmywarting/node-domexception.git" + }, + "engines": { + "node": ">=10.5.0" + }, + "author": "Jimmy Wärting", + "license": "MIT", + "bugs": { + "url": "https://github.com/jimmywarting/node-domexception/issues" + }, + "homepage": "https://github.com/jimmywarting/node-domexception#readme", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + } + ] +} diff --git a/backend/node_modules/node-domexception/.history/package_20210527204925.json b/backend/node_modules/node-domexception/.history/package_20210527204925.json new file mode 100644 index 0000000000000000000000000000000000000000..dbbb5d2429ff41c42178bb3fb2c5a5b3eee1d5b7 --- /dev/null +++ b/backend/node_modules/node-domexception/.history/package_20210527204925.json @@ -0,0 +1,25 @@ +{ + "name": "node-domexception", + "version": "1.0.0", + "description": "An implementation of the DOMException class from NodeJS", + "main": "index.js", + "repository": { + "type": "git", + "url": "git+https://github.com/jimmywarting/node-domexception.git" + }, + "engines": { + "node": ">=10.5.0" + }, + "author": "Jimmy Wärting", + "license": "MIT", + "bugs": { + "url": "https://github.com/jimmywarting/node-domexception/issues" + }, + "homepage": "https://github.com/jimmywarting/node-domexception#readme", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + } + ] +} diff --git a/backend/node_modules/node-domexception/.history/package_20210527205145.json b/backend/node_modules/node-domexception/.history/package_20210527205145.json new file mode 100644 index 0000000000000000000000000000000000000000..cd08e704ea2957b835964f467ad62b59d6f5c158 --- /dev/null +++ b/backend/node_modules/node-domexception/.history/package_20210527205145.json @@ -0,0 +1,29 @@ +{ + "name": "node-domexception", + "version": "1.0.0", + "description": "An implementation of the DOMException class from NodeJS", + "main": "index.js", + "repository": { + "type": "git", + "url": "git+https://github.com/jimmywarting/node-domexception.git" + }, + "engines": { + "node": ">=10.5.0" + }, + "author": "Jimmy Wärting", + "license": "MIT", + "bugs": { + "url": "https://github.com/jimmywarting/node-domexception/issues" + }, + "homepage": "https://github.com/jimmywarting/node-domexception#readme", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + }, + { + "type": "github", + "url": "https://paypal.me/jimmywarting" + } + ] +} diff --git a/backend/node_modules/node-domexception/.history/package_20210527205156.json b/backend/node_modules/node-domexception/.history/package_20210527205156.json new file mode 100644 index 0000000000000000000000000000000000000000..cd08e704ea2957b835964f467ad62b59d6f5c158 --- /dev/null +++ b/backend/node_modules/node-domexception/.history/package_20210527205156.json @@ -0,0 +1,29 @@ +{ + "name": "node-domexception", + "version": "1.0.0", + "description": "An implementation of the DOMException class from NodeJS", + "main": "index.js", + "repository": { + "type": "git", + "url": "git+https://github.com/jimmywarting/node-domexception.git" + }, + "engines": { + "node": ">=10.5.0" + }, + "author": "Jimmy Wärting", + "license": "MIT", + "bugs": { + "url": "https://github.com/jimmywarting/node-domexception/issues" + }, + "homepage": "https://github.com/jimmywarting/node-domexception#readme", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + }, + { + "type": "github", + "url": "https://paypal.me/jimmywarting" + } + ] +} diff --git a/backend/node_modules/node-domexception/.history/test_20210527205603.js b/backend/node_modules/node-domexception/.history/test_20210527205603.js new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/backend/node_modules/node-domexception/.history/test_20210527205957.js b/backend/node_modules/node-domexception/.history/test_20210527205957.js new file mode 100644 index 0000000000000000000000000000000000000000..73feac5f1113f35fe45d7a74bdaa02dd8b9e99a1 --- /dev/null +++ b/backend/node_modules/node-domexception/.history/test_20210527205957.js @@ -0,0 +1,3 @@ +require('./index.js') + +console.log(DOMException.INDEX_SIZE_ERR) diff --git a/backend/node_modules/node-domexception/.history/test_20210527210021.js b/backend/node_modules/node-domexception/.history/test_20210527210021.js new file mode 100644 index 0000000000000000000000000000000000000000..be47491600fba68a1e18514413905569fbd7a960 --- /dev/null +++ b/backend/node_modules/node-domexception/.history/test_20210527210021.js @@ -0,0 +1,3 @@ +const e = require('./index.js') + +console.log(e.INDEX_SIZE_ERR) diff --git a/backend/node_modules/node-domexception/LICENSE b/backend/node_modules/node-domexception/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..bc8ceb7f252ddb401a53503b93f78703ae62f1e7 --- /dev/null +++ b/backend/node_modules/node-domexception/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 Jimmy Wärting + +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/backend/node_modules/node-domexception/README.md b/backend/node_modules/node-domexception/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a36946147d2db3f8f9bf27f6e8537bdc91bd38c9 --- /dev/null +++ b/backend/node_modules/node-domexception/README.md @@ -0,0 +1,46 @@ +# DOMException +An implementation of the DOMException class from NodeJS + +NodeJS has DOMException built in, but it's not globally available, and you can't require/import it from somewhere. + +This package exposes the [`DOMException`](https://developer.mozilla.org/en-US/docs/Web/API/DOMException) class that comes from NodeJS itself. (including all of the legacy codes) + +(plz don't depend on this package in any other environment other than node >=10.5) + +```js +import DOMException from 'node-domexception' +import { MessageChannel } from 'worker_threads' + +async function hello() { + const port = new MessageChannel().port1 + const ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) +} + +hello().catch(err => { + console.assert(err.name === 'DataCloneError') + console.assert(err.code === 25) + console.assert(err instanceof DOMException) +}) + +const e1 = new DOMException('Something went wrong', 'BadThingsError') +console.assert(e1.name === 'BadThingsError') +console.assert(e1.code === 0) + +const e2 = new DOMException('Another exciting error message', 'NoModificationAllowedError') +console.assert(e2.name === 'NoModificationAllowedError') +console.assert(e2.code === 7) + +console.assert(DOMException.INUSE_ATTRIBUTE_ERR === 10) +``` + +# Background + +The only possible way is to use some web-ish tools that have been introduced into NodeJS that throws a DOMException and catch the constructor. This is exactly what this package dose for you and exposes it.
+This way you will have the same class that NodeJS has and you can check if the error is a instance of DOMException.
+The instanceof check would not have worked with a custom class such as the DOMException provided by domenic which also is much larger in size since it has to re-construct the hole class from the ground up. + +The DOMException is used in many places such as the Fetch API, File & Blobs, PostMessaging and more.
+Why they decided to call it **DOM**, I don't know + +Please consider sponsoring if you find this helpful diff --git a/backend/node_modules/node-domexception/index.js b/backend/node_modules/node-domexception/index.js new file mode 100644 index 0000000000000000000000000000000000000000..b7bbe951938adfde643d88ea8da70c414c0b362e --- /dev/null +++ b/backend/node_modules/node-domexception/index.js @@ -0,0 +1,16 @@ +/*! node-domexception. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + try { + const { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) + } catch (err) { + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException diff --git a/backend/node_modules/node-domexception/package.json b/backend/node_modules/node-domexception/package.json new file mode 100644 index 0000000000000000000000000000000000000000..cd08e704ea2957b835964f467ad62b59d6f5c158 --- /dev/null +++ b/backend/node_modules/node-domexception/package.json @@ -0,0 +1,29 @@ +{ + "name": "node-domexception", + "version": "1.0.0", + "description": "An implementation of the DOMException class from NodeJS", + "main": "index.js", + "repository": { + "type": "git", + "url": "git+https://github.com/jimmywarting/node-domexception.git" + }, + "engines": { + "node": ">=10.5.0" + }, + "author": "Jimmy Wärting", + "license": "MIT", + "bugs": { + "url": "https://github.com/jimmywarting/node-domexception/issues" + }, + "homepage": "https://github.com/jimmywarting/node-domexception#readme", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + }, + { + "type": "github", + "url": "https://paypal.me/jimmywarting" + } + ] +} diff --git a/backend/node_modules/node-fetch/LICENSE.md b/backend/node_modules/node-fetch/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..660ffecb58b02f27a562c193c71f14b7b573fc96 --- /dev/null +++ b/backend/node_modules/node-fetch/LICENSE.md @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2016 David Frank + +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/backend/node_modules/node-fetch/README.md b/backend/node_modules/node-fetch/README.md new file mode 100644 index 0000000000000000000000000000000000000000..55f09b7ffe21daa5ce7211c671b4c13fac894a69 --- /dev/null +++ b/backend/node_modules/node-fetch/README.md @@ -0,0 +1,634 @@ +node-fetch +========== + +[![npm version][npm-image]][npm-url] +[![build status][travis-image]][travis-url] +[![coverage status][codecov-image]][codecov-url] +[![install size][install-size-image]][install-size-url] +[![Discord][discord-image]][discord-url] + +A light-weight module that brings `window.fetch` to Node.js + +(We are looking for [v2 maintainers and collaborators](https://github.com/bitinn/node-fetch/issues/567)) + +[![Backers][opencollective-image]][opencollective-url] + + + +- [Motivation](#motivation) +- [Features](#features) +- [Difference from client-side fetch](#difference-from-client-side-fetch) +- [Installation](#installation) +- [Loading and configuring the module](#loading-and-configuring-the-module) +- [Common Usage](#common-usage) + - [Plain text or HTML](#plain-text-or-html) + - [JSON](#json) + - [Simple Post](#simple-post) + - [Post with JSON](#post-with-json) + - [Post with form parameters](#post-with-form-parameters) + - [Handling exceptions](#handling-exceptions) + - [Handling client and server errors](#handling-client-and-server-errors) +- [Advanced Usage](#advanced-usage) + - [Streams](#streams) + - [Buffer](#buffer) + - [Accessing Headers and other Meta data](#accessing-headers-and-other-meta-data) + - [Extract Set-Cookie Header](#extract-set-cookie-header) + - [Post data using a file stream](#post-data-using-a-file-stream) + - [Post with form-data (detect multipart)](#post-with-form-data-detect-multipart) + - [Request cancellation with AbortSignal](#request-cancellation-with-abortsignal) +- [API](#api) + - [fetch(url[, options])](#fetchurl-options) + - [Options](#options) + - [Class: Request](#class-request) + - [Class: Response](#class-response) + - [Class: Headers](#class-headers) + - [Interface: Body](#interface-body) + - [Class: FetchError](#class-fetcherror) +- [License](#license) +- [Acknowledgement](#acknowledgement) + + + +## Motivation + +Instead of implementing `XMLHttpRequest` in Node.js to run browser-specific [Fetch polyfill](https://github.com/github/fetch), why not go from native `http` to `fetch` API directly? Hence, `node-fetch`, minimal code for a `window.fetch` compatible API on Node.js runtime. + +See Matt Andrews' [isomorphic-fetch](https://github.com/matthew-andrews/isomorphic-fetch) or Leonardo Quixada's [cross-fetch](https://github.com/lquixada/cross-fetch) for isomorphic usage (exports `node-fetch` for server-side, `whatwg-fetch` for client-side). + +## Features + +- Stay consistent with `window.fetch` API. +- Make conscious trade-off when following [WHATWG fetch spec][whatwg-fetch] and [stream spec](https://streams.spec.whatwg.org/) implementation details, document known differences. +- Use native promise but allow substituting it with [insert your favorite promise library]. +- Use native Node streams for body on both request and response. +- Decode content encoding (gzip/deflate) properly and convert string output (such as `res.text()` and `res.json()`) to UTF-8 automatically. +- Useful extensions such as timeout, redirect limit, response size limit, [explicit errors](ERROR-HANDLING.md) for troubleshooting. + +## Difference from client-side fetch + +- See [Known Differences](LIMITS.md) for details. +- If you happen to use a missing feature that `window.fetch` offers, feel free to open an issue. +- Pull requests are welcomed too! + +## Installation + +Current stable release (`2.x`) + +```sh +$ npm install node-fetch +``` + +## Loading and configuring the module +We suggest you load the module via `require` until the stabilization of ES modules in node: +```js +const fetch = require('node-fetch'); +``` + +If you are using a Promise library other than native, set it through `fetch.Promise`: +```js +const Bluebird = require('bluebird'); + +fetch.Promise = Bluebird; +``` + +## Common Usage + +NOTE: The documentation below is up-to-date with `2.x` releases; see the [`1.x` readme](https://github.com/bitinn/node-fetch/blob/1.x/README.md), [changelog](https://github.com/bitinn/node-fetch/blob/1.x/CHANGELOG.md) and [2.x upgrade guide](UPGRADE-GUIDE.md) for the differences. + +#### Plain text or HTML +```js +fetch('https://github.com/') + .then(res => res.text()) + .then(body => console.log(body)); +``` + +#### JSON + +```js + +fetch('https://api.github.com/users/github') + .then(res => res.json()) + .then(json => console.log(json)); +``` + +#### Simple Post +```js +fetch('https://httpbin.org/post', { method: 'POST', body: 'a=1' }) + .then(res => res.json()) // expecting a json response + .then(json => console.log(json)); +``` + +#### Post with JSON + +```js +const body = { a: 1 }; + +fetch('https://httpbin.org/post', { + method: 'post', + body: JSON.stringify(body), + headers: { 'Content-Type': 'application/json' }, + }) + .then(res => res.json()) + .then(json => console.log(json)); +``` + +#### Post with form parameters +`URLSearchParams` is available in Node.js as of v7.5.0. See [official documentation](https://nodejs.org/api/url.html#url_class_urlsearchparams) for more usage methods. + +NOTE: The `Content-Type` header is only set automatically to `x-www-form-urlencoded` when an instance of `URLSearchParams` is given as such: + +```js +const { URLSearchParams } = require('url'); + +const params = new URLSearchParams(); +params.append('a', 1); + +fetch('https://httpbin.org/post', { method: 'POST', body: params }) + .then(res => res.json()) + .then(json => console.log(json)); +``` + +#### Handling exceptions +NOTE: 3xx-5xx responses are *NOT* exceptions and should be handled in `then()`; see the next section for more information. + +Adding a catch to the fetch promise chain will catch *all* exceptions, such as errors originating from node core libraries, network errors and operational errors, which are instances of FetchError. See the [error handling document](ERROR-HANDLING.md) for more details. + +```js +fetch('https://domain.invalid/') + .catch(err => console.error(err)); +``` + +#### Handling client and server errors +It is common to create a helper function to check that the response contains no client (4xx) or server (5xx) error responses: + +```js +function checkStatus(res) { + if (res.ok) { // res.status >= 200 && res.status < 300 + return res; + } else { + throw MyCustomError(res.statusText); + } +} + +fetch('https://httpbin.org/status/400') + .then(checkStatus) + .then(res => console.log('will not get here...')) +``` + +## Advanced Usage + +#### Streams +The "Node.js way" is to use streams when possible: + +```js +fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png') + .then(res => { + const dest = fs.createWriteStream('./octocat.png'); + res.body.pipe(dest); + }); +``` + +In Node.js 14 you can also use async iterators to read `body`; however, be careful to catch +errors -- the longer a response runs, the more likely it is to encounter an error. + +```js +const fetch = require('node-fetch'); +const response = await fetch('https://httpbin.org/stream/3'); +try { + for await (const chunk of response.body) { + console.dir(JSON.parse(chunk.toString())); + } +} catch (err) { + console.error(err.stack); +} +``` + +In Node.js 12 you can also use async iterators to read `body`; however, async iterators with streams +did not mature until Node.js 14, so you need to do some extra work to ensure you handle errors +directly from the stream and wait on it response to fully close. + +```js +const fetch = require('node-fetch'); +const read = async body => { + let error; + body.on('error', err => { + error = err; + }); + for await (const chunk of body) { + console.dir(JSON.parse(chunk.toString())); + } + return new Promise((resolve, reject) => { + body.on('close', () => { + error ? reject(error) : resolve(); + }); + }); +}; +try { + const response = await fetch('https://httpbin.org/stream/3'); + await read(response.body); +} catch (err) { + console.error(err.stack); +} +``` + +#### Buffer +If you prefer to cache binary data in full, use buffer(). (NOTE: `buffer()` is a `node-fetch`-only API) + +```js +const fileType = require('file-type'); + +fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png') + .then(res => res.buffer()) + .then(buffer => fileType(buffer)) + .then(type => { /* ... */ }); +``` + +#### Accessing Headers and other Meta data +```js +fetch('https://github.com/') + .then(res => { + console.log(res.ok); + console.log(res.status); + console.log(res.statusText); + console.log(res.headers.raw()); + console.log(res.headers.get('content-type')); + }); +``` + +#### Extract Set-Cookie Header + +Unlike browsers, you can access raw `Set-Cookie` headers manually using `Headers.raw()`. This is a `node-fetch` only API. + +```js +fetch(url).then(res => { + // returns an array of values, instead of a string of comma-separated values + console.log(res.headers.raw()['set-cookie']); +}); +``` + +#### Post data using a file stream + +```js +const { createReadStream } = require('fs'); + +const stream = createReadStream('input.txt'); + +fetch('https://httpbin.org/post', { method: 'POST', body: stream }) + .then(res => res.json()) + .then(json => console.log(json)); +``` + +#### Post with form-data (detect multipart) + +```js +const FormData = require('form-data'); + +const form = new FormData(); +form.append('a', 1); + +fetch('https://httpbin.org/post', { method: 'POST', body: form }) + .then(res => res.json()) + .then(json => console.log(json)); + +// OR, using custom headers +// NOTE: getHeaders() is non-standard API + +const form = new FormData(); +form.append('a', 1); + +const options = { + method: 'POST', + body: form, + headers: form.getHeaders() +} + +fetch('https://httpbin.org/post', options) + .then(res => res.json()) + .then(json => console.log(json)); +``` + +#### Request cancellation with AbortSignal + +> NOTE: You may cancel streamed requests only on Node >= v8.0.0 + +You may cancel requests with `AbortController`. A suggested implementation is [`abort-controller`](https://www.npmjs.com/package/abort-controller). + +An example of timing out a request after 150ms could be achieved as the following: + +```js +import AbortController from 'abort-controller'; + +const controller = new AbortController(); +const timeout = setTimeout( + () => { controller.abort(); }, + 150, +); + +fetch(url, { signal: controller.signal }) + .then(res => res.json()) + .then( + data => { + useData(data) + }, + err => { + if (err.name === 'AbortError') { + // request was aborted + } + }, + ) + .finally(() => { + clearTimeout(timeout); + }); +``` + +See [test cases](https://github.com/bitinn/node-fetch/blob/master/test/test.js) for more examples. + + +## API + +### fetch(url[, options]) + +- `url` A string representing the URL for fetching +- `options` [Options](#fetch-options) for the HTTP(S) request +- Returns: Promise<[Response](#class-response)> + +Perform an HTTP(S) fetch. + +`url` should be an absolute url, such as `https://example.com/`. A path-relative URL (`/file/under/root`) or protocol-relative URL (`//can-be-http-or-https.com/`) will result in a rejected `Promise`. + + +### Options + +The default values are shown after each option key. + +```js +{ + // These properties are part of the Fetch Standard + method: 'GET', + headers: {}, // request headers. format is the identical to that accepted by the Headers constructor (see below) + body: null, // request body. can be null, a string, a Buffer, a Blob, or a Node.js Readable stream + redirect: 'follow', // set to `manual` to extract redirect headers, `error` to reject redirect + signal: null, // pass an instance of AbortSignal to optionally abort requests + + // The following properties are node-fetch extensions + follow: 20, // maximum redirect count. 0 to not follow redirect + timeout: 0, // req/res timeout in ms, it resets on redirect. 0 to disable (OS limit applies). Signal is recommended instead. + compress: true, // support gzip/deflate content encoding. false to disable + size: 0, // maximum response body size in bytes. 0 to disable + agent: null // http(s).Agent instance or function that returns an instance (see below) +} +``` + +##### Default Headers + +If no values are set, the following request headers will be sent automatically: + +Header | Value +------------------- | -------------------------------------------------------- +`Accept-Encoding` | `gzip,deflate` _(when `options.compress === true`)_ +`Accept` | `*/*` +`Content-Length` | _(automatically calculated, if possible)_ +`Transfer-Encoding` | `chunked` _(when `req.body` is a stream)_ +`User-Agent` | `node-fetch/1.0 (+https://github.com/bitinn/node-fetch)` + +Note: when `body` is a `Stream`, `Content-Length` is not set automatically. + +##### Custom Agent + +The `agent` option allows you to specify networking related options which are out of the scope of Fetch, including and not limited to the following: + +- Support self-signed certificate +- Use only IPv4 or IPv6 +- Custom DNS Lookup + +See [`http.Agent`](https://nodejs.org/api/http.html#http_new_agent_options) for more information. + +If no agent is specified, the default agent provided by Node.js is used. Note that [this changed in Node.js 19](https://github.com/nodejs/node/blob/4267b92604ad78584244488e7f7508a690cb80d0/lib/_http_agent.js#L564) to have `keepalive` true by default. If you wish to enable `keepalive` in an earlier version of Node.js, you can override the agent as per the following code sample. + +In addition, the `agent` option accepts a function that returns `http`(s)`.Agent` instance given current [URL](https://nodejs.org/api/url.html), this is useful during a redirection chain across HTTP and HTTPS protocol. + +```js +const httpAgent = new http.Agent({ + keepAlive: true +}); +const httpsAgent = new https.Agent({ + keepAlive: true +}); + +const options = { + agent: function (_parsedURL) { + if (_parsedURL.protocol == 'http:') { + return httpAgent; + } else { + return httpsAgent; + } + } +} +``` + + +### Class: Request + +An HTTP(S) request containing information about URL, method, headers, and the body. This class implements the [Body](#iface-body) interface. + +Due to the nature of Node.js, the following properties are not implemented at this moment: + +- `type` +- `destination` +- `referrer` +- `referrerPolicy` +- `mode` +- `credentials` +- `cache` +- `integrity` +- `keepalive` + +The following node-fetch extension properties are provided: + +- `follow` +- `compress` +- `counter` +- `agent` + +See [options](#fetch-options) for exact meaning of these extensions. + +#### new Request(input[, options]) + +*(spec-compliant)* + +- `input` A string representing a URL, or another `Request` (which will be cloned) +- `options` [Options][#fetch-options] for the HTTP(S) request + +Constructs a new `Request` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request). + +In most cases, directly `fetch(url, options)` is simpler than creating a `Request` object. + + +### Class: Response + +An HTTP(S) response. This class implements the [Body](#iface-body) interface. + +The following properties are not implemented in node-fetch at this moment: + +- `Response.error()` +- `Response.redirect()` +- `type` +- `trailer` + +#### new Response([body[, options]]) + +*(spec-compliant)* + +- `body` A `String` or [`Readable` stream][node-readable] +- `options` A [`ResponseInit`][response-init] options dictionary + +Constructs a new `Response` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response). + +Because Node.js does not implement service workers (for which this class was designed), one rarely has to construct a `Response` directly. + +#### response.ok + +*(spec-compliant)* + +Convenience property representing if the request ended normally. Will evaluate to true if the response status was greater than or equal to 200 but smaller than 300. + +#### response.redirected + +*(spec-compliant)* + +Convenience property representing if the request has been redirected at least once. Will evaluate to true if the internal redirect counter is greater than 0. + + +### Class: Headers + +This class allows manipulating and iterating over a set of HTTP headers. All methods specified in the [Fetch Standard][whatwg-fetch] are implemented. + +#### new Headers([init]) + +*(spec-compliant)* + +- `init` Optional argument to pre-fill the `Headers` object + +Construct a new `Headers` object. `init` can be either `null`, a `Headers` object, an key-value map object or any iterable object. + +```js +// Example adapted from https://fetch.spec.whatwg.org/#example-headers-class + +const meta = { + 'Content-Type': 'text/xml', + 'Breaking-Bad': '<3' +}; +const headers = new Headers(meta); + +// The above is equivalent to +const meta = [ + [ 'Content-Type', 'text/xml' ], + [ 'Breaking-Bad', '<3' ] +]; +const headers = new Headers(meta); + +// You can in fact use any iterable objects, like a Map or even another Headers +const meta = new Map(); +meta.set('Content-Type', 'text/xml'); +meta.set('Breaking-Bad', '<3'); +const headers = new Headers(meta); +const copyOfHeaders = new Headers(headers); +``` + + +### Interface: Body + +`Body` is an abstract interface with methods that are applicable to both `Request` and `Response` classes. + +The following methods are not yet implemented in node-fetch at this moment: + +- `formData()` + +#### body.body + +*(deviation from spec)* + +* Node.js [`Readable` stream][node-readable] + +Data are encapsulated in the `Body` object. Note that while the [Fetch Standard][whatwg-fetch] requires the property to always be a WHATWG `ReadableStream`, in node-fetch it is a Node.js [`Readable` stream][node-readable]. + +#### body.bodyUsed + +*(spec-compliant)* + +* `Boolean` + +A boolean property for if this body has been consumed. Per the specs, a consumed body cannot be used again. + +#### body.arrayBuffer() +#### body.blob() +#### body.json() +#### body.text() + +*(spec-compliant)* + +* Returns: Promise + +Consume the body and return a promise that will resolve to one of these formats. + +#### body.buffer() + +*(node-fetch extension)* + +* Returns: Promise<Buffer> + +Consume the body and return a promise that will resolve to a Buffer. + +#### body.textConverted() + +*(node-fetch extension)* + +* Returns: Promise<String> + +Identical to `body.text()`, except instead of always converting to UTF-8, encoding sniffing will be performed and text converted to UTF-8 if possible. + +(This API requires an optional dependency of the npm package [encoding](https://www.npmjs.com/package/encoding), which you need to install manually. `webpack` users may see [a warning message](https://github.com/bitinn/node-fetch/issues/412#issuecomment-379007792) due to this optional dependency.) + + +### Class: FetchError + +*(node-fetch extension)* + +An operational error in the fetching process. See [ERROR-HANDLING.md][] for more info. + + +### Class: AbortError + +*(node-fetch extension)* + +An Error thrown when the request is aborted in response to an `AbortSignal`'s `abort` event. It has a `name` property of `AbortError`. See [ERROR-HANDLING.MD][] for more info. + +## Acknowledgement + +Thanks to [github/fetch](https://github.com/github/fetch) for providing a solid implementation reference. + +`node-fetch` v1 was maintained by [@bitinn](https://github.com/bitinn); v2 was maintained by [@TimothyGu](https://github.com/timothygu), [@bitinn](https://github.com/bitinn) and [@jimmywarting](https://github.com/jimmywarting); v2 readme is written by [@jkantr](https://github.com/jkantr). + +## License + +MIT + +[npm-image]: https://flat.badgen.net/npm/v/node-fetch +[npm-url]: https://www.npmjs.com/package/node-fetch +[travis-image]: https://flat.badgen.net/travis/bitinn/node-fetch +[travis-url]: https://travis-ci.org/bitinn/node-fetch +[codecov-image]: https://flat.badgen.net/codecov/c/github/bitinn/node-fetch/master +[codecov-url]: https://codecov.io/gh/bitinn/node-fetch +[install-size-image]: https://flat.badgen.net/packagephobia/install/node-fetch +[install-size-url]: https://packagephobia.now.sh/result?p=node-fetch +[discord-image]: https://img.shields.io/discord/619915844268326952?color=%237289DA&label=Discord&style=flat-square +[discord-url]: https://discord.gg/Zxbndcm +[opencollective-image]: https://opencollective.com/node-fetch/backers.svg +[opencollective-url]: https://opencollective.com/node-fetch +[whatwg-fetch]: https://fetch.spec.whatwg.org/ +[response-init]: https://fetch.spec.whatwg.org/#responseinit +[node-readable]: https://nodejs.org/api/stream.html#stream_readable_streams +[mdn-headers]: https://developer.mozilla.org/en-US/docs/Web/API/Headers +[LIMITS.md]: https://github.com/bitinn/node-fetch/blob/master/LIMITS.md +[ERROR-HANDLING.md]: https://github.com/bitinn/node-fetch/blob/master/ERROR-HANDLING.md +[UPGRADE-GUIDE.md]: https://github.com/bitinn/node-fetch/blob/master/UPGRADE-GUIDE.md diff --git a/backend/node_modules/node-fetch/browser.js b/backend/node_modules/node-fetch/browser.js new file mode 100644 index 0000000000000000000000000000000000000000..ee86265ae3adab9f03cf10f486384735417320e6 --- /dev/null +++ b/backend/node_modules/node-fetch/browser.js @@ -0,0 +1,25 @@ +"use strict"; + +// ref: https://github.com/tc39/proposal-global +var getGlobal = function () { + // the only reliable means to get the global object is + // `Function('return this')()` + // However, this causes CSP violations in Chrome apps. + if (typeof self !== 'undefined') { return self; } + if (typeof window !== 'undefined') { return window; } + if (typeof global !== 'undefined') { return global; } + throw new Error('unable to locate global object'); +} + +var globalObject = getGlobal(); + +module.exports = exports = globalObject.fetch; + +// Needed for TypeScript and Webpack. +if (globalObject.fetch) { + exports.default = globalObject.fetch.bind(globalObject); +} + +exports.Headers = globalObject.Headers; +exports.Request = globalObject.Request; +exports.Response = globalObject.Response; diff --git a/backend/node_modules/node-fetch/lib/index.es.js b/backend/node_modules/node-fetch/lib/index.es.js new file mode 100644 index 0000000000000000000000000000000000000000..aae9799c1a8798d5899ffed6deda4c98b7007b48 --- /dev/null +++ b/backend/node_modules/node-fetch/lib/index.es.js @@ -0,0 +1,1777 @@ +process.emitWarning("The .es.js file is deprecated. Use .mjs instead."); + +import Stream from 'stream'; +import http from 'http'; +import Url from 'url'; +import whatwgUrl from 'whatwg-url'; +import https from 'https'; +import zlib from 'zlib'; + +// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js + +// fix for "Readable" isn't a named export issue +const Readable = Stream.Readable; + +const BUFFER = Symbol('buffer'); +const TYPE = Symbol('type'); + +class Blob { + constructor() { + this[TYPE] = ''; + + const blobParts = arguments[0]; + const options = arguments[1]; + + const buffers = []; + let size = 0; + + if (blobParts) { + const a = blobParts; + const length = Number(a.length); + for (let i = 0; i < length; i++) { + const element = a[i]; + let buffer; + if (element instanceof Buffer) { + buffer = element; + } else if (ArrayBuffer.isView(element)) { + buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength); + } else if (element instanceof ArrayBuffer) { + buffer = Buffer.from(element); + } else if (element instanceof Blob) { + buffer = element[BUFFER]; + } else { + buffer = Buffer.from(typeof element === 'string' ? element : String(element)); + } + size += buffer.length; + buffers.push(buffer); + } + } + + this[BUFFER] = Buffer.concat(buffers); + + let type = options && options.type !== undefined && String(options.type).toLowerCase(); + if (type && !/[^\u0020-\u007E]/.test(type)) { + this[TYPE] = type; + } + } + get size() { + return this[BUFFER].length; + } + get type() { + return this[TYPE]; + } + text() { + return Promise.resolve(this[BUFFER].toString()); + } + arrayBuffer() { + const buf = this[BUFFER]; + const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + return Promise.resolve(ab); + } + stream() { + const readable = new Readable(); + readable._read = function () {}; + readable.push(this[BUFFER]); + readable.push(null); + return readable; + } + toString() { + return '[object Blob]'; + } + slice() { + const size = this.size; + + const start = arguments[0]; + const end = arguments[1]; + let relativeStart, relativeEnd; + if (start === undefined) { + relativeStart = 0; + } else if (start < 0) { + relativeStart = Math.max(size + start, 0); + } else { + relativeStart = Math.min(start, size); + } + if (end === undefined) { + relativeEnd = size; + } else if (end < 0) { + relativeEnd = Math.max(size + end, 0); + } else { + relativeEnd = Math.min(end, size); + } + const span = Math.max(relativeEnd - relativeStart, 0); + + const buffer = this[BUFFER]; + const slicedBuffer = buffer.slice(relativeStart, relativeStart + span); + const blob = new Blob([], { type: arguments[2] }); + blob[BUFFER] = slicedBuffer; + return blob; + } +} + +Object.defineProperties(Blob.prototype, { + size: { enumerable: true }, + type: { enumerable: true }, + slice: { enumerable: true } +}); + +Object.defineProperty(Blob.prototype, Symbol.toStringTag, { + value: 'Blob', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * fetch-error.js + * + * FetchError interface for operational errors + */ + +/** + * Create FetchError instance + * + * @param String message Error message for human + * @param String type Error type for machine + * @param String systemError For Node.js system error + * @return FetchError + */ +function FetchError(message, type, systemError) { + Error.call(this, message); + + this.message = message; + this.type = type; + + // when err.type is `system`, err.code contains system error code + if (systemError) { + this.code = this.errno = systemError.code; + } + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +FetchError.prototype = Object.create(Error.prototype); +FetchError.prototype.constructor = FetchError; +FetchError.prototype.name = 'FetchError'; + +let convert; +try { + convert = require('encoding').convert; +} catch (e) {} + +const INTERNALS = Symbol('Body internals'); + +// fix an issue where "PassThrough" isn't a named export for node <10 +const PassThrough = Stream.PassThrough; + +/** + * Body mixin + * + * Ref: https://fetch.spec.whatwg.org/#body + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +function Body(body) { + var _this = this; + + var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + _ref$size = _ref.size; + + let size = _ref$size === undefined ? 0 : _ref$size; + var _ref$timeout = _ref.timeout; + let timeout = _ref$timeout === undefined ? 0 : _ref$timeout; + + if (body == null) { + // body is undefined or null + body = null; + } else if (isURLSearchParams(body)) { + // body is a URLSearchParams + body = Buffer.from(body.toString()); + } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { + // body is ArrayBuffer + body = Buffer.from(body); + } else if (ArrayBuffer.isView(body)) { + // body is ArrayBufferView + body = Buffer.from(body.buffer, body.byteOffset, body.byteLength); + } else if (body instanceof Stream) ; else { + // none of the above + // coerce to string then buffer + body = Buffer.from(String(body)); + } + this[INTERNALS] = { + body, + disturbed: false, + error: null + }; + this.size = size; + this.timeout = timeout; + + if (body instanceof Stream) { + body.on('error', function (err) { + const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err); + _this[INTERNALS].error = error; + }); + } +} + +Body.prototype = { + get body() { + return this[INTERNALS].body; + }, + + get bodyUsed() { + return this[INTERNALS].disturbed; + }, + + /** + * Decode response as ArrayBuffer + * + * @return Promise + */ + arrayBuffer() { + return consumeBody.call(this).then(function (buf) { + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + }); + }, + + /** + * Return raw response as Blob + * + * @return Promise + */ + blob() { + let ct = this.headers && this.headers.get('content-type') || ''; + return consumeBody.call(this).then(function (buf) { + return Object.assign( + // Prevent copying + new Blob([], { + type: ct.toLowerCase() + }), { + [BUFFER]: buf + }); + }); + }, + + /** + * Decode response as json + * + * @return Promise + */ + json() { + var _this2 = this; + + return consumeBody.call(this).then(function (buffer) { + try { + return JSON.parse(buffer.toString()); + } catch (err) { + return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json')); + } + }); + }, + + /** + * Decode response as text + * + * @return Promise + */ + text() { + return consumeBody.call(this).then(function (buffer) { + return buffer.toString(); + }); + }, + + /** + * Decode response as buffer (non-spec api) + * + * @return Promise + */ + buffer() { + return consumeBody.call(this); + }, + + /** + * Decode response as text, while automatically detecting the encoding and + * trying to decode to UTF-8 (non-spec api) + * + * @return Promise + */ + textConverted() { + var _this3 = this; + + return consumeBody.call(this).then(function (buffer) { + return convertBody(buffer, _this3.headers); + }); + } +}; + +// In browsers, all properties are enumerable. +Object.defineProperties(Body.prototype, { + body: { enumerable: true }, + bodyUsed: { enumerable: true }, + arrayBuffer: { enumerable: true }, + blob: { enumerable: true }, + json: { enumerable: true }, + text: { enumerable: true } +}); + +Body.mixIn = function (proto) { + for (const name of Object.getOwnPropertyNames(Body.prototype)) { + // istanbul ignore else: future proof + if (!(name in proto)) { + const desc = Object.getOwnPropertyDescriptor(Body.prototype, name); + Object.defineProperty(proto, name, desc); + } + } +}; + +/** + * Consume and convert an entire Body to a Buffer. + * + * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body + * + * @return Promise + */ +function consumeBody() { + var _this4 = this; + + if (this[INTERNALS].disturbed) { + return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`)); + } + + this[INTERNALS].disturbed = true; + + if (this[INTERNALS].error) { + return Body.Promise.reject(this[INTERNALS].error); + } + + let body = this.body; + + // body is null + if (body === null) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is blob + if (isBlob(body)) { + body = body.stream(); + } + + // body is buffer + if (Buffer.isBuffer(body)) { + return Body.Promise.resolve(body); + } + + // istanbul ignore if: should never happen + if (!(body instanceof Stream)) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is stream + // get ready to actually consume the body + let accum = []; + let accumBytes = 0; + let abort = false; + + return new Body.Promise(function (resolve, reject) { + let resTimeout; + + // allow timeout on slow response body + if (_this4.timeout) { + resTimeout = setTimeout(function () { + abort = true; + reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout')); + }, _this4.timeout); + } + + // handle stream errors + body.on('error', function (err) { + if (err.name === 'AbortError') { + // if the request was aborted, reject with this Error + abort = true; + reject(err); + } else { + // other errors, such as incorrect content-encoding + reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + + body.on('data', function (chunk) { + if (abort || chunk === null) { + return; + } + + if (_this4.size && accumBytes + chunk.length > _this4.size) { + abort = true; + reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size')); + return; + } + + accumBytes += chunk.length; + accum.push(chunk); + }); + + body.on('end', function () { + if (abort) { + return; + } + + clearTimeout(resTimeout); + + try { + resolve(Buffer.concat(accum, accumBytes)); + } catch (err) { + // handle streams that have accumulated too much data (issue #414) + reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + }); +} + +/** + * Detect buffer encoding and convert to target encoding + * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding + * + * @param Buffer buffer Incoming buffer + * @param String encoding Target encoding + * @return String + */ +function convertBody(buffer, headers) { + if (typeof convert !== 'function') { + throw new Error('The package `encoding` must be installed to use the textConverted() function'); + } + + const ct = headers.get('content-type'); + let charset = 'utf-8'; + let res, str; + + // header + if (ct) { + res = /charset=([^;]*)/i.exec(ct); + } + + // no charset in content type, peek at response body for at most 1024 bytes + str = buffer.slice(0, 1024).toString(); + + // html5 + if (!res && str) { + res = / 0 && arguments[0] !== undefined ? arguments[0] : undefined; + + this[MAP] = Object.create(null); + + if (init instanceof Headers) { + const rawHeaders = init.raw(); + const headerNames = Object.keys(rawHeaders); + + for (const headerName of headerNames) { + for (const value of rawHeaders[headerName]) { + this.append(headerName, value); + } + } + + return; + } + + // We don't worry about converting prop to ByteString here as append() + // will handle it. + if (init == null) ; else if (typeof init === 'object') { + const method = init[Symbol.iterator]; + if (method != null) { + if (typeof method !== 'function') { + throw new TypeError('Header pairs must be iterable'); + } + + // sequence> + // Note: per spec we have to first exhaust the lists then process them + const pairs = []; + for (const pair of init) { + if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') { + throw new TypeError('Each header pair must be iterable'); + } + pairs.push(Array.from(pair)); + } + + for (const pair of pairs) { + if (pair.length !== 2) { + throw new TypeError('Each header pair must be a name/value tuple'); + } + this.append(pair[0], pair[1]); + } + } else { + // record + for (const key of Object.keys(init)) { + const value = init[key]; + this.append(key, value); + } + } + } else { + throw new TypeError('Provided initializer must be an object'); + } + } + + /** + * Return combined header value given name + * + * @param String name Header name + * @return Mixed + */ + get(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key === undefined) { + return null; + } + + return this[MAP][key].join(', '); + } + + /** + * Iterate over all headers + * + * @param Function callback Executed for each item with parameters (value, name, thisArg) + * @param Boolean thisArg `this` context for callback function + * @return Void + */ + forEach(callback) { + let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; + + let pairs = getHeaders(this); + let i = 0; + while (i < pairs.length) { + var _pairs$i = pairs[i]; + const name = _pairs$i[0], + value = _pairs$i[1]; + + callback.call(thisArg, value, name, this); + pairs = getHeaders(this); + i++; + } + } + + /** + * Overwrite header values given name + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + set(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + this[MAP][key !== undefined ? key : name] = [value]; + } + + /** + * Append a value onto existing header + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + append(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + if (key !== undefined) { + this[MAP][key].push(value); + } else { + this[MAP][name] = [value]; + } + } + + /** + * Check for header name existence + * + * @param String name Header name + * @return Boolean + */ + has(name) { + name = `${name}`; + validateName(name); + return find(this[MAP], name) !== undefined; + } + + /** + * Delete all header values given name + * + * @param String name Header name + * @return Void + */ + delete(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key !== undefined) { + delete this[MAP][key]; + } + } + + /** + * Return raw headers (non-spec api) + * + * @return Object + */ + raw() { + return this[MAP]; + } + + /** + * Get an iterator on keys. + * + * @return Iterator + */ + keys() { + return createHeadersIterator(this, 'key'); + } + + /** + * Get an iterator on values. + * + * @return Iterator + */ + values() { + return createHeadersIterator(this, 'value'); + } + + /** + * Get an iterator on entries. + * + * This is the default iterator of the Headers object. + * + * @return Iterator + */ + [Symbol.iterator]() { + return createHeadersIterator(this, 'key+value'); + } +} +Headers.prototype.entries = Headers.prototype[Symbol.iterator]; + +Object.defineProperty(Headers.prototype, Symbol.toStringTag, { + value: 'Headers', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Headers.prototype, { + get: { enumerable: true }, + forEach: { enumerable: true }, + set: { enumerable: true }, + append: { enumerable: true }, + has: { enumerable: true }, + delete: { enumerable: true }, + keys: { enumerable: true }, + values: { enumerable: true }, + entries: { enumerable: true } +}); + +function getHeaders(headers) { + let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value'; + + const keys = Object.keys(headers[MAP]).sort(); + return keys.map(kind === 'key' ? function (k) { + return k.toLowerCase(); + } : kind === 'value' ? function (k) { + return headers[MAP][k].join(', '); + } : function (k) { + return [k.toLowerCase(), headers[MAP][k].join(', ')]; + }); +} + +const INTERNAL = Symbol('internal'); + +function createHeadersIterator(target, kind) { + const iterator = Object.create(HeadersIteratorPrototype); + iterator[INTERNAL] = { + target, + kind, + index: 0 + }; + return iterator; +} + +const HeadersIteratorPrototype = Object.setPrototypeOf({ + next() { + // istanbul ignore if + if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) { + throw new TypeError('Value of `this` is not a HeadersIterator'); + } + + var _INTERNAL = this[INTERNAL]; + const target = _INTERNAL.target, + kind = _INTERNAL.kind, + index = _INTERNAL.index; + + const values = getHeaders(target, kind); + const len = values.length; + if (index >= len) { + return { + value: undefined, + done: true + }; + } + + this[INTERNAL].index = index + 1; + + return { + value: values[index], + done: false + }; + } +}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))); + +Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, { + value: 'HeadersIterator', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * Export the Headers object in a form that Node.js can consume. + * + * @param Headers headers + * @return Object + */ +function exportNodeCompatibleHeaders(headers) { + const obj = Object.assign({ __proto__: null }, headers[MAP]); + + // http.request() only supports string as Host header. This hack makes + // specifying custom Host header possible. + const hostHeaderKey = find(headers[MAP], 'Host'); + if (hostHeaderKey !== undefined) { + obj[hostHeaderKey] = obj[hostHeaderKey][0]; + } + + return obj; +} + +/** + * Create a Headers object from an object of headers, ignoring those that do + * not conform to HTTP grammar productions. + * + * @param Object obj Object of headers + * @return Headers + */ +function createHeadersLenient(obj) { + const headers = new Headers(); + for (const name of Object.keys(obj)) { + if (invalidTokenRegex.test(name)) { + continue; + } + if (Array.isArray(obj[name])) { + for (const val of obj[name]) { + if (invalidHeaderCharRegex.test(val)) { + continue; + } + if (headers[MAP][name] === undefined) { + headers[MAP][name] = [val]; + } else { + headers[MAP][name].push(val); + } + } + } else if (!invalidHeaderCharRegex.test(obj[name])) { + headers[MAP][name] = [obj[name]]; + } + } + return headers; +} + +const INTERNALS$1 = Symbol('Response internals'); + +// fix an issue where "STATUS_CODES" aren't a named export for node <10 +const STATUS_CODES = http.STATUS_CODES; + +/** + * Response class + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +class Response { + constructor() { + let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + Body.call(this, body, opts); + + const status = opts.status || 200; + const headers = new Headers(opts.headers); + + if (body != null && !headers.has('Content-Type')) { + const contentType = extractContentType(body); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + this[INTERNALS$1] = { + url: opts.url, + status, + statusText: opts.statusText || STATUS_CODES[status], + headers, + counter: opts.counter + }; + } + + get url() { + return this[INTERNALS$1].url || ''; + } + + get status() { + return this[INTERNALS$1].status; + } + + /** + * Convenience property representing if the request ended normally + */ + get ok() { + return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; + } + + get redirected() { + return this[INTERNALS$1].counter > 0; + } + + get statusText() { + return this[INTERNALS$1].statusText; + } + + get headers() { + return this[INTERNALS$1].headers; + } + + /** + * Clone this response + * + * @return Response + */ + clone() { + return new Response(clone(this), { + url: this.url, + status: this.status, + statusText: this.statusText, + headers: this.headers, + ok: this.ok, + redirected: this.redirected + }); + } +} + +Body.mixIn(Response.prototype); + +Object.defineProperties(Response.prototype, { + url: { enumerable: true }, + status: { enumerable: true }, + ok: { enumerable: true }, + redirected: { enumerable: true }, + statusText: { enumerable: true }, + headers: { enumerable: true }, + clone: { enumerable: true } +}); + +Object.defineProperty(Response.prototype, Symbol.toStringTag, { + value: 'Response', + writable: false, + enumerable: false, + configurable: true +}); + +const INTERNALS$2 = Symbol('Request internals'); +const URL = Url.URL || whatwgUrl.URL; + +// fix an issue where "format", "parse" aren't a named export for node <10 +const parse_url = Url.parse; +const format_url = Url.format; + +/** + * Wrapper around `new URL` to handle arbitrary URLs + * + * @param {string} urlStr + * @return {void} + */ +function parseURL(urlStr) { + /* + Check whether the URL is absolute or not + Scheme: https://tools.ietf.org/html/rfc3986#section-3.1 + Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3 + */ + if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) { + urlStr = new URL(urlStr).toString(); + } + + // Fallback to old implementation for arbitrary URLs + return parse_url(urlStr); +} + +const streamDestructionSupported = 'destroy' in Stream.Readable.prototype; + +/** + * Check if a value is an instance of Request. + * + * @param Mixed input + * @return Boolean + */ +function isRequest(input) { + return typeof input === 'object' && typeof input[INTERNALS$2] === 'object'; +} + +function isAbortSignal(signal) { + const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal); + return !!(proto && proto.constructor.name === 'AbortSignal'); +} + +/** + * Request class + * + * @param Mixed input Url or Request instance + * @param Object init Custom options + * @return Void + */ +class Request { + constructor(input) { + let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + let parsedURL; + + // normalize input + if (!isRequest(input)) { + if (input && input.href) { + // in order to support Node.js' Url objects; though WHATWG's URL objects + // will fall into this branch also (since their `toString()` will return + // `href` property anyway) + parsedURL = parseURL(input.href); + } else { + // coerce input to a string before attempting to parse + parsedURL = parseURL(`${input}`); + } + input = {}; + } else { + parsedURL = parseURL(input.url); + } + + let method = init.method || input.method || 'GET'; + method = method.toUpperCase(); + + if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { + throw new TypeError('Request with GET/HEAD method cannot have body'); + } + + let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; + + Body.call(this, inputBody, { + timeout: init.timeout || input.timeout || 0, + size: init.size || input.size || 0 + }); + + const headers = new Headers(init.headers || input.headers || {}); + + if (inputBody != null && !headers.has('Content-Type')) { + const contentType = extractContentType(inputBody); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + let signal = isRequest(input) ? input.signal : null; + if ('signal' in init) signal = init.signal; + + if (signal != null && !isAbortSignal(signal)) { + throw new TypeError('Expected signal to be an instanceof AbortSignal'); + } + + this[INTERNALS$2] = { + method, + redirect: init.redirect || input.redirect || 'follow', + headers, + parsedURL, + signal + }; + + // node-fetch-only options + this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20; + this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true; + this.counter = init.counter || input.counter || 0; + this.agent = init.agent || input.agent; + } + + get method() { + return this[INTERNALS$2].method; + } + + get url() { + return format_url(this[INTERNALS$2].parsedURL); + } + + get headers() { + return this[INTERNALS$2].headers; + } + + get redirect() { + return this[INTERNALS$2].redirect; + } + + get signal() { + return this[INTERNALS$2].signal; + } + + /** + * Clone this request + * + * @return Request + */ + clone() { + return new Request(this); + } +} + +Body.mixIn(Request.prototype); + +Object.defineProperty(Request.prototype, Symbol.toStringTag, { + value: 'Request', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Request.prototype, { + method: { enumerable: true }, + url: { enumerable: true }, + headers: { enumerable: true }, + redirect: { enumerable: true }, + clone: { enumerable: true }, + signal: { enumerable: true } +}); + +/** + * Convert a Request to Node.js http request options. + * + * @param Request A Request instance + * @return Object The options object to be passed to http.request + */ +function getNodeRequestOptions(request) { + const parsedURL = request[INTERNALS$2].parsedURL; + const headers = new Headers(request[INTERNALS$2].headers); + + // fetch step 1.3 + if (!headers.has('Accept')) { + headers.set('Accept', '*/*'); + } + + // Basic fetch + if (!parsedURL.protocol || !parsedURL.hostname) { + throw new TypeError('Only absolute URLs are supported'); + } + + if (!/^https?:$/.test(parsedURL.protocol)) { + throw new TypeError('Only HTTP(S) protocols are supported'); + } + + if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) { + throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8'); + } + + // HTTP-network-or-cache fetch steps 2.4-2.7 + let contentLengthValue = null; + if (request.body == null && /^(POST|PUT)$/i.test(request.method)) { + contentLengthValue = '0'; + } + if (request.body != null) { + const totalBytes = getTotalBytes(request); + if (typeof totalBytes === 'number') { + contentLengthValue = String(totalBytes); + } + } + if (contentLengthValue) { + headers.set('Content-Length', contentLengthValue); + } + + // HTTP-network-or-cache fetch step 2.11 + if (!headers.has('User-Agent')) { + headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)'); + } + + // HTTP-network-or-cache fetch step 2.15 + if (request.compress && !headers.has('Accept-Encoding')) { + headers.set('Accept-Encoding', 'gzip,deflate'); + } + + let agent = request.agent; + if (typeof agent === 'function') { + agent = agent(parsedURL); + } + + // HTTP-network fetch step 4.2 + // chunked encoding is handled by Node.js + + return Object.assign({}, parsedURL, { + method: request.method, + headers: exportNodeCompatibleHeaders(headers), + agent + }); +} + +/** + * abort-error.js + * + * AbortError interface for cancelled requests + */ + +/** + * Create AbortError instance + * + * @param String message Error message for human + * @return AbortError + */ +function AbortError(message) { + Error.call(this, message); + + this.type = 'aborted'; + this.message = message; + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +AbortError.prototype = Object.create(Error.prototype); +AbortError.prototype.constructor = AbortError; +AbortError.prototype.name = 'AbortError'; + +const URL$1 = Url.URL || whatwgUrl.URL; + +// fix an issue where "PassThrough", "resolve" aren't a named export for node <10 +const PassThrough$1 = Stream.PassThrough; + +const isDomainOrSubdomain = function isDomainOrSubdomain(destination, original) { + const orig = new URL$1(original).hostname; + const dest = new URL$1(destination).hostname; + + return orig === dest || orig[orig.length - dest.length - 1] === '.' && orig.endsWith(dest); +}; + +/** + * isSameProtocol reports whether the two provided URLs use the same protocol. + * + * Both domains must already be in canonical form. + * @param {string|URL} original + * @param {string|URL} destination + */ +const isSameProtocol = function isSameProtocol(destination, original) { + const orig = new URL$1(original).protocol; + const dest = new URL$1(destination).protocol; + + return orig === dest; +}; + +/** + * Fetch function + * + * @param Mixed url Absolute url or Request instance + * @param Object opts Fetch options + * @return Promise + */ +function fetch(url, opts) { + + // allow custom promise + if (!fetch.Promise) { + throw new Error('native promise missing, set fetch.Promise to your favorite alternative'); + } + + Body.Promise = fetch.Promise; + + // wrap http.request into fetch + return new fetch.Promise(function (resolve, reject) { + // build request object + const request = new Request(url, opts); + const options = getNodeRequestOptions(request); + + const send = (options.protocol === 'https:' ? https : http).request; + const signal = request.signal; + + let response = null; + + const abort = function abort() { + let error = new AbortError('The user aborted a request.'); + reject(error); + if (request.body && request.body instanceof Stream.Readable) { + destroyStream(request.body, error); + } + if (!response || !response.body) return; + response.body.emit('error', error); + }; + + if (signal && signal.aborted) { + abort(); + return; + } + + const abortAndFinalize = function abortAndFinalize() { + abort(); + finalize(); + }; + + // send request + const req = send(options); + let reqTimeout; + + if (signal) { + signal.addEventListener('abort', abortAndFinalize); + } + + function finalize() { + req.abort(); + if (signal) signal.removeEventListener('abort', abortAndFinalize); + clearTimeout(reqTimeout); + } + + if (request.timeout) { + req.once('socket', function (socket) { + reqTimeout = setTimeout(function () { + reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout')); + finalize(); + }, request.timeout); + }); + } + + req.on('error', function (err) { + reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); + + if (response && response.body) { + destroyStream(response.body, err); + } + + finalize(); + }); + + fixResponseChunkedTransferBadEnding(req, function (err) { + if (signal && signal.aborted) { + return; + } + + if (response && response.body) { + destroyStream(response.body, err); + } + }); + + /* c8 ignore next 18 */ + if (parseInt(process.version.substring(1)) < 14) { + // Before Node.js 14, pipeline() does not fully support async iterators and does not always + // properly handle when the socket close/end events are out of order. + req.on('socket', function (s) { + s.addListener('close', function (hadError) { + // if a data listener is still present we didn't end cleanly + const hasDataListener = s.listenerCount('data') > 0; + + // if end happened before close but the socket didn't emit an error, do it now + if (response && hasDataListener && !hadError && !(signal && signal.aborted)) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + response.body.emit('error', err); + } + }); + }); + } + + req.on('response', function (res) { + clearTimeout(reqTimeout); + + const headers = createHeadersLenient(res.headers); + + // HTTP fetch step 5 + if (fetch.isRedirect(res.statusCode)) { + // HTTP fetch step 5.2 + const location = headers.get('Location'); + + // HTTP fetch step 5.3 + let locationURL = null; + try { + locationURL = location === null ? null : new URL$1(location, request.url).toString(); + } catch (err) { + // error here can only be invalid URL in Location: header + // do not throw when options.redirect == manual + // let the user extract the errorneous redirect URL + if (request.redirect !== 'manual') { + reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect')); + finalize(); + return; + } + } + + // HTTP fetch step 5.5 + switch (request.redirect) { + case 'error': + reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect')); + finalize(); + return; + case 'manual': + // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL. + if (locationURL !== null) { + // handle corrupted header + try { + headers.set('Location', locationURL); + } catch (err) { + // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request + reject(err); + } + } + break; + case 'follow': + // HTTP-redirect fetch step 2 + if (locationURL === null) { + break; + } + + // HTTP-redirect fetch step 5 + if (request.counter >= request.follow) { + reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 6 (counter increment) + // Create a new Request object. + const requestOpts = { + headers: new Headers(request.headers), + follow: request.follow, + counter: request.counter + 1, + agent: request.agent, + compress: request.compress, + method: request.method, + body: request.body, + signal: request.signal, + timeout: request.timeout, + size: request.size + }; + + if (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) { + for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) { + requestOpts.headers.delete(name); + } + } + + // HTTP-redirect fetch step 9 + if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) { + reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 11 + if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') { + requestOpts.method = 'GET'; + requestOpts.body = undefined; + requestOpts.headers.delete('content-length'); + } + + // HTTP-redirect fetch step 15 + resolve(fetch(new Request(locationURL, requestOpts))); + finalize(); + return; + } + } + + // prepare response + res.once('end', function () { + if (signal) signal.removeEventListener('abort', abortAndFinalize); + }); + let body = res.pipe(new PassThrough$1()); + + const response_options = { + url: request.url, + status: res.statusCode, + statusText: res.statusMessage, + headers: headers, + size: request.size, + timeout: request.timeout, + counter: request.counter + }; + + // HTTP-network fetch step 12.1.1.3 + const codings = headers.get('Content-Encoding'); + + // HTTP-network fetch step 12.1.1.4: handle content codings + + // in following scenarios we ignore compression support + // 1. compression support is disabled + // 2. HEAD request + // 3. no Content-Encoding header + // 4. no content response (204) + // 5. content not modified response (304) + if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) { + response = new Response(body, response_options); + resolve(response); + return; + } + + // For Node v6+ + // Be less strict when decoding compressed responses, since sometimes + // servers send slightly invalid responses that are still accepted + // by common browsers. + // Always using Z_SYNC_FLUSH is what cURL does. + const zlibOptions = { + flush: zlib.Z_SYNC_FLUSH, + finishFlush: zlib.Z_SYNC_FLUSH + }; + + // for gzip + if (codings == 'gzip' || codings == 'x-gzip') { + body = body.pipe(zlib.createGunzip(zlibOptions)); + response = new Response(body, response_options); + resolve(response); + return; + } + + // for deflate + if (codings == 'deflate' || codings == 'x-deflate') { + // handle the infamous raw deflate response from old servers + // a hack for old IIS and Apache servers + const raw = res.pipe(new PassThrough$1()); + raw.once('data', function (chunk) { + // see http://stackoverflow.com/questions/37519828 + if ((chunk[0] & 0x0F) === 0x08) { + body = body.pipe(zlib.createInflate()); + } else { + body = body.pipe(zlib.createInflateRaw()); + } + response = new Response(body, response_options); + resolve(response); + }); + raw.on('end', function () { + // some old IIS servers return zero-length OK deflate responses, so 'data' is never emitted. + if (!response) { + response = new Response(body, response_options); + resolve(response); + } + }); + return; + } + + // for br + if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') { + body = body.pipe(zlib.createBrotliDecompress()); + response = new Response(body, response_options); + resolve(response); + return; + } + + // otherwise, use response as-is + response = new Response(body, response_options); + resolve(response); + }); + + writeToStream(req, request); + }); +} +function fixResponseChunkedTransferBadEnding(request, errorCallback) { + let socket; + + request.on('socket', function (s) { + socket = s; + }); + + request.on('response', function (response) { + const headers = response.headers; + + if (headers['transfer-encoding'] === 'chunked' && !headers['content-length']) { + response.once('close', function (hadError) { + // tests for socket presence, as in some situations the + // the 'socket' event is not triggered for the request + // (happens in deno), avoids `TypeError` + // if a data listener is still present we didn't end cleanly + const hasDataListener = socket && socket.listenerCount('data') > 0; + + if (hasDataListener && !hadError) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + errorCallback(err); + } + }); + } + }); +} + +function destroyStream(stream, err) { + if (stream.destroy) { + stream.destroy(err); + } else { + // node < 8 + stream.emit('error', err); + stream.end(); + } +} + +/** + * Redirect code matching + * + * @param Number code Status code + * @return Boolean + */ +fetch.isRedirect = function (code) { + return code === 301 || code === 302 || code === 303 || code === 307 || code === 308; +}; + +// expose Promise +fetch.Promise = global.Promise; + +export default fetch; +export { Headers, Request, Response, FetchError, AbortError }; diff --git a/backend/node_modules/node-fetch/lib/index.js b/backend/node_modules/node-fetch/lib/index.js new file mode 100644 index 0000000000000000000000000000000000000000..567ff5da58e83683bec0ea9e86221041ddf9435f --- /dev/null +++ b/backend/node_modules/node-fetch/lib/index.js @@ -0,0 +1,1787 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } + +var Stream = _interopDefault(require('stream')); +var http = _interopDefault(require('http')); +var Url = _interopDefault(require('url')); +var whatwgUrl = _interopDefault(require('whatwg-url')); +var https = _interopDefault(require('https')); +var zlib = _interopDefault(require('zlib')); + +// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js + +// fix for "Readable" isn't a named export issue +const Readable = Stream.Readable; + +const BUFFER = Symbol('buffer'); +const TYPE = Symbol('type'); + +class Blob { + constructor() { + this[TYPE] = ''; + + const blobParts = arguments[0]; + const options = arguments[1]; + + const buffers = []; + let size = 0; + + if (blobParts) { + const a = blobParts; + const length = Number(a.length); + for (let i = 0; i < length; i++) { + const element = a[i]; + let buffer; + if (element instanceof Buffer) { + buffer = element; + } else if (ArrayBuffer.isView(element)) { + buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength); + } else if (element instanceof ArrayBuffer) { + buffer = Buffer.from(element); + } else if (element instanceof Blob) { + buffer = element[BUFFER]; + } else { + buffer = Buffer.from(typeof element === 'string' ? element : String(element)); + } + size += buffer.length; + buffers.push(buffer); + } + } + + this[BUFFER] = Buffer.concat(buffers); + + let type = options && options.type !== undefined && String(options.type).toLowerCase(); + if (type && !/[^\u0020-\u007E]/.test(type)) { + this[TYPE] = type; + } + } + get size() { + return this[BUFFER].length; + } + get type() { + return this[TYPE]; + } + text() { + return Promise.resolve(this[BUFFER].toString()); + } + arrayBuffer() { + const buf = this[BUFFER]; + const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + return Promise.resolve(ab); + } + stream() { + const readable = new Readable(); + readable._read = function () {}; + readable.push(this[BUFFER]); + readable.push(null); + return readable; + } + toString() { + return '[object Blob]'; + } + slice() { + const size = this.size; + + const start = arguments[0]; + const end = arguments[1]; + let relativeStart, relativeEnd; + if (start === undefined) { + relativeStart = 0; + } else if (start < 0) { + relativeStart = Math.max(size + start, 0); + } else { + relativeStart = Math.min(start, size); + } + if (end === undefined) { + relativeEnd = size; + } else if (end < 0) { + relativeEnd = Math.max(size + end, 0); + } else { + relativeEnd = Math.min(end, size); + } + const span = Math.max(relativeEnd - relativeStart, 0); + + const buffer = this[BUFFER]; + const slicedBuffer = buffer.slice(relativeStart, relativeStart + span); + const blob = new Blob([], { type: arguments[2] }); + blob[BUFFER] = slicedBuffer; + return blob; + } +} + +Object.defineProperties(Blob.prototype, { + size: { enumerable: true }, + type: { enumerable: true }, + slice: { enumerable: true } +}); + +Object.defineProperty(Blob.prototype, Symbol.toStringTag, { + value: 'Blob', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * fetch-error.js + * + * FetchError interface for operational errors + */ + +/** + * Create FetchError instance + * + * @param String message Error message for human + * @param String type Error type for machine + * @param String systemError For Node.js system error + * @return FetchError + */ +function FetchError(message, type, systemError) { + Error.call(this, message); + + this.message = message; + this.type = type; + + // when err.type is `system`, err.code contains system error code + if (systemError) { + this.code = this.errno = systemError.code; + } + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +FetchError.prototype = Object.create(Error.prototype); +FetchError.prototype.constructor = FetchError; +FetchError.prototype.name = 'FetchError'; + +let convert; +try { + convert = require('encoding').convert; +} catch (e) {} + +const INTERNALS = Symbol('Body internals'); + +// fix an issue where "PassThrough" isn't a named export for node <10 +const PassThrough = Stream.PassThrough; + +/** + * Body mixin + * + * Ref: https://fetch.spec.whatwg.org/#body + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +function Body(body) { + var _this = this; + + var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + _ref$size = _ref.size; + + let size = _ref$size === undefined ? 0 : _ref$size; + var _ref$timeout = _ref.timeout; + let timeout = _ref$timeout === undefined ? 0 : _ref$timeout; + + if (body == null) { + // body is undefined or null + body = null; + } else if (isURLSearchParams(body)) { + // body is a URLSearchParams + body = Buffer.from(body.toString()); + } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { + // body is ArrayBuffer + body = Buffer.from(body); + } else if (ArrayBuffer.isView(body)) { + // body is ArrayBufferView + body = Buffer.from(body.buffer, body.byteOffset, body.byteLength); + } else if (body instanceof Stream) ; else { + // none of the above + // coerce to string then buffer + body = Buffer.from(String(body)); + } + this[INTERNALS] = { + body, + disturbed: false, + error: null + }; + this.size = size; + this.timeout = timeout; + + if (body instanceof Stream) { + body.on('error', function (err) { + const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err); + _this[INTERNALS].error = error; + }); + } +} + +Body.prototype = { + get body() { + return this[INTERNALS].body; + }, + + get bodyUsed() { + return this[INTERNALS].disturbed; + }, + + /** + * Decode response as ArrayBuffer + * + * @return Promise + */ + arrayBuffer() { + return consumeBody.call(this).then(function (buf) { + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + }); + }, + + /** + * Return raw response as Blob + * + * @return Promise + */ + blob() { + let ct = this.headers && this.headers.get('content-type') || ''; + return consumeBody.call(this).then(function (buf) { + return Object.assign( + // Prevent copying + new Blob([], { + type: ct.toLowerCase() + }), { + [BUFFER]: buf + }); + }); + }, + + /** + * Decode response as json + * + * @return Promise + */ + json() { + var _this2 = this; + + return consumeBody.call(this).then(function (buffer) { + try { + return JSON.parse(buffer.toString()); + } catch (err) { + return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json')); + } + }); + }, + + /** + * Decode response as text + * + * @return Promise + */ + text() { + return consumeBody.call(this).then(function (buffer) { + return buffer.toString(); + }); + }, + + /** + * Decode response as buffer (non-spec api) + * + * @return Promise + */ + buffer() { + return consumeBody.call(this); + }, + + /** + * Decode response as text, while automatically detecting the encoding and + * trying to decode to UTF-8 (non-spec api) + * + * @return Promise + */ + textConverted() { + var _this3 = this; + + return consumeBody.call(this).then(function (buffer) { + return convertBody(buffer, _this3.headers); + }); + } +}; + +// In browsers, all properties are enumerable. +Object.defineProperties(Body.prototype, { + body: { enumerable: true }, + bodyUsed: { enumerable: true }, + arrayBuffer: { enumerable: true }, + blob: { enumerable: true }, + json: { enumerable: true }, + text: { enumerable: true } +}); + +Body.mixIn = function (proto) { + for (const name of Object.getOwnPropertyNames(Body.prototype)) { + // istanbul ignore else: future proof + if (!(name in proto)) { + const desc = Object.getOwnPropertyDescriptor(Body.prototype, name); + Object.defineProperty(proto, name, desc); + } + } +}; + +/** + * Consume and convert an entire Body to a Buffer. + * + * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body + * + * @return Promise + */ +function consumeBody() { + var _this4 = this; + + if (this[INTERNALS].disturbed) { + return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`)); + } + + this[INTERNALS].disturbed = true; + + if (this[INTERNALS].error) { + return Body.Promise.reject(this[INTERNALS].error); + } + + let body = this.body; + + // body is null + if (body === null) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is blob + if (isBlob(body)) { + body = body.stream(); + } + + // body is buffer + if (Buffer.isBuffer(body)) { + return Body.Promise.resolve(body); + } + + // istanbul ignore if: should never happen + if (!(body instanceof Stream)) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is stream + // get ready to actually consume the body + let accum = []; + let accumBytes = 0; + let abort = false; + + return new Body.Promise(function (resolve, reject) { + let resTimeout; + + // allow timeout on slow response body + if (_this4.timeout) { + resTimeout = setTimeout(function () { + abort = true; + reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout')); + }, _this4.timeout); + } + + // handle stream errors + body.on('error', function (err) { + if (err.name === 'AbortError') { + // if the request was aborted, reject with this Error + abort = true; + reject(err); + } else { + // other errors, such as incorrect content-encoding + reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + + body.on('data', function (chunk) { + if (abort || chunk === null) { + return; + } + + if (_this4.size && accumBytes + chunk.length > _this4.size) { + abort = true; + reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size')); + return; + } + + accumBytes += chunk.length; + accum.push(chunk); + }); + + body.on('end', function () { + if (abort) { + return; + } + + clearTimeout(resTimeout); + + try { + resolve(Buffer.concat(accum, accumBytes)); + } catch (err) { + // handle streams that have accumulated too much data (issue #414) + reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + }); +} + +/** + * Detect buffer encoding and convert to target encoding + * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding + * + * @param Buffer buffer Incoming buffer + * @param String encoding Target encoding + * @return String + */ +function convertBody(buffer, headers) { + if (typeof convert !== 'function') { + throw new Error('The package `encoding` must be installed to use the textConverted() function'); + } + + const ct = headers.get('content-type'); + let charset = 'utf-8'; + let res, str; + + // header + if (ct) { + res = /charset=([^;]*)/i.exec(ct); + } + + // no charset in content type, peek at response body for at most 1024 bytes + str = buffer.slice(0, 1024).toString(); + + // html5 + if (!res && str) { + res = / 0 && arguments[0] !== undefined ? arguments[0] : undefined; + + this[MAP] = Object.create(null); + + if (init instanceof Headers) { + const rawHeaders = init.raw(); + const headerNames = Object.keys(rawHeaders); + + for (const headerName of headerNames) { + for (const value of rawHeaders[headerName]) { + this.append(headerName, value); + } + } + + return; + } + + // We don't worry about converting prop to ByteString here as append() + // will handle it. + if (init == null) ; else if (typeof init === 'object') { + const method = init[Symbol.iterator]; + if (method != null) { + if (typeof method !== 'function') { + throw new TypeError('Header pairs must be iterable'); + } + + // sequence> + // Note: per spec we have to first exhaust the lists then process them + const pairs = []; + for (const pair of init) { + if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') { + throw new TypeError('Each header pair must be iterable'); + } + pairs.push(Array.from(pair)); + } + + for (const pair of pairs) { + if (pair.length !== 2) { + throw new TypeError('Each header pair must be a name/value tuple'); + } + this.append(pair[0], pair[1]); + } + } else { + // record + for (const key of Object.keys(init)) { + const value = init[key]; + this.append(key, value); + } + } + } else { + throw new TypeError('Provided initializer must be an object'); + } + } + + /** + * Return combined header value given name + * + * @param String name Header name + * @return Mixed + */ + get(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key === undefined) { + return null; + } + + return this[MAP][key].join(', '); + } + + /** + * Iterate over all headers + * + * @param Function callback Executed for each item with parameters (value, name, thisArg) + * @param Boolean thisArg `this` context for callback function + * @return Void + */ + forEach(callback) { + let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; + + let pairs = getHeaders(this); + let i = 0; + while (i < pairs.length) { + var _pairs$i = pairs[i]; + const name = _pairs$i[0], + value = _pairs$i[1]; + + callback.call(thisArg, value, name, this); + pairs = getHeaders(this); + i++; + } + } + + /** + * Overwrite header values given name + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + set(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + this[MAP][key !== undefined ? key : name] = [value]; + } + + /** + * Append a value onto existing header + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + append(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + if (key !== undefined) { + this[MAP][key].push(value); + } else { + this[MAP][name] = [value]; + } + } + + /** + * Check for header name existence + * + * @param String name Header name + * @return Boolean + */ + has(name) { + name = `${name}`; + validateName(name); + return find(this[MAP], name) !== undefined; + } + + /** + * Delete all header values given name + * + * @param String name Header name + * @return Void + */ + delete(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key !== undefined) { + delete this[MAP][key]; + } + } + + /** + * Return raw headers (non-spec api) + * + * @return Object + */ + raw() { + return this[MAP]; + } + + /** + * Get an iterator on keys. + * + * @return Iterator + */ + keys() { + return createHeadersIterator(this, 'key'); + } + + /** + * Get an iterator on values. + * + * @return Iterator + */ + values() { + return createHeadersIterator(this, 'value'); + } + + /** + * Get an iterator on entries. + * + * This is the default iterator of the Headers object. + * + * @return Iterator + */ + [Symbol.iterator]() { + return createHeadersIterator(this, 'key+value'); + } +} +Headers.prototype.entries = Headers.prototype[Symbol.iterator]; + +Object.defineProperty(Headers.prototype, Symbol.toStringTag, { + value: 'Headers', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Headers.prototype, { + get: { enumerable: true }, + forEach: { enumerable: true }, + set: { enumerable: true }, + append: { enumerable: true }, + has: { enumerable: true }, + delete: { enumerable: true }, + keys: { enumerable: true }, + values: { enumerable: true }, + entries: { enumerable: true } +}); + +function getHeaders(headers) { + let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value'; + + const keys = Object.keys(headers[MAP]).sort(); + return keys.map(kind === 'key' ? function (k) { + return k.toLowerCase(); + } : kind === 'value' ? function (k) { + return headers[MAP][k].join(', '); + } : function (k) { + return [k.toLowerCase(), headers[MAP][k].join(', ')]; + }); +} + +const INTERNAL = Symbol('internal'); + +function createHeadersIterator(target, kind) { + const iterator = Object.create(HeadersIteratorPrototype); + iterator[INTERNAL] = { + target, + kind, + index: 0 + }; + return iterator; +} + +const HeadersIteratorPrototype = Object.setPrototypeOf({ + next() { + // istanbul ignore if + if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) { + throw new TypeError('Value of `this` is not a HeadersIterator'); + } + + var _INTERNAL = this[INTERNAL]; + const target = _INTERNAL.target, + kind = _INTERNAL.kind, + index = _INTERNAL.index; + + const values = getHeaders(target, kind); + const len = values.length; + if (index >= len) { + return { + value: undefined, + done: true + }; + } + + this[INTERNAL].index = index + 1; + + return { + value: values[index], + done: false + }; + } +}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))); + +Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, { + value: 'HeadersIterator', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * Export the Headers object in a form that Node.js can consume. + * + * @param Headers headers + * @return Object + */ +function exportNodeCompatibleHeaders(headers) { + const obj = Object.assign({ __proto__: null }, headers[MAP]); + + // http.request() only supports string as Host header. This hack makes + // specifying custom Host header possible. + const hostHeaderKey = find(headers[MAP], 'Host'); + if (hostHeaderKey !== undefined) { + obj[hostHeaderKey] = obj[hostHeaderKey][0]; + } + + return obj; +} + +/** + * Create a Headers object from an object of headers, ignoring those that do + * not conform to HTTP grammar productions. + * + * @param Object obj Object of headers + * @return Headers + */ +function createHeadersLenient(obj) { + const headers = new Headers(); + for (const name of Object.keys(obj)) { + if (invalidTokenRegex.test(name)) { + continue; + } + if (Array.isArray(obj[name])) { + for (const val of obj[name]) { + if (invalidHeaderCharRegex.test(val)) { + continue; + } + if (headers[MAP][name] === undefined) { + headers[MAP][name] = [val]; + } else { + headers[MAP][name].push(val); + } + } + } else if (!invalidHeaderCharRegex.test(obj[name])) { + headers[MAP][name] = [obj[name]]; + } + } + return headers; +} + +const INTERNALS$1 = Symbol('Response internals'); + +// fix an issue where "STATUS_CODES" aren't a named export for node <10 +const STATUS_CODES = http.STATUS_CODES; + +/** + * Response class + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +class Response { + constructor() { + let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + Body.call(this, body, opts); + + const status = opts.status || 200; + const headers = new Headers(opts.headers); + + if (body != null && !headers.has('Content-Type')) { + const contentType = extractContentType(body); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + this[INTERNALS$1] = { + url: opts.url, + status, + statusText: opts.statusText || STATUS_CODES[status], + headers, + counter: opts.counter + }; + } + + get url() { + return this[INTERNALS$1].url || ''; + } + + get status() { + return this[INTERNALS$1].status; + } + + /** + * Convenience property representing if the request ended normally + */ + get ok() { + return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; + } + + get redirected() { + return this[INTERNALS$1].counter > 0; + } + + get statusText() { + return this[INTERNALS$1].statusText; + } + + get headers() { + return this[INTERNALS$1].headers; + } + + /** + * Clone this response + * + * @return Response + */ + clone() { + return new Response(clone(this), { + url: this.url, + status: this.status, + statusText: this.statusText, + headers: this.headers, + ok: this.ok, + redirected: this.redirected + }); + } +} + +Body.mixIn(Response.prototype); + +Object.defineProperties(Response.prototype, { + url: { enumerable: true }, + status: { enumerable: true }, + ok: { enumerable: true }, + redirected: { enumerable: true }, + statusText: { enumerable: true }, + headers: { enumerable: true }, + clone: { enumerable: true } +}); + +Object.defineProperty(Response.prototype, Symbol.toStringTag, { + value: 'Response', + writable: false, + enumerable: false, + configurable: true +}); + +const INTERNALS$2 = Symbol('Request internals'); +const URL = Url.URL || whatwgUrl.URL; + +// fix an issue where "format", "parse" aren't a named export for node <10 +const parse_url = Url.parse; +const format_url = Url.format; + +/** + * Wrapper around `new URL` to handle arbitrary URLs + * + * @param {string} urlStr + * @return {void} + */ +function parseURL(urlStr) { + /* + Check whether the URL is absolute or not + Scheme: https://tools.ietf.org/html/rfc3986#section-3.1 + Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3 + */ + if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) { + urlStr = new URL(urlStr).toString(); + } + + // Fallback to old implementation for arbitrary URLs + return parse_url(urlStr); +} + +const streamDestructionSupported = 'destroy' in Stream.Readable.prototype; + +/** + * Check if a value is an instance of Request. + * + * @param Mixed input + * @return Boolean + */ +function isRequest(input) { + return typeof input === 'object' && typeof input[INTERNALS$2] === 'object'; +} + +function isAbortSignal(signal) { + const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal); + return !!(proto && proto.constructor.name === 'AbortSignal'); +} + +/** + * Request class + * + * @param Mixed input Url or Request instance + * @param Object init Custom options + * @return Void + */ +class Request { + constructor(input) { + let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + let parsedURL; + + // normalize input + if (!isRequest(input)) { + if (input && input.href) { + // in order to support Node.js' Url objects; though WHATWG's URL objects + // will fall into this branch also (since their `toString()` will return + // `href` property anyway) + parsedURL = parseURL(input.href); + } else { + // coerce input to a string before attempting to parse + parsedURL = parseURL(`${input}`); + } + input = {}; + } else { + parsedURL = parseURL(input.url); + } + + let method = init.method || input.method || 'GET'; + method = method.toUpperCase(); + + if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { + throw new TypeError('Request with GET/HEAD method cannot have body'); + } + + let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; + + Body.call(this, inputBody, { + timeout: init.timeout || input.timeout || 0, + size: init.size || input.size || 0 + }); + + const headers = new Headers(init.headers || input.headers || {}); + + if (inputBody != null && !headers.has('Content-Type')) { + const contentType = extractContentType(inputBody); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + let signal = isRequest(input) ? input.signal : null; + if ('signal' in init) signal = init.signal; + + if (signal != null && !isAbortSignal(signal)) { + throw new TypeError('Expected signal to be an instanceof AbortSignal'); + } + + this[INTERNALS$2] = { + method, + redirect: init.redirect || input.redirect || 'follow', + headers, + parsedURL, + signal + }; + + // node-fetch-only options + this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20; + this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true; + this.counter = init.counter || input.counter || 0; + this.agent = init.agent || input.agent; + } + + get method() { + return this[INTERNALS$2].method; + } + + get url() { + return format_url(this[INTERNALS$2].parsedURL); + } + + get headers() { + return this[INTERNALS$2].headers; + } + + get redirect() { + return this[INTERNALS$2].redirect; + } + + get signal() { + return this[INTERNALS$2].signal; + } + + /** + * Clone this request + * + * @return Request + */ + clone() { + return new Request(this); + } +} + +Body.mixIn(Request.prototype); + +Object.defineProperty(Request.prototype, Symbol.toStringTag, { + value: 'Request', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Request.prototype, { + method: { enumerable: true }, + url: { enumerable: true }, + headers: { enumerable: true }, + redirect: { enumerable: true }, + clone: { enumerable: true }, + signal: { enumerable: true } +}); + +/** + * Convert a Request to Node.js http request options. + * + * @param Request A Request instance + * @return Object The options object to be passed to http.request + */ +function getNodeRequestOptions(request) { + const parsedURL = request[INTERNALS$2].parsedURL; + const headers = new Headers(request[INTERNALS$2].headers); + + // fetch step 1.3 + if (!headers.has('Accept')) { + headers.set('Accept', '*/*'); + } + + // Basic fetch + if (!parsedURL.protocol || !parsedURL.hostname) { + throw new TypeError('Only absolute URLs are supported'); + } + + if (!/^https?:$/.test(parsedURL.protocol)) { + throw new TypeError('Only HTTP(S) protocols are supported'); + } + + if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) { + throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8'); + } + + // HTTP-network-or-cache fetch steps 2.4-2.7 + let contentLengthValue = null; + if (request.body == null && /^(POST|PUT)$/i.test(request.method)) { + contentLengthValue = '0'; + } + if (request.body != null) { + const totalBytes = getTotalBytes(request); + if (typeof totalBytes === 'number') { + contentLengthValue = String(totalBytes); + } + } + if (contentLengthValue) { + headers.set('Content-Length', contentLengthValue); + } + + // HTTP-network-or-cache fetch step 2.11 + if (!headers.has('User-Agent')) { + headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)'); + } + + // HTTP-network-or-cache fetch step 2.15 + if (request.compress && !headers.has('Accept-Encoding')) { + headers.set('Accept-Encoding', 'gzip,deflate'); + } + + let agent = request.agent; + if (typeof agent === 'function') { + agent = agent(parsedURL); + } + + // HTTP-network fetch step 4.2 + // chunked encoding is handled by Node.js + + return Object.assign({}, parsedURL, { + method: request.method, + headers: exportNodeCompatibleHeaders(headers), + agent + }); +} + +/** + * abort-error.js + * + * AbortError interface for cancelled requests + */ + +/** + * Create AbortError instance + * + * @param String message Error message for human + * @return AbortError + */ +function AbortError(message) { + Error.call(this, message); + + this.type = 'aborted'; + this.message = message; + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +AbortError.prototype = Object.create(Error.prototype); +AbortError.prototype.constructor = AbortError; +AbortError.prototype.name = 'AbortError'; + +const URL$1 = Url.URL || whatwgUrl.URL; + +// fix an issue where "PassThrough", "resolve" aren't a named export for node <10 +const PassThrough$1 = Stream.PassThrough; + +const isDomainOrSubdomain = function isDomainOrSubdomain(destination, original) { + const orig = new URL$1(original).hostname; + const dest = new URL$1(destination).hostname; + + return orig === dest || orig[orig.length - dest.length - 1] === '.' && orig.endsWith(dest); +}; + +/** + * isSameProtocol reports whether the two provided URLs use the same protocol. + * + * Both domains must already be in canonical form. + * @param {string|URL} original + * @param {string|URL} destination + */ +const isSameProtocol = function isSameProtocol(destination, original) { + const orig = new URL$1(original).protocol; + const dest = new URL$1(destination).protocol; + + return orig === dest; +}; + +/** + * Fetch function + * + * @param Mixed url Absolute url or Request instance + * @param Object opts Fetch options + * @return Promise + */ +function fetch(url, opts) { + + // allow custom promise + if (!fetch.Promise) { + throw new Error('native promise missing, set fetch.Promise to your favorite alternative'); + } + + Body.Promise = fetch.Promise; + + // wrap http.request into fetch + return new fetch.Promise(function (resolve, reject) { + // build request object + const request = new Request(url, opts); + const options = getNodeRequestOptions(request); + + const send = (options.protocol === 'https:' ? https : http).request; + const signal = request.signal; + + let response = null; + + const abort = function abort() { + let error = new AbortError('The user aborted a request.'); + reject(error); + if (request.body && request.body instanceof Stream.Readable) { + destroyStream(request.body, error); + } + if (!response || !response.body) return; + response.body.emit('error', error); + }; + + if (signal && signal.aborted) { + abort(); + return; + } + + const abortAndFinalize = function abortAndFinalize() { + abort(); + finalize(); + }; + + // send request + const req = send(options); + let reqTimeout; + + if (signal) { + signal.addEventListener('abort', abortAndFinalize); + } + + function finalize() { + req.abort(); + if (signal) signal.removeEventListener('abort', abortAndFinalize); + clearTimeout(reqTimeout); + } + + if (request.timeout) { + req.once('socket', function (socket) { + reqTimeout = setTimeout(function () { + reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout')); + finalize(); + }, request.timeout); + }); + } + + req.on('error', function (err) { + reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); + + if (response && response.body) { + destroyStream(response.body, err); + } + + finalize(); + }); + + fixResponseChunkedTransferBadEnding(req, function (err) { + if (signal && signal.aborted) { + return; + } + + if (response && response.body) { + destroyStream(response.body, err); + } + }); + + /* c8 ignore next 18 */ + if (parseInt(process.version.substring(1)) < 14) { + // Before Node.js 14, pipeline() does not fully support async iterators and does not always + // properly handle when the socket close/end events are out of order. + req.on('socket', function (s) { + s.addListener('close', function (hadError) { + // if a data listener is still present we didn't end cleanly + const hasDataListener = s.listenerCount('data') > 0; + + // if end happened before close but the socket didn't emit an error, do it now + if (response && hasDataListener && !hadError && !(signal && signal.aborted)) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + response.body.emit('error', err); + } + }); + }); + } + + req.on('response', function (res) { + clearTimeout(reqTimeout); + + const headers = createHeadersLenient(res.headers); + + // HTTP fetch step 5 + if (fetch.isRedirect(res.statusCode)) { + // HTTP fetch step 5.2 + const location = headers.get('Location'); + + // HTTP fetch step 5.3 + let locationURL = null; + try { + locationURL = location === null ? null : new URL$1(location, request.url).toString(); + } catch (err) { + // error here can only be invalid URL in Location: header + // do not throw when options.redirect == manual + // let the user extract the errorneous redirect URL + if (request.redirect !== 'manual') { + reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect')); + finalize(); + return; + } + } + + // HTTP fetch step 5.5 + switch (request.redirect) { + case 'error': + reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect')); + finalize(); + return; + case 'manual': + // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL. + if (locationURL !== null) { + // handle corrupted header + try { + headers.set('Location', locationURL); + } catch (err) { + // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request + reject(err); + } + } + break; + case 'follow': + // HTTP-redirect fetch step 2 + if (locationURL === null) { + break; + } + + // HTTP-redirect fetch step 5 + if (request.counter >= request.follow) { + reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 6 (counter increment) + // Create a new Request object. + const requestOpts = { + headers: new Headers(request.headers), + follow: request.follow, + counter: request.counter + 1, + agent: request.agent, + compress: request.compress, + method: request.method, + body: request.body, + signal: request.signal, + timeout: request.timeout, + size: request.size + }; + + if (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) { + for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) { + requestOpts.headers.delete(name); + } + } + + // HTTP-redirect fetch step 9 + if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) { + reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 11 + if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') { + requestOpts.method = 'GET'; + requestOpts.body = undefined; + requestOpts.headers.delete('content-length'); + } + + // HTTP-redirect fetch step 15 + resolve(fetch(new Request(locationURL, requestOpts))); + finalize(); + return; + } + } + + // prepare response + res.once('end', function () { + if (signal) signal.removeEventListener('abort', abortAndFinalize); + }); + let body = res.pipe(new PassThrough$1()); + + const response_options = { + url: request.url, + status: res.statusCode, + statusText: res.statusMessage, + headers: headers, + size: request.size, + timeout: request.timeout, + counter: request.counter + }; + + // HTTP-network fetch step 12.1.1.3 + const codings = headers.get('Content-Encoding'); + + // HTTP-network fetch step 12.1.1.4: handle content codings + + // in following scenarios we ignore compression support + // 1. compression support is disabled + // 2. HEAD request + // 3. no Content-Encoding header + // 4. no content response (204) + // 5. content not modified response (304) + if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) { + response = new Response(body, response_options); + resolve(response); + return; + } + + // For Node v6+ + // Be less strict when decoding compressed responses, since sometimes + // servers send slightly invalid responses that are still accepted + // by common browsers. + // Always using Z_SYNC_FLUSH is what cURL does. + const zlibOptions = { + flush: zlib.Z_SYNC_FLUSH, + finishFlush: zlib.Z_SYNC_FLUSH + }; + + // for gzip + if (codings == 'gzip' || codings == 'x-gzip') { + body = body.pipe(zlib.createGunzip(zlibOptions)); + response = new Response(body, response_options); + resolve(response); + return; + } + + // for deflate + if (codings == 'deflate' || codings == 'x-deflate') { + // handle the infamous raw deflate response from old servers + // a hack for old IIS and Apache servers + const raw = res.pipe(new PassThrough$1()); + raw.once('data', function (chunk) { + // see http://stackoverflow.com/questions/37519828 + if ((chunk[0] & 0x0F) === 0x08) { + body = body.pipe(zlib.createInflate()); + } else { + body = body.pipe(zlib.createInflateRaw()); + } + response = new Response(body, response_options); + resolve(response); + }); + raw.on('end', function () { + // some old IIS servers return zero-length OK deflate responses, so 'data' is never emitted. + if (!response) { + response = new Response(body, response_options); + resolve(response); + } + }); + return; + } + + // for br + if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') { + body = body.pipe(zlib.createBrotliDecompress()); + response = new Response(body, response_options); + resolve(response); + return; + } + + // otherwise, use response as-is + response = new Response(body, response_options); + resolve(response); + }); + + writeToStream(req, request); + }); +} +function fixResponseChunkedTransferBadEnding(request, errorCallback) { + let socket; + + request.on('socket', function (s) { + socket = s; + }); + + request.on('response', function (response) { + const headers = response.headers; + + if (headers['transfer-encoding'] === 'chunked' && !headers['content-length']) { + response.once('close', function (hadError) { + // tests for socket presence, as in some situations the + // the 'socket' event is not triggered for the request + // (happens in deno), avoids `TypeError` + // if a data listener is still present we didn't end cleanly + const hasDataListener = socket && socket.listenerCount('data') > 0; + + if (hasDataListener && !hadError) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + errorCallback(err); + } + }); + } + }); +} + +function destroyStream(stream, err) { + if (stream.destroy) { + stream.destroy(err); + } else { + // node < 8 + stream.emit('error', err); + stream.end(); + } +} + +/** + * Redirect code matching + * + * @param Number code Status code + * @return Boolean + */ +fetch.isRedirect = function (code) { + return code === 301 || code === 302 || code === 303 || code === 307 || code === 308; +}; + +// expose Promise +fetch.Promise = global.Promise; + +module.exports = exports = fetch; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = exports; +exports.Headers = Headers; +exports.Request = Request; +exports.Response = Response; +exports.FetchError = FetchError; +exports.AbortError = AbortError; diff --git a/backend/node_modules/node-fetch/lib/index.mjs b/backend/node_modules/node-fetch/lib/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..2863dd9c318754a77c6bfb57ec5e7db8759abd8b --- /dev/null +++ b/backend/node_modules/node-fetch/lib/index.mjs @@ -0,0 +1,1775 @@ +import Stream from 'stream'; +import http from 'http'; +import Url from 'url'; +import whatwgUrl from 'whatwg-url'; +import https from 'https'; +import zlib from 'zlib'; + +// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js + +// fix for "Readable" isn't a named export issue +const Readable = Stream.Readable; + +const BUFFER = Symbol('buffer'); +const TYPE = Symbol('type'); + +class Blob { + constructor() { + this[TYPE] = ''; + + const blobParts = arguments[0]; + const options = arguments[1]; + + const buffers = []; + let size = 0; + + if (blobParts) { + const a = blobParts; + const length = Number(a.length); + for (let i = 0; i < length; i++) { + const element = a[i]; + let buffer; + if (element instanceof Buffer) { + buffer = element; + } else if (ArrayBuffer.isView(element)) { + buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength); + } else if (element instanceof ArrayBuffer) { + buffer = Buffer.from(element); + } else if (element instanceof Blob) { + buffer = element[BUFFER]; + } else { + buffer = Buffer.from(typeof element === 'string' ? element : String(element)); + } + size += buffer.length; + buffers.push(buffer); + } + } + + this[BUFFER] = Buffer.concat(buffers); + + let type = options && options.type !== undefined && String(options.type).toLowerCase(); + if (type && !/[^\u0020-\u007E]/.test(type)) { + this[TYPE] = type; + } + } + get size() { + return this[BUFFER].length; + } + get type() { + return this[TYPE]; + } + text() { + return Promise.resolve(this[BUFFER].toString()); + } + arrayBuffer() { + const buf = this[BUFFER]; + const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + return Promise.resolve(ab); + } + stream() { + const readable = new Readable(); + readable._read = function () {}; + readable.push(this[BUFFER]); + readable.push(null); + return readable; + } + toString() { + return '[object Blob]'; + } + slice() { + const size = this.size; + + const start = arguments[0]; + const end = arguments[1]; + let relativeStart, relativeEnd; + if (start === undefined) { + relativeStart = 0; + } else if (start < 0) { + relativeStart = Math.max(size + start, 0); + } else { + relativeStart = Math.min(start, size); + } + if (end === undefined) { + relativeEnd = size; + } else if (end < 0) { + relativeEnd = Math.max(size + end, 0); + } else { + relativeEnd = Math.min(end, size); + } + const span = Math.max(relativeEnd - relativeStart, 0); + + const buffer = this[BUFFER]; + const slicedBuffer = buffer.slice(relativeStart, relativeStart + span); + const blob = new Blob([], { type: arguments[2] }); + blob[BUFFER] = slicedBuffer; + return blob; + } +} + +Object.defineProperties(Blob.prototype, { + size: { enumerable: true }, + type: { enumerable: true }, + slice: { enumerable: true } +}); + +Object.defineProperty(Blob.prototype, Symbol.toStringTag, { + value: 'Blob', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * fetch-error.js + * + * FetchError interface for operational errors + */ + +/** + * Create FetchError instance + * + * @param String message Error message for human + * @param String type Error type for machine + * @param String systemError For Node.js system error + * @return FetchError + */ +function FetchError(message, type, systemError) { + Error.call(this, message); + + this.message = message; + this.type = type; + + // when err.type is `system`, err.code contains system error code + if (systemError) { + this.code = this.errno = systemError.code; + } + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +FetchError.prototype = Object.create(Error.prototype); +FetchError.prototype.constructor = FetchError; +FetchError.prototype.name = 'FetchError'; + +let convert; +try { + convert = require('encoding').convert; +} catch (e) {} + +const INTERNALS = Symbol('Body internals'); + +// fix an issue where "PassThrough" isn't a named export for node <10 +const PassThrough = Stream.PassThrough; + +/** + * Body mixin + * + * Ref: https://fetch.spec.whatwg.org/#body + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +function Body(body) { + var _this = this; + + var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + _ref$size = _ref.size; + + let size = _ref$size === undefined ? 0 : _ref$size; + var _ref$timeout = _ref.timeout; + let timeout = _ref$timeout === undefined ? 0 : _ref$timeout; + + if (body == null) { + // body is undefined or null + body = null; + } else if (isURLSearchParams(body)) { + // body is a URLSearchParams + body = Buffer.from(body.toString()); + } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { + // body is ArrayBuffer + body = Buffer.from(body); + } else if (ArrayBuffer.isView(body)) { + // body is ArrayBufferView + body = Buffer.from(body.buffer, body.byteOffset, body.byteLength); + } else if (body instanceof Stream) ; else { + // none of the above + // coerce to string then buffer + body = Buffer.from(String(body)); + } + this[INTERNALS] = { + body, + disturbed: false, + error: null + }; + this.size = size; + this.timeout = timeout; + + if (body instanceof Stream) { + body.on('error', function (err) { + const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err); + _this[INTERNALS].error = error; + }); + } +} + +Body.prototype = { + get body() { + return this[INTERNALS].body; + }, + + get bodyUsed() { + return this[INTERNALS].disturbed; + }, + + /** + * Decode response as ArrayBuffer + * + * @return Promise + */ + arrayBuffer() { + return consumeBody.call(this).then(function (buf) { + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + }); + }, + + /** + * Return raw response as Blob + * + * @return Promise + */ + blob() { + let ct = this.headers && this.headers.get('content-type') || ''; + return consumeBody.call(this).then(function (buf) { + return Object.assign( + // Prevent copying + new Blob([], { + type: ct.toLowerCase() + }), { + [BUFFER]: buf + }); + }); + }, + + /** + * Decode response as json + * + * @return Promise + */ + json() { + var _this2 = this; + + return consumeBody.call(this).then(function (buffer) { + try { + return JSON.parse(buffer.toString()); + } catch (err) { + return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json')); + } + }); + }, + + /** + * Decode response as text + * + * @return Promise + */ + text() { + return consumeBody.call(this).then(function (buffer) { + return buffer.toString(); + }); + }, + + /** + * Decode response as buffer (non-spec api) + * + * @return Promise + */ + buffer() { + return consumeBody.call(this); + }, + + /** + * Decode response as text, while automatically detecting the encoding and + * trying to decode to UTF-8 (non-spec api) + * + * @return Promise + */ + textConverted() { + var _this3 = this; + + return consumeBody.call(this).then(function (buffer) { + return convertBody(buffer, _this3.headers); + }); + } +}; + +// In browsers, all properties are enumerable. +Object.defineProperties(Body.prototype, { + body: { enumerable: true }, + bodyUsed: { enumerable: true }, + arrayBuffer: { enumerable: true }, + blob: { enumerable: true }, + json: { enumerable: true }, + text: { enumerable: true } +}); + +Body.mixIn = function (proto) { + for (const name of Object.getOwnPropertyNames(Body.prototype)) { + // istanbul ignore else: future proof + if (!(name in proto)) { + const desc = Object.getOwnPropertyDescriptor(Body.prototype, name); + Object.defineProperty(proto, name, desc); + } + } +}; + +/** + * Consume and convert an entire Body to a Buffer. + * + * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body + * + * @return Promise + */ +function consumeBody() { + var _this4 = this; + + if (this[INTERNALS].disturbed) { + return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`)); + } + + this[INTERNALS].disturbed = true; + + if (this[INTERNALS].error) { + return Body.Promise.reject(this[INTERNALS].error); + } + + let body = this.body; + + // body is null + if (body === null) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is blob + if (isBlob(body)) { + body = body.stream(); + } + + // body is buffer + if (Buffer.isBuffer(body)) { + return Body.Promise.resolve(body); + } + + // istanbul ignore if: should never happen + if (!(body instanceof Stream)) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is stream + // get ready to actually consume the body + let accum = []; + let accumBytes = 0; + let abort = false; + + return new Body.Promise(function (resolve, reject) { + let resTimeout; + + // allow timeout on slow response body + if (_this4.timeout) { + resTimeout = setTimeout(function () { + abort = true; + reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout')); + }, _this4.timeout); + } + + // handle stream errors + body.on('error', function (err) { + if (err.name === 'AbortError') { + // if the request was aborted, reject with this Error + abort = true; + reject(err); + } else { + // other errors, such as incorrect content-encoding + reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + + body.on('data', function (chunk) { + if (abort || chunk === null) { + return; + } + + if (_this4.size && accumBytes + chunk.length > _this4.size) { + abort = true; + reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size')); + return; + } + + accumBytes += chunk.length; + accum.push(chunk); + }); + + body.on('end', function () { + if (abort) { + return; + } + + clearTimeout(resTimeout); + + try { + resolve(Buffer.concat(accum, accumBytes)); + } catch (err) { + // handle streams that have accumulated too much data (issue #414) + reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + }); +} + +/** + * Detect buffer encoding and convert to target encoding + * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding + * + * @param Buffer buffer Incoming buffer + * @param String encoding Target encoding + * @return String + */ +function convertBody(buffer, headers) { + if (typeof convert !== 'function') { + throw new Error('The package `encoding` must be installed to use the textConverted() function'); + } + + const ct = headers.get('content-type'); + let charset = 'utf-8'; + let res, str; + + // header + if (ct) { + res = /charset=([^;]*)/i.exec(ct); + } + + // no charset in content type, peek at response body for at most 1024 bytes + str = buffer.slice(0, 1024).toString(); + + // html5 + if (!res && str) { + res = / 0 && arguments[0] !== undefined ? arguments[0] : undefined; + + this[MAP] = Object.create(null); + + if (init instanceof Headers) { + const rawHeaders = init.raw(); + const headerNames = Object.keys(rawHeaders); + + for (const headerName of headerNames) { + for (const value of rawHeaders[headerName]) { + this.append(headerName, value); + } + } + + return; + } + + // We don't worry about converting prop to ByteString here as append() + // will handle it. + if (init == null) ; else if (typeof init === 'object') { + const method = init[Symbol.iterator]; + if (method != null) { + if (typeof method !== 'function') { + throw new TypeError('Header pairs must be iterable'); + } + + // sequence> + // Note: per spec we have to first exhaust the lists then process them + const pairs = []; + for (const pair of init) { + if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') { + throw new TypeError('Each header pair must be iterable'); + } + pairs.push(Array.from(pair)); + } + + for (const pair of pairs) { + if (pair.length !== 2) { + throw new TypeError('Each header pair must be a name/value tuple'); + } + this.append(pair[0], pair[1]); + } + } else { + // record + for (const key of Object.keys(init)) { + const value = init[key]; + this.append(key, value); + } + } + } else { + throw new TypeError('Provided initializer must be an object'); + } + } + + /** + * Return combined header value given name + * + * @param String name Header name + * @return Mixed + */ + get(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key === undefined) { + return null; + } + + return this[MAP][key].join(', '); + } + + /** + * Iterate over all headers + * + * @param Function callback Executed for each item with parameters (value, name, thisArg) + * @param Boolean thisArg `this` context for callback function + * @return Void + */ + forEach(callback) { + let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; + + let pairs = getHeaders(this); + let i = 0; + while (i < pairs.length) { + var _pairs$i = pairs[i]; + const name = _pairs$i[0], + value = _pairs$i[1]; + + callback.call(thisArg, value, name, this); + pairs = getHeaders(this); + i++; + } + } + + /** + * Overwrite header values given name + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + set(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + this[MAP][key !== undefined ? key : name] = [value]; + } + + /** + * Append a value onto existing header + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + append(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + if (key !== undefined) { + this[MAP][key].push(value); + } else { + this[MAP][name] = [value]; + } + } + + /** + * Check for header name existence + * + * @param String name Header name + * @return Boolean + */ + has(name) { + name = `${name}`; + validateName(name); + return find(this[MAP], name) !== undefined; + } + + /** + * Delete all header values given name + * + * @param String name Header name + * @return Void + */ + delete(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key !== undefined) { + delete this[MAP][key]; + } + } + + /** + * Return raw headers (non-spec api) + * + * @return Object + */ + raw() { + return this[MAP]; + } + + /** + * Get an iterator on keys. + * + * @return Iterator + */ + keys() { + return createHeadersIterator(this, 'key'); + } + + /** + * Get an iterator on values. + * + * @return Iterator + */ + values() { + return createHeadersIterator(this, 'value'); + } + + /** + * Get an iterator on entries. + * + * This is the default iterator of the Headers object. + * + * @return Iterator + */ + [Symbol.iterator]() { + return createHeadersIterator(this, 'key+value'); + } +} +Headers.prototype.entries = Headers.prototype[Symbol.iterator]; + +Object.defineProperty(Headers.prototype, Symbol.toStringTag, { + value: 'Headers', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Headers.prototype, { + get: { enumerable: true }, + forEach: { enumerable: true }, + set: { enumerable: true }, + append: { enumerable: true }, + has: { enumerable: true }, + delete: { enumerable: true }, + keys: { enumerable: true }, + values: { enumerable: true }, + entries: { enumerable: true } +}); + +function getHeaders(headers) { + let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value'; + + const keys = Object.keys(headers[MAP]).sort(); + return keys.map(kind === 'key' ? function (k) { + return k.toLowerCase(); + } : kind === 'value' ? function (k) { + return headers[MAP][k].join(', '); + } : function (k) { + return [k.toLowerCase(), headers[MAP][k].join(', ')]; + }); +} + +const INTERNAL = Symbol('internal'); + +function createHeadersIterator(target, kind) { + const iterator = Object.create(HeadersIteratorPrototype); + iterator[INTERNAL] = { + target, + kind, + index: 0 + }; + return iterator; +} + +const HeadersIteratorPrototype = Object.setPrototypeOf({ + next() { + // istanbul ignore if + if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) { + throw new TypeError('Value of `this` is not a HeadersIterator'); + } + + var _INTERNAL = this[INTERNAL]; + const target = _INTERNAL.target, + kind = _INTERNAL.kind, + index = _INTERNAL.index; + + const values = getHeaders(target, kind); + const len = values.length; + if (index >= len) { + return { + value: undefined, + done: true + }; + } + + this[INTERNAL].index = index + 1; + + return { + value: values[index], + done: false + }; + } +}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))); + +Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, { + value: 'HeadersIterator', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * Export the Headers object in a form that Node.js can consume. + * + * @param Headers headers + * @return Object + */ +function exportNodeCompatibleHeaders(headers) { + const obj = Object.assign({ __proto__: null }, headers[MAP]); + + // http.request() only supports string as Host header. This hack makes + // specifying custom Host header possible. + const hostHeaderKey = find(headers[MAP], 'Host'); + if (hostHeaderKey !== undefined) { + obj[hostHeaderKey] = obj[hostHeaderKey][0]; + } + + return obj; +} + +/** + * Create a Headers object from an object of headers, ignoring those that do + * not conform to HTTP grammar productions. + * + * @param Object obj Object of headers + * @return Headers + */ +function createHeadersLenient(obj) { + const headers = new Headers(); + for (const name of Object.keys(obj)) { + if (invalidTokenRegex.test(name)) { + continue; + } + if (Array.isArray(obj[name])) { + for (const val of obj[name]) { + if (invalidHeaderCharRegex.test(val)) { + continue; + } + if (headers[MAP][name] === undefined) { + headers[MAP][name] = [val]; + } else { + headers[MAP][name].push(val); + } + } + } else if (!invalidHeaderCharRegex.test(obj[name])) { + headers[MAP][name] = [obj[name]]; + } + } + return headers; +} + +const INTERNALS$1 = Symbol('Response internals'); + +// fix an issue where "STATUS_CODES" aren't a named export for node <10 +const STATUS_CODES = http.STATUS_CODES; + +/** + * Response class + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +class Response { + constructor() { + let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + Body.call(this, body, opts); + + const status = opts.status || 200; + const headers = new Headers(opts.headers); + + if (body != null && !headers.has('Content-Type')) { + const contentType = extractContentType(body); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + this[INTERNALS$1] = { + url: opts.url, + status, + statusText: opts.statusText || STATUS_CODES[status], + headers, + counter: opts.counter + }; + } + + get url() { + return this[INTERNALS$1].url || ''; + } + + get status() { + return this[INTERNALS$1].status; + } + + /** + * Convenience property representing if the request ended normally + */ + get ok() { + return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; + } + + get redirected() { + return this[INTERNALS$1].counter > 0; + } + + get statusText() { + return this[INTERNALS$1].statusText; + } + + get headers() { + return this[INTERNALS$1].headers; + } + + /** + * Clone this response + * + * @return Response + */ + clone() { + return new Response(clone(this), { + url: this.url, + status: this.status, + statusText: this.statusText, + headers: this.headers, + ok: this.ok, + redirected: this.redirected + }); + } +} + +Body.mixIn(Response.prototype); + +Object.defineProperties(Response.prototype, { + url: { enumerable: true }, + status: { enumerable: true }, + ok: { enumerable: true }, + redirected: { enumerable: true }, + statusText: { enumerable: true }, + headers: { enumerable: true }, + clone: { enumerable: true } +}); + +Object.defineProperty(Response.prototype, Symbol.toStringTag, { + value: 'Response', + writable: false, + enumerable: false, + configurable: true +}); + +const INTERNALS$2 = Symbol('Request internals'); +const URL = Url.URL || whatwgUrl.URL; + +// fix an issue where "format", "parse" aren't a named export for node <10 +const parse_url = Url.parse; +const format_url = Url.format; + +/** + * Wrapper around `new URL` to handle arbitrary URLs + * + * @param {string} urlStr + * @return {void} + */ +function parseURL(urlStr) { + /* + Check whether the URL is absolute or not + Scheme: https://tools.ietf.org/html/rfc3986#section-3.1 + Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3 + */ + if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) { + urlStr = new URL(urlStr).toString(); + } + + // Fallback to old implementation for arbitrary URLs + return parse_url(urlStr); +} + +const streamDestructionSupported = 'destroy' in Stream.Readable.prototype; + +/** + * Check if a value is an instance of Request. + * + * @param Mixed input + * @return Boolean + */ +function isRequest(input) { + return typeof input === 'object' && typeof input[INTERNALS$2] === 'object'; +} + +function isAbortSignal(signal) { + const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal); + return !!(proto && proto.constructor.name === 'AbortSignal'); +} + +/** + * Request class + * + * @param Mixed input Url or Request instance + * @param Object init Custom options + * @return Void + */ +class Request { + constructor(input) { + let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + let parsedURL; + + // normalize input + if (!isRequest(input)) { + if (input && input.href) { + // in order to support Node.js' Url objects; though WHATWG's URL objects + // will fall into this branch also (since their `toString()` will return + // `href` property anyway) + parsedURL = parseURL(input.href); + } else { + // coerce input to a string before attempting to parse + parsedURL = parseURL(`${input}`); + } + input = {}; + } else { + parsedURL = parseURL(input.url); + } + + let method = init.method || input.method || 'GET'; + method = method.toUpperCase(); + + if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { + throw new TypeError('Request with GET/HEAD method cannot have body'); + } + + let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; + + Body.call(this, inputBody, { + timeout: init.timeout || input.timeout || 0, + size: init.size || input.size || 0 + }); + + const headers = new Headers(init.headers || input.headers || {}); + + if (inputBody != null && !headers.has('Content-Type')) { + const contentType = extractContentType(inputBody); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + let signal = isRequest(input) ? input.signal : null; + if ('signal' in init) signal = init.signal; + + if (signal != null && !isAbortSignal(signal)) { + throw new TypeError('Expected signal to be an instanceof AbortSignal'); + } + + this[INTERNALS$2] = { + method, + redirect: init.redirect || input.redirect || 'follow', + headers, + parsedURL, + signal + }; + + // node-fetch-only options + this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20; + this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true; + this.counter = init.counter || input.counter || 0; + this.agent = init.agent || input.agent; + } + + get method() { + return this[INTERNALS$2].method; + } + + get url() { + return format_url(this[INTERNALS$2].parsedURL); + } + + get headers() { + return this[INTERNALS$2].headers; + } + + get redirect() { + return this[INTERNALS$2].redirect; + } + + get signal() { + return this[INTERNALS$2].signal; + } + + /** + * Clone this request + * + * @return Request + */ + clone() { + return new Request(this); + } +} + +Body.mixIn(Request.prototype); + +Object.defineProperty(Request.prototype, Symbol.toStringTag, { + value: 'Request', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Request.prototype, { + method: { enumerable: true }, + url: { enumerable: true }, + headers: { enumerable: true }, + redirect: { enumerable: true }, + clone: { enumerable: true }, + signal: { enumerable: true } +}); + +/** + * Convert a Request to Node.js http request options. + * + * @param Request A Request instance + * @return Object The options object to be passed to http.request + */ +function getNodeRequestOptions(request) { + const parsedURL = request[INTERNALS$2].parsedURL; + const headers = new Headers(request[INTERNALS$2].headers); + + // fetch step 1.3 + if (!headers.has('Accept')) { + headers.set('Accept', '*/*'); + } + + // Basic fetch + if (!parsedURL.protocol || !parsedURL.hostname) { + throw new TypeError('Only absolute URLs are supported'); + } + + if (!/^https?:$/.test(parsedURL.protocol)) { + throw new TypeError('Only HTTP(S) protocols are supported'); + } + + if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) { + throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8'); + } + + // HTTP-network-or-cache fetch steps 2.4-2.7 + let contentLengthValue = null; + if (request.body == null && /^(POST|PUT)$/i.test(request.method)) { + contentLengthValue = '0'; + } + if (request.body != null) { + const totalBytes = getTotalBytes(request); + if (typeof totalBytes === 'number') { + contentLengthValue = String(totalBytes); + } + } + if (contentLengthValue) { + headers.set('Content-Length', contentLengthValue); + } + + // HTTP-network-or-cache fetch step 2.11 + if (!headers.has('User-Agent')) { + headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)'); + } + + // HTTP-network-or-cache fetch step 2.15 + if (request.compress && !headers.has('Accept-Encoding')) { + headers.set('Accept-Encoding', 'gzip,deflate'); + } + + let agent = request.agent; + if (typeof agent === 'function') { + agent = agent(parsedURL); + } + + // HTTP-network fetch step 4.2 + // chunked encoding is handled by Node.js + + return Object.assign({}, parsedURL, { + method: request.method, + headers: exportNodeCompatibleHeaders(headers), + agent + }); +} + +/** + * abort-error.js + * + * AbortError interface for cancelled requests + */ + +/** + * Create AbortError instance + * + * @param String message Error message for human + * @return AbortError + */ +function AbortError(message) { + Error.call(this, message); + + this.type = 'aborted'; + this.message = message; + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +AbortError.prototype = Object.create(Error.prototype); +AbortError.prototype.constructor = AbortError; +AbortError.prototype.name = 'AbortError'; + +const URL$1 = Url.URL || whatwgUrl.URL; + +// fix an issue where "PassThrough", "resolve" aren't a named export for node <10 +const PassThrough$1 = Stream.PassThrough; + +const isDomainOrSubdomain = function isDomainOrSubdomain(destination, original) { + const orig = new URL$1(original).hostname; + const dest = new URL$1(destination).hostname; + + return orig === dest || orig[orig.length - dest.length - 1] === '.' && orig.endsWith(dest); +}; + +/** + * isSameProtocol reports whether the two provided URLs use the same protocol. + * + * Both domains must already be in canonical form. + * @param {string|URL} original + * @param {string|URL} destination + */ +const isSameProtocol = function isSameProtocol(destination, original) { + const orig = new URL$1(original).protocol; + const dest = new URL$1(destination).protocol; + + return orig === dest; +}; + +/** + * Fetch function + * + * @param Mixed url Absolute url or Request instance + * @param Object opts Fetch options + * @return Promise + */ +function fetch(url, opts) { + + // allow custom promise + if (!fetch.Promise) { + throw new Error('native promise missing, set fetch.Promise to your favorite alternative'); + } + + Body.Promise = fetch.Promise; + + // wrap http.request into fetch + return new fetch.Promise(function (resolve, reject) { + // build request object + const request = new Request(url, opts); + const options = getNodeRequestOptions(request); + + const send = (options.protocol === 'https:' ? https : http).request; + const signal = request.signal; + + let response = null; + + const abort = function abort() { + let error = new AbortError('The user aborted a request.'); + reject(error); + if (request.body && request.body instanceof Stream.Readable) { + destroyStream(request.body, error); + } + if (!response || !response.body) return; + response.body.emit('error', error); + }; + + if (signal && signal.aborted) { + abort(); + return; + } + + const abortAndFinalize = function abortAndFinalize() { + abort(); + finalize(); + }; + + // send request + const req = send(options); + let reqTimeout; + + if (signal) { + signal.addEventListener('abort', abortAndFinalize); + } + + function finalize() { + req.abort(); + if (signal) signal.removeEventListener('abort', abortAndFinalize); + clearTimeout(reqTimeout); + } + + if (request.timeout) { + req.once('socket', function (socket) { + reqTimeout = setTimeout(function () { + reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout')); + finalize(); + }, request.timeout); + }); + } + + req.on('error', function (err) { + reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); + + if (response && response.body) { + destroyStream(response.body, err); + } + + finalize(); + }); + + fixResponseChunkedTransferBadEnding(req, function (err) { + if (signal && signal.aborted) { + return; + } + + if (response && response.body) { + destroyStream(response.body, err); + } + }); + + /* c8 ignore next 18 */ + if (parseInt(process.version.substring(1)) < 14) { + // Before Node.js 14, pipeline() does not fully support async iterators and does not always + // properly handle when the socket close/end events are out of order. + req.on('socket', function (s) { + s.addListener('close', function (hadError) { + // if a data listener is still present we didn't end cleanly + const hasDataListener = s.listenerCount('data') > 0; + + // if end happened before close but the socket didn't emit an error, do it now + if (response && hasDataListener && !hadError && !(signal && signal.aborted)) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + response.body.emit('error', err); + } + }); + }); + } + + req.on('response', function (res) { + clearTimeout(reqTimeout); + + const headers = createHeadersLenient(res.headers); + + // HTTP fetch step 5 + if (fetch.isRedirect(res.statusCode)) { + // HTTP fetch step 5.2 + const location = headers.get('Location'); + + // HTTP fetch step 5.3 + let locationURL = null; + try { + locationURL = location === null ? null : new URL$1(location, request.url).toString(); + } catch (err) { + // error here can only be invalid URL in Location: header + // do not throw when options.redirect == manual + // let the user extract the errorneous redirect URL + if (request.redirect !== 'manual') { + reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect')); + finalize(); + return; + } + } + + // HTTP fetch step 5.5 + switch (request.redirect) { + case 'error': + reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect')); + finalize(); + return; + case 'manual': + // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL. + if (locationURL !== null) { + // handle corrupted header + try { + headers.set('Location', locationURL); + } catch (err) { + // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request + reject(err); + } + } + break; + case 'follow': + // HTTP-redirect fetch step 2 + if (locationURL === null) { + break; + } + + // HTTP-redirect fetch step 5 + if (request.counter >= request.follow) { + reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 6 (counter increment) + // Create a new Request object. + const requestOpts = { + headers: new Headers(request.headers), + follow: request.follow, + counter: request.counter + 1, + agent: request.agent, + compress: request.compress, + method: request.method, + body: request.body, + signal: request.signal, + timeout: request.timeout, + size: request.size + }; + + if (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) { + for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) { + requestOpts.headers.delete(name); + } + } + + // HTTP-redirect fetch step 9 + if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) { + reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 11 + if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') { + requestOpts.method = 'GET'; + requestOpts.body = undefined; + requestOpts.headers.delete('content-length'); + } + + // HTTP-redirect fetch step 15 + resolve(fetch(new Request(locationURL, requestOpts))); + finalize(); + return; + } + } + + // prepare response + res.once('end', function () { + if (signal) signal.removeEventListener('abort', abortAndFinalize); + }); + let body = res.pipe(new PassThrough$1()); + + const response_options = { + url: request.url, + status: res.statusCode, + statusText: res.statusMessage, + headers: headers, + size: request.size, + timeout: request.timeout, + counter: request.counter + }; + + // HTTP-network fetch step 12.1.1.3 + const codings = headers.get('Content-Encoding'); + + // HTTP-network fetch step 12.1.1.4: handle content codings + + // in following scenarios we ignore compression support + // 1. compression support is disabled + // 2. HEAD request + // 3. no Content-Encoding header + // 4. no content response (204) + // 5. content not modified response (304) + if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) { + response = new Response(body, response_options); + resolve(response); + return; + } + + // For Node v6+ + // Be less strict when decoding compressed responses, since sometimes + // servers send slightly invalid responses that are still accepted + // by common browsers. + // Always using Z_SYNC_FLUSH is what cURL does. + const zlibOptions = { + flush: zlib.Z_SYNC_FLUSH, + finishFlush: zlib.Z_SYNC_FLUSH + }; + + // for gzip + if (codings == 'gzip' || codings == 'x-gzip') { + body = body.pipe(zlib.createGunzip(zlibOptions)); + response = new Response(body, response_options); + resolve(response); + return; + } + + // for deflate + if (codings == 'deflate' || codings == 'x-deflate') { + // handle the infamous raw deflate response from old servers + // a hack for old IIS and Apache servers + const raw = res.pipe(new PassThrough$1()); + raw.once('data', function (chunk) { + // see http://stackoverflow.com/questions/37519828 + if ((chunk[0] & 0x0F) === 0x08) { + body = body.pipe(zlib.createInflate()); + } else { + body = body.pipe(zlib.createInflateRaw()); + } + response = new Response(body, response_options); + resolve(response); + }); + raw.on('end', function () { + // some old IIS servers return zero-length OK deflate responses, so 'data' is never emitted. + if (!response) { + response = new Response(body, response_options); + resolve(response); + } + }); + return; + } + + // for br + if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') { + body = body.pipe(zlib.createBrotliDecompress()); + response = new Response(body, response_options); + resolve(response); + return; + } + + // otherwise, use response as-is + response = new Response(body, response_options); + resolve(response); + }); + + writeToStream(req, request); + }); +} +function fixResponseChunkedTransferBadEnding(request, errorCallback) { + let socket; + + request.on('socket', function (s) { + socket = s; + }); + + request.on('response', function (response) { + const headers = response.headers; + + if (headers['transfer-encoding'] === 'chunked' && !headers['content-length']) { + response.once('close', function (hadError) { + // tests for socket presence, as in some situations the + // the 'socket' event is not triggered for the request + // (happens in deno), avoids `TypeError` + // if a data listener is still present we didn't end cleanly + const hasDataListener = socket && socket.listenerCount('data') > 0; + + if (hasDataListener && !hadError) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + errorCallback(err); + } + }); + } + }); +} + +function destroyStream(stream, err) { + if (stream.destroy) { + stream.destroy(err); + } else { + // node < 8 + stream.emit('error', err); + stream.end(); + } +} + +/** + * Redirect code matching + * + * @param Number code Status code + * @return Boolean + */ +fetch.isRedirect = function (code) { + return code === 301 || code === 302 || code === 303 || code === 307 || code === 308; +}; + +// expose Promise +fetch.Promise = global.Promise; + +export default fetch; +export { Headers, Request, Response, FetchError, AbortError }; diff --git a/backend/node_modules/node-fetch/package.json b/backend/node_modules/node-fetch/package.json new file mode 100644 index 0000000000000000000000000000000000000000..e0be17689a436a7734b168e8d12f5e97e054f0a5 --- /dev/null +++ b/backend/node_modules/node-fetch/package.json @@ -0,0 +1,89 @@ +{ + "name": "node-fetch", + "version": "2.7.0", + "description": "A light-weight module that brings window.fetch to node.js", + "main": "lib/index.js", + "browser": "./browser.js", + "module": "lib/index.mjs", + "files": [ + "lib/index.js", + "lib/index.mjs", + "lib/index.es.js", + "browser.js" + ], + "engines": { + "node": "4.x || >=6.0.0" + }, + "scripts": { + "build": "cross-env BABEL_ENV=rollup rollup -c", + "prepare": "npm run build", + "test": "cross-env BABEL_ENV=test mocha --require babel-register --throw-deprecation test/test.js", + "report": "cross-env BABEL_ENV=coverage nyc --reporter lcov --reporter text mocha -R spec test/test.js", + "coverage": "cross-env BABEL_ENV=coverage nyc --reporter json --reporter text mocha -R spec test/test.js && codecov -f coverage/coverage-final.json" + }, + "repository": { + "type": "git", + "url": "https://github.com/bitinn/node-fetch.git" + }, + "keywords": [ + "fetch", + "http", + "promise" + ], + "author": "David Frank", + "license": "MIT", + "bugs": { + "url": "https://github.com/bitinn/node-fetch/issues" + }, + "homepage": "https://github.com/bitinn/node-fetch", + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + }, + "devDependencies": { + "@ungap/url-search-params": "^0.1.2", + "abort-controller": "^1.1.0", + "abortcontroller-polyfill": "^1.3.0", + "babel-core": "^6.26.3", + "babel-plugin-istanbul": "^4.1.6", + "babel-plugin-transform-async-generator-functions": "^6.24.1", + "babel-polyfill": "^6.26.0", + "babel-preset-env": "1.4.0", + "babel-register": "^6.16.3", + "chai": "^3.5.0", + "chai-as-promised": "^7.1.1", + "chai-iterator": "^1.1.1", + "chai-string": "~1.3.0", + "codecov": "3.3.0", + "cross-env": "^5.2.0", + "form-data": "^2.3.3", + "is-builtin-module": "^1.0.0", + "mocha": "^5.0.0", + "nyc": "11.9.0", + "parted": "^0.1.1", + "promise": "^8.0.3", + "resumer": "0.0.0", + "rollup": "^0.63.4", + "rollup-plugin-babel": "^3.0.7", + "string-to-arraybuffer": "^1.0.2", + "teeny-request": "3.7.0" + }, + "release": { + "branches": [ + "+([0-9]).x", + "main", + "next", + { + "name": "beta", + "prerelease": true + } + ] + } +} diff --git a/backend/node_modules/object-assign/index.js b/backend/node_modules/object-assign/index.js new file mode 100644 index 0000000000000000000000000000000000000000..0930cf8890b9af66125c222c29d7bd75614ac6b4 --- /dev/null +++ b/backend/node_modules/object-assign/index.js @@ -0,0 +1,90 @@ +/* +object-assign +(c) Sindre Sorhus +@license MIT +*/ + +'use strict'; +/* eslint-disable no-unused-vars */ +var getOwnPropertySymbols = Object.getOwnPropertySymbols; +var hasOwnProperty = Object.prototype.hasOwnProperty; +var propIsEnumerable = Object.prototype.propertyIsEnumerable; + +function toObject(val) { + if (val === null || val === undefined) { + throw new TypeError('Object.assign cannot be called with null or undefined'); + } + + return Object(val); +} + +function shouldUseNative() { + try { + if (!Object.assign) { + return false; + } + + // Detect buggy property enumeration order in older V8 versions. + + // https://bugs.chromium.org/p/v8/issues/detail?id=4118 + var test1 = new String('abc'); // eslint-disable-line no-new-wrappers + test1[5] = 'de'; + if (Object.getOwnPropertyNames(test1)[0] === '5') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test2 = {}; + for (var i = 0; i < 10; i++) { + test2['_' + String.fromCharCode(i)] = i; + } + var order2 = Object.getOwnPropertyNames(test2).map(function (n) { + return test2[n]; + }); + if (order2.join('') !== '0123456789') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test3 = {}; + 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { + test3[letter] = letter; + }); + if (Object.keys(Object.assign({}, test3)).join('') !== + 'abcdefghijklmnopqrst') { + return false; + } + + return true; + } catch (err) { + // We don't expect any of the above to throw, but better to be safe. + return false; + } +} + +module.exports = shouldUseNative() ? Object.assign : function (target, source) { + var from; + var to = toObject(target); + var symbols; + + for (var s = 1; s < arguments.length; s++) { + from = Object(arguments[s]); + + for (var key in from) { + if (hasOwnProperty.call(from, key)) { + to[key] = from[key]; + } + } + + if (getOwnPropertySymbols) { + symbols = getOwnPropertySymbols(from); + for (var i = 0; i < symbols.length; i++) { + if (propIsEnumerable.call(from, symbols[i])) { + to[symbols[i]] = from[symbols[i]]; + } + } + } + } + + return to; +}; diff --git a/backend/node_modules/object-assign/license b/backend/node_modules/object-assign/license new file mode 100644 index 0000000000000000000000000000000000000000..654d0bfe943437d43242325b1fbcff5f400d84ee --- /dev/null +++ b/backend/node_modules/object-assign/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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/backend/node_modules/object-assign/package.json b/backend/node_modules/object-assign/package.json new file mode 100644 index 0000000000000000000000000000000000000000..503eb1e6d0f5a1404c8e7f6c09fbda7e40fd29b4 --- /dev/null +++ b/backend/node_modules/object-assign/package.json @@ -0,0 +1,42 @@ +{ + "name": "object-assign", + "version": "4.1.1", + "description": "ES2015 `Object.assign()` ponyfill", + "license": "MIT", + "repository": "sindresorhus/object-assign", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "test": "xo && ava", + "bench": "matcha bench.js" + }, + "files": [ + "index.js" + ], + "keywords": [ + "object", + "assign", + "extend", + "properties", + "es2015", + "ecmascript", + "harmony", + "ponyfill", + "prollyfill", + "polyfill", + "shim", + "browser" + ], + "devDependencies": { + "ava": "^0.16.0", + "lodash": "^4.16.4", + "matcha": "^0.7.0", + "xo": "^0.16.0" + } +} diff --git a/backend/node_modules/object-assign/readme.md b/backend/node_modules/object-assign/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..1be09d35c776cc0e9cc59519c2de6b9eecf8aa68 --- /dev/null +++ b/backend/node_modules/object-assign/readme.md @@ -0,0 +1,61 @@ +# object-assign [![Build Status](https://travis-ci.org/sindresorhus/object-assign.svg?branch=master)](https://travis-ci.org/sindresorhus/object-assign) + +> ES2015 [`Object.assign()`](http://www.2ality.com/2014/01/object-assign.html) [ponyfill](https://ponyfill.com) + + +## Use the built-in + +Node.js 4 and up, as well as every evergreen browser (Chrome, Edge, Firefox, Opera, Safari), +support `Object.assign()` :tada:. If you target only those environments, then by all +means, use `Object.assign()` instead of this package. + + +## Install + +``` +$ npm install --save object-assign +``` + + +## Usage + +```js +const objectAssign = require('object-assign'); + +objectAssign({foo: 0}, {bar: 1}); +//=> {foo: 0, bar: 1} + +// multiple sources +objectAssign({foo: 0}, {bar: 1}, {baz: 2}); +//=> {foo: 0, bar: 1, baz: 2} + +// overwrites equal keys +objectAssign({foo: 0}, {foo: 1}, {foo: 2}); +//=> {foo: 2} + +// ignores null and undefined sources +objectAssign({foo: 0}, null, {bar: 1}, undefined); +//=> {foo: 0, bar: 1} +``` + + +## API + +### objectAssign(target, [source, ...]) + +Assigns enumerable own properties of `source` objects to the `target` object and returns the `target` object. Additional `source` objects will overwrite previous ones. + + +## Resources + +- [ES2015 spec - Object.assign](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.assign) + + +## Related + +- [deep-assign](https://github.com/sindresorhus/deep-assign) - Recursive `Object.assign()` + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/backend/node_modules/object-inspect/.eslintrc b/backend/node_modules/object-inspect/.eslintrc new file mode 100644 index 0000000000000000000000000000000000000000..21f903923ef11aef5d6ca8ade40028520b82a37a --- /dev/null +++ b/backend/node_modules/object-inspect/.eslintrc @@ -0,0 +1,53 @@ +{ + "root": true, + "extends": "@ljharb", + "rules": { + "complexity": 0, + "func-style": [2, "declaration"], + "indent": [2, 4], + "max-lines": 1, + "max-lines-per-function": 1, + "max-params": [2, 4], + "max-statements": 0, + "max-statements-per-line": [2, { "max": 2 }], + "no-magic-numbers": 0, + "no-param-reassign": 1, + "strict": 0, // TODO + }, + "overrides": [ + { + "files": ["test/**", "test-*", "example/**"], + "extends": "@ljharb/eslint-config/tests", + "rules": { + "id-length": 0, + }, + }, + { + "files": ["example/**"], + "rules": { + "no-console": 0, + }, + }, + { + "files": ["test/browser/**"], + "env": { + "browser": true, + }, + }, + { + "files": ["test/bigint*"], + "rules": { + "new-cap": [2, { "capIsNewExceptions": ["BigInt"] }], + }, + }, + { + "files": "index.js", + "globals": { + "HTMLElement": false, + }, + "rules": { + "no-use-before-define": 1, + }, + }, + ], +} diff --git a/backend/node_modules/object-inspect/.github/FUNDING.yml b/backend/node_modules/object-inspect/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..730276bd121df856ede4c51d6e7b63d071242487 --- /dev/null +++ b/backend/node_modules/object-inspect/.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/object-inspect +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/backend/node_modules/object-inspect/.nycrc b/backend/node_modules/object-inspect/.nycrc new file mode 100644 index 0000000000000000000000000000000000000000..58a5db7834ad50f2f9a5814f49d98db106381316 --- /dev/null +++ b/backend/node_modules/object-inspect/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "instrumentation": false, + "sourceMap": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "example", + "test", + "test-core-js.js" + ] +} diff --git a/backend/node_modules/object-inspect/CHANGELOG.md b/backend/node_modules/object-inspect/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..c5772b4c07882cb35f459e5f08a8bec5b1887467 --- /dev/null +++ b/backend/node_modules/object-inspect/CHANGELOG.md @@ -0,0 +1,389 @@ +# 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.13.1](https://github.com/inspect-js/object-inspect/compare/v1.13.0...v1.13.1) - 2023-10-19 + +### Commits + +- [Fix] in IE 8, global can !== window despite them being prototypes of each other [`30d0859`](https://github.com/inspect-js/object-inspect/commit/30d0859dc4606cf75c2410edcd5d5c6355f8d372) + +## [v1.13.0](https://github.com/inspect-js/object-inspect/compare/v1.12.3...v1.13.0) - 2023-10-14 + +### Commits + +- [New] add special handling for the global object [`431bab2`](https://github.com/inspect-js/object-inspect/commit/431bab21a490ee51d35395966a504501e8c685da) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `tape` [`fd4f619`](https://github.com/inspect-js/object-inspect/commit/fd4f6193562b4b0e95dcf5c0201b4e8cbbc4f58d) +- [Dev Deps] update `mock-property`, `tape` [`b453f6c`](https://github.com/inspect-js/object-inspect/commit/b453f6ceeebf8a1b738a1029754092e0367a4134) +- [Dev Deps] update `error-cause` [`e8ffc57`](https://github.com/inspect-js/object-inspect/commit/e8ffc577d73b92bb6a4b00c44f14e3319e374888) +- [Dev Deps] update `tape` [`054b8b9`](https://github.com/inspect-js/object-inspect/commit/054b8b9b98633284cf989e582450ebfbbe53503c) +- [Dev Deps] temporarily remove `aud` due to breaking change in transitive deps [`2476845`](https://github.com/inspect-js/object-inspect/commit/2476845e0678dd290c541c81cd3dec8420782c52) +- [Dev Deps] pin `glob`, since v10.3.8+ requires a broken `jackspeak` [`383fa5e`](https://github.com/inspect-js/object-inspect/commit/383fa5eebc0afd705cc778a4b49d8e26452e49a8) +- [Dev Deps] pin `jackspeak` since 2.1.2+ depends on npm aliases, which kill the install process in npm < 6 [`68c244c`](https://github.com/inspect-js/object-inspect/commit/68c244c5174cdd877e5dcb8ee90aa3f44b2f25be) + +## [v1.12.3](https://github.com/inspect-js/object-inspect/compare/v1.12.2...v1.12.3) - 2023-01-12 + +### Commits + +- [Fix] in eg FF 24, collections lack forEach [`75fc226`](https://github.com/inspect-js/object-inspect/commit/75fc22673c82d45f28322b1946bb0eb41b672b7f) +- [actions] update rebase action to use reusable workflow [`250a277`](https://github.com/inspect-js/object-inspect/commit/250a277a095e9dacc029ab8454dcfc15de549dcd) +- [Dev Deps] update `aud`, `es-value-fixtures`, `tape` [`66a19b3`](https://github.com/inspect-js/object-inspect/commit/66a19b3209ccc3c5ef4b34c3cb0160e65d1ce9d5) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `error-cause` [`c43d332`](https://github.com/inspect-js/object-inspect/commit/c43d3324b48384a16fd3dc444e5fc589d785bef3) +- [Tests] add `@pkgjs/support` to `postlint` [`e2618d2`](https://github.com/inspect-js/object-inspect/commit/e2618d22a7a3fa361b6629b53c1752fddc9c4d80) + +## [v1.12.2](https://github.com/inspect-js/object-inspect/compare/v1.12.1...v1.12.2) - 2022-05-26 + +### Commits + +- [Fix] use `util.inspect` for a custom inspection symbol method [`e243bf2`](https://github.com/inspect-js/object-inspect/commit/e243bf2eda6c4403ac6f1146fddb14d12e9646c1) +- [meta] add support info [`ca20ba3`](https://github.com/inspect-js/object-inspect/commit/ca20ba35713c17068ca912a86c542f5e8acb656c) +- [Fix] ignore `cause` in node v16.9 and v16.10 where it has a bug [`86aa553`](https://github.com/inspect-js/object-inspect/commit/86aa553a4a455562c2c56f1540f0bf857b9d314b) + +## [v1.12.1](https://github.com/inspect-js/object-inspect/compare/v1.12.0...v1.12.1) - 2022-05-21 + +### Commits + +- [Tests] use `mock-property` [`4ec8893`](https://github.com/inspect-js/object-inspect/commit/4ec8893ea9bfd28065ca3638cf6762424bf44352) +- [meta] use `npmignore` to autogenerate an npmignore file [`07f868c`](https://github.com/inspect-js/object-inspect/commit/07f868c10bd25a9d18686528339bb749c211fc9a) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `tape` [`b05244b`](https://github.com/inspect-js/object-inspect/commit/b05244b4f331e00c43b3151bc498041be77ccc91) +- [Dev Deps] update `@ljharb/eslint-config`, `error-cause`, `es-value-fixtures`, `functions-have-names`, `tape` [`d037398`](https://github.com/inspect-js/object-inspect/commit/d037398dcc5d531532e4c19c4a711ed677f579c1) +- [Fix] properly handle callable regexes in older engines [`848fe48`](https://github.com/inspect-js/object-inspect/commit/848fe48bd6dd0064ba781ee6f3c5e54a94144c37) + +## [v1.12.0](https://github.com/inspect-js/object-inspect/compare/v1.11.1...v1.12.0) - 2021-12-18 + +### Commits + +- [New] add `numericSeparator` boolean option [`2d2d537`](https://github.com/inspect-js/object-inspect/commit/2d2d537f5359a4300ce1c10241369f8024f89e11) +- [Robustness] cache more prototype methods [`191533d`](https://github.com/inspect-js/object-inspect/commit/191533da8aec98a05eadd73a5a6e979c9c8653e8) +- [New] ensure an Error’s `cause` is displayed [`53bc2ce`](https://github.com/inspect-js/object-inspect/commit/53bc2cee4e5a9cc4986f3cafa22c0685f340715e) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config` [`bc164b6`](https://github.com/inspect-js/object-inspect/commit/bc164b6e2e7d36b263970f16f54de63048b84a36) +- [Robustness] cache `RegExp.prototype.test` [`a314ab8`](https://github.com/inspect-js/object-inspect/commit/a314ab8271b905cbabc594c82914d2485a8daf12) +- [meta] fix auto-changelog settings [`5ed0983`](https://github.com/inspect-js/object-inspect/commit/5ed0983be72f73e32e2559997517a95525c7e20d) + +## [v1.11.1](https://github.com/inspect-js/object-inspect/compare/v1.11.0...v1.11.1) - 2021-12-05 + +### Commits + +- [meta] add `auto-changelog` [`7dbdd22`](https://github.com/inspect-js/object-inspect/commit/7dbdd228401d6025d8b7391476d88aee9ea9bbdf) +- [actions] reuse common workflows [`c8823bc`](https://github.com/inspect-js/object-inspect/commit/c8823bc0a8790729680709d45fb6e652432e91aa) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `safe-publish-latest`, `tape` [`7532b12`](https://github.com/inspect-js/object-inspect/commit/7532b120598307497b712890f75af8056f6d37a6) +- [Refactor] use `has-tostringtag` to behave correctly in the presence of symbol shams [`94abb5d`](https://github.com/inspect-js/object-inspect/commit/94abb5d4e745bf33253942dea86b3e538d2ff6c6) +- [actions] update codecov uploader [`5ed5102`](https://github.com/inspect-js/object-inspect/commit/5ed51025267a00e53b1341357315490ac4eb0874) +- [Dev Deps] update `eslint`, `tape` [`37b2ad2`](https://github.com/inspect-js/object-inspect/commit/37b2ad26c08d94bfd01d5d07069a0b28ef4e2ad7) +- [meta] add `sideEffects` flag [`d341f90`](https://github.com/inspect-js/object-inspect/commit/d341f905ef8bffa6a694cda6ddc5ba343532cd4f) + +## [v1.11.0](https://github.com/inspect-js/object-inspect/compare/v1.10.3...v1.11.0) - 2021-07-12 + +### Commits + +- [New] `customInspect`: add `symbol` option, to mimic modern util.inspect behavior [`e973a6e`](https://github.com/inspect-js/object-inspect/commit/e973a6e21f8140c5837cf25e9d89bdde88dc3120) +- [Dev Deps] update `eslint` [`05f1cb3`](https://github.com/inspect-js/object-inspect/commit/05f1cb3cbcfe1f238e8b51cf9bc294305b7ed793) + +## [v1.10.3](https://github.com/inspect-js/object-inspect/compare/v1.10.2...v1.10.3) - 2021-05-07 + +### Commits + +- [Fix] handle core-js Symbol shams [`4acfc2c`](https://github.com/inspect-js/object-inspect/commit/4acfc2c4b503498759120eb517abad6d51c9c5d6) +- [readme] update badges [`95c323a`](https://github.com/inspect-js/object-inspect/commit/95c323ad909d6cbabb95dd6015c190ba6db9c1f2) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud` [`cb38f48`](https://github.com/inspect-js/object-inspect/commit/cb38f485de6ec7a95109b5a9bbd0a1deba2f6611) + +## [v1.10.2](https://github.com/inspect-js/object-inspect/compare/v1.10.1...v1.10.2) - 2021-04-17 + +### Commits + +- [Fix] use a robust check for a boxed Symbol [`87f12d6`](https://github.com/inspect-js/object-inspect/commit/87f12d6e69ce530be04659c81a4cd502943acac5) + +## [v1.10.1](https://github.com/inspect-js/object-inspect/compare/v1.10.0...v1.10.1) - 2021-04-17 + +### Commits + +- [Fix] use a robust check for a boxed bigint [`d5ca829`](https://github.com/inspect-js/object-inspect/commit/d5ca8298b6d2e5c7b9334a5b21b96ed95d225c91) + +## [v1.10.0](https://github.com/inspect-js/object-inspect/compare/v1.9.0...v1.10.0) - 2021-04-17 + +### Commits + +- [Tests] increase coverage [`d8abb8a`](https://github.com/inspect-js/object-inspect/commit/d8abb8a62c2f084919df994a433b346e0d87a227) +- [actions] use `node/install` instead of `node/run`; use `codecov` action [`4bfec2e`](https://github.com/inspect-js/object-inspect/commit/4bfec2e30aaef6ddef6cbb1448306f9f8b9520b7) +- [New] respect `Symbol.toStringTag` on objects [`799b58f`](https://github.com/inspect-js/object-inspect/commit/799b58f536a45e4484633a8e9daeb0330835f175) +- [Fix] do not allow Symbol.toStringTag to masquerade as builtins [`d6c5b37`](https://github.com/inspect-js/object-inspect/commit/d6c5b37d7e94427796b82432fb0c8964f033a6ab) +- [New] add `WeakRef` support [`b6d898e`](https://github.com/inspect-js/object-inspect/commit/b6d898ee21868c780a7ee66b28532b5b34ed7f09) +- [meta] do not publish github action workflow files [`918cdfc`](https://github.com/inspect-js/object-inspect/commit/918cdfc4b6fe83f559ff6ef04fe66201e3ff5cbd) +- [meta] create `FUNDING.yml` [`0bb5fc5`](https://github.com/inspect-js/object-inspect/commit/0bb5fc516dbcd2cd728bd89cee0b580acc5ce301) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`22c8dc0`](https://github.com/inspect-js/object-inspect/commit/22c8dc0cac113d70f4781e49a950070923a671be) +- [meta] use `prepublishOnly` script for npm 7+ [`e52ee09`](https://github.com/inspect-js/object-inspect/commit/e52ee09e8050b8dbac94ef57f786675567728223) +- [Dev Deps] update `eslint` [`7c4e6fd`](https://github.com/inspect-js/object-inspect/commit/7c4e6fdedcd27cc980e13c9ad834d05a96f3d40c) + +## [v1.9.0](https://github.com/inspect-js/object-inspect/compare/v1.8.0...v1.9.0) - 2020-11-30 + +### Commits + +- [Tests] migrate tests to Github Actions [`d262251`](https://github.com/inspect-js/object-inspect/commit/d262251e13e16d3490b5473672f6b6d6ff86675d) +- [New] add enumerable own Symbols to plain object output [`ee60c03`](https://github.com/inspect-js/object-inspect/commit/ee60c033088cff9d33baa71e59a362a541b48284) +- [Tests] add passing tests [`01ac3e4`](https://github.com/inspect-js/object-inspect/commit/01ac3e4b5a30f97875a63dc9b1416b3bd626afc9) +- [actions] add "Require Allow Edits" action [`c2d7746`](https://github.com/inspect-js/object-inspect/commit/c2d774680cde4ca4af332d84d4121b26f798ba9e) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `core-js` [`70058de`](https://github.com/inspect-js/object-inspect/commit/70058de1579fc54d1d15ed6c2dbe246637ce70ff) +- [Fix] hex characters in strings should be uppercased, to match node `assert` [`6ab8faa`](https://github.com/inspect-js/object-inspect/commit/6ab8faaa0abc08fe7a8e2afd8b39c6f1f0e00113) +- [Tests] run `nyc` on all tests [`4c47372`](https://github.com/inspect-js/object-inspect/commit/4c473727879ddc8e28b599202551ddaaf07b6210) +- [Tests] node 0.8 has an unpredictable property order; fix `groups` test by removing property [`f192069`](https://github.com/inspect-js/object-inspect/commit/f192069a978a3b60e6f0e0d45ac7df260ab9a778) +- [New] add enumerable properties to Function inspect result, per node’s `assert` [`fd38e1b`](https://github.com/inspect-js/object-inspect/commit/fd38e1bc3e2a1dc82091ce3e021917462eee64fc) +- [Tests] fix tests for node < 10, due to regex match `groups` [`2ac6462`](https://github.com/inspect-js/object-inspect/commit/2ac6462cc4f72eaa0b63a8cfee9aabe3008b2330) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config` [`44b59e2`](https://github.com/inspect-js/object-inspect/commit/44b59e2676a7f825ef530dfd19dafb599e3b9456) +- [Robustness] cache `Symbol.prototype.toString` [`f3c2074`](https://github.com/inspect-js/object-inspect/commit/f3c2074d8f32faf8292587c07c9678ea931703dd) +- [Dev Deps] update `eslint` [`9411294`](https://github.com/inspect-js/object-inspect/commit/94112944b9245e3302e25453277876402d207e7f) +- [meta] `require-allow-edits` no longer requires an explicit github token [`36c0220`](https://github.com/inspect-js/object-inspect/commit/36c02205de3c2b0e84d53777c5c9fd54a36c48ab) +- [actions] update rebase checkout action to v2 [`55a39a6`](https://github.com/inspect-js/object-inspect/commit/55a39a64e944f19c6a7d8efddf3df27700f20d14) +- [actions] switch Automatic Rebase workflow to `pull_request_target` event [`f59fd3c`](https://github.com/inspect-js/object-inspect/commit/f59fd3cf406c3a7c7ece140904a80bbc6bacfcca) +- [Dev Deps] update `eslint` [`a492bec`](https://github.com/inspect-js/object-inspect/commit/a492becec644b0155c9c4bc1caf6f9fac11fb2c7) + +## [v1.8.0](https://github.com/inspect-js/object-inspect/compare/v1.7.0...v1.8.0) - 2020-06-18 + +### Fixed + +- [New] add `indent` option [`#27`](https://github.com/inspect-js/object-inspect/issues/27) + +### Commits + +- [Tests] add codecov [`4324cbb`](https://github.com/inspect-js/object-inspect/commit/4324cbb1a2bd7710822a4151ff373570db22453e) +- [New] add `maxStringLength` option [`b3995cb`](https://github.com/inspect-js/object-inspect/commit/b3995cb71e15b5ee127a3094c43994df9d973502) +- [New] add `customInspect` option, to disable custom inspect methods [`28b9179`](https://github.com/inspect-js/object-inspect/commit/28b9179ee802bb3b90810100c11637db90c2fb6d) +- [Tests] add Date and RegExp tests [`3b28eca`](https://github.com/inspect-js/object-inspect/commit/3b28eca57b0367aeadffac604ea09e8bdae7d97b) +- [actions] add automatic rebasing / merge commit blocking [`0d9c6c0`](https://github.com/inspect-js/object-inspect/commit/0d9c6c044e83475ff0bfffb9d35b149834c83a2e) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `core-js`, `tape`; add `aud` [`7c204f2`](https://github.com/inspect-js/object-inspect/commit/7c204f22b9e41bc97147f4d32d4cb045b17769a6) +- [readme] fix repo URLs, remove testling [`34ca9a0`](https://github.com/inspect-js/object-inspect/commit/34ca9a0dabfe75bd311f806a326fadad029909a3) +- [Fix] when truncating a deep array, note it as `[Array]` instead of just `[Object]` [`f74c82d`](https://github.com/inspect-js/object-inspect/commit/f74c82dd0b35386445510deb250f34c41be3ec0e) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`1a8a5ea`](https://github.com/inspect-js/object-inspect/commit/1a8a5ea069ea2bee89d77caedad83ffa23d35711) +- [Fix] do not be fooled by a function’s own `toString` method [`7cb5c65`](https://github.com/inspect-js/object-inspect/commit/7cb5c657a976f94715c19c10556a30f15bb7d5d7) +- [patch] indicate explicitly that anon functions are anonymous, to match node [`81ebdd4`](https://github.com/inspect-js/object-inspect/commit/81ebdd4215005144074bbdff3f6bafa01407910a) +- [Dev Deps] loosen the `core-js` dep [`e7472e8`](https://github.com/inspect-js/object-inspect/commit/e7472e8e242117670560bd995830c2a4d12080f5) +- [Dev Deps] update `tape` [`699827e`](https://github.com/inspect-js/object-inspect/commit/699827e6b37258b5203c33c78c009bf4b0e6a66d) +- [meta] add `safe-publish-latest` [`c5d2868`](https://github.com/inspect-js/object-inspect/commit/c5d2868d6eb33c472f37a20f89ceef2787046088) +- [Dev Deps] update `@ljharb/eslint-config` [`9199501`](https://github.com/inspect-js/object-inspect/commit/919950195d486114ccebacbdf9d74d7f382693b0) + +## [v1.7.0](https://github.com/inspect-js/object-inspect/compare/v1.6.0...v1.7.0) - 2019-11-10 + +### Commits + +- [Tests] use shared travis-ci configs [`19899ed`](https://github.com/inspect-js/object-inspect/commit/19899edbf31f4f8809acf745ce34ad1ce1bfa63b) +- [Tests] add linting [`a00f057`](https://github.com/inspect-js/object-inspect/commit/a00f057d917f66ea26dd37769c6b810ec4af97e8) +- [Tests] lint last file [`2698047`](https://github.com/inspect-js/object-inspect/commit/2698047b58af1e2e88061598ef37a75f228dddf6) +- [Tests] up to `node` `v12.7`, `v11.15`, `v10.16`, `v8.16`, `v6.17` [`589e87a`](https://github.com/inspect-js/object-inspect/commit/589e87a99cadcff4b600e6a303418e9d922836e8) +- [New] add support for `WeakMap` and `WeakSet` [`3ddb3e4`](https://github.com/inspect-js/object-inspect/commit/3ddb3e4e0c8287130c61a12e0ed9c104b1549306) +- [meta] clean up license so github can detect it properly [`27527bb`](https://github.com/inspect-js/object-inspect/commit/27527bb801520c9610c68cc3b55d6f20a2bee56d) +- [Tests] cover `util.inspect.custom` [`36d47b9`](https://github.com/inspect-js/object-inspect/commit/36d47b9c59056a57ef2f1491602c726359561800) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `core-js`, `tape` [`b614eaa`](https://github.com/inspect-js/object-inspect/commit/b614eaac901da0e5c69151f534671f990a94cace) +- [Tests] fix coverage thresholds [`7b7b176`](https://github.com/inspect-js/object-inspect/commit/7b7b176e15f8bd6e8b2f261ff5a493c2fe78d9c2) +- [Tests] bigint tests now can run on unflagged node [`063af31`](https://github.com/inspect-js/object-inspect/commit/063af31ce9cd13c202e3b67c07ba06dc9b7c0f81) +- [Refactor] add early bailout to `isMap` and `isSet` checks [`fc51047`](https://github.com/inspect-js/object-inspect/commit/fc5104714a3671d37e225813db79470d6335683b) +- [meta] add `funding` field [`7f9953a`](https://github.com/inspect-js/object-inspect/commit/7f9953a113eec7b064a6393cf9f90ba15f1d131b) +- [Tests] Fix invalid strict-mode syntax with hexadecimal [`a8b5425`](https://github.com/inspect-js/object-inspect/commit/a8b542503b4af1599a275209a1a99f5fdedb1ead) +- [Dev Deps] update `@ljharb/eslint-config` [`98df157`](https://github.com/inspect-js/object-inspect/commit/98df1577314d9188a3fc3f17fdcf2fba697ae1bd) +- add copyright to LICENSE [`bb69fd0`](https://github.com/inspect-js/object-inspect/commit/bb69fd017a062d299e44da1f9b2c7dcd67f621e6) +- [Tests] use `npx aud` in `posttest` [`4838353`](https://github.com/inspect-js/object-inspect/commit/4838353593974cf7f905b9ef04c03c094f0cdbe2) +- [Tests] move `0.6` to allowed failures, because it won‘t build on travis [`1bff32a`](https://github.com/inspect-js/object-inspect/commit/1bff32aa52e8aea687f0856b28ba754b3e43ebf7) + +## [v1.6.0](https://github.com/inspect-js/object-inspect/compare/v1.5.0...v1.6.0) - 2018-05-02 + +### Commits + +- [New] add support for boxed BigInt primitives [`356c66a`](https://github.com/inspect-js/object-inspect/commit/356c66a410e7aece7162c8319880a5ef647beaa9) +- [Tests] up to `node` `v10.0`, `v9.11`, `v8.11`, `v6.14`, `v4.9` [`c77b65b`](https://github.com/inspect-js/object-inspect/commit/c77b65bba593811b906b9ec57561c5cba92e2db3) +- [New] Add support for upcoming `BigInt` [`1ac548e`](https://github.com/inspect-js/object-inspect/commit/1ac548e4b27e26466c28c9a5e63e5d4e0591c31f) +- [Tests] run bigint tests in CI with --harmony-bigint flag [`d31b738`](https://github.com/inspect-js/object-inspect/commit/d31b73831880254b5c6cf5691cda9a149fbc5f04) +- [Dev Deps] update `core-js`, `tape` [`ff9eff6`](https://github.com/inspect-js/object-inspect/commit/ff9eff67113341ee1aaf80c1c22d683f43bfbccf) +- [Docs] fix example to use `safer-buffer` [`48cae12`](https://github.com/inspect-js/object-inspect/commit/48cae12a73ec6cacc955175bc56bbe6aee6a211f) + +## [v1.5.0](https://github.com/inspect-js/object-inspect/compare/v1.4.1...v1.5.0) - 2017-12-25 + +### Commits + +- [New] add `quoteStyle` option [`f5a72d2`](https://github.com/inspect-js/object-inspect/commit/f5a72d26edb3959b048f74c056ca7100a6b091e4) +- [Tests] add more test coverage [`30ebe4e`](https://github.com/inspect-js/object-inspect/commit/30ebe4e1fa943b99ecbb85be7614256d536e2759) +- [Tests] require 0.6 to pass [`99a008c`](https://github.com/inspect-js/object-inspect/commit/99a008ccace189a60fd7da18bf00e32c9572b980) + +## [v1.4.1](https://github.com/inspect-js/object-inspect/compare/v1.4.0...v1.4.1) - 2017-12-19 + +### Commits + +- [Tests] up to `node` `v9.3`, `v8.9`, `v6.12` [`6674476`](https://github.com/inspect-js/object-inspect/commit/6674476cc56acaac1bde96c84fed5ef631911906) +- [Fix] `inspect(Object(-0))` should be “Object(-0)”, not “Object(0)” [`d0a031f`](https://github.com/inspect-js/object-inspect/commit/d0a031f1cbb3024ee9982bfe364dd18a7e4d1bd3) + +## [v1.4.0](https://github.com/inspect-js/object-inspect/compare/v1.3.0...v1.4.0) - 2017-10-24 + +### Commits + +- [Tests] add `npm run coverage` [`3b48fb2`](https://github.com/inspect-js/object-inspect/commit/3b48fb25db037235eeb808f0b2830aad7aa36f70) +- [Tests] remove commented-out osx builds [`71e24db`](https://github.com/inspect-js/object-inspect/commit/71e24db8ad6ee3b9b381c5300b0475f2ba595a73) +- [New] add support for `util.inspect.custom`, in node only. [`20cca77`](https://github.com/inspect-js/object-inspect/commit/20cca7762d7e17f15b21a90793dff84acce155df) +- [Tests] up to `node` `v8.6`; use `nvm install-latest-npm` to ensure new npm doesn’t break old node [`252952d`](https://github.com/inspect-js/object-inspect/commit/252952d230d8065851dd3d4d5fe8398aae068529) +- [Tests] up to `node` `v8.8` [`4aa868d`](https://github.com/inspect-js/object-inspect/commit/4aa868d3a62914091d489dd6ec6eed194ee67cd3) +- [Dev Deps] update `core-js`, `tape` [`59483d1`](https://github.com/inspect-js/object-inspect/commit/59483d1df418f852f51fa0db7b24aa6b0209a27a) + +## [v1.3.0](https://github.com/inspect-js/object-inspect/compare/v1.2.2...v1.3.0) - 2017-07-31 + +### Fixed + +- [Fix] Map/Set: work around core-js bug < v2.5.0 [`#9`](https://github.com/inspect-js/object-inspect/issues/9) + +### Commits + +- [New] add support for arrays with additional object keys [`0d19937`](https://github.com/inspect-js/object-inspect/commit/0d199374ee37959e51539616666f420ccb29acb9) +- [Tests] up to `node` `v8.2`, `v7.10`, `v6.11`; fix new npm breaking on older nodes [`e24784a`](https://github.com/inspect-js/object-inspect/commit/e24784a90c49117787157a12a63897c49cf89bbb) +- Only apps should have lockfiles [`c6faebc`](https://github.com/inspect-js/object-inspect/commit/c6faebcb2ee486a889a4a1c4d78c0776c7576185) +- [Dev Deps] update `tape` [`7345a0a`](https://github.com/inspect-js/object-inspect/commit/7345a0aeba7e91b888a079c10004d17696a7f586) + +## [v1.2.2](https://github.com/inspect-js/object-inspect/compare/v1.2.1...v1.2.2) - 2017-03-24 + +### Commits + +- [Tests] up to `node` `v7.7`, `v6.10`, `v4.8`; improve test matrix [`a2ddc15`](https://github.com/inspect-js/object-inspect/commit/a2ddc15a1f2c65af18076eea1c0eb9cbceb478a0) +- [Tests] up to `node` `v7.0`, `v6.9`, `v5.12`, `v4.6`, `io.js` `v3.3`; improve test matrix [`a48949f`](https://github.com/inspect-js/object-inspect/commit/a48949f6b574b2d4d2298109d8e8d0eb3e7a83e7) +- [Performance] check for primitive types as early as possible. [`3b8092a`](https://github.com/inspect-js/object-inspect/commit/3b8092a2a4deffd0575f94334f00194e2d48dad3) +- [Refactor] remove unneeded `else`s. [`7255034`](https://github.com/inspect-js/object-inspect/commit/725503402e08de4f96f6bf2d8edef44ac36f26b6) +- [Refactor] avoid recreating `lowbyte` function every time. [`81edd34`](https://github.com/inspect-js/object-inspect/commit/81edd3475bd15bdd18e84de7472033dcf5004aaa) +- [Fix] differentiate -0 from 0 [`521d345`](https://github.com/inspect-js/object-inspect/commit/521d3456b009da7bf1c5785c8a9df5a9f8718264) +- [Refactor] move object key gathering into separate function [`aca6265`](https://github.com/inspect-js/object-inspect/commit/aca626536eaeef697196c6e9db3e90e7e0355b6a) +- [Refactor] consolidate wrapping logic for boxed primitives into a function. [`4e440cd`](https://github.com/inspect-js/object-inspect/commit/4e440cd9065df04802a2a1dead03f48c353ca301) +- [Robustness] use `typeof` instead of comparing to literal `undefined` [`5ca6f60`](https://github.com/inspect-js/object-inspect/commit/5ca6f601937506daff8ed2fcf686363b55807b69) +- [Refactor] consolidate Map/Set notations. [`4e576e5`](https://github.com/inspect-js/object-inspect/commit/4e576e5d7ed2f9ec3fb7f37a0d16732eb10758a9) +- [Tests] ensure that this function remains anonymous, despite ES6 name inference. [`7540ae5`](https://github.com/inspect-js/object-inspect/commit/7540ae591278756db614fa4def55ca413150e1a3) +- [Refactor] explicitly coerce Error objects to strings. [`7f4ca84`](https://github.com/inspect-js/object-inspect/commit/7f4ca8424ee8dc2c0ca5a422d94f7fac40327261) +- [Refactor] split up `var` declarations for debuggability [`6f2c11e`](https://github.com/inspect-js/object-inspect/commit/6f2c11e6a85418586a00292dcec5e97683f89bc3) +- [Robustness] cache `Object.prototype.toString` [`df44a20`](https://github.com/inspect-js/object-inspect/commit/df44a20adfccf31529d60d1df2079bfc3c836e27) +- [Dev Deps] update `tape` [`3ec714e`](https://github.com/inspect-js/object-inspect/commit/3ec714eba57bc3f58a6eb4fca1376f49e70d300a) +- [Dev Deps] update `tape` [`beb72d9`](https://github.com/inspect-js/object-inspect/commit/beb72d969653747d7cde300393c28755375329b0) + +## [v1.2.1](https://github.com/inspect-js/object-inspect/compare/v1.2.0...v1.2.1) - 2016-04-09 + +### Fixed + +- [Fix] fix Boolean `false` object inspection. [`#7`](https://github.com/substack/object-inspect/pull/7) + +## [v1.2.0](https://github.com/inspect-js/object-inspect/compare/v1.1.0...v1.2.0) - 2016-04-09 + +### Fixed + +- [New] add support for inspecting String/Number/Boolean objects. [`#6`](https://github.com/inspect-js/object-inspect/issues/6) + +### Commits + +- [Dev Deps] update `tape` [`742caa2`](https://github.com/inspect-js/object-inspect/commit/742caa262cf7af4c815d4821c8bd0129c1446432) + +## [v1.1.0](https://github.com/inspect-js/object-inspect/compare/1.0.2...v1.1.0) - 2015-12-14 + +### Merged + +- [New] add ES6 Map/Set support. [`#4`](https://github.com/inspect-js/object-inspect/pull/4) + +### Fixed + +- [New] add ES6 Map/Set support. [`#3`](https://github.com/inspect-js/object-inspect/issues/3) + +### Commits + +- Update `travis.yml` to test on bunches of `iojs` and `node` versions. [`4c1fd65`](https://github.com/inspect-js/object-inspect/commit/4c1fd65cc3bd95307e854d114b90478324287fd2) +- [Dev Deps] update `tape` [`88a907e`](https://github.com/inspect-js/object-inspect/commit/88a907e33afbe408e4b5d6e4e42a33143f88848c) + +## [1.0.2](https://github.com/inspect-js/object-inspect/compare/1.0.1...1.0.2) - 2015-08-07 + +### Commits + +- [Fix] Cache `Object.prototype.hasOwnProperty` in case it's deleted later. [`1d0075d`](https://github.com/inspect-js/object-inspect/commit/1d0075d3091dc82246feeb1f9871cb2b8ed227b3) +- [Dev Deps] Update `tape` [`ca8d5d7`](https://github.com/inspect-js/object-inspect/commit/ca8d5d75635ddbf76f944e628267581e04958457) +- gitignore node_modules since this is a reusable modules. [`ed41407`](https://github.com/inspect-js/object-inspect/commit/ed41407811743ca530cdeb28f982beb96026af82) + +## [1.0.1](https://github.com/inspect-js/object-inspect/compare/1.0.0...1.0.1) - 2015-07-19 + +### Commits + +- Make `inspect` work with symbol primitives and objects, including in node 0.11 and 0.12. [`ddf1b94`](https://github.com/inspect-js/object-inspect/commit/ddf1b94475ab951f1e3bccdc0a48e9073cfbfef4) +- bump tape [`103d674`](https://github.com/inspect-js/object-inspect/commit/103d67496b504bdcfdd765d303a773f87ec106e2) +- use newer travis config [`d497276`](https://github.com/inspect-js/object-inspect/commit/d497276c1da14234bb5098a59cf20de75fbc316a) + +## [1.0.0](https://github.com/inspect-js/object-inspect/compare/0.4.0...1.0.0) - 2014-08-05 + +### Commits + +- error inspect works properly [`260a22d`](https://github.com/inspect-js/object-inspect/commit/260a22d134d3a8a482c67d52091c6040c34f4299) +- seen coverage [`57269e8`](https://github.com/inspect-js/object-inspect/commit/57269e8baa992a7439047f47325111fdcbcb8417) +- htmlelement instance coverage [`397ffe1`](https://github.com/inspect-js/object-inspect/commit/397ffe10a1980350868043ef9de65686d438979f) +- more element coverage [`6905cc2`](https://github.com/inspect-js/object-inspect/commit/6905cc2f7df35600177e613b0642b4df5efd3eca) +- failing test for type errors [`385b615`](https://github.com/inspect-js/object-inspect/commit/385b6152e49b51b68449a662f410b084ed7c601a) +- fn name coverage [`edc906d`](https://github.com/inspect-js/object-inspect/commit/edc906d40fca6b9194d304062c037ee8e398c4c2) +- server-side element test [`362d1d3`](https://github.com/inspect-js/object-inspect/commit/362d1d3e86f187651c29feeb8478110afada385b) +- custom inspect fn [`e89b0f6`](https://github.com/inspect-js/object-inspect/commit/e89b0f6fe6d5e03681282af83732a509160435a6) +- fixed browser test [`b530882`](https://github.com/inspect-js/object-inspect/commit/b5308824a1c8471c5617e394766a03a6977102a9) +- depth test, matches node [`1cfd9e0`](https://github.com/inspect-js/object-inspect/commit/1cfd9e0285a4ae1dff44101ad482915d9bf47e48) +- exercise hasOwnProperty path [`8d753fb`](https://github.com/inspect-js/object-inspect/commit/8d753fb362a534fa1106e4d80f2ee9bea06a66d9) +- more cases covered for errors [`c5c46a5`](https://github.com/inspect-js/object-inspect/commit/c5c46a569ec4606583497e8550f0d8c7ad39a4a4) +- \W obj key test case [`b0eceee`](https://github.com/inspect-js/object-inspect/commit/b0eceeea6e0eb94d686c1046e99b9e25e5005f75) +- coverage for explicit depth param [`e12b91c`](https://github.com/inspect-js/object-inspect/commit/e12b91cd59683362f3a0e80f46481a0211e26c15) + +## [0.4.0](https://github.com/inspect-js/object-inspect/compare/0.3.1...0.4.0) - 2014-03-21 + +### Commits + +- passing lowbyte interpolation test [`b847511`](https://github.com/inspect-js/object-inspect/commit/b8475114f5def7e7961c5353d48d3d8d9a520985) +- lowbyte test [`4a2b0e1`](https://github.com/inspect-js/object-inspect/commit/4a2b0e142667fc933f195472759385ac08f3946c) + +## [0.3.1](https://github.com/inspect-js/object-inspect/compare/0.3.0...0.3.1) - 2014-03-04 + +### Commits + +- sort keys [`a07b19c`](https://github.com/inspect-js/object-inspect/commit/a07b19cc3b1521a82d4fafb6368b7a9775428a05) + +## [0.3.0](https://github.com/inspect-js/object-inspect/compare/0.2.0...0.3.0) - 2014-03-04 + +### Commits + +- [] and {} instead of [ ] and { } [`654c44b`](https://github.com/inspect-js/object-inspect/commit/654c44b2865811f3519e57bb8526e0821caf5c6b) + +## [0.2.0](https://github.com/inspect-js/object-inspect/compare/0.1.3...0.2.0) - 2014-03-04 + +### Commits + +- failing holes test [`99cdfad`](https://github.com/inspect-js/object-inspect/commit/99cdfad03c6474740275a75636fe6ca86c77737a) +- regex already work [`e324033`](https://github.com/inspect-js/object-inspect/commit/e324033267025995ec97d32ed0a65737c99477a6) +- failing undef/null test [`1f88a00`](https://github.com/inspect-js/object-inspect/commit/1f88a00265d3209719dda8117b7e6360b4c20943) +- holes in the all example [`7d345f3`](https://github.com/inspect-js/object-inspect/commit/7d345f3676dcbe980cff89a4f6c243269ebbb709) +- check for .inspect(), fixes Buffer use-case [`c3f7546`](https://github.com/inspect-js/object-inspect/commit/c3f75466dbca125347d49847c05262c292f12b79) +- fixes for holes [`ce25f73`](https://github.com/inspect-js/object-inspect/commit/ce25f736683de4b92ff27dc5471218415e2d78d8) +- weird null behavior [`405c1ea`](https://github.com/inspect-js/object-inspect/commit/405c1ea72cd5a8cf3b498c3eaa903d01b9fbcab5) +- tape is actually a devDependency, upgrade [`703b0ce`](https://github.com/inspect-js/object-inspect/commit/703b0ce6c5817b4245a082564bccd877e0bb6990) +- put date in the example [`a342219`](https://github.com/inspect-js/object-inspect/commit/a3422190eeaa013215f46df2d0d37b48595ac058) +- passing the null test [`4ab737e`](https://github.com/inspect-js/object-inspect/commit/4ab737ebf862a75d247ebe51e79307a34d6380d4) + +## [0.1.3](https://github.com/inspect-js/object-inspect/compare/0.1.1...0.1.3) - 2013-07-26 + +### Commits + +- special isElement() check [`882768a`](https://github.com/inspect-js/object-inspect/commit/882768a54035d30747be9de1baf14e5aa0daa128) +- oh right old IEs don't have indexOf either [`36d1275`](https://github.com/inspect-js/object-inspect/commit/36d12756c38b08a74370b0bb696c809e529913a5) + +## [0.1.1](https://github.com/inspect-js/object-inspect/compare/0.1.0...0.1.1) - 2013-07-26 + +### Commits + +- tests! [`4422fd9`](https://github.com/inspect-js/object-inspect/commit/4422fd95532c2745aa6c4f786f35f1090be29998) +- fix for ie<9, doesn't have hasOwnProperty [`6b7d611`](https://github.com/inspect-js/object-inspect/commit/6b7d61183050f6da801ea04473211da226482613) +- fix for all IEs: no f.name [`4e0c2f6`](https://github.com/inspect-js/object-inspect/commit/4e0c2f6dfd01c306d067d7163319acc97c94ee50) +- badges [`5ed0d88`](https://github.com/inspect-js/object-inspect/commit/5ed0d88e4e407f9cb327fa4a146c17921f9680f3) + +## [0.1.0](https://github.com/inspect-js/object-inspect/compare/0.0.0...0.1.0) - 2013-07-26 + +### Commits + +- [Function] for functions [`ad5c485`](https://github.com/inspect-js/object-inspect/commit/ad5c485098fc83352cb540a60b2548ca56820e0b) + +## 0.0.0 - 2013-07-26 + +### Commits + +- working browser example [`34be6b6`](https://github.com/inspect-js/object-inspect/commit/34be6b6548f9ce92bdc3c27572857ba0c4a1218d) +- package.json etc [`cad51f2`](https://github.com/inspect-js/object-inspect/commit/cad51f23fc6bcf1a456ed6abe16088256c2f632f) +- docs complete [`b80cce2`](https://github.com/inspect-js/object-inspect/commit/b80cce2490c4e7183a9ee11ea89071f0abec4446) +- circular example [`4b4a7b9`](https://github.com/inspect-js/object-inspect/commit/4b4a7b92209e4e6b4630976cb6bcd17d14165a59) +- string rep [`7afb479`](https://github.com/inspect-js/object-inspect/commit/7afb479baa798d27f09e0a178b72ea327f60f5c8) diff --git a/backend/node_modules/object-inspect/LICENSE b/backend/node_modules/object-inspect/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..ca64cc1e605205438cc1b04b215f6fc12ab3f039 --- /dev/null +++ b/backend/node_modules/object-inspect/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2013 James Halliday + +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/backend/node_modules/object-inspect/example/all.js b/backend/node_modules/object-inspect/example/all.js new file mode 100644 index 0000000000000000000000000000000000000000..2f3355c509acd1a0e9d409f9e655939d6d18c2ec --- /dev/null +++ b/backend/node_modules/object-inspect/example/all.js @@ -0,0 +1,23 @@ +'use strict'; + +var inspect = require('../'); +var Buffer = require('safer-buffer').Buffer; + +var holes = ['a', 'b']; +holes[4] = 'e'; +holes[6] = 'g'; + +var obj = { + a: 1, + b: [3, 4, undefined, null], + c: undefined, + d: null, + e: { + regex: /^x/i, + buf: Buffer.from('abc'), + holes: holes + }, + now: new Date() +}; +obj.self = obj; +console.log(inspect(obj)); diff --git a/backend/node_modules/object-inspect/example/circular.js b/backend/node_modules/object-inspect/example/circular.js new file mode 100644 index 0000000000000000000000000000000000000000..487a7c169d0df8c4acb6ad02b26ce76175ecfc0f --- /dev/null +++ b/backend/node_modules/object-inspect/example/circular.js @@ -0,0 +1,6 @@ +'use strict'; + +var inspect = require('../'); +var obj = { a: 1, b: [3, 4] }; +obj.c = obj; +console.log(inspect(obj)); diff --git a/backend/node_modules/object-inspect/example/fn.js b/backend/node_modules/object-inspect/example/fn.js new file mode 100644 index 0000000000000000000000000000000000000000..9b5db8de036ffc6718969bee9193de36409235aa --- /dev/null +++ b/backend/node_modules/object-inspect/example/fn.js @@ -0,0 +1,5 @@ +'use strict'; + +var inspect = require('../'); +var obj = [1, 2, function f(n) { return n + 5; }, 4]; +console.log(inspect(obj)); diff --git a/backend/node_modules/object-inspect/example/inspect.js b/backend/node_modules/object-inspect/example/inspect.js new file mode 100644 index 0000000000000000000000000000000000000000..e2df7c9f471356c48f14e7af2813119ffb6854bb --- /dev/null +++ b/backend/node_modules/object-inspect/example/inspect.js @@ -0,0 +1,10 @@ +'use strict'; + +/* eslint-env browser */ +var inspect = require('../'); + +var d = document.createElement('div'); +d.setAttribute('id', 'beep'); +d.innerHTML = 'woooiiiii'; + +console.log(inspect([d, { a: 3, b: 4, c: [5, 6, [7, [8, [9]]]] }])); diff --git a/backend/node_modules/object-inspect/index.js b/backend/node_modules/object-inspect/index.js new file mode 100644 index 0000000000000000000000000000000000000000..ff203349231e381af6a6525b832172628b7c3c69 --- /dev/null +++ b/backend/node_modules/object-inspect/index.js @@ -0,0 +1,524 @@ +var hasMap = typeof Map === 'function' && Map.prototype; +var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, 'size') : null; +var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === 'function' ? mapSizeDescriptor.get : null; +var mapForEach = hasMap && Map.prototype.forEach; +var hasSet = typeof Set === 'function' && Set.prototype; +var setSizeDescriptor = Object.getOwnPropertyDescriptor && hasSet ? Object.getOwnPropertyDescriptor(Set.prototype, 'size') : null; +var setSize = hasSet && setSizeDescriptor && typeof setSizeDescriptor.get === 'function' ? setSizeDescriptor.get : null; +var setForEach = hasSet && Set.prototype.forEach; +var hasWeakMap = typeof WeakMap === 'function' && WeakMap.prototype; +var weakMapHas = hasWeakMap ? WeakMap.prototype.has : null; +var hasWeakSet = typeof WeakSet === 'function' && WeakSet.prototype; +var weakSetHas = hasWeakSet ? WeakSet.prototype.has : null; +var hasWeakRef = typeof WeakRef === 'function' && WeakRef.prototype; +var weakRefDeref = hasWeakRef ? WeakRef.prototype.deref : null; +var booleanValueOf = Boolean.prototype.valueOf; +var objectToString = Object.prototype.toString; +var functionToString = Function.prototype.toString; +var $match = String.prototype.match; +var $slice = String.prototype.slice; +var $replace = String.prototype.replace; +var $toUpperCase = String.prototype.toUpperCase; +var $toLowerCase = String.prototype.toLowerCase; +var $test = RegExp.prototype.test; +var $concat = Array.prototype.concat; +var $join = Array.prototype.join; +var $arrSlice = Array.prototype.slice; +var $floor = Math.floor; +var bigIntValueOf = typeof BigInt === 'function' ? BigInt.prototype.valueOf : null; +var gOPS = Object.getOwnPropertySymbols; +var symToString = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? Symbol.prototype.toString : null; +var hasShammedSymbols = typeof Symbol === 'function' && typeof Symbol.iterator === 'object'; +// ie, `has-tostringtag/shams +var toStringTag = typeof Symbol === 'function' && Symbol.toStringTag && (typeof Symbol.toStringTag === hasShammedSymbols ? 'object' : 'symbol') + ? Symbol.toStringTag + : null; +var isEnumerable = Object.prototype.propertyIsEnumerable; + +var gPO = (typeof Reflect === 'function' ? Reflect.getPrototypeOf : Object.getPrototypeOf) || ( + [].__proto__ === Array.prototype // eslint-disable-line no-proto + ? function (O) { + return O.__proto__; // eslint-disable-line no-proto + } + : null +); + +function addNumericSeparator(num, str) { + if ( + num === Infinity + || num === -Infinity + || num !== num + || (num && num > -1000 && num < 1000) + || $test.call(/e/, str) + ) { + return str; + } + var sepRegex = /[0-9](?=(?:[0-9]{3})+(?![0-9]))/g; + if (typeof num === 'number') { + var int = num < 0 ? -$floor(-num) : $floor(num); // trunc(num) + if (int !== num) { + var intStr = String(int); + var dec = $slice.call(str, intStr.length + 1); + return $replace.call(intStr, sepRegex, '$&_') + '.' + $replace.call($replace.call(dec, /([0-9]{3})/g, '$&_'), /_$/, ''); + } + } + return $replace.call(str, sepRegex, '$&_'); +} + +var utilInspect = require('./util.inspect'); +var inspectCustom = utilInspect.custom; +var inspectSymbol = isSymbol(inspectCustom) ? inspectCustom : null; + +module.exports = function inspect_(obj, options, depth, seen) { + var opts = options || {}; + + if (has(opts, 'quoteStyle') && (opts.quoteStyle !== 'single' && opts.quoteStyle !== 'double')) { + throw new TypeError('option "quoteStyle" must be "single" or "double"'); + } + if ( + has(opts, 'maxStringLength') && (typeof opts.maxStringLength === 'number' + ? opts.maxStringLength < 0 && opts.maxStringLength !== Infinity + : opts.maxStringLength !== null + ) + ) { + throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`'); + } + var customInspect = has(opts, 'customInspect') ? opts.customInspect : true; + if (typeof customInspect !== 'boolean' && customInspect !== 'symbol') { + throw new TypeError('option "customInspect", if provided, must be `true`, `false`, or `\'symbol\'`'); + } + + if ( + has(opts, 'indent') + && opts.indent !== null + && opts.indent !== '\t' + && !(parseInt(opts.indent, 10) === opts.indent && opts.indent > 0) + ) { + throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`'); + } + if (has(opts, 'numericSeparator') && typeof opts.numericSeparator !== 'boolean') { + throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`'); + } + var numericSeparator = opts.numericSeparator; + + if (typeof obj === 'undefined') { + return 'undefined'; + } + if (obj === null) { + return 'null'; + } + if (typeof obj === 'boolean') { + return obj ? 'true' : 'false'; + } + + if (typeof obj === 'string') { + return inspectString(obj, opts); + } + if (typeof obj === 'number') { + if (obj === 0) { + return Infinity / obj > 0 ? '0' : '-0'; + } + var str = String(obj); + return numericSeparator ? addNumericSeparator(obj, str) : str; + } + if (typeof obj === 'bigint') { + var bigIntStr = String(obj) + 'n'; + return numericSeparator ? addNumericSeparator(obj, bigIntStr) : bigIntStr; + } + + var maxDepth = typeof opts.depth === 'undefined' ? 5 : opts.depth; + if (typeof depth === 'undefined') { depth = 0; } + if (depth >= maxDepth && maxDepth > 0 && typeof obj === 'object') { + return isArray(obj) ? '[Array]' : '[Object]'; + } + + var indent = getIndent(opts, depth); + + if (typeof seen === 'undefined') { + seen = []; + } else if (indexOf(seen, obj) >= 0) { + return '[Circular]'; + } + + function inspect(value, from, noIndent) { + if (from) { + seen = $arrSlice.call(seen); + seen.push(from); + } + if (noIndent) { + var newOpts = { + depth: opts.depth + }; + if (has(opts, 'quoteStyle')) { + newOpts.quoteStyle = opts.quoteStyle; + } + return inspect_(value, newOpts, depth + 1, seen); + } + return inspect_(value, opts, depth + 1, seen); + } + + if (typeof obj === 'function' && !isRegExp(obj)) { // in older engines, regexes are callable + var name = nameOf(obj); + var keys = arrObjKeys(obj, inspect); + return '[Function' + (name ? ': ' + name : ' (anonymous)') + ']' + (keys.length > 0 ? ' { ' + $join.call(keys, ', ') + ' }' : ''); + } + if (isSymbol(obj)) { + var symString = hasShammedSymbols ? $replace.call(String(obj), /^(Symbol\(.*\))_[^)]*$/, '$1') : symToString.call(obj); + return typeof obj === 'object' && !hasShammedSymbols ? markBoxed(symString) : symString; + } + if (isElement(obj)) { + var s = '<' + $toLowerCase.call(String(obj.nodeName)); + var attrs = obj.attributes || []; + for (var i = 0; i < attrs.length; i++) { + s += ' ' + attrs[i].name + '=' + wrapQuotes(quote(attrs[i].value), 'double', opts); + } + s += '>'; + if (obj.childNodes && obj.childNodes.length) { s += '...'; } + s += ''; + return s; + } + if (isArray(obj)) { + if (obj.length === 0) { return '[]'; } + var xs = arrObjKeys(obj, inspect); + if (indent && !singleLineValues(xs)) { + return '[' + indentedJoin(xs, indent) + ']'; + } + return '[ ' + $join.call(xs, ', ') + ' ]'; + } + if (isError(obj)) { + var parts = arrObjKeys(obj, inspect); + if (!('cause' in Error.prototype) && 'cause' in obj && !isEnumerable.call(obj, 'cause')) { + return '{ [' + String(obj) + '] ' + $join.call($concat.call('[cause]: ' + inspect(obj.cause), parts), ', ') + ' }'; + } + if (parts.length === 0) { return '[' + String(obj) + ']'; } + return '{ [' + String(obj) + '] ' + $join.call(parts, ', ') + ' }'; + } + if (typeof obj === 'object' && customInspect) { + if (inspectSymbol && typeof obj[inspectSymbol] === 'function' && utilInspect) { + return utilInspect(obj, { depth: maxDepth - depth }); + } else if (customInspect !== 'symbol' && typeof obj.inspect === 'function') { + return obj.inspect(); + } + } + if (isMap(obj)) { + var mapParts = []; + if (mapForEach) { + mapForEach.call(obj, function (value, key) { + mapParts.push(inspect(key, obj, true) + ' => ' + inspect(value, obj)); + }); + } + return collectionOf('Map', mapSize.call(obj), mapParts, indent); + } + if (isSet(obj)) { + var setParts = []; + if (setForEach) { + setForEach.call(obj, function (value) { + setParts.push(inspect(value, obj)); + }); + } + return collectionOf('Set', setSize.call(obj), setParts, indent); + } + if (isWeakMap(obj)) { + return weakCollectionOf('WeakMap'); + } + if (isWeakSet(obj)) { + return weakCollectionOf('WeakSet'); + } + if (isWeakRef(obj)) { + return weakCollectionOf('WeakRef'); + } + if (isNumber(obj)) { + return markBoxed(inspect(Number(obj))); + } + if (isBigInt(obj)) { + return markBoxed(inspect(bigIntValueOf.call(obj))); + } + if (isBoolean(obj)) { + return markBoxed(booleanValueOf.call(obj)); + } + if (isString(obj)) { + return markBoxed(inspect(String(obj))); + } + // note: in IE 8, sometimes `global !== window` but both are the prototypes of each other + /* eslint-env browser */ + if (typeof window !== 'undefined' && obj === window) { + return '{ [object Window] }'; + } + if (obj === global) { + return '{ [object globalThis] }'; + } + if (!isDate(obj) && !isRegExp(obj)) { + var ys = arrObjKeys(obj, inspect); + var isPlainObject = gPO ? gPO(obj) === Object.prototype : obj instanceof Object || obj.constructor === Object; + var protoTag = obj instanceof Object ? '' : 'null prototype'; + var stringTag = !isPlainObject && toStringTag && Object(obj) === obj && toStringTag in obj ? $slice.call(toStr(obj), 8, -1) : protoTag ? 'Object' : ''; + var constructorTag = isPlainObject || typeof obj.constructor !== 'function' ? '' : obj.constructor.name ? obj.constructor.name + ' ' : ''; + var tag = constructorTag + (stringTag || protoTag ? '[' + $join.call($concat.call([], stringTag || [], protoTag || []), ': ') + '] ' : ''); + if (ys.length === 0) { return tag + '{}'; } + if (indent) { + return tag + '{' + indentedJoin(ys, indent) + '}'; + } + return tag + '{ ' + $join.call(ys, ', ') + ' }'; + } + return String(obj); +}; + +function wrapQuotes(s, defaultStyle, opts) { + var quoteChar = (opts.quoteStyle || defaultStyle) === 'double' ? '"' : "'"; + return quoteChar + s + quoteChar; +} + +function quote(s) { + return $replace.call(String(s), /"/g, '"'); +} + +function isArray(obj) { return toStr(obj) === '[object Array]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } +function isDate(obj) { return toStr(obj) === '[object Date]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } +function isRegExp(obj) { return toStr(obj) === '[object RegExp]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } +function isError(obj) { return toStr(obj) === '[object Error]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } +function isString(obj) { return toStr(obj) === '[object String]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } +function isNumber(obj) { return toStr(obj) === '[object Number]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } +function isBoolean(obj) { return toStr(obj) === '[object Boolean]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } + +// Symbol and BigInt do have Symbol.toStringTag by spec, so that can't be used to eliminate false positives +function isSymbol(obj) { + if (hasShammedSymbols) { + return obj && typeof obj === 'object' && obj instanceof Symbol; + } + if (typeof obj === 'symbol') { + return true; + } + if (!obj || typeof obj !== 'object' || !symToString) { + return false; + } + try { + symToString.call(obj); + return true; + } catch (e) {} + return false; +} + +function isBigInt(obj) { + if (!obj || typeof obj !== 'object' || !bigIntValueOf) { + return false; + } + try { + bigIntValueOf.call(obj); + return true; + } catch (e) {} + return false; +} + +var hasOwn = Object.prototype.hasOwnProperty || function (key) { return key in this; }; +function has(obj, key) { + return hasOwn.call(obj, key); +} + +function toStr(obj) { + return objectToString.call(obj); +} + +function nameOf(f) { + if (f.name) { return f.name; } + var m = $match.call(functionToString.call(f), /^function\s*([\w$]+)/); + if (m) { return m[1]; } + return null; +} + +function indexOf(xs, x) { + if (xs.indexOf) { return xs.indexOf(x); } + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) { return i; } + } + return -1; +} + +function isMap(x) { + if (!mapSize || !x || typeof x !== 'object') { + return false; + } + try { + mapSize.call(x); + try { + setSize.call(x); + } catch (s) { + return true; + } + return x instanceof Map; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; +} + +function isWeakMap(x) { + if (!weakMapHas || !x || typeof x !== 'object') { + return false; + } + try { + weakMapHas.call(x, weakMapHas); + try { + weakSetHas.call(x, weakSetHas); + } catch (s) { + return true; + } + return x instanceof WeakMap; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; +} + +function isWeakRef(x) { + if (!weakRefDeref || !x || typeof x !== 'object') { + return false; + } + try { + weakRefDeref.call(x); + return true; + } catch (e) {} + return false; +} + +function isSet(x) { + if (!setSize || !x || typeof x !== 'object') { + return false; + } + try { + setSize.call(x); + try { + mapSize.call(x); + } catch (m) { + return true; + } + return x instanceof Set; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; +} + +function isWeakSet(x) { + if (!weakSetHas || !x || typeof x !== 'object') { + return false; + } + try { + weakSetHas.call(x, weakSetHas); + try { + weakMapHas.call(x, weakMapHas); + } catch (s) { + return true; + } + return x instanceof WeakSet; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; +} + +function isElement(x) { + if (!x || typeof x !== 'object') { return false; } + if (typeof HTMLElement !== 'undefined' && x instanceof HTMLElement) { + return true; + } + return typeof x.nodeName === 'string' && typeof x.getAttribute === 'function'; +} + +function inspectString(str, opts) { + if (str.length > opts.maxStringLength) { + var remaining = str.length - opts.maxStringLength; + var trailer = '... ' + remaining + ' more character' + (remaining > 1 ? 's' : ''); + return inspectString($slice.call(str, 0, opts.maxStringLength), opts) + trailer; + } + // eslint-disable-next-line no-control-regex + var s = $replace.call($replace.call(str, /(['\\])/g, '\\$1'), /[\x00-\x1f]/g, lowbyte); + return wrapQuotes(s, 'single', opts); +} + +function lowbyte(c) { + var n = c.charCodeAt(0); + var x = { + 8: 'b', + 9: 't', + 10: 'n', + 12: 'f', + 13: 'r' + }[n]; + if (x) { return '\\' + x; } + return '\\x' + (n < 0x10 ? '0' : '') + $toUpperCase.call(n.toString(16)); +} + +function markBoxed(str) { + return 'Object(' + str + ')'; +} + +function weakCollectionOf(type) { + return type + ' { ? }'; +} + +function collectionOf(type, size, entries, indent) { + var joinedEntries = indent ? indentedJoin(entries, indent) : $join.call(entries, ', '); + return type + ' (' + size + ') {' + joinedEntries + '}'; +} + +function singleLineValues(xs) { + for (var i = 0; i < xs.length; i++) { + if (indexOf(xs[i], '\n') >= 0) { + return false; + } + } + return true; +} + +function getIndent(opts, depth) { + var baseIndent; + if (opts.indent === '\t') { + baseIndent = '\t'; + } else if (typeof opts.indent === 'number' && opts.indent > 0) { + baseIndent = $join.call(Array(opts.indent + 1), ' '); + } else { + return null; + } + return { + base: baseIndent, + prev: $join.call(Array(depth + 1), baseIndent) + }; +} + +function indentedJoin(xs, indent) { + if (xs.length === 0) { return ''; } + var lineJoiner = '\n' + indent.prev + indent.base; + return lineJoiner + $join.call(xs, ',' + lineJoiner) + '\n' + indent.prev; +} + +function arrObjKeys(obj, inspect) { + var isArr = isArray(obj); + var xs = []; + if (isArr) { + xs.length = obj.length; + for (var i = 0; i < obj.length; i++) { + xs[i] = has(obj, i) ? inspect(obj[i], obj) : ''; + } + } + var syms = typeof gOPS === 'function' ? gOPS(obj) : []; + var symMap; + if (hasShammedSymbols) { + symMap = {}; + for (var k = 0; k < syms.length; k++) { + symMap['$' + syms[k]] = syms[k]; + } + } + + for (var key in obj) { // eslint-disable-line no-restricted-syntax + if (!has(obj, key)) { continue; } // eslint-disable-line no-restricted-syntax, no-continue + if (isArr && String(Number(key)) === key && key < obj.length) { continue; } // eslint-disable-line no-restricted-syntax, no-continue + if (hasShammedSymbols && symMap['$' + key] instanceof Symbol) { + // this is to prevent shammed Symbols, which are stored as strings, from being included in the string key section + continue; // eslint-disable-line no-restricted-syntax, no-continue + } else if ($test.call(/[^\w$]/, key)) { + xs.push(inspect(key, obj) + ': ' + inspect(obj[key], obj)); + } else { + xs.push(key + ': ' + inspect(obj[key], obj)); + } + } + if (typeof gOPS === 'function') { + for (var j = 0; j < syms.length; j++) { + if (isEnumerable.call(obj, syms[j])) { + xs.push('[' + inspect(syms[j]) + ']: ' + inspect(obj[syms[j]], obj)); + } + } + } + return xs; +} diff --git a/backend/node_modules/object-inspect/package-support.json b/backend/node_modules/object-inspect/package-support.json new file mode 100644 index 0000000000000000000000000000000000000000..5cc12d0585a386018d3c486be5a841d8377d15db --- /dev/null +++ b/backend/node_modules/object-inspect/package-support.json @@ -0,0 +1,20 @@ +{ + "versions": [ + { + "version": "*", + "target": { + "node": "all" + }, + "response": { + "type": "time-permitting" + }, + "backing": { + "npm-funding": true, + "donations": [ + "https://github.com/ljharb", + "https://tidelift.com/funding/github/npm/object-inspect" + ] + } + } + ] +} diff --git a/backend/node_modules/object-inspect/package.json b/backend/node_modules/object-inspect/package.json new file mode 100644 index 0000000000000000000000000000000000000000..02de342ecb2d9aa4882e7e16a46a1e877f67e8dd --- /dev/null +++ b/backend/node_modules/object-inspect/package.json @@ -0,0 +1,99 @@ +{ + "name": "object-inspect", + "version": "1.13.1", + "description": "string representations of objects in node and the browser", + "main": "index.js", + "sideEffects": false, + "devDependencies": { + "@ljharb/eslint-config": "^21.1.0", + "@pkgjs/support": "^0.0.6", + "auto-changelog": "^2.4.0", + "core-js": "^2.6.12", + "error-cause": "^1.0.6", + "es-value-fixtures": "^1.4.2", + "eslint": "=8.8.0", + "for-each": "^0.3.3", + "functions-have-names": "^1.2.3", + "glob": "=10.3.7", + "globalthis": "^1.0.3", + "has-tostringtag": "^1.0.0", + "in-publish": "^2.0.1", + "jackspeak": "=2.1.1", + "make-arrow-function": "^1.2.0", + "mock-property": "^1.0.2", + "npmignore": "^0.3.0", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "string.prototype.repeat": "^1.0.0", + "tape": "^5.7.1" + }, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "pretest": "npm run lint", + "lint": "eslint --ext=js,mjs .", + "postlint": "npx @pkgjs/support validate", + "test": "npm run tests-only && npm run test:corejs", + "tests-only": "nyc tape 'test/*.js'", + "test:corejs": "nyc tape test-core-js.js 'test/*.js'", + "posttest": "npx aud --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)\")\"" + }, + "testling": { + "files": [ + "test/*.js", + "test/browser/*.js" + ], + "browsers": [ + "ie/6..latest", + "chrome/latest", + "firefox/latest", + "safari/latest", + "opera/latest", + "iphone/latest", + "ipad/latest", + "android/latest" + ] + }, + "repository": { + "type": "git", + "url": "git://github.com/inspect-js/object-inspect.git" + }, + "homepage": "https://github.com/inspect-js/object-inspect", + "keywords": [ + "inspect", + "util.inspect", + "object", + "stringify", + "pretty" + ], + "author": { + "name": "James Halliday", + "email": "mail@substack.net", + "url": "http://substack.net" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "browser": { + "./util.inspect.js": false + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows", + "./test-core-js.js" + ] + }, + "support": true +} diff --git a/backend/node_modules/object-inspect/readme.markdown b/backend/node_modules/object-inspect/readme.markdown new file mode 100644 index 0000000000000000000000000000000000000000..9ff6bec3661be5c09ed95bfc0971de871280fe6c --- /dev/null +++ b/backend/node_modules/object-inspect/readme.markdown @@ -0,0 +1,86 @@ +# object-inspect [![Version Badge][2]][1] + +string representations of objects in node and the browser + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][5]][6] +[![dev dependency status][7]][8] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][11]][1] + +# example + +## circular + +``` js +var inspect = require('object-inspect'); +var obj = { a: 1, b: [3,4] }; +obj.c = obj; +console.log(inspect(obj)); +``` + +## dom element + +``` js +var inspect = require('object-inspect'); + +var d = document.createElement('div'); +d.setAttribute('id', 'beep'); +d.innerHTML = 'woooiiiii'; + +console.log(inspect([ d, { a: 3, b : 4, c: [5,6,[7,[8,[9]]]] } ])); +``` + +output: + +``` +[
...
, { a: 3, b: 4, c: [ 5, 6, [ 7, [ 8, [ ... ] ] ] ] } ] +``` + +# methods + +``` js +var inspect = require('object-inspect') +``` + +## var s = inspect(obj, opts={}) + +Return a string `s` with the string representation of `obj` up to a depth of `opts.depth`. + +Additional options: + - `quoteStyle`: must be "single" or "double", if present. Default `'single'` for strings, `'double'` for HTML elements. + - `maxStringLength`: must be `0`, a positive integer, `Infinity`, or `null`, if present. Default `Infinity`. + - `customInspect`: When `true`, a custom inspect method function will be invoked (either undere the `util.inspect.custom` symbol, or the `inspect` property). When the string `'symbol'`, only the symbol method will be invoked. Default `true`. + - `indent`: must be "\t", `null`, or a positive integer. Default `null`. + - `numericSeparator`: must be a boolean, if present. Default `false`. If `true`, all numbers will be printed with numeric separators (eg, `1234.5678` will be printed as `'1_234.567_8'`) + +# install + +With [npm](https://npmjs.org) do: + +``` +npm install object-inspect +``` + +# license + +MIT + +[1]: https://npmjs.org/package/object-inspect +[2]: https://versionbadg.es/inspect-js/object-inspect.svg +[5]: https://david-dm.org/inspect-js/object-inspect.svg +[6]: https://david-dm.org/inspect-js/object-inspect +[7]: https://david-dm.org/inspect-js/object-inspect/dev-status.svg +[8]: https://david-dm.org/inspect-js/object-inspect#info=devDependencies +[11]: https://nodei.co/npm/object-inspect.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/object-inspect.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/object-inspect.svg +[downloads-url]: https://npm-stat.com/charts.html?package=object-inspect +[codecov-image]: https://codecov.io/gh/inspect-js/object-inspect/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/object-inspect/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/object-inspect +[actions-url]: https://github.com/inspect-js/object-inspect/actions diff --git a/backend/node_modules/object-inspect/test-core-js.js b/backend/node_modules/object-inspect/test-core-js.js new file mode 100644 index 0000000000000000000000000000000000000000..e53c40022533f691fd17d623cd24a8ecb5a82669 --- /dev/null +++ b/backend/node_modules/object-inspect/test-core-js.js @@ -0,0 +1,26 @@ +'use strict'; + +require('core-js'); + +var inspect = require('./'); +var test = require('tape'); + +test('Maps', function (t) { + t.equal(inspect(new Map([[1, 2]])), 'Map (1) {1 => 2}'); + t.end(); +}); + +test('WeakMaps', function (t) { + t.equal(inspect(new WeakMap([[{}, 2]])), 'WeakMap { ? }'); + t.end(); +}); + +test('Sets', function (t) { + t.equal(inspect(new Set([[1, 2]])), 'Set (1) {[ 1, 2 ]}'); + t.end(); +}); + +test('WeakSets', function (t) { + t.equal(inspect(new WeakSet([[1, 2]])), 'WeakSet { ? }'); + t.end(); +}); diff --git a/backend/node_modules/object-inspect/test/bigint.js b/backend/node_modules/object-inspect/test/bigint.js new file mode 100644 index 0000000000000000000000000000000000000000..4ecc31df8ab3fd311570d866b418514d159abfde --- /dev/null +++ b/backend/node_modules/object-inspect/test/bigint.js @@ -0,0 +1,58 @@ +'use strict'; + +var inspect = require('../'); +var test = require('tape'); +var hasToStringTag = require('has-tostringtag/shams')(); + +test('bigint', { skip: typeof BigInt === 'undefined' }, function (t) { + t.test('primitives', function (st) { + st.plan(3); + + st.equal(inspect(BigInt(-256)), '-256n'); + st.equal(inspect(BigInt(0)), '0n'); + st.equal(inspect(BigInt(256)), '256n'); + }); + + t.test('objects', function (st) { + st.plan(3); + + st.equal(inspect(Object(BigInt(-256))), 'Object(-256n)'); + st.equal(inspect(Object(BigInt(0))), 'Object(0n)'); + st.equal(inspect(Object(BigInt(256))), 'Object(256n)'); + }); + + t.test('syntactic primitives', function (st) { + st.plan(3); + + /* eslint-disable no-new-func */ + st.equal(inspect(Function('return -256n')()), '-256n'); + st.equal(inspect(Function('return 0n')()), '0n'); + st.equal(inspect(Function('return 256n')()), '256n'); + }); + + t.test('toStringTag', { skip: !hasToStringTag }, function (st) { + st.plan(1); + + var faker = {}; + faker[Symbol.toStringTag] = 'BigInt'; + st.equal( + inspect(faker), + '{ [Symbol(Symbol.toStringTag)]: \'BigInt\' }', + 'object lying about being a BigInt inspects as an object' + ); + }); + + t.test('numericSeparator', function (st) { + st.equal(inspect(BigInt(0), { numericSeparator: false }), '0n', '0n, numericSeparator false'); + st.equal(inspect(BigInt(0), { numericSeparator: true }), '0n', '0n, numericSeparator true'); + + st.equal(inspect(BigInt(1234), { numericSeparator: false }), '1234n', '1234n, numericSeparator false'); + st.equal(inspect(BigInt(1234), { numericSeparator: true }), '1_234n', '1234n, numericSeparator true'); + st.equal(inspect(BigInt(-1234), { numericSeparator: false }), '-1234n', '1234n, numericSeparator false'); + st.equal(inspect(BigInt(-1234), { numericSeparator: true }), '-1_234n', '1234n, numericSeparator true'); + + st.end(); + }); + + t.end(); +}); diff --git a/backend/node_modules/object-inspect/test/browser/dom.js b/backend/node_modules/object-inspect/test/browser/dom.js new file mode 100644 index 0000000000000000000000000000000000000000..210c0b233e9f72c5733ef80fa38a3e8a315e5c29 --- /dev/null +++ b/backend/node_modules/object-inspect/test/browser/dom.js @@ -0,0 +1,15 @@ +var inspect = require('../../'); +var test = require('tape'); + +test('dom element', function (t) { + t.plan(1); + + var d = document.createElement('div'); + d.setAttribute('id', 'beep'); + d.innerHTML = 'woooiiiii'; + + t.equal( + inspect([d, { a: 3, b: 4, c: [5, 6, [7, [8, [9]]]] }]), + '[
...
, { a: 3, b: 4, c: [ 5, 6, [ 7, [ 8, [Object] ] ] ] } ]' + ); +}); diff --git a/backend/node_modules/object-inspect/test/circular.js b/backend/node_modules/object-inspect/test/circular.js new file mode 100644 index 0000000000000000000000000000000000000000..5df4233cb202efc92a8e874ef74f0c69d6ac29d1 --- /dev/null +++ b/backend/node_modules/object-inspect/test/circular.js @@ -0,0 +1,16 @@ +var inspect = require('../'); +var test = require('tape'); + +test('circular', function (t) { + t.plan(2); + var obj = { a: 1, b: [3, 4] }; + obj.c = obj; + t.equal(inspect(obj), '{ a: 1, b: [ 3, 4 ], c: [Circular] }'); + + var double = {}; + double.a = [double]; + double.b = {}; + double.b.inner = double.b; + double.b.obj = double; + t.equal(inspect(double), '{ a: [ [Circular] ], b: { inner: [Circular], obj: [Circular] } }'); +}); diff --git a/backend/node_modules/object-inspect/test/deep.js b/backend/node_modules/object-inspect/test/deep.js new file mode 100644 index 0000000000000000000000000000000000000000..99ce32a088f90f217c1e4b001f4e41d3ddd4f3ec --- /dev/null +++ b/backend/node_modules/object-inspect/test/deep.js @@ -0,0 +1,12 @@ +var inspect = require('../'); +var test = require('tape'); + +test('deep', function (t) { + t.plan(4); + var obj = [[[[[[500]]]]]]; + t.equal(inspect(obj), '[ [ [ [ [ [Array] ] ] ] ] ]'); + t.equal(inspect(obj, { depth: 4 }), '[ [ [ [ [Array] ] ] ] ]'); + t.equal(inspect(obj, { depth: 2 }), '[ [ [Array] ] ]'); + + t.equal(inspect([[[{ a: 1 }]]], { depth: 3 }), '[ [ [ [Object] ] ] ]'); +}); diff --git a/backend/node_modules/object-inspect/test/element.js b/backend/node_modules/object-inspect/test/element.js new file mode 100644 index 0000000000000000000000000000000000000000..47fa9e240029eb6fa2906727e20ec843fc3b6308 --- /dev/null +++ b/backend/node_modules/object-inspect/test/element.js @@ -0,0 +1,53 @@ +var inspect = require('../'); +var test = require('tape'); + +test('element', function (t) { + t.plan(3); + var elem = { + nodeName: 'div', + attributes: [{ name: 'class', value: 'row' }], + getAttribute: function (key) { return key; }, + childNodes: [] + }; + var obj = [1, elem, 3]; + t.deepEqual(inspect(obj), '[ 1,
, 3 ]'); + t.deepEqual(inspect(obj, { quoteStyle: 'single' }), "[ 1,
, 3 ]"); + t.deepEqual(inspect(obj, { quoteStyle: 'double' }), '[ 1,
, 3 ]'); +}); + +test('element no attr', function (t) { + t.plan(1); + var elem = { + nodeName: 'div', + getAttribute: function (key) { return key; }, + childNodes: [] + }; + var obj = [1, elem, 3]; + t.deepEqual(inspect(obj), '[ 1,
, 3 ]'); +}); + +test('element with contents', function (t) { + t.plan(1); + var elem = { + nodeName: 'div', + getAttribute: function (key) { return key; }, + childNodes: [{ nodeName: 'b' }] + }; + var obj = [1, elem, 3]; + t.deepEqual(inspect(obj), '[ 1,
...
, 3 ]'); +}); + +test('element instance', function (t) { + t.plan(1); + var h = global.HTMLElement; + global.HTMLElement = function (name, attr) { + this.nodeName = name; + this.attributes = attr; + }; + global.HTMLElement.prototype.getAttribute = function () {}; + + var elem = new global.HTMLElement('div', []); + var obj = [1, elem, 3]; + t.deepEqual(inspect(obj), '[ 1,
, 3 ]'); + global.HTMLElement = h; +}); diff --git a/backend/node_modules/object-inspect/test/err.js b/backend/node_modules/object-inspect/test/err.js new file mode 100644 index 0000000000000000000000000000000000000000..cc1d884abdc52c8b5443b6212ab1d0d886ce9c33 --- /dev/null +++ b/backend/node_modules/object-inspect/test/err.js @@ -0,0 +1,48 @@ +var test = require('tape'); +var ErrorWithCause = require('error-cause/Error'); + +var inspect = require('../'); + +test('type error', function (t) { + t.plan(1); + var aerr = new TypeError(); + aerr.foo = 555; + aerr.bar = [1, 2, 3]; + + var berr = new TypeError('tuv'); + berr.baz = 555; + + var cerr = new SyntaxError(); + cerr.message = 'whoa'; + cerr['a-b'] = 5; + + var withCause = new ErrorWithCause('foo', { cause: 'bar' }); + var withCausePlus = new ErrorWithCause('foo', { cause: 'bar' }); + withCausePlus.foo = 'bar'; + var withUndefinedCause = new ErrorWithCause('foo', { cause: undefined }); + var withEnumerableCause = new Error('foo'); + withEnumerableCause.cause = 'bar'; + + var obj = [ + new TypeError(), + new TypeError('xxx'), + aerr, + berr, + cerr, + withCause, + withCausePlus, + withUndefinedCause, + withEnumerableCause + ]; + t.equal(inspect(obj), '[ ' + [ + '[TypeError]', + '[TypeError: xxx]', + '{ [TypeError] foo: 555, bar: [ 1, 2, 3 ] }', + '{ [TypeError: tuv] baz: 555 }', + '{ [SyntaxError: whoa] message: \'whoa\', \'a-b\': 5 }', + 'cause' in Error.prototype ? '[Error: foo]' : '{ [Error: foo] [cause]: \'bar\' }', + '{ [Error: foo] ' + ('cause' in Error.prototype ? '' : '[cause]: \'bar\', ') + 'foo: \'bar\' }', + 'cause' in Error.prototype ? '[Error: foo]' : '{ [Error: foo] [cause]: undefined }', + '{ [Error: foo] cause: \'bar\' }' + ].join(', ') + ' ]'); +}); diff --git a/backend/node_modules/object-inspect/test/fakes.js b/backend/node_modules/object-inspect/test/fakes.js new file mode 100644 index 0000000000000000000000000000000000000000..a65c08c15a6e4c9c5500cbbb7a2b01327a5a8c4b --- /dev/null +++ b/backend/node_modules/object-inspect/test/fakes.js @@ -0,0 +1,29 @@ +'use strict'; + +var inspect = require('../'); +var test = require('tape'); +var hasToStringTag = require('has-tostringtag/shams')(); +var forEach = require('for-each'); + +test('fakes', { skip: !hasToStringTag }, function (t) { + forEach([ + 'Array', + 'Boolean', + 'Date', + 'Error', + 'Number', + 'RegExp', + 'String' + ], function (expected) { + var faker = {}; + faker[Symbol.toStringTag] = expected; + + t.equal( + inspect(faker), + '{ [Symbol(Symbol.toStringTag)]: \'' + expected + '\' }', + 'faker masquerading as ' + expected + ' is not shown as one' + ); + }); + + t.end(); +}); diff --git a/backend/node_modules/object-inspect/test/fn.js b/backend/node_modules/object-inspect/test/fn.js new file mode 100644 index 0000000000000000000000000000000000000000..de3ca625e73adcabc8570a11318504d8d6aa6806 --- /dev/null +++ b/backend/node_modules/object-inspect/test/fn.js @@ -0,0 +1,76 @@ +var inspect = require('../'); +var test = require('tape'); +var arrow = require('make-arrow-function')(); +var functionsHaveConfigurableNames = require('functions-have-names').functionsHaveConfigurableNames(); + +test('function', function (t) { + t.plan(1); + var obj = [1, 2, function f(n) { return n; }, 4]; + t.equal(inspect(obj), '[ 1, 2, [Function: f], 4 ]'); +}); + +test('function name', function (t) { + t.plan(1); + var f = (function () { + return function () {}; + }()); + f.toString = function toStr() { return 'function xxx () {}'; }; + var obj = [1, 2, f, 4]; + t.equal(inspect(obj), '[ 1, 2, [Function (anonymous)] { toString: [Function: toStr] }, 4 ]'); +}); + +test('anon function', function (t) { + var f = (function () { + return function () {}; + }()); + var obj = [1, 2, f, 4]; + t.equal(inspect(obj), '[ 1, 2, [Function (anonymous)], 4 ]'); + + t.end(); +}); + +test('arrow function', { skip: !arrow }, function (t) { + t.equal(inspect(arrow), '[Function (anonymous)]'); + + t.end(); +}); + +test('truly nameless function', { skip: !arrow || !functionsHaveConfigurableNames }, function (t) { + function f() {} + Object.defineProperty(f, 'name', { value: false }); + t.equal(f.name, false); + t.equal( + inspect(f), + '[Function: f]', + 'named function with falsy `.name` does not hide its original name' + ); + + function g() {} + Object.defineProperty(g, 'name', { value: true }); + t.equal(g.name, true); + t.equal( + inspect(g), + '[Function: true]', + 'named function with truthy `.name` hides its original name' + ); + + var anon = function () {}; // eslint-disable-line func-style + Object.defineProperty(anon, 'name', { value: null }); + t.equal(anon.name, null); + t.equal( + inspect(anon), + '[Function (anonymous)]', + 'anon function with falsy `.name` does not hide its anonymity' + ); + + var anon2 = function () {}; // eslint-disable-line func-style + Object.defineProperty(anon2, 'name', { value: 1 }); + t.equal(anon2.name, 1); + t.equal( + inspect(anon2), + '[Function: 1]', + 'anon function with truthy `.name` hides its anonymity' + ); + + t.end(); +}); diff --git a/backend/node_modules/object-inspect/test/global.js b/backend/node_modules/object-inspect/test/global.js new file mode 100644 index 0000000000000000000000000000000000000000..c57216aebd518555d0ba6e6677238b6cf4aee59d --- /dev/null +++ b/backend/node_modules/object-inspect/test/global.js @@ -0,0 +1,17 @@ +'use strict'; + +var inspect = require('../'); + +var test = require('tape'); +var globalThis = require('globalthis')(); + +test('global object', function (t) { + /* eslint-env browser */ + var expected = typeof window === 'undefined' ? 'globalThis' : 'Window'; + t.equal( + inspect([globalThis]), + '[ { [object ' + expected + '] } ]' + ); + + t.end(); +}); diff --git a/backend/node_modules/object-inspect/test/has.js b/backend/node_modules/object-inspect/test/has.js new file mode 100644 index 0000000000000000000000000000000000000000..01800dee6b07894536485e9a23ca6cda472984a2 --- /dev/null +++ b/backend/node_modules/object-inspect/test/has.js @@ -0,0 +1,15 @@ +'use strict'; + +var inspect = require('../'); +var test = require('tape'); +var mockProperty = require('mock-property'); + +test('when Object#hasOwnProperty is deleted', function (t) { + t.plan(1); + var arr = [1, , 3]; // eslint-disable-line no-sparse-arrays + + t.teardown(mockProperty(Array.prototype, 1, { value: 2 })); // this is needed to account for "in" vs "hasOwnProperty" + t.teardown(mockProperty(Object.prototype, 'hasOwnProperty', { 'delete': true })); + + t.equal(inspect(arr), '[ 1, , 3 ]'); +}); diff --git a/backend/node_modules/object-inspect/test/holes.js b/backend/node_modules/object-inspect/test/holes.js new file mode 100644 index 0000000000000000000000000000000000000000..87fc8c84aedf765a2c908f451564e54ac27dcb85 --- /dev/null +++ b/backend/node_modules/object-inspect/test/holes.js @@ -0,0 +1,15 @@ +var test = require('tape'); +var inspect = require('../'); + +var xs = ['a', 'b']; +xs[5] = 'f'; +xs[7] = 'j'; +xs[8] = 'k'; + +test('holes', function (t) { + t.plan(1); + t.equal( + inspect(xs), + "[ 'a', 'b', , , , 'f', , 'j', 'k' ]" + ); +}); diff --git a/backend/node_modules/object-inspect/test/indent-option.js b/backend/node_modules/object-inspect/test/indent-option.js new file mode 100644 index 0000000000000000000000000000000000000000..89d8fcedfa318ca67c9ba8fe694ba06fd2b47044 --- /dev/null +++ b/backend/node_modules/object-inspect/test/indent-option.js @@ -0,0 +1,271 @@ +var test = require('tape'); +var forEach = require('for-each'); + +var inspect = require('../'); + +test('bad indent options', function (t) { + forEach([ + undefined, + true, + false, + -1, + 1.2, + Infinity, + -Infinity, + NaN + ], function (indent) { + t['throws']( + function () { inspect('', { indent: indent }); }, + TypeError, + inspect(indent) + ' is invalid' + ); + }); + + t.end(); +}); + +test('simple object with indent', function (t) { + t.plan(2); + + var obj = { a: 1, b: 2 }; + + var expectedSpaces = [ + '{', + ' a: 1,', + ' b: 2', + '}' + ].join('\n'); + var expectedTabs = [ + '{', + ' a: 1,', + ' b: 2', + '}' + ].join('\n'); + + t.equal(inspect(obj, { indent: 2 }), expectedSpaces, 'two'); + t.equal(inspect(obj, { indent: '\t' }), expectedTabs, 'tabs'); +}); + +test('two deep object with indent', function (t) { + t.plan(2); + + var obj = { a: 1, b: { c: 3, d: 4 } }; + + var expectedSpaces = [ + '{', + ' a: 1,', + ' b: {', + ' c: 3,', + ' d: 4', + ' }', + '}' + ].join('\n'); + var expectedTabs = [ + '{', + ' a: 1,', + ' b: {', + ' c: 3,', + ' d: 4', + ' }', + '}' + ].join('\n'); + + t.equal(inspect(obj, { indent: 2 }), expectedSpaces, 'two'); + t.equal(inspect(obj, { indent: '\t' }), expectedTabs, 'tabs'); +}); + +test('simple array with all single line elements', function (t) { + t.plan(2); + + var obj = [1, 2, 3, 'asdf\nsdf']; + + var expected = '[ 1, 2, 3, \'asdf\\nsdf\' ]'; + + t.equal(inspect(obj, { indent: 2 }), expected, 'two'); + t.equal(inspect(obj, { indent: '\t' }), expected, 'tabs'); +}); + +test('array with complex elements', function (t) { + t.plan(2); + + var obj = [1, { a: 1, b: { c: 1 } }, 'asdf\nsdf']; + + var expectedSpaces = [ + '[', + ' 1,', + ' {', + ' a: 1,', + ' b: {', + ' c: 1', + ' }', + ' },', + ' \'asdf\\nsdf\'', + ']' + ].join('\n'); + var expectedTabs = [ + '[', + ' 1,', + ' {', + ' a: 1,', + ' b: {', + ' c: 1', + ' }', + ' },', + ' \'asdf\\nsdf\'', + ']' + ].join('\n'); + + t.equal(inspect(obj, { indent: 2 }), expectedSpaces, 'two'); + t.equal(inspect(obj, { indent: '\t' }), expectedTabs, 'tabs'); +}); + +test('values', function (t) { + t.plan(2); + var obj = [{}, [], { 'a-b': 5 }]; + + var expectedSpaces = [ + '[', + ' {},', + ' [],', + ' {', + ' \'a-b\': 5', + ' }', + ']' + ].join('\n'); + var expectedTabs = [ + '[', + ' {},', + ' [],', + ' {', + ' \'a-b\': 5', + ' }', + ']' + ].join('\n'); + + t.equal(inspect(obj, { indent: 2 }), expectedSpaces, 'two'); + t.equal(inspect(obj, { indent: '\t' }), expectedTabs, 'tabs'); +}); + +test('Map', { skip: typeof Map !== 'function' }, function (t) { + var map = new Map(); + map.set({ a: 1 }, ['b']); + map.set(3, NaN); + + var expectedStringSpaces = [ + 'Map (2) {', + ' { a: 1 } => [ \'b\' ],', + ' 3 => NaN', + '}' + ].join('\n'); + var expectedStringTabs = [ + 'Map (2) {', + ' { a: 1 } => [ \'b\' ],', + ' 3 => NaN', + '}' + ].join('\n'); + var expectedStringTabsDoubleQuotes = [ + 'Map (2) {', + ' { a: 1 } => [ "b" ],', + ' 3 => NaN', + '}' + ].join('\n'); + + t.equal( + inspect(map, { indent: 2 }), + expectedStringSpaces, + 'Map keys are not indented (two)' + ); + t.equal( + inspect(map, { indent: '\t' }), + expectedStringTabs, + 'Map keys are not indented (tabs)' + ); + t.equal( + inspect(map, { indent: '\t', quoteStyle: 'double' }), + expectedStringTabsDoubleQuotes, + 'Map keys are not indented (tabs + double quotes)' + ); + + t.equal(inspect(new Map(), { indent: 2 }), 'Map (0) {}', 'empty Map should show as empty (two)'); + t.equal(inspect(new Map(), { indent: '\t' }), 'Map (0) {}', 'empty Map should show as empty (tabs)'); + + var nestedMap = new Map(); + nestedMap.set(nestedMap, map); + var expectedNestedSpaces = [ + 'Map (1) {', + ' [Circular] => Map (2) {', + ' { a: 1 } => [ \'b\' ],', + ' 3 => NaN', + ' }', + '}' + ].join('\n'); + var expectedNestedTabs = [ + 'Map (1) {', + ' [Circular] => Map (2) {', + ' { a: 1 } => [ \'b\' ],', + ' 3 => NaN', + ' }', + '}' + ].join('\n'); + t.equal(inspect(nestedMap, { indent: 2 }), expectedNestedSpaces, 'Map containing a Map should work (two)'); + t.equal(inspect(nestedMap, { indent: '\t' }), expectedNestedTabs, 'Map containing a Map should work (tabs)'); + + t.end(); +}); + +test('Set', { skip: typeof Set !== 'function' }, function (t) { + var set = new Set(); + set.add({ a: 1 }); + set.add(['b']); + var expectedStringSpaces = [ + 'Set (2) {', + ' {', + ' a: 1', + ' },', + ' [ \'b\' ]', + '}' + ].join('\n'); + var expectedStringTabs = [ + 'Set (2) {', + ' {', + ' a: 1', + ' },', + ' [ \'b\' ]', + '}' + ].join('\n'); + t.equal(inspect(set, { indent: 2 }), expectedStringSpaces, 'new Set([{ a: 1 }, ["b"]]) should show size and contents (two)'); + t.equal(inspect(set, { indent: '\t' }), expectedStringTabs, 'new Set([{ a: 1 }, ["b"]]) should show size and contents (tabs)'); + + t.equal(inspect(new Set(), { indent: 2 }), 'Set (0) {}', 'empty Set should show as empty (two)'); + t.equal(inspect(new Set(), { indent: '\t' }), 'Set (0) {}', 'empty Set should show as empty (tabs)'); + + var nestedSet = new Set(); + nestedSet.add(set); + nestedSet.add(nestedSet); + var expectedNestedSpaces = [ + 'Set (2) {', + ' Set (2) {', + ' {', + ' a: 1', + ' },', + ' [ \'b\' ]', + ' },', + ' [Circular]', + '}' + ].join('\n'); + var expectedNestedTabs = [ + 'Set (2) {', + ' Set (2) {', + ' {', + ' a: 1', + ' },', + ' [ \'b\' ]', + ' },', + ' [Circular]', + '}' + ].join('\n'); + t.equal(inspect(nestedSet, { indent: 2 }), expectedNestedSpaces, 'Set containing a Set should work (two)'); + t.equal(inspect(nestedSet, { indent: '\t' }), expectedNestedTabs, 'Set containing a Set should work (tabs)'); + + t.end(); +}); diff --git a/backend/node_modules/object-inspect/test/inspect.js b/backend/node_modules/object-inspect/test/inspect.js new file mode 100644 index 0000000000000000000000000000000000000000..1abf81b1f00b305519e52fe74477b2c5b71803c7 --- /dev/null +++ b/backend/node_modules/object-inspect/test/inspect.js @@ -0,0 +1,139 @@ +var test = require('tape'); +var hasSymbols = require('has-symbols/shams')(); +var utilInspect = require('../util.inspect'); +var repeat = require('string.prototype.repeat'); + +var inspect = require('..'); + +test('inspect', function (t) { + t.plan(5); + + var obj = [{ inspect: function xyzInspect() { return '!XYZ¡'; } }, []]; + var stringResult = '[ !XYZ¡, [] ]'; + var falseResult = '[ { inspect: [Function: xyzInspect] }, [] ]'; + + t.equal(inspect(obj), stringResult); + t.equal(inspect(obj, { customInspect: true }), stringResult); + t.equal(inspect(obj, { customInspect: 'symbol' }), falseResult); + t.equal(inspect(obj, { customInspect: false }), falseResult); + t['throws']( + function () { inspect(obj, { customInspect: 'not a boolean or "symbol"' }); }, + TypeError, + '`customInspect` must be a boolean or the string "symbol"' + ); +}); + +test('inspect custom symbol', { skip: !hasSymbols || !utilInspect || !utilInspect.custom }, function (t) { + t.plan(4); + + var obj = { inspect: function stringInspect() { return 'string'; } }; + obj[utilInspect.custom] = function custom() { return 'symbol'; }; + + var symbolResult = '[ symbol, [] ]'; + var stringResult = '[ string, [] ]'; + var falseResult = '[ { inspect: [Function: stringInspect]' + (utilInspect.custom ? ', [' + inspect(utilInspect.custom) + ']: [Function: custom]' : '') + ' }, [] ]'; + + var symbolStringFallback = utilInspect.custom ? symbolResult : stringResult; + var symbolFalseFallback = utilInspect.custom ? symbolResult : falseResult; + + t.equal(inspect([obj, []]), symbolStringFallback); + t.equal(inspect([obj, []], { customInspect: true }), symbolStringFallback); + t.equal(inspect([obj, []], { customInspect: 'symbol' }), symbolFalseFallback); + t.equal(inspect([obj, []], { customInspect: false }), falseResult); +}); + +test('symbols', { skip: !hasSymbols }, function (t) { + t.plan(2); + + var obj = { a: 1 }; + obj[Symbol('test')] = 2; + obj[Symbol.iterator] = 3; + Object.defineProperty(obj, Symbol('non-enum'), { + enumerable: false, + value: 4 + }); + + if (typeof Symbol.iterator === 'symbol') { + t.equal(inspect(obj), '{ a: 1, [Symbol(test)]: 2, [Symbol(Symbol.iterator)]: 3 }', 'object with symbols'); + t.equal(inspect([obj, []]), '[ { a: 1, [Symbol(test)]: 2, [Symbol(Symbol.iterator)]: 3 }, [] ]', 'object with symbols in array'); + } else { + // symbol sham key ordering is unreliable + t.match( + inspect(obj), + /^(?:{ a: 1, \[Symbol\(test\)\]: 2, \[Symbol\(Symbol.iterator\)\]: 3 }|{ a: 1, \[Symbol\(Symbol.iterator\)\]: 3, \[Symbol\(test\)\]: 2 })$/, + 'object with symbols (nondeterministic symbol sham key ordering)' + ); + t.match( + inspect([obj, []]), + /^\[ (?:{ a: 1, \[Symbol\(test\)\]: 2, \[Symbol\(Symbol.iterator\)\]: 3 }|{ a: 1, \[Symbol\(Symbol.iterator\)\]: 3, \[Symbol\(test\)\]: 2 }), \[\] \]$/, + 'object with symbols in array (nondeterministic symbol sham key ordering)' + ); + } +}); + +test('maxStringLength', function (t) { + t['throws']( + function () { inspect('', { maxStringLength: -1 }); }, + TypeError, + 'maxStringLength must be >= 0, or Infinity, not negative' + ); + + var str = repeat('a', 1e8); + + t.equal( + inspect([str], { maxStringLength: 10 }), + '[ \'aaaaaaaaaa\'... 99999990 more characters ]', + 'maxStringLength option limits output' + ); + + t.equal( + inspect(['f'], { maxStringLength: null }), + '[ \'\'... 1 more character ]', + 'maxStringLength option accepts `null`' + ); + + t.equal( + inspect([str], { maxStringLength: Infinity }), + '[ \'' + str + '\' ]', + 'maxStringLength option accepts ∞' + ); + + t.end(); +}); + +test('inspect options', { skip: !utilInspect.custom }, function (t) { + var obj = {}; + obj[utilInspect.custom] = function () { + return JSON.stringify(arguments); + }; + t.equal( + inspect(obj), + utilInspect(obj, { depth: 5 }), + 'custom symbols will use node\'s inspect' + ); + t.equal( + inspect(obj, { depth: 2 }), + utilInspect(obj, { depth: 2 }), + 'a reduced depth will be passed to node\'s inspect' + ); + t.equal( + inspect({ d1: obj }, { depth: 3 }), + '{ d1: ' + utilInspect(obj, { depth: 2 }) + ' }', + 'deep objects will receive a reduced depth' + ); + t.equal( + inspect({ d1: obj }, { depth: 1 }), + '{ d1: [Object] }', + 'unlike nodejs inspect, customInspect will not be used once the depth is exceeded.' + ); + t.end(); +}); + +test('inspect URL', { skip: typeof URL === 'undefined' }, function (t) { + t.match( + inspect(new URL('https://nodejs.org')), + /nodejs\.org/, // Different environments stringify it differently + 'url can be inspected' + ); + t.end(); +}); diff --git a/backend/node_modules/object-inspect/test/lowbyte.js b/backend/node_modules/object-inspect/test/lowbyte.js new file mode 100644 index 0000000000000000000000000000000000000000..68a345d8578004506a45296d6de9e091b7811272 --- /dev/null +++ b/backend/node_modules/object-inspect/test/lowbyte.js @@ -0,0 +1,12 @@ +var test = require('tape'); +var inspect = require('../'); + +var obj = { x: 'a\r\nb', y: '\x05! \x1f \x12' }; + +test('interpolate low bytes', function (t) { + t.plan(1); + t.equal( + inspect(obj), + "{ x: 'a\\r\\nb', y: '\\x05! \\x1F \\x12' }" + ); +}); diff --git a/backend/node_modules/object-inspect/test/number.js b/backend/node_modules/object-inspect/test/number.js new file mode 100644 index 0000000000000000000000000000000000000000..8f287e8e2ab93785108de2e82e5b359ffb524f02 --- /dev/null +++ b/backend/node_modules/object-inspect/test/number.js @@ -0,0 +1,58 @@ +var test = require('tape'); +var v = require('es-value-fixtures'); +var forEach = require('for-each'); + +var inspect = require('../'); + +test('negative zero', function (t) { + t.equal(inspect(0), '0', 'inspect(0) === "0"'); + t.equal(inspect(Object(0)), 'Object(0)', 'inspect(Object(0)) === "Object(0)"'); + + t.equal(inspect(-0), '-0', 'inspect(-0) === "-0"'); + t.equal(inspect(Object(-0)), 'Object(-0)', 'inspect(Object(-0)) === "Object(-0)"'); + + t.end(); +}); + +test('numericSeparator', function (t) { + forEach(v.nonBooleans, function (nonBoolean) { + t['throws']( + function () { inspect(true, { numericSeparator: nonBoolean }); }, + TypeError, + inspect(nonBoolean) + ' is not a boolean' + ); + }); + + t.test('3 digit numbers', function (st) { + var failed = false; + for (var i = -999; i < 1000; i += 1) { + var actual = inspect(i); + var actualSepNo = inspect(i, { numericSeparator: false }); + var actualSepYes = inspect(i, { numericSeparator: true }); + var expected = String(i); + if (actual !== expected || actualSepNo !== expected || actualSepYes !== expected) { + failed = true; + t.equal(actual, expected); + t.equal(actualSepNo, expected); + t.equal(actualSepYes, expected); + } + } + + st.notOk(failed, 'all 3 digit numbers passed'); + + st.end(); + }); + + t.equal(inspect(1e3), '1000', '1000'); + t.equal(inspect(1e3, { numericSeparator: false }), '1000', '1000, numericSeparator false'); + t.equal(inspect(1e3, { numericSeparator: true }), '1_000', '1000, numericSeparator true'); + t.equal(inspect(-1e3), '-1000', '-1000'); + t.equal(inspect(-1e3, { numericSeparator: false }), '-1000', '-1000, numericSeparator false'); + t.equal(inspect(-1e3, { numericSeparator: true }), '-1_000', '-1000, numericSeparator true'); + + t.equal(inspect(1234.5678, { numericSeparator: true }), '1_234.567_8', 'fractional numbers get separators'); + t.equal(inspect(1234.56789, { numericSeparator: true }), '1_234.567_89', 'fractional numbers get separators'); + t.equal(inspect(1234.567891, { numericSeparator: true }), '1_234.567_891', 'fractional numbers get separators'); + + t.end(); +}); diff --git a/backend/node_modules/object-inspect/test/quoteStyle.js b/backend/node_modules/object-inspect/test/quoteStyle.js new file mode 100644 index 0000000000000000000000000000000000000000..ae4d734bff6c30bbabc11c4fb071e220a4cef02b --- /dev/null +++ b/backend/node_modules/object-inspect/test/quoteStyle.js @@ -0,0 +1,17 @@ +'use strict'; + +var inspect = require('../'); +var test = require('tape'); + +test('quoteStyle option', function (t) { + t['throws'](function () { inspect(null, { quoteStyle: false }); }, 'false is not a valid value'); + t['throws'](function () { inspect(null, { quoteStyle: true }); }, 'true is not a valid value'); + t['throws'](function () { inspect(null, { quoteStyle: '' }); }, '"" is not a valid value'); + t['throws'](function () { inspect(null, { quoteStyle: {} }); }, '{} is not a valid value'); + t['throws'](function () { inspect(null, { quoteStyle: [] }); }, '[] is not a valid value'); + t['throws'](function () { inspect(null, { quoteStyle: 42 }); }, '42 is not a valid value'); + t['throws'](function () { inspect(null, { quoteStyle: NaN }); }, 'NaN is not a valid value'); + t['throws'](function () { inspect(null, { quoteStyle: function () {} }); }, 'a function is not a valid value'); + + t.end(); +}); diff --git a/backend/node_modules/object-inspect/test/toStringTag.js b/backend/node_modules/object-inspect/test/toStringTag.js new file mode 100644 index 0000000000000000000000000000000000000000..95f82703d08f358b00f180c7b479b9f33dff3dac --- /dev/null +++ b/backend/node_modules/object-inspect/test/toStringTag.js @@ -0,0 +1,40 @@ +'use strict'; + +var test = require('tape'); +var hasToStringTag = require('has-tostringtag/shams')(); + +var inspect = require('../'); + +test('Symbol.toStringTag', { skip: !hasToStringTag }, function (t) { + t.plan(4); + + var obj = { a: 1 }; + t.equal(inspect(obj), '{ a: 1 }', 'object, no Symbol.toStringTag'); + + obj[Symbol.toStringTag] = 'foo'; + t.equal(inspect(obj), '{ a: 1, [Symbol(Symbol.toStringTag)]: \'foo\' }', 'object with Symbol.toStringTag'); + + t.test('null objects', { skip: 'toString' in { __proto__: null } }, function (st) { + st.plan(2); + + var dict = { __proto__: null, a: 1 }; + st.equal(inspect(dict), '[Object: null prototype] { a: 1 }', 'null object with Symbol.toStringTag'); + + dict[Symbol.toStringTag] = 'Dict'; + st.equal(inspect(dict), '[Dict: null prototype] { a: 1, [Symbol(Symbol.toStringTag)]: \'Dict\' }', 'null object with Symbol.toStringTag'); + }); + + t.test('instances', function (st) { + st.plan(4); + + function C() { + this.a = 1; + } + st.equal(Object.prototype.toString.call(new C()), '[object Object]', 'instance, no toStringTag, Object.prototype.toString'); + st.equal(inspect(new C()), 'C { a: 1 }', 'instance, no toStringTag'); + + C.prototype[Symbol.toStringTag] = 'Class!'; + st.equal(Object.prototype.toString.call(new C()), '[object Class!]', 'instance, with toStringTag, Object.prototype.toString'); + st.equal(inspect(new C()), 'C [Class!] { a: 1 }', 'instance, with toStringTag'); + }); +}); diff --git a/backend/node_modules/object-inspect/test/undef.js b/backend/node_modules/object-inspect/test/undef.js new file mode 100644 index 0000000000000000000000000000000000000000..e3f4961229c249a1d4f242d415b5193fc0ad5056 --- /dev/null +++ b/backend/node_modules/object-inspect/test/undef.js @@ -0,0 +1,12 @@ +var test = require('tape'); +var inspect = require('../'); + +var obj = { a: 1, b: [3, 4, undefined, null], c: undefined, d: null }; + +test('undef and null', function (t) { + t.plan(1); + t.equal( + inspect(obj), + '{ a: 1, b: [ 3, 4, undefined, null ], c: undefined, d: null }' + ); +}); diff --git a/backend/node_modules/object-inspect/test/values.js b/backend/node_modules/object-inspect/test/values.js new file mode 100644 index 0000000000000000000000000000000000000000..4832b9fe95dcf93454d446c334cad783a5996915 --- /dev/null +++ b/backend/node_modules/object-inspect/test/values.js @@ -0,0 +1,211 @@ +'use strict'; + +var inspect = require('../'); +var test = require('tape'); +var mockProperty = require('mock-property'); +var hasSymbols = require('has-symbols/shams')(); +var hasToStringTag = require('has-tostringtag/shams')(); + +test('values', function (t) { + t.plan(1); + var obj = [{}, [], { 'a-b': 5 }]; + t.equal(inspect(obj), '[ {}, [], { \'a-b\': 5 } ]'); +}); + +test('arrays with properties', function (t) { + t.plan(1); + var arr = [3]; + arr.foo = 'bar'; + var obj = [1, 2, arr]; + obj.baz = 'quux'; + obj.index = -1; + t.equal(inspect(obj), '[ 1, 2, [ 3, foo: \'bar\' ], baz: \'quux\', index: -1 ]'); +}); + +test('has', function (t) { + t.plan(1); + t.teardown(mockProperty(Object.prototype, 'hasOwnProperty', { 'delete': true })); + + t.equal(inspect({ a: 1, b: 2 }), '{ a: 1, b: 2 }'); +}); + +test('indexOf seen', function (t) { + t.plan(1); + var xs = [1, 2, 3, {}]; + xs.push(xs); + + var seen = []; + seen.indexOf = undefined; + + t.equal( + inspect(xs, {}, 0, seen), + '[ 1, 2, 3, {}, [Circular] ]' + ); +}); + +test('seen seen', function (t) { + t.plan(1); + var xs = [1, 2, 3]; + + var seen = [xs]; + seen.indexOf = undefined; + + t.equal( + inspect(xs, {}, 0, seen), + '[Circular]' + ); +}); + +test('seen seen seen', function (t) { + t.plan(1); + var xs = [1, 2, 3]; + + var seen = [5, xs]; + seen.indexOf = undefined; + + t.equal( + inspect(xs, {}, 0, seen), + '[Circular]' + ); +}); + +test('symbols', { skip: !hasSymbols }, function (t) { + var sym = Symbol('foo'); + t.equal(inspect(sym), 'Symbol(foo)', 'Symbol("foo") should be "Symbol(foo)"'); + if (typeof sym === 'symbol') { + // Symbol shams are incapable of differentiating boxed from unboxed symbols + t.equal(inspect(Object(sym)), 'Object(Symbol(foo))', 'Object(Symbol("foo")) should be "Object(Symbol(foo))"'); + } + + t.test('toStringTag', { skip: !hasToStringTag }, function (st) { + st.plan(1); + + var faker = {}; + faker[Symbol.toStringTag] = 'Symbol'; + st.equal( + inspect(faker), + '{ [Symbol(Symbol.toStringTag)]: \'Symbol\' }', + 'object lying about being a Symbol inspects as an object' + ); + }); + + t.end(); +}); + +test('Map', { skip: typeof Map !== 'function' }, function (t) { + var map = new Map(); + map.set({ a: 1 }, ['b']); + map.set(3, NaN); + var expectedString = 'Map (2) {' + inspect({ a: 1 }) + ' => ' + inspect(['b']) + ', 3 => NaN}'; + t.equal(inspect(map), expectedString, 'new Map([[{ a: 1 }, ["b"]], [3, NaN]]) should show size and contents'); + t.equal(inspect(new Map()), 'Map (0) {}', 'empty Map should show as empty'); + + var nestedMap = new Map(); + nestedMap.set(nestedMap, map); + t.equal(inspect(nestedMap), 'Map (1) {[Circular] => ' + expectedString + '}', 'Map containing a Map should work'); + + t.end(); +}); + +test('WeakMap', { skip: typeof WeakMap !== 'function' }, function (t) { + var map = new WeakMap(); + map.set({ a: 1 }, ['b']); + var expectedString = 'WeakMap { ? }'; + t.equal(inspect(map), expectedString, 'new WeakMap([[{ a: 1 }, ["b"]]]) should not show size or contents'); + t.equal(inspect(new WeakMap()), 'WeakMap { ? }', 'empty WeakMap should not show as empty'); + + t.end(); +}); + +test('Set', { skip: typeof Set !== 'function' }, function (t) { + var set = new Set(); + set.add({ a: 1 }); + set.add(['b']); + var expectedString = 'Set (2) {' + inspect({ a: 1 }) + ', ' + inspect(['b']) + '}'; + t.equal(inspect(set), expectedString, 'new Set([{ a: 1 }, ["b"]]) should show size and contents'); + t.equal(inspect(new Set()), 'Set (0) {}', 'empty Set should show as empty'); + + var nestedSet = new Set(); + nestedSet.add(set); + nestedSet.add(nestedSet); + t.equal(inspect(nestedSet), 'Set (2) {' + expectedString + ', [Circular]}', 'Set containing a Set should work'); + + t.end(); +}); + +test('WeakSet', { skip: typeof WeakSet !== 'function' }, function (t) { + var map = new WeakSet(); + map.add({ a: 1 }); + var expectedString = 'WeakSet { ? }'; + t.equal(inspect(map), expectedString, 'new WeakSet([{ a: 1 }]) should not show size or contents'); + t.equal(inspect(new WeakSet()), 'WeakSet { ? }', 'empty WeakSet should not show as empty'); + + t.end(); +}); + +test('WeakRef', { skip: typeof WeakRef !== 'function' }, function (t) { + var ref = new WeakRef({ a: 1 }); + var expectedString = 'WeakRef { ? }'; + t.equal(inspect(ref), expectedString, 'new WeakRef({ a: 1 }) should not show contents'); + + t.end(); +}); + +test('FinalizationRegistry', { skip: typeof FinalizationRegistry !== 'function' }, function (t) { + var registry = new FinalizationRegistry(function () {}); + var expectedString = 'FinalizationRegistry [FinalizationRegistry] {}'; + t.equal(inspect(registry), expectedString, 'new FinalizationRegistry(function () {}) should work normallys'); + + t.end(); +}); + +test('Strings', function (t) { + var str = 'abc'; + + t.equal(inspect(str), "'" + str + "'", 'primitive string shows as such'); + t.equal(inspect(str, { quoteStyle: 'single' }), "'" + str + "'", 'primitive string shows as such, single quoted'); + t.equal(inspect(str, { quoteStyle: 'double' }), '"' + str + '"', 'primitive string shows as such, double quoted'); + t.equal(inspect(Object(str)), 'Object(' + inspect(str) + ')', 'String object shows as such'); + t.equal(inspect(Object(str), { quoteStyle: 'single' }), 'Object(' + inspect(str, { quoteStyle: 'single' }) + ')', 'String object shows as such, single quoted'); + t.equal(inspect(Object(str), { quoteStyle: 'double' }), 'Object(' + inspect(str, { quoteStyle: 'double' }) + ')', 'String object shows as such, double quoted'); + + t.end(); +}); + +test('Numbers', function (t) { + var num = 42; + + t.equal(inspect(num), String(num), 'primitive number shows as such'); + t.equal(inspect(Object(num)), 'Object(' + inspect(num) + ')', 'Number object shows as such'); + + t.end(); +}); + +test('Booleans', function (t) { + t.equal(inspect(true), String(true), 'primitive true shows as such'); + t.equal(inspect(Object(true)), 'Object(' + inspect(true) + ')', 'Boolean object true shows as such'); + + t.equal(inspect(false), String(false), 'primitive false shows as such'); + t.equal(inspect(Object(false)), 'Object(' + inspect(false) + ')', 'Boolean false object shows as such'); + + t.end(); +}); + +test('Date', function (t) { + var now = new Date(); + t.equal(inspect(now), String(now), 'Date shows properly'); + t.equal(inspect(new Date(NaN)), 'Invalid Date', 'Invalid Date shows properly'); + + t.end(); +}); + +test('RegExps', function (t) { + t.equal(inspect(/a/g), '/a/g', 'regex shows properly'); + t.equal(inspect(new RegExp('abc', 'i')), '/abc/i', 'new RegExp shows properly'); + + var match = 'abc abc'.match(/[ab]+/); + delete match.groups; // for node < 10 + t.equal(inspect(match), '[ \'ab\', index: 0, input: \'abc abc\' ]', 'RegExp match object shows properly'); + + t.end(); +}); diff --git a/backend/node_modules/object-inspect/util.inspect.js b/backend/node_modules/object-inspect/util.inspect.js new file mode 100644 index 0000000000000000000000000000000000000000..7784fab55d08875a01b24636f3a541c3d0bd39b2 --- /dev/null +++ b/backend/node_modules/object-inspect/util.inspect.js @@ -0,0 +1 @@ +module.exports = require('util').inspect; diff --git a/backend/node_modules/on-finished/HISTORY.md b/backend/node_modules/on-finished/HISTORY.md new file mode 100644 index 0000000000000000000000000000000000000000..1917595a714e11049ec9402d87aa625c68caa080 --- /dev/null +++ b/backend/node_modules/on-finished/HISTORY.md @@ -0,0 +1,98 @@ +2.4.1 / 2022-02-22 +================== + + * Fix error on early async hooks implementations + +2.4.0 / 2022-02-21 +================== + + * Prevent loss of async hooks context + +2.3.0 / 2015-05-26 +================== + + * Add defined behavior for HTTP `CONNECT` requests + * Add defined behavior for HTTP `Upgrade` requests + * deps: ee-first@1.1.1 + +2.2.1 / 2015-04-22 +================== + + * Fix `isFinished(req)` when data buffered + +2.2.0 / 2014-12-22 +================== + + * Add message object to callback arguments + +2.1.1 / 2014-10-22 +================== + + * Fix handling of pipelined requests + +2.1.0 / 2014-08-16 +================== + + * Check if `socket` is detached + * Return `undefined` for `isFinished` if state unknown + +2.0.0 / 2014-08-16 +================== + + * Add `isFinished` function + * Move to `jshttp` organization + * Remove support for plain socket argument + * Rename to `on-finished` + * Support both `req` and `res` as arguments + * deps: ee-first@1.0.5 + +1.2.2 / 2014-06-10 +================== + + * Reduce listeners added to emitters + - avoids "event emitter leak" warnings when used multiple times on same request + +1.2.1 / 2014-06-08 +================== + + * Fix returned value when already finished + +1.2.0 / 2014-06-05 +================== + + * Call callback when called on already-finished socket + +1.1.4 / 2014-05-27 +================== + + * Support node.js 0.8 + +1.1.3 / 2014-04-30 +================== + + * Make sure errors passed as instanceof `Error` + +1.1.2 / 2014-04-18 +================== + + * Default the `socket` to passed-in object + +1.1.1 / 2014-01-16 +================== + + * Rename module to `finished` + +1.1.0 / 2013-12-25 +================== + + * Call callback when called on already-errored socket + +1.0.1 / 2013-12-20 +================== + + * Actually pass the error to the callback + +1.0.0 / 2013-12-20 +================== + + * Initial release diff --git a/backend/node_modules/on-finished/LICENSE b/backend/node_modules/on-finished/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..5931fd23eab9dd3be559cd4bd81253df87a5297c --- /dev/null +++ b/backend/node_modules/on-finished/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2013 Jonathan Ong +Copyright (c) 2014 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/backend/node_modules/on-finished/README.md b/backend/node_modules/on-finished/README.md new file mode 100644 index 0000000000000000000000000000000000000000..8973cded6589a6cc5a9e1718e3fb0d709fe6e8d8 --- /dev/null +++ b/backend/node_modules/on-finished/README.md @@ -0,0 +1,162 @@ +# on-finished + +[![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] + +Execute a callback when a HTTP request closes, finishes, or errors. + +## Install + +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 on-finished +``` + +## API + +```js +var onFinished = require('on-finished') +``` + +### onFinished(res, listener) + +Attach a listener to listen for the response to finish. The listener will +be invoked only once when the response finished. If the response finished +to an error, the first argument will contain the error. If the response +has already finished, the listener will be invoked. + +Listening to the end of a response would be used to close things associated +with the response, like open files. + +Listener is invoked as `listener(err, res)`. + + + +```js +onFinished(res, function (err, res) { + // clean up open fds, etc. + // err contains the error if request error'd +}) +``` + +### onFinished(req, listener) + +Attach a listener to listen for the request to finish. The listener will +be invoked only once when the request finished. If the request finished +to an error, the first argument will contain the error. If the request +has already finished, the listener will be invoked. + +Listening to the end of a request would be used to know when to continue +after reading the data. + +Listener is invoked as `listener(err, req)`. + + + +```js +var data = '' + +req.setEncoding('utf8') +req.on('data', function (str) { + data += str +}) + +onFinished(req, function (err, req) { + // data is read unless there is err +}) +``` + +### onFinished.isFinished(res) + +Determine if `res` is already finished. This would be useful to check and +not even start certain operations if the response has already finished. + +### onFinished.isFinished(req) + +Determine if `req` is already finished. This would be useful to check and +not even start certain operations if the request has already finished. + +## Special Node.js requests + +### HTTP CONNECT method + +The meaning of the `CONNECT` method from RFC 7231, section 4.3.6: + +> The CONNECT method requests that the recipient establish a tunnel to +> the destination origin server identified by the request-target and, +> if successful, thereafter restrict its behavior to blind forwarding +> of packets, in both directions, until the tunnel is closed. Tunnels +> are commonly used to create an end-to-end virtual connection, through +> one or more proxies, which can then be secured using TLS (Transport +> Layer Security, [RFC5246]). + +In Node.js, these request objects come from the `'connect'` event on +the HTTP server. + +When this module is used on a HTTP `CONNECT` request, the request is +considered "finished" immediately, **due to limitations in the Node.js +interface**. This means if the `CONNECT` request contains a request entity, +the request will be considered "finished" even before it has been read. + +There is no such thing as a response object to a `CONNECT` request in +Node.js, so there is no support for one. + +### HTTP Upgrade request + +The meaning of the `Upgrade` header from RFC 7230, section 6.1: + +> The "Upgrade" header field is intended to provide a simple mechanism +> for transitioning from HTTP/1.1 to some other protocol on the same +> connection. + +In Node.js, these request objects come from the `'upgrade'` event on +the HTTP server. + +When this module is used on a HTTP request with an `Upgrade` header, the +request is considered "finished" immediately, **due to limitations in the +Node.js interface**. This means if the `Upgrade` request contains a request +entity, the request will be considered "finished" even before it has been +read. + +There is no such thing as a response object to a `Upgrade` request in +Node.js, so there is no support for one. + +## Example + +The following code ensures that file descriptors are always closed +once the response finishes. + +```js +var destroy = require('destroy') +var fs = require('fs') +var http = require('http') +var onFinished = require('on-finished') + +http.createServer(function onRequest (req, res) { + var stream = fs.createReadStream('package.json') + stream.pipe(res) + onFinished(res, function () { + destroy(stream) + }) +}) +``` + +## License + +[MIT](LICENSE) + +[ci-image]: https://badgen.net/github/checks/jshttp/on-finished/master?label=ci +[ci-url]: https://github.com/jshttp/on-finished/actions/workflows/ci.yml +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/on-finished/master +[coveralls-url]: https://coveralls.io/r/jshttp/on-finished?branch=master +[node-image]: https://badgen.net/npm/node/on-finished +[node-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/on-finished +[npm-url]: https://npmjs.org/package/on-finished +[npm-version-image]: https://badgen.net/npm/v/on-finished diff --git a/backend/node_modules/on-finished/index.js b/backend/node_modules/on-finished/index.js new file mode 100644 index 0000000000000000000000000000000000000000..e68df7bde39bb47aa1fd7eff4b317b3969de75bd --- /dev/null +++ b/backend/node_modules/on-finished/index.js @@ -0,0 +1,234 @@ +/*! + * on-finished + * Copyright(c) 2013 Jonathan Ong + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = onFinished +module.exports.isFinished = isFinished + +/** + * Module dependencies. + * @private + */ + +var asyncHooks = tryRequireAsyncHooks() +var first = require('ee-first') + +/** + * Variables. + * @private + */ + +/* istanbul ignore next */ +var defer = typeof setImmediate === 'function' + ? setImmediate + : function (fn) { process.nextTick(fn.bind.apply(fn, arguments)) } + +/** + * Invoke callback when the response has finished, useful for + * cleaning up resources afterwards. + * + * @param {object} msg + * @param {function} listener + * @return {object} + * @public + */ + +function onFinished (msg, listener) { + if (isFinished(msg) !== false) { + defer(listener, null, msg) + return msg + } + + // attach the listener to the message + attachListener(msg, wrap(listener)) + + return msg +} + +/** + * Determine if message is already finished. + * + * @param {object} msg + * @return {boolean} + * @public + */ + +function isFinished (msg) { + var socket = msg.socket + + if (typeof msg.finished === 'boolean') { + // OutgoingMessage + return Boolean(msg.finished || (socket && !socket.writable)) + } + + if (typeof msg.complete === 'boolean') { + // IncomingMessage + return Boolean(msg.upgrade || !socket || !socket.readable || (msg.complete && !msg.readable)) + } + + // don't know + return undefined +} + +/** + * Attach a finished listener to the message. + * + * @param {object} msg + * @param {function} callback + * @private + */ + +function attachFinishedListener (msg, callback) { + var eeMsg + var eeSocket + var finished = false + + function onFinish (error) { + eeMsg.cancel() + eeSocket.cancel() + + finished = true + callback(error) + } + + // finished on first message event + eeMsg = eeSocket = first([[msg, 'end', 'finish']], onFinish) + + function onSocket (socket) { + // remove listener + msg.removeListener('socket', onSocket) + + if (finished) return + if (eeMsg !== eeSocket) return + + // finished on first socket event + eeSocket = first([[socket, 'error', 'close']], onFinish) + } + + if (msg.socket) { + // socket already assigned + onSocket(msg.socket) + return + } + + // wait for socket to be assigned + msg.on('socket', onSocket) + + if (msg.socket === undefined) { + // istanbul ignore next: node.js 0.8 patch + patchAssignSocket(msg, onSocket) + } +} + +/** + * Attach the listener to the message. + * + * @param {object} msg + * @return {function} + * @private + */ + +function attachListener (msg, listener) { + var attached = msg.__onFinished + + // create a private single listener with queue + if (!attached || !attached.queue) { + attached = msg.__onFinished = createListener(msg) + attachFinishedListener(msg, attached) + } + + attached.queue.push(listener) +} + +/** + * Create listener on message. + * + * @param {object} msg + * @return {function} + * @private + */ + +function createListener (msg) { + function listener (err) { + if (msg.__onFinished === listener) msg.__onFinished = null + if (!listener.queue) return + + var queue = listener.queue + listener.queue = null + + for (var i = 0; i < queue.length; i++) { + queue[i](err, msg) + } + } + + listener.queue = [] + + return listener +} + +/** + * Patch ServerResponse.prototype.assignSocket for node.js 0.8. + * + * @param {ServerResponse} res + * @param {function} callback + * @private + */ + +// istanbul ignore next: node.js 0.8 patch +function patchAssignSocket (res, callback) { + var assignSocket = res.assignSocket + + if (typeof assignSocket !== 'function') return + + // res.on('socket', callback) is broken in 0.8 + res.assignSocket = function _assignSocket (socket) { + assignSocket.call(this, socket) + callback(socket) + } +} + +/** + * Try to require async_hooks + * @private + */ + +function tryRequireAsyncHooks () { + try { + return require('async_hooks') + } catch (e) { + return {} + } +} + +/** + * Wrap function with async resource, if possible. + * AsyncResource.bind static method backported. + * @private + */ + +function wrap (fn) { + var res + + // create anonymous resource + if (asyncHooks.AsyncResource) { + res = new asyncHooks.AsyncResource(fn.name || 'bound-anonymous-fn') + } + + // incompatible node.js + if (!res || !res.runInAsyncScope) { + return fn + } + + // return bound function + return res.runInAsyncScope.bind(res, fn, null) +} diff --git a/backend/node_modules/on-finished/package.json b/backend/node_modules/on-finished/package.json new file mode 100644 index 0000000000000000000000000000000000000000..644cd814b9d745714e4d16753de8bc8856e201e4 --- /dev/null +++ b/backend/node_modules/on-finished/package.json @@ -0,0 +1,39 @@ +{ + "name": "on-finished", + "description": "Execute a callback when a request closes, finishes, or errors", + "version": "2.4.1", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)" + ], + "license": "MIT", + "repository": "jshttp/on-finished", + "dependencies": { + "ee-first": "1.1.1" + }, + "devDependencies": { + "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": "5.2.0", + "eslint-plugin-standard": "4.1.0", + "mocha": "9.2.1", + "nyc": "15.1.0" + }, + "engines": { + "node": ">= 0.8" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "index.js" + ], + "scripts": { + "lint": "eslint .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-ci": "nyc --reporter=lcovonly --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test" + } +} diff --git a/backend/node_modules/openai/CHANGELOG.md b/backend/node_modules/openai/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..48a52d25830ffe96e8d6afa6575445e96825ea58 --- /dev/null +++ b/backend/node_modules/openai/CHANGELOG.md @@ -0,0 +1,957 @@ +# Changelog + +## 4.35.0 (2024-04-15) + +Full Changelog: [v4.34.0...v4.35.0](https://github.com/openai/openai-node/compare/v4.34.0...v4.35.0) + +### Features + +* **errors:** add request_id property ([#769](https://github.com/openai/openai-node/issues/769)) ([43aa6a1](https://github.com/openai/openai-node/commit/43aa6a19cfb1448903dfaddc4da3def2eda9cbab)) + +## 4.34.0 (2024-04-15) + +Full Changelog: [v4.33.1...v4.34.0](https://github.com/openai/openai-node/compare/v4.33.1...v4.34.0) + +### Features + +* **api:** add batch API ([#768](https://github.com/openai/openai-node/issues/768)) ([7fe34f2](https://github.com/openai/openai-node/commit/7fe34f2d0bda9c1cb116a593f02bd0cc15a52e12)) +* **api:** updates ([#766](https://github.com/openai/openai-node/issues/766)) ([52bcc47](https://github.com/openai/openai-node/commit/52bcc47043e4c3ffe15ae9e7ac0fa87e2493aad9)) + +## 4.33.1 (2024-04-12) + +Full Changelog: [v4.33.0...v4.33.1](https://github.com/openai/openai-node/compare/v4.33.0...v4.33.1) + +### Chores + +* **internal:** formatting ([#763](https://github.com/openai/openai-node/issues/763)) ([b6acf54](https://github.com/openai/openai-node/commit/b6acf54baab7e6cbf6ce3ad1d6c70197cc0181d0)) +* **internal:** improve ecosystem tests ([#761](https://github.com/openai/openai-node/issues/761)) ([fcf748d](https://github.com/openai/openai-node/commit/fcf748dbbd23f972ff9fd81a8b2a35232a2d6e5c)) + +## 4.33.0 (2024-04-05) + +Full Changelog: [v4.32.2...v4.33.0](https://github.com/openai/openai-node/compare/v4.32.2...v4.33.0) + +### Features + +* **api:** add additional messages when creating thread run ([#759](https://github.com/openai/openai-node/issues/759)) ([f1fdb41](https://github.com/openai/openai-node/commit/f1fdb410e087f9b94faeda0558de573ec1118601)) + +## 4.32.2 (2024-04-04) + +Full Changelog: [v4.32.1...v4.32.2](https://github.com/openai/openai-node/compare/v4.32.1...v4.32.2) + +### Bug Fixes + +* **streaming:** handle special line characters and fix multi-byte character decoding ([#757](https://github.com/openai/openai-node/issues/757)) ([8dcdda2](https://github.com/openai/openai-node/commit/8dcdda2b0d1d86486eea5fd47d24a8d26fde4c19)) +* **tests:** update wrangler to v3.19.0 (CVE-2023-7080) ([#755](https://github.com/openai/openai-node/issues/755)) ([47ca41d](https://github.com/openai/openai-node/commit/47ca41da9a739b2e04b721cb1fe843e5dd152465)) + + +### Chores + +* **tests:** bump ecosystem tests dependencies ([#753](https://github.com/openai/openai-node/issues/753)) ([3f86ea2](https://github.com/openai/openai-node/commit/3f86ea2205c90e05bcbe582491a4bed01075a5b1)) + +## 4.32.1 (2024-04-02) + +Full Changelog: [v4.32.0...v4.32.1](https://github.com/openai/openai-node/compare/v4.32.0...v4.32.1) + +### Chores + +* **deps:** bump yarn to v1.22.22 ([#751](https://github.com/openai/openai-node/issues/751)) ([5b41d10](https://github.com/openai/openai-node/commit/5b41d1077f219b8feb7557cfab98caf7b5de560d)) + +## 4.32.0 (2024-04-01) + +Full Changelog: [v4.31.0...v4.32.0](https://github.com/openai/openai-node/compare/v4.31.0...v4.32.0) + +### Features + +* **api:** add support for filtering messages by run_id ([#747](https://github.com/openai/openai-node/issues/747)) ([9a397ac](https://github.com/openai/openai-node/commit/9a397acffa9f10c3f48e86e3bdb3851770f87b42)) +* **api:** run polling helpers ([#749](https://github.com/openai/openai-node/issues/749)) ([02920ae](https://github.com/openai/openai-node/commit/02920ae082480fc7a7ffe9fa583d053a40dc7120)) + + +### Chores + +* **deps:** remove unused dependency digest-fetch ([#748](https://github.com/openai/openai-node/issues/748)) ([5376837](https://github.com/openai/openai-node/commit/537683734d39dd956a7dcef4339c1167ce6fe13c)) + + +### Documentation + +* **readme:** change undocumented params wording ([#744](https://github.com/openai/openai-node/issues/744)) ([8796691](https://github.com/openai/openai-node/commit/87966911045275db86844dfdcde59653edaef264)) + + +### Refactors + +* rename createAndStream to stream ([02920ae](https://github.com/openai/openai-node/commit/02920ae082480fc7a7ffe9fa583d053a40dc7120)) + +## 4.31.0 (2024-03-30) + +Full Changelog: [v4.30.0...v4.31.0](https://github.com/openai/openai-node/compare/v4.30.0...v4.31.0) + +### Features + +* **api:** adding temperature parameter ([#742](https://github.com/openai/openai-node/issues/742)) ([b173b05](https://github.com/openai/openai-node/commit/b173b05eb52266d8f2c835ec4ed71cba8cdc609b)) + + +### Bug Fixes + +* **streaming:** trigger all event handlers with fromReadableStream ([#741](https://github.com/openai/openai-node/issues/741)) ([7b1e593](https://github.com/openai/openai-node/commit/7b1e5937d97b309ed51928b4388dcde74abda8dc)) + +## 4.30.0 (2024-03-28) + +Full Changelog: [v4.29.2...v4.30.0](https://github.com/openai/openai-node/compare/v4.29.2...v4.30.0) + +### Features + +* assistant fromReadableStream ([#738](https://github.com/openai/openai-node/issues/738)) ([8f4ba18](https://github.com/openai/openai-node/commit/8f4ba18268797d6c54c393d701b13c7ff2aa71bc)) + + +### Bug Fixes + +* **client:** correctly send deno version header ([#736](https://github.com/openai/openai-node/issues/736)) ([b7ea175](https://github.com/openai/openai-node/commit/b7ea175b2854909de77b920dd25613f1d2daefd6)) +* **example:** correcting example ([#739](https://github.com/openai/openai-node/issues/739)) ([a819551](https://github.com/openai/openai-node/commit/a81955175da24e196490a38850bbf6f9b6779ea8)) +* handle process.env being undefined in debug func ([#733](https://github.com/openai/openai-node/issues/733)) ([2baa149](https://github.com/openai/openai-node/commit/2baa1491f7834f779ca49c3027d2344ead412dd2)) +* **internal:** make toFile use input file's options ([#727](https://github.com/openai/openai-node/issues/727)) ([15880d7](https://github.com/openai/openai-node/commit/15880d77b6c1cf58a6b9cfdbf7ae4442cdbddbd6)) + + +### Chores + +* **internal:** add type ([#737](https://github.com/openai/openai-node/issues/737)) ([18c1989](https://github.com/openai/openai-node/commit/18c19891f783019517d7961fe03c4d98de0fcf93)) + + +### Documentation + +* **readme:** consistent use of sentence case in headings ([#729](https://github.com/openai/openai-node/issues/729)) ([7e515fd](https://github.com/openai/openai-node/commit/7e515fde433ebfb7871d75d53915eef05a08a916)) +* **readme:** document how to make undocumented requests ([#730](https://github.com/openai/openai-node/issues/730)) ([a06d861](https://github.com/openai/openai-node/commit/a06d861a015eeee411fa2c6ed9bf3000313cfc03)) + +## 4.29.2 (2024-03-19) + +Full Changelog: [v4.29.1...v4.29.2](https://github.com/openai/openai-node/compare/v4.29.1...v4.29.2) + +### Chores + +* **internal:** update generated pragma comment ([#724](https://github.com/openai/openai-node/issues/724)) ([139e205](https://github.com/openai/openai-node/commit/139e205ed1ed30cb1df982d852a093dcea945aba)) + + +### Documentation + +* assistant improvements ([#725](https://github.com/openai/openai-node/issues/725)) ([6a2c41b](https://github.com/openai/openai-node/commit/6a2c41b0ce833eba0cdea6a7d221697f3be26abb)) +* fix typo in CONTRIBUTING.md ([#722](https://github.com/openai/openai-node/issues/722)) ([05ff8f7](https://github.com/openai/openai-node/commit/05ff8f7671fe6ce5d9517034f76a166a0bd27803)) + +## 4.29.1 (2024-03-15) + +Full Changelog: [v4.29.0...v4.29.1](https://github.com/openai/openai-node/compare/v4.29.0...v4.29.1) + +### Documentation + +* **readme:** assistant streaming ([#719](https://github.com/openai/openai-node/issues/719)) ([bc9a1ca](https://github.com/openai/openai-node/commit/bc9a1ca308020a88c29d409edc06cdfca8cbf8f5)) + +## 4.29.0 (2024-03-13) + +Full Changelog: [v4.28.5...v4.29.0](https://github.com/openai/openai-node/compare/v4.28.5...v4.29.0) + +### Features + +* **assistants:** add support for streaming ([#714](https://github.com/openai/openai-node/issues/714)) ([7d27d28](https://github.com/openai/openai-node/commit/7d27d286876d0a575d91a4752f401126fe93d2a3)) + +## 4.28.5 (2024-03-13) + +Full Changelog: [v4.28.4...v4.28.5](https://github.com/openai/openai-node/compare/v4.28.4...v4.28.5) + +### Bug Fixes + +* **ChatCompletionStream:** abort on async iterator break and handle errors ([#699](https://github.com/openai/openai-node/issues/699)) ([ac417a2](https://github.com/openai/openai-node/commit/ac417a2db31919d2b52f2eb2e38f9c67a8f73254)) +* **streaming:** correctly handle trailing new lines in byte chunks ([#708](https://github.com/openai/openai-node/issues/708)) ([4753be2](https://github.com/openai/openai-node/commit/4753be272b1d1dade7a769cf350b829fc639f36e)) + + +### Chores + +* **api:** update docs ([#703](https://github.com/openai/openai-node/issues/703)) ([e1db98b](https://github.com/openai/openai-node/commit/e1db98bef29d200e2e401e3f5d7b2db6839c7836)) +* **docs:** mention install from git repo ([#700](https://github.com/openai/openai-node/issues/700)) ([c081bdb](https://github.com/openai/openai-node/commit/c081bdbb55585e63370496d324dc6f94d86424d1)) +* fix error handler in readme ([#704](https://github.com/openai/openai-node/issues/704)) ([4ff790a](https://github.com/openai/openai-node/commit/4ff790a67cf876191e04ad0e369e447e080b78a7)) +* **internal:** add explicit type annotation to decoder ([#712](https://github.com/openai/openai-node/issues/712)) ([d728e99](https://github.com/openai/openai-node/commit/d728e9923554e4c72c9efa3bd528561400d50ad8)) +* **types:** fix accidental exposure of Buffer type to cloudflare ([#709](https://github.com/openai/openai-node/issues/709)) ([0323ecb](https://github.com/openai/openai-node/commit/0323ecb98ddbd8910fc5719c8bab5175b945d2ab)) + + +### Documentation + +* **contributing:** improve wording ([#696](https://github.com/openai/openai-node/issues/696)) ([940d569](https://github.com/openai/openai-node/commit/940d5695f4cacddbb58e3bfc50fec28c468c7e63)) +* **readme:** fix https proxy example ([#705](https://github.com/openai/openai-node/issues/705)) ([d144789](https://github.com/openai/openai-node/commit/d1447890a556d37928b628f6449bb80de224d207)) +* **readme:** fix typo in custom fetch implementation ([#698](https://github.com/openai/openai-node/issues/698)) ([64041fd](https://github.com/openai/openai-node/commit/64041fd33da569eccae64afe4e50ee803017b20b)) +* remove extraneous --save and yarn install instructions ([#710](https://github.com/openai/openai-node/issues/710)) ([8ec216d](https://github.com/openai/openai-node/commit/8ec216d6b72ee4d67e26786f06c93af18d042117)) +* use [@deprecated](https://github.com/deprecated) decorator for deprecated params ([#711](https://github.com/openai/openai-node/issues/711)) ([4688ef4](https://github.com/openai/openai-node/commit/4688ef4b36e9f383a3abf6cdb31d498163a7bb9e)) + +## 4.28.4 (2024-02-28) + +Full Changelog: [v4.28.3...v4.28.4](https://github.com/openai/openai-node/compare/v4.28.3...v4.28.4) + +### Features + +* **api:** add wav and pcm to response_format ([#691](https://github.com/openai/openai-node/issues/691)) ([b1c6171](https://github.com/openai/openai-node/commit/b1c61711961a62a4d7b47909a68ecd65231a66af)) + + +### Chores + +* **ci:** update actions/setup-node action to v4 ([#685](https://github.com/openai/openai-node/issues/685)) ([f2704d5](https://github.com/openai/openai-node/commit/f2704d5f1580c0f1d31584ef88702cde8f6804d4)) +* **internal:** fix ecosystem tests ([#693](https://github.com/openai/openai-node/issues/693)) ([616624d](https://github.com/openai/openai-node/commit/616624d3d9fd10ce254ce0d435b2b73ed11679f2)) +* **types:** extract run status to a named type ([#686](https://github.com/openai/openai-node/issues/686)) ([b3b3b8e](https://github.com/openai/openai-node/commit/b3b3b8ea20e0f311d3bd53dfd22ccc04f5dce5f7)) +* update @types/react to 18.2.58, @types/react-dom to 18.2.19 ([#688](https://github.com/openai/openai-node/issues/688)) ([2a0d0b1](https://github.com/openai/openai-node/commit/2a0d0b1cb197eef25e42bbba88ee90c37d623f24)) +* update dependency @types/node to v20.11.20 ([#690](https://github.com/openai/openai-node/issues/690)) ([4ca005b](https://github.com/openai/openai-node/commit/4ca005be082d6c50fe95da6148896b62080bfe07)) +* update dependency @types/ws to v8.5.10 ([#683](https://github.com/openai/openai-node/issues/683)) ([a617268](https://github.com/openai/openai-node/commit/a6172683a3390422984ad282ac4940781493e772)) +* update dependency next to v13.5.6 ([#689](https://github.com/openai/openai-node/issues/689)) ([abb3b66](https://github.com/openai/openai-node/commit/abb3b6674b8f9f8ff9c2cc61629a31883ae4d8c8)) + +## 4.28.3 (2024-02-20) + +Full Changelog: [v4.28.2...v4.28.3](https://github.com/openai/openai-node/compare/v4.28.2...v4.28.3) + +### Bug Fixes + +* **ci:** revert "move github release logic to github app" ([#680](https://github.com/openai/openai-node/issues/680)) ([8b4009a](https://github.com/openai/openai-node/commit/8b4009af05a2e0824f99d3cf8cd9063f234ae470)) + +## 4.28.2 (2024-02-19) + +Full Changelog: [v4.28.1...v4.28.2](https://github.com/openai/openai-node/compare/v4.28.1...v4.28.2) + +### Bug Fixes + +* **api:** remove non-GA instance_id param ([#677](https://github.com/openai/openai-node/issues/677)) ([4d0d4da](https://github.com/openai/openai-node/commit/4d0d4daf3bfca0089c5258a136542513e6b372e6)) + +## 4.28.1 (2024-02-19) + +Full Changelog: [v4.28.0...v4.28.1](https://github.com/openai/openai-node/compare/v4.28.0...v4.28.1) + +### Chores + +* **ci:** move github release logic to github app ([#671](https://github.com/openai/openai-node/issues/671)) ([ecca6bc](https://github.com/openai/openai-node/commit/ecca6bc2eea391ee53f1a1d6cac9665199447ae0)) +* **internal:** refactor release environment script ([#674](https://github.com/openai/openai-node/issues/674)) ([27d3770](https://github.com/openai/openai-node/commit/27d37705d17e05c3761ccefcf09c4e2018eb5772)) + +## 4.28.0 (2024-02-13) + +Full Changelog: [v4.27.1...v4.28.0](https://github.com/openai/openai-node/compare/v4.27.1...v4.28.0) + +### Features + +* **api:** updates ([#669](https://github.com/openai/openai-node/issues/669)) ([e1900f9](https://github.com/openai/openai-node/commit/e1900f97ee3f4758d47a7eb4659e30abe3750c99)) + +## 4.27.1 (2024-02-12) + +Full Changelog: [v4.27.0...v4.27.1](https://github.com/openai/openai-node/compare/v4.27.0...v4.27.1) + +## 4.27.0 (2024-02-08) + +Full Changelog: [v4.26.1...v4.27.0](https://github.com/openai/openai-node/compare/v4.26.1...v4.27.0) + +### Features + +* **api:** add `timestamp_granularities`, add `gpt-3.5-turbo-0125` model ([#661](https://github.com/openai/openai-node/issues/661)) ([5016806](https://github.com/openai/openai-node/commit/50168066862f66b529bae29f4564741300303246)) + + +### Chores + +* **internal:** fix retry mechanism for ecosystem-test ([#663](https://github.com/openai/openai-node/issues/663)) ([0eb7ed5](https://github.com/openai/openai-node/commit/0eb7ed5ca3f7c7b29c316fc7d725d834cee73989)) +* respect `application/vnd.api+json` content-type header ([#664](https://github.com/openai/openai-node/issues/664)) ([f4fad54](https://github.com/openai/openai-node/commit/f4fad549c5c366d8dd8b936b7699639b895e82a1)) + +## 4.26.1 (2024-02-05) + +Full Changelog: [v4.26.0...v4.26.1](https://github.com/openai/openai-node/compare/v4.26.0...v4.26.1) + +### Chores + +* **internal:** enable building when git installed ([#657](https://github.com/openai/openai-node/issues/657)) ([8c80a7d](https://github.com/openai/openai-node/commit/8c80a7d6d36155901a19d1f9cd1fec17b89e261e)) +* **internal:** re-order pagination import ([#656](https://github.com/openai/openai-node/issues/656)) ([21ae54e](https://github.com/openai/openai-node/commit/21ae54ea2cc2779e440909782a6ac8b70f88ec1f)) +* **internal:** support pre-release versioning ([#653](https://github.com/openai/openai-node/issues/653)) ([0c3859f](https://github.com/openai/openai-node/commit/0c3859f88164ae3eb6ec8c29e8889a50861cb35b)) +* **test:** add delay between ecosystem tests retry ([#651](https://github.com/openai/openai-node/issues/651)) ([6a4cc5c](https://github.com/openai/openai-node/commit/6a4cc5cea36ae408c8c1eb2ea0ea02f96ffb77b7)) + + +### Documentation + +* add a CONTRIBUTING.md ([#659](https://github.com/openai/openai-node/issues/659)) ([8ea58b0](https://github.com/openai/openai-node/commit/8ea58b0b9e7382a3b3af852a9a3a288a485ad33a)) + +## 4.26.0 (2024-01-25) + +Full Changelog: [v4.25.0...v4.26.0](https://github.com/openai/openai-node/compare/v4.25.0...v4.26.0) + +### Features + +* **api:** add text embeddings dimensions param ([#650](https://github.com/openai/openai-node/issues/650)) ([1b5a977](https://github.com/openai/openai-node/commit/1b5a977d0eef7f5cf97daf27333cbbeb6bb479f3)) + + +### Chores + +* **internal:** add internal helpers & improve build scripts ([#643](https://github.com/openai/openai-node/issues/643)) ([9392f50](https://github.com/openai/openai-node/commit/9392f50e47f26b16632c9eb12187ea7f8a565e09)) +* **internal:** adjust ecosystem-tests logging in CI ([#646](https://github.com/openai/openai-node/issues/646)) ([156084b](https://github.com/openai/openai-node/commit/156084b8734194a5856612378115b948c82ec6e4)) +* **internal:** don't re-export streaming type ([#648](https://github.com/openai/openai-node/issues/648)) ([4c4be94](https://github.com/openai/openai-node/commit/4c4be945fa3f54036183e2d0877060db47ea564b)) +* **internal:** fix binary files ([#645](https://github.com/openai/openai-node/issues/645)) ([e1fbc39](https://github.com/openai/openai-node/commit/e1fbc396f4d1dd8ba980c25ba03b670dfed887a0)) +* **internal:** minor streaming updates ([#647](https://github.com/openai/openai-node/issues/647)) ([2f073e4](https://github.com/openai/openai-node/commit/2f073e4e6c9cd0ff3ad434907da710704765a005)) +* **internal:** pin deno version ([#649](https://github.com/openai/openai-node/issues/649)) ([7e4b903](https://github.com/openai/openai-node/commit/7e4b9039320e4ccbafb45f57dce273bedc9b7cb3)) + +## 4.25.0 (2024-01-21) + +Full Changelog: [v4.24.7...v4.25.0](https://github.com/openai/openai-node/compare/v4.24.7...v4.25.0) + +### Features + +* **api:** add usage to runs and run steps ([#640](https://github.com/openai/openai-node/issues/640)) ([3caa416](https://github.com/openai/openai-node/commit/3caa4166b8abb5bffb4c8be1495834b7f16af32d)) + + +### Bug Fixes + +* allow body type in RequestOptions to be null ([#637](https://github.com/openai/openai-node/issues/637)) ([c4f8a36](https://github.com/openai/openai-node/commit/c4f8a3698dc1d80439131c5097975d6a5db1b4e2)) +* handle system_fingerprint in streaming helpers ([#636](https://github.com/openai/openai-node/issues/636)) ([f273530](https://github.com/openai/openai-node/commit/f273530ac491300842aef463852821a1a27805fb)) +* **types:** accept undefined for optional client options ([#635](https://github.com/openai/openai-node/issues/635)) ([e48cd57](https://github.com/openai/openai-node/commit/e48cd57931cd0e81a77b55653cb1f663111dd733)) + + +### Chores + +* **internal:** debug logging for retries; speculative retry-after-ms support ([#633](https://github.com/openai/openai-node/issues/633)) ([fd64971](https://github.com/openai/openai-node/commit/fd64971612d1d7fcbd8a63885d333485bff68ab1)) +* **internal:** update comment ([#631](https://github.com/openai/openai-node/issues/631)) ([e109d40](https://github.com/openai/openai-node/commit/e109d40a5c02c5bf4586e54d92bf0e355d254c1b)) + +## 4.24.7 (2024-01-13) + +Full Changelog: [v4.24.6...v4.24.7](https://github.com/openai/openai-node/compare/v4.24.6...v4.24.7) + +### Chores + +* **ecosystem-tests:** fix flaky vercel-edge, cloudflare-worker, and deno tests ([#626](https://github.com/openai/openai-node/issues/626)) ([ae412a5](https://github.com/openai/openai-node/commit/ae412a5f12e701e07e71bd9791c55a56858e8383)) +* **ecosystem-tests:** fix typo in deno test ([#628](https://github.com/openai/openai-node/issues/628)) ([048ec94](https://github.com/openai/openai-node/commit/048ec943f8d12acba9829c35ebf0b2d3f24930c8)) + +## 4.24.6 (2024-01-12) + +Full Changelog: [v4.24.5...v4.24.6](https://github.com/openai/openai-node/compare/v4.24.5...v4.24.6) + +### Chores + +* **ecosystem-tests:** fix flaky tests and remove fine tuning calls ([#623](https://github.com/openai/openai-node/issues/623)) ([258d79f](https://github.com/openai/openai-node/commit/258d79f52bb31f4f3723f6f4b97ebe8f3fa187bd)) +* **ecosystem-tests:** fix flaky tests and remove fine tuning calls ([#625](https://github.com/openai/openai-node/issues/625)) ([58e5fd8](https://github.com/openai/openai-node/commit/58e5fd8f27052be6ac9587256b161f4bf3a3805f)) + +## 4.24.5 (2024-01-12) + +Full Changelog: [v4.24.4...v4.24.5](https://github.com/openai/openai-node/compare/v4.24.4...v4.24.5) + +### Refactors + +* **api:** remove deprecated endpoints ([#621](https://github.com/openai/openai-node/issues/621)) ([2054d71](https://github.com/openai/openai-node/commit/2054d71e6b0d407229a4c5aecd75e38c336c2c02)) + +## 4.24.4 (2024-01-11) + +Full Changelog: [v4.24.3...v4.24.4](https://github.com/openai/openai-node/compare/v4.24.3...v4.24.4) + +### Chores + +* **internal:** narrow type into stringifyQuery ([#619](https://github.com/openai/openai-node/issues/619)) ([88fb9cd](https://github.com/openai/openai-node/commit/88fb9cd1bb415850b0b4868944617282d0b92e2a)) + +## 4.24.3 (2024-01-10) + +Full Changelog: [v4.24.2...v4.24.3](https://github.com/openai/openai-node/compare/v4.24.2...v4.24.3) + +### Bug Fixes + +* use default base url if BASE_URL env var is blank ([#615](https://github.com/openai/openai-node/issues/615)) ([a27ad3d](https://github.com/openai/openai-node/commit/a27ad3d4e06f2202daa169668d0e7d89e87a38a7)) + +## 4.24.2 (2024-01-08) + +Full Changelog: [v4.24.1...v4.24.2](https://github.com/openai/openai-node/compare/v4.24.1...v4.24.2) + +### Bug Fixes + +* **headers:** always send lowercase headers and strip undefined (BREAKING in rare cases) ([#608](https://github.com/openai/openai-node/issues/608)) ([4ea159f](https://github.com/openai/openai-node/commit/4ea159f0aa9a1f4c365c74ee726714fe692ddf9f)) + + +### Chores + +* add .keep files for examples and custom code directories ([#612](https://github.com/openai/openai-node/issues/612)) ([5e0f733](https://github.com/openai/openai-node/commit/5e0f733d3cd3c8e6d41659141168cd0708e017a3)) +* **internal:** bump license ([#605](https://github.com/openai/openai-node/issues/605)) ([045ee74](https://github.com/openai/openai-node/commit/045ee74fd3ffba9e6d1301fe1ffd8bd3c63720a2)) +* **internal:** improve type signatures ([#609](https://github.com/openai/openai-node/issues/609)) ([e1ccc82](https://github.com/openai/openai-node/commit/e1ccc82e4991262a631dcffa4d09bdc553e50fbb)) + + +### Documentation + +* fix docstring typos ([#600](https://github.com/openai/openai-node/issues/600)) ([1934fa1](https://github.com/openai/openai-node/commit/1934fa15f654ea89e226457f76febe6015616f6c)) +* improve audio example to show how to stream to a file ([#598](https://github.com/openai/openai-node/issues/598)) ([e950ad9](https://github.com/openai/openai-node/commit/e950ad969e845d608ed71bd3e3095cd6c941d93d)) + +## 4.24.1 (2023-12-22) + +Full Changelog: [v4.24.0...v4.24.1](https://github.com/openai/openai-node/compare/v4.24.0...v4.24.1) + +### Bug Fixes + +* **pagination:** correct type annotation object field ([#590](https://github.com/openai/openai-node/issues/590)) ([4066eda](https://github.com/openai/openai-node/commit/4066edad4b5305e82e610f44f4720843f2b69d39)) + + +### Documentation + +* **messages:** improvements to helpers reference + typos ([#595](https://github.com/openai/openai-node/issues/595)) ([96a59b9](https://github.com/openai/openai-node/commit/96a59b91c424db67b8a5bdb7cab5da68c57282d4)) +* reformat README.md ([#592](https://github.com/openai/openai-node/issues/592)) ([8ffc7f8](https://github.com/openai/openai-node/commit/8ffc7f876cc8f4b7afaf68a37f94f826ef22a6b8)) + + +### Refactors + +* write jest config in typescript ([#588](https://github.com/openai/openai-node/issues/588)) ([eb6ceeb](https://github.com/openai/openai-node/commit/eb6ceebf90ba45ec5b803f32b9b080829f6a973a)) + +## 4.24.0 (2023-12-19) + +Full Changelog: [v4.23.0...v4.24.0](https://github.com/openai/openai-node/compare/v4.23.0...v4.24.0) + +### Features + +* **api:** add additional instructions for runs ([#586](https://github.com/openai/openai-node/issues/586)) ([401d93e](https://github.com/openai/openai-node/commit/401d93ea39fe0e90088799858299322035c0a7e8)) + + +### Chores + +* **deps:** update dependency start-server-and-test to v2.0.3 ([#580](https://github.com/openai/openai-node/issues/580)) ([8e1aca1](https://github.com/openai/openai-node/commit/8e1aca1f8be6e583483919ed9ef9b04fab076066)) +* **deps:** update dependency ts-jest to v29.1.1 ([#578](https://github.com/openai/openai-node/issues/578)) ([a6edb7b](https://github.com/openai/openai-node/commit/a6edb7bc3cfc447d0c55ae23cc1c2219105d3666)) +* **deps:** update jest ([#582](https://github.com/openai/openai-node/issues/582)) ([e49e471](https://github.com/openai/openai-node/commit/e49e471ec7a136f2cbaf82551ccaaea366c87a91)) +* **internal:** bump deps ([#583](https://github.com/openai/openai-node/issues/583)) ([2e07b4c](https://github.com/openai/openai-node/commit/2e07b4c66ab1fdbb353fdd00994e293f93e981db)) +* **internal:** update deps ([#581](https://github.com/openai/openai-node/issues/581)) ([7b690dc](https://github.com/openai/openai-node/commit/7b690dca67ee8c3b0a89caf7f786ede5dc612a76)) + + +### Documentation + +* upgrade models in examples to latest version ([#585](https://github.com/openai/openai-node/issues/585)) ([60101a4](https://github.com/openai/openai-node/commit/60101a4117b1a8223d09fb9fe21d89af32431939)) + +## 4.23.0 (2023-12-17) + +Full Changelog: [v4.22.1...v4.23.0](https://github.com/openai/openai-node/compare/v4.22.1...v4.23.0) + +### Features + +* **api:** add token logprobs to chat completions ([#576](https://github.com/openai/openai-node/issues/576)) ([8d4292e](https://github.com/openai/openai-node/commit/8d4292e6358920b2c9d8df49c6a154231c468512)) + + +### Chores + +* **ci:** run release workflow once per day ([#574](https://github.com/openai/openai-node/issues/574)) ([529f09f](https://github.com/openai/openai-node/commit/529f09f827a675d6e851590acff4e6f4f2af2d26)) + +## 4.22.1 (2023-12-15) + +Full Changelog: [v4.22.0...v4.22.1](https://github.com/openai/openai-node/compare/v4.22.0...v4.22.1) + +### Chores + +* update dependencies ([#572](https://github.com/openai/openai-node/issues/572)) ([a51e620](https://github.com/openai/openai-node/commit/a51e62065224a516b17dd850ae564f5436d8db52)) + + +### Documentation + +* replace runFunctions with runTools in readme ([#570](https://github.com/openai/openai-node/issues/570)) ([c3b9ad5](https://github.com/openai/openai-node/commit/c3b9ad58e5f74d3339889aeb1d758c8c18f54de7)) + +## 4.22.0 (2023-12-15) + +Full Changelog: [v4.21.0...v4.22.0](https://github.com/openai/openai-node/compare/v4.21.0...v4.22.0) + +### Features + +* **api:** add optional `name` argument + improve docs ([#569](https://github.com/openai/openai-node/issues/569)) ([3b68ace](https://github.com/openai/openai-node/commit/3b68ace533976aedbf642d9b018d0de8d9a8bb88)) + + +### Chores + +* update prettier ([#567](https://github.com/openai/openai-node/issues/567)) ([83dec2a](https://github.com/openai/openai-node/commit/83dec2af62c481d7de16d8a3644aa239ded9e30c)) + +## 4.21.0 (2023-12-11) + +Full Changelog: [v4.20.1...v4.21.0](https://github.com/openai/openai-node/compare/v4.20.1...v4.21.0) + +### Features + +* **client:** support reading the base url from an env variable ([#547](https://github.com/openai/openai-node/issues/547)) ([06fb68d](https://github.com/openai/openai-node/commit/06fb68de1ff80983e349b6715d1037e2072c8dd4)) + + +### Bug Fixes + +* correct some runTools behavior and deprecate runFunctions ([#562](https://github.com/openai/openai-node/issues/562)) ([f5cdd0f](https://github.com/openai/openai-node/commit/f5cdd0f704d3d075cdfc5bc2df1f7a8bae5cd9f1)) +* prevent 400 when using runTools/runFunctions with Azure OpenAI API ([#544](https://github.com/openai/openai-node/issues/544)) ([735d9b8](https://github.com/openai/openai-node/commit/735d9b86acdc067e1ee6ebe1ea50de2955431050)) + + +### Documentation + +* **readme:** update example snippets ([#546](https://github.com/openai/openai-node/issues/546)) ([566d290](https://github.com/openai/openai-node/commit/566d290006920f536788bb77f4d24a6906e2971f)) + + +### Build System + +* specify `packageManager: yarn` ([#561](https://github.com/openai/openai-node/issues/561)) ([935b898](https://github.com/openai/openai-node/commit/935b8983c74f7b03b67d22f4d194989838f963f3)) + +## 4.20.1 (2023-11-24) + +Full Changelog: [v4.20.0...v4.20.1](https://github.com/openai/openai-node/compare/v4.20.0...v4.20.1) + +### Chores + +* **internal:** remove file import and conditionally run prepare ([#533](https://github.com/openai/openai-node/issues/533)) ([48cb729](https://github.com/openai/openai-node/commit/48cb729bfc484ce3d04273be417b307a0d20644f)) + + +### Documentation + +* **readme:** fix typo and add examples link ([#529](https://github.com/openai/openai-node/issues/529)) ([cf959b1](https://github.com/openai/openai-node/commit/cf959b17db0a4f8dd7eb59add333c4a461b02459)) + +## 4.20.0 (2023-11-22) + +Full Changelog: [v4.19.1...v4.20.0](https://github.com/openai/openai-node/compare/v4.19.1...v4.20.0) + +### Features + +* allow installing package directly from github ([#522](https://github.com/openai/openai-node/issues/522)) ([51926d7](https://github.com/openai/openai-node/commit/51926d7a0092744e49de39f4988feddf313adafa)) + + +### Chores + +* **internal:** don't call prepare in dist ([#525](https://github.com/openai/openai-node/issues/525)) ([d09411e](https://github.com/openai/openai-node/commit/d09411ebaa28d6610e1b880d03339d520b4a1833)) + +## 4.19.1 (2023-11-20) + +Full Changelog: [v4.19.0...v4.19.1](https://github.com/openai/openai-node/compare/v4.19.0...v4.19.1) + +## 4.19.0 (2023-11-15) + +Full Changelog: [v4.18.0...v4.19.0](https://github.com/openai/openai-node/compare/v4.18.0...v4.19.0) + +### Features + +* **api:** updates ([#501](https://github.com/openai/openai-node/issues/501)) ([944d58e](https://github.com/openai/openai-node/commit/944d58e5fc46f1a0671aaa2b809d28e67edf6023)) + +## 4.18.0 (2023-11-14) + +Full Changelog: [v4.17.5...v4.18.0](https://github.com/openai/openai-node/compare/v4.17.5...v4.18.0) + +### Features + +* **api:** add gpt-3.5-turbo-1106 ([#496](https://github.com/openai/openai-node/issues/496)) ([45f7672](https://github.com/openai/openai-node/commit/45f7672ccf4856ac309b08c6c96f0e73ab48b525)) + +## 4.17.5 (2023-11-13) + +Full Changelog: [v4.17.4...v4.17.5](https://github.com/openai/openai-node/compare/v4.17.4...v4.17.5) + +### Chores + +* fix typo in docs and add request header for function calls ([#494](https://github.com/openai/openai-node/issues/494)) ([22ce244](https://github.com/openai/openai-node/commit/22ce2443a77f10988b3215bd81ba17d4eda4b10e)) + +## 4.17.4 (2023-11-10) + +Full Changelog: [v4.17.3...v4.17.4](https://github.com/openai/openai-node/compare/v4.17.3...v4.17.4) + +### Chores + +* **internal:** update jest config ([#482](https://github.com/openai/openai-node/issues/482)) ([3013e8c](https://github.com/openai/openai-node/commit/3013e8c73a61a397a418ca75b996f0a7dd03a744)) + +## 4.17.3 (2023-11-09) + +Full Changelog: [v4.17.2...v4.17.3](https://github.com/openai/openai-node/compare/v4.17.2...v4.17.3) + +## 4.17.2 (2023-11-09) + +Full Changelog: [v4.17.1...v4.17.2](https://github.com/openai/openai-node/compare/v4.17.1...v4.17.2) + +### Chores + +* **internal:** bump deno version number ([#478](https://github.com/openai/openai-node/issues/478)) ([69913f3](https://github.com/openai/openai-node/commit/69913f3a4b0123394029759375445dae7b4f15ab)) + +## 4.17.1 (2023-11-09) + +Full Changelog: [v4.17.0...v4.17.1](https://github.com/openai/openai-node/compare/v4.17.0...v4.17.1) + +### Refactors + +* **client:** deprecate files.retrieveContent in favour of files.content ([#474](https://github.com/openai/openai-node/issues/474)) ([7c7bfc2](https://github.com/openai/openai-node/commit/7c7bfc2fad5a786c9172110e90c9566a943e49f9)) + +## 4.17.0 (2023-11-08) + +Full Changelog: [v4.16.2...v4.17.0](https://github.com/openai/openai-node/compare/v4.16.2...v4.17.0) + +### Features + +* **api:** unify function types ([#467](https://github.com/openai/openai-node/issues/467)) ([d51cd94](https://github.com/openai/openai-node/commit/d51cd94b3103219789447e2e9afc4762ae672e5a)) + + +### Refactors + +* **api:** rename FunctionObject to FunctionDefinition ([#470](https://github.com/openai/openai-node/issues/470)) ([f3990c7](https://github.com/openai/openai-node/commit/f3990c779e596309b62f41d7a1253d8629aca3bf)) + +## 4.16.2 (2023-11-08) + +Full Changelog: [v4.16.1...v4.16.2](https://github.com/openai/openai-node/compare/v4.16.1...v4.16.2) + +### Bug Fixes + +* **api:** accidentally required params, add new models & other fixes ([#463](https://github.com/openai/openai-node/issues/463)) ([1cb403e](https://github.com/openai/openai-node/commit/1cb403e4ccde61bb1613d362f6bdbca8b1681e00)) +* **api:** update embedding response object type ([#466](https://github.com/openai/openai-node/issues/466)) ([53b7e25](https://github.com/openai/openai-node/commit/53b7e2539cca0b272be96136c123d2b33745e7f6)) +* asssitant_deleted -> assistant_deleted ([#452](https://github.com/openai/openai-node/issues/452)) ([ef89bd7](https://github.com/openai/openai-node/commit/ef89bd74d85c833bf7de500eecd1b092a0ad3f37)) +* **types:** ensure all code paths return a value ([#458](https://github.com/openai/openai-node/issues/458)) ([19402c3](https://github.com/openai/openai-node/commit/19402c365572a99cbee58bcd34a9942e741269bf)) + + +### Chores + +* **docs:** fix github links ([#457](https://github.com/openai/openai-node/issues/457)) ([6b9b94e](https://github.com/openai/openai-node/commit/6b9b94e4e123349a908b708cd574ff107f40a8e1)) +* **internal:** fix typo in comment ([#456](https://github.com/openai/openai-node/issues/456)) ([fe24342](https://github.com/openai/openai-node/commit/fe2434284a91d424510873a18079b8870469c672)) + + +### Documentation + +* update deno deploy link to include v ([#441](https://github.com/openai/openai-node/issues/441)) ([47b13aa](https://github.com/openai/openai-node/commit/47b13aaa6fac86fffabee1f752ee6d2efc3def9b)) + +## 4.16.1 (2023-11-06) + +Full Changelog: [v4.16.0...v4.16.1](https://github.com/openai/openai-node/compare/v4.16.0...v4.16.1) + +### Bug Fixes + +* **api:** retreival -> retrieval ([#437](https://github.com/openai/openai-node/issues/437)) ([b4bd3ee](https://github.com/openai/openai-node/commit/b4bd3eefdd3903abcc57c431382cc2124d39307b)) + + +### Documentation + +* **api:** improve docstrings ([#435](https://github.com/openai/openai-node/issues/435)) ([ee8b24c](https://github.com/openai/openai-node/commit/ee8b24c70a5ccb944e02ff2201668d6bc2b597b3)) + +## 4.16.0 (2023-11-06) + +Full Changelog: [v4.15.4...v4.16.0](https://github.com/openai/openai-node/compare/v4.15.4...v4.16.0) + +### Features + +* **api:** releases from DevDay; assistants, multimodality, tools, dall-e-3, tts, and more ([#433](https://github.com/openai/openai-node/issues/433)) ([fb92f5e](https://github.com/openai/openai-node/commit/fb92f5e6e3b6e7969b3d91f4ccdaef87e5fea0a4)) + + +### Bug Fixes + +* improve deno readme ([#429](https://github.com/openai/openai-node/issues/429)) ([871ceac](https://github.com/openai/openai-node/commit/871ceac2b37f53f7fc7c0163454115c709cd7ced)) + + +### Documentation + +* deno version ([#432](https://github.com/openai/openai-node/issues/432)) ([74bf336](https://github.com/openai/openai-node/commit/74bf3364379fd23252fde01401c44b2fa796cba4)) +* update deno link in more places ([#431](https://github.com/openai/openai-node/issues/431)) ([5da63d4](https://github.com/openai/openai-node/commit/5da63d4a9143c0ab493b742f7fde22b01a372844)) + +## 4.15.4 (2023-11-05) + +Full Changelog: [v4.15.3...v4.15.4](https://github.com/openai/openai-node/compare/v4.15.3...v4.15.4) + +### Documentation + +* **readme:** remove redundant whitespace ([#427](https://github.com/openai/openai-node/issues/427)) ([aa3a178](https://github.com/openai/openai-node/commit/aa3a1782914a4a285263e4d070bca73e72ed47ec)) + +## 4.15.3 (2023-11-04) + +Full Changelog: [v4.15.2...v4.15.3](https://github.com/openai/openai-node/compare/v4.15.2...v4.15.3) + +### Bug Fixes + +* improve deno releases ([#425](https://github.com/openai/openai-node/issues/425)) ([19469f2](https://github.com/openai/openai-node/commit/19469f266ff69a4e549402188d9f6ad87f5a7778)) + +## 4.15.2 (2023-11-04) + +Full Changelog: [v4.15.1...v4.15.2](https://github.com/openai/openai-node/compare/v4.15.1...v4.15.2) + +### Documentation + +* fix deno.land import ([#423](https://github.com/openai/openai-node/issues/423)) ([e5415a2](https://github.com/openai/openai-node/commit/e5415a29ab447ced8535fafda7928b0a6748c8d1)) + +## 4.15.1 (2023-11-04) + +Full Changelog: [v4.15.0...v4.15.1](https://github.com/openai/openai-node/compare/v4.15.0...v4.15.1) + +### Documentation + +* document customizing fetch ([#420](https://github.com/openai/openai-node/issues/420)) ([1ca982f](https://github.com/openai/openai-node/commit/1ca982f192daf49e33b7acb5505ed26c9d891255)) + +## 4.15.0 (2023-11-03) + +Full Changelog: [v4.14.2...v4.15.0](https://github.com/openai/openai-node/compare/v4.14.2...v4.15.0) + +### Features + +* **beta:** add streaming and function calling helpers ([#409](https://github.com/openai/openai-node/issues/409)) ([510c1f3](https://github.com/openai/openai-node/commit/510c1f325ee55197b4c2f434475128c265500746)) +* **client:** allow binary returns ([#416](https://github.com/openai/openai-node/issues/416)) ([02f7ad7](https://github.com/openai/openai-node/commit/02f7ad7f736751e0e7687e6744bae464d4e40b79)) +* **github:** include a devcontainer setup ([#413](https://github.com/openai/openai-node/issues/413)) ([fb2996f](https://github.com/openai/openai-node/commit/fb2996f0d291210878145aacf9b952f8133d9414)) +* streaming improvements ([#411](https://github.com/openai/openai-node/issues/411)) ([37b622c](https://github.com/openai/openai-node/commit/37b622c79ddbd6c286b730e740403c82b542e796)) + +## 4.14.2 (2023-10-30) + +Full Changelog: [v4.14.1...v4.14.2](https://github.com/openai/openai-node/compare/v4.14.1...v4.14.2) + +### Chores + +* **docs:** update deno link ([#407](https://github.com/openai/openai-node/issues/407)) ([0328882](https://github.com/openai/openai-node/commit/0328882cccb3e5386283ffa5eb9cd8ad9442f3a0)) + +## 4.14.1 (2023-10-27) + +Full Changelog: [v4.14.0...v4.14.1](https://github.com/openai/openai-node/compare/v4.14.0...v4.14.1) + +### Bug Fixes + +* deploy deno in a github workflow instead of postpublish step ([#405](https://github.com/openai/openai-node/issues/405)) ([3a6dba0](https://github.com/openai/openai-node/commit/3a6dba074258274bffcfe3a4260ca1b95bcd6bdc)) +* typo in build script ([#403](https://github.com/openai/openai-node/issues/403)) ([76c5c96](https://github.com/openai/openai-node/commit/76c5c96a359f750f58ea38b5d32365db7e34409a)) + + +### Chores + +* **internal:** update gitignore ([#406](https://github.com/openai/openai-node/issues/406)) ([986b0bb](https://github.com/openai/openai-node/commit/986b0bbac9f5ca43a0df6f29f2a468dd4223e053)) + +## 4.14.0 (2023-10-25) + +Full Changelog: [v4.13.0...v4.14.0](https://github.com/openai/openai-node/compare/v4.13.0...v4.14.0) + +### Features + +* **client:** adjust retry behavior to be exponential backoff ([#400](https://github.com/openai/openai-node/issues/400)) ([2bc14ce](https://github.com/openai/openai-node/commit/2bc14ce300ef020bc045199fe3d76dd352d78ef9)) + + +### Chores + +* **docs:** update deno version ([#399](https://github.com/openai/openai-node/issues/399)) ([cdee077](https://github.com/openai/openai-node/commit/cdee0770690d4b66b357d970827e9ba1597ffb89)) + +## 4.13.0 (2023-10-22) + +Full Changelog: [v4.12.4...v4.13.0](https://github.com/openai/openai-node/compare/v4.12.4...v4.13.0) + +### Features + +* **api:** add embeddings encoding_format ([#390](https://github.com/openai/openai-node/issues/390)) ([cf70dea](https://github.com/openai/openai-node/commit/cf70deaba1426786aba9b938d280c61aeb516e34)) +* handle 204 No Content gracefully ([#391](https://github.com/openai/openai-node/issues/391)) ([2dd005c](https://github.com/openai/openai-node/commit/2dd005c1c497605036d3524f19d130b3fc5f8d8b)) + +## 4.12.4 (2023-10-17) + +Full Changelog: [v4.12.3...v4.12.4](https://github.com/openai/openai-node/compare/v4.12.3...v4.12.4) + +### Bug Fixes + +* import web-streams-polyfill without overriding globals ([#385](https://github.com/openai/openai-node/issues/385)) ([be8e18b](https://github.com/openai/openai-node/commit/be8e18ba4c6a16e7b6413c77246f83230e0b8fc2)) + +## 4.12.3 (2023-10-16) + +Full Changelog: [v4.12.2...v4.12.3](https://github.com/openai/openai-node/compare/v4.12.2...v4.12.3) + +### Documentation + +* organisation -> organization (UK to US English) ([#382](https://github.com/openai/openai-node/issues/382)) ([516f0ad](https://github.com/openai/openai-node/commit/516f0ade1ec1fd8fc4c78999ee0f656cc2b5ae58)) + +## 4.12.2 (2023-10-16) + +Full Changelog: [v4.12.1...v4.12.2](https://github.com/openai/openai-node/compare/v4.12.1...v4.12.2) + +### Bug Fixes + +* **client:** correctly handle errors during streaming ([#377](https://github.com/openai/openai-node/issues/377)) ([09233b1](https://github.com/openai/openai-node/commit/09233b1ccc80ee900be19050f438cc8aa9dbb513)) +* **client:** correctly handle errors during streaming ([#379](https://github.com/openai/openai-node/issues/379)) ([9ced580](https://github.com/openai/openai-node/commit/9ced5804777a5857d6775a49ddf30ed9cc016fab)) +* improve status code in error messages ([#381](https://github.com/openai/openai-node/issues/381)) ([68dfb17](https://github.com/openai/openai-node/commit/68dfb17cce300ade8d29afc854d616833b3283ca)) + + +### Chores + +* add case insensitive get header function ([#373](https://github.com/openai/openai-node/issues/373)) ([b088998](https://github.com/openai/openai-node/commit/b088998ae610de54bb8700eefd6b664eb9a2fcc3)) +* **internal:** add debug logs for stream responses ([#380](https://github.com/openai/openai-node/issues/380)) ([689db0b](https://github.com/openai/openai-node/commit/689db0b8058527ae5c3af5e457c962d8a6635297)) +* show deprecation notice on re-export ([#368](https://github.com/openai/openai-node/issues/368)) ([b176703](https://github.com/openai/openai-node/commit/b176703102998f0e9d8ca2ed93ccd495fd10a6ee)) +* update comment ([#376](https://github.com/openai/openai-node/issues/376)) ([a06c685](https://github.com/openai/openai-node/commit/a06c6850bfdd756dc8f07dd1f70218be610faa30)) +* update comment ([#378](https://github.com/openai/openai-node/issues/378)) ([b04031d](https://github.com/openai/openai-node/commit/b04031d19210a66f82c7d233a50f7bc427a1bf92)) + + +### Refactors + +* **streaming:** change Stream constructor signature ([#370](https://github.com/openai/openai-node/issues/370)) ([71984ed](https://github.com/openai/openai-node/commit/71984edc3141ba99ffa1327bab6a182b4452209f)) +* **test:** refactor authentication tests ([#371](https://github.com/openai/openai-node/issues/371)) ([e0d459f](https://github.com/openai/openai-node/commit/e0d459f958451a99e15a11a0e5ea6471abbe1ac1)) + +## 4.12.1 (2023-10-11) + +Full Changelog: [v4.12.0...v4.12.1](https://github.com/openai/openai-node/compare/v4.12.0...v4.12.1) + +### Bug Fixes + +* fix namespace exports regression ([#366](https://github.com/openai/openai-node/issues/366)) ([b2b1d85](https://github.com/openai/openai-node/commit/b2b1d85d90eef51e689ca75c0ca2f35bb63cccc0)) + +## 4.12.0 (2023-10-11) + +Full Changelog: [v4.11.1...v4.12.0](https://github.com/openai/openai-node/compare/v4.11.1...v4.12.0) + +### Features + +* **api:** remove `content_filter` stop_reason and update documentation ([#352](https://github.com/openai/openai-node/issues/352)) ([a4b401e](https://github.com/openai/openai-node/commit/a4b401e91a0b3fbf55aedfb6ed6d93396377bf27)) +* re-export chat completion types at the top level, and work around webpack limitations ([#365](https://github.com/openai/openai-node/issues/365)) ([bb815d0](https://github.com/openai/openai-node/commit/bb815d0373ae33f58329e34e8983f5b3881db22d)) + + +### Bug Fixes + +* prevent ReferenceError, update compatibility to ES2020 and Node 18+ ([#356](https://github.com/openai/openai-node/issues/356)) ([fc71a4b](https://github.com/openai/openai-node/commit/fc71a4b6b73208ff3e8f0c8792a9a03e3790d26b)) + + +### Chores + +* **internal:** minor formatting improvement ([#354](https://github.com/openai/openai-node/issues/354)) ([3799863](https://github.com/openai/openai-node/commit/3799863da4ff2a27940ef0b7e57360c72e44d986)) + +## 4.11.1 (2023-10-03) + +Full Changelog: [v4.11.0...v4.11.1](https://github.com/openai/openai-node/compare/v4.11.0...v4.11.1) + +## 4.11.0 (2023-09-29) + +Full Changelog: [v4.10.0...v4.11.0](https://github.com/openai/openai-node/compare/v4.10.0...v4.11.0) + +### Features + +* **client:** handle retry-after with a date ([#340](https://github.com/openai/openai-node/issues/340)) ([b6dd384](https://github.com/openai/openai-node/commit/b6dd38488ea7cc4c22495f16d027b7ffdb87da53)) +* **package:** export a root error type ([#338](https://github.com/openai/openai-node/issues/338)) ([462bcda](https://github.com/openai/openai-node/commit/462bcda7140611afa20bc25de4aec6d4b205b37d)) + + +### Bug Fixes + +* **api:** add content_filter to chat completion finish reason ([#344](https://github.com/openai/openai-node/issues/344)) ([f10c757](https://github.com/openai/openai-node/commit/f10c757d831d90407ba47b4659d9cd34b1a35b1d)) + + +### Chores + +* **internal:** bump lock file ([#334](https://github.com/openai/openai-node/issues/334)) ([fd2337b](https://github.com/openai/openai-node/commit/fd2337b018ab2f31bcea8f9feda0ddaf755390c7)) +* **internal:** update lock file ([#339](https://github.com/openai/openai-node/issues/339)) ([1bf84b6](https://github.com/openai/openai-node/commit/1bf84b672c386f8ca46bb8fc120eb8d8d48b3a82)) +* **internal:** update lock file ([#342](https://github.com/openai/openai-node/issues/342)) ([0001f06](https://github.com/openai/openai-node/commit/0001f062728b0e2047d2bf03b9d947a4be0c7206)) +* **internal:** update lock file ([#343](https://github.com/openai/openai-node/issues/343)) ([a02ac8e](https://github.com/openai/openai-node/commit/a02ac8e7f881551527a3cbcadad53b7e424650e8)) + +## 4.10.0 (2023-09-21) + +Full Changelog: [v4.9.1...v4.10.0](https://github.com/openai/openai-node/compare/v4.9.1...v4.10.0) + +### Features + +* **api:** add 'gpt-3.5-turbo-instruct', fine-tune error objects, update documentation ([#329](https://github.com/openai/openai-node/issues/329)) ([e5f3852](https://github.com/openai/openai-node/commit/e5f385233737002b4bb47a94cba33da7fedfe64d)) + +## 4.10.0 (2023-09-21) + +Full Changelog: [v4.9.1...v4.10.0](https://github.com/openai/openai-node/compare/v4.9.1...v4.10.0) + +### Features + +* **api:** add 'gpt-3.5-turbo-instruct', fine-tune error objects, update documentation ([#329](https://github.com/openai/openai-node/issues/329)) ([e5f3852](https://github.com/openai/openai-node/commit/e5f385233737002b4bb47a94cba33da7fedfe64d)) + +## 4.9.1 (2023-09-21) + +Full Changelog: [v4.9.0...v4.9.1](https://github.com/openai/openai-node/compare/v4.9.0...v4.9.1) + +### Documentation + +* **README:** fix variable names in some examples ([#327](https://github.com/openai/openai-node/issues/327)) ([5e05b31](https://github.com/openai/openai-node/commit/5e05b31c132545ce166cea92c5f3e4410fd40711)) + +## 4.9.0 (2023-09-20) + +Full Changelog: [v4.8.0...v4.9.0](https://github.com/openai/openai-node/compare/v4.8.0...v4.9.0) + +### Features + +* **client:** support importing node or web shims manually ([#325](https://github.com/openai/openai-node/issues/325)) ([628f293](https://github.com/openai/openai-node/commit/628f2935a8791625685f68f73db8f3759b8f4f91)) + +## 4.8.0 (2023-09-15) + +Full Changelog: [v4.7.1...v4.8.0](https://github.com/openai/openai-node/compare/v4.7.1...v4.8.0) + +### Features + +* **errors:** add status code to error message ([#315](https://github.com/openai/openai-node/issues/315)) ([9341219](https://github.com/openai/openai-node/commit/93412197c67cb3fb203f35e3ae0a7c3fb173453e)) + +## 4.7.1 (2023-09-15) + +Full Changelog: [v4.7.0...v4.7.1](https://github.com/openai/openai-node/compare/v4.7.0...v4.7.1) + +### Documentation + +* declare Bun 1.0 officially supported ([#314](https://github.com/openai/openai-node/issues/314)) ([a16e268](https://github.com/openai/openai-node/commit/a16e26863390235cb43e2fe0e569298a4f84c32f)) + +## 4.7.0 (2023-09-14) + +Full Changelog: [v4.6.0...v4.7.0](https://github.com/openai/openai-node/compare/v4.6.0...v4.7.0) + +### Features + +* **client:** retry on 408 Request Timeout ([#310](https://github.com/openai/openai-node/issues/310)) ([1f98eac](https://github.com/openai/openai-node/commit/1f98eac5be956e56d75ef5456115165b45a4763c)) +* make docs urls in comments absolute ([#306](https://github.com/openai/openai-node/issues/306)) ([9db3819](https://github.com/openai/openai-node/commit/9db381961e38d2280b0602447e7d91691b327bde)) + +## 4.6.0 (2023-09-08) + +Full Changelog: [v4.5.0...v4.6.0](https://github.com/openai/openai-node/compare/v4.5.0...v4.6.0) + +### Features + +* **types:** extract ChatCompletionRole enum to its own type ([#298](https://github.com/openai/openai-node/issues/298)) ([5893e37](https://github.com/openai/openai-node/commit/5893e37406ff85331c85a3baa519ca3051a28e00)) + + +### Bug Fixes + +* fix module not found errors in Vercel edge ([#300](https://github.com/openai/openai-node/issues/300)) ([47c79fe](https://github.com/openai/openai-node/commit/47c79fee0fa715ad04410e73530829602736d85f)) + +## 4.5.0 (2023-09-06) + +Full Changelog: [v4.4.0...v4.5.0](https://github.com/openai/openai-node/compare/v4.4.0...v4.5.0) + +### Features + +* **client:** add files.waitForProcessing() method ([#292](https://github.com/openai/openai-node/issues/292)) ([ef59010](https://github.com/openai/openai-node/commit/ef59010cab0c666fa8a437ec6e27800789aa8705)) +* fixes tests where an array has to have unique enum values ([#290](https://github.com/openai/openai-node/issues/290)) ([a10b895](https://github.com/openai/openai-node/commit/a10b8956b3eaae7cdcb90329a8386a41219ca021)) +* make docs more readable by eliminating unnecessary escape sequences ([#287](https://github.com/openai/openai-node/issues/287)) ([a068043](https://github.com/openai/openai-node/commit/a06804314d4815d420c97f6f965c926ea70d56df)) + + +### Bug Fixes + +* **client:** fix TS errors that appear when users Go to Source in VSCode ([#281](https://github.com/openai/openai-node/issues/281)) ([8dc59bc](https://github.com/openai/openai-node/commit/8dc59bcf924cc991747ca475c714d915e04c6012)), closes [#249](https://github.com/openai/openai-node/issues/249) +* **client:** handle case where the client is instantiated with a undefined baseURL ([#285](https://github.com/openai/openai-node/issues/285)) ([5095cf3](https://github.com/openai/openai-node/commit/5095cf340743e4627b4f0ad2f055ebe332824d23)) +* **client:** use explicit file extensions in _shims imports ([#276](https://github.com/openai/openai-node/issues/276)) ([16fe929](https://github.com/openai/openai-node/commit/16fe929688d35c2ebe52c8cf1c1570bafda5f97e)) + + +### Documentation + +* **api:** update docstrings ([#286](https://github.com/openai/openai-node/issues/286)) ([664e953](https://github.com/openai/openai-node/commit/664e9532c8acfbf981e9a788ab40c111ebe2fda0)) +* **readme:** add link to api.md ([#291](https://github.com/openai/openai-node/issues/291)) ([0d1cce2](https://github.com/openai/openai-node/commit/0d1cce26cdc6567c10c8d72bbc72a788ffb8f2be)) + +## 4.4.0 (2023-09-01) + +Full Changelog: [v4.3.1...v4.4.0](https://github.com/openai/openai-node/compare/v4.3.1...v4.4.0) + +### Features + +* **package:** add Bun export map ([#269](https://github.com/openai/openai-node/issues/269)) ([16f239c](https://github.com/openai/openai-node/commit/16f239c6b4e8526371b01c511d2e0ebba4c5c8c6)) +* re-export chat completion types at the top level ([#268](https://github.com/openai/openai-node/issues/268)) ([1a71a39](https://github.com/openai/openai-node/commit/1a71a39421828fdde7b8605094363a5047d2fdc9)) +* **tests:** unskip multipart form data tests ([#275](https://github.com/openai/openai-node/issues/275)) ([47d3e18](https://github.com/openai/openai-node/commit/47d3e18a3ee987d04b958dad1a51821ad5472d54)) +* **types:** fix ambiguous auto-import for chat completions params ([#266](https://github.com/openai/openai-node/issues/266)) ([19c99fb](https://github.com/openai/openai-node/commit/19c99fb268d6d6c7fc7aaa66475c35f45d12b4bd)) + + +### Bug Fixes + +* revert import change which triggered circular import bug in webpack ([#274](https://github.com/openai/openai-node/issues/274)) ([6534e36](https://github.com/openai/openai-node/commit/6534e3620d7e2983e98b42cf95fa966deab1ab1d)) + +## 4.3.1 (2023-08-29) + +Full Changelog: [v4.3.0...v4.3.1](https://github.com/openai/openai-node/compare/v4.3.0...v4.3.1) + +### Bug Fixes + +* **types:** improve getNextPage() return type ([#262](https://github.com/openai/openai-node/issues/262)) ([245a984](https://github.com/openai/openai-node/commit/245a9847d1ba5bbe5262bc06b2f7bb7385cd3a9a)) + + +### Chores + +* **ci:** setup workflows to create releases and release PRs ([#259](https://github.com/openai/openai-node/issues/259)) ([290908c](https://github.com/openai/openai-node/commit/290908ce24dc6c31df18b2eb7808d5b495387454)) + +## [4.3.0](https://github.com/openai/openai-node/compare/v4.2.0...v4.3.0) (2023-08-27) + + +### Features + +* **client:** add auto-pagination to fine tuning list endpoints ([#254](https://github.com/openai/openai-node/issues/254)) ([5f89c5e](https://github.com/openai/openai-node/commit/5f89c5e6b9088cc2e86405a32b60cae91c078ce1)) +* **cli:** rewrite in JS for better compatibility ([#244](https://github.com/openai/openai-node/issues/244)) ([d8d7c05](https://github.com/openai/openai-node/commit/d8d7c0592bfad89669cd2f174e6207370cd7d3fb)) + + +### Bug Fixes + +* **stream:** declare Stream.controller as public ([#252](https://github.com/openai/openai-node/issues/252)) ([81e5de7](https://github.com/openai/openai-node/commit/81e5de7ba94c992cafa3d08e2697c8122382497a)) + + +### Documentation + +* **readme:** mention Azure support ([#253](https://github.com/openai/openai-node/issues/253)) ([294727a](https://github.com/openai/openai-node/commit/294727ad3543d91ef59df285ce1616c442d369db)) + + +### Chores + +* **internal:** add helper method ([#255](https://github.com/openai/openai-node/issues/255)) ([6d8cff0](https://github.com/openai/openai-node/commit/6d8cff00164c0f65ed40b941486f2e0d752feb1e)) + +## [4.2.0](https://github.com/openai/openai-node/compare/v4.1.0...v4.2.0) (2023-08-23) + + +### Features + +* **types:** export RequestOptions type ([#240](https://github.com/openai/openai-node/issues/240)) ([ecf3bce](https://github.com/openai/openai-node/commit/ecf3bcee3c64a80a3cd901aa32d3db78d1364645)) + + +### Chores + +* **internal:** export HeadersInit type shim ([#241](https://github.com/openai/openai-node/issues/241)) ([cf9f672](https://github.com/openai/openai-node/commit/cf9f6729b5b232a37841c33db33b2519b54f19b2)) diff --git a/backend/node_modules/openai/LICENSE b/backend/node_modules/openai/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..621a6becfb46d605cab24a7fe8dbcfd99a2890da --- /dev/null +++ b/backend/node_modules/openai/LICENSE @@ -0,0 +1,201 @@ + 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: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) 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 + + (d) 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 2024 OpenAI + + 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/backend/node_modules/openai/README.md b/backend/node_modules/openai/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c32fcfcd9fc7b242b9ad453ee9ab987f6447ddd2 --- /dev/null +++ b/backend/node_modules/openai/README.md @@ -0,0 +1,591 @@ +# OpenAI Node API Library + +[![NPM version](https://img.shields.io/npm/v/openai.svg)](https://npmjs.org/package/openai) + +This library provides convenient access to the OpenAI REST API from TypeScript or JavaScript. + +It is generated from our [OpenAPI specification](https://github.com/openai/openai-openapi) with [Stainless](https://stainlessapi.com/). + +To learn how to use the OpenAI API, check out our [API Reference](https://platform.openai.com/docs/api-reference) and [Documentation](https://platform.openai.com/docs). + +## Installation + +```sh +npm install openai +``` + +You can import in Deno via: + + + +```ts +import OpenAI from 'https://deno.land/x/openai@v4.35.0/mod.ts'; +``` + + + +## Usage + +The full API of this library can be found in [api.md file](api.md) along with many [code examples](https://github.com/openai/openai-node/tree/master/examples). The code below shows how to get started using the chat completions API. + + +```js +import OpenAI from 'openai'; + +const openai = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted +}); + +async function main() { + const chatCompletion = await openai.chat.completions.create({ + messages: [{ role: 'user', content: 'Say this is a test' }], + model: 'gpt-3.5-turbo', + }); +} + +main(); +``` + +## Streaming responses + +We provide support for streaming responses using Server Sent Events (SSE). + +```ts +import OpenAI from 'openai'; + +const openai = new OpenAI(); + +async function main() { + const stream = await openai.chat.completions.create({ + model: 'gpt-4', + messages: [{ role: 'user', content: 'Say this is a test' }], + stream: true, + }); + for await (const chunk of stream) { + process.stdout.write(chunk.choices[0]?.delta?.content || ''); + } +} + +main(); +``` + +If you need to cancel a stream, you can `break` from the loop +or call `stream.controller.abort()`. + +### Request & Response types + +This library includes TypeScript definitions for all request params and response fields. You may import and use them like so: + + +```ts +import OpenAI from 'openai'; + +const openai = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted +}); + +async function main() { + const params: OpenAI.Chat.ChatCompletionCreateParams = { + messages: [{ role: 'user', content: 'Say this is a test' }], + model: 'gpt-3.5-turbo', + }; + const chatCompletion: OpenAI.Chat.ChatCompletion = await openai.chat.completions.create(params); +} + +main(); +``` + +Documentation for each method, request param, and response field are available in docstrings and will appear on hover in most modern editors. + +> [!IMPORTANT] +> Previous versions of this SDK used a `Configuration` class. See the [v3 to v4 migration guide](https://github.com/openai/openai-node/discussions/217). + +### Polling Helpers + +When interacting with the API some actions such as starting a Run may take time to complete. The SDK includes +helper functions which will poll the status until it reaches a terminal state and then return the resulting object. +If an API method results in an action which could benefit from polling there will be a corresponding version of the +method ending in 'AndPoll'. + +For instance to create a Run and poll until it reaches a terminal state you can run: + +```ts +const run = await openai.beta.threads.runs.createAndPoll(thread.id, { + assistant_id: assistantId, +}); +``` + +More information on the lifecycle of a Run can be found in the [Run Lifecycle Documentation](https://platform.openai.com/docs/assistants/how-it-works/run-lifecycle) + +### Streaming Helpers + +The SDK also includes helpers to process streams and handle the incoming events. + +```ts +const run = openai.beta.threads.runs + .stream(thread.id, { + assistant_id: assistant.id, + }) + .on('textCreated', (text) => process.stdout.write('\nassistant > ')) + .on('textDelta', (textDelta, snapshot) => process.stdout.write(textDelta.value)) + .on('toolCallCreated', (toolCall) => process.stdout.write(`\nassistant > ${toolCall.type}\n\n`)) + .on('toolCallDelta', (toolCallDelta, snapshot) => { + if (toolCallDelta.type === 'code_interpreter') { + if (toolCallDelta.code_interpreter.input) { + process.stdout.write(toolCallDelta.code_interpreter.input); + } + if (toolCallDelta.code_interpreter.outputs) { + process.stdout.write('\noutput >\n'); + toolCallDelta.code_interpreter.outputs.forEach((output) => { + if (output.type === 'logs') { + process.stdout.write(`\n${output.logs}\n`); + } + }); + } + } + }); +``` + +More information on streaming helpers can be found in the dedicated documentation: [helpers.md](helpers.md) + +### Streaming responses + +This library provides several conveniences for streaming chat completions, for example: + +```ts +import OpenAI from 'openai'; + +const openai = new OpenAI(); + +async function main() { + const stream = await openai.beta.chat.completions.stream({ + model: 'gpt-4', + messages: [{ role: 'user', content: 'Say this is a test' }], + stream: true, + }); + + stream.on('content', (delta, snapshot) => { + process.stdout.write(delta); + }); + + // or, equivalently: + for await (const chunk of stream) { + process.stdout.write(chunk.choices[0]?.delta?.content || ''); + } + + const chatCompletion = await stream.finalChatCompletion(); + console.log(chatCompletion); // {id: "…", choices: […], …} +} + +main(); +``` + +Streaming with `openai.beta.chat.completions.stream({…})` exposes +[various helpers for your convenience](helpers.md#events) including event handlers and promises. + +Alternatively, you can use `openai.chat.completions.create({ stream: true, … })` +which only returns an async iterable of the chunks in the stream and thus uses less memory +(it does not build up a final chat completion object for you). + +If you need to cancel a stream, you can `break` from a `for await` loop or call `stream.abort()`. + +### Automated function calls + +We provide the `openai.beta.chat.completions.runTools({…})` +convenience helper for using function tool calls with the `/chat/completions` endpoint +which automatically call the JavaScript functions you provide +and sends their results back to the `/chat/completions` endpoint, +looping as long as the model requests tool calls. + +If you pass a `parse` function, it will automatically parse the `arguments` for you +and returns any parsing errors to the model to attempt auto-recovery. +Otherwise, the args will be passed to the function you provide as a string. + +If you pass `tool_choice: {function: {name: …}}` instead of `auto`, +it returns immediately after calling that function (and only loops to auto-recover parsing errors). + +```ts +import OpenAI from 'openai'; + +const client = new OpenAI(); + +async function main() { + const runner = client.beta.chat.completions + .runTools({ + model: 'gpt-3.5-turbo', + messages: [{ role: 'user', content: 'How is the weather this week?' }], + tools: [ + { + type: 'function', + function: { + function: getCurrentLocation, + parameters: { type: 'object', properties: {} }, + }, + }, + { + type: 'function', + function: { + function: getWeather, + parse: JSON.parse, // or use a validation library like zod for typesafe parsing. + parameters: { + type: 'object', + properties: { + location: { type: 'string' }, + }, + }, + }, + }, + ], + }) + .on('message', (message) => console.log(message)); + + const finalContent = await runner.finalContent(); + console.log(); + console.log('Final content:', finalContent); +} + +async function getCurrentLocation() { + return 'Boston'; // Simulate lookup +} + +async function getWeather(args: { location: string }) { + const { location } = args; + // … do lookup … + return { temperature, precipitation }; +} + +main(); + +// {role: "user", content: "How's the weather this week?"} +// {role: "assistant", tool_calls: [{type: "function", function: {name: "getCurrentLocation", arguments: "{}"}, id: "123"} +// {role: "tool", name: "getCurrentLocation", content: "Boston", tool_call_id: "123"} +// {role: "assistant", tool_calls: [{type: "function", function: {name: "getWeather", arguments: '{"location": "Boston"}'}, id: "1234"}]} +// {role: "tool", name: "getWeather", content: '{"temperature": "50degF", "preciptation": "high"}', tool_call_id: "1234"} +// {role: "assistant", content: "It's looking cold and rainy - you might want to wear a jacket!"} +// +// Final content: "It's looking cold and rainy - you might want to wear a jacket!" +``` + +Like with `.stream()`, we provide a variety of [helpers and events](helpers.md#events). + +Note that `runFunctions` was previously available as well, but has been deprecated in favor of `runTools`. + +Read more about various examples such as with integrating with [zod](helpers.md#integrate-with-zod), +[next.js](helpers.md#integrate-wtih-next-js), and [proxying a stream to the browser](helpers.md#proxy-streaming-to-a-browser). + +## File uploads + +Request parameters that correspond to file uploads can be passed in many different forms: + +- `File` (or an object with the same structure) +- a `fetch` `Response` (or an object with the same structure) +- an `fs.ReadStream` +- the return value of our `toFile` helper + +```ts +import fs from 'fs'; +import fetch from 'node-fetch'; +import OpenAI, { toFile } from 'openai'; + +const openai = new OpenAI(); + +// If you have access to Node `fs` we recommend using `fs.createReadStream()`: +await openai.files.create({ file: fs.createReadStream('input.jsonl'), purpose: 'fine-tune' }); + +// Or if you have the web `File` API you can pass a `File` instance: +await openai.files.create({ file: new File(['my bytes'], 'input.jsonl'), purpose: 'fine-tune' }); + +// You can also pass a `fetch` `Response`: +await openai.files.create({ file: await fetch('https://somesite/input.jsonl'), purpose: 'fine-tune' }); + +// Finally, if none of the above are convenient, you can use our `toFile` helper: +await openai.files.create({ + file: await toFile(Buffer.from('my bytes'), 'input.jsonl'), + purpose: 'fine-tune', +}); +await openai.files.create({ + file: await toFile(new Uint8Array([0, 1, 2]), 'input.jsonl'), + purpose: 'fine-tune', +}); +``` + +## Handling errors + +When the library is unable to connect to the API, +or if the API returns a non-success status code (i.e., 4xx or 5xx response), +a subclass of `APIError` will be thrown: + + +```ts +async function main() { + const job = await openai.fineTuning.jobs + .create({ model: 'gpt-3.5-turbo', training_file: 'file-abc123' }) + .catch(async (err) => { + if (err instanceof OpenAI.APIError) { + console.log(err.status); // 400 + console.log(err.name); // BadRequestError + console.log(err.headers); // {server: 'nginx', ...} + } else { + throw err; + } + }); +} + +main(); +``` + +Error codes are as followed: + +| Status Code | Error Type | +| ----------- | -------------------------- | +| 400 | `BadRequestError` | +| 401 | `AuthenticationError` | +| 403 | `PermissionDeniedError` | +| 404 | `NotFoundError` | +| 422 | `UnprocessableEntityError` | +| 429 | `RateLimitError` | +| >=500 | `InternalServerError` | +| N/A | `APIConnectionError` | + +### Azure OpenAI + +An example of using this library with Azure OpenAI can be found [here](https://github.com/openai/openai-node/blob/master/examples/azure.ts). + +Please note there are subtle differences in API shape & behavior between the Azure OpenAI API and the OpenAI API, +so using this library with Azure OpenAI may result in incorrect types, which can lead to bugs. + +See [`@azure/openai`](https://www.npmjs.com/package/@azure/openai) for an Azure-specific SDK provided by Microsoft. + +### Retries + +Certain errors will be automatically retried 2 times by default, with a short exponential backoff. +Connection errors (for example, due to a network connectivity problem), 408 Request Timeout, 409 Conflict, +429 Rate Limit, and >=500 Internal errors will all be retried by default. + +You can use the `maxRetries` option to configure or disable this: + + +```js +// Configure the default for all requests: +const openai = new OpenAI({ + maxRetries: 0, // default is 2 +}); + +// Or, configure per-request: +await openai.chat.completions.create({ messages: [{ role: 'user', content: 'How can I get the name of the current day in Node.js?' }], model: 'gpt-3.5-turbo' }, { + maxRetries: 5, +}); +``` + +### Timeouts + +Requests time out after 10 minutes by default. You can configure this with a `timeout` option: + + +```ts +// Configure the default for all requests: +const openai = new OpenAI({ + timeout: 20 * 1000, // 20 seconds (default is 10 minutes) +}); + +// Override per-request: +await openai.chat.completions.create({ messages: [{ role: 'user', content: 'How can I list all files in a directory using Python?' }], model: 'gpt-3.5-turbo' }, { + timeout: 5 * 1000, +}); +``` + +On timeout, an `APIConnectionTimeoutError` is thrown. + +Note that requests which time out will be [retried twice by default](#retries). + +## Auto-pagination + +List methods in the OpenAI API are paginated. +You can use `for await … of` syntax to iterate through items across all pages: + +```ts +async function fetchAllFineTuningJobs(params) { + const allFineTuningJobs = []; + // Automatically fetches more pages as needed. + for await (const fineTuningJob of openai.fineTuning.jobs.list({ limit: 20 })) { + allFineTuningJobs.push(fineTuningJob); + } + return allFineTuningJobs; +} +``` + +Alternatively, you can make request a single page at a time: + +```ts +let page = await openai.fineTuning.jobs.list({ limit: 20 }); +for (const fineTuningJob of page.data) { + console.log(fineTuningJob); +} + +// Convenience methods are provided for manually paginating: +while (page.hasNextPage()) { + page = page.getNextPage(); + // ... +} +``` + +## Advanced Usage + +### Accessing raw Response data (e.g., headers) + +The "raw" `Response` returned by `fetch()` can be accessed through the `.asResponse()` method on the `APIPromise` type that all methods return. + +You can also use the `.withResponse()` method to get the raw `Response` along with the parsed data. + + +```ts +const openai = new OpenAI(); + +const response = await openai.chat.completions + .create({ messages: [{ role: 'user', content: 'Say this is a test' }], model: 'gpt-3.5-turbo' }) + .asResponse(); +console.log(response.headers.get('X-My-Header')); +console.log(response.statusText); // access the underlying Response object + +const { data: chatCompletion, response: raw } = await openai.chat.completions + .create({ messages: [{ role: 'user', content: 'Say this is a test' }], model: 'gpt-3.5-turbo' }) + .withResponse(); +console.log(raw.headers.get('X-My-Header')); +console.log(chatCompletion); +``` + +### Making custom/undocumented requests + +This library is typed for convenient access to the documented API. If you need to access undocumented +endpoints, params, or response properties, the library can still be used. + +#### Undocumented endpoints + +To make requests to undocumented endpoints, you can use `client.get`, `client.post`, and other HTTP verbs. +Options on the client, such as retries, will be respected when making these requests. + +```ts +await client.post('/some/path', { + body: { some_prop: 'foo' }, + query: { some_query_arg: 'bar' }, +}); +``` + +#### Undocumented request params + +To make requests using undocumented parameters, you may use `// @ts-expect-error` on the undocumented +parameter. This library doesn't validate at runtime that the request matches the type, so any extra values you +send will be sent as-is. + +```ts +client.foo.create({ + foo: 'my_param', + bar: 12, + // @ts-expect-error baz is not yet public + baz: 'undocumented option', +}); +``` + +For requests with the `GET` verb, any extra params will be in the query, all other requests will send the +extra param in the body. + +If you want to explicitly send an extra argument, you can do so with the `query`, `body`, and `headers` request +options. + +#### Undocumented response properties + +To access undocumented response properties, you may access the response object with `// @ts-expect-error` on +the response object, or cast the response object to the requisite type. Like the request params, we do not +validate or strip extra properties from the response from the API. + +### Customizing the fetch client + +By default, this library uses `node-fetch` in Node, and expects a global `fetch` function in other environments. + +If you would prefer to use a global, web-standards-compliant `fetch` function even in a Node environment, +(for example, if you are running Node with `--experimental-fetch` or using NextJS which polyfills with `undici`), +add the following import before your first import `from "OpenAI"`: + +```ts +// Tell TypeScript and the package to use the global web fetch instead of node-fetch. +// Note, despite the name, this does not add any polyfills, but expects them to be provided if needed. +import 'openai/shims/web'; +import OpenAI from 'openai'; +``` + +To do the inverse, add `import "openai/shims/node"` (which does import polyfills). +This can also be useful if you are getting the wrong TypeScript types for `Response` ([more details](https://github.com/openai/openai-node/tree/master/src/_shims#readme)). + +### Logging and middleware + +You may also provide a custom `fetch` function when instantiating the client, +which can be used to inspect or alter the `Request` or `Response` before/after each request: + +```ts +import { fetch } from 'undici'; // as one example +import OpenAI from 'openai'; + +const client = new OpenAI({ + fetch: async (url: RequestInfo, init?: RequestInit): Promise => { + console.log('About to make a request', url, init); + const response = await fetch(url, init); + console.log('Got response', response); + return response; + }, +}); +``` + +Note that if given a `DEBUG=true` environment variable, this library will log all requests and responses automatically. +This is intended for debugging purposes only and may change in the future without notice. + +### Configuring an HTTP(S) Agent (e.g., for proxies) + +By default, this library uses a stable agent for all http/https requests to reuse TCP connections, eliminating many TCP & TLS handshakes and shaving around 100ms off most requests. + +If you would like to disable or customize this behavior, for example to use the API behind a proxy, you can pass an `httpAgent` which is used for all requests (be they http or https), for example: + + +```ts +import http from 'http'; +import { HttpsProxyAgent } from 'https-proxy-agent'; + +// Configure the default for all requests: +const openai = new OpenAI({ + httpAgent: new HttpsProxyAgent(process.env.PROXY_URL), +}); + +// Override per-request: +await openai.models.list({ + httpAgent: new http.Agent({ keepAlive: false }), +}); +``` + +## Semantic versioning + +This package generally follows [SemVer](https://semver.org/spec/v2.0.0.html) conventions, though certain backwards-incompatible changes may be released as minor versions: + +1. Changes that only affect static types, without breaking runtime behavior. +2. Changes to library internals which are technically public but not intended or documented for external use. _(Please open a GitHub issue to let us know if you are relying on such internals)_. +3. Changes that we do not expect to impact the vast majority of users in practice. + +We take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience. + +We are keen for your feedback; please open an [issue](https://www.github.com/openai/openai-node/issues) with questions, bugs, or suggestions. + +## Requirements + +TypeScript >= 4.5 is supported. + +The following runtimes are supported: + +- Node.js 18 LTS or later ([non-EOL](https://endoflife.date/nodejs)) versions. +- Deno v1.28.0 or higher, using `import OpenAI from "npm:openai"`. +- Bun 1.0 or later. +- Cloudflare Workers. +- Vercel Edge Runtime. +- Jest 28 or greater with the `"node"` environment (`"jsdom"` is not supported at this time). +- Nitro v2.6 or greater. + +Note that React Native is not supported at this time. + +If you are interested in other runtime environments, please open or upvote an issue on GitHub. diff --git a/backend/node_modules/openai/_shims/MultipartBody.d.ts b/backend/node_modules/openai/_shims/MultipartBody.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d9118c834aaacf4aeddd02148d26e7bd1bef1dcc --- /dev/null +++ b/backend/node_modules/openai/_shims/MultipartBody.d.ts @@ -0,0 +1,9 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ +export declare class MultipartBody { + body: any; + constructor(body: any); + get [Symbol.toStringTag](): string; +} +//# sourceMappingURL=MultipartBody.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/_shims/MultipartBody.d.ts.map b/backend/node_modules/openai/_shims/MultipartBody.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..fc6a8b6c493141ac5121de21df87d1c8afddd76d --- /dev/null +++ b/backend/node_modules/openai/_shims/MultipartBody.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"MultipartBody.d.ts","sourceRoot":"","sources":["../src/_shims/MultipartBody.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,qBAAa,aAAa;IACL,IAAI,EAAE,GAAG;gBAAT,IAAI,EAAE,GAAG;IAC5B,IAAI,CAAC,MAAM,CAAC,WAAW,CAAC,IAAI,MAAM,CAEjC;CACF"} \ No newline at end of file diff --git a/backend/node_modules/openai/_shims/MultipartBody.js b/backend/node_modules/openai/_shims/MultipartBody.js new file mode 100644 index 0000000000000000000000000000000000000000..67efb4657c52696a62d15dfc63ab2550338e80cc --- /dev/null +++ b/backend/node_modules/openai/_shims/MultipartBody.js @@ -0,0 +1,16 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MultipartBody = void 0; +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ +class MultipartBody { + constructor(body) { + this.body = body; + } + get [Symbol.toStringTag]() { + return 'MultipartBody'; + } +} +exports.MultipartBody = MultipartBody; +//# sourceMappingURL=MultipartBody.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/_shims/MultipartBody.js.map b/backend/node_modules/openai/_shims/MultipartBody.js.map new file mode 100644 index 0000000000000000000000000000000000000000..adad49f6ec62c4055bd3d5a9ba1c10f5c430ac3e --- /dev/null +++ b/backend/node_modules/openai/_shims/MultipartBody.js.map @@ -0,0 +1 @@ +{"version":3,"file":"MultipartBody.js","sourceRoot":"","sources":["../src/_shims/MultipartBody.ts"],"names":[],"mappings":";;;AAAA;;GAEG;AACH,MAAa,aAAa;IACxB,YAAmB,IAAS;QAAT,SAAI,GAAJ,IAAI,CAAK;IAAG,CAAC;IAChC,IAAI,CAAC,MAAM,CAAC,WAAW,CAAC;QACtB,OAAO,eAAe,CAAC;IACzB,CAAC;CACF;AALD,sCAKC"} \ No newline at end of file diff --git a/backend/node_modules/openai/_shims/MultipartBody.mjs b/backend/node_modules/openai/_shims/MultipartBody.mjs new file mode 100644 index 0000000000000000000000000000000000000000..68a828077ca9282ffb1781ffb3addc784851191a --- /dev/null +++ b/backend/node_modules/openai/_shims/MultipartBody.mjs @@ -0,0 +1,12 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ +export class MultipartBody { + constructor(body) { + this.body = body; + } + get [Symbol.toStringTag]() { + return 'MultipartBody'; + } +} +//# sourceMappingURL=MultipartBody.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/_shims/MultipartBody.mjs.map b/backend/node_modules/openai/_shims/MultipartBody.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..6aca41300ca08f134f4ec9001bee3eeea1a9f83a --- /dev/null +++ b/backend/node_modules/openai/_shims/MultipartBody.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"MultipartBody.mjs","sourceRoot":"","sources":["../src/_shims/MultipartBody.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,OAAO,aAAa;IACxB,YAAmB,IAAS;QAAT,SAAI,GAAJ,IAAI,CAAK;IAAG,CAAC;IAChC,IAAI,CAAC,MAAM,CAAC,WAAW,CAAC;QACtB,OAAO,eAAe,CAAC;IACzB,CAAC;CACF"} \ No newline at end of file diff --git a/backend/node_modules/openai/_shims/README.md b/backend/node_modules/openai/_shims/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b3a349b41b588ba2c9b06d0751a9e8a07375d513 --- /dev/null +++ b/backend/node_modules/openai/_shims/README.md @@ -0,0 +1,46 @@ +# 👋 Wondering what everything in here does? + +`openai` supports a wide variety of runtime environments like Node.js, Deno, Bun, browsers, and various +edge runtimes, as well as both CommonJS (CJS) and EcmaScript Modules (ESM). + +To do this, `openai` provides shims for either using `node-fetch` when in Node (because `fetch` is still experimental there) or the global `fetch` API built into the environment when not in Node. + +It uses [conditional exports](https://nodejs.org/api/packages.html#conditional-exports) to +automatically select the correct shims for each environment. However, conditional exports are a fairly new +feature and not supported everywhere. For instance, the TypeScript `"moduleResolution": "node"` + +setting doesn't consult the `exports` map, compared to `"moduleResolution": "nodeNext"`, which does. +Unfortunately that's still the default setting, and it can result in errors like +getting the wrong raw `Response` type from `.asResponse()`, for example. + +The user can work around these issues by manually importing one of: + +- `import 'openai/shims/node'` +- `import 'openai/shims/web'` + +All of the code here in `_shims` handles selecting the automatic default shims or manual overrides. + +### How it works - Runtime + +Runtime shims get installed by calling `setShims` exported by `openai/_shims/registry`. + +Manually importing `openai/shims/node` or `openai/shims/web`, calls `setShims` with the respective runtime shims. + +All client code imports shims from `openai/_shims/index`, which: + +- checks if shims have been set manually +- if not, calls `setShims` with the shims from `openai/_shims/auto/runtime` +- re-exports the installed shims from `openai/_shims/registry`. + +`openai/_shims/auto/runtime` exports web runtime shims. +If the `node` export condition is set, the export map replaces it with `openai/_shims/auto/runtime-node`. + +### How it works - Type time + +All client code imports shim types from `openai/_shims/index`, which selects the manual types from `openai/_shims/manual-types` if they have been declared, otherwise it exports the auto types from `openai/_shims/auto/types`. + +`openai/_shims/manual-types` exports an empty namespace. +Manually importing `openai/shims/node` or `openai/shims/web` merges declarations into this empty namespace, so they get picked up by `openai/_shims/index`. + +`openai/_shims/auto/types` exports web type definitions. +If the `node` export condition is set, the export map replaces it with `openai/_shims/auto/types-node`, though TS only picks this up if `"moduleResolution": "nodenext"` or `"moduleResolution": "bundler"`. diff --git a/backend/node_modules/openai/_shims/auto/runtime-bun.d.ts b/backend/node_modules/openai/_shims/auto/runtime-bun.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1baecb82d688a282be99d75b99a7b1441a1a4208 --- /dev/null +++ b/backend/node_modules/openai/_shims/auto/runtime-bun.d.ts @@ -0,0 +1,5 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ +export * from "../bun-runtime.js"; +//# sourceMappingURL=runtime-bun.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/_shims/auto/runtime-bun.d.ts.map b/backend/node_modules/openai/_shims/auto/runtime-bun.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..8d57eee522f4a5c067b20cd97d433058996a3095 --- /dev/null +++ b/backend/node_modules/openai/_shims/auto/runtime-bun.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"runtime-bun.d.ts","sourceRoot":"","sources":["../../src/_shims/auto/runtime-bun.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,cAAc,gBAAgB,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/openai/_shims/auto/runtime-bun.js b/backend/node_modules/openai/_shims/auto/runtime-bun.js new file mode 100644 index 0000000000000000000000000000000000000000..312c535a81c8a614f8e614fd7065919c0f821247 --- /dev/null +++ b/backend/node_modules/openai/_shims/auto/runtime-bun.js @@ -0,0 +1,21 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ +__exportStar(require("../bun-runtime.js"), exports); +//# sourceMappingURL=runtime-bun.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/_shims/auto/runtime-bun.js.map b/backend/node_modules/openai/_shims/auto/runtime-bun.js.map new file mode 100644 index 0000000000000000000000000000000000000000..c78786e46d377c5d56ef6db1e0378ac192780397 --- /dev/null +++ b/backend/node_modules/openai/_shims/auto/runtime-bun.js.map @@ -0,0 +1 @@ +{"version":3,"file":"runtime-bun.js","sourceRoot":"","sources":["../../src/_shims/auto/runtime-bun.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA;;GAEG;AACH,oDAA+B"} \ No newline at end of file diff --git a/backend/node_modules/openai/_shims/auto/runtime-bun.mjs b/backend/node_modules/openai/_shims/auto/runtime-bun.mjs new file mode 100644 index 0000000000000000000000000000000000000000..3197faec3f2ec5957ce1793358d515496a33f3d9 --- /dev/null +++ b/backend/node_modules/openai/_shims/auto/runtime-bun.mjs @@ -0,0 +1,2 @@ +export * from "../bun-runtime.mjs"; +//# sourceMappingURL=runtime-bun.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/_shims/auto/runtime-bun.mjs.map b/backend/node_modules/openai/_shims/auto/runtime-bun.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..32011c56c5907d853a925b29f8f883c9eb4dd58c --- /dev/null +++ b/backend/node_modules/openai/_shims/auto/runtime-bun.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"runtime-bun.mjs","sourceRoot":"","sources":["../../src/_shims/auto/runtime-bun.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/backend/node_modules/openai/_shims/auto/runtime-node.d.ts b/backend/node_modules/openai/_shims/auto/runtime-node.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9db3401cac38ef2f2837bb639a3bd7da77c8fb73 --- /dev/null +++ b/backend/node_modules/openai/_shims/auto/runtime-node.d.ts @@ -0,0 +1,5 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ +export * from "../node-runtime.js"; +//# sourceMappingURL=runtime-node.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/_shims/auto/runtime-node.d.ts.map b/backend/node_modules/openai/_shims/auto/runtime-node.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..63a03d62cbdf8d212aa6a8337913330f608275ed --- /dev/null +++ b/backend/node_modules/openai/_shims/auto/runtime-node.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"runtime-node.d.ts","sourceRoot":"","sources":["../../src/_shims/auto/runtime-node.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,cAAc,iBAAiB,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/openai/_shims/auto/runtime-node.js b/backend/node_modules/openai/_shims/auto/runtime-node.js new file mode 100644 index 0000000000000000000000000000000000000000..318ae7c1f6758aae8d3a0f61ed78e6d2b2a13d70 --- /dev/null +++ b/backend/node_modules/openai/_shims/auto/runtime-node.js @@ -0,0 +1,21 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ +__exportStar(require("../node-runtime.js"), exports); +//# sourceMappingURL=runtime-node.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/_shims/auto/runtime-node.js.map b/backend/node_modules/openai/_shims/auto/runtime-node.js.map new file mode 100644 index 0000000000000000000000000000000000000000..4d43fab0a7ed9aea28e40cde0fb438cc8ab4cc23 --- /dev/null +++ b/backend/node_modules/openai/_shims/auto/runtime-node.js.map @@ -0,0 +1 @@ +{"version":3,"file":"runtime-node.js","sourceRoot":"","sources":["../../src/_shims/auto/runtime-node.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA;;GAEG;AACH,qDAAgC"} \ No newline at end of file diff --git a/backend/node_modules/openai/_shims/auto/runtime-node.mjs b/backend/node_modules/openai/_shims/auto/runtime-node.mjs new file mode 100644 index 0000000000000000000000000000000000000000..f846bd307b0724bd14a75223ac513e8f6f7644f8 --- /dev/null +++ b/backend/node_modules/openai/_shims/auto/runtime-node.mjs @@ -0,0 +1,2 @@ +export * from "../node-runtime.mjs"; +//# sourceMappingURL=runtime-node.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/_shims/auto/runtime-node.mjs.map b/backend/node_modules/openai/_shims/auto/runtime-node.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..aa25d93b4fba39ebee2671bd61926aad00ac2ef1 --- /dev/null +++ b/backend/node_modules/openai/_shims/auto/runtime-node.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"runtime-node.mjs","sourceRoot":"","sources":["../../src/_shims/auto/runtime-node.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/backend/node_modules/openai/_shims/auto/runtime.d.ts b/backend/node_modules/openai/_shims/auto/runtime.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ad73696f1f76be2e752fdd775227cdc5fb2ed2d7 --- /dev/null +++ b/backend/node_modules/openai/_shims/auto/runtime.d.ts @@ -0,0 +1,5 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ +export * from "../web-runtime.js"; +//# sourceMappingURL=runtime.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/_shims/auto/runtime.d.ts.map b/backend/node_modules/openai/_shims/auto/runtime.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..256985a44bfc685da5fd982727817964ab101072 --- /dev/null +++ b/backend/node_modules/openai/_shims/auto/runtime.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"runtime.d.ts","sourceRoot":"","sources":["../../src/_shims/auto/runtime.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,cAAc,gBAAgB,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/openai/_shims/auto/runtime.js b/backend/node_modules/openai/_shims/auto/runtime.js new file mode 100644 index 0000000000000000000000000000000000000000..25593917b487337852812c4248ec199b6229515f --- /dev/null +++ b/backend/node_modules/openai/_shims/auto/runtime.js @@ -0,0 +1,21 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ +__exportStar(require("../web-runtime.js"), exports); +//# sourceMappingURL=runtime.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/_shims/auto/runtime.js.map b/backend/node_modules/openai/_shims/auto/runtime.js.map new file mode 100644 index 0000000000000000000000000000000000000000..3cbe401a88807c426b94f3b583cf347259e26805 --- /dev/null +++ b/backend/node_modules/openai/_shims/auto/runtime.js.map @@ -0,0 +1 @@ +{"version":3,"file":"runtime.js","sourceRoot":"","sources":["../../src/_shims/auto/runtime.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA;;GAEG;AACH,oDAA+B"} \ No newline at end of file diff --git a/backend/node_modules/openai/_shims/auto/runtime.mjs b/backend/node_modules/openai/_shims/auto/runtime.mjs new file mode 100644 index 0000000000000000000000000000000000000000..c16bf9eb438aa8378b8daaaa0e783e69b328e34e --- /dev/null +++ b/backend/node_modules/openai/_shims/auto/runtime.mjs @@ -0,0 +1,2 @@ +export * from "../web-runtime.mjs"; +//# sourceMappingURL=runtime.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/_shims/auto/runtime.mjs.map b/backend/node_modules/openai/_shims/auto/runtime.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..5a61fc694d343863e1add490d3e4c51551488276 --- /dev/null +++ b/backend/node_modules/openai/_shims/auto/runtime.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"runtime.mjs","sourceRoot":"","sources":["../../src/_shims/auto/runtime.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/backend/node_modules/openai/_shims/auto/types-node.d.ts b/backend/node_modules/openai/_shims/auto/types-node.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..66e5296b5ab1058233d5244592ccc2e5c55bfbc1 --- /dev/null +++ b/backend/node_modules/openai/_shims/auto/types-node.d.ts @@ -0,0 +1,5 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ +export * from "../node-types.js"; +//# sourceMappingURL=types-node.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/_shims/auto/types-node.d.ts.map b/backend/node_modules/openai/_shims/auto/types-node.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..bc0e15d77dc37703b45c4a4604baf18792d3b964 --- /dev/null +++ b/backend/node_modules/openai/_shims/auto/types-node.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types-node.d.ts","sourceRoot":"","sources":["../../src/_shims/auto/types-node.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,cAAc,eAAe,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/openai/_shims/auto/types-node.js b/backend/node_modules/openai/_shims/auto/types-node.js new file mode 100644 index 0000000000000000000000000000000000000000..b7577b3769b4658c9f94b9b4f32da54555663f1f --- /dev/null +++ b/backend/node_modules/openai/_shims/auto/types-node.js @@ -0,0 +1,21 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ +__exportStar(require("../node-types.js"), exports); +//# sourceMappingURL=types-node.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/_shims/auto/types-node.js.map b/backend/node_modules/openai/_shims/auto/types-node.js.map new file mode 100644 index 0000000000000000000000000000000000000000..553fe3e37be31a8b8c90bf86f0ff74a200773ac8 --- /dev/null +++ b/backend/node_modules/openai/_shims/auto/types-node.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types-node.js","sourceRoot":"","sources":["../../src/_shims/auto/types-node.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA;;GAEG;AACH,mDAA8B"} \ No newline at end of file diff --git a/backend/node_modules/openai/_shims/auto/types-node.mjs b/backend/node_modules/openai/_shims/auto/types-node.mjs new file mode 100644 index 0000000000000000000000000000000000000000..10c37f2f3665d1dffe1d25da6c255091e178095f --- /dev/null +++ b/backend/node_modules/openai/_shims/auto/types-node.mjs @@ -0,0 +1,2 @@ +export * from "../node-types.mjs"; +//# sourceMappingURL=types-node.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/_shims/auto/types-node.mjs.map b/backend/node_modules/openai/_shims/auto/types-node.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..27e85a2c64f6d3121cf11ba5e6bf4c37db868656 --- /dev/null +++ b/backend/node_modules/openai/_shims/auto/types-node.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"types-node.mjs","sourceRoot":"","sources":["../../src/_shims/auto/types-node.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/backend/node_modules/openai/_shims/auto/types.d.ts b/backend/node_modules/openai/_shims/auto/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d7755070baf84504ad1f106e1516f3a62ada11fd --- /dev/null +++ b/backend/node_modules/openai/_shims/auto/types.d.ts @@ -0,0 +1,101 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ +export type Agent = any; + +// @ts-ignore +declare const _fetch: unknown extends typeof fetch ? never : typeof fetch; +export { _fetch as fetch }; + +// @ts-ignore +type _Request = unknown extends Request ? never : Request; +export { _Request as Request }; + +// @ts-ignore +type _RequestInfo = unknown extends RequestInfo ? never : RequestInfo; +export { type _RequestInfo as RequestInfo }; + +// @ts-ignore +type _RequestInit = unknown extends RequestInit ? never : RequestInit; +export { type _RequestInit as RequestInit }; + +// @ts-ignore +type _Response = unknown extends Response ? never : Response; +export { _Response as Response }; + +// @ts-ignore +type _ResponseInit = unknown extends ResponseInit ? never : ResponseInit; +export { type _ResponseInit as ResponseInit }; + +// @ts-ignore +type _ResponseType = unknown extends ResponseType ? never : ResponseType; +export { type _ResponseType as ResponseType }; + +// @ts-ignore +type _BodyInit = unknown extends BodyInit ? never : BodyInit; +export { type _BodyInit as BodyInit }; + +// @ts-ignore +type _Headers = unknown extends Headers ? never : Headers; +export { _Headers as Headers }; + +// @ts-ignore +type _HeadersInit = unknown extends HeadersInit ? never : HeadersInit; +export { type _HeadersInit as HeadersInit }; + +type EndingType = 'native' | 'transparent'; + +export interface BlobPropertyBag { + endings?: EndingType; + type?: string; +} + +export interface FilePropertyBag extends BlobPropertyBag { + lastModified?: number; +} + +export type FileFromPathOptions = Omit; + +// @ts-ignore +type _FormData = unknown extends FormData ? never : FormData; +// @ts-ignore +declare const _FormData: unknown extends typeof FormData ? never : typeof FormData; +export { _FormData as FormData }; + +// @ts-ignore +type _File = unknown extends File ? never : File; +// @ts-ignore +declare const _File: unknown extends typeof File ? never : typeof File; +export { _File as File }; + +// @ts-ignore +type _Blob = unknown extends Blob ? never : Blob; +// @ts-ignore +declare const _Blob: unknown extends typeof Blob ? never : typeof Blob; +export { _Blob as Blob }; + +export declare class Readable { + readable: boolean; + readonly readableEnded: boolean; + readonly readableFlowing: boolean | null; + readonly readableHighWaterMark: number; + readonly readableLength: number; + readonly readableObjectMode: boolean; + destroyed: boolean; + read(size?: number): any; + pause(): this; + resume(): this; + isPaused(): boolean; + destroy(error?: Error): this; + [Symbol.asyncIterator](): AsyncIterableIterator; +} + +export declare class FsReadStream extends Readable { + path: {}; // node type is string | Buffer +} + +// @ts-ignore +type _ReadableStream = unknown extends ReadableStream ? never : ReadableStream; +// @ts-ignore +declare const _ReadableStream: unknown extends typeof ReadableStream ? never : typeof ReadableStream; +export { _ReadableStream as ReadableStream }; diff --git a/backend/node_modules/openai/_shims/auto/types.js b/backend/node_modules/openai/_shims/auto/types.js new file mode 100644 index 0000000000000000000000000000000000000000..ddbdb799c8d3a5a22f9400270cb1b71b570c202a --- /dev/null +++ b/backend/node_modules/openai/_shims/auto/types.js @@ -0,0 +1,3 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ diff --git a/backend/node_modules/openai/_shims/auto/types.mjs b/backend/node_modules/openai/_shims/auto/types.mjs new file mode 100644 index 0000000000000000000000000000000000000000..ddbdb799c8d3a5a22f9400270cb1b71b570c202a --- /dev/null +++ b/backend/node_modules/openai/_shims/auto/types.mjs @@ -0,0 +1,3 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ diff --git a/backend/node_modules/openai/_shims/bun-runtime.d.ts b/backend/node_modules/openai/_shims/bun-runtime.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7228102128fac743b426858bb2a5cea68effed8c --- /dev/null +++ b/backend/node_modules/openai/_shims/bun-runtime.d.ts @@ -0,0 +1,6 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ +import { type Shims } from "./registry.js"; +export declare function getRuntime(): Shims; +//# sourceMappingURL=bun-runtime.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/_shims/bun-runtime.d.ts.map b/backend/node_modules/openai/_shims/bun-runtime.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..9de8c6579a8d7d24927d5218fff8c0a7704a0933 --- /dev/null +++ b/backend/node_modules/openai/_shims/bun-runtime.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"bun-runtime.d.ts","sourceRoot":"","sources":["../src/_shims/bun-runtime.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,OAAO,EAAE,KAAK,KAAK,EAAE,MAAM,YAAY,CAAC;AAIxC,wBAAgB,UAAU,IAAI,KAAK,CAMlC"} \ No newline at end of file diff --git a/backend/node_modules/openai/_shims/bun-runtime.js b/backend/node_modules/openai/_shims/bun-runtime.js new file mode 100644 index 0000000000000000000000000000000000000000..e098e16693de4c4ef913d8b3a4c8dc359812d18a --- /dev/null +++ b/backend/node_modules/openai/_shims/bun-runtime.js @@ -0,0 +1,14 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getRuntime = void 0; +const web_runtime_1 = require("./web-runtime.js"); +const node_fs_1 = require("node:fs"); +function getRuntime() { + const runtime = (0, web_runtime_1.getRuntime)(); + function isFsReadStream(value) { + return value instanceof node_fs_1.ReadStream; + } + return { ...runtime, isFsReadStream }; +} +exports.getRuntime = getRuntime; +//# sourceMappingURL=bun-runtime.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/_shims/bun-runtime.js.map b/backend/node_modules/openai/_shims/bun-runtime.js.map new file mode 100644 index 0000000000000000000000000000000000000000..fdea46205cecf7d48f30799df96dbdec409410cf --- /dev/null +++ b/backend/node_modules/openai/_shims/bun-runtime.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bun-runtime.js","sourceRoot":"","sources":["../src/_shims/bun-runtime.ts"],"names":[],"mappings":";;;AAIA,kDAA4D;AAC5D,qCAAqD;AAErD,SAAgB,UAAU;IACxB,MAAM,OAAO,GAAG,IAAA,wBAAa,GAAE,CAAC;IAChC,SAAS,cAAc,CAAC,KAAU;QAChC,OAAO,KAAK,YAAY,oBAAY,CAAC;IACvC,CAAC;IACD,OAAO,EAAE,GAAG,OAAO,EAAE,cAAc,EAAE,CAAC;AACxC,CAAC;AAND,gCAMC"} \ No newline at end of file diff --git a/backend/node_modules/openai/_shims/bun-runtime.mjs b/backend/node_modules/openai/_shims/bun-runtime.mjs new file mode 100644 index 0000000000000000000000000000000000000000..8f52de8b4136c200702c5be0b32a738c62bdca22 --- /dev/null +++ b/backend/node_modules/openai/_shims/bun-runtime.mjs @@ -0,0 +1,10 @@ +import { getRuntime as getWebRuntime } from "./web-runtime.mjs"; +import { ReadStream as FsReadStream } from 'node:fs'; +export function getRuntime() { + const runtime = getWebRuntime(); + function isFsReadStream(value) { + return value instanceof FsReadStream; + } + return { ...runtime, isFsReadStream }; +} +//# sourceMappingURL=bun-runtime.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/_shims/bun-runtime.mjs.map b/backend/node_modules/openai/_shims/bun-runtime.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..4a1b11ddc561b69e78964cd08d922a01190c580f --- /dev/null +++ b/backend/node_modules/openai/_shims/bun-runtime.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"bun-runtime.mjs","sourceRoot":"","sources":["../src/_shims/bun-runtime.ts"],"names":[],"mappings":"OAIO,EAAE,UAAU,IAAI,aAAa,EAAE;OAC/B,EAAE,UAAU,IAAI,YAAY,EAAE,MAAM,SAAS;AAEpD,MAAM,UAAU,UAAU;IACxB,MAAM,OAAO,GAAG,aAAa,EAAE,CAAC;IAChC,SAAS,cAAc,CAAC,KAAU;QAChC,OAAO,KAAK,YAAY,YAAY,CAAC;IACvC,CAAC;IACD,OAAO,EAAE,GAAG,OAAO,EAAE,cAAc,EAAE,CAAC;AACxC,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/openai/_shims/index.d.ts b/backend/node_modules/openai/_shims/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7ff9513784c8e65b265e3e27f4339ae124842f91 --- /dev/null +++ b/backend/node_modules/openai/_shims/index.d.ts @@ -0,0 +1,81 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ +import { manual } from "./manual-types.js"; +import * as auto from 'openai/_shims/auto/types'; +import { type RequestOptions } from "../core.js"; + +type SelectType = unknown extends Manual ? Auto : Manual; + +export const kind: string; + +// @ts-ignore +export type Agent = SelectType; + +// @ts-ignore +export const fetch: SelectType; + +// @ts-ignore +export type Request = SelectType; +// @ts-ignore +export type RequestInfo = SelectType; +// @ts-ignore +export type RequestInit = SelectType; + +// @ts-ignore +export type Response = SelectType; +// @ts-ignore +export type ResponseInit = SelectType; +// @ts-ignore +export type ResponseType = SelectType; +// @ts-ignore +export type BodyInit = SelectType; +// @ts-ignore +export type Headers = SelectType; +// @ts-ignore +export const Headers: SelectType; +// @ts-ignore +export type HeadersInit = SelectType; + +// @ts-ignore +export type BlobPropertyBag = SelectType; +// @ts-ignore +export type FilePropertyBag = SelectType; +// @ts-ignore +export type FileFromPathOptions = SelectType; +// @ts-ignore +export type FormData = SelectType; +// @ts-ignore +export const FormData: SelectType; +// @ts-ignore +export type File = SelectType; +// @ts-ignore +export const File: SelectType; +// @ts-ignore +export type Blob = SelectType; +// @ts-ignore +export const Blob: SelectType; + +// @ts-ignore +export type Readable = SelectType; +// @ts-ignore +export type FsReadStream = SelectType; +// @ts-ignore +export type ReadableStream = SelectType; +// @ts-ignore +export const ReadableStream: SelectType; + +export function getMultipartRequestOptions>( + form: FormData, + opts: RequestOptions, +): Promise>; + +export function getDefaultAgent(url: string): any; + +// @ts-ignore +export type FileFromPathOptions = SelectType; + +export function fileFromPath(path: string, options?: FileFromPathOptions): Promise; +export function fileFromPath(path: string, filename?: string, options?: FileFromPathOptions): Promise; + +export function isFsReadStream(value: any): value is FsReadStream; diff --git a/backend/node_modules/openai/_shims/index.js b/backend/node_modules/openai/_shims/index.js new file mode 100644 index 0000000000000000000000000000000000000000..b5fc8229e90852a1b61e9442bf87cc2fe3b6ddfb --- /dev/null +++ b/backend/node_modules/openai/_shims/index.js @@ -0,0 +1,13 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ +const shims = require('./registry'); +const auto = require('openai/_shims/auto/runtime'); +if (!shims.kind) shims.setShims(auto.getRuntime(), { auto: true }); +for (const property of Object.keys(shims)) { + Object.defineProperty(exports, property, { + get() { + return shims[property]; + }, + }); +} diff --git a/backend/node_modules/openai/_shims/index.mjs b/backend/node_modules/openai/_shims/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..81665e610efbbb48f459c12418edc18c7c74b095 --- /dev/null +++ b/backend/node_modules/openai/_shims/index.mjs @@ -0,0 +1,7 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ +import * as shims from './registry.mjs'; +import * as auto from 'openai/_shims/auto/runtime'; +if (!shims.kind) shims.setShims(auto.getRuntime(), { auto: true }); +export * from './registry.mjs'; diff --git a/backend/node_modules/openai/_shims/manual-types.d.ts b/backend/node_modules/openai/_shims/manual-types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3d00fc243378204f80beef898da42c5eaf1f5cf7 --- /dev/null +++ b/backend/node_modules/openai/_shims/manual-types.d.ts @@ -0,0 +1,12 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ +/** + * Types will get added to this namespace when you import one of the following: + * + * import 'openai/shims/node' + * import 'openai/shims/web' + * + * Importing more than one will cause type and runtime errors. + */ +export namespace manual {} diff --git a/backend/node_modules/openai/_shims/manual-types.js b/backend/node_modules/openai/_shims/manual-types.js new file mode 100644 index 0000000000000000000000000000000000000000..ddbdb799c8d3a5a22f9400270cb1b71b570c202a --- /dev/null +++ b/backend/node_modules/openai/_shims/manual-types.js @@ -0,0 +1,3 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ diff --git a/backend/node_modules/openai/_shims/manual-types.mjs b/backend/node_modules/openai/_shims/manual-types.mjs new file mode 100644 index 0000000000000000000000000000000000000000..ddbdb799c8d3a5a22f9400270cb1b71b570c202a --- /dev/null +++ b/backend/node_modules/openai/_shims/manual-types.mjs @@ -0,0 +1,3 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ diff --git a/backend/node_modules/openai/_shims/node-runtime.d.ts b/backend/node_modules/openai/_shims/node-runtime.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0c2b042d816470cf457feafe6239e702828e6eb4 --- /dev/null +++ b/backend/node_modules/openai/_shims/node-runtime.d.ts @@ -0,0 +1,3 @@ +import { type Shims } from "./registry.js"; +export declare function getRuntime(): Shims; +//# sourceMappingURL=node-runtime.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/_shims/node-runtime.d.ts.map b/backend/node_modules/openai/_shims/node-runtime.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..84184553320817670251025dab7211a4cf88426a --- /dev/null +++ b/backend/node_modules/openai/_shims/node-runtime.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"node-runtime.d.ts","sourceRoot":"","sources":["../src/_shims/node-runtime.ts"],"names":[],"mappings":"AAcA,OAAO,EAAE,KAAK,KAAK,EAAE,MAAM,YAAY,CAAC;AA+CxC,wBAAgB,UAAU,IAAI,KAAK,CAqBlC"} \ No newline at end of file diff --git a/backend/node_modules/openai/_shims/node-runtime.js b/backend/node_modules/openai/_shims/node-runtime.js new file mode 100644 index 0000000000000000000000000000000000000000..9bd175b6458acae94349b11d8a5304ead858ae8d --- /dev/null +++ b/backend/node_modules/openai/_shims/node-runtime.js @@ -0,0 +1,90 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getRuntime = void 0; +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ +const nf = __importStar(require("node-fetch")); +const fd = __importStar(require("formdata-node")); +const agentkeepalive_1 = __importDefault(require("agentkeepalive")); +const abort_controller_1 = require("abort-controller"); +const node_fs_1 = require("node:fs"); +const form_data_encoder_1 = require("form-data-encoder"); +const node_stream_1 = require("node:stream"); +const MultipartBody_1 = require("./MultipartBody.js"); +// @ts-ignore (this package does not have proper export maps for this export) +const ponyfill_es2018_js_1 = require("web-streams-polyfill/dist/ponyfill.es2018.js"); +let fileFromPathWarned = false; +async function fileFromPath(path, ...args) { + // this import fails in environments that don't handle export maps correctly, like old versions of Jest + const { fileFromPath: _fileFromPath } = await Promise.resolve().then(() => __importStar(require('formdata-node/file-from-path'))); + if (!fileFromPathWarned) { + console.warn(`fileFromPath is deprecated; use fs.createReadStream(${JSON.stringify(path)}) instead`); + fileFromPathWarned = true; + } + // @ts-ignore + return await _fileFromPath(path, ...args); +} +const defaultHttpAgent = new agentkeepalive_1.default({ keepAlive: true, timeout: 5 * 60 * 1000 }); +const defaultHttpsAgent = new agentkeepalive_1.default.HttpsAgent({ keepAlive: true, timeout: 5 * 60 * 1000 }); +async function getMultipartRequestOptions(form, opts) { + const encoder = new form_data_encoder_1.FormDataEncoder(form); + const readable = node_stream_1.Readable.from(encoder); + const body = new MultipartBody_1.MultipartBody(readable); + const headers = { + ...opts.headers, + ...encoder.headers, + 'Content-Length': encoder.contentLength, + }; + return { ...opts, body: body, headers }; +} +function getRuntime() { + // Polyfill global object if needed. + if (typeof AbortController === 'undefined') { + // @ts-expect-error (the types are subtly different, but compatible in practice) + globalThis.AbortController = abort_controller_1.AbortController; + } + return { + kind: 'node', + fetch: nf.default, + Request: nf.Request, + Response: nf.Response, + Headers: nf.Headers, + FormData: fd.FormData, + Blob: fd.Blob, + File: fd.File, + ReadableStream: ponyfill_es2018_js_1.ReadableStream, + getMultipartRequestOptions, + getDefaultAgent: (url) => (url.startsWith('https') ? defaultHttpsAgent : defaultHttpAgent), + fileFromPath, + isFsReadStream: (value) => value instanceof node_fs_1.ReadStream, + }; +} +exports.getRuntime = getRuntime; +//# sourceMappingURL=node-runtime.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/_shims/node-runtime.js.map b/backend/node_modules/openai/_shims/node-runtime.js.map new file mode 100644 index 0000000000000000000000000000000000000000..d66bc7e27875efdb46a9648c9361aaef69c4f0ba --- /dev/null +++ b/backend/node_modules/openai/_shims/node-runtime.js.map @@ -0,0 +1 @@ +{"version":3,"file":"node-runtime.js","sourceRoot":"","sources":["../src/_shims/node-runtime.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;GAEG;AACH,+CAAiC;AACjC,kDAAoC;AAEpC,oEAA4C;AAC5C,uDAA8E;AAC9E,qCAAqD;AAErD,yDAAoD;AACpD,6CAAuC;AAEvC,sDAAgD;AAGhD,6EAA6E;AAC7E,qFAA8E;AAI9E,IAAI,kBAAkB,GAAG,KAAK,CAAC;AAS/B,KAAK,UAAU,YAAY,CAAC,IAAY,EAAE,GAAG,IAAW;IACtD,uGAAuG;IACvG,MAAM,EAAE,YAAY,EAAE,aAAa,EAAE,GAAG,w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E,CAAC,OAAO;QACjB,OAAO,EAAE,EAAE,CAAC,OAAO;QACnB,QAAQ,EAAE,EAAE,CAAC,QAAQ;QACrB,OAAO,EAAE,EAAE,CAAC,OAAO;QACnB,QAAQ,EAAE,EAAE,CAAC,QAAQ;QACrB,IAAI,EAAE,EAAE,CAAC,IAAI;QACb,IAAI,EAAE,EAAE,CAAC,IAAI;QACb,cAAc,EAAd,mCAAc;QACd,0BAA0B;QAC1B,eAAe,EAAE,CAAC,GAAW,EAAS,EAAE,CAAC,CAAC,GAAG,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,iBAAiB,CAAC,CAAC,CAAC,gBAAgB,CAAC;QACzG,YAAY;QACZ,cAAc,EAAE,CAAC,KAAU,EAAyB,EAAE,CAAC,KAAK,YAAY,oBAAY;KACrF,CAAC;AACJ,CAAC;AArBD,gCAqBC"} \ No newline at end of file diff --git a/backend/node_modules/openai/_shims/node-runtime.mjs b/backend/node_modules/openai/_shims/node-runtime.mjs new file mode 100644 index 0000000000000000000000000000000000000000..e6635d29c80552f16e5e2e6a874c134253d83f65 --- /dev/null +++ b/backend/node_modules/openai/_shims/node-runtime.mjs @@ -0,0 +1,56 @@ +import * as nf from 'node-fetch'; +import * as fd from 'formdata-node'; +import KeepAliveAgent from 'agentkeepalive'; +import { AbortController as AbortControllerPolyfill } from 'abort-controller'; +import { ReadStream as FsReadStream } from 'node:fs'; +import { FormDataEncoder } from 'form-data-encoder'; +import { Readable } from 'node:stream'; +import { MultipartBody } from "./MultipartBody.mjs"; +import { ReadableStream } from 'web-streams-polyfill/dist/ponyfill.es2018.js'; +let fileFromPathWarned = false; +async function fileFromPath(path, ...args) { + // this import fails in environments that don't handle export maps correctly, like old versions of Jest + const { fileFromPath: _fileFromPath } = await import('formdata-node/file-from-path'); + if (!fileFromPathWarned) { + console.warn(`fileFromPath is deprecated; use fs.createReadStream(${JSON.stringify(path)}) instead`); + fileFromPathWarned = true; + } + // @ts-ignore + return await _fileFromPath(path, ...args); +} +const defaultHttpAgent = new KeepAliveAgent({ keepAlive: true, timeout: 5 * 60 * 1000 }); +const defaultHttpsAgent = new KeepAliveAgent.HttpsAgent({ keepAlive: true, timeout: 5 * 60 * 1000 }); +async function getMultipartRequestOptions(form, opts) { + const encoder = new FormDataEncoder(form); + const readable = Readable.from(encoder); + const body = new MultipartBody(readable); + const headers = { + ...opts.headers, + ...encoder.headers, + 'Content-Length': encoder.contentLength, + }; + return { ...opts, body: body, headers }; +} +export function getRuntime() { + // Polyfill global object if needed. + if (typeof AbortController === 'undefined') { + // @ts-expect-error (the types are subtly different, but compatible in practice) + globalThis.AbortController = AbortControllerPolyfill; + } + return { + kind: 'node', + fetch: nf.default, + Request: nf.Request, + Response: nf.Response, + Headers: nf.Headers, + FormData: fd.FormData, + Blob: fd.Blob, + File: fd.File, + ReadableStream, + getMultipartRequestOptions, + getDefaultAgent: (url) => (url.startsWith('https') ? defaultHttpsAgent : defaultHttpAgent), + fileFromPath, + isFsReadStream: (value) => value instanceof FsReadStream, + }; +} +//# sourceMappingURL=node-runtime.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/_shims/node-runtime.mjs.map b/backend/node_modules/openai/_shims/node-runtime.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..9cf561be9a385c91cfae2d8adf96468ddaca5f91 --- /dev/null +++ b/backend/node_modules/openai/_shims/node-runtime.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"node-runtime.mjs","sourceRoot":"","sources":["../src/_shims/node-runtime.ts"],"names":[],"mappings":"OAGO,KAAK,EAAE,MAAM,YAAY;OACzB,KAAK,EAAE,MAAM,eAAe;OAE5B,cAAc,MAAM,gBAAgB;OACpC,EAAE,eAAe,IAAI,uBAAuB,EAAE,MAAM,kBAAkB;OACtE,EAAE,UAAU,IAAI,YAAY,EAAE,MAAM,SAAS;OAE7C,EAAE,eAAe,EAAE,MAAM,mBAAmB;OAC5C,EAAE,QAAQ,EAAE,MAAM,aAAa;OAE/B,EAA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AE,CAAC;AACjD,CAAC;AAED,MAAM,UAAU,UAAU;IACxB,oCAAoC;IACpC,IAAI,OAAO,eAAe,KAAK,WAAW,EAAE;QAC1C,gFAAgF;QAChF,UAAU,CAAC,eAAe,GAAG,uBAAuB,CAAC;KACtD;IACD,OAAO;QACL,IAAI,EAAE,MAAM;QACZ,KAAK,EAAE,EAAE,CAAC,OAAO;QACjB,OAAO,EAAE,EAAE,CAAC,OAAO;QACnB,QAAQ,EAAE,EAAE,CAAC,QAAQ;QACrB,OAAO,EAAE,EAAE,CAAC,OAAO;QACnB,QAAQ,EAAE,EAAE,CAAC,QAAQ;QACrB,IAAI,EAAE,EAAE,CAAC,IAAI;QACb,IAAI,EAAE,EAAE,CAAC,IAAI;QACb,cAAc;QACd,0BAA0B;QAC1B,eAAe,EAAE,CAAC,GAAW,EAAS,EAAE,CAAC,CAAC,GAAG,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,iBAAiB,CAAC,CAAC,CAAC,gBAAgB,CAAC;QACzG,YAAY;QACZ,cAAc,EAAE,CAAC,KAAU,EAAyB,EAAE,CAAC,KAAK,YAAY,YAAY;KACrF,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/openai/_shims/node-types.d.ts b/backend/node_modules/openai/_shims/node-types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b31698f780b28f6187a3875497e4df5549c7a15b --- /dev/null +++ b/backend/node_modules/openai/_shims/node-types.d.ts @@ -0,0 +1,42 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ +import * as nf from 'node-fetch'; +import * as fd from 'formdata-node'; + +export { type Agent } from 'node:http'; +export { type Readable } from 'node:stream'; +export { type ReadStream as FsReadStream } from 'node:fs'; +export { ReadableStream } from 'web-streams-polyfill'; + +export const fetch: typeof nf.default; + +export type Request = nf.Request; +export type RequestInfo = nf.RequestInfo; +export type RequestInit = nf.RequestInit; + +export type Response = nf.Response; +export type ResponseInit = nf.ResponseInit; +export type ResponseType = nf.ResponseType; +export type BodyInit = nf.BodyInit; +export type Headers = nf.Headers; +export type HeadersInit = nf.HeadersInit; + +type EndingType = 'native' | 'transparent'; +export interface BlobPropertyBag { + endings?: EndingType; + type?: string; +} + +export interface FilePropertyBag extends BlobPropertyBag { + lastModified?: number; +} + +export type FileFromPathOptions = Omit; + +export type FormData = fd.FormData; +export const FormData: typeof fd.FormData; +export type File = fd.File; +export const File: typeof fd.File; +export type Blob = fd.Blob; +export const Blob: typeof fd.Blob; diff --git a/backend/node_modules/openai/_shims/node-types.js b/backend/node_modules/openai/_shims/node-types.js new file mode 100644 index 0000000000000000000000000000000000000000..ddbdb799c8d3a5a22f9400270cb1b71b570c202a --- /dev/null +++ b/backend/node_modules/openai/_shims/node-types.js @@ -0,0 +1,3 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ diff --git a/backend/node_modules/openai/_shims/node-types.mjs b/backend/node_modules/openai/_shims/node-types.mjs new file mode 100644 index 0000000000000000000000000000000000000000..ddbdb799c8d3a5a22f9400270cb1b71b570c202a --- /dev/null +++ b/backend/node_modules/openai/_shims/node-types.mjs @@ -0,0 +1,3 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ diff --git a/backend/node_modules/openai/_shims/registry.d.ts b/backend/node_modules/openai/_shims/registry.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c041fa2c7b75483847dde34e7b68d91f896f0b06 --- /dev/null +++ b/backend/node_modules/openai/_shims/registry.d.ts @@ -0,0 +1,37 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ +import { type RequestOptions } from "../core.js"; +export interface Shims { + kind: string; + fetch: any; + Request: any; + Response: any; + Headers: any; + FormData: any; + Blob: any; + File: any; + ReadableStream: any; + getMultipartRequestOptions: >(form: Shims['FormData'], opts: RequestOptions) => Promise>; + getDefaultAgent: (url: string) => any; + fileFromPath: ((path: string, filename?: string, options?: {}) => Promise) | ((path: string, options?: {}) => Promise); + isFsReadStream: (value: any) => boolean; +} +export declare let auto: boolean; +export declare let kind: Shims['kind'] | undefined; +export declare let fetch: Shims['fetch'] | undefined; +export declare let Request: Shims['Request'] | undefined; +export declare let Response: Shims['Response'] | undefined; +export declare let Headers: Shims['Headers'] | undefined; +export declare let FormData: Shims['FormData'] | undefined; +export declare let Blob: Shims['Blob'] | undefined; +export declare let File: Shims['File'] | undefined; +export declare let ReadableStream: Shims['ReadableStream'] | undefined; +export declare let getMultipartRequestOptions: Shims['getMultipartRequestOptions'] | undefined; +export declare let getDefaultAgent: Shims['getDefaultAgent'] | undefined; +export declare let fileFromPath: Shims['fileFromPath'] | undefined; +export declare let isFsReadStream: Shims['isFsReadStream'] | undefined; +export declare function setShims(shims: Shims, options?: { + auto: boolean; +}): void; +//# sourceMappingURL=registry.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/_shims/registry.d.ts.map b/backend/node_modules/openai/_shims/registry.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..036e7d445138851702bc502ace871bc10725f0ca --- /dev/null +++ b/backend/node_modules/openai/_shims/registry.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"registry.d.ts","sourceRoot":"","sources":["../src/_shims/registry.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,OAAO,EAAE,KAAK,cAAc,EAAE,MAAM,SAAS,CAAC;AAE9C,MAAM,WAAW,KAAK;IACpB,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,GAAG,CAAC;IACX,OAAO,EAAE,GAAG,CAAC;IACb,QAAQ,EAAE,GAAG,CAAC;IACd,OAAO,EAAE,GAAG,CAAC;IACb,QAAQ,EAAE,GAAG,CAAC;IACd,IAAI,EAAE,GAAG,CAAC;IACV,IAAI,EAAE,GAAG,CAAC;IACV,cAAc,EAAE,GAAG,CAAC;IACpB,0BAA0B,EAAE,CAAC,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EACtD,IAAI,EAAE,KAAK,CA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AC;AAC3E,eAAO,IAAI,0BAA0B,EAAE,KAAK,CAAC,4BAA4B,CAAC,GAAG,SAAqB,CAAC;AACnG,eAAO,IAAI,eAAe,EAAE,KAAK,CAAC,iBAAiB,CAAC,GAAG,SAAqB,CAAC;AAC7E,eAAO,IAAI,YAAY,EAAE,KAAK,CAAC,cAAc,CAAC,GAAG,SAAqB,CAAC;AACvE,eAAO,IAAI,cAAc,EAAE,KAAK,CAAC,gBAAgB,CAAC,GAAG,SAAqB,CAAC;AAE3E,wBAAgB,QAAQ,CAAC,KAAK,EAAE,KAAK,EAAE,OAAO,GAAE;IAAE,IAAI,EAAE,OAAO,CAAA;CAAoB,QAuBlF"} \ No newline at end of file diff --git a/backend/node_modules/openai/_shims/registry.js b/backend/node_modules/openai/_shims/registry.js new file mode 100644 index 0000000000000000000000000000000000000000..824fbf6b69906e1cc836cc39b93d950a4918d028 --- /dev/null +++ b/backend/node_modules/openai/_shims/registry.js @@ -0,0 +1,41 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.setShims = exports.isFsReadStream = exports.fileFromPath = exports.getDefaultAgent = exports.getMultipartRequestOptions = exports.ReadableStream = exports.File = exports.Blob = exports.FormData = exports.Headers = exports.Response = exports.Request = exports.fetch = exports.kind = exports.auto = void 0; +exports.auto = false; +exports.kind = undefined; +exports.fetch = undefined; +exports.Request = undefined; +exports.Response = undefined; +exports.Headers = undefined; +exports.FormData = undefined; +exports.Blob = undefined; +exports.File = undefined; +exports.ReadableStream = undefined; +exports.getMultipartRequestOptions = undefined; +exports.getDefaultAgent = undefined; +exports.fileFromPath = undefined; +exports.isFsReadStream = undefined; +function setShims(shims, options = { auto: false }) { + if (exports.auto) { + throw new Error(`you must \`import 'openai/shims/${shims.kind}'\` before importing anything else from openai`); + } + if (exports.kind) { + throw new Error(`can't \`import 'openai/shims/${shims.kind}'\` after \`import 'openai/shims/${exports.kind}'\``); + } + exports.auto = options.auto; + exports.kind = shims.kind; + exports.fetch = shims.fetch; + exports.Request = shims.Request; + exports.Response = shims.Response; + exports.Headers = shims.Headers; + exports.FormData = shims.FormData; + exports.Blob = shims.Blob; + exports.File = shims.File; + exports.ReadableStream = shims.ReadableStream; + exports.getMultipartRequestOptions = shims.getMultipartRequestOptions; + exports.getDefaultAgent = shims.getDefaultAgent; + exports.fileFromPath = shims.fileFromPath; + exports.isFsReadStream = shims.isFsReadStream; +} +exports.setShims = setShims; +//# sourceMappingURL=registry.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/_shims/registry.js.map b/backend/node_modules/openai/_shims/registry.js.map new file mode 100644 index 0000000000000000000000000000000000000000..4827a45d85b7930b3016d20b3796c18bf0dd1de7 --- /dev/null +++ b/backend/node_modules/openai/_shims/registry.js.map @@ -0,0 +1 @@ +{"version":3,"file":"registry.js","sourceRoot":"","sources":["../src/_shims/registry.ts"],"names":[],"mappings":";;;AA0BW,QAAA,IAAI,GAAG,KAAK,CAAC;AACb,QAAA,IAAI,GAA8B,SAAS,CAAC;AAC5C,QAAA,KAAK,GAA+B,SAAS,CAAC;AAC9C,QAAA,OAAO,GAAiC,SAAS,CAAC;AAClD,QAAA,QAAQ,GAAkC,SAAS,CAAC;AACpD,QAAA,OAAO,GAAiC,SAAS,CAAC;AAClD,QAAA,QAAQ,GAAkC,SAAS,CAAC;AACpD,QAAA,IAAI,GAA8B,SAAS,CAAC;AAC5C,QAAA,IAAI,GAA8B,SAAS,CAAC;AAC5C,QAAA,cAAc,GAAwC,SAAS,CAAC;AAChE,QAAA,0BAA0B,GAAoD,SAAS,CAAC;AACxF,QAAA,eAAe,GAAyC,SAAS,CAAC;AAClE,QAAA,YAAY,GAAsC,SAAS,CAAC;AAC5D,QAAA,cAAc,GAAwC,SAAS,CAAC;AAE3E,SAAgB,QAAQ,CAAC,KAAY,EAAE,UAA6B,EAAE,IAAI,EAAE,KAAK,EAAE;IACjF,IAAI,YAAI,EAAE;QACR,MAAM,IAAI,KAAK,CACb,mCAAmC,KAAK,CAAC,IAAI,gDAAgD,CAC9F,CAAC;KACH;IACD,IAAI,YAAI,EAAE;QACR,MAAM,IAAI,KAAK,CAAC,gCAAgC,KAAK,CAAC,IAAI,oCAAoC,YAAI,KAAK,CAAC,CAAC;KAC1G;IACD,YAAI,GAAG,OAAO,CAAC,IAAI,CAAC;IACpB,YAAI,GAAG,KAAK,CAAC,IAAI,CAAC;IAClB,aAAK,GAAG,KAAK,CAAC,KAAK,CAAC;IACpB,eAAO,GAAG,KAAK,CAAC,OAAO,CAAC;IACxB,gBAAQ,GAAG,KAAK,CAAC,QAAQ,CAAC;IAC1B,eAAO,GAAG,KAAK,CAAC,OAAO,CAAC;IACxB,gBAAQ,GAAG,KAAK,CAAC,QAAQ,CAAC;IAC1B,YAAI,GAAG,KAAK,CAAC,IAAI,CAAC;IAClB,YAAI,GAAG,KAAK,CAAC,IAAI,CAAC;IAClB,sBAAc,GAAG,KAAK,CAAC,cAAc,CAAC;IACtC,kCAA0B,GAAG,KAAK,CAAC,0BAA0B,CAAC;IAC9D,uBAAe,GAAG,KAAK,CAAC,eAAe,CAAC;IACxC,oBAAY,GAAG,KAAK,CAAC,YAAY,CAAC;IAClC,sBAAc,GAAG,KAAK,CAAC,cAAc,CAAC;AACxC,CAAC;AAvBD,4BAuBC"} \ No newline at end of file diff --git a/backend/node_modules/openai/_shims/registry.mjs b/backend/node_modules/openai/_shims/registry.mjs new file mode 100644 index 0000000000000000000000000000000000000000..c757629227fa5d6913802ddb824243426e6af0f4 --- /dev/null +++ b/backend/node_modules/openai/_shims/registry.mjs @@ -0,0 +1,37 @@ +export let auto = false; +export let kind = undefined; +export let fetch = undefined; +export let Request = undefined; +export let Response = undefined; +export let Headers = undefined; +export let FormData = undefined; +export let Blob = undefined; +export let File = undefined; +export let ReadableStream = undefined; +export let getMultipartRequestOptions = undefined; +export let getDefaultAgent = undefined; +export let fileFromPath = undefined; +export let isFsReadStream = undefined; +export function setShims(shims, options = { auto: false }) { + if (auto) { + throw new Error(`you must \`import 'openai/shims/${shims.kind}'\` before importing anything else from openai`); + } + if (kind) { + throw new Error(`can't \`import 'openai/shims/${shims.kind}'\` after \`import 'openai/shims/${kind}'\``); + } + auto = options.auto; + kind = shims.kind; + fetch = shims.fetch; + Request = shims.Request; + Response = shims.Response; + Headers = shims.Headers; + FormData = shims.FormData; + Blob = shims.Blob; + File = shims.File; + ReadableStream = shims.ReadableStream; + getMultipartRequestOptions = shims.getMultipartRequestOptions; + getDefaultAgent = shims.getDefaultAgent; + fileFromPath = shims.fileFromPath; + isFsReadStream = shims.isFsReadStream; +} +//# sourceMappingURL=registry.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/_shims/registry.mjs.map b/backend/node_modules/openai/_shims/registry.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..92ec20a9a2429961c9320e687f9d3fcdb11275d7 --- /dev/null +++ b/backend/node_modules/openai/_shims/registry.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"registry.mjs","sourceRoot":"","sources":["../src/_shims/registry.ts"],"names":[],"mappings":"AA0BA,MAAM,CAAC,IAAI,IAAI,GAAG,KAAK,CAAC;AACxB,MAAM,CAAC,IAAI,IAAI,GAA8B,SAAS,CAAC;AACvD,MAAM,CAAC,IAAI,KAAK,GAA+B,SAAS,CAAC;AACzD,MAAM,CAAC,IAAI,OAAO,GAAiC,SAAS,CAAC;AAC7D,MAAM,CAAC,IAAI,QAAQ,GAAkC,SAAS,CAAC;AAC/D,MAAM,CAAC,IAAI,OAAO,GAAiC,SAAS,CAAC;AAC7D,MAAM,CAAC,IAAI,QAAQ,GAAkC,SAAS,CAAC;AAC/D,MAAM,CAAC,IAAI,IAAI,GAA8B,SAAS,CAAC;AACvD,MAAM,CAAC,IAAI,IAAI,GAA8B,SAAS,CAAC;AACvD,MAAM,CAAC,IAAI,cAAc,GAAwC,SAAS,CAAC;AAC3E,MAAM,CAAC,IAAI,0BAA0B,GAAoD,SAAS,CAAC;AACnG,MAAM,CAAC,IAAI,eAAe,GAAyC,SAAS,CAAC;AAC7E,MAAM,CAAC,IAAI,YAAY,GAAsC,SAAS,CAAC;AACvE,MAAM,CAAC,IAAI,cAAc,GAAwC,SAAS,CAAC;AAE3E,MAAM,UAAU,QAAQ,CAAC,KAAY,EAAE,UAA6B,EAAE,IAAI,EAAE,KAAK,EAAE;IACjF,IAAI,IAAI,EAAE;QACR,MAAM,IAAI,KAAK,CACb,mCAAmC,KAAK,CAAC,IAAI,gDAAgD,CAC9F,CAAC;KACH;IACD,IAAI,IAAI,EAAE;QACR,MAAM,IAAI,KAAK,CAAC,gCAAgC,KAAK,CAAC,IAAI,oCAAoC,IAAI,KAAK,CAAC,CAAC;KAC1G;IACD,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;IACpB,IAAI,GAAG,KAAK,CAAC,IAAI,CAAC;IAClB,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC;IACpB,OAAO,GAAG,KAAK,CAAC,OAAO,CAAC;IACxB,QAAQ,GAAG,KAAK,CAAC,QAAQ,CAAC;IAC1B,OAAO,GAAG,KAAK,CAAC,OAAO,CAAC;IACxB,QAAQ,GAAG,KAAK,CAAC,QAAQ,CAAC;IAC1B,IAAI,GAAG,KAAK,CAAC,IAAI,CAAC;IAClB,IAAI,GAAG,KAAK,CAAC,IAAI,CAAC;IAClB,cAAc,GAAG,KAAK,CAAC,cAAc,CAAC;IACtC,0BAA0B,GAAG,KAAK,CAAC,0BAA0B,CAAC;IAC9D,eAAe,GAAG,KAAK,CAAC,eAAe,CAAC;IACxC,YAAY,GAAG,KAAK,CAAC,YAAY,CAAC;IAClC,cAAc,GAAG,KAAK,CAAC,cAAc,CAAC;AACxC,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/openai/_shims/web-runtime.d.ts b/backend/node_modules/openai/_shims/web-runtime.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4ae807700cfac151dee30e36f252ffced6a65784 --- /dev/null +++ b/backend/node_modules/openai/_shims/web-runtime.d.ts @@ -0,0 +1,5 @@ +import { type Shims } from "./registry.js"; +export declare function getRuntime({ manuallyImported }?: { + manuallyImported?: boolean; +}): Shims; +//# sourceMappingURL=web-runtime.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/_shims/web-runtime.d.ts.map b/backend/node_modules/openai/_shims/web-runtime.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..c6a1874e7ea616773d2fd158f24e971e7a7537ad --- /dev/null +++ b/backend/node_modules/openai/_shims/web-runtime.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"web-runtime.d.ts","sourceRoot":"","sources":["../src/_shims/web-runtime.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,KAAK,KAAK,EAAE,MAAM,YAAY,CAAC;AAExC,wBAAgB,UAAU,CAAC,EAAE,gBAAgB,EAAE,GAAE;IAAE,gBAAgB,CAAC,EAAE,OAAO,CAAA;CAAO,GAAG,KAAK,CA+F3F"} \ No newline at end of file diff --git a/backend/node_modules/openai/_shims/web-runtime.js b/backend/node_modules/openai/_shims/web-runtime.js new file mode 100644 index 0000000000000000000000000000000000000000..f2f37327d38670be144f04ccef87db64e7e528eb --- /dev/null +++ b/backend/node_modules/openai/_shims/web-runtime.js @@ -0,0 +1,78 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getRuntime = void 0; +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ +const MultipartBody_1 = require("./MultipartBody.js"); +function getRuntime({ manuallyImported } = {}) { + const recommendation = manuallyImported ? + `You may need to use polyfills` + : `Add one of these imports before your first \`import … from 'openai'\`: +- \`import 'openai/shims/node'\` (if you're running on Node) +- \`import 'openai/shims/web'\` (otherwise) +`; + let _fetch, _Request, _Response, _Headers; + try { + // @ts-ignore + _fetch = fetch; + // @ts-ignore + _Request = Request; + // @ts-ignore + _Response = Response; + // @ts-ignore + _Headers = Headers; + } + catch (error) { + throw new Error(`this environment is missing the following Web Fetch API type: ${error.message}. ${recommendation}`); + } + return { + kind: 'web', + fetch: _fetch, + Request: _Request, + Response: _Response, + Headers: _Headers, + FormData: + // @ts-ignore + typeof FormData !== 'undefined' ? FormData : (class FormData { + // @ts-ignore + constructor() { + throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${recommendation}`); + } + }), + Blob: typeof Blob !== 'undefined' ? Blob : (class Blob { + constructor() { + throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${recommendation}`); + } + }), + File: + // @ts-ignore + typeof File !== 'undefined' ? File : (class File { + // @ts-ignore + constructor() { + throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${recommendation}`); + } + }), + ReadableStream: + // @ts-ignore + typeof ReadableStream !== 'undefined' ? ReadableStream : (class ReadableStream { + // @ts-ignore + constructor() { + throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${recommendation}`); + } + }), + getMultipartRequestOptions: async ( + // @ts-ignore + form, opts) => ({ + ...opts, + body: new MultipartBody_1.MultipartBody(form), + }), + getDefaultAgent: (url) => undefined, + fileFromPath: () => { + throw new Error('The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/openai/openai-node#file-uploads'); + }, + isFsReadStream: (value) => false, + }; +} +exports.getRuntime = getRuntime; +//# sourceMappingURL=web-runtime.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/_shims/web-runtime.js.map b/backend/node_modules/openai/_shims/web-runtime.js.map new file mode 100644 index 0000000000000000000000000000000000000000..4aeb05f1b5df6035f712b9ef35045f27f3aa77cb --- /dev/null +++ b/backend/node_modules/openai/_shims/web-runtime.js.map @@ -0,0 +1 @@ +{"version":3,"file":"web-runtime.js","sourceRoot":"","sources":["../src/_shims/web-runtime.ts"],"names":[],"mappings":";;;AAAA;;GAEG;AACH,sDAAgD;AAIhD,SAAgB,UAAU,CAAC,EAAE,gBAAgB,KAAqC,EAAE;IAClF,MAAM,cAAc,GAClB,gBAAgB,CAAC,CAAC;QAChB,+BAA+B;QACjC,CAAC,CAAC;;;CAGL,CAAC;IAEA,IAAI,MAA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I,KAAK,CACb,uFAAuF,cAAc,EAAE,CACxG,CAAC;YACJ,CAAC;SACF,CACF;QACH,0BAA0B,EAAE,KAAK;QAC/B,aAAa;QACb,IAAc,EACd,IAAuB,EACK,EAAE,CAAC,CAAC;YAChC,GAAG,IAAI;YACP,IAAI,EAAE,IAAI,6BAAa,CAAC,IAAI,CAAQ;SACrC,CAAC;QACF,eAAe,EAAE,CAAC,GAAW,EAAE,EAAE,CAAC,SAAS;QAC3C,YAAY,EAAE,GAAG,EAAE;YACjB,MAAM,IAAI,KAAK,CACb,gJAAgJ,CACjJ,CAAC;QACJ,CAAC;QACD,cAAc,EAAE,CAAC,KAAU,EAAE,EAAE,CAAC,KAAK;KACtC,CAAC;AACJ,CAAC;AA/FD,gCA+FC"} \ No newline at end of file diff --git a/backend/node_modules/openai/_shims/web-runtime.mjs b/backend/node_modules/openai/_shims/web-runtime.mjs new file mode 100644 index 0000000000000000000000000000000000000000..691d5081f6e038713e7718dd4dbb4be3e0884ae9 --- /dev/null +++ b/backend/node_modules/openai/_shims/web-runtime.mjs @@ -0,0 +1,71 @@ +import { MultipartBody } from "./MultipartBody.mjs"; +export function getRuntime({ manuallyImported } = {}) { + const recommendation = manuallyImported ? + `You may need to use polyfills` + : `Add one of these imports before your first \`import … from 'openai'\`: +- \`import 'openai/shims/node'\` (if you're running on Node) +- \`import 'openai/shims/web'\` (otherwise) +`; + let _fetch, _Request, _Response, _Headers; + try { + // @ts-ignore + _fetch = fetch; + // @ts-ignore + _Request = Request; + // @ts-ignore + _Response = Response; + // @ts-ignore + _Headers = Headers; + } + catch (error) { + throw new Error(`this environment is missing the following Web Fetch API type: ${error.message}. ${recommendation}`); + } + return { + kind: 'web', + fetch: _fetch, + Request: _Request, + Response: _Response, + Headers: _Headers, + FormData: + // @ts-ignore + typeof FormData !== 'undefined' ? FormData : (class FormData { + // @ts-ignore + constructor() { + throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${recommendation}`); + } + }), + Blob: typeof Blob !== 'undefined' ? Blob : (class Blob { + constructor() { + throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${recommendation}`); + } + }), + File: + // @ts-ignore + typeof File !== 'undefined' ? File : (class File { + // @ts-ignore + constructor() { + throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${recommendation}`); + } + }), + ReadableStream: + // @ts-ignore + typeof ReadableStream !== 'undefined' ? ReadableStream : (class ReadableStream { + // @ts-ignore + constructor() { + throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${recommendation}`); + } + }), + getMultipartRequestOptions: async ( + // @ts-ignore + form, opts) => ({ + ...opts, + body: new MultipartBody(form), + }), + getDefaultAgent: (url) => undefined, + fileFromPath: () => { + throw new Error('The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/openai/openai-node#file-uploads'); + }, + isFsReadStream: (value) => false, + }; +} +//# sourceMappingURL=web-runtime.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/_shims/web-runtime.mjs.map b/backend/node_modules/openai/_shims/web-runtime.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..921ce6b644259385f43b521775a0123be7bf032e --- /dev/null +++ b/backend/node_modules/openai/_shims/web-runtime.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"web-runtime.mjs","sourceRoot":"","sources":["../src/_shims/web-runtime.ts"],"names":[],"mappings":"OAGO,EAAE,aAAa,EAAE;AAIxB,MAAM,UAAU,UAAU,CAAC,EAAE,gBAAgB,KAAqC,EAAE;IAClF,MAAM,cAAc,GAClB,gBAAgB,CAAC,CAAC;QAChB,+BAA+B;QACjC,CAAC,CAAC;;;CAGL,CAAC;IAEA,IAAI,MAAM,EAAE,QAAQ,EAAE,SAAS,EAAE,QAAQ,CAAC;IAC1C,IAAI;QACF,aAAa;QACb,MAAM,GAAG,KAAK,CAAC;QACf,aAAa;QACb,QAAQ,GAAG,OAAO,CAAC;QACnB,aAAa;QACb,SAAS,GAAG,QAAQ,CAAC;QACrB,aA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,aAAa,CAAC,IAAI,CAAQ;SACrC,CAAC;QACF,eAAe,EAAE,CAAC,GAAW,EAAE,EAAE,CAAC,SAAS;QAC3C,YAAY,EAAE,GAAG,EAAE;YACjB,MAAM,IAAI,KAAK,CACb,gJAAgJ,CACjJ,CAAC;QACJ,CAAC;QACD,cAAc,EAAE,CAAC,KAAU,EAAE,EAAE,CAAC,KAAK;KACtC,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/openai/_shims/web-types.d.ts b/backend/node_modules/openai/_shims/web-types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4ff351383278a4b2ed4afbbfd7d9d134f648f81b --- /dev/null +++ b/backend/node_modules/openai/_shims/web-types.d.ts @@ -0,0 +1,83 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ +export type Agent = any; + +declare const _fetch: typeof fetch; +export { _fetch as fetch }; + +type _Request = Request; +export { _Request as Request }; + +type _RequestInfo = RequestInfo; +export { type _RequestInfo as RequestInfo }; + +type _RequestInit = RequestInit; +export { type _RequestInit as RequestInit }; + +type _Response = Response; +export { _Response as Response }; + +type _ResponseInit = ResponseInit; +export { type _ResponseInit as ResponseInit }; + +type _ResponseType = ResponseType; +export { type _ResponseType as ResponseType }; + +type _BodyInit = BodyInit; +export { type _BodyInit as BodyInit }; + +type _Headers = Headers; +export { _Headers as Headers }; + +type _HeadersInit = HeadersInit; +export { type _HeadersInit as HeadersInit }; + +type EndingType = 'native' | 'transparent'; + +export interface BlobPropertyBag { + endings?: EndingType; + type?: string; +} + +export interface FilePropertyBag extends BlobPropertyBag { + lastModified?: number; +} + +export type FileFromPathOptions = Omit; + +type _FormData = FormData; +declare const _FormData: typeof FormData; +export { _FormData as FormData }; + +type _File = File; +declare const _File: typeof File; +export { _File as File }; + +type _Blob = Blob; +declare const _Blob: typeof Blob; +export { _Blob as Blob }; + +export declare class Readable { + readable: boolean; + readonly readableEnded: boolean; + readonly readableFlowing: boolean | null; + readonly readableHighWaterMark: number; + readonly readableLength: number; + readonly readableObjectMode: boolean; + destroyed: boolean; + read(size?: number): any; + pause(): this; + resume(): this; + isPaused(): boolean; + destroy(error?: Error): this; + [Symbol.asyncIterator](): AsyncIterableIterator; +} + +export declare class FsReadStream extends Readable { + path: {}; // node type is string | Buffer +} + +type _ReadableStream = ReadableStream; +declare const _ReadableStream: typeof ReadableStream; +export { _ReadableStream as ReadableStream }; diff --git a/backend/node_modules/openai/_shims/web-types.js b/backend/node_modules/openai/_shims/web-types.js new file mode 100644 index 0000000000000000000000000000000000000000..ddbdb799c8d3a5a22f9400270cb1b71b570c202a --- /dev/null +++ b/backend/node_modules/openai/_shims/web-types.js @@ -0,0 +1,3 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ diff --git a/backend/node_modules/openai/_shims/web-types.mjs b/backend/node_modules/openai/_shims/web-types.mjs new file mode 100644 index 0000000000000000000000000000000000000000..ddbdb799c8d3a5a22f9400270cb1b71b570c202a --- /dev/null +++ b/backend/node_modules/openai/_shims/web-types.mjs @@ -0,0 +1,3 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ diff --git a/backend/node_modules/openai/bin/cli b/backend/node_modules/openai/bin/cli new file mode 100755 index 0000000000000000000000000000000000000000..00275ace4a264a7646ca0299b5d0d5f2019eb305 --- /dev/null +++ b/backend/node_modules/openai/bin/cli @@ -0,0 +1,49 @@ +#!/usr/bin/env node + +const { spawnSync } = require('child_process'); + +const commands = { + migrate: { + description: 'Run migrations to update from openai v3 to v4', + fn: () => { + console.log('This automatic code migration is provided by grit.io'); + console.log('Visit https://app.grit.io/studio?preset=openai_v4 for more details.') + + const result = spawnSync( + 'npx', + ['-y', '@getgrit/launcher', 'apply', 'openai_v4', ...process.argv.slice(3)], + { stdio: 'inherit' }, + ); + if (result.status !== 0) { + process.exit(result.status); + } + } + } +} + +function exitWithHelp() { + console.log("Usage: $0 "); + console.log(); + console.log('Subcommands:'); + + for (const [name, info] of Object.entries(commands)) { + console.log(` ${name} ${info.description}`); + } + + console.log(); + process.exit(1); +} + +if (process.argv.length < 3) { + exitWithHelp(); +} + +const commandName = process.argv[2]; + +const command = commands[commandName]; +if (!command) { + console.log(`Unknown subcommand ${commandName}.`); + exitWithHelp(); +} + +command.fn(); diff --git a/backend/node_modules/openai/core.d.ts b/backend/node_modules/openai/core.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cc1108c4a9f1c51f33d7a799f742e23de6792ae6 --- /dev/null +++ b/backend/node_modules/openai/core.d.ts @@ -0,0 +1,239 @@ + + +import { Stream } from "./streaming.js"; +import { APIError } from "./error.js"; +import { type Readable, type Agent, type RequestInfo, type RequestInit, type Response, type HeadersInit } from "./_shims/index.js"; +export { type Response }; +export { maybeMultipartFormRequestOptions, multipartFormRequestOptions, createForm, type Uploadable, } from "./uploads.js"; +export type Fetch = (url: RequestInfo, init?: RequestInit) => Promise; +type PromiseOrValue = T | Promise; +type APIResponseProps = { + response: Response; + options: FinalRequestOptions; + controller: AbortController; +}; +/** + * A subclass of `Promise` providing additional helper methods + * for interacting with the SDK. + */ +export declare class APIPromise extends Promise { + private responsePromise; + private parseResponse; + private parsedPromise; + constructor(responsePromise: Promise, parseResponse?: (props: APIResponseProps) => PromiseOrValue); + _thenUnwrap(transform: (data: T) => U): APIPromise; + /** + * Gets the raw `Response` instance instead of parsing the response + * data. + * + * If you want to parse the response body but still get the `Response` + * instance, you can use {@link withResponse()}. + * + * 👋 Getting the wrong TypeScript type for `Response`? + * Try setting `"moduleResolution": "NodeNext"` if you can, + * or add one of these imports before your first `import … from 'openai'`: + * - `import 'openai/shims/node'` (if you're running on Node) + * - `import 'openai/shims/web'` (otherwise) + */ + asResponse(): Promise; + /** + * Gets the parsed response data and the raw `Response` instance. + * + * If you just want to get the raw `Response` instance without parsing it, + * you can use {@link asResponse()}. + * + * + * 👋 Getting the wrong TypeScript type for `Response`? + * Try setting `"moduleResolution": "NodeNext"` if you can, + * or add one of these imports before your first `import … from 'openai'`: + * - `import 'openai/shims/node'` (if you're running on Node) + * - `import 'openai/shims/web'` (otherwise) + */ + withResponse(): Promise<{ + data: T; + response: Response; + }>; + private parse; + then(onfulfilled?: ((value: T) => TResult1 | PromiseLike) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike) | undefined | null): Promise; + catch(onrejected?: ((reason: any) => TResult | PromiseLike) | undefined | null): Promise; + finally(onfinally?: (() => void) | undefined | null): Promise; +} +export declare abstract class APIClient { + baseURL: string; + maxRetries: number; + timeout: number; + httpAgent: Agent | undefined; + private fetch; + protected idempotencyHeader?: string; + constructor({ baseURL, maxRetries, timeout, // 10 minutes + httpAgent, fetch: overridenFetch, }: { + baseURL: string; + maxRetries?: number | undefined; + timeout: number | undefined; + httpAgent: Agent | undefined; + fetch: Fetch | undefined; + }); + protected authHeaders(opts: FinalRequestOptions): Headers; + /** + * Override this to add your own default headers, for example: + * + * { + * ...super.defaultHeaders(), + * Authorization: 'Bearer 123', + * } + */ + protected defaultHeaders(opts: FinalRequestOptions): Headers; + protected abstract defaultQuery(): DefaultQuery | undefined; + /** + * Override this to add your own headers validation: + */ + protected validateHeaders(headers: Headers, customHeaders: Headers): void; + protected defaultIdempotencyKey(): string; + get(path: string, opts?: PromiseOrValue>): APIPromise; + post(path: string, opts?: PromiseOrValue>): APIPromise; + patch(path: string, opts?: PromiseOrValue>): APIPromise; + put(path: string, opts?: PromiseOrValue>): APIPromise; + delete(path: string, opts?: PromiseOrValue>): APIPromise; + private methodRequest; + getAPIList = AbstractPage>(path: string, Page: new (...args: any[]) => PageClass, opts?: RequestOptions): PagePromise; + private calculateContentLength; + buildRequest(options: FinalRequestOptions): { + req: RequestInit; + url: string; + timeout: number; + }; + private buildHeaders; + /** + * Used as a callback for mutating the given `FinalRequestOptions` object. + */ + protected prepareOptions(options: FinalRequestOptions): Promise; + /** + * Used as a callback for mutating the given `RequestInit` object. + * + * This is useful for cases where you want to add certain headers based off of + * the request properties, e.g. `method` or `url`. + */ + protected prepareRequest(request: RequestInit, { url, options }: { + url: string; + options: FinalRequestOptions; + }): Promise; + protected parseHeaders(headers: HeadersInit | null | undefined): Record; + protected makeStatusError(status: number | undefined, error: Object | undefined, message: string | undefined, headers: Headers | undefined): APIError; + request(options: PromiseOrValue>, remainingRetries?: number | null): APIPromise; + private makeRequest; + requestAPIList = AbstractPage>(Page: new (...args: ConstructorParameters) => PageClass, options: FinalRequestOptions): PagePromise; + buildURL(path: string, query: Req | null | undefined): string; + protected stringifyQuery(query: Record): string; + fetchWithTimeout(url: RequestInfo, init: RequestInit | undefined, ms: number, controller: AbortController): Promise; + protected getRequestClient(): RequestClient; + private shouldRetry; + private retryRequest; + private calculateDefaultRetryTimeoutMillis; + private getUserAgent; +} +export type PageInfo = { + url: URL; +} | { + params: Record | null; +}; +export declare abstract class AbstractPage implements AsyncIterable { + #private; + protected options: FinalRequestOptions; + protected response: Response; + protected body: unknown; + constructor(client: APIClient, response: Response, body: unknown, options: FinalRequestOptions); + /** + * @deprecated Use nextPageInfo instead + */ + abstract nextPageParams(): Partial> | null; + abstract nextPageInfo(): PageInfo | null; + abstract getPaginatedItems(): Item[]; + hasNextPage(): boolean; + getNextPage(): Promise; + iterPages(): AsyncGenerator, void, unknown>; + [Symbol.asyncIterator](): AsyncGenerator, void, unknown>; +} +/** + * This subclass of Promise will resolve to an instantiated Page once the request completes. + * + * It also implements AsyncIterable to allow auto-paginating iteration on an unawaited list call, eg: + * + * for await (const item of client.items.list()) { + * console.log(item) + * } + */ +export declare class PagePromise, Item = ReturnType[number]> extends APIPromise implements AsyncIterable { + constructor(client: APIClient, request: Promise, Page: new (...args: ConstructorParameters) => PageClass); + /** + * Allow auto-paginating iteration on an unawaited list call, eg: + * + * for await (const item of client.items.list()) { + * console.log(item) + * } + */ + [Symbol.asyncIterator](): AsyncGenerator, void, unknown>; +} +export declare const createResponseHeaders: (headers: Awaited>['headers']) => Record; +type HTTPMethod = 'get' | 'post' | 'put' | 'patch' | 'delete'; +export type RequestClient = { + fetch: Fetch; +}; +export type Headers = Record; +export type DefaultQuery = Record; +export type KeysEnum = { + [P in keyof Required]: true; +}; +export type RequestOptions | Readable> = { + method?: HTTPMethod; + path?: string; + query?: Req | undefined; + body?: Req | null | undefined; + headers?: Headers | undefined; + maxRetries?: number; + stream?: boolean | undefined; + timeout?: number; + httpAgent?: Agent; + signal?: AbortSignal | undefined | null; + idempotencyKey?: string; + __binaryResponse?: boolean | undefined; + __streamClass?: typeof Stream; +}; +export declare const isRequestOptions: (obj: unknown) => obj is RequestOptions; +export type FinalRequestOptions | Readable> = RequestOptions & { + method: HTTPMethod; + path: string; +}; +export declare const safeJSON: (text: string) => any; +export declare const sleep: (ms: number) => Promise; +export declare const castToError: (err: any) => Error; +export declare const ensurePresent: (value: T | null | undefined) => T; +/** + * Read an environment variable. + * + * Trims beginning and trailing whitespace. + * + * Will return undefined if the environment variable doesn't exist or cannot be accessed. + */ +export declare const readEnv: (env: string) => string | undefined; +export declare const coerceInteger: (value: unknown) => number; +export declare const coerceFloat: (value: unknown) => number; +export declare const coerceBoolean: (value: unknown) => boolean; +export declare const maybeCoerceInteger: (value: unknown) => number | undefined; +export declare const maybeCoerceFloat: (value: unknown) => number | undefined; +export declare const maybeCoerceBoolean: (value: unknown) => boolean | undefined; +export declare function isEmptyObj(obj: Object | null | undefined): boolean; +export declare function hasOwn(obj: Object, key: string): boolean; +export declare function debug(action: string, ...args: any[]): void; +export declare const isRunningInBrowser: () => boolean; +export interface HeadersProtocol { + get: (header: string) => string | null | undefined; +} +export type HeadersLike = Record | HeadersProtocol; +export declare const isHeadersProtocol: (headers: any) => headers is HeadersProtocol; +export declare const getRequiredHeader: (headers: HeadersLike, header: string) => string; +/** + * Encodes a string to Base64 format. + */ +export declare const toBase64: (str: string | null | undefined) => string; +export declare function isObj(obj: unknown): obj is Record; +//# sourceMappingURL=core.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/core.d.ts.map b/backend/node_modules/openai/core.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..a71f83de0967ba2cf73bf1f58737be169f06f47a --- /dev/null +++ b/backend/node_modules/openai/core.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"core.d.ts","sourceRoot":"","sources":["src/core.ts"],"names":[],"mappings":";;AACA,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,EAEL,QAAQ,EAIT,MAAM,SAAS,CAAC;AACjB,OAAO,EAEL,KAAK,QAAQ,EAEb,KAAK,KAAK,EAEV,KAAK,WAAW,EAChB,KAAK,WAAW,EAChB,KAAK,QAAQ,EACb,KAAK,WAAW,EACjB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,KAAK,QAAQ,EAAE,CAAC;AAEzB,OAAO,EACL,gCAAgC,EAChC,2BAA2B,EAC3B,UAAU,EACV,KAAK,UAAU,GAChB,MAAM,WAAW,CAAC;AAEnB,MAAM,MAAM,KAAK,GAAG,CAAC,GAAG,EAAE,WAAW,EAAE,IAAI,CAAC,EAAE,WAAW,KAAK,OAAO,CAAC,QAAQ,CAAC,CAAC;AAEhF,KAAK,cAAc,CAAC,CAAC,IAAI,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;AAExC,KAAK,gBAAgB,GAAG;IACtB,QAAQ,EAAE,QAAQ,CAAC;IACnB,OAAO,EAAE,mBAAmB,CAAC;IAC7B,UAAU,EAAE,eAAe,CAAC;CAC7B,CAAC;AA4CF;;;GAGG;AACH,qBAAa,UAAU,CAAC,CAAC,CAAE,SAAQ,OAAO,CAAC,CAAC,CAAC;IAIzC,OAAO,CAAC,eAAe;IACvB,OAAO,CAAC,aAAa;IAJvB,OAAO,CAAC,aAAa,CAAyB;gBAGpC,eAAe,EAAE,OAAO,CAAC,gBAAgB,CAAC,EAC1C,aAAa,GAAE,CAAC,KAAK,EAAE,gBAAgB,KAAK,cAAc,CAAC,CAAC,CAAwB;IAU9F,WAAW,CAAC,CAAC,EAAE,SAAS,EAAE,CAAC,IAAI,EAAE,CAAC,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AE,GAAG,SAAS,CAAC,GAAG,eAAe,CAAC;AAE1F,eAAO,MAAM,iBAAiB,YAAa,GAAG,+BAE7C,CAAC;AAEF,eAAO,MAAM,iBAAiB,YAAa,WAAW,UAAU,MAAM,KAAG,MA2BxE,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,QAAQ,QAAS,MAAM,GAAG,IAAI,GAAG,SAAS,KAAG,MAWzD,CAAC;AAEF,wBAAgB,KAAK,CAAC,GAAG,EAAE,OAAO,GAAG,GAAG,IAAI,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAElE"} \ No newline at end of file diff --git a/backend/node_modules/openai/core.js b/backend/node_modules/openai/core.js new file mode 100644 index 0000000000000000000000000000000000000000..209258fd0af605f209e72fcd445bd44bd93e9729 --- /dev/null +++ b/backend/node_modules/openai/core.js @@ -0,0 +1,879 @@ +"use strict"; +var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +}; +var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var _AbstractPage_client; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isObj = exports.toBase64 = exports.getRequiredHeader = exports.isHeadersProtocol = exports.isRunningInBrowser = exports.debug = exports.hasOwn = exports.isEmptyObj = exports.maybeCoerceBoolean = exports.maybeCoerceFloat = exports.maybeCoerceInteger = exports.coerceBoolean = exports.coerceFloat = exports.coerceInteger = exports.readEnv = exports.ensurePresent = exports.castToError = exports.sleep = exports.safeJSON = exports.isRequestOptions = exports.createResponseHeaders = exports.PagePromise = exports.AbstractPage = exports.APIClient = exports.APIPromise = exports.createForm = exports.multipartFormRequestOptions = exports.maybeMultipartFormRequestOptions = void 0; +const version_1 = require("./version.js"); +const streaming_1 = require("./streaming.js"); +const error_1 = require("./error.js"); +const index_1 = require("./_shims/index.js"); +const uploads_1 = require("./uploads.js"); +var uploads_2 = require("./uploads.js"); +Object.defineProperty(exports, "maybeMultipartFormRequestOptions", { enumerable: true, get: function () { return uploads_2.maybeMultipartFormRequestOptions; } }); +Object.defineProperty(exports, "multipartFormRequestOptions", { enumerable: true, get: function () { return uploads_2.multipartFormRequestOptions; } }); +Object.defineProperty(exports, "createForm", { enumerable: true, get: function () { return uploads_2.createForm; } }); +async function defaultParseResponse(props) { + const { response } = props; + if (props.options.stream) { + debug('response', response.status, response.url, response.headers, response.body); + // Note: there is an invariant here that isn't represented in the type system + // that if you set `stream: true` the response type must also be `Stream` + if (props.options.__streamClass) { + return props.options.__streamClass.fromSSEResponse(response, props.controller); + } + return streaming_1.Stream.fromSSEResponse(response, props.controller); + } + // fetch refuses to read the body when the status code is 204. + if (response.status === 204) { + return null; + } + if (props.options.__binaryResponse) { + return response; + } + const contentType = response.headers.get('content-type'); + const isJSON = contentType?.includes('application/json') || contentType?.includes('application/vnd.api+json'); + if (isJSON) { + const json = await response.json(); + debug('response', response.status, response.url, response.headers, json); + return json; + } + const text = await response.text(); + debug('response', response.status, response.url, response.headers, text); + // TODO handle blob, arraybuffer, other content types, etc. + return text; +} +/** + * A subclass of `Promise` providing additional helper methods + * for interacting with the SDK. + */ +class APIPromise extends Promise { + constructor(responsePromise, parseResponse = defaultParseResponse) { + super((resolve) => { + // this is maybe a bit weird but this has to be a no-op to not implicitly + // parse the response body; instead .then, .catch, .finally are overridden + // to parse the response + resolve(null); + }); + this.responsePromise = responsePromise; + this.parseResponse = parseResponse; + } + _thenUnwrap(transform) { + return new APIPromise(this.responsePromise, async (props) => transform(await this.parseResponse(props))); + } + /** + * Gets the raw `Response` instance instead of parsing the response + * data. + * + * If you want to parse the response body but still get the `Response` + * instance, you can use {@link withResponse()}. + * + * 👋 Getting the wrong TypeScript type for `Response`? + * Try setting `"moduleResolution": "NodeNext"` if you can, + * or add one of these imports before your first `import … from 'openai'`: + * - `import 'openai/shims/node'` (if you're running on Node) + * - `import 'openai/shims/web'` (otherwise) + */ + asResponse() { + return this.responsePromise.then((p) => p.response); + } + /** + * Gets the parsed response data and the raw `Response` instance. + * + * If you just want to get the raw `Response` instance without parsing it, + * you can use {@link asResponse()}. + * + * + * 👋 Getting the wrong TypeScript type for `Response`? + * Try setting `"moduleResolution": "NodeNext"` if you can, + * or add one of these imports before your first `import … from 'openai'`: + * - `import 'openai/shims/node'` (if you're running on Node) + * - `import 'openai/shims/web'` (otherwise) + */ + async withResponse() { + const [data, response] = await Promise.all([this.parse(), this.asResponse()]); + return { data, response }; + } + parse() { + if (!this.parsedPromise) { + this.parsedPromise = this.responsePromise.then(this.parseResponse); + } + return this.parsedPromise; + } + then(onfulfilled, onrejected) { + return this.parse().then(onfulfilled, onrejected); + } + catch(onrejected) { + return this.parse().catch(onrejected); + } + finally(onfinally) { + return this.parse().finally(onfinally); + } +} +exports.APIPromise = APIPromise; +class APIClient { + constructor({ baseURL, maxRetries = 2, timeout = 600000, // 10 minutes + httpAgent, fetch: overridenFetch, }) { + this.baseURL = baseURL; + this.maxRetries = validatePositiveInteger('maxRetries', maxRetries); + this.timeout = validatePositiveInteger('timeout', timeout); + this.httpAgent = httpAgent; + this.fetch = overridenFetch ?? index_1.fetch; + } + authHeaders(opts) { + return {}; + } + /** + * Override this to add your own default headers, for example: + * + * { + * ...super.defaultHeaders(), + * Authorization: 'Bearer 123', + * } + */ + defaultHeaders(opts) { + return { + Accept: 'application/json', + 'Content-Type': 'application/json', + 'User-Agent': this.getUserAgent(), + ...getPlatformHeaders(), + ...this.authHeaders(opts), + }; + } + /** + * Override this to add your own headers validation: + */ + validateHeaders(headers, customHeaders) { } + defaultIdempotencyKey() { + return `stainless-node-retry-${uuid4()}`; + } + get(path, opts) { + return this.methodRequest('get', path, opts); + } + post(path, opts) { + return this.methodRequest('post', path, opts); + } + patch(path, opts) { + return this.methodRequest('patch', path, opts); + } + put(path, opts) { + return this.methodRequest('put', path, opts); + } + delete(path, opts) { + return this.methodRequest('delete', path, opts); + } + methodRequest(method, path, opts) { + return this.request(Promise.resolve(opts).then((opts) => ({ method, path, ...opts }))); + } + getAPIList(path, Page, opts) { + return this.requestAPIList(Page, { method: 'get', path, ...opts }); + } + calculateContentLength(body) { + if (typeof body === 'string') { + if (typeof Buffer !== 'undefined') { + return Buffer.byteLength(body, 'utf8').toString(); + } + if (typeof TextEncoder !== 'undefined') { + const encoder = new TextEncoder(); + const encoded = encoder.encode(body); + return encoded.length.toString(); + } + } + return null; + } + buildRequest(options) { + const { method, path, query, headers: headers = {} } = options; + const body = (0, uploads_1.isMultipartBody)(options.body) ? options.body.body + : options.body ? JSON.stringify(options.body, null, 2) + : null; + const contentLength = this.calculateContentLength(body); + const url = this.buildURL(path, query); + if ('timeout' in options) + validatePositiveInteger('timeout', options.timeout); + const timeout = options.timeout ?? this.timeout; + const httpAgent = options.httpAgent ?? this.httpAgent ?? (0, index_1.getDefaultAgent)(url); + const minAgentTimeout = timeout + 1000; + if (typeof httpAgent?.options?.timeout === 'number' && + minAgentTimeout > (httpAgent.options.timeout ?? 0)) { + // Allow any given request to bump our agent active socket timeout. + // This may seem strange, but leaking active sockets should be rare and not particularly problematic, + // and without mutating agent we would need to create more of them. + // This tradeoff optimizes for performance. + httpAgent.options.timeout = minAgentTimeout; + } + if (this.idempotencyHeader && method !== 'get') { + if (!options.idempotencyKey) + options.idempotencyKey = this.defaultIdempotencyKey(); + headers[this.idempotencyHeader] = options.idempotencyKey; + } + const reqHeaders = this.buildHeaders({ options, headers, contentLength }); + const req = { + method, + ...(body && { body: body }), + headers: reqHeaders, + ...(httpAgent && { agent: httpAgent }), + // @ts-ignore node-fetch uses a custom AbortSignal type that is + // not compatible with standard web types + signal: options.signal ?? null, + }; + return { req, url, timeout }; + } + buildHeaders({ options, headers, contentLength, }) { + const reqHeaders = {}; + if (contentLength) { + reqHeaders['content-length'] = contentLength; + } + const defaultHeaders = this.defaultHeaders(options); + applyHeadersMut(reqHeaders, defaultHeaders); + applyHeadersMut(reqHeaders, headers); + // let builtin fetch set the Content-Type for multipart bodies + if ((0, uploads_1.isMultipartBody)(options.body) && index_1.kind !== 'node') { + delete reqHeaders['content-type']; + } + this.validateHeaders(reqHeaders, headers); + return reqHeaders; + } + /** + * Used as a callback for mutating the given `FinalRequestOptions` object. + */ + async prepareOptions(options) { } + /** + * Used as a callback for mutating the given `RequestInit` object. + * + * This is useful for cases where you want to add certain headers based off of + * the request properties, e.g. `method` or `url`. + */ + async prepareRequest(request, { url, options }) { } + parseHeaders(headers) { + return (!headers ? {} + : Symbol.iterator in headers ? + Object.fromEntries(Array.from(headers).map((header) => [...header])) + : { ...headers }); + } + makeStatusError(status, error, message, headers) { + return error_1.APIError.generate(status, error, message, headers); + } + request(options, remainingRetries = null) { + return new APIPromise(this.makeRequest(options, remainingRetries)); + } + async makeRequest(optionsInput, retriesRemaining) { + const options = await optionsInput; + if (retriesRemaining == null) { + retriesRemaining = options.maxRetries ?? this.maxRetries; + } + await this.prepareOptions(options); + const { req, url, timeout } = this.buildRequest(options); + await this.prepareRequest(req, { url, options }); + debug('request', url, options, req.headers); + if (options.signal?.aborted) { + throw new error_1.APIUserAbortError(); + } + const controller = new AbortController(); + const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(exports.castToError); + if (response instanceof Error) { + if (options.signal?.aborted) { + throw new error_1.APIUserAbortError(); + } + if (retriesRemaining) { + return this.retryRequest(options, retriesRemaining); + } + if (response.name === 'AbortError') { + throw new error_1.APIConnectionTimeoutError(); + } + throw new error_1.APIConnectionError({ cause: response }); + } + const responseHeaders = (0, exports.createResponseHeaders)(response.headers); + if (!response.ok) { + if (retriesRemaining && this.shouldRetry(response)) { + const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; + debug(`response (error; ${retryMessage})`, response.status, url, responseHeaders); + return this.retryRequest(options, retriesRemaining, responseHeaders); + } + const errText = await response.text().catch((e) => (0, exports.castToError)(e).message); + const errJSON = (0, exports.safeJSON)(errText); + const errMessage = errJSON ? undefined : errText; + const retryMessage = retriesRemaining ? `(error; no more retries left)` : `(error; not retryable)`; + debug(`response (error; ${retryMessage})`, response.status, url, responseHeaders, errMessage); + const err = this.makeStatusError(response.status, errJSON, errMessage, responseHeaders); + throw err; + } + return { response, options, controller }; + } + requestAPIList(Page, options) { + const request = this.makeRequest(options, null); + return new PagePromise(this, request, Page); + } + buildURL(path, query) { + const url = isAbsoluteURL(path) ? + new URL(path) + : new URL(this.baseURL + (this.baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path)); + const defaultQuery = this.defaultQuery(); + if (!isEmptyObj(defaultQuery)) { + query = { ...defaultQuery, ...query }; + } + if (typeof query === 'object' && query && !Array.isArray(query)) { + url.search = this.stringifyQuery(query); + } + return url.toString(); + } + stringifyQuery(query) { + return Object.entries(query) + .filter(([_, value]) => typeof value !== 'undefined') + .map(([key, value]) => { + if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { + return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`; + } + if (value === null) { + return `${encodeURIComponent(key)}=`; + } + throw new error_1.OpenAIError(`Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`); + }) + .join('&'); + } + async fetchWithTimeout(url, init, ms, controller) { + const { signal, ...options } = init || {}; + if (signal) + signal.addEventListener('abort', () => controller.abort()); + const timeout = setTimeout(() => controller.abort(), ms); + return (this.getRequestClient() + // use undefined this binding; fetch errors if bound to something else in browser/cloudflare + .fetch.call(undefined, url, { signal: controller.signal, ...options }) + .finally(() => { + clearTimeout(timeout); + })); + } + getRequestClient() { + return { fetch: this.fetch }; + } + shouldRetry(response) { + // Note this is not a standard header. + const shouldRetryHeader = response.headers.get('x-should-retry'); + // If the server explicitly says whether or not to retry, obey. + if (shouldRetryHeader === 'true') + return true; + if (shouldRetryHeader === 'false') + return false; + // Retry on request timeouts. + if (response.status === 408) + return true; + // Retry on lock timeouts. + if (response.status === 409) + return true; + // Retry on rate limits. + if (response.status === 429) + return true; + // Retry internal errors. + if (response.status >= 500) + return true; + return false; + } + async retryRequest(options, retriesRemaining, responseHeaders) { + let timeoutMillis; + // Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it. + const retryAfterMillisHeader = responseHeaders?.['retry-after-ms']; + if (retryAfterMillisHeader) { + const timeoutMs = parseFloat(retryAfterMillisHeader); + if (!Number.isNaN(timeoutMs)) { + timeoutMillis = timeoutMs; + } + } + // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After + const retryAfterHeader = responseHeaders?.['retry-after']; + if (retryAfterHeader && !timeoutMillis) { + const timeoutSeconds = parseFloat(retryAfterHeader); + if (!Number.isNaN(timeoutSeconds)) { + timeoutMillis = timeoutSeconds * 1000; + } + else { + timeoutMillis = Date.parse(retryAfterHeader) - Date.now(); + } + } + // If the API asks us to wait a certain amount of time (and it's a reasonable amount), + // just do what it says, but otherwise calculate a default + if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) { + const maxRetries = options.maxRetries ?? this.maxRetries; + timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries); + } + await (0, exports.sleep)(timeoutMillis); + return this.makeRequest(options, retriesRemaining - 1); + } + calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) { + const initialRetryDelay = 0.5; + const maxRetryDelay = 8.0; + const numRetries = maxRetries - retriesRemaining; + // Apply exponential backoff, but not more than the max. + const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay); + // Apply some jitter, take up to at most 25 percent of the retry time. + const jitter = 1 - Math.random() * 0.25; + return sleepSeconds * jitter * 1000; + } + getUserAgent() { + return `${this.constructor.name}/JS ${version_1.VERSION}`; + } +} +exports.APIClient = APIClient; +class AbstractPage { + constructor(client, response, body, options) { + _AbstractPage_client.set(this, void 0); + __classPrivateFieldSet(this, _AbstractPage_client, client, "f"); + this.options = options; + this.response = response; + this.body = body; + } + hasNextPage() { + const items = this.getPaginatedItems(); + if (!items.length) + return false; + return this.nextPageInfo() != null; + } + async getNextPage() { + const nextInfo = this.nextPageInfo(); + if (!nextInfo) { + throw new error_1.OpenAIError('No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.'); + } + const nextOptions = { ...this.options }; + if ('params' in nextInfo && typeof nextOptions.query === 'object') { + nextOptions.query = { ...nextOptions.query, ...nextInfo.params }; + } + else if ('url' in nextInfo) { + const params = [...Object.entries(nextOptions.query || {}), ...nextInfo.url.searchParams.entries()]; + for (const [key, value] of params) { + nextInfo.url.searchParams.set(key, value); + } + nextOptions.query = undefined; + nextOptions.path = nextInfo.url.toString(); + } + return await __classPrivateFieldGet(this, _AbstractPage_client, "f").requestAPIList(this.constructor, nextOptions); + } + async *iterPages() { + // eslint-disable-next-line @typescript-eslint/no-this-alias + let page = this; + yield page; + while (page.hasNextPage()) { + page = await page.getNextPage(); + yield page; + } + } + async *[(_AbstractPage_client = new WeakMap(), Symbol.asyncIterator)]() { + for await (const page of this.iterPages()) { + for (const item of page.getPaginatedItems()) { + yield item; + } + } + } +} +exports.AbstractPage = AbstractPage; +/** + * This subclass of Promise will resolve to an instantiated Page once the request completes. + * + * It also implements AsyncIterable to allow auto-paginating iteration on an unawaited list call, eg: + * + * for await (const item of client.items.list()) { + * console.log(item) + * } + */ +class PagePromise extends APIPromise { + constructor(client, request, Page) { + super(request, async (props) => new Page(client, props.response, await defaultParseResponse(props), props.options)); + } + /** + * Allow auto-paginating iteration on an unawaited list call, eg: + * + * for await (const item of client.items.list()) { + * console.log(item) + * } + */ + async *[Symbol.asyncIterator]() { + const page = await this; + for await (const item of page) { + yield item; + } + } +} +exports.PagePromise = PagePromise; +const createResponseHeaders = (headers) => { + return new Proxy(Object.fromEntries( + // @ts-ignore + headers.entries()), { + get(target, name) { + const key = name.toString(); + return target[key.toLowerCase()] || target[key]; + }, + }); +}; +exports.createResponseHeaders = createResponseHeaders; +// This is required so that we can determine if a given object matches the RequestOptions +// type at runtime. While this requires duplication, it is enforced by the TypeScript +// compiler such that any missing / extraneous keys will cause an error. +const requestOptionsKeys = { + method: true, + path: true, + query: true, + body: true, + headers: true, + maxRetries: true, + stream: true, + timeout: true, + httpAgent: true, + signal: true, + idempotencyKey: true, + __binaryResponse: true, + __streamClass: true, +}; +const isRequestOptions = (obj) => { + return (typeof obj === 'object' && + obj !== null && + !isEmptyObj(obj) && + Object.keys(obj).every((k) => hasOwn(requestOptionsKeys, k))); +}; +exports.isRequestOptions = isRequestOptions; +const getPlatformProperties = () => { + if (typeof Deno !== 'undefined' && Deno.build != null) { + return { + 'X-Stainless-Lang': 'js', + 'X-Stainless-Package-Version': version_1.VERSION, + 'X-Stainless-OS': normalizePlatform(Deno.build.os), + 'X-Stainless-Arch': normalizeArch(Deno.build.arch), + 'X-Stainless-Runtime': 'deno', + 'X-Stainless-Runtime-Version': typeof Deno.version === 'string' ? Deno.version : Deno.version?.deno ?? 'unknown', + }; + } + if (typeof EdgeRuntime !== 'undefined') { + return { + 'X-Stainless-Lang': 'js', + 'X-Stainless-Package-Version': version_1.VERSION, + 'X-Stainless-OS': 'Unknown', + 'X-Stainless-Arch': `other:${EdgeRuntime}`, + 'X-Stainless-Runtime': 'edge', + 'X-Stainless-Runtime-Version': process.version, + }; + } + // Check if Node.js + if (Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]') { + return { + 'X-Stainless-Lang': 'js', + 'X-Stainless-Package-Version': version_1.VERSION, + 'X-Stainless-OS': normalizePlatform(process.platform), + 'X-Stainless-Arch': normalizeArch(process.arch), + 'X-Stainless-Runtime': 'node', + 'X-Stainless-Runtime-Version': process.version, + }; + } + const browserInfo = getBrowserInfo(); + if (browserInfo) { + return { + 'X-Stainless-Lang': 'js', + 'X-Stainless-Package-Version': version_1.VERSION, + 'X-Stainless-OS': 'Unknown', + 'X-Stainless-Arch': 'unknown', + 'X-Stainless-Runtime': `browser:${browserInfo.browser}`, + 'X-Stainless-Runtime-Version': browserInfo.version, + }; + } + // TODO add support for Cloudflare workers, etc. + return { + 'X-Stainless-Lang': 'js', + 'X-Stainless-Package-Version': version_1.VERSION, + 'X-Stainless-OS': 'Unknown', + 'X-Stainless-Arch': 'unknown', + 'X-Stainless-Runtime': 'unknown', + 'X-Stainless-Runtime-Version': 'unknown', + }; +}; +// Note: modified from https://github.com/JS-DevTools/host-environment/blob/b1ab79ecde37db5d6e163c050e54fe7d287d7c92/src/isomorphic.browser.ts +function getBrowserInfo() { + if (typeof navigator === 'undefined' || !navigator) { + return null; + } + // NOTE: The order matters here! + const browserPatterns = [ + { key: 'edge', pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'ie', pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'ie', pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'chrome', pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'firefox', pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'safari', pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ }, + ]; + // Find the FIRST matching browser + for (const { key, pattern } of browserPatterns) { + const match = pattern.exec(navigator.userAgent); + if (match) { + const major = match[1] || 0; + const minor = match[2] || 0; + const patch = match[3] || 0; + return { browser: key, version: `${major}.${minor}.${patch}` }; + } + } + return null; +} +const normalizeArch = (arch) => { + // Node docs: + // - https://nodejs.org/api/process.html#processarch + // Deno docs: + // - https://doc.deno.land/deno/stable/~/Deno.build + if (arch === 'x32') + return 'x32'; + if (arch === 'x86_64' || arch === 'x64') + return 'x64'; + if (arch === 'arm') + return 'arm'; + if (arch === 'aarch64' || arch === 'arm64') + return 'arm64'; + if (arch) + return `other:${arch}`; + return 'unknown'; +}; +const normalizePlatform = (platform) => { + // Node platforms: + // - https://nodejs.org/api/process.html#processplatform + // Deno platforms: + // - https://doc.deno.land/deno/stable/~/Deno.build + // - https://github.com/denoland/deno/issues/14799 + platform = platform.toLowerCase(); + // NOTE: this iOS check is untested and may not work + // Node does not work natively on IOS, there is a fork at + // https://github.com/nodejs-mobile/nodejs-mobile + // however it is unknown at the time of writing how to detect if it is running + if (platform.includes('ios')) + return 'iOS'; + if (platform === 'android') + return 'Android'; + if (platform === 'darwin') + return 'MacOS'; + if (platform === 'win32') + return 'Windows'; + if (platform === 'freebsd') + return 'FreeBSD'; + if (platform === 'openbsd') + return 'OpenBSD'; + if (platform === 'linux') + return 'Linux'; + if (platform) + return `Other:${platform}`; + return 'Unknown'; +}; +let _platformHeaders; +const getPlatformHeaders = () => { + return (_platformHeaders ?? (_platformHeaders = getPlatformProperties())); +}; +const safeJSON = (text) => { + try { + return JSON.parse(text); + } + catch (err) { + return undefined; + } +}; +exports.safeJSON = safeJSON; +// https://stackoverflow.com/a/19709846 +const startsWithSchemeRegexp = new RegExp('^(?:[a-z]+:)?//', 'i'); +const isAbsoluteURL = (url) => { + return startsWithSchemeRegexp.test(url); +}; +const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); +exports.sleep = sleep; +const validatePositiveInteger = (name, n) => { + if (typeof n !== 'number' || !Number.isInteger(n)) { + throw new error_1.OpenAIError(`${name} must be an integer`); + } + if (n < 0) { + throw new error_1.OpenAIError(`${name} must be a positive integer`); + } + return n; +}; +const castToError = (err) => { + if (err instanceof Error) + return err; + return new Error(err); +}; +exports.castToError = castToError; +const ensurePresent = (value) => { + if (value == null) + throw new error_1.OpenAIError(`Expected a value to be given but received ${value} instead.`); + return value; +}; +exports.ensurePresent = ensurePresent; +/** + * Read an environment variable. + * + * Trims beginning and trailing whitespace. + * + * Will return undefined if the environment variable doesn't exist or cannot be accessed. + */ +const readEnv = (env) => { + if (typeof process !== 'undefined') { + return process.env?.[env]?.trim() ?? undefined; + } + if (typeof Deno !== 'undefined') { + return Deno.env?.get?.(env)?.trim(); + } + return undefined; +}; +exports.readEnv = readEnv; +const coerceInteger = (value) => { + if (typeof value === 'number') + return Math.round(value); + if (typeof value === 'string') + return parseInt(value, 10); + throw new error_1.OpenAIError(`Could not coerce ${value} (type: ${typeof value}) into a number`); +}; +exports.coerceInteger = coerceInteger; +const coerceFloat = (value) => { + if (typeof value === 'number') + return value; + if (typeof value === 'string') + return parseFloat(value); + throw new error_1.OpenAIError(`Could not coerce ${value} (type: ${typeof value}) into a number`); +}; +exports.coerceFloat = coerceFloat; +const coerceBoolean = (value) => { + if (typeof value === 'boolean') + return value; + if (typeof value === 'string') + return value === 'true'; + return Boolean(value); +}; +exports.coerceBoolean = coerceBoolean; +const maybeCoerceInteger = (value) => { + if (value === undefined) { + return undefined; + } + return (0, exports.coerceInteger)(value); +}; +exports.maybeCoerceInteger = maybeCoerceInteger; +const maybeCoerceFloat = (value) => { + if (value === undefined) { + return undefined; + } + return (0, exports.coerceFloat)(value); +}; +exports.maybeCoerceFloat = maybeCoerceFloat; +const maybeCoerceBoolean = (value) => { + if (value === undefined) { + return undefined; + } + return (0, exports.coerceBoolean)(value); +}; +exports.maybeCoerceBoolean = maybeCoerceBoolean; +// https://stackoverflow.com/a/34491287 +function isEmptyObj(obj) { + if (!obj) + return true; + for (const _k in obj) + return false; + return true; +} +exports.isEmptyObj = isEmptyObj; +// https://eslint.org/docs/latest/rules/no-prototype-builtins +function hasOwn(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} +exports.hasOwn = hasOwn; +/** + * Copies headers from "newHeaders" onto "targetHeaders", + * using lower-case for all properties, + * ignoring any keys with undefined values, + * and deleting any keys with null values. + */ +function applyHeadersMut(targetHeaders, newHeaders) { + for (const k in newHeaders) { + if (!hasOwn(newHeaders, k)) + continue; + const lowerKey = k.toLowerCase(); + if (!lowerKey) + continue; + const val = newHeaders[k]; + if (val === null) { + delete targetHeaders[lowerKey]; + } + else if (val !== undefined) { + targetHeaders[lowerKey] = val; + } + } +} +function debug(action, ...args) { + if (typeof process !== 'undefined' && process?.env?.['DEBUG'] === 'true') { + console.log(`OpenAI:DEBUG:${action}`, ...args); + } +} +exports.debug = debug; +/** + * https://stackoverflow.com/a/2117523 + */ +const uuid4 = () => { + return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => { + const r = (Math.random() * 16) | 0; + const v = c === 'x' ? r : (r & 0x3) | 0x8; + return v.toString(16); + }); +}; +const isRunningInBrowser = () => { + return ( + // @ts-ignore + typeof window !== 'undefined' && + // @ts-ignore + typeof window.document !== 'undefined' && + // @ts-ignore + typeof navigator !== 'undefined'); +}; +exports.isRunningInBrowser = isRunningInBrowser; +const isHeadersProtocol = (headers) => { + return typeof headers?.get === 'function'; +}; +exports.isHeadersProtocol = isHeadersProtocol; +const getRequiredHeader = (headers, header) => { + const lowerCasedHeader = header.toLowerCase(); + if ((0, exports.isHeadersProtocol)(headers)) { + // to deal with the case where the header looks like Stainless-Event-Id + const intercapsHeader = header[0]?.toUpperCase() + + header.substring(1).replace(/([^\w])(\w)/g, (_m, g1, g2) => g1 + g2.toUpperCase()); + for (const key of [header, lowerCasedHeader, header.toUpperCase(), intercapsHeader]) { + const value = headers.get(key); + if (value) { + return value; + } + } + } + for (const [key, value] of Object.entries(headers)) { + if (key.toLowerCase() === lowerCasedHeader) { + if (Array.isArray(value)) { + if (value.length <= 1) + return value[0]; + console.warn(`Received ${value.length} entries for the ${header} header, using the first entry.`); + return value[0]; + } + return value; + } + } + throw new Error(`Could not find ${header} header`); +}; +exports.getRequiredHeader = getRequiredHeader; +/** + * Encodes a string to Base64 format. + */ +const toBase64 = (str) => { + if (!str) + return ''; + if (typeof Buffer !== 'undefined') { + return Buffer.from(str).toString('base64'); + } + if (typeof btoa !== 'undefined') { + return btoa(str); + } + throw new error_1.OpenAIError('Cannot generate b64 string; Expected `Buffer` or `btoa` to be defined'); +}; +exports.toBase64 = toBase64; +function isObj(obj) { + return obj != null && typeof obj === 'object' && !Array.isArray(obj); +} +exports.isObj = isObj; +//# sourceMappingURL=core.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/core.js.map b/backend/node_modules/openai/core.js.map new file mode 100644 index 0000000000000000000000000000000000000000..4fd3ad6c309d27fe8f108566bdecceab2fc34fc7 --- /dev/null +++ b/backend/node_modules/openai/core.js.map @@ -0,0 +1 @@ +{"version":3,"file":"core.js","sourceRoot":"","sources":["src/core.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,0CAAoC;AACpC,8CAAqC;AACrC,sCAMiB;AACjB,6CAUwB;AAExB,0CAA4C;AAC5C,wCAKmB;AAJjB,2HAAA,gCAAgC,OAAA;AAChC,sHAAA,2BAA2B,OAAA;AAC3B,qGAAA,UAAU,OAAA;AAcZ,KAAK,UAAU,oBAAoB,CAAI,KAAuB;IAC5D,MAAM,EAAE,QAAQ,EAAE,GAAG,KAAK,CAAC;IAC3B,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,EAAE;QACxB,KAAK,CAAC,UAAU,EAAE,QAAQ,CAAC,MAAM,EAAE,QAAQ,CAAC,GAAG,EAAE,QAAQ,CAAC,OAAO,EAAE,QAAQ,CAAC,IAAI,CAAC,CAAC;QAElF,6EAA6E;QAC7E,4EAA4E;QAE5E,IAAI,KAAK,CAAC,OAAO,CAAC,aAAa,EAAE;YAC/B,OAAO,KAAK,CAAC,OAAO,CAAC,aAAa,CAAC,eAAe,CAAC,QAAQ,EAAE,KAAK,CAAC,UAA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,MAAM,IAAI,CAAC;oBAAE,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC;gBACvC,OAAO,CAAC,IAAI,CAAC,YAAY,KAAK,CAAC,MAAM,oBAAoB,MAAM,iCAAiC,CAAC,CAAC;gBAClG,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC;aACjB;YACD,OAAO,KAAK,CAAC;SACd;KACF;IAED,MAAM,IAAI,KAAK,CAAC,kBAAkB,MAAM,SAAS,CAAC,CAAC;AACrD,CAAC,CAAC;AA3BW,QAAA,iBAAiB,qBA2B5B;AAEF;;GAEG;AACI,MAAM,QAAQ,GAAG,CAAC,GAA8B,EAAU,EAAE;IACjE,IAAI,CAAC,GAAG;QAAE,OAAO,EAAE,CAAC;IACpB,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE;QACjC,OAAO,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;KAC5C;IAED,IAAI,OAAO,IAAI,KAAK,WAAW,EAAE;QAC/B,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC;KAClB;IAED,MAAM,IAAI,mBAAW,CAAC,uEAAuE,CAAC,CAAC;AACjG,CAAC,CAAC;AAXW,QAAA,QAAQ,YAWnB;AAEF,SAAgB,KAAK,CAAC,GAAY;IAChC,OAAO,GAAG,IAAI,IAAI,IAAI,OAAO,GAAG,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;AACvE,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/backend/node_modules/openai/core.mjs b/backend/node_modules/openai/core.mjs new file mode 100644 index 0000000000000000000000000000000000000000..2a8e9a6de2975a6a3e4af9f8d9ff62cfe4ee577e --- /dev/null +++ b/backend/node_modules/openai/core.mjs @@ -0,0 +1,848 @@ +var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +}; +var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var _AbstractPage_client; +import { VERSION } from "./version.mjs"; +import { Stream } from "./streaming.mjs"; +import { OpenAIError, APIError, APIConnectionError, APIConnectionTimeoutError, APIUserAbortError, } from "./error.mjs"; +import { kind as shimsKind, getDefaultAgent, fetch, } from "./_shims/index.mjs"; +import { isMultipartBody } from "./uploads.mjs"; +export { maybeMultipartFormRequestOptions, multipartFormRequestOptions, createForm, } from "./uploads.mjs"; +async function defaultParseResponse(props) { + const { response } = props; + if (props.options.stream) { + debug('response', response.status, response.url, response.headers, response.body); + // Note: there is an invariant here that isn't represented in the type system + // that if you set `stream: true` the response type must also be `Stream` + if (props.options.__streamClass) { + return props.options.__streamClass.fromSSEResponse(response, props.controller); + } + return Stream.fromSSEResponse(response, props.controller); + } + // fetch refuses to read the body when the status code is 204. + if (response.status === 204) { + return null; + } + if (props.options.__binaryResponse) { + return response; + } + const contentType = response.headers.get('content-type'); + const isJSON = contentType?.includes('application/json') || contentType?.includes('application/vnd.api+json'); + if (isJSON) { + const json = await response.json(); + debug('response', response.status, response.url, response.headers, json); + return json; + } + const text = await response.text(); + debug('response', response.status, response.url, response.headers, text); + // TODO handle blob, arraybuffer, other content types, etc. + return text; +} +/** + * A subclass of `Promise` providing additional helper methods + * for interacting with the SDK. + */ +export class APIPromise extends Promise { + constructor(responsePromise, parseResponse = defaultParseResponse) { + super((resolve) => { + // this is maybe a bit weird but this has to be a no-op to not implicitly + // parse the response body; instead .then, .catch, .finally are overridden + // to parse the response + resolve(null); + }); + this.responsePromise = responsePromise; + this.parseResponse = parseResponse; + } + _thenUnwrap(transform) { + return new APIPromise(this.responsePromise, async (props) => transform(await this.parseResponse(props))); + } + /** + * Gets the raw `Response` instance instead of parsing the response + * data. + * + * If you want to parse the response body but still get the `Response` + * instance, you can use {@link withResponse()}. + * + * 👋 Getting the wrong TypeScript type for `Response`? + * Try setting `"moduleResolution": "NodeNext"` if you can, + * or add one of these imports before your first `import … from 'openai'`: + * - `import 'openai/shims/node'` (if you're running on Node) + * - `import 'openai/shims/web'` (otherwise) + */ + asResponse() { + return this.responsePromise.then((p) => p.response); + } + /** + * Gets the parsed response data and the raw `Response` instance. + * + * If you just want to get the raw `Response` instance without parsing it, + * you can use {@link asResponse()}. + * + * + * 👋 Getting the wrong TypeScript type for `Response`? + * Try setting `"moduleResolution": "NodeNext"` if you can, + * or add one of these imports before your first `import … from 'openai'`: + * - `import 'openai/shims/node'` (if you're running on Node) + * - `import 'openai/shims/web'` (otherwise) + */ + async withResponse() { + const [data, response] = await Promise.all([this.parse(), this.asResponse()]); + return { data, response }; + } + parse() { + if (!this.parsedPromise) { + this.parsedPromise = this.responsePromise.then(this.parseResponse); + } + return this.parsedPromise; + } + then(onfulfilled, onrejected) { + return this.parse().then(onfulfilled, onrejected); + } + catch(onrejected) { + return this.parse().catch(onrejected); + } + finally(onfinally) { + return this.parse().finally(onfinally); + } +} +export class APIClient { + constructor({ baseURL, maxRetries = 2, timeout = 600000, // 10 minutes + httpAgent, fetch: overridenFetch, }) { + this.baseURL = baseURL; + this.maxRetries = validatePositiveInteger('maxRetries', maxRetries); + this.timeout = validatePositiveInteger('timeout', timeout); + this.httpAgent = httpAgent; + this.fetch = overridenFetch ?? fetch; + } + authHeaders(opts) { + return {}; + } + /** + * Override this to add your own default headers, for example: + * + * { + * ...super.defaultHeaders(), + * Authorization: 'Bearer 123', + * } + */ + defaultHeaders(opts) { + return { + Accept: 'application/json', + 'Content-Type': 'application/json', + 'User-Agent': this.getUserAgent(), + ...getPlatformHeaders(), + ...this.authHeaders(opts), + }; + } + /** + * Override this to add your own headers validation: + */ + validateHeaders(headers, customHeaders) { } + defaultIdempotencyKey() { + return `stainless-node-retry-${uuid4()}`; + } + get(path, opts) { + return this.methodRequest('get', path, opts); + } + post(path, opts) { + return this.methodRequest('post', path, opts); + } + patch(path, opts) { + return this.methodRequest('patch', path, opts); + } + put(path, opts) { + return this.methodRequest('put', path, opts); + } + delete(path, opts) { + return this.methodRequest('delete', path, opts); + } + methodRequest(method, path, opts) { + return this.request(Promise.resolve(opts).then((opts) => ({ method, path, ...opts }))); + } + getAPIList(path, Page, opts) { + return this.requestAPIList(Page, { method: 'get', path, ...opts }); + } + calculateContentLength(body) { + if (typeof body === 'string') { + if (typeof Buffer !== 'undefined') { + return Buffer.byteLength(body, 'utf8').toString(); + } + if (typeof TextEncoder !== 'undefined') { + const encoder = new TextEncoder(); + const encoded = encoder.encode(body); + return encoded.length.toString(); + } + } + return null; + } + buildRequest(options) { + const { method, path, query, headers: headers = {} } = options; + const body = isMultipartBody(options.body) ? options.body.body + : options.body ? JSON.stringify(options.body, null, 2) + : null; + const contentLength = this.calculateContentLength(body); + const url = this.buildURL(path, query); + if ('timeout' in options) + validatePositiveInteger('timeout', options.timeout); + const timeout = options.timeout ?? this.timeout; + const httpAgent = options.httpAgent ?? this.httpAgent ?? getDefaultAgent(url); + const minAgentTimeout = timeout + 1000; + if (typeof httpAgent?.options?.timeout === 'number' && + minAgentTimeout > (httpAgent.options.timeout ?? 0)) { + // Allow any given request to bump our agent active socket timeout. + // This may seem strange, but leaking active sockets should be rare and not particularly problematic, + // and without mutating agent we would need to create more of them. + // This tradeoff optimizes for performance. + httpAgent.options.timeout = minAgentTimeout; + } + if (this.idempotencyHeader && method !== 'get') { + if (!options.idempotencyKey) + options.idempotencyKey = this.defaultIdempotencyKey(); + headers[this.idempotencyHeader] = options.idempotencyKey; + } + const reqHeaders = this.buildHeaders({ options, headers, contentLength }); + const req = { + method, + ...(body && { body: body }), + headers: reqHeaders, + ...(httpAgent && { agent: httpAgent }), + // @ts-ignore node-fetch uses a custom AbortSignal type that is + // not compatible with standard web types + signal: options.signal ?? null, + }; + return { req, url, timeout }; + } + buildHeaders({ options, headers, contentLength, }) { + const reqHeaders = {}; + if (contentLength) { + reqHeaders['content-length'] = contentLength; + } + const defaultHeaders = this.defaultHeaders(options); + applyHeadersMut(reqHeaders, defaultHeaders); + applyHeadersMut(reqHeaders, headers); + // let builtin fetch set the Content-Type for multipart bodies + if (isMultipartBody(options.body) && shimsKind !== 'node') { + delete reqHeaders['content-type']; + } + this.validateHeaders(reqHeaders, headers); + return reqHeaders; + } + /** + * Used as a callback for mutating the given `FinalRequestOptions` object. + */ + async prepareOptions(options) { } + /** + * Used as a callback for mutating the given `RequestInit` object. + * + * This is useful for cases where you want to add certain headers based off of + * the request properties, e.g. `method` or `url`. + */ + async prepareRequest(request, { url, options }) { } + parseHeaders(headers) { + return (!headers ? {} + : Symbol.iterator in headers ? + Object.fromEntries(Array.from(headers).map((header) => [...header])) + : { ...headers }); + } + makeStatusError(status, error, message, headers) { + return APIError.generate(status, error, message, headers); + } + request(options, remainingRetries = null) { + return new APIPromise(this.makeRequest(options, remainingRetries)); + } + async makeRequest(optionsInput, retriesRemaining) { + const options = await optionsInput; + if (retriesRemaining == null) { + retriesRemaining = options.maxRetries ?? this.maxRetries; + } + await this.prepareOptions(options); + const { req, url, timeout } = this.buildRequest(options); + await this.prepareRequest(req, { url, options }); + debug('request', url, options, req.headers); + if (options.signal?.aborted) { + throw new APIUserAbortError(); + } + const controller = new AbortController(); + const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError); + if (response instanceof Error) { + if (options.signal?.aborted) { + throw new APIUserAbortError(); + } + if (retriesRemaining) { + return this.retryRequest(options, retriesRemaining); + } + if (response.name === 'AbortError') { + throw new APIConnectionTimeoutError(); + } + throw new APIConnectionError({ cause: response }); + } + const responseHeaders = createResponseHeaders(response.headers); + if (!response.ok) { + if (retriesRemaining && this.shouldRetry(response)) { + const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; + debug(`response (error; ${retryMessage})`, response.status, url, responseHeaders); + return this.retryRequest(options, retriesRemaining, responseHeaders); + } + const errText = await response.text().catch((e) => castToError(e).message); + const errJSON = safeJSON(errText); + const errMessage = errJSON ? undefined : errText; + const retryMessage = retriesRemaining ? `(error; no more retries left)` : `(error; not retryable)`; + debug(`response (error; ${retryMessage})`, response.status, url, responseHeaders, errMessage); + const err = this.makeStatusError(response.status, errJSON, errMessage, responseHeaders); + throw err; + } + return { response, options, controller }; + } + requestAPIList(Page, options) { + const request = this.makeRequest(options, null); + return new PagePromise(this, request, Page); + } + buildURL(path, query) { + const url = isAbsoluteURL(path) ? + new URL(path) + : new URL(this.baseURL + (this.baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path)); + const defaultQuery = this.defaultQuery(); + if (!isEmptyObj(defaultQuery)) { + query = { ...defaultQuery, ...query }; + } + if (typeof query === 'object' && query && !Array.isArray(query)) { + url.search = this.stringifyQuery(query); + } + return url.toString(); + } + stringifyQuery(query) { + return Object.entries(query) + .filter(([_, value]) => typeof value !== 'undefined') + .map(([key, value]) => { + if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { + return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`; + } + if (value === null) { + return `${encodeURIComponent(key)}=`; + } + throw new OpenAIError(`Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`); + }) + .join('&'); + } + async fetchWithTimeout(url, init, ms, controller) { + const { signal, ...options } = init || {}; + if (signal) + signal.addEventListener('abort', () => controller.abort()); + const timeout = setTimeout(() => controller.abort(), ms); + return (this.getRequestClient() + // use undefined this binding; fetch errors if bound to something else in browser/cloudflare + .fetch.call(undefined, url, { signal: controller.signal, ...options }) + .finally(() => { + clearTimeout(timeout); + })); + } + getRequestClient() { + return { fetch: this.fetch }; + } + shouldRetry(response) { + // Note this is not a standard header. + const shouldRetryHeader = response.headers.get('x-should-retry'); + // If the server explicitly says whether or not to retry, obey. + if (shouldRetryHeader === 'true') + return true; + if (shouldRetryHeader === 'false') + return false; + // Retry on request timeouts. + if (response.status === 408) + return true; + // Retry on lock timeouts. + if (response.status === 409) + return true; + // Retry on rate limits. + if (response.status === 429) + return true; + // Retry internal errors. + if (response.status >= 500) + return true; + return false; + } + async retryRequest(options, retriesRemaining, responseHeaders) { + let timeoutMillis; + // Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it. + const retryAfterMillisHeader = responseHeaders?.['retry-after-ms']; + if (retryAfterMillisHeader) { + const timeoutMs = parseFloat(retryAfterMillisHeader); + if (!Number.isNaN(timeoutMs)) { + timeoutMillis = timeoutMs; + } + } + // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After + const retryAfterHeader = responseHeaders?.['retry-after']; + if (retryAfterHeader && !timeoutMillis) { + const timeoutSeconds = parseFloat(retryAfterHeader); + if (!Number.isNaN(timeoutSeconds)) { + timeoutMillis = timeoutSeconds * 1000; + } + else { + timeoutMillis = Date.parse(retryAfterHeader) - Date.now(); + } + } + // If the API asks us to wait a certain amount of time (and it's a reasonable amount), + // just do what it says, but otherwise calculate a default + if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) { + const maxRetries = options.maxRetries ?? this.maxRetries; + timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries); + } + await sleep(timeoutMillis); + return this.makeRequest(options, retriesRemaining - 1); + } + calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) { + const initialRetryDelay = 0.5; + const maxRetryDelay = 8.0; + const numRetries = maxRetries - retriesRemaining; + // Apply exponential backoff, but not more than the max. + const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay); + // Apply some jitter, take up to at most 25 percent of the retry time. + const jitter = 1 - Math.random() * 0.25; + return sleepSeconds * jitter * 1000; + } + getUserAgent() { + return `${this.constructor.name}/JS ${VERSION}`; + } +} +export class AbstractPage { + constructor(client, response, body, options) { + _AbstractPage_client.set(this, void 0); + __classPrivateFieldSet(this, _AbstractPage_client, client, "f"); + this.options = options; + this.response = response; + this.body = body; + } + hasNextPage() { + const items = this.getPaginatedItems(); + if (!items.length) + return false; + return this.nextPageInfo() != null; + } + async getNextPage() { + const nextInfo = this.nextPageInfo(); + if (!nextInfo) { + throw new OpenAIError('No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.'); + } + const nextOptions = { ...this.options }; + if ('params' in nextInfo && typeof nextOptions.query === 'object') { + nextOptions.query = { ...nextOptions.query, ...nextInfo.params }; + } + else if ('url' in nextInfo) { + const params = [...Object.entries(nextOptions.query || {}), ...nextInfo.url.searchParams.entries()]; + for (const [key, value] of params) { + nextInfo.url.searchParams.set(key, value); + } + nextOptions.query = undefined; + nextOptions.path = nextInfo.url.toString(); + } + return await __classPrivateFieldGet(this, _AbstractPage_client, "f").requestAPIList(this.constructor, nextOptions); + } + async *iterPages() { + // eslint-disable-next-line @typescript-eslint/no-this-alias + let page = this; + yield page; + while (page.hasNextPage()) { + page = await page.getNextPage(); + yield page; + } + } + async *[(_AbstractPage_client = new WeakMap(), Symbol.asyncIterator)]() { + for await (const page of this.iterPages()) { + for (const item of page.getPaginatedItems()) { + yield item; + } + } + } +} +/** + * This subclass of Promise will resolve to an instantiated Page once the request completes. + * + * It also implements AsyncIterable to allow auto-paginating iteration on an unawaited list call, eg: + * + * for await (const item of client.items.list()) { + * console.log(item) + * } + */ +export class PagePromise extends APIPromise { + constructor(client, request, Page) { + super(request, async (props) => new Page(client, props.response, await defaultParseResponse(props), props.options)); + } + /** + * Allow auto-paginating iteration on an unawaited list call, eg: + * + * for await (const item of client.items.list()) { + * console.log(item) + * } + */ + async *[Symbol.asyncIterator]() { + const page = await this; + for await (const item of page) { + yield item; + } + } +} +export const createResponseHeaders = (headers) => { + return new Proxy(Object.fromEntries( + // @ts-ignore + headers.entries()), { + get(target, name) { + const key = name.toString(); + return target[key.toLowerCase()] || target[key]; + }, + }); +}; +// This is required so that we can determine if a given object matches the RequestOptions +// type at runtime. While this requires duplication, it is enforced by the TypeScript +// compiler such that any missing / extraneous keys will cause an error. +const requestOptionsKeys = { + method: true, + path: true, + query: true, + body: true, + headers: true, + maxRetries: true, + stream: true, + timeout: true, + httpAgent: true, + signal: true, + idempotencyKey: true, + __binaryResponse: true, + __streamClass: true, +}; +export const isRequestOptions = (obj) => { + return (typeof obj === 'object' && + obj !== null && + !isEmptyObj(obj) && + Object.keys(obj).every((k) => hasOwn(requestOptionsKeys, k))); +}; +const getPlatformProperties = () => { + if (typeof Deno !== 'undefined' && Deno.build != null) { + return { + 'X-Stainless-Lang': 'js', + 'X-Stainless-Package-Version': VERSION, + 'X-Stainless-OS': normalizePlatform(Deno.build.os), + 'X-Stainless-Arch': normalizeArch(Deno.build.arch), + 'X-Stainless-Runtime': 'deno', + 'X-Stainless-Runtime-Version': typeof Deno.version === 'string' ? Deno.version : Deno.version?.deno ?? 'unknown', + }; + } + if (typeof EdgeRuntime !== 'undefined') { + return { + 'X-Stainless-Lang': 'js', + 'X-Stainless-Package-Version': VERSION, + 'X-Stainless-OS': 'Unknown', + 'X-Stainless-Arch': `other:${EdgeRuntime}`, + 'X-Stainless-Runtime': 'edge', + 'X-Stainless-Runtime-Version': process.version, + }; + } + // Check if Node.js + if (Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]') { + return { + 'X-Stainless-Lang': 'js', + 'X-Stainless-Package-Version': VERSION, + 'X-Stainless-OS': normalizePlatform(process.platform), + 'X-Stainless-Arch': normalizeArch(process.arch), + 'X-Stainless-Runtime': 'node', + 'X-Stainless-Runtime-Version': process.version, + }; + } + const browserInfo = getBrowserInfo(); + if (browserInfo) { + return { + 'X-Stainless-Lang': 'js', + 'X-Stainless-Package-Version': VERSION, + 'X-Stainless-OS': 'Unknown', + 'X-Stainless-Arch': 'unknown', + 'X-Stainless-Runtime': `browser:${browserInfo.browser}`, + 'X-Stainless-Runtime-Version': browserInfo.version, + }; + } + // TODO add support for Cloudflare workers, etc. + return { + 'X-Stainless-Lang': 'js', + 'X-Stainless-Package-Version': VERSION, + 'X-Stainless-OS': 'Unknown', + 'X-Stainless-Arch': 'unknown', + 'X-Stainless-Runtime': 'unknown', + 'X-Stainless-Runtime-Version': 'unknown', + }; +}; +// Note: modified from https://github.com/JS-DevTools/host-environment/blob/b1ab79ecde37db5d6e163c050e54fe7d287d7c92/src/isomorphic.browser.ts +function getBrowserInfo() { + if (typeof navigator === 'undefined' || !navigator) { + return null; + } + // NOTE: The order matters here! + const browserPatterns = [ + { key: 'edge', pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'ie', pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'ie', pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'chrome', pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'firefox', pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'safari', pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ }, + ]; + // Find the FIRST matching browser + for (const { key, pattern } of browserPatterns) { + const match = pattern.exec(navigator.userAgent); + if (match) { + const major = match[1] || 0; + const minor = match[2] || 0; + const patch = match[3] || 0; + return { browser: key, version: `${major}.${minor}.${patch}` }; + } + } + return null; +} +const normalizeArch = (arch) => { + // Node docs: + // - https://nodejs.org/api/process.html#processarch + // Deno docs: + // - https://doc.deno.land/deno/stable/~/Deno.build + if (arch === 'x32') + return 'x32'; + if (arch === 'x86_64' || arch === 'x64') + return 'x64'; + if (arch === 'arm') + return 'arm'; + if (arch === 'aarch64' || arch === 'arm64') + return 'arm64'; + if (arch) + return `other:${arch}`; + return 'unknown'; +}; +const normalizePlatform = (platform) => { + // Node platforms: + // - https://nodejs.org/api/process.html#processplatform + // Deno platforms: + // - https://doc.deno.land/deno/stable/~/Deno.build + // - https://github.com/denoland/deno/issues/14799 + platform = platform.toLowerCase(); + // NOTE: this iOS check is untested and may not work + // Node does not work natively on IOS, there is a fork at + // https://github.com/nodejs-mobile/nodejs-mobile + // however it is unknown at the time of writing how to detect if it is running + if (platform.includes('ios')) + return 'iOS'; + if (platform === 'android') + return 'Android'; + if (platform === 'darwin') + return 'MacOS'; + if (platform === 'win32') + return 'Windows'; + if (platform === 'freebsd') + return 'FreeBSD'; + if (platform === 'openbsd') + return 'OpenBSD'; + if (platform === 'linux') + return 'Linux'; + if (platform) + return `Other:${platform}`; + return 'Unknown'; +}; +let _platformHeaders; +const getPlatformHeaders = () => { + return (_platformHeaders ?? (_platformHeaders = getPlatformProperties())); +}; +export const safeJSON = (text) => { + try { + return JSON.parse(text); + } + catch (err) { + return undefined; + } +}; +// https://stackoverflow.com/a/19709846 +const startsWithSchemeRegexp = new RegExp('^(?:[a-z]+:)?//', 'i'); +const isAbsoluteURL = (url) => { + return startsWithSchemeRegexp.test(url); +}; +export const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); +const validatePositiveInteger = (name, n) => { + if (typeof n !== 'number' || !Number.isInteger(n)) { + throw new OpenAIError(`${name} must be an integer`); + } + if (n < 0) { + throw new OpenAIError(`${name} must be a positive integer`); + } + return n; +}; +export const castToError = (err) => { + if (err instanceof Error) + return err; + return new Error(err); +}; +export const ensurePresent = (value) => { + if (value == null) + throw new OpenAIError(`Expected a value to be given but received ${value} instead.`); + return value; +}; +/** + * Read an environment variable. + * + * Trims beginning and trailing whitespace. + * + * Will return undefined if the environment variable doesn't exist or cannot be accessed. + */ +export const readEnv = (env) => { + if (typeof process !== 'undefined') { + return process.env?.[env]?.trim() ?? undefined; + } + if (typeof Deno !== 'undefined') { + return Deno.env?.get?.(env)?.trim(); + } + return undefined; +}; +export const coerceInteger = (value) => { + if (typeof value === 'number') + return Math.round(value); + if (typeof value === 'string') + return parseInt(value, 10); + throw new OpenAIError(`Could not coerce ${value} (type: ${typeof value}) into a number`); +}; +export const coerceFloat = (value) => { + if (typeof value === 'number') + return value; + if (typeof value === 'string') + return parseFloat(value); + throw new OpenAIError(`Could not coerce ${value} (type: ${typeof value}) into a number`); +}; +export const coerceBoolean = (value) => { + if (typeof value === 'boolean') + return value; + if (typeof value === 'string') + return value === 'true'; + return Boolean(value); +}; +export const maybeCoerceInteger = (value) => { + if (value === undefined) { + return undefined; + } + return coerceInteger(value); +}; +export const maybeCoerceFloat = (value) => { + if (value === undefined) { + return undefined; + } + return coerceFloat(value); +}; +export const maybeCoerceBoolean = (value) => { + if (value === undefined) { + return undefined; + } + return coerceBoolean(value); +}; +// https://stackoverflow.com/a/34491287 +export function isEmptyObj(obj) { + if (!obj) + return true; + for (const _k in obj) + return false; + return true; +} +// https://eslint.org/docs/latest/rules/no-prototype-builtins +export function hasOwn(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} +/** + * Copies headers from "newHeaders" onto "targetHeaders", + * using lower-case for all properties, + * ignoring any keys with undefined values, + * and deleting any keys with null values. + */ +function applyHeadersMut(targetHeaders, newHeaders) { + for (const k in newHeaders) { + if (!hasOwn(newHeaders, k)) + continue; + const lowerKey = k.toLowerCase(); + if (!lowerKey) + continue; + const val = newHeaders[k]; + if (val === null) { + delete targetHeaders[lowerKey]; + } + else if (val !== undefined) { + targetHeaders[lowerKey] = val; + } + } +} +export function debug(action, ...args) { + if (typeof process !== 'undefined' && process?.env?.['DEBUG'] === 'true') { + console.log(`OpenAI:DEBUG:${action}`, ...args); + } +} +/** + * https://stackoverflow.com/a/2117523 + */ +const uuid4 = () => { + return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => { + const r = (Math.random() * 16) | 0; + const v = c === 'x' ? r : (r & 0x3) | 0x8; + return v.toString(16); + }); +}; +export const isRunningInBrowser = () => { + return ( + // @ts-ignore + typeof window !== 'undefined' && + // @ts-ignore + typeof window.document !== 'undefined' && + // @ts-ignore + typeof navigator !== 'undefined'); +}; +export const isHeadersProtocol = (headers) => { + return typeof headers?.get === 'function'; +}; +export const getRequiredHeader = (headers, header) => { + const lowerCasedHeader = header.toLowerCase(); + if (isHeadersProtocol(headers)) { + // to deal with the case where the header looks like Stainless-Event-Id + const intercapsHeader = header[0]?.toUpperCase() + + header.substring(1).replace(/([^\w])(\w)/g, (_m, g1, g2) => g1 + g2.toUpperCase()); + for (const key of [header, lowerCasedHeader, header.toUpperCase(), intercapsHeader]) { + const value = headers.get(key); + if (value) { + return value; + } + } + } + for (const [key, value] of Object.entries(headers)) { + if (key.toLowerCase() === lowerCasedHeader) { + if (Array.isArray(value)) { + if (value.length <= 1) + return value[0]; + console.warn(`Received ${value.length} entries for the ${header} header, using the first entry.`); + return value[0]; + } + return value; + } + } + throw new Error(`Could not find ${header} header`); +}; +/** + * Encodes a string to Base64 format. + */ +export const toBase64 = (str) => { + if (!str) + return ''; + if (typeof Buffer !== 'undefined') { + return Buffer.from(str).toString('base64'); + } + if (typeof btoa !== 'undefined') { + return btoa(str); + } + throw new OpenAIError('Cannot generate b64 string; Expected `Buffer` or `btoa` to be defined'); +}; +export function isObj(obj) { + return obj != null && typeof obj === 'object' && !Array.isArray(obj); +} +//# sourceMappingURL=core.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/core.mjs.map b/backend/node_modules/openai/core.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..00839f61cb77da46eeba35a7d969ed2fa0a9b9d2 --- /dev/null +++ b/backend/node_modules/openai/core.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"core.mjs","sourceRoot":"","sources":["src/core.ts"],"names":[],"mappings":";;;;;;;;;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,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/openai/error.d.ts b/backend/node_modules/openai/error.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4ac9f9d8bcf68095c713feae8932d6348d0dbcc3 --- /dev/null +++ b/backend/node_modules/openai/error.d.ts @@ -0,0 +1,57 @@ +import { Headers } from "./core.js"; +export declare class OpenAIError extends Error { +} +export declare class APIError extends OpenAIError { + readonly status: number | undefined; + readonly headers: Headers | undefined; + readonly error: Object | undefined; + readonly code: string | null | undefined; + readonly param: string | null | undefined; + readonly type: string | undefined; + readonly request_id: string | null | undefined; + constructor(status: number | undefined, error: Object | undefined, message: string | undefined, headers: Headers | undefined); + private static makeMessage; + static generate(status: number | undefined, errorResponse: Object | undefined, message: string | undefined, headers: Headers | undefined): APIError; +} +export declare class APIUserAbortError extends APIError { + readonly status: undefined; + constructor({ message }?: { + message?: string; + }); +} +export declare class APIConnectionError extends APIError { + readonly status: undefined; + constructor({ message, cause }: { + message?: string; + cause?: Error | undefined; + }); +} +export declare class APIConnectionTimeoutError extends APIConnectionError { + constructor({ message }?: { + message?: string; + }); +} +export declare class BadRequestError extends APIError { + readonly status: 400; +} +export declare class AuthenticationError extends APIError { + readonly status: 401; +} +export declare class PermissionDeniedError extends APIError { + readonly status: 403; +} +export declare class NotFoundError extends APIError { + readonly status: 404; +} +export declare class ConflictError extends APIError { + readonly status: 409; +} +export declare class UnprocessableEntityError extends APIError { + readonly status: 422; +} +export declare class RateLimitError extends APIError { + readonly status: 429; +} +export declare class InternalServerError extends APIError { +} +//# sourceMappingURL=error.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/error.d.ts.map b/backend/node_modules/openai/error.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..32508566ba296494ebd46e77c2dd41840905c7da --- /dev/null +++ b/backend/node_modules/openai/error.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"error.d.ts","sourceRoot":"","sources":["src/error.ts"],"names":[],"mappings":"AAEA,OAAO,EAAe,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KAAK,GAAG,SAAS,CAAA;KAAE;CAMhF;AAED,qBAAa,yBAA0B,SAAQ,kBAAkB;gBACnD,EAAE,OAAO,EAAE,GAAE;QAAE,OAAO,CAAC,EAAE,MAAM,CAAA;KAAO;CAGnD;AAED,qBAAa,eAAgB,SAAQ,QAAQ;IAC3C,SAAkB,MAAM,EAAE,GAAG,CAAO;CACrC;AAED,qBAAa,mBAAoB,SAAQ,QAAQ;IAC/C,SAAkB,MAAM,EAAE,GAAG,CAAO;CACrC;AAED,qBAAa,qBAAsB,SAAQ,QAAQ;IACjD,SAAkB,MAAM,EAAE,GAAG,CAAO;CACrC;AAED,qBAAa,aAAc,SAAQ,QAAQ;IACzC,SAAkB,MAAM,EAAE,GAAG,CAAO;CACrC;AAED,qBAAa,aAAc,SAAQ,QAAQ;IACzC,SAAkB,MAAM,EAAE,GAAG,CAAO;CACrC;AAED,qBAAa,wBAAyB,SAAQ,QAAQ;IACpD,SAAkB,MAAM,EAAE,GAAG,CAAO;CACrC;AAED,qBAAa,cAAe,SAAQ,QAAQ;IAC1C,SAAkB,MAAM,EAAE,GAAG,CAAO;CACrC;AAED,qBAAa,mBAAoB,SAAQ,QAAQ;CAAG"} \ No newline at end of file diff --git a/backend/node_modules/openai/error.js b/backend/node_modules/openai/error.js new file mode 100644 index 0000000000000000000000000000000000000000..d816d10a2092bb5f502beed75ddf25137908db3a --- /dev/null +++ b/backend/node_modules/openai/error.js @@ -0,0 +1,148 @@ +"use strict"; +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.InternalServerError = exports.RateLimitError = exports.UnprocessableEntityError = exports.ConflictError = exports.NotFoundError = exports.PermissionDeniedError = exports.AuthenticationError = exports.BadRequestError = exports.APIConnectionTimeoutError = exports.APIConnectionError = exports.APIUserAbortError = exports.APIError = exports.OpenAIError = void 0; +const core_1 = require("./core.js"); +class OpenAIError extends Error { +} +exports.OpenAIError = OpenAIError; +class APIError extends OpenAIError { + constructor(status, error, message, headers) { + super(`${APIError.makeMessage(status, error, message)}`); + this.status = status; + this.headers = headers; + this.request_id = headers?.['x-request-id']; + const data = error; + this.error = data; + this.code = data?.['code']; + this.param = data?.['param']; + this.type = data?.['type']; + } + static makeMessage(status, error, message) { + const msg = error?.message ? + typeof error.message === 'string' ? + error.message + : JSON.stringify(error.message) + : error ? JSON.stringify(error) + : message; + if (status && msg) { + return `${status} ${msg}`; + } + if (status) { + return `${status} status code (no body)`; + } + if (msg) { + return msg; + } + return '(no status code or body)'; + } + static generate(status, errorResponse, message, headers) { + if (!status) { + return new APIConnectionError({ cause: (0, core_1.castToError)(errorResponse) }); + } + const error = errorResponse?.['error']; + if (status === 400) { + return new BadRequestError(status, error, message, headers); + } + if (status === 401) { + return new AuthenticationError(status, error, message, headers); + } + if (status === 403) { + return new PermissionDeniedError(status, error, message, headers); + } + if (status === 404) { + return new NotFoundError(status, error, message, headers); + } + if (status === 409) { + return new ConflictError(status, error, message, headers); + } + if (status === 422) { + return new UnprocessableEntityError(status, error, message, headers); + } + if (status === 429) { + return new RateLimitError(status, error, message, headers); + } + if (status >= 500) { + return new InternalServerError(status, error, message, headers); + } + return new APIError(status, error, message, headers); + } +} +exports.APIError = APIError; +class APIUserAbortError extends APIError { + constructor({ message } = {}) { + super(undefined, undefined, message || 'Request was aborted.', undefined); + this.status = undefined; + } +} +exports.APIUserAbortError = APIUserAbortError; +class APIConnectionError extends APIError { + constructor({ message, cause }) { + super(undefined, undefined, message || 'Connection error.', undefined); + this.status = undefined; + // in some environments the 'cause' property is already declared + // @ts-ignore + if (cause) + this.cause = cause; + } +} +exports.APIConnectionError = APIConnectionError; +class APIConnectionTimeoutError extends APIConnectionError { + constructor({ message } = {}) { + super({ message: message ?? 'Request timed out.' }); + } +} +exports.APIConnectionTimeoutError = APIConnectionTimeoutError; +class BadRequestError extends APIError { + constructor() { + super(...arguments); + this.status = 400; + } +} +exports.BadRequestError = BadRequestError; +class AuthenticationError extends APIError { + constructor() { + super(...arguments); + this.status = 401; + } +} +exports.AuthenticationError = AuthenticationError; +class PermissionDeniedError extends APIError { + constructor() { + super(...arguments); + this.status = 403; + } +} +exports.PermissionDeniedError = PermissionDeniedError; +class NotFoundError extends APIError { + constructor() { + super(...arguments); + this.status = 404; + } +} +exports.NotFoundError = NotFoundError; +class ConflictError extends APIError { + constructor() { + super(...arguments); + this.status = 409; + } +} +exports.ConflictError = ConflictError; +class UnprocessableEntityError extends APIError { + constructor() { + super(...arguments); + this.status = 422; + } +} +exports.UnprocessableEntityError = UnprocessableEntityError; +class RateLimitError extends APIError { + constructor() { + super(...arguments); + this.status = 429; + } +} +exports.RateLimitError = RateLimitError; +class InternalServerError extends APIError { +} +exports.InternalServerError = InternalServerError; +//# sourceMappingURL=error.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/error.js.map b/backend/node_modules/openai/error.js.map new file mode 100644 index 0000000000000000000000000000000000000000..a76e5133de9185a3c9719bf06785679182860d85 --- /dev/null +++ b/backend/node_modules/openai/error.js.map @@ -0,0 +1 @@ +{"version":3,"file":"error.js","sourceRoot":"","sources":["src/error.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;AAEtF,oCAA8C;AAE9C,MAAa,WAAY,SAAQ,KAAK;CAAG;AAAzC,kCAAyC;AAEzC,MAAa,QAAS,SAAQ,WAAW;IAWvC,YACE,MAA0B,EAC1B,KAAyB,EACzB,OAA2B,EAC3B,OAA4B;QAE5B,KAAK,CAAC,GAAG,QAAQ,CAAC,WAAW,CAAC,MAAM,EAAE,KAAK,EAAE,OAAO,CAAC,EAAE,CAAC,CAAC;QACzD,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,UAAU,GAAG,OAAO,EAAE,CAAC,cAAc,CAAC,CAAC;QAE5C,MAAM,IAAI,GAAG,KAA4B,CAAC;QAC1C,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;QAClB,I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,QAAQ;CAAG;AAApD,kDAAoD"} \ No newline at end of file diff --git a/backend/node_modules/openai/error.mjs b/backend/node_modules/openai/error.mjs new file mode 100644 index 0000000000000000000000000000000000000000..c296b29416d0beb0ff0edd9cd1d87f8171b2cf64 --- /dev/null +++ b/backend/node_modules/openai/error.mjs @@ -0,0 +1,132 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +import { castToError } from "./core.mjs"; +export class OpenAIError extends Error { +} +export class APIError extends OpenAIError { + constructor(status, error, message, headers) { + super(`${APIError.makeMessage(status, error, message)}`); + this.status = status; + this.headers = headers; + this.request_id = headers?.['x-request-id']; + const data = error; + this.error = data; + this.code = data?.['code']; + this.param = data?.['param']; + this.type = data?.['type']; + } + static makeMessage(status, error, message) { + const msg = error?.message ? + typeof error.message === 'string' ? + error.message + : JSON.stringify(error.message) + : error ? JSON.stringify(error) + : message; + if (status && msg) { + return `${status} ${msg}`; + } + if (status) { + return `${status} status code (no body)`; + } + if (msg) { + return msg; + } + return '(no status code or body)'; + } + static generate(status, errorResponse, message, headers) { + if (!status) { + return new APIConnectionError({ cause: castToError(errorResponse) }); + } + const error = errorResponse?.['error']; + if (status === 400) { + return new BadRequestError(status, error, message, headers); + } + if (status === 401) { + return new AuthenticationError(status, error, message, headers); + } + if (status === 403) { + return new PermissionDeniedError(status, error, message, headers); + } + if (status === 404) { + return new NotFoundError(status, error, message, headers); + } + if (status === 409) { + return new ConflictError(status, error, message, headers); + } + if (status === 422) { + return new UnprocessableEntityError(status, error, message, headers); + } + if (status === 429) { + return new RateLimitError(status, error, message, headers); + } + if (status >= 500) { + return new InternalServerError(status, error, message, headers); + } + return new APIError(status, error, message, headers); + } +} +export class APIUserAbortError extends APIError { + constructor({ message } = {}) { + super(undefined, undefined, message || 'Request was aborted.', undefined); + this.status = undefined; + } +} +export class APIConnectionError extends APIError { + constructor({ message, cause }) { + super(undefined, undefined, message || 'Connection error.', undefined); + this.status = undefined; + // in some environments the 'cause' property is already declared + // @ts-ignore + if (cause) + this.cause = cause; + } +} +export class APIConnectionTimeoutError extends APIConnectionError { + constructor({ message } = {}) { + super({ message: message ?? 'Request timed out.' }); + } +} +export class BadRequestError extends APIError { + constructor() { + super(...arguments); + this.status = 400; + } +} +export class AuthenticationError extends APIError { + constructor() { + super(...arguments); + this.status = 401; + } +} +export class PermissionDeniedError extends APIError { + constructor() { + super(...arguments); + this.status = 403; + } +} +export class NotFoundError extends APIError { + constructor() { + super(...arguments); + this.status = 404; + } +} +export class ConflictError extends APIError { + constructor() { + super(...arguments); + this.status = 409; + } +} +export class UnprocessableEntityError extends APIError { + constructor() { + super(...arguments); + this.status = 422; + } +} +export class RateLimitError extends APIError { + constructor() { + super(...arguments); + this.status = 429; + } +} +export class InternalServerError extends APIError { +} +//# sourceMappingURL=error.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/error.mjs.map b/backend/node_modules/openai/error.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..b783d433237d9149586344206401096ae13f26a0 --- /dev/null +++ b/backend/node_modules/openai/error.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"error.mjs","sourceRoot":"","sources":["src/error.ts"],"names":[],"mappings":"AAAA,sFAAsF;OAE/E,EAAE,WAAW,EAAW;AAE/B,MAAM,OAAO,WAAY,SAAQ,KAAK;CAAG;AAEzC,MAAM,OAAO,QAAS,SAAQ,WAAW;IAWvC,YACE,MAA0B,EAC1B,KAAyB,EACzB,OAA2B,EAC3B,OAA4B;QAE5B,KAAK,CAAC,GAAG,QAAQ,CAAC,WAAW,CAAC,MAAM,EAAE,KAAK,EAAE,OAAO,CAAC,EAAE,CAAC,CAAC;QACzD,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,UAAU,GAAG,OAAO,EAAE,CAAC,cAAc,CAAC,CAAC;QAE5C,MAAM,IAAI,GAAG,KAA4B,CAAC;QAC1C,IAAI,CAAC,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ts b/backend/node_modules/openai/index.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..4a7fd69cf91fa4cb99845bcad8c31225de6df434 --- /dev/null +++ b/backend/node_modules/openai/index.d.mts @@ -0,0 +1,200 @@ +import * as Core from "./core.js"; +import * as Errors from "./error.js"; +import { type Agent } from "./_shims/index.js"; +import * as Uploads from "./uploads.js"; +import * as Pagination from 'openai/pagination'; +import * as API from 'openai/resources/index'; +export interface ClientOptions { + /** + * Defaults to process.env['OPENAI_API_KEY']. + */ + apiKey?: string | undefined; + /** + * Defaults to process.env['OPENAI_ORG_ID']. + */ + organization?: string | null | undefined; + /** + * Override the default base URL for the API, e.g., "https://api.example.com/v2/" + * + * Defaults to process.env['OPENAI_BASE_URL']. + */ + baseURL?: string | null | undefined; + /** + * The maximum amount of time (in milliseconds) that the client should wait for a response + * from the server before timing out a single request. + * + * Note that request timeouts are retried by default, so in a worst-case scenario you may wait + * much longer than this timeout before the promise succeeds or fails. + */ + timeout?: number; + /** + * An HTTP agent used to manage HTTP(S) connections. + * + * If not provided, an agent will be constructed by default in the Node.js environment, + * otherwise no agent is used. + */ + httpAgent?: Agent; + /** + * Specify a custom `fetch` function implementation. + * + * If not provided, we use `node-fetch` on Node.js and otherwise expect that `fetch` is + * defined globally. + */ + fetch?: Core.Fetch | undefined; + /** + * The maximum number of times that the client will retry a request in case of a + * temporary failure, like a network error or a 5XX error from the server. + * + * @default 2 + */ + maxRetries?: number; + /** + * Default headers to include with every request to the API. + * + * These can be removed in individual requests by explicitly setting the + * header to `undefined` or `null` in request options. + */ + defaultHeaders?: Core.Headers; + /** + * Default query parameters to include with every request to the API. + * + * These can be removed in individual requests by explicitly setting the + * param to `undefined` in request options. + */ + defaultQuery?: Core.DefaultQuery; + /** + * By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers. + * Only set this option to `true` if you understand the risks and have appropriate mitigations in place. + */ + dangerouslyAllowBrowser?: boolean; +} +/** API Client for interfacing with the OpenAI API. */ +export declare class OpenAI extends Core.APIClient { + apiKey: string; + organization: string | null; + private _options; + /** + * API Client for interfacing with the OpenAI API. + * + * @param {string | undefined} [opts.apiKey=process.env['OPENAI_API_KEY'] ?? undefined] + * @param {string | null | undefined} [opts.organization=process.env['OPENAI_ORG_ID'] ?? null] + * @param {string} [opts.baseURL=process.env['OPENAI_BASE_URL'] ?? https://api.openai.com/v1] - Override the default base URL for the API. + * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. + * @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections. + * @param {Core.Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. + * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. + * @param {Core.Headers} opts.defaultHeaders - Default headers to include with every request to the API. + * @param {Core.DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API. + * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers. + */ + constructor({ baseURL, apiKey, organization, ...opts }?: ClientOptions); + completions: API.Completions; + chat: API.Chat; + embeddings: API.Embeddings; + files: API.Files; + images: API.Images; + audio: API.Audio; + moderations: API.Moderations; + models: API.Models; + fineTuning: API.FineTuning; + beta: API.Beta; + batches: API.Batches; + protected defaultQuery(): Core.DefaultQuery | undefined; + protected defaultHeaders(opts: Core.FinalRequestOptions): Core.Headers; + protected authHeaders(opts: Core.FinalRequestOptions): Core.Headers; + static OpenAI: typeof OpenAI; + static OpenAIError: typeof Errors.OpenAIError; + static APIError: typeof Errors.APIError; + static APIConnectionError: typeof Errors.APIConnectionError; + static APIConnectionTimeoutError: typeof Errors.APIConnectionTimeoutError; + static APIUserAbortError: typeof Errors.APIUserAbortError; + static NotFoundError: typeof Errors.NotFoundError; + static ConflictError: typeof Errors.ConflictError; + static RateLimitError: typeof Errors.RateLimitError; + static BadRequestError: typeof Errors.BadRequestError; + static AuthenticationError: typeof Errors.AuthenticationError; + static InternalServerError: typeof Errors.InternalServerError; + static PermissionDeniedError: typeof Errors.PermissionDeniedError; + static UnprocessableEntityError: typeof Errors.UnprocessableEntityError; +} +export declare const OpenAIError: typeof Errors.OpenAIError, APIError: typeof Errors.APIError, APIConnectionError: typeof Errors.APIConnectionError, APIConnectionTimeoutError: typeof Errors.APIConnectionTimeoutError, APIUserAbortError: typeof Errors.APIUserAbortError, NotFoundError: typeof Errors.NotFoundError, ConflictError: typeof Errors.ConflictError, RateLimitError: typeof Errors.RateLimitError, BadRequestError: typeof Errors.BadRequestError, AuthenticationError: typeof Errors.AuthenticationError, InternalServerError: typeof Errors.InternalServerError, PermissionDeniedError: typeof Errors.PermissionDeniedError, UnprocessableEntityError: typeof Errors.UnprocessableEntityError; +export import toFile = Uploads.toFile; +export import fileFromPath = Uploads.fileFromPath; +export declare namespace OpenAI { + export import toFile = Uploads.toFile; + export import fileFromPath = Uploads.fileFromPath; + export import RequestOptions = Core.RequestOptions; + export import Page = Pagination.Page; + export import PageResponse = Pagination.PageResponse; + export import CursorPage = Pagination.CursorPage; + export import CursorPageParams = Pagination.CursorPageParams; + export import CursorPageResponse = Pagination.CursorPageResponse; + export import Completions = API.Completions; + export import Completion = API.Completion; + export import CompletionChoice = API.CompletionChoice; + export import CompletionUsage = API.CompletionUsage; + export import CompletionCreateParams = API.CompletionCreateParams; + export import CompletionCreateParamsNonStreaming = API.CompletionCreateParamsNonStreaming; + export import CompletionCreateParamsStreaming = API.CompletionCreateParamsStreaming; + export import Chat = API.Chat; + export import ChatCompletion = API.ChatCompletion; + export import ChatCompletionAssistantMessageParam = API.ChatCompletionAssistantMessageParam; + export import ChatCompletionChunk = API.ChatCompletionChunk; + export import ChatCompletionContentPart = API.ChatCompletionContentPart; + export import ChatCompletionContentPartImage = API.ChatCompletionContentPartImage; + export import ChatCompletionContentPartText = API.ChatCompletionContentPartText; + export import ChatCompletionFunctionCallOption = API.ChatCompletionFunctionCallOption; + export import ChatCompletionFunctionMessageParam = API.ChatCompletionFunctionMessageParam; + export import ChatCompletionMessage = API.ChatCompletionMessage; + export import ChatCompletionMessageParam = API.ChatCompletionMessageParam; + export import ChatCompletionMessageToolCall = API.ChatCompletionMessageToolCall; + export import ChatCompletionNamedToolChoice = API.ChatCompletionNamedToolChoice; + export import ChatCompletionRole = API.ChatCompletionRole; + export import ChatCompletionSystemMessageParam = API.ChatCompletionSystemMessageParam; + export import ChatCompletionTokenLogprob = API.ChatCompletionTokenLogprob; + export import ChatCompletionTool = API.ChatCompletionTool; + export import ChatCompletionToolChoiceOption = API.ChatCompletionToolChoiceOption; + export import ChatCompletionToolMessageParam = API.ChatCompletionToolMessageParam; + export import ChatCompletionUserMessageParam = API.ChatCompletionUserMessageParam; + export import ChatCompletionCreateParams = API.ChatCompletionCreateParams; + export import ChatCompletionCreateParamsNonStreaming = API.ChatCompletionCreateParamsNonStreaming; + export import ChatCompletionCreateParamsStreaming = API.ChatCompletionCreateParamsStreaming; + export import Embeddings = API.Embeddings; + export import CreateEmbeddingResponse = API.CreateEmbeddingResponse; + export import Embedding = API.Embedding; + export import EmbeddingCreateParams = API.EmbeddingCreateParams; + export import Files = API.Files; + export import FileContent = API.FileContent; + export import FileDeleted = API.FileDeleted; + export import FileObject = API.FileObject; + export import FileObjectsPage = API.FileObjectsPage; + export import FileCreateParams = API.FileCreateParams; + export import FileListParams = API.FileListParams; + export import Images = API.Images; + export import Image = API.Image; + export import ImagesResponse = API.ImagesResponse; + export import ImageCreateVariationParams = API.ImageCreateVariationParams; + export import ImageEditParams = API.ImageEditParams; + export import ImageGenerateParams = API.ImageGenerateParams; + export import Audio = API.Audio; + export import Moderations = API.Moderations; + export import Moderation = API.Moderation; + export import ModerationCreateResponse = API.ModerationCreateResponse; + export import ModerationCreateParams = API.ModerationCreateParams; + export import Models = API.Models; + export import Model = API.Model; + export import ModelDeleted = API.ModelDeleted; + export import ModelsPage = API.ModelsPage; + export import FineTuning = API.FineTuning; + export import Beta = API.Beta; + export import Batches = API.Batches; + export import Batch = API.Batch; + export import BatchError = API.BatchError; + export import BatchRequestCounts = API.BatchRequestCounts; + export import BatchCreateParams = API.BatchCreateParams; + export import ErrorObject = API.ErrorObject; + export import FunctionDefinition = API.FunctionDefinition; + export import FunctionParameters = API.FunctionParameters; +} +export default OpenAI; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/index.d.ts b/backend/node_modules/openai/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4a7fd69cf91fa4cb99845bcad8c31225de6df434 --- /dev/null +++ b/backend/node_modules/openai/index.d.ts @@ -0,0 +1,200 @@ +import * as Core from "./core.js"; +import * as Errors from "./error.js"; +import { type Agent } from "./_shims/index.js"; +import * as Uploads from "./uploads.js"; +import * as Pagination from 'openai/pagination'; +import * as API from 'openai/resources/index'; +export interface ClientOptions { + /** + * Defaults to process.env['OPENAI_API_KEY']. + */ + apiKey?: string | undefined; + /** + * Defaults to process.env['OPENAI_ORG_ID']. + */ + organization?: string | null | undefined; + /** + * Override the default base URL for the API, e.g., "https://api.example.com/v2/" + * + * Defaults to process.env['OPENAI_BASE_URL']. + */ + baseURL?: string | null | undefined; + /** + * The maximum amount of time (in milliseconds) that the client should wait for a response + * from the server before timing out a single request. + * + * Note that request timeouts are retried by default, so in a worst-case scenario you may wait + * much longer than this timeout before the promise succeeds or fails. + */ + timeout?: number; + /** + * An HTTP agent used to manage HTTP(S) connections. + * + * If not provided, an agent will be constructed by default in the Node.js environment, + * otherwise no agent is used. + */ + httpAgent?: Agent; + /** + * Specify a custom `fetch` function implementation. + * + * If not provided, we use `node-fetch` on Node.js and otherwise expect that `fetch` is + * defined globally. + */ + fetch?: Core.Fetch | undefined; + /** + * The maximum number of times that the client will retry a request in case of a + * temporary failure, like a network error or a 5XX error from the server. + * + * @default 2 + */ + maxRetries?: number; + /** + * Default headers to include with every request to the API. + * + * These can be removed in individual requests by explicitly setting the + * header to `undefined` or `null` in request options. + */ + defaultHeaders?: Core.Headers; + /** + * Default query parameters to include with every request to the API. + * + * These can be removed in individual requests by explicitly setting the + * param to `undefined` in request options. + */ + defaultQuery?: Core.DefaultQuery; + /** + * By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers. + * Only set this option to `true` if you understand the risks and have appropriate mitigations in place. + */ + dangerouslyAllowBrowser?: boolean; +} +/** API Client for interfacing with the OpenAI API. */ +export declare class OpenAI extends Core.APIClient { + apiKey: string; + organization: string | null; + private _options; + /** + * API Client for interfacing with the OpenAI API. + * + * @param {string | undefined} [opts.apiKey=process.env['OPENAI_API_KEY'] ?? undefined] + * @param {string | null | undefined} [opts.organization=process.env['OPENAI_ORG_ID'] ?? null] + * @param {string} [opts.baseURL=process.env['OPENAI_BASE_URL'] ?? https://api.openai.com/v1] - Override the default base URL for the API. + * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. + * @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections. + * @param {Core.Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. + * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. + * @param {Core.Headers} opts.defaultHeaders - Default headers to include with every request to the API. + * @param {Core.DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API. + * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers. + */ + constructor({ baseURL, apiKey, organization, ...opts }?: ClientOptions); + completions: API.Completions; + chat: API.Chat; + embeddings: API.Embeddings; + files: API.Files; + images: API.Images; + audio: API.Audio; + moderations: API.Moderations; + models: API.Models; + fineTuning: API.FineTuning; + beta: API.Beta; + batches: API.Batches; + protected defaultQuery(): Core.DefaultQuery | undefined; + protected defaultHeaders(opts: Core.FinalRequestOptions): Core.Headers; + protected authHeaders(opts: Core.FinalRequestOptions): Core.Headers; + static OpenAI: typeof OpenAI; + static OpenAIError: typeof Errors.OpenAIError; + static APIError: typeof Errors.APIError; + static APIConnectionError: typeof Errors.APIConnectionError; + static APIConnectionTimeoutError: typeof Errors.APIConnectionTimeoutError; + static APIUserAbortError: typeof Errors.APIUserAbortError; + static NotFoundError: typeof Errors.NotFoundError; + static ConflictError: typeof Errors.ConflictError; + static RateLimitError: typeof Errors.RateLimitError; + static BadRequestError: typeof Errors.BadRequestError; + static AuthenticationError: typeof Errors.AuthenticationError; + static InternalServerError: typeof Errors.InternalServerError; + static PermissionDeniedError: typeof Errors.PermissionDeniedError; + static UnprocessableEntityError: typeof Errors.UnprocessableEntityError; +} +export declare const OpenAIError: typeof Errors.OpenAIError, APIError: typeof Errors.APIError, APIConnectionError: typeof Errors.APIConnectionError, APIConnectionTimeoutError: typeof Errors.APIConnectionTimeoutError, APIUserAbortError: typeof Errors.APIUserAbortError, NotFoundError: typeof Errors.NotFoundError, ConflictError: typeof Errors.ConflictError, RateLimitError: typeof Errors.RateLimitError, BadRequestError: typeof Errors.BadRequestError, AuthenticationError: typeof Errors.AuthenticationError, InternalServerError: typeof Errors.InternalServerError, PermissionDeniedError: typeof Errors.PermissionDeniedError, UnprocessableEntityError: typeof Errors.UnprocessableEntityError; +export import toFile = Uploads.toFile; +export import fileFromPath = Uploads.fileFromPath; +export declare namespace OpenAI { + export import toFile = Uploads.toFile; + export import fileFromPath = Uploads.fileFromPath; + export import RequestOptions = Core.RequestOptions; + export import Page = Pagination.Page; + export import PageResponse = Pagination.PageResponse; + export import CursorPage = Pagination.CursorPage; + export import CursorPageParams = Pagination.CursorPageParams; + export import CursorPageResponse = Pagination.CursorPageResponse; + export import Completions = API.Completions; + export import Completion = API.Completion; + export import CompletionChoice = API.CompletionChoice; + export import CompletionUsage = API.CompletionUsage; + export import CompletionCreateParams = API.CompletionCreateParams; + export import CompletionCreateParamsNonStreaming = API.CompletionCreateParamsNonStreaming; + export import CompletionCreateParamsStreaming = API.CompletionCreateParamsStreaming; + export import Chat = API.Chat; + export import ChatCompletion = API.ChatCompletion; + export import ChatCompletionAssistantMessageParam = API.ChatCompletionAssistantMessageParam; + export import ChatCompletionChunk = API.ChatCompletionChunk; + export import ChatCompletionContentPart = API.ChatCompletionContentPart; + export import ChatCompletionContentPartImage = API.ChatCompletionContentPartImage; + export import ChatCompletionContentPartText = API.ChatCompletionContentPartText; + export import ChatCompletionFunctionCallOption = API.ChatCompletionFunctionCallOption; + export import ChatCompletionFunctionMessageParam = API.ChatCompletionFunctionMessageParam; + export import ChatCompletionMessage = API.ChatCompletionMessage; + export import ChatCompletionMessageParam = API.ChatCompletionMessageParam; + export import ChatCompletionMessageToolCall = API.ChatCompletionMessageToolCall; + export import ChatCompletionNamedToolChoice = API.ChatCompletionNamedToolChoice; + export import ChatCompletionRole = API.ChatCompletionRole; + export import ChatCompletionSystemMessageParam = API.ChatCompletionSystemMessageParam; + export import ChatCompletionTokenLogprob = API.ChatCompletionTokenLogprob; + export import ChatCompletionTool = API.ChatCompletionTool; + export import ChatCompletionToolChoiceOption = API.ChatCompletionToolChoiceOption; + export import ChatCompletionToolMessageParam = API.ChatCompletionToolMessageParam; + export import ChatCompletionUserMessageParam = API.ChatCompletionUserMessageParam; + export import ChatCompletionCreateParams = API.ChatCompletionCreateParams; + export import ChatCompletionCreateParamsNonStreaming = API.ChatCompletionCreateParamsNonStreaming; + export import ChatCompletionCreateParamsStreaming = API.ChatCompletionCreateParamsStreaming; + export import Embeddings = API.Embeddings; + export import CreateEmbeddingResponse = API.CreateEmbeddingResponse; + export import Embedding = API.Embedding; + export import EmbeddingCreateParams = API.EmbeddingCreateParams; + export import Files = API.Files; + export import FileContent = API.FileContent; + export import FileDeleted = API.FileDeleted; + export import FileObject = API.FileObject; + export import FileObjectsPage = API.FileObjectsPage; + export import FileCreateParams = API.FileCreateParams; + export import FileListParams = API.FileListParams; + export import Images = API.Images; + export import Image = API.Image; + export import ImagesResponse = API.ImagesResponse; + export import ImageCreateVariationParams = API.ImageCreateVariationParams; + export import ImageEditParams = API.ImageEditParams; + export import ImageGenerateParams = API.ImageGenerateParams; + export import Audio = API.Audio; + export import Moderations = API.Moderations; + export import Moderation = API.Moderation; + export import ModerationCreateResponse = API.ModerationCreateResponse; + export import ModerationCreateParams = API.ModerationCreateParams; + export import Models = API.Models; + export import Model = API.Model; + export import ModelDeleted = API.ModelDeleted; + export import ModelsPage = API.ModelsPage; + export import FineTuning = API.FineTuning; + export import Beta = API.Beta; + export import Batches = API.Batches; + export import Batch = API.Batch; + export import BatchError = API.BatchError; + export import BatchRequestCounts = API.BatchRequestCounts; + export import BatchCreateParams = API.BatchCreateParams; + export import ErrorObject = API.ErrorObject; + export import FunctionDefinition = API.FunctionDefinition; + export import FunctionParameters = API.FunctionParameters; +} +export default OpenAI; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/index.d.ts.map b/backend/node_modules/openai/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..7344e6d9713a1633220d2ce2c59bccd2d984ded7 --- /dev/null +++ b/backend/node_modules/openai/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["src/index.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,IAAI,MAAM,QAAQ,CAAC;AAC/B,OAAO,KAAK,MAAM,MAAM,SAAS,CAAC;AAClC,OAAO,EAAE,KAAK,KAAK,EAAE,MAAM,gBAAgB,CAAC;AAC5C,OAAO,KAAK,OAAO,MAAM,WAAW,CAAC;AACrC,OAAO,KAAK,UAAU,MAAM,mBAAmB,CAAC;AAChD,OAAO,KAAK,GAAG,MAAM,wBAAwB,CAAC;AAE9C,MAAM,WAAW,aAAa;IAC5B;;OAEG;IACH,MAAM,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAE5B;;OAEG;IACH,YAAY,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC;IAEzC;;;;OAIG;IACH,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC;IAEpC;;;;;;OAMG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IAEjB;;;;;OAKG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C,MAAM,QAAQ,kBAAkB,GAAG,GAAG,CAAC,kBAAkB,CAAC;IAC1D,MAAM,QAAQ,iBAAiB,GAAG,GAAG,CAAC,iBAAiB,CAAC;IAExD,MAAM,QAAQ,WAAW,GAAG,GAAG,CAAC,WAAW,CAAC;IAC5C,MAAM,QAAQ,kBAAkB,GAAG,GAAG,CAAC,kBAAkB,CAAC;IAC1D,MAAM,QAAQ,kBAAkB,GAAG,GAAG,CAAC,kBAAkB,CAAC;CAC3D;AAED,eAAe,MAAM,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/openai/index.js b/backend/node_modules/openai/index.js new file mode 100644 index 0000000000000000000000000000000000000000..df990a27486c362d486fc3f7b42aed936bd9116d --- /dev/null +++ b/backend/node_modules/openai/index.js @@ -0,0 +1,140 @@ +"use strict"; +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var _a; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.fileFromPath = exports.toFile = exports.UnprocessableEntityError = exports.PermissionDeniedError = exports.InternalServerError = exports.AuthenticationError = exports.BadRequestError = exports.RateLimitError = exports.ConflictError = exports.NotFoundError = exports.APIUserAbortError = exports.APIConnectionTimeoutError = exports.APIConnectionError = exports.APIError = exports.OpenAIError = exports.OpenAI = void 0; +const Core = __importStar(require("./core.js")); +const Errors = __importStar(require("./error.js")); +const Uploads = __importStar(require("./uploads.js")); +const Pagination = __importStar(require("openai/pagination")); +const API = __importStar(require("openai/resources/index")); +/** API Client for interfacing with the OpenAI API. */ +class OpenAI extends Core.APIClient { + /** + * API Client for interfacing with the OpenAI API. + * + * @param {string | undefined} [opts.apiKey=process.env['OPENAI_API_KEY'] ?? undefined] + * @param {string | null | undefined} [opts.organization=process.env['OPENAI_ORG_ID'] ?? null] + * @param {string} [opts.baseURL=process.env['OPENAI_BASE_URL'] ?? https://api.openai.com/v1] - Override the default base URL for the API. + * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. + * @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections. + * @param {Core.Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. + * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. + * @param {Core.Headers} opts.defaultHeaders - Default headers to include with every request to the API. + * @param {Core.DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API. + * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers. + */ + constructor({ baseURL = Core.readEnv('OPENAI_BASE_URL'), apiKey = Core.readEnv('OPENAI_API_KEY'), organization = Core.readEnv('OPENAI_ORG_ID') ?? null, ...opts } = {}) { + if (apiKey === undefined) { + throw new Errors.OpenAIError("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' })."); + } + const options = { + apiKey, + organization, + ...opts, + baseURL: baseURL || `https://api.openai.com/v1`, + }; + if (!options.dangerouslyAllowBrowser && Core.isRunningInBrowser()) { + throw new Errors.OpenAIError("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n"); + } + super({ + baseURL: options.baseURL, + timeout: options.timeout ?? 600000 /* 10 minutes */, + httpAgent: options.httpAgent, + maxRetries: options.maxRetries, + fetch: options.fetch, + }); + this.completions = new API.Completions(this); + this.chat = new API.Chat(this); + this.embeddings = new API.Embeddings(this); + this.files = new API.Files(this); + this.images = new API.Images(this); + this.audio = new API.Audio(this); + this.moderations = new API.Moderations(this); + this.models = new API.Models(this); + this.fineTuning = new API.FineTuning(this); + this.beta = new API.Beta(this); + this.batches = new API.Batches(this); + this._options = options; + this.apiKey = apiKey; + this.organization = organization; + } + defaultQuery() { + return this._options.defaultQuery; + } + defaultHeaders(opts) { + return { + ...super.defaultHeaders(opts), + 'OpenAI-Organization': this.organization, + ...this._options.defaultHeaders, + }; + } + authHeaders(opts) { + return { Authorization: `Bearer ${this.apiKey}` }; + } +} +exports.OpenAI = OpenAI; +_a = OpenAI; +OpenAI.OpenAI = _a; +OpenAI.OpenAIError = Errors.OpenAIError; +OpenAI.APIError = Errors.APIError; +OpenAI.APIConnectionError = Errors.APIConnectionError; +OpenAI.APIConnectionTimeoutError = Errors.APIConnectionTimeoutError; +OpenAI.APIUserAbortError = Errors.APIUserAbortError; +OpenAI.NotFoundError = Errors.NotFoundError; +OpenAI.ConflictError = Errors.ConflictError; +OpenAI.RateLimitError = Errors.RateLimitError; +OpenAI.BadRequestError = Errors.BadRequestError; +OpenAI.AuthenticationError = Errors.AuthenticationError; +OpenAI.InternalServerError = Errors.InternalServerError; +OpenAI.PermissionDeniedError = Errors.PermissionDeniedError; +OpenAI.UnprocessableEntityError = Errors.UnprocessableEntityError; +exports.OpenAIError = Errors.OpenAIError, exports.APIError = Errors.APIError, exports.APIConnectionError = Errors.APIConnectionError, exports.APIConnectionTimeoutError = Errors.APIConnectionTimeoutError, exports.APIUserAbortError = Errors.APIUserAbortError, exports.NotFoundError = Errors.NotFoundError, exports.ConflictError = Errors.ConflictError, exports.RateLimitError = Errors.RateLimitError, exports.BadRequestError = Errors.BadRequestError, exports.AuthenticationError = Errors.AuthenticationError, exports.InternalServerError = Errors.InternalServerError, exports.PermissionDeniedError = Errors.PermissionDeniedError, exports.UnprocessableEntityError = Errors.UnprocessableEntityError; +exports.toFile = Uploads.toFile; +exports.fileFromPath = Uploads.fileFromPath; +(function (OpenAI) { + // Helper functions + OpenAI.toFile = Uploads.toFile; + OpenAI.fileFromPath = Uploads.fileFromPath; + OpenAI.Page = Pagination.Page; + OpenAI.CursorPage = Pagination.CursorPage; + OpenAI.Completions = API.Completions; + OpenAI.Chat = API.Chat; + OpenAI.Embeddings = API.Embeddings; + OpenAI.Files = API.Files; + OpenAI.FileObjectsPage = API.FileObjectsPage; + OpenAI.Images = API.Images; + OpenAI.Audio = API.Audio; + OpenAI.Moderations = API.Moderations; + OpenAI.Models = API.Models; + OpenAI.ModelsPage = API.ModelsPage; + OpenAI.FineTuning = API.FineTuning; + OpenAI.Beta = API.Beta; + OpenAI.Batches = API.Batches; +})(OpenAI = exports.OpenAI || (exports.OpenAI = {})); +exports = module.exports = OpenAI; +exports.default = OpenAI; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/index.js.map b/backend/node_modules/openai/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..270c6de8c004ddc776bbb012677adc1deef62acc --- /dev/null +++ b/backend/node_modules/openai/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["src/index.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEtF,gDAA+B;AAC/B,mDAAkC;AAElC,sDAAqC;AACrC,8DAAgD;AAChD,4DAA8C;AA4E9C,sDAAsD;AACtD,MAAa,MAAO,SAAQ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AAC;IAOpB,YAAK,GAAG,GAAG,CAAC,KAAK,CAAC;IAElB,kBAAW,GAAG,GAAG,CAAC,WAAW,CAAC;IAK9B,aAAM,GAAG,GAAG,CAAC,MAAM,CAAC;IAGpB,iBAAU,GAAG,GAAG,CAAC,UAAU,CAAC;IAE5B,iBAAU,GAAG,GAAG,CAAC,UAAU,CAAC;IAE5B,WAAI,GAAG,GAAG,CAAC,IAAI,CAAC;IAEhB,cAAO,GAAG,GAAG,CAAC,OAAO,CAAC;AAStC,CAAC,EA3FgB,MAAM,GAAN,cAAM,KAAN,cAAM,QA2FtB;AAED,kBAAe,MAAM,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/openai/index.mjs b/backend/node_modules/openai/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..b68d4dff6a184ad921523bc21330211e7e47441f --- /dev/null +++ b/backend/node_modules/openai/index.mjs @@ -0,0 +1,112 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +var _a; +import * as Core from "./core.mjs"; +import * as Errors from "./error.mjs"; +import * as Uploads from "./uploads.mjs"; +import * as Pagination from 'openai/pagination'; +import * as API from 'openai/resources/index'; +/** API Client for interfacing with the OpenAI API. */ +export class OpenAI extends Core.APIClient { + /** + * API Client for interfacing with the OpenAI API. + * + * @param {string | undefined} [opts.apiKey=process.env['OPENAI_API_KEY'] ?? undefined] + * @param {string | null | undefined} [opts.organization=process.env['OPENAI_ORG_ID'] ?? null] + * @param {string} [opts.baseURL=process.env['OPENAI_BASE_URL'] ?? https://api.openai.com/v1] - Override the default base URL for the API. + * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. + * @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections. + * @param {Core.Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. + * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. + * @param {Core.Headers} opts.defaultHeaders - Default headers to include with every request to the API. + * @param {Core.DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API. + * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers. + */ + constructor({ baseURL = Core.readEnv('OPENAI_BASE_URL'), apiKey = Core.readEnv('OPENAI_API_KEY'), organization = Core.readEnv('OPENAI_ORG_ID') ?? null, ...opts } = {}) { + if (apiKey === undefined) { + throw new Errors.OpenAIError("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' })."); + } + const options = { + apiKey, + organization, + ...opts, + baseURL: baseURL || `https://api.openai.com/v1`, + }; + if (!options.dangerouslyAllowBrowser && Core.isRunningInBrowser()) { + throw new Errors.OpenAIError("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n"); + } + super({ + baseURL: options.baseURL, + timeout: options.timeout ?? 600000 /* 10 minutes */, + httpAgent: options.httpAgent, + maxRetries: options.maxRetries, + fetch: options.fetch, + }); + this.completions = new API.Completions(this); + this.chat = new API.Chat(this); + this.embeddings = new API.Embeddings(this); + this.files = new API.Files(this); + this.images = new API.Images(this); + this.audio = new API.Audio(this); + this.moderations = new API.Moderations(this); + this.models = new API.Models(this); + this.fineTuning = new API.FineTuning(this); + this.beta = new API.Beta(this); + this.batches = new API.Batches(this); + this._options = options; + this.apiKey = apiKey; + this.organization = organization; + } + defaultQuery() { + return this._options.defaultQuery; + } + defaultHeaders(opts) { + return { + ...super.defaultHeaders(opts), + 'OpenAI-Organization': this.organization, + ...this._options.defaultHeaders, + }; + } + authHeaders(opts) { + return { Authorization: `Bearer ${this.apiKey}` }; + } +} +_a = OpenAI; +OpenAI.OpenAI = _a; +OpenAI.OpenAIError = Errors.OpenAIError; +OpenAI.APIError = Errors.APIError; +OpenAI.APIConnectionError = Errors.APIConnectionError; +OpenAI.APIConnectionTimeoutError = Errors.APIConnectionTimeoutError; +OpenAI.APIUserAbortError = Errors.APIUserAbortError; +OpenAI.NotFoundError = Errors.NotFoundError; +OpenAI.ConflictError = Errors.ConflictError; +OpenAI.RateLimitError = Errors.RateLimitError; +OpenAI.BadRequestError = Errors.BadRequestError; +OpenAI.AuthenticationError = Errors.AuthenticationError; +OpenAI.InternalServerError = Errors.InternalServerError; +OpenAI.PermissionDeniedError = Errors.PermissionDeniedError; +OpenAI.UnprocessableEntityError = Errors.UnprocessableEntityError; +export const { OpenAIError, APIError, APIConnectionError, APIConnectionTimeoutError, APIUserAbortError, NotFoundError, ConflictError, RateLimitError, BadRequestError, AuthenticationError, InternalServerError, PermissionDeniedError, UnprocessableEntityError, } = Errors; +export var toFile = Uploads.toFile; +export var fileFromPath = Uploads.fileFromPath; +(function (OpenAI) { + // Helper functions + OpenAI.toFile = Uploads.toFile; + OpenAI.fileFromPath = Uploads.fileFromPath; + OpenAI.Page = Pagination.Page; + OpenAI.CursorPage = Pagination.CursorPage; + OpenAI.Completions = API.Completions; + OpenAI.Chat = API.Chat; + OpenAI.Embeddings = API.Embeddings; + OpenAI.Files = API.Files; + OpenAI.FileObjectsPage = API.FileObjectsPage; + OpenAI.Images = API.Images; + OpenAI.Audio = API.Audio; + OpenAI.Moderations = API.Moderations; + OpenAI.Models = API.Models; + OpenAI.ModelsPage = API.ModelsPage; + OpenAI.FineTuning = API.FineTuning; + OpenAI.Beta = API.Beta; + OpenAI.Batches = API.Batches; +})(OpenAI || (OpenAI = {})); +export default OpenAI; +//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/index.mjs.map b/backend/node_modules/openai/index.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..6c13b0de6e4f7eef911b6ed50542a94d2edf9fc1 --- /dev/null +++ b/backend/node_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AC;IAK5B,YAAK,GAAG,GAAG,CAAC,KAAK,CAAC;IAIlB,sBAAe,GAAG,GAAG,CAAC,eAAe,CAAC;IAItC,aAAM,GAAG,GAAG,CAAC,MAAM,CAAC;IAOpB,YAAK,GAAG,GAAG,CAAC,KAAK,CAAC;IAElB,kBAAW,GAAG,GAAG,CAAC,WAAW,CAAC;IAK9B,aAAM,GAAG,GAAG,CAAC,MAAM,CAAC;IAGpB,iBAAU,GAAG,GAAG,CAAC,UAAU,CAAC;IAE5B,iBAAU,GAAG,GAAG,CAAC,UAAU,CAAC;IAE5B,WAAI,GAAG,GAAG,CAAC,IAAI,CAAC;IAEhB,cAAO,GAAG,GAAG,CAAC,OAAO,CAAC;AAStC,CAAC,EA3FgB,MAAM,KAAN,MAAM,QA2FtB;AAED,eAAe,MAAM,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/openai/lib/AbstractAssistantStreamRunner.d.ts b/backend/node_modules/openai/lib/AbstractAssistantStreamRunner.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1e869c23ecc97aa01d30700983423af39e644477 --- /dev/null +++ b/backend/node_modules/openai/lib/AbstractAssistantStreamRunner.d.ts @@ -0,0 +1,74 @@ + +import * as Core from 'openai/core'; +import { APIUserAbortError, OpenAIError } from 'openai/error'; +import { Run, RunSubmitToolOutputsParamsBase } from 'openai/resources/beta/threads/runs/runs'; +import { RunCreateParamsBase, Runs } from 'openai/resources/beta/threads/runs/runs'; +import { ThreadCreateAndRunParamsBase, Threads } from 'openai/resources/beta/threads/threads'; +export declare abstract class AbstractAssistantStreamRunner = AbstractAssistantRunnerEvents> { + #private; + controller: AbortController; + constructor(); + protected _run(executor: () => Promise): void; + protected _addRun(run: Run): Run; + protected _connected(): void; + get ended(): boolean; + get errored(): boolean; + get aborted(): boolean; + abort(): void; + /** + * Adds the listener function to the end of the listeners array for the event. + * No checks are made to see if the listener has already been added. Multiple calls passing + * the same combination of event and listener will result in the listener being added, and + * called, multiple times. + * @returns this ChatCompletionStream, so that calls can be chained + */ + on(event: Event, listener: ListenerForEvent): this; + /** + * Removes the specified listener from the listener array for the event. + * off() will remove, at most, one instance of a listener from the listener array. If any single + * listener has been added multiple times to the listener array for the specified event, then + * off() must be called multiple times to remove each instance. + * @returns this ChatCompletionStream, so that calls can be chained + */ + off(event: Event, listener: ListenerForEvent): this; + /** + * Adds a one-time listener function for the event. The next time the event is triggered, + * this listener is removed and then invoked. + * @returns this ChatCompletionStream, so that calls can be chained + */ + once(event: Event, listener: ListenerForEvent): this; + /** + * This is similar to `.once()`, but returns a Promise that resolves the next time + * the event is triggered, instead of calling a listener callback. + * @returns a Promise that resolves the next time given event is triggered, + * or rejects if an error is emitted. (If you request the 'error' event, + * returns a promise that resolves with the error). + * + * Example: + * + * const message = await stream.emitted('message') // rejects if the stream errors + */ + emitted(event: Event): Promise extends [infer Param] ? Param : EventParameters extends [] ? void : EventParameters>; + done(): Promise; + protected _emit(event: Event, ...args: EventParameters): void; + protected _threadAssistantStream(body: ThreadCreateAndRunParamsBase, thread: Threads, options?: Core.RequestOptions): Promise; + protected _runAssistantStream(threadId: string, runs: Runs, params: RunCreateParamsBase, options?: Core.RequestOptions): Promise; + protected _runToolAssistantStream(threadId: string, runId: string, runs: Runs, params: RunSubmitToolOutputsParamsBase, options?: Core.RequestOptions): Promise; + protected _createThreadAssistantStream(thread: Threads, body: ThreadCreateAndRunParamsBase, options?: Core.RequestOptions): Promise; + protected _createToolAssistantStream(run: Runs, threadId: string, runId: string, params: RunSubmitToolOutputsParamsBase, options?: Core.RequestOptions): Promise; + protected _createAssistantStream(run: Runs, threadId: string, params: RunCreateParamsBase, options?: Core.RequestOptions): Promise; +} +type CustomEvents = { + [k in Event]: k extends keyof AbstractAssistantRunnerEvents ? AbstractAssistantRunnerEvents[k] : (...args: any[]) => void; +}; +type ListenerForEvent, Event extends keyof Events> = Event extends (keyof AbstractAssistantRunnerEvents) ? AbstractAssistantRunnerEvents[Event] : Events[Event]; +type EventParameters, Event extends keyof Events> = Parameters>; +export interface AbstractAssistantRunnerEvents { + connect: () => void; + run: (run: Run) => void; + error: (error: OpenAIError) => void; + abort: (error: APIUserAbortError) => void; + end: () => void; +} +export {}; +//# sourceMappingURL=AbstractAssistantStreamRunner.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/lib/AbstractAssistantStreamRunner.d.ts.map b/backend/node_modules/openai/lib/AbstractAssistantStreamRunner.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..17b0ce36de07a5f30befe8c555d15a2bc89a0c2d --- /dev/null +++ b/backend/node_modules/openai/lib/AbstractAssistantStreamRunner.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"AbstractAssistantStreamRunner.d.ts","sourceRoot":"","sources":["../src/lib/AbstractAssistantStreamRunner.ts"],"names":[],"mappings":";AAAA,OAAO,KAAK,IAAI,MAAM,aAAa,CAAC;AACpC,OAAO,EAAE,iBAAiB,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC9D,OAAO,EAAE,GAAG,EAAE,8BAA8B,EAAE,MAAM,yCAAyC,CAAC;AAC9F,OAAO,EAAE,mBAAmB,EAAE,IAAI,EAAE,MAAM,yCAAyC,CAAC;AACpF,OAAO,EAAE,4BAA4B,EAAE,OAAO,EAAE,MAAM,uCAAuC,CAAC;AAE9F,8BAAsB,6BAA6B,CACjD,MAAM,SAAS,YAAY,CAAC,GAAG,CAAC,GAAG,6BAA6B;;IAEhE,UAAU,EAAE,eAAe,CAAyB;;IAoCpD,SAAS,CAAC,IAAI,CAAC,QAAQ,EAAE,MAAM,OAAO,CAAC,GAAG,CAAC;IAW3C,SAAS,CAAC,OAAO,CAAC,GAAG,EAAE,GAAG,GAAG,GAAG;IAIhC,SAAS,CAAC,UAAU;IAMpB,IAAI,KAAK,IAAI,OAAO,CAEnB;IAED,IAAI,OAAO,IAAI,OAAO,CAErB;IAED,IAAI,OAAO,IAAI,OAAO,CAErB;IAED,KAAK;IAIL;;;;;;OAMG;IACH,EAAE,CAAC,KAAK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MAAM,WAAW,6BAA6B;IAC5C,OAAO,EAAE,MAAM,IAAI,CAAC;IACpB,GAAG,EAAE,CAAC,GAAG,EAAE,GAAG,KAAK,IAAI,CAAC;IACxB,KAAK,EAAE,CAAC,KAAK,EAAE,WAAW,KAAK,IAAI,CAAC;IACpC,KAAK,EAAE,CAAC,KAAK,EAAE,iBAAiB,KAAK,IAAI,CAAC;IAC1C,GAAG,EAAE,MAAM,IAAI,CAAC;CACjB"} \ No newline at end of file diff --git a/backend/node_modules/openai/lib/AbstractAssistantStreamRunner.js b/backend/node_modules/openai/lib/AbstractAssistantStreamRunner.js new file mode 100644 index 0000000000000000000000000000000000000000..d47de5a71c12d9d7465c364e2cf8d30b6ee67e9e --- /dev/null +++ b/backend/node_modules/openai/lib/AbstractAssistantStreamRunner.js @@ -0,0 +1,246 @@ +"use strict"; +var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +}; +var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var _AbstractAssistantStreamRunner_connectedPromise, _AbstractAssistantStreamRunner_resolveConnectedPromise, _AbstractAssistantStreamRunner_rejectConnectedPromise, _AbstractAssistantStreamRunner_endPromise, _AbstractAssistantStreamRunner_resolveEndPromise, _AbstractAssistantStreamRunner_rejectEndPromise, _AbstractAssistantStreamRunner_listeners, _AbstractAssistantStreamRunner_ended, _AbstractAssistantStreamRunner_errored, _AbstractAssistantStreamRunner_aborted, _AbstractAssistantStreamRunner_catchingPromiseCreated, _AbstractAssistantStreamRunner_handleError; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AbstractAssistantStreamRunner = void 0; +const error_1 = require("openai/error"); +class AbstractAssistantStreamRunner { + constructor() { + this.controller = new AbortController(); + _AbstractAssistantStreamRunner_connectedPromise.set(this, void 0); + _AbstractAssistantStreamRunner_resolveConnectedPromise.set(this, () => { }); + _AbstractAssistantStreamRunner_rejectConnectedPromise.set(this, () => { }); + _AbstractAssistantStreamRunner_endPromise.set(this, void 0); + _AbstractAssistantStreamRunner_resolveEndPromise.set(this, () => { }); + _AbstractAssistantStreamRunner_rejectEndPromise.set(this, () => { }); + _AbstractAssistantStreamRunner_listeners.set(this, {}); + _AbstractAssistantStreamRunner_ended.set(this, false); + _AbstractAssistantStreamRunner_errored.set(this, false); + _AbstractAssistantStreamRunner_aborted.set(this, false); + _AbstractAssistantStreamRunner_catchingPromiseCreated.set(this, false); + _AbstractAssistantStreamRunner_handleError.set(this, (error) => { + __classPrivateFieldSet(this, _AbstractAssistantStreamRunner_errored, true, "f"); + if (error instanceof Error && error.name === 'AbortError') { + error = new error_1.APIUserAbortError(); + } + if (error instanceof error_1.APIUserAbortError) { + __classPrivateFieldSet(this, _AbstractAssistantStreamRunner_aborted, true, "f"); + return this._emit('abort', error); + } + if (error instanceof error_1.OpenAIError) { + return this._emit('error', error); + } + if (error instanceof Error) { + const openAIError = new error_1.OpenAIError(error.message); + // @ts-ignore + openAIError.cause = error; + return this._emit('error', openAIError); + } + return this._emit('error', new error_1.OpenAIError(String(error))); + }); + __classPrivateFieldSet(this, _AbstractAssistantStreamRunner_connectedPromise, new Promise((resolve, reject) => { + __classPrivateFieldSet(this, _AbstractAssistantStreamRunner_resolveConnectedPromise, resolve, "f"); + __classPrivateFieldSet(this, _AbstractAssistantStreamRunner_rejectConnectedPromise, reject, "f"); + }), "f"); + __classPrivateFieldSet(this, _AbstractAssistantStreamRunner_endPromise, new Promise((resolve, reject) => { + __classPrivateFieldSet(this, _AbstractAssistantStreamRunner_resolveEndPromise, resolve, "f"); + __classPrivateFieldSet(this, _AbstractAssistantStreamRunner_rejectEndPromise, reject, "f"); + }), "f"); + // Don't let these promises cause unhandled rejection errors. + // we will manually cause an unhandled rejection error later + // if the user hasn't registered any error listener or called + // any promise-returning method. + __classPrivateFieldGet(this, _AbstractAssistantStreamRunner_connectedPromise, "f").catch(() => { }); + __classPrivateFieldGet(this, _AbstractAssistantStreamRunner_endPromise, "f").catch(() => { }); + } + _run(executor) { + // Unfortunately if we call `executor()` immediately we get runtime errors about + // references to `this` before the `super()` constructor call returns. + setTimeout(() => { + executor().then(() => { + // this._emitFinal(); + this._emit('end'); + }, __classPrivateFieldGet(this, _AbstractAssistantStreamRunner_handleError, "f")); + }, 0); + } + _addRun(run) { + return run; + } + _connected() { + if (this.ended) + return; + __classPrivateFieldGet(this, _AbstractAssistantStreamRunner_resolveConnectedPromise, "f").call(this); + this._emit('connect'); + } + get ended() { + return __classPrivateFieldGet(this, _AbstractAssistantStreamRunner_ended, "f"); + } + get errored() { + return __classPrivateFieldGet(this, _AbstractAssistantStreamRunner_errored, "f"); + } + get aborted() { + return __classPrivateFieldGet(this, _AbstractAssistantStreamRunner_aborted, "f"); + } + abort() { + this.controller.abort(); + } + /** + * Adds the listener function to the end of the listeners array for the event. + * No checks are made to see if the listener has already been added. Multiple calls passing + * the same combination of event and listener will result in the listener being added, and + * called, multiple times. + * @returns this ChatCompletionStream, so that calls can be chained + */ + on(event, listener) { + const listeners = __classPrivateFieldGet(this, _AbstractAssistantStreamRunner_listeners, "f")[event] || (__classPrivateFieldGet(this, _AbstractAssistantStreamRunner_listeners, "f")[event] = []); + listeners.push({ listener }); + return this; + } + /** + * Removes the specified listener from the listener array for the event. + * off() will remove, at most, one instance of a listener from the listener array. If any single + * listener has been added multiple times to the listener array for the specified event, then + * off() must be called multiple times to remove each instance. + * @returns this ChatCompletionStream, so that calls can be chained + */ + off(event, listener) { + const listeners = __classPrivateFieldGet(this, _AbstractAssistantStreamRunner_listeners, "f")[event]; + if (!listeners) + return this; + const index = listeners.findIndex((l) => l.listener === listener); + if (index >= 0) + listeners.splice(index, 1); + return this; + } + /** + * Adds a one-time listener function for the event. The next time the event is triggered, + * this listener is removed and then invoked. + * @returns this ChatCompletionStream, so that calls can be chained + */ + once(event, listener) { + const listeners = __classPrivateFieldGet(this, _AbstractAssistantStreamRunner_listeners, "f")[event] || (__classPrivateFieldGet(this, _AbstractAssistantStreamRunner_listeners, "f")[event] = []); + listeners.push({ listener, once: true }); + return this; + } + /** + * This is similar to `.once()`, but returns a Promise that resolves the next time + * the event is triggered, instead of calling a listener callback. + * @returns a Promise that resolves the next time given event is triggered, + * or rejects if an error is emitted. (If you request the 'error' event, + * returns a promise that resolves with the error). + * + * Example: + * + * const message = await stream.emitted('message') // rejects if the stream errors + */ + emitted(event) { + return new Promise((resolve, reject) => { + __classPrivateFieldSet(this, _AbstractAssistantStreamRunner_catchingPromiseCreated, true, "f"); + if (event !== 'error') + this.once('error', reject); + this.once(event, resolve); + }); + } + async done() { + __classPrivateFieldSet(this, _AbstractAssistantStreamRunner_catchingPromiseCreated, true, "f"); + await __classPrivateFieldGet(this, _AbstractAssistantStreamRunner_endPromise, "f"); + } + _emit(event, ...args) { + // make sure we don't emit any events after end + if (__classPrivateFieldGet(this, _AbstractAssistantStreamRunner_ended, "f")) { + return; + } + if (event === 'end') { + __classPrivateFieldSet(this, _AbstractAssistantStreamRunner_ended, true, "f"); + __classPrivateFieldGet(this, _AbstractAssistantStreamRunner_resolveEndPromise, "f").call(this); + } + const listeners = __classPrivateFieldGet(this, _AbstractAssistantStreamRunner_listeners, "f")[event]; + if (listeners) { + __classPrivateFieldGet(this, _AbstractAssistantStreamRunner_listeners, "f")[event] = listeners.filter((l) => !l.once); + listeners.forEach(({ listener }) => listener(...args)); + } + if (event === 'abort') { + const error = args[0]; + if (!__classPrivateFieldGet(this, _AbstractAssistantStreamRunner_catchingPromiseCreated, "f") && !listeners?.length) { + Promise.reject(error); + } + __classPrivateFieldGet(this, _AbstractAssistantStreamRunner_rejectConnectedPromise, "f").call(this, error); + __classPrivateFieldGet(this, _AbstractAssistantStreamRunner_rejectEndPromise, "f").call(this, error); + this._emit('end'); + return; + } + if (event === 'error') { + // NOTE: _emit('error', error) should only be called from #handleError(). + const error = args[0]; + if (!__classPrivateFieldGet(this, _AbstractAssistantStreamRunner_catchingPromiseCreated, "f") && !listeners?.length) { + // Trigger an unhandled rejection if the user hasn't registered any error handlers. + // If you are seeing stack traces here, make sure to handle errors via either: + // - runner.on('error', () => ...) + // - await runner.done() + // - await runner.finalChatCompletion() + // - etc. + Promise.reject(error); + } + __classPrivateFieldGet(this, _AbstractAssistantStreamRunner_rejectConnectedPromise, "f").call(this, error); + __classPrivateFieldGet(this, _AbstractAssistantStreamRunner_rejectEndPromise, "f").call(this, error); + this._emit('end'); + } + } + async _threadAssistantStream(body, thread, options) { + return await this._createThreadAssistantStream(thread, body, options); + } + async _runAssistantStream(threadId, runs, params, options) { + return await this._createAssistantStream(runs, threadId, params, options); + } + async _runToolAssistantStream(threadId, runId, runs, params, options) { + return await this._createToolAssistantStream(runs, threadId, runId, params, options); + } + async _createThreadAssistantStream(thread, body, options) { + const signal = options?.signal; + if (signal) { + if (signal.aborted) + this.controller.abort(); + signal.addEventListener('abort', () => this.controller.abort()); + } + // this.#validateParams(params); + const runResult = await thread.createAndRun({ ...body, stream: false }, { ...options, signal: this.controller.signal }); + this._connected(); + return this._addRun(runResult); + } + async _createToolAssistantStream(run, threadId, runId, params, options) { + const signal = options?.signal; + if (signal) { + if (signal.aborted) + this.controller.abort(); + signal.addEventListener('abort', () => this.controller.abort()); + } + const runResult = await run.submitToolOutputs(threadId, runId, { ...params, stream: false }, { ...options, signal: this.controller.signal }); + this._connected(); + return this._addRun(runResult); + } + async _createAssistantStream(run, threadId, params, options) { + const signal = options?.signal; + if (signal) { + if (signal.aborted) + this.controller.abort(); + signal.addEventListener('abort', () => this.controller.abort()); + } + // this.#validateParams(params); + const runResult = await run.create(threadId, { ...params, stream: false }, { ...options, signal: this.controller.signal }); + this._connected(); + return this._addRun(runResult); + } +} +exports.AbstractAssistantStreamRunner = AbstractAssistantStreamRunner; +_AbstractAssistantStreamRunner_connectedPromise = new WeakMap(), _AbstractAssistantStreamRunner_resolveConnectedPromise = new WeakMap(), _AbstractAssistantStreamRunner_rejectConnectedPromise = new WeakMap(), _AbstractAssistantStreamRunner_endPromise = new WeakMap(), _AbstractAssistantStreamRunner_resolveEndPromise = new WeakMap(), _AbstractAssistantStreamRunner_rejectEndPromise = new WeakMap(), _AbstractAssistantStreamRunner_listeners = new WeakMap(), _AbstractAssistantStreamRunner_ended = new WeakMap(), _AbstractAssistantStreamRunner_errored = new WeakMap(), _AbstractAssistantStreamRunner_aborted = new WeakMap(), _AbstractAssistantStreamRunner_catchingPromiseCreated = new WeakMap(), _AbstractAssistantStreamRunner_handleError = new WeakMap(); +//# sourceMappingURL=AbstractAssistantStreamRunner.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/lib/AbstractAssistantStreamRunner.js.map b/backend/node_modules/openai/lib/AbstractAssistantStreamRunner.js.map new file mode 100644 index 0000000000000000000000000000000000000000..1df97b8a7c7c275a00e6db9486f81693fa751ec1 --- /dev/null +++ b/backend/node_modules/openai/lib/AbstractAssistantStreamRunner.js.map @@ -0,0 +1 @@ +{"version":3,"file":"AbstractAssistantStreamRunner.js","sourceRoot":"","sources":["../src/lib/AbstractAssistantStreamRunner.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AACA,wCAA8D;AAK9D,MAAsB,6BAA6B;IAoBjD;QAjBA,eAAU,GAAoB,IAAI,eAAe,EAAE,CAAC;QAEpD,kEAAiC;QACjC,iEAAuC,GAAG,EAAE,GAAE,CAAC,EAAC;QAChD,gEAAwD,GAAG,EAAE,GAAE,CAAC,EAAC;QAEjE,4DAA2B;QAC3B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SAAgB,CAAC,CAAC;IACxC,CAAC;IAES,KAAK,CAAC,sBAAsB,CACpC,GAAS,EACT,QAAgB,EAChB,MAA2B,EAC3B,OAA6B;QAE7B,MAAM,MAAM,GAAG,OAAO,EAAE,MAAM,CAAC;QAC/B,IAAI,MAAM,EAAE;YACV,IAAI,MAAM,CAAC,OAAO;gBAAE,IAAI,CAAC,UAAU,CAAC,KAAK,EAAE,CAAC;YAC5C,MAAM,CAAC,gBAAgB,CAAC,OAAO,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,UAAU,CAAC,KAAK,EAAE,CAAC,CAAC;SACjE;QACD,gCAAgC;QAEhC,MAAM,SAAS,GAAG,MAAM,GAAG,CAAC,MAAM,CAChC,QAAQ,EACR,EAAE,GAAG,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,EAC5B,EAAE,GAAG,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,UAAU,CAAC,MAAM,EAAE,CAC/C,CAAC;QACF,IAAI,CAAC,UAAU,EAAE,CAAC;QAClB,OAAO,IAAI,CAAC,OAAO,CAAC,SAAgB,CAAC,CAAC;IACxC,CAAC;CACF;AAlTD,sEAkTC"} \ No newline at end of file diff --git a/backend/node_modules/openai/lib/AbstractAssistantStreamRunner.mjs b/backend/node_modules/openai/lib/AbstractAssistantStreamRunner.mjs new file mode 100644 index 0000000000000000000000000000000000000000..b6919af042e1e03206ad6ec25ed64c487f95de80 --- /dev/null +++ b/backend/node_modules/openai/lib/AbstractAssistantStreamRunner.mjs @@ -0,0 +1,242 @@ +var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +}; +var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var _AbstractAssistantStreamRunner_connectedPromise, _AbstractAssistantStreamRunner_resolveConnectedPromise, _AbstractAssistantStreamRunner_rejectConnectedPromise, _AbstractAssistantStreamRunner_endPromise, _AbstractAssistantStreamRunner_resolveEndPromise, _AbstractAssistantStreamRunner_rejectEndPromise, _AbstractAssistantStreamRunner_listeners, _AbstractAssistantStreamRunner_ended, _AbstractAssistantStreamRunner_errored, _AbstractAssistantStreamRunner_aborted, _AbstractAssistantStreamRunner_catchingPromiseCreated, _AbstractAssistantStreamRunner_handleError; +import { APIUserAbortError, OpenAIError } from 'openai/error'; +export class AbstractAssistantStreamRunner { + constructor() { + this.controller = new AbortController(); + _AbstractAssistantStreamRunner_connectedPromise.set(this, void 0); + _AbstractAssistantStreamRunner_resolveConnectedPromise.set(this, () => { }); + _AbstractAssistantStreamRunner_rejectConnectedPromise.set(this, () => { }); + _AbstractAssistantStreamRunner_endPromise.set(this, void 0); + _AbstractAssistantStreamRunner_resolveEndPromise.set(this, () => { }); + _AbstractAssistantStreamRunner_rejectEndPromise.set(this, () => { }); + _AbstractAssistantStreamRunner_listeners.set(this, {}); + _AbstractAssistantStreamRunner_ended.set(this, false); + _AbstractAssistantStreamRunner_errored.set(this, false); + _AbstractAssistantStreamRunner_aborted.set(this, false); + _AbstractAssistantStreamRunner_catchingPromiseCreated.set(this, false); + _AbstractAssistantStreamRunner_handleError.set(this, (error) => { + __classPrivateFieldSet(this, _AbstractAssistantStreamRunner_errored, true, "f"); + if (error instanceof Error && error.name === 'AbortError') { + error = new APIUserAbortError(); + } + if (error instanceof APIUserAbortError) { + __classPrivateFieldSet(this, _AbstractAssistantStreamRunner_aborted, true, "f"); + return this._emit('abort', error); + } + if (error instanceof OpenAIError) { + return this._emit('error', error); + } + if (error instanceof Error) { + const openAIError = new OpenAIError(error.message); + // @ts-ignore + openAIError.cause = error; + return this._emit('error', openAIError); + } + return this._emit('error', new OpenAIError(String(error))); + }); + __classPrivateFieldSet(this, _AbstractAssistantStreamRunner_connectedPromise, new Promise((resolve, reject) => { + __classPrivateFieldSet(this, _AbstractAssistantStreamRunner_resolveConnectedPromise, resolve, "f"); + __classPrivateFieldSet(this, _AbstractAssistantStreamRunner_rejectConnectedPromise, reject, "f"); + }), "f"); + __classPrivateFieldSet(this, _AbstractAssistantStreamRunner_endPromise, new Promise((resolve, reject) => { + __classPrivateFieldSet(this, _AbstractAssistantStreamRunner_resolveEndPromise, resolve, "f"); + __classPrivateFieldSet(this, _AbstractAssistantStreamRunner_rejectEndPromise, reject, "f"); + }), "f"); + // Don't let these promises cause unhandled rejection errors. + // we will manually cause an unhandled rejection error later + // if the user hasn't registered any error listener or called + // any promise-returning method. + __classPrivateFieldGet(this, _AbstractAssistantStreamRunner_connectedPromise, "f").catch(() => { }); + __classPrivateFieldGet(this, _AbstractAssistantStreamRunner_endPromise, "f").catch(() => { }); + } + _run(executor) { + // Unfortunately if we call `executor()` immediately we get runtime errors about + // references to `this` before the `super()` constructor call returns. + setTimeout(() => { + executor().then(() => { + // this._emitFinal(); + this._emit('end'); + }, __classPrivateFieldGet(this, _AbstractAssistantStreamRunner_handleError, "f")); + }, 0); + } + _addRun(run) { + return run; + } + _connected() { + if (this.ended) + return; + __classPrivateFieldGet(this, _AbstractAssistantStreamRunner_resolveConnectedPromise, "f").call(this); + this._emit('connect'); + } + get ended() { + return __classPrivateFieldGet(this, _AbstractAssistantStreamRunner_ended, "f"); + } + get errored() { + return __classPrivateFieldGet(this, _AbstractAssistantStreamRunner_errored, "f"); + } + get aborted() { + return __classPrivateFieldGet(this, _AbstractAssistantStreamRunner_aborted, "f"); + } + abort() { + this.controller.abort(); + } + /** + * Adds the listener function to the end of the listeners array for the event. + * No checks are made to see if the listener has already been added. Multiple calls passing + * the same combination of event and listener will result in the listener being added, and + * called, multiple times. + * @returns this ChatCompletionStream, so that calls can be chained + */ + on(event, listener) { + const listeners = __classPrivateFieldGet(this, _AbstractAssistantStreamRunner_listeners, "f")[event] || (__classPrivateFieldGet(this, _AbstractAssistantStreamRunner_listeners, "f")[event] = []); + listeners.push({ listener }); + return this; + } + /** + * Removes the specified listener from the listener array for the event. + * off() will remove, at most, one instance of a listener from the listener array. If any single + * listener has been added multiple times to the listener array for the specified event, then + * off() must be called multiple times to remove each instance. + * @returns this ChatCompletionStream, so that calls can be chained + */ + off(event, listener) { + const listeners = __classPrivateFieldGet(this, _AbstractAssistantStreamRunner_listeners, "f")[event]; + if (!listeners) + return this; + const index = listeners.findIndex((l) => l.listener === listener); + if (index >= 0) + listeners.splice(index, 1); + return this; + } + /** + * Adds a one-time listener function for the event. The next time the event is triggered, + * this listener is removed and then invoked. + * @returns this ChatCompletionStream, so that calls can be chained + */ + once(event, listener) { + const listeners = __classPrivateFieldGet(this, _AbstractAssistantStreamRunner_listeners, "f")[event] || (__classPrivateFieldGet(this, _AbstractAssistantStreamRunner_listeners, "f")[event] = []); + listeners.push({ listener, once: true }); + return this; + } + /** + * This is similar to `.once()`, but returns a Promise that resolves the next time + * the event is triggered, instead of calling a listener callback. + * @returns a Promise that resolves the next time given event is triggered, + * or rejects if an error is emitted. (If you request the 'error' event, + * returns a promise that resolves with the error). + * + * Example: + * + * const message = await stream.emitted('message') // rejects if the stream errors + */ + emitted(event) { + return new Promise((resolve, reject) => { + __classPrivateFieldSet(this, _AbstractAssistantStreamRunner_catchingPromiseCreated, true, "f"); + if (event !== 'error') + this.once('error', reject); + this.once(event, resolve); + }); + } + async done() { + __classPrivateFieldSet(this, _AbstractAssistantStreamRunner_catchingPromiseCreated, true, "f"); + await __classPrivateFieldGet(this, _AbstractAssistantStreamRunner_endPromise, "f"); + } + _emit(event, ...args) { + // make sure we don't emit any events after end + if (__classPrivateFieldGet(this, _AbstractAssistantStreamRunner_ended, "f")) { + return; + } + if (event === 'end') { + __classPrivateFieldSet(this, _AbstractAssistantStreamRunner_ended, true, "f"); + __classPrivateFieldGet(this, _AbstractAssistantStreamRunner_resolveEndPromise, "f").call(this); + } + const listeners = __classPrivateFieldGet(this, _AbstractAssistantStreamRunner_listeners, "f")[event]; + if (listeners) { + __classPrivateFieldGet(this, _AbstractAssistantStreamRunner_listeners, "f")[event] = listeners.filter((l) => !l.once); + listeners.forEach(({ listener }) => listener(...args)); + } + if (event === 'abort') { + const error = args[0]; + if (!__classPrivateFieldGet(this, _AbstractAssistantStreamRunner_catchingPromiseCreated, "f") && !listeners?.length) { + Promise.reject(error); + } + __classPrivateFieldGet(this, _AbstractAssistantStreamRunner_rejectConnectedPromise, "f").call(this, error); + __classPrivateFieldGet(this, _AbstractAssistantStreamRunner_rejectEndPromise, "f").call(this, error); + this._emit('end'); + return; + } + if (event === 'error') { + // NOTE: _emit('error', error) should only be called from #handleError(). + const error = args[0]; + if (!__classPrivateFieldGet(this, _AbstractAssistantStreamRunner_catchingPromiseCreated, "f") && !listeners?.length) { + // Trigger an unhandled rejection if the user hasn't registered any error handlers. + // If you are seeing stack traces here, make sure to handle errors via either: + // - runner.on('error', () => ...) + // - await runner.done() + // - await runner.finalChatCompletion() + // - etc. + Promise.reject(error); + } + __classPrivateFieldGet(this, _AbstractAssistantStreamRunner_rejectConnectedPromise, "f").call(this, error); + __classPrivateFieldGet(this, _AbstractAssistantStreamRunner_rejectEndPromise, "f").call(this, error); + this._emit('end'); + } + } + async _threadAssistantStream(body, thread, options) { + return await this._createThreadAssistantStream(thread, body, options); + } + async _runAssistantStream(threadId, runs, params, options) { + return await this._createAssistantStream(runs, threadId, params, options); + } + async _runToolAssistantStream(threadId, runId, runs, params, options) { + return await this._createToolAssistantStream(runs, threadId, runId, params, options); + } + async _createThreadAssistantStream(thread, body, options) { + const signal = options?.signal; + if (signal) { + if (signal.aborted) + this.controller.abort(); + signal.addEventListener('abort', () => this.controller.abort()); + } + // this.#validateParams(params); + const runResult = await thread.createAndRun({ ...body, stream: false }, { ...options, signal: this.controller.signal }); + this._connected(); + return this._addRun(runResult); + } + async _createToolAssistantStream(run, threadId, runId, params, options) { + const signal = options?.signal; + if (signal) { + if (signal.aborted) + this.controller.abort(); + signal.addEventListener('abort', () => this.controller.abort()); + } + const runResult = await run.submitToolOutputs(threadId, runId, { ...params, stream: false }, { ...options, signal: this.controller.signal }); + this._connected(); + return this._addRun(runResult); + } + async _createAssistantStream(run, threadId, params, options) { + const signal = options?.signal; + if (signal) { + if (signal.aborted) + this.controller.abort(); + signal.addEventListener('abort', () => this.controller.abort()); + } + // this.#validateParams(params); + const runResult = await run.create(threadId, { ...params, stream: false }, { ...options, signal: this.controller.signal }); + this._connected(); + return this._addRun(runResult); + } +} +_AbstractAssistantStreamRunner_connectedPromise = new WeakMap(), _AbstractAssistantStreamRunner_resolveConnectedPromise = new WeakMap(), _AbstractAssistantStreamRunner_rejectConnectedPromise = new WeakMap(), _AbstractAssistantStreamRunner_endPromise = new WeakMap(), _AbstractAssistantStreamRunner_resolveEndPromise = new WeakMap(), _AbstractAssistantStreamRunner_rejectEndPromise = new WeakMap(), _AbstractAssistantStreamRunner_listeners = new WeakMap(), _AbstractAssistantStreamRunner_ended = new WeakMap(), _AbstractAssistantStreamRunner_errored = new WeakMap(), _AbstractAssistantStreamRunner_aborted = new WeakMap(), _AbstractAssistantStreamRunner_catchingPromiseCreated = new WeakMap(), _AbstractAssistantStreamRunner_handleError = new WeakMap(); +//# sourceMappingURL=AbstractAssistantStreamRunner.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/lib/AbstractAssistantStreamRunner.mjs.map b/backend/node_modules/openai/lib/AbstractAssistantStreamRunner.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..f1f83e37c7fb7b29b9d0d7c5f3827aec60a1da6d --- /dev/null +++ b/backend/node_modules/openai/lib/AbstractAssistantStreamRunner.mjs.map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AC,OAAO,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,UAAU,CAAC,KAAK,EAAE,CAAC,CAAC;SACjE;QAED,MAAM,SAAS,GAAG,MAAM,GAAG,CAAC,iBAAiB,CAC3C,QAAQ,EACR,KAAK,EACL,EAAE,GAAG,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,EAC5B,EAAE,GAAG,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,UAAU,CAAC,MAAM,EAAE,CAC/C,CAAC;QACF,IAAI,CAAC,UAAU,EAAE,CAAC;QAClB,OAAO,IAAI,CAAC,OAAO,CAAC,SAAgB,CAAC,CAAC;IACxC,CAAC;IAES,KAAK,CAAC,sBAAsB,CACpC,GAAS,EACT,QAAgB,EAChB,MAA2B,EAC3B,OAA6B;QAE7B,MAAM,MAAM,GAAG,OAAO,EAAE,MAAM,CAAC;QAC/B,IAAI,MAAM,EAAE;YACV,IAAI,MAAM,CAAC,OAAO;gBAAE,IAAI,CAAC,UAAU,CAAC,KAAK,EAAE,CAAC;YAC5C,MAAM,CAAC,gBAAgB,CAAC,OAAO,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,UAAU,CAAC,KAAK,EAAE,CAAC,CAAC;SACjE;QACD,gCAAgC;QAEhC,MAAM,SAAS,GAAG,MAAM,GAAG,CAAC,MAAM,CAChC,QAAQ,EACR,EAAE,GAAG,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,EAC5B,EAAE,GAAG,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,UAAU,CAAC,MAAM,EAAE,CAC/C,CAAC;QACF,IAAI,CAAC,UAAU,EAAE,CAAC;QAClB,OAAO,IAAI,CAAC,OAAO,CAAC,SAAgB,CAAC,CAAC;IACxC,CAAC;CACF"} \ No newline at end of file diff --git a/backend/node_modules/openai/lib/AbstractChatCompletionRunner.d.ts b/backend/node_modules/openai/lib/AbstractChatCompletionRunner.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c05aa959c1c27429444d9eadac40caf08559475a --- /dev/null +++ b/backend/node_modules/openai/lib/AbstractChatCompletionRunner.d.ts @@ -0,0 +1,114 @@ + +import * as Core from 'openai/core'; +import { type CompletionUsage } from 'openai/resources/completions'; +import { type Completions, type ChatCompletion, type ChatCompletionMessage, type ChatCompletionMessageParam, type ChatCompletionCreateParams } from 'openai/resources/chat/completions'; +import { APIUserAbortError, OpenAIError } from 'openai/error'; +import { type BaseFunctionsArgs } from "./RunnableFunction.js"; +import { ChatCompletionFunctionRunnerParams, ChatCompletionToolRunnerParams } from "./ChatCompletionRunner.js"; +import { ChatCompletionStreamingFunctionRunnerParams, ChatCompletionStreamingToolRunnerParams } from "./ChatCompletionStreamingRunner.js"; +export interface RunnerOptions extends Core.RequestOptions { + /** How many requests to make before canceling. Default 10. */ + maxChatCompletions?: number; +} +export declare abstract class AbstractChatCompletionRunner = AbstractChatCompletionRunnerEvents> { + #private; + controller: AbortController; + protected _chatCompletions: ChatCompletion[]; + messages: ChatCompletionMessageParam[]; + constructor(); + protected _run(executor: () => Promise): void; + protected _addChatCompletion(chatCompletion: ChatCompletion): ChatCompletion; + protected _addMessage(message: ChatCompletionMessageParam, emit?: boolean): void; + protected _connected(): void; + get ended(): boolean; + get errored(): boolean; + get aborted(): boolean; + abort(): void; + /** + * Adds the listener function to the end of the listeners array for the event. + * No checks are made to see if the listener has already been added. Multiple calls passing + * the same combination of event and listener will result in the listener being added, and + * called, multiple times. + * @returns this ChatCompletionStream, so that calls can be chained + */ + on(event: Event, listener: ListenerForEvent): this; + /** + * Removes the specified listener from the listener array for the event. + * off() will remove, at most, one instance of a listener from the listener array. If any single + * listener has been added multiple times to the listener array for the specified event, then + * off() must be called multiple times to remove each instance. + * @returns this ChatCompletionStream, so that calls can be chained + */ + off(event: Event, listener: ListenerForEvent): this; + /** + * Adds a one-time listener function for the event. The next time the event is triggered, + * this listener is removed and then invoked. + * @returns this ChatCompletionStream, so that calls can be chained + */ + once(event: Event, listener: ListenerForEvent): this; + /** + * This is similar to `.once()`, but returns a Promise that resolves the next time + * the event is triggered, instead of calling a listener callback. + * @returns a Promise that resolves the next time given event is triggered, + * or rejects if an error is emitted. (If you request the 'error' event, + * returns a promise that resolves with the error). + * + * Example: + * + * const message = await stream.emitted('message') // rejects if the stream errors + */ + emitted(event: Event): Promise extends [infer Param] ? Param : EventParameters extends [] ? void : EventParameters>; + done(): Promise; + /** + * @returns a promise that resolves with the final ChatCompletion, or rejects + * if an error occurred or the stream ended prematurely without producing a ChatCompletion. + */ + finalChatCompletion(): Promise; + /** + * @returns a promise that resolves with the content of the final ChatCompletionMessage, or rejects + * if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage. + */ + finalContent(): Promise; + /** + * @returns a promise that resolves with the the final assistant ChatCompletionMessage response, + * or rejects if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage. + */ + finalMessage(): Promise; + /** + * @returns a promise that resolves with the content of the final FunctionCall, or rejects + * if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage. + */ + finalFunctionCall(): Promise; + finalFunctionCallResult(): Promise; + totalUsage(): Promise; + allChatCompletions(): ChatCompletion[]; + protected _emit(event: Event, ...args: EventParameters): void; + protected _emitFinal(): void; + protected _createChatCompletion(completions: Completions, params: ChatCompletionCreateParams, options?: Core.RequestOptions): Promise; + protected _runChatCompletion(completions: Completions, params: ChatCompletionCreateParams, options?: Core.RequestOptions): Promise; + protected _runFunctions(completions: Completions, params: ChatCompletionFunctionRunnerParams | ChatCompletionStreamingFunctionRunnerParams, options?: RunnerOptions): Promise; + protected _runTools(completions: Completions, params: ChatCompletionToolRunnerParams | ChatCompletionStreamingToolRunnerParams, options?: RunnerOptions): Promise; +} +type CustomEvents = { + [k in Event]: k extends keyof AbstractChatCompletionRunnerEvents ? AbstractChatCompletionRunnerEvents[k] : (...args: any[]) => void; +}; +type ListenerForEvent, Event extends keyof Events> = Event extends (keyof AbstractChatCompletionRunnerEvents) ? AbstractChatCompletionRunnerEvents[Event] : Events[Event]; +type EventParameters, Event extends keyof Events> = Parameters>; +export interface AbstractChatCompletionRunnerEvents { + connect: () => void; + functionCall: (functionCall: ChatCompletionMessage.FunctionCall) => void; + message: (message: ChatCompletionMessageParam) => void; + chatCompletion: (completion: ChatCompletion) => void; + finalContent: (contentSnapshot: string) => void; + finalMessage: (message: ChatCompletionMessageParam) => void; + finalChatCompletion: (completion: ChatCompletion) => void; + finalFunctionCall: (functionCall: ChatCompletionMessage.FunctionCall) => void; + functionCallResult: (content: string) => void; + finalFunctionCallResult: (content: string) => void; + error: (error: OpenAIError) => void; + abort: (error: APIUserAbortError) => void; + end: () => void; + totalUsage: (usage: CompletionUsage) => void; +} +export {}; +//# sourceMappingURL=AbstractChatCompletionRunner.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/lib/AbstractChatCompletionRunner.d.ts.map b/backend/node_modules/openai/lib/AbstractChatCompletionRunner.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..551b705275905ce09f1f2e38f565fd3948a7a5c0 --- /dev/null +++ b/backend/node_modules/openai/lib/AbstractChatCompletionRunner.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"AbstractChatCompletionRunner.d.ts","sourceRoot":"","sources":["../src/lib/AbstractChatCompletionRunner.ts"],"names":[],"mappings":";AAAA,OAAO,KAAK,IAAI,MAAM,aAAa,CAAC;AACpC,OAAO,EAAE,KAAK,eAAe,EAAE,MAAM,8BAA8B,CAAC;AACpE,OAAO,EACL,KAAK,WAAW,EAChB,KAAK,cAAc,EACnB,KAAK,qBAAqB,EAC1B,KAAK,0BAA0B,EAC/B,KAAK,0BAA0B,EAEhC,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAE,iBAAiB,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC9D,OAAO,EAGL,KAAK,iBAAiB,EACvB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,kCAAkC,EAAE,8BAA8B,EAAE,MAAM,wBAAwB,CAAC;AAC5G,OAAO,EACL,2CAA2C,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,CAAC,UAAU,EAAE,cAAc,KAAK,IAAI,CAAC;IAC1D,iBAAiB,EAAE,CAAC,YAAY,EAAE,qBAAqB,CAAC,YAAY,KAAK,IAAI,CAAC;IAC9E,kBAAkB,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;IAC9C,uBAAuB,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;IACnD,KAAK,EAAE,CAAC,KAAK,EAAE,WAAW,KAAK,IAAI,CAAC;IACpC,KAAK,EAAE,CAAC,KAAK,EAAE,iBAAiB,KAAK,IAAI,CAAC;IAC1C,GAAG,EAAE,MAAM,IAAI,CAAC;IAChB,UAAU,EAAE,CAAC,KAAK,EAAE,eAAe,KAAK,IAAI,CAAC;CAC9C"} \ No newline at end of file diff --git a/backend/node_modules/openai/lib/AbstractChatCompletionRunner.js b/backend/node_modules/openai/lib/AbstractChatCompletionRunner.js new file mode 100644 index 0000000000000000000000000000000000000000..3ff28cebd0bc336d5c424948ef7d86e75259d5fa --- /dev/null +++ b/backend/node_modules/openai/lib/AbstractChatCompletionRunner.js @@ -0,0 +1,519 @@ +"use strict"; +var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +}; +var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var _AbstractChatCompletionRunner_instances, _AbstractChatCompletionRunner_connectedPromise, _AbstractChatCompletionRunner_resolveConnectedPromise, _AbstractChatCompletionRunner_rejectConnectedPromise, _AbstractChatCompletionRunner_endPromise, _AbstractChatCompletionRunner_resolveEndPromise, _AbstractChatCompletionRunner_rejectEndPromise, _AbstractChatCompletionRunner_listeners, _AbstractChatCompletionRunner_ended, _AbstractChatCompletionRunner_errored, _AbstractChatCompletionRunner_aborted, _AbstractChatCompletionRunner_catchingPromiseCreated, _AbstractChatCompletionRunner_getFinalContent, _AbstractChatCompletionRunner_getFinalMessage, _AbstractChatCompletionRunner_getFinalFunctionCall, _AbstractChatCompletionRunner_getFinalFunctionCallResult, _AbstractChatCompletionRunner_calculateTotalUsage, _AbstractChatCompletionRunner_handleError, _AbstractChatCompletionRunner_validateParams, _AbstractChatCompletionRunner_stringifyFunctionCallResult; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AbstractChatCompletionRunner = void 0; +const error_1 = require("openai/error"); +const RunnableFunction_1 = require("./RunnableFunction.js"); +const chatCompletionUtils_1 = require("./chatCompletionUtils.js"); +const DEFAULT_MAX_CHAT_COMPLETIONS = 10; +class AbstractChatCompletionRunner { + constructor() { + _AbstractChatCompletionRunner_instances.add(this); + this.controller = new AbortController(); + _AbstractChatCompletionRunner_connectedPromise.set(this, void 0); + _AbstractChatCompletionRunner_resolveConnectedPromise.set(this, () => { }); + _AbstractChatCompletionRunner_rejectConnectedPromise.set(this, () => { }); + _AbstractChatCompletionRunner_endPromise.set(this, void 0); + _AbstractChatCompletionRunner_resolveEndPromise.set(this, () => { }); + _AbstractChatCompletionRunner_rejectEndPromise.set(this, () => { }); + _AbstractChatCompletionRunner_listeners.set(this, {}); + this._chatCompletions = []; + this.messages = []; + _AbstractChatCompletionRunner_ended.set(this, false); + _AbstractChatCompletionRunner_errored.set(this, false); + _AbstractChatCompletionRunner_aborted.set(this, false); + _AbstractChatCompletionRunner_catchingPromiseCreated.set(this, false); + _AbstractChatCompletionRunner_handleError.set(this, (error) => { + __classPrivateFieldSet(this, _AbstractChatCompletionRunner_errored, true, "f"); + if (error instanceof Error && error.name === 'AbortError') { + error = new error_1.APIUserAbortError(); + } + if (error instanceof error_1.APIUserAbortError) { + __classPrivateFieldSet(this, _AbstractChatCompletionRunner_aborted, true, "f"); + return this._emit('abort', error); + } + if (error instanceof error_1.OpenAIError) { + return this._emit('error', error); + } + if (error instanceof Error) { + const openAIError = new error_1.OpenAIError(error.message); + // @ts-ignore + openAIError.cause = error; + return this._emit('error', openAIError); + } + return this._emit('error', new error_1.OpenAIError(String(error))); + }); + __classPrivateFieldSet(this, _AbstractChatCompletionRunner_connectedPromise, new Promise((resolve, reject) => { + __classPrivateFieldSet(this, _AbstractChatCompletionRunner_resolveConnectedPromise, resolve, "f"); + __classPrivateFieldSet(this, _AbstractChatCompletionRunner_rejectConnectedPromise, reject, "f"); + }), "f"); + __classPrivateFieldSet(this, _AbstractChatCompletionRunner_endPromise, new Promise((resolve, reject) => { + __classPrivateFieldSet(this, _AbstractChatCompletionRunner_resolveEndPromise, resolve, "f"); + __classPrivateFieldSet(this, _AbstractChatCompletionRunner_rejectEndPromise, reject, "f"); + }), "f"); + // Don't let these promises cause unhandled rejection errors. + // we will manually cause an unhandled rejection error later + // if the user hasn't registered any error listener or called + // any promise-returning method. + __classPrivateFieldGet(this, _AbstractChatCompletionRunner_connectedPromise, "f").catch(() => { }); + __classPrivateFieldGet(this, _AbstractChatCompletionRunner_endPromise, "f").catch(() => { }); + } + _run(executor) { + // Unfortunately if we call `executor()` immediately we get runtime errors about + // references to `this` before the `super()` constructor call returns. + setTimeout(() => { + executor().then(() => { + this._emitFinal(); + this._emit('end'); + }, __classPrivateFieldGet(this, _AbstractChatCompletionRunner_handleError, "f")); + }, 0); + } + _addChatCompletion(chatCompletion) { + this._chatCompletions.push(chatCompletion); + this._emit('chatCompletion', chatCompletion); + const message = chatCompletion.choices[0]?.message; + if (message) + this._addMessage(message); + return chatCompletion; + } + _addMessage(message, emit = true) { + if (!('content' in message)) + message.content = null; + this.messages.push(message); + if (emit) { + this._emit('message', message); + if (((0, chatCompletionUtils_1.isFunctionMessage)(message) || (0, chatCompletionUtils_1.isToolMessage)(message)) && message.content) { + // Note, this assumes that {role: 'tool', content: …} is always the result of a call of tool of type=function. + this._emit('functionCallResult', message.content); + } + else if ((0, chatCompletionUtils_1.isAssistantMessage)(message) && message.function_call) { + this._emit('functionCall', message.function_call); + } + else if ((0, chatCompletionUtils_1.isAssistantMessage)(message) && message.tool_calls) { + for (const tool_call of message.tool_calls) { + if (tool_call.type === 'function') { + this._emit('functionCall', tool_call.function); + } + } + } + } + } + _connected() { + if (this.ended) + return; + __classPrivateFieldGet(this, _AbstractChatCompletionRunner_resolveConnectedPromise, "f").call(this); + this._emit('connect'); + } + get ended() { + return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_ended, "f"); + } + get errored() { + return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_errored, "f"); + } + get aborted() { + return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_aborted, "f"); + } + abort() { + this.controller.abort(); + } + /** + * Adds the listener function to the end of the listeners array for the event. + * No checks are made to see if the listener has already been added. Multiple calls passing + * the same combination of event and listener will result in the listener being added, and + * called, multiple times. + * @returns this ChatCompletionStream, so that calls can be chained + */ + on(event, listener) { + const listeners = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_listeners, "f")[event] || (__classPrivateFieldGet(this, _AbstractChatCompletionRunner_listeners, "f")[event] = []); + listeners.push({ listener }); + return this; + } + /** + * Removes the specified listener from the listener array for the event. + * off() will remove, at most, one instance of a listener from the listener array. If any single + * listener has been added multiple times to the listener array for the specified event, then + * off() must be called multiple times to remove each instance. + * @returns this ChatCompletionStream, so that calls can be chained + */ + off(event, listener) { + const listeners = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_listeners, "f")[event]; + if (!listeners) + return this; + const index = listeners.findIndex((l) => l.listener === listener); + if (index >= 0) + listeners.splice(index, 1); + return this; + } + /** + * Adds a one-time listener function for the event. The next time the event is triggered, + * this listener is removed and then invoked. + * @returns this ChatCompletionStream, so that calls can be chained + */ + once(event, listener) { + const listeners = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_listeners, "f")[event] || (__classPrivateFieldGet(this, _AbstractChatCompletionRunner_listeners, "f")[event] = []); + listeners.push({ listener, once: true }); + return this; + } + /** + * This is similar to `.once()`, but returns a Promise that resolves the next time + * the event is triggered, instead of calling a listener callback. + * @returns a Promise that resolves the next time given event is triggered, + * or rejects if an error is emitted. (If you request the 'error' event, + * returns a promise that resolves with the error). + * + * Example: + * + * const message = await stream.emitted('message') // rejects if the stream errors + */ + emitted(event) { + return new Promise((resolve, reject) => { + __classPrivateFieldSet(this, _AbstractChatCompletionRunner_catchingPromiseCreated, true, "f"); + if (event !== 'error') + this.once('error', reject); + this.once(event, resolve); + }); + } + async done() { + __classPrivateFieldSet(this, _AbstractChatCompletionRunner_catchingPromiseCreated, true, "f"); + await __classPrivateFieldGet(this, _AbstractChatCompletionRunner_endPromise, "f"); + } + /** + * @returns a promise that resolves with the final ChatCompletion, or rejects + * if an error occurred or the stream ended prematurely without producing a ChatCompletion. + */ + async finalChatCompletion() { + await this.done(); + const completion = this._chatCompletions[this._chatCompletions.length - 1]; + if (!completion) + throw new error_1.OpenAIError('stream ended without producing a ChatCompletion'); + return completion; + } + /** + * @returns a promise that resolves with the content of the final ChatCompletionMessage, or rejects + * if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage. + */ + async finalContent() { + await this.done(); + return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalContent).call(this); + } + /** + * @returns a promise that resolves with the the final assistant ChatCompletionMessage response, + * or rejects if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage. + */ + async finalMessage() { + await this.done(); + return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this); + } + /** + * @returns a promise that resolves with the content of the final FunctionCall, or rejects + * if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage. + */ + async finalFunctionCall() { + await this.done(); + return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCall).call(this); + } + async finalFunctionCallResult() { + await this.done(); + return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCallResult).call(this); + } + async totalUsage() { + await this.done(); + return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_calculateTotalUsage).call(this); + } + allChatCompletions() { + return [...this._chatCompletions]; + } + _emit(event, ...args) { + // make sure we don't emit any events after end + if (__classPrivateFieldGet(this, _AbstractChatCompletionRunner_ended, "f")) { + return; + } + if (event === 'end') { + __classPrivateFieldSet(this, _AbstractChatCompletionRunner_ended, true, "f"); + __classPrivateFieldGet(this, _AbstractChatCompletionRunner_resolveEndPromise, "f").call(this); + } + const listeners = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_listeners, "f")[event]; + if (listeners) { + __classPrivateFieldGet(this, _AbstractChatCompletionRunner_listeners, "f")[event] = listeners.filter((l) => !l.once); + listeners.forEach(({ listener }) => listener(...args)); + } + if (event === 'abort') { + const error = args[0]; + if (!__classPrivateFieldGet(this, _AbstractChatCompletionRunner_catchingPromiseCreated, "f") && !listeners?.length) { + Promise.reject(error); + } + __classPrivateFieldGet(this, _AbstractChatCompletionRunner_rejectConnectedPromise, "f").call(this, error); + __classPrivateFieldGet(this, _AbstractChatCompletionRunner_rejectEndPromise, "f").call(this, error); + this._emit('end'); + return; + } + if (event === 'error') { + // NOTE: _emit('error', error) should only be called from #handleError(). + const error = args[0]; + if (!__classPrivateFieldGet(this, _AbstractChatCompletionRunner_catchingPromiseCreated, "f") && !listeners?.length) { + // Trigger an unhandled rejection if the user hasn't registered any error handlers. + // If you are seeing stack traces here, make sure to handle errors via either: + // - runner.on('error', () => ...) + // - await runner.done() + // - await runner.finalChatCompletion() + // - etc. + Promise.reject(error); + } + __classPrivateFieldGet(this, _AbstractChatCompletionRunner_rejectConnectedPromise, "f").call(this, error); + __classPrivateFieldGet(this, _AbstractChatCompletionRunner_rejectEndPromise, "f").call(this, error); + this._emit('end'); + } + } + _emitFinal() { + const completion = this._chatCompletions[this._chatCompletions.length - 1]; + if (completion) + this._emit('finalChatCompletion', completion); + const finalMessage = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this); + if (finalMessage) + this._emit('finalMessage', finalMessage); + const finalContent = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalContent).call(this); + if (finalContent) + this._emit('finalContent', finalContent); + const finalFunctionCall = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCall).call(this); + if (finalFunctionCall) + this._emit('finalFunctionCall', finalFunctionCall); + const finalFunctionCallResult = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCallResult).call(this); + if (finalFunctionCallResult != null) + this._emit('finalFunctionCallResult', finalFunctionCallResult); + if (this._chatCompletions.some((c) => c.usage)) { + this._emit('totalUsage', __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_calculateTotalUsage).call(this)); + } + } + async _createChatCompletion(completions, params, options) { + const signal = options?.signal; + if (signal) { + if (signal.aborted) + this.controller.abort(); + signal.addEventListener('abort', () => this.controller.abort()); + } + __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_validateParams).call(this, params); + const chatCompletion = await completions.create({ ...params, stream: false }, { ...options, signal: this.controller.signal }); + this._connected(); + return this._addChatCompletion(chatCompletion); + } + async _runChatCompletion(completions, params, options) { + for (const message of params.messages) { + this._addMessage(message, false); + } + return await this._createChatCompletion(completions, params, options); + } + async _runFunctions(completions, params, options) { + const role = 'function'; + const { function_call = 'auto', stream, ...restParams } = params; + const singleFunctionToCall = typeof function_call !== 'string' && function_call?.name; + const { maxChatCompletions = DEFAULT_MAX_CHAT_COMPLETIONS } = options || {}; + const functionsByName = {}; + for (const f of params.functions) { + functionsByName[f.name || f.function.name] = f; + } + const functions = params.functions.map((f) => ({ + name: f.name || f.function.name, + parameters: f.parameters, + description: f.description, + })); + for (const message of params.messages) { + this._addMessage(message, false); + } + for (let i = 0; i < maxChatCompletions; ++i) { + const chatCompletion = await this._createChatCompletion(completions, { + ...restParams, + function_call, + functions, + messages: [...this.messages], + }, options); + const message = chatCompletion.choices[0]?.message; + if (!message) { + throw new error_1.OpenAIError(`missing message in ChatCompletion response`); + } + if (!message.function_call) + return; + const { name, arguments: args } = message.function_call; + const fn = functionsByName[name]; + if (!fn) { + const content = `Invalid function_call: ${JSON.stringify(name)}. Available options are: ${functions + .map((f) => JSON.stringify(f.name)) + .join(', ')}. Please try again`; + this._addMessage({ role, name, content }); + continue; + } + else if (singleFunctionToCall && singleFunctionToCall !== name) { + const content = `Invalid function_call: ${JSON.stringify(name)}. ${JSON.stringify(singleFunctionToCall)} requested. Please try again`; + this._addMessage({ role, name, content }); + continue; + } + let parsed; + try { + parsed = (0, RunnableFunction_1.isRunnableFunctionWithParse)(fn) ? await fn.parse(args) : args; + } + catch (error) { + this._addMessage({ + role, + name, + content: error instanceof Error ? error.message : String(error), + }); + continue; + } + // @ts-expect-error it can't rule out `never` type. + const rawContent = await fn.function(parsed, this); + const content = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_stringifyFunctionCallResult).call(this, rawContent); + this._addMessage({ role, name, content }); + if (singleFunctionToCall) + return; + } + } + async _runTools(completions, params, options) { + const role = 'tool'; + const { tool_choice = 'auto', stream, ...restParams } = params; + const singleFunctionToCall = typeof tool_choice !== 'string' && tool_choice?.function?.name; + const { maxChatCompletions = DEFAULT_MAX_CHAT_COMPLETIONS } = options || {}; + const functionsByName = {}; + for (const f of params.tools) { + if (f.type === 'function') { + functionsByName[f.function.name || f.function.function.name] = f.function; + } + } + const tools = 'tools' in params ? + params.tools.map((t) => t.type === 'function' ? + { + type: 'function', + function: { + name: t.function.name || t.function.function.name, + parameters: t.function.parameters, + description: t.function.description, + }, + } + : t) + : undefined; + for (const message of params.messages) { + this._addMessage(message, false); + } + for (let i = 0; i < maxChatCompletions; ++i) { + const chatCompletion = await this._createChatCompletion(completions, { + ...restParams, + tool_choice, + tools, + messages: [...this.messages], + }, options); + const message = chatCompletion.choices[0]?.message; + if (!message) { + throw new error_1.OpenAIError(`missing message in ChatCompletion response`); + } + if (!message.tool_calls) { + return; + } + for (const tool_call of message.tool_calls) { + if (tool_call.type !== 'function') + continue; + const tool_call_id = tool_call.id; + const { name, arguments: args } = tool_call.function; + const fn = functionsByName[name]; + if (!fn) { + const content = `Invalid tool_call: ${JSON.stringify(name)}. Available options are: ${tools + .map((f) => JSON.stringify(f.function.name)) + .join(', ')}. Please try again`; + this._addMessage({ role, tool_call_id, content }); + continue; + } + else if (singleFunctionToCall && singleFunctionToCall !== name) { + const content = `Invalid tool_call: ${JSON.stringify(name)}. ${JSON.stringify(singleFunctionToCall)} requested. Please try again`; + this._addMessage({ role, tool_call_id, content }); + continue; + } + let parsed; + try { + parsed = (0, RunnableFunction_1.isRunnableFunctionWithParse)(fn) ? await fn.parse(args) : args; + } + catch (error) { + const content = error instanceof Error ? error.message : String(error); + this._addMessage({ role, tool_call_id, content }); + continue; + } + // @ts-expect-error it can't rule out `never` type. + const rawContent = await fn.function(parsed, this); + const content = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_stringifyFunctionCallResult).call(this, rawContent); + this._addMessage({ role, tool_call_id, content }); + if (singleFunctionToCall) { + return; + } + } + } + return; + } +} +exports.AbstractChatCompletionRunner = AbstractChatCompletionRunner; +_AbstractChatCompletionRunner_connectedPromise = new WeakMap(), _AbstractChatCompletionRunner_resolveConnectedPromise = new WeakMap(), _AbstractChatCompletionRunner_rejectConnectedPromise = new WeakMap(), _AbstractChatCompletionRunner_endPromise = new WeakMap(), _AbstractChatCompletionRunner_resolveEndPromise = new WeakMap(), _AbstractChatCompletionRunner_rejectEndPromise = new WeakMap(), _AbstractChatCompletionRunner_listeners = new WeakMap(), _AbstractChatCompletionRunner_ended = new WeakMap(), _AbstractChatCompletionRunner_errored = new WeakMap(), _AbstractChatCompletionRunner_aborted = new WeakMap(), _AbstractChatCompletionRunner_catchingPromiseCreated = new WeakMap(), _AbstractChatCompletionRunner_handleError = new WeakMap(), _AbstractChatCompletionRunner_instances = new WeakSet(), _AbstractChatCompletionRunner_getFinalContent = function _AbstractChatCompletionRunner_getFinalContent() { + return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this).content ?? null; +}, _AbstractChatCompletionRunner_getFinalMessage = function _AbstractChatCompletionRunner_getFinalMessage() { + let i = this.messages.length; + while (i-- > 0) { + const message = this.messages[i]; + if ((0, chatCompletionUtils_1.isAssistantMessage)(message)) { + return { ...message, content: message.content ?? null }; + } + } + throw new error_1.OpenAIError('stream ended without producing a ChatCompletionMessage with role=assistant'); +}, _AbstractChatCompletionRunner_getFinalFunctionCall = function _AbstractChatCompletionRunner_getFinalFunctionCall() { + for (let i = this.messages.length - 1; i >= 0; i--) { + const message = this.messages[i]; + if ((0, chatCompletionUtils_1.isAssistantMessage)(message) && message?.function_call) { + return message.function_call; + } + if ((0, chatCompletionUtils_1.isAssistantMessage)(message) && message?.tool_calls?.length) { + return message.tool_calls.at(-1)?.function; + } + } + return; +}, _AbstractChatCompletionRunner_getFinalFunctionCallResult = function _AbstractChatCompletionRunner_getFinalFunctionCallResult() { + for (let i = this.messages.length - 1; i >= 0; i--) { + const message = this.messages[i]; + if ((0, chatCompletionUtils_1.isFunctionMessage)(message) && message.content != null) { + return message.content; + } + if ((0, chatCompletionUtils_1.isToolMessage)(message) && + message.content != null && + this.messages.some((x) => x.role === 'assistant' && + x.tool_calls?.some((y) => y.type === 'function' && y.id === message.tool_call_id))) { + return message.content; + } + } + return; +}, _AbstractChatCompletionRunner_calculateTotalUsage = function _AbstractChatCompletionRunner_calculateTotalUsage() { + const total = { + completion_tokens: 0, + prompt_tokens: 0, + total_tokens: 0, + }; + for (const { usage } of this._chatCompletions) { + if (usage) { + total.completion_tokens += usage.completion_tokens; + total.prompt_tokens += usage.prompt_tokens; + total.total_tokens += usage.total_tokens; + } + } + return total; +}, _AbstractChatCompletionRunner_validateParams = function _AbstractChatCompletionRunner_validateParams(params) { + if (params.n != null && params.n > 1) { + throw new error_1.OpenAIError('ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.'); + } +}, _AbstractChatCompletionRunner_stringifyFunctionCallResult = function _AbstractChatCompletionRunner_stringifyFunctionCallResult(rawContent) { + return (typeof rawContent === 'string' ? rawContent + : rawContent === undefined ? 'undefined' + : JSON.stringify(rawContent)); +}; +//# sourceMappingURL=AbstractChatCompletionRunner.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/lib/AbstractChatCompletionRunner.js.map b/backend/node_modules/openai/lib/AbstractChatCompletionRunner.js.map new file mode 100644 index 0000000000000000000000000000000000000000..6adf79b93b48ff634573410d58139056a3d7b767 --- /dev/null +++ b/backend/node_modules/openai/lib/AbstractChatCompletionRunner.js.map @@ -0,0 +1 @@ +{"version":3,"file":"AbstractChatCompletionRunner.js","sourceRoot":"","sources":["../src/lib/AbstractChatCompletionRunner.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAUA,wCAA8D;AAC9D,4DAI4B;AAM5B,kEAA6F;AAE7F,MAAM,4BAA4B,GAAG,EAAE,CAAC;AAMxC,MAAsB,4BAA4B;IAuBhD;;QApBA,eAAU,GAAoB,IAAI,eAAe,EAAE,CAAC;QAEpD,iEAAiC;QACjC,gEAAuC,GAAG,EAAE,GAAE,CAAC,EAAC;QAChD,+DAAwD,GAAG,EAAE,GAAE,CAAC,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AAI,IAAI,CAAC,gBAAgB,EAAE;QAC7C,IAAI,KAAK,EAAE;YACT,KAAK,CAAC,iBAAiB,IAAI,KAAK,CAAC,iBAAiB,CAAC;YACnD,KAAK,CAAC,aAAa,IAAI,KAAK,CAAC,aAAa,CAAC;YAC3C,KAAK,CAAC,YAAY,IAAI,KAAK,CAAC,YAAY,CAAC;SAC1C;KACF;IACD,OAAO,KAAK,CAAC;AACf,CAAC,uGAkGe,MAAkC;IAChD,IAAI,MAAM,CAAC,CAAC,IAAI,IAAI,IAAI,MAAM,CAAC,CAAC,GAAG,CAAC,EAAE;QACpC,MAAM,IAAI,mBAAW,CACnB,8HAA8H,CAC/H,CAAC;KACH;AACH,CAAC,iIA6N4B,UAAmB;IAC9C,OAAO,CACL,OAAO,UAAU,KAAK,QAAQ,CAAC,CAAC,CAAC,UAAU;QAC3C,CAAC,CAAC,UAAU,KAAK,SAAS,CAAC,CAAC,CAAC,WAAW;YACxC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,UAAU,CAAC,CAC7B,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/openai/lib/AbstractChatCompletionRunner.mjs b/backend/node_modules/openai/lib/AbstractChatCompletionRunner.mjs new file mode 100644 index 0000000000000000000000000000000000000000..d22a9128c0f8b09f79de7e1517affbb1fd327db0 --- /dev/null +++ b/backend/node_modules/openai/lib/AbstractChatCompletionRunner.mjs @@ -0,0 +1,515 @@ +var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +}; +var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var _AbstractChatCompletionRunner_instances, _AbstractChatCompletionRunner_connectedPromise, _AbstractChatCompletionRunner_resolveConnectedPromise, _AbstractChatCompletionRunner_rejectConnectedPromise, _AbstractChatCompletionRunner_endPromise, _AbstractChatCompletionRunner_resolveEndPromise, _AbstractChatCompletionRunner_rejectEndPromise, _AbstractChatCompletionRunner_listeners, _AbstractChatCompletionRunner_ended, _AbstractChatCompletionRunner_errored, _AbstractChatCompletionRunner_aborted, _AbstractChatCompletionRunner_catchingPromiseCreated, _AbstractChatCompletionRunner_getFinalContent, _AbstractChatCompletionRunner_getFinalMessage, _AbstractChatCompletionRunner_getFinalFunctionCall, _AbstractChatCompletionRunner_getFinalFunctionCallResult, _AbstractChatCompletionRunner_calculateTotalUsage, _AbstractChatCompletionRunner_handleError, _AbstractChatCompletionRunner_validateParams, _AbstractChatCompletionRunner_stringifyFunctionCallResult; +import { APIUserAbortError, OpenAIError } from 'openai/error'; +import { isRunnableFunctionWithParse, } from "./RunnableFunction.mjs"; +import { isAssistantMessage, isFunctionMessage, isToolMessage } from "./chatCompletionUtils.mjs"; +const DEFAULT_MAX_CHAT_COMPLETIONS = 10; +export class AbstractChatCompletionRunner { + constructor() { + _AbstractChatCompletionRunner_instances.add(this); + this.controller = new AbortController(); + _AbstractChatCompletionRunner_connectedPromise.set(this, void 0); + _AbstractChatCompletionRunner_resolveConnectedPromise.set(this, () => { }); + _AbstractChatCompletionRunner_rejectConnectedPromise.set(this, () => { }); + _AbstractChatCompletionRunner_endPromise.set(this, void 0); + _AbstractChatCompletionRunner_resolveEndPromise.set(this, () => { }); + _AbstractChatCompletionRunner_rejectEndPromise.set(this, () => { }); + _AbstractChatCompletionRunner_listeners.set(this, {}); + this._chatCompletions = []; + this.messages = []; + _AbstractChatCompletionRunner_ended.set(this, false); + _AbstractChatCompletionRunner_errored.set(this, false); + _AbstractChatCompletionRunner_aborted.set(this, false); + _AbstractChatCompletionRunner_catchingPromiseCreated.set(this, false); + _AbstractChatCompletionRunner_handleError.set(this, (error) => { + __classPrivateFieldSet(this, _AbstractChatCompletionRunner_errored, true, "f"); + if (error instanceof Error && error.name === 'AbortError') { + error = new APIUserAbortError(); + } + if (error instanceof APIUserAbortError) { + __classPrivateFieldSet(this, _AbstractChatCompletionRunner_aborted, true, "f"); + return this._emit('abort', error); + } + if (error instanceof OpenAIError) { + return this._emit('error', error); + } + if (error instanceof Error) { + const openAIError = new OpenAIError(error.message); + // @ts-ignore + openAIError.cause = error; + return this._emit('error', openAIError); + } + return this._emit('error', new OpenAIError(String(error))); + }); + __classPrivateFieldSet(this, _AbstractChatCompletionRunner_connectedPromise, new Promise((resolve, reject) => { + __classPrivateFieldSet(this, _AbstractChatCompletionRunner_resolveConnectedPromise, resolve, "f"); + __classPrivateFieldSet(this, _AbstractChatCompletionRunner_rejectConnectedPromise, reject, "f"); + }), "f"); + __classPrivateFieldSet(this, _AbstractChatCompletionRunner_endPromise, new Promise((resolve, reject) => { + __classPrivateFieldSet(this, _AbstractChatCompletionRunner_resolveEndPromise, resolve, "f"); + __classPrivateFieldSet(this, _AbstractChatCompletionRunner_rejectEndPromise, reject, "f"); + }), "f"); + // Don't let these promises cause unhandled rejection errors. + // we will manually cause an unhandled rejection error later + // if the user hasn't registered any error listener or called + // any promise-returning method. + __classPrivateFieldGet(this, _AbstractChatCompletionRunner_connectedPromise, "f").catch(() => { }); + __classPrivateFieldGet(this, _AbstractChatCompletionRunner_endPromise, "f").catch(() => { }); + } + _run(executor) { + // Unfortunately if we call `executor()` immediately we get runtime errors about + // references to `this` before the `super()` constructor call returns. + setTimeout(() => { + executor().then(() => { + this._emitFinal(); + this._emit('end'); + }, __classPrivateFieldGet(this, _AbstractChatCompletionRunner_handleError, "f")); + }, 0); + } + _addChatCompletion(chatCompletion) { + this._chatCompletions.push(chatCompletion); + this._emit('chatCompletion', chatCompletion); + const message = chatCompletion.choices[0]?.message; + if (message) + this._addMessage(message); + return chatCompletion; + } + _addMessage(message, emit = true) { + if (!('content' in message)) + message.content = null; + this.messages.push(message); + if (emit) { + this._emit('message', message); + if ((isFunctionMessage(message) || isToolMessage(message)) && message.content) { + // Note, this assumes that {role: 'tool', content: …} is always the result of a call of tool of type=function. + this._emit('functionCallResult', message.content); + } + else if (isAssistantMessage(message) && message.function_call) { + this._emit('functionCall', message.function_call); + } + else if (isAssistantMessage(message) && message.tool_calls) { + for (const tool_call of message.tool_calls) { + if (tool_call.type === 'function') { + this._emit('functionCall', tool_call.function); + } + } + } + } + } + _connected() { + if (this.ended) + return; + __classPrivateFieldGet(this, _AbstractChatCompletionRunner_resolveConnectedPromise, "f").call(this); + this._emit('connect'); + } + get ended() { + return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_ended, "f"); + } + get errored() { + return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_errored, "f"); + } + get aborted() { + return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_aborted, "f"); + } + abort() { + this.controller.abort(); + } + /** + * Adds the listener function to the end of the listeners array for the event. + * No checks are made to see if the listener has already been added. Multiple calls passing + * the same combination of event and listener will result in the listener being added, and + * called, multiple times. + * @returns this ChatCompletionStream, so that calls can be chained + */ + on(event, listener) { + const listeners = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_listeners, "f")[event] || (__classPrivateFieldGet(this, _AbstractChatCompletionRunner_listeners, "f")[event] = []); + listeners.push({ listener }); + return this; + } + /** + * Removes the specified listener from the listener array for the event. + * off() will remove, at most, one instance of a listener from the listener array. If any single + * listener has been added multiple times to the listener array for the specified event, then + * off() must be called multiple times to remove each instance. + * @returns this ChatCompletionStream, so that calls can be chained + */ + off(event, listener) { + const listeners = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_listeners, "f")[event]; + if (!listeners) + return this; + const index = listeners.findIndex((l) => l.listener === listener); + if (index >= 0) + listeners.splice(index, 1); + return this; + } + /** + * Adds a one-time listener function for the event. The next time the event is triggered, + * this listener is removed and then invoked. + * @returns this ChatCompletionStream, so that calls can be chained + */ + once(event, listener) { + const listeners = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_listeners, "f")[event] || (__classPrivateFieldGet(this, _AbstractChatCompletionRunner_listeners, "f")[event] = []); + listeners.push({ listener, once: true }); + return this; + } + /** + * This is similar to `.once()`, but returns a Promise that resolves the next time + * the event is triggered, instead of calling a listener callback. + * @returns a Promise that resolves the next time given event is triggered, + * or rejects if an error is emitted. (If you request the 'error' event, + * returns a promise that resolves with the error). + * + * Example: + * + * const message = await stream.emitted('message') // rejects if the stream errors + */ + emitted(event) { + return new Promise((resolve, reject) => { + __classPrivateFieldSet(this, _AbstractChatCompletionRunner_catchingPromiseCreated, true, "f"); + if (event !== 'error') + this.once('error', reject); + this.once(event, resolve); + }); + } + async done() { + __classPrivateFieldSet(this, _AbstractChatCompletionRunner_catchingPromiseCreated, true, "f"); + await __classPrivateFieldGet(this, _AbstractChatCompletionRunner_endPromise, "f"); + } + /** + * @returns a promise that resolves with the final ChatCompletion, or rejects + * if an error occurred or the stream ended prematurely without producing a ChatCompletion. + */ + async finalChatCompletion() { + await this.done(); + const completion = this._chatCompletions[this._chatCompletions.length - 1]; + if (!completion) + throw new OpenAIError('stream ended without producing a ChatCompletion'); + return completion; + } + /** + * @returns a promise that resolves with the content of the final ChatCompletionMessage, or rejects + * if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage. + */ + async finalContent() { + await this.done(); + return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalContent).call(this); + } + /** + * @returns a promise that resolves with the the final assistant ChatCompletionMessage response, + * or rejects if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage. + */ + async finalMessage() { + await this.done(); + return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this); + } + /** + * @returns a promise that resolves with the content of the final FunctionCall, or rejects + * if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage. + */ + async finalFunctionCall() { + await this.done(); + return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCall).call(this); + } + async finalFunctionCallResult() { + await this.done(); + return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCallResult).call(this); + } + async totalUsage() { + await this.done(); + return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_calculateTotalUsage).call(this); + } + allChatCompletions() { + return [...this._chatCompletions]; + } + _emit(event, ...args) { + // make sure we don't emit any events after end + if (__classPrivateFieldGet(this, _AbstractChatCompletionRunner_ended, "f")) { + return; + } + if (event === 'end') { + __classPrivateFieldSet(this, _AbstractChatCompletionRunner_ended, true, "f"); + __classPrivateFieldGet(this, _AbstractChatCompletionRunner_resolveEndPromise, "f").call(this); + } + const listeners = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_listeners, "f")[event]; + if (listeners) { + __classPrivateFieldGet(this, _AbstractChatCompletionRunner_listeners, "f")[event] = listeners.filter((l) => !l.once); + listeners.forEach(({ listener }) => listener(...args)); + } + if (event === 'abort') { + const error = args[0]; + if (!__classPrivateFieldGet(this, _AbstractChatCompletionRunner_catchingPromiseCreated, "f") && !listeners?.length) { + Promise.reject(error); + } + __classPrivateFieldGet(this, _AbstractChatCompletionRunner_rejectConnectedPromise, "f").call(this, error); + __classPrivateFieldGet(this, _AbstractChatCompletionRunner_rejectEndPromise, "f").call(this, error); + this._emit('end'); + return; + } + if (event === 'error') { + // NOTE: _emit('error', error) should only be called from #handleError(). + const error = args[0]; + if (!__classPrivateFieldGet(this, _AbstractChatCompletionRunner_catchingPromiseCreated, "f") && !listeners?.length) { + // Trigger an unhandled rejection if the user hasn't registered any error handlers. + // If you are seeing stack traces here, make sure to handle errors via either: + // - runner.on('error', () => ...) + // - await runner.done() + // - await runner.finalChatCompletion() + // - etc. + Promise.reject(error); + } + __classPrivateFieldGet(this, _AbstractChatCompletionRunner_rejectConnectedPromise, "f").call(this, error); + __classPrivateFieldGet(this, _AbstractChatCompletionRunner_rejectEndPromise, "f").call(this, error); + this._emit('end'); + } + } + _emitFinal() { + const completion = this._chatCompletions[this._chatCompletions.length - 1]; + if (completion) + this._emit('finalChatCompletion', completion); + const finalMessage = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this); + if (finalMessage) + this._emit('finalMessage', finalMessage); + const finalContent = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalContent).call(this); + if (finalContent) + this._emit('finalContent', finalContent); + const finalFunctionCall = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCall).call(this); + if (finalFunctionCall) + this._emit('finalFunctionCall', finalFunctionCall); + const finalFunctionCallResult = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCallResult).call(this); + if (finalFunctionCallResult != null) + this._emit('finalFunctionCallResult', finalFunctionCallResult); + if (this._chatCompletions.some((c) => c.usage)) { + this._emit('totalUsage', __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_calculateTotalUsage).call(this)); + } + } + async _createChatCompletion(completions, params, options) { + const signal = options?.signal; + if (signal) { + if (signal.aborted) + this.controller.abort(); + signal.addEventListener('abort', () => this.controller.abort()); + } + __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_validateParams).call(this, params); + const chatCompletion = await completions.create({ ...params, stream: false }, { ...options, signal: this.controller.signal }); + this._connected(); + return this._addChatCompletion(chatCompletion); + } + async _runChatCompletion(completions, params, options) { + for (const message of params.messages) { + this._addMessage(message, false); + } + return await this._createChatCompletion(completions, params, options); + } + async _runFunctions(completions, params, options) { + const role = 'function'; + const { function_call = 'auto', stream, ...restParams } = params; + const singleFunctionToCall = typeof function_call !== 'string' && function_call?.name; + const { maxChatCompletions = DEFAULT_MAX_CHAT_COMPLETIONS } = options || {}; + const functionsByName = {}; + for (const f of params.functions) { + functionsByName[f.name || f.function.name] = f; + } + const functions = params.functions.map((f) => ({ + name: f.name || f.function.name, + parameters: f.parameters, + description: f.description, + })); + for (const message of params.messages) { + this._addMessage(message, false); + } + for (let i = 0; i < maxChatCompletions; ++i) { + const chatCompletion = await this._createChatCompletion(completions, { + ...restParams, + function_call, + functions, + messages: [...this.messages], + }, options); + const message = chatCompletion.choices[0]?.message; + if (!message) { + throw new OpenAIError(`missing message in ChatCompletion response`); + } + if (!message.function_call) + return; + const { name, arguments: args } = message.function_call; + const fn = functionsByName[name]; + if (!fn) { + const content = `Invalid function_call: ${JSON.stringify(name)}. Available options are: ${functions + .map((f) => JSON.stringify(f.name)) + .join(', ')}. Please try again`; + this._addMessage({ role, name, content }); + continue; + } + else if (singleFunctionToCall && singleFunctionToCall !== name) { + const content = `Invalid function_call: ${JSON.stringify(name)}. ${JSON.stringify(singleFunctionToCall)} requested. Please try again`; + this._addMessage({ role, name, content }); + continue; + } + let parsed; + try { + parsed = isRunnableFunctionWithParse(fn) ? await fn.parse(args) : args; + } + catch (error) { + this._addMessage({ + role, + name, + content: error instanceof Error ? error.message : String(error), + }); + continue; + } + // @ts-expect-error it can't rule out `never` type. + const rawContent = await fn.function(parsed, this); + const content = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_stringifyFunctionCallResult).call(this, rawContent); + this._addMessage({ role, name, content }); + if (singleFunctionToCall) + return; + } + } + async _runTools(completions, params, options) { + const role = 'tool'; + const { tool_choice = 'auto', stream, ...restParams } = params; + const singleFunctionToCall = typeof tool_choice !== 'string' && tool_choice?.function?.name; + const { maxChatCompletions = DEFAULT_MAX_CHAT_COMPLETIONS } = options || {}; + const functionsByName = {}; + for (const f of params.tools) { + if (f.type === 'function') { + functionsByName[f.function.name || f.function.function.name] = f.function; + } + } + const tools = 'tools' in params ? + params.tools.map((t) => t.type === 'function' ? + { + type: 'function', + function: { + name: t.function.name || t.function.function.name, + parameters: t.function.parameters, + description: t.function.description, + }, + } + : t) + : undefined; + for (const message of params.messages) { + this._addMessage(message, false); + } + for (let i = 0; i < maxChatCompletions; ++i) { + const chatCompletion = await this._createChatCompletion(completions, { + ...restParams, + tool_choice, + tools, + messages: [...this.messages], + }, options); + const message = chatCompletion.choices[0]?.message; + if (!message) { + throw new OpenAIError(`missing message in ChatCompletion response`); + } + if (!message.tool_calls) { + return; + } + for (const tool_call of message.tool_calls) { + if (tool_call.type !== 'function') + continue; + const tool_call_id = tool_call.id; + const { name, arguments: args } = tool_call.function; + const fn = functionsByName[name]; + if (!fn) { + const content = `Invalid tool_call: ${JSON.stringify(name)}. Available options are: ${tools + .map((f) => JSON.stringify(f.function.name)) + .join(', ')}. Please try again`; + this._addMessage({ role, tool_call_id, content }); + continue; + } + else if (singleFunctionToCall && singleFunctionToCall !== name) { + const content = `Invalid tool_call: ${JSON.stringify(name)}. ${JSON.stringify(singleFunctionToCall)} requested. Please try again`; + this._addMessage({ role, tool_call_id, content }); + continue; + } + let parsed; + try { + parsed = isRunnableFunctionWithParse(fn) ? await fn.parse(args) : args; + } + catch (error) { + const content = error instanceof Error ? error.message : String(error); + this._addMessage({ role, tool_call_id, content }); + continue; + } + // @ts-expect-error it can't rule out `never` type. + const rawContent = await fn.function(parsed, this); + const content = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_stringifyFunctionCallResult).call(this, rawContent); + this._addMessage({ role, tool_call_id, content }); + if (singleFunctionToCall) { + return; + } + } + } + return; + } +} +_AbstractChatCompletionRunner_connectedPromise = new WeakMap(), _AbstractChatCompletionRunner_resolveConnectedPromise = new WeakMap(), _AbstractChatCompletionRunner_rejectConnectedPromise = new WeakMap(), _AbstractChatCompletionRunner_endPromise = new WeakMap(), _AbstractChatCompletionRunner_resolveEndPromise = new WeakMap(), _AbstractChatCompletionRunner_rejectEndPromise = new WeakMap(), _AbstractChatCompletionRunner_listeners = new WeakMap(), _AbstractChatCompletionRunner_ended = new WeakMap(), _AbstractChatCompletionRunner_errored = new WeakMap(), _AbstractChatCompletionRunner_aborted = new WeakMap(), _AbstractChatCompletionRunner_catchingPromiseCreated = new WeakMap(), _AbstractChatCompletionRunner_handleError = new WeakMap(), _AbstractChatCompletionRunner_instances = new WeakSet(), _AbstractChatCompletionRunner_getFinalContent = function _AbstractChatCompletionRunner_getFinalContent() { + return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this).content ?? null; +}, _AbstractChatCompletionRunner_getFinalMessage = function _AbstractChatCompletionRunner_getFinalMessage() { + let i = this.messages.length; + while (i-- > 0) { + const message = this.messages[i]; + if (isAssistantMessage(message)) { + return { ...message, content: message.content ?? null }; + } + } + throw new OpenAIError('stream ended without producing a ChatCompletionMessage with role=assistant'); +}, _AbstractChatCompletionRunner_getFinalFunctionCall = function _AbstractChatCompletionRunner_getFinalFunctionCall() { + for (let i = this.messages.length - 1; i >= 0; i--) { + const message = this.messages[i]; + if (isAssistantMessage(message) && message?.function_call) { + return message.function_call; + } + if (isAssistantMessage(message) && message?.tool_calls?.length) { + return message.tool_calls.at(-1)?.function; + } + } + return; +}, _AbstractChatCompletionRunner_getFinalFunctionCallResult = function _AbstractChatCompletionRunner_getFinalFunctionCallResult() { + for (let i = this.messages.length - 1; i >= 0; i--) { + const message = this.messages[i]; + if (isFunctionMessage(message) && message.content != null) { + return message.content; + } + if (isToolMessage(message) && + message.content != null && + this.messages.some((x) => x.role === 'assistant' && + x.tool_calls?.some((y) => y.type === 'function' && y.id === message.tool_call_id))) { + return message.content; + } + } + return; +}, _AbstractChatCompletionRunner_calculateTotalUsage = function _AbstractChatCompletionRunner_calculateTotalUsage() { + const total = { + completion_tokens: 0, + prompt_tokens: 0, + total_tokens: 0, + }; + for (const { usage } of this._chatCompletions) { + if (usage) { + total.completion_tokens += usage.completion_tokens; + total.prompt_tokens += usage.prompt_tokens; + total.total_tokens += usage.total_tokens; + } + } + return total; +}, _AbstractChatCompletionRunner_validateParams = function _AbstractChatCompletionRunner_validateParams(params) { + if (params.n != null && params.n > 1) { + throw new OpenAIError('ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.'); + } +}, _AbstractChatCompletionRunner_stringifyFunctionCallResult = function _AbstractChatCompletionRunner_stringifyFunctionCallResult(rawContent) { + return (typeof rawContent === 'string' ? rawContent + : rawContent === undefined ? 'undefined' + : JSON.stringify(rawContent)); +}; +//# sourceMappingURL=AbstractChatCompletionRunner.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/lib/AbstractChatCompletionRunner.mjs.map b/backend/node_modules/openai/lib/AbstractChatCompletionRunner.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..b15639723f72f77b87b5c5c35f664739bf3a10c4 --- /dev/null +++ b/backend/node_modules/openai/lib/AbstractChatCompletionRunner.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"AbstractChatCompletionRunner.mjs","sourceRoot":"","sources":["../src/lib/AbstractChatCompletionRunner.ts"],"names":[],"mappings":";;;;;;;;;;;;OAUO,EAAE,iBAAiB,EAAE,WAAW,EAAE,MAAM,cAAc;OACtD,EAEL,2BAA2B,GAE5B;OAMM,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,aAAa,EAAE;AAE/D,MAAM,4BAA4B,GAAG,EAAE,CAAC;AAMxC,MAAM,OAAgB,4BAA4B;IAuBhD;;QApBA,eAAU,GAAoB,IAAI,eAAe,EAAE,CAAC;QAEpD,iEAAiC;QACjC,gEAAuC,GAAG,EAAE,GAAE,CAAC,EAAC;QAChD,+DAAwD,GAAG,EAAE,GAAE,CAAC,EAAC;QAEjE,2DA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C;YACnD,KAAK,CAAC,aAAa,IAAI,KAAK,CAAC,aAAa,CAAC;YAC3C,KAAK,CAAC,YAAY,IAAI,KAAK,CAAC,YAAY,CAAC;SAC1C;KACF;IACD,OAAO,KAAK,CAAC;AACf,CAAC,uGAkGe,MAAkC;IAChD,IAAI,MAAM,CAAC,CAAC,IAAI,IAAI,IAAI,MAAM,CAAC,CAAC,GAAG,CAAC,EAAE;QACpC,MAAM,IAAI,WAAW,CACnB,8HAA8H,CAC/H,CAAC;KACH;AACH,CAAC,iIA6N4B,UAAmB;IAC9C,OAAO,CACL,OAAO,UAAU,KAAK,QAAQ,CAAC,CAAC,CAAC,UAAU;QAC3C,CAAC,CAAC,UAAU,KAAK,SAAS,CAAC,CAAC,CAAC,WAAW;YACxC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,UAAU,CAAC,CAC7B,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/openai/lib/AssistantStream.d.ts b/backend/node_modules/openai/lib/AssistantStream.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f5cd47ae734151d14126bf81925a9dbb99bdc4da --- /dev/null +++ b/backend/node_modules/openai/lib/AssistantStream.d.ts @@ -0,0 +1,58 @@ +import { Message, Text, ImageFile, TextDelta, Messages } from 'openai/resources/beta/threads/messages/messages'; +import * as Core from 'openai/core'; +import { RequestOptions } from 'openai/core'; +import { Run, RunCreateParamsBase, Runs, RunSubmitToolOutputsParamsBase } from 'openai/resources/beta/threads/runs/runs'; +import { AbstractAssistantRunnerEvents, AbstractAssistantStreamRunner } from "./AbstractAssistantStreamRunner.js"; +import { type ReadableStream } from 'openai/_shims/index'; +import { AssistantStreamEvent } from 'openai/resources/beta/assistants/assistants'; +import { RunStep, RunStepDelta, ToolCall, ToolCallDelta } from 'openai/resources/beta/threads/runs/steps'; +import { ThreadCreateAndRunParamsBase, Threads } from 'openai/resources/beta/threads/threads'; +import MessageDelta = Messages.MessageDelta; +export interface AssistantStreamEvents extends AbstractAssistantRunnerEvents { + messageCreated: (message: Message) => void; + messageDelta: (message: MessageDelta, snapshot: Message) => void; + messageDone: (message: Message) => void; + runStepCreated: (runStep: RunStep) => void; + runStepDelta: (delta: RunStepDelta, snapshot: Runs.RunStep) => void; + runStepDone: (runStep: Runs.RunStep, snapshot: Runs.RunStep) => void; + toolCallCreated: (toolCall: ToolCall) => void; + toolCallDelta: (delta: ToolCallDelta, snapshot: ToolCall) => void; + toolCallDone: (toolCall: ToolCall) => void; + textCreated: (content: Text) => void; + textDelta: (delta: TextDelta, snapshot: Text) => void; + textDone: (content: Text, snapshot: Message) => void; + imageFileDone: (content: ImageFile, snapshot: Message) => void; + end: () => void; + event: (event: AssistantStreamEvent) => void; +} +export type ThreadCreateAndRunParamsBaseStream = Omit & { + stream?: true; +}; +export type RunCreateParamsBaseStream = Omit & { + stream?: true; +}; +export type RunSubmitToolOutputsParamsStream = Omit & { + stream?: true; +}; +export declare class AssistantStream extends AbstractAssistantStreamRunner implements AsyncIterable { + #private; + [Symbol.asyncIterator](): AsyncIterator; + static fromReadableStream(stream: ReadableStream): AssistantStream; + protected _fromReadableStream(readableStream: ReadableStream, options?: Core.RequestOptions): Promise; + toReadableStream(): ReadableStream; + static createToolAssistantStream(threadId: string, runId: string, runs: Runs, body: RunSubmitToolOutputsParamsStream, options: RequestOptions | undefined): AssistantStream; + protected _createToolAssistantStream(run: Runs, threadId: string, runId: string, params: RunSubmitToolOutputsParamsStream, options?: Core.RequestOptions): Promise; + static createThreadAssistantStream(body: ThreadCreateAndRunParamsBaseStream, thread: Threads, options?: RequestOptions): AssistantStream; + static createAssistantStream(threadId: string, runs: Runs, params: RunCreateParamsBaseStream, options?: RequestOptions): AssistantStream; + currentEvent(): AssistantStreamEvent | undefined; + currentRun(): Run | undefined; + currentMessageSnapshot(): Message | undefined; + currentRunStepSnapshot(): Runs.RunStep | undefined; + finalRunSteps(): Promise; + finalMessages(): Promise; + finalRun(): Promise; + protected _createThreadAssistantStream(thread: Threads, params: ThreadCreateAndRunParamsBase, options?: Core.RequestOptions): Promise; + protected _createAssistantStream(run: Runs, threadId: string, params: RunCreateParamsBase, options?: Core.RequestOptions): Promise; + static accumulateDelta(acc: Record, delta: Record): Record; +} +//# sourceMappingURL=AssistantStream.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/lib/AssistantStream.d.ts.map b/backend/node_modules/openai/lib/AssistantStream.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..60eb043645c04ebeedef46654e7289653558c621 --- /dev/null +++ b/backend/node_modules/openai/lib/AssistantStream.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"AssistantStream.d.ts","sourceRoot":"","sources":["../src/lib/AssistantStream.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,OAAO,EAEP,IAAI,EACJ,SAAS,EACT,SAAS,EACT,QAAQ,EACT,MAAM,iDAAiD,CAAC;AACzD,OAAO,KAAK,IAAI,MAAM,aAAa,CAAC;AACpC,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAC7C,OAAO,EACL,GAAG,EACH,mBAAmB,EAEnB,IAAI,EACJ,8BAA8B,EAE/B,MAAM,yCAAyC,CAAC;AACjD,OAAO,EACL,6BAA6B,EAC7B,6BAA6B,EAC9B,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,KAAK,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAG1D,OAAO,EACL,oBAAoB,EAIrB,MAAM,6CAA6C,CAAC;AACrD,OAAO,EAAE,OAAO,EAAE,YAAY,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,0CAA0C,CAAC;AAC1G,OAAO,EAAE,4BAA4B,EAAE,OAAO,EAAE,MAAM,uCAAuC,CAAC;AAC9F,OAAO,YAAY,GAAG,QAAQ,CAAC,YAAY,CAAC;AAE5C,MAAM,WAAW,qBAAsB,SAAQ,6BAA6B;IAE1E,cAAc,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,IAAI,CAAC;IAC3C,YAAY,EAA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B,IAAI,OAAO,GAAG,SAAS;IAI7C,sBAAsB,IAAI,IAAI,CAAC,OAAO,GAAG,SAAS;IAI5C,aAAa,IAAI,OAAO,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC;IAMxC,aAAa,IAAI,OAAO,CAAC,OAAO,EAAE,CAAC;IAMnC,QAAQ,IAAI,OAAO,CAAC,GAAG,CAAC;cAOL,4BAA4B,CACnD,MAAM,EAAE,OAAO,EACf,MAAM,EAAE,4BAA4B,EACpC,OAAO,CAAC,EAAE,IAAI,CAAC,cAAc,GAC5B,OAAO,CAAC,GAAG,CAAC;cAsBU,sBAAsB,CAC7C,GAAG,EAAE,IAAI,EACT,QAAQ,EAAE,MAAM,EAChB,MAAM,EAAE,mBAAmB,EAC3B,OAAO,CAAC,EAAE,IAAI,CAAC,cAAc,GAC5B,OAAO,CAAC,GAAG,CAAC;IAmUf,MAAM,CAAC,eAAe,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EAAE,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC;CAgElG"} \ No newline at end of file diff --git a/backend/node_modules/openai/lib/AssistantStream.js b/backend/node_modules/openai/lib/AssistantStream.js new file mode 100644 index 0000000000000000000000000000000000000000..f8d7deb51ab79daa6dd278cf72807fa240d818fe --- /dev/null +++ b/backend/node_modules/openai/lib/AssistantStream.js @@ -0,0 +1,548 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +}; +var _AssistantStream_instances, _AssistantStream_events, _AssistantStream_runStepSnapshots, _AssistantStream_messageSnapshots, _AssistantStream_messageSnapshot, _AssistantStream_finalRun, _AssistantStream_currentContentIndex, _AssistantStream_currentContent, _AssistantStream_currentToolCallIndex, _AssistantStream_currentToolCall, _AssistantStream_currentEvent, _AssistantStream_currentRunSnapshot, _AssistantStream_currentRunStepSnapshot, _AssistantStream_addEvent, _AssistantStream_endRequest, _AssistantStream_handleMessage, _AssistantStream_handleRunStep, _AssistantStream_handleEvent, _AssistantStream_accumulateRunStep, _AssistantStream_accumulateMessage, _AssistantStream_accumulateContent, _AssistantStream_handleRun; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AssistantStream = void 0; +const Core = __importStar(require("openai/core")); +const AbstractAssistantStreamRunner_1 = require("./AbstractAssistantStreamRunner.js"); +const streaming_1 = require("openai/streaming"); +const error_1 = require("openai/error"); +class AssistantStream extends AbstractAssistantStreamRunner_1.AbstractAssistantStreamRunner { + constructor() { + super(...arguments); + _AssistantStream_instances.add(this); + //Track all events in a single list for reference + _AssistantStream_events.set(this, []); + //Used to accumulate deltas + //We are accumulating many types so the value here is not strict + _AssistantStream_runStepSnapshots.set(this, {}); + _AssistantStream_messageSnapshots.set(this, {}); + _AssistantStream_messageSnapshot.set(this, void 0); + _AssistantStream_finalRun.set(this, void 0); + _AssistantStream_currentContentIndex.set(this, void 0); + _AssistantStream_currentContent.set(this, void 0); + _AssistantStream_currentToolCallIndex.set(this, void 0); + _AssistantStream_currentToolCall.set(this, void 0); + //For current snapshot methods + _AssistantStream_currentEvent.set(this, void 0); + _AssistantStream_currentRunSnapshot.set(this, void 0); + _AssistantStream_currentRunStepSnapshot.set(this, void 0); + } + [(_AssistantStream_events = new WeakMap(), _AssistantStream_runStepSnapshots = new WeakMap(), _AssistantStream_messageSnapshots = new WeakMap(), _AssistantStream_messageSnapshot = new WeakMap(), _AssistantStream_finalRun = new WeakMap(), _AssistantStream_currentContentIndex = new WeakMap(), _AssistantStream_currentContent = new WeakMap(), _AssistantStream_currentToolCallIndex = new WeakMap(), _AssistantStream_currentToolCall = new WeakMap(), _AssistantStream_currentEvent = new WeakMap(), _AssistantStream_currentRunSnapshot = new WeakMap(), _AssistantStream_currentRunStepSnapshot = new WeakMap(), _AssistantStream_instances = new WeakSet(), Symbol.asyncIterator)]() { + const pushQueue = []; + const readQueue = []; + let done = false; + //Catch all for passing along all events + this.on('event', (event) => { + const reader = readQueue.shift(); + if (reader) { + reader.resolve(event); + } + else { + pushQueue.push(event); + } + }); + this.on('end', () => { + done = true; + for (const reader of readQueue) { + reader.resolve(undefined); + } + readQueue.length = 0; + }); + this.on('abort', (err) => { + done = true; + for (const reader of readQueue) { + reader.reject(err); + } + readQueue.length = 0; + }); + this.on('error', (err) => { + done = true; + for (const reader of readQueue) { + reader.reject(err); + } + readQueue.length = 0; + }); + return { + next: async () => { + if (!pushQueue.length) { + if (done) { + return { value: undefined, done: true }; + } + return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((chunk) => (chunk ? { value: chunk, done: false } : { value: undefined, done: true })); + } + const chunk = pushQueue.shift(); + return { value: chunk, done: false }; + }, + return: async () => { + this.abort(); + return { value: undefined, done: true }; + }, + }; + } + static fromReadableStream(stream) { + const runner = new AssistantStream(); + runner._run(() => runner._fromReadableStream(stream)); + return runner; + } + async _fromReadableStream(readableStream, options) { + const signal = options?.signal; + if (signal) { + if (signal.aborted) + this.controller.abort(); + signal.addEventListener('abort', () => this.controller.abort()); + } + this._connected(); + const stream = streaming_1.Stream.fromReadableStream(readableStream, this.controller); + for await (const event of stream) { + __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event); + } + if (stream.controller.signal?.aborted) { + throw new error_1.APIUserAbortError(); + } + return this._addRun(__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this)); + } + toReadableStream() { + const stream = new streaming_1.Stream(this[Symbol.asyncIterator].bind(this), this.controller); + return stream.toReadableStream(); + } + static createToolAssistantStream(threadId, runId, runs, body, options) { + const runner = new AssistantStream(); + runner._run(() => runner._runToolAssistantStream(threadId, runId, runs, body, { + ...options, + headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' }, + })); + return runner; + } + async _createToolAssistantStream(run, threadId, runId, params, options) { + const signal = options?.signal; + if (signal) { + if (signal.aborted) + this.controller.abort(); + signal.addEventListener('abort', () => this.controller.abort()); + } + const body = { ...params, stream: true }; + const stream = await run.submitToolOutputs(threadId, runId, body, { + ...options, + signal: this.controller.signal, + }); + this._connected(); + for await (const event of stream) { + __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event); + } + if (stream.controller.signal?.aborted) { + throw new error_1.APIUserAbortError(); + } + return this._addRun(__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this)); + } + static createThreadAssistantStream(body, thread, options) { + const runner = new AssistantStream(); + runner._run(() => runner._threadAssistantStream(body, thread, { + ...options, + headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' }, + })); + return runner; + } + static createAssistantStream(threadId, runs, params, options) { + const runner = new AssistantStream(); + runner._run(() => runner._runAssistantStream(threadId, runs, params, { + ...options, + headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' }, + })); + return runner; + } + currentEvent() { + return __classPrivateFieldGet(this, _AssistantStream_currentEvent, "f"); + } + currentRun() { + return __classPrivateFieldGet(this, _AssistantStream_currentRunSnapshot, "f"); + } + currentMessageSnapshot() { + return __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f"); + } + currentRunStepSnapshot() { + return __classPrivateFieldGet(this, _AssistantStream_currentRunStepSnapshot, "f"); + } + async finalRunSteps() { + await this.done(); + return Object.values(__classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")); + } + async finalMessages() { + await this.done(); + return Object.values(__classPrivateFieldGet(this, _AssistantStream_messageSnapshots, "f")); + } + async finalRun() { + await this.done(); + if (!__classPrivateFieldGet(this, _AssistantStream_finalRun, "f")) + throw Error('Final run was not received.'); + return __classPrivateFieldGet(this, _AssistantStream_finalRun, "f"); + } + async _createThreadAssistantStream(thread, params, options) { + const signal = options?.signal; + if (signal) { + if (signal.aborted) + this.controller.abort(); + signal.addEventListener('abort', () => this.controller.abort()); + } + const body = { ...params, stream: true }; + const stream = await thread.createAndRun(body, { ...options, signal: this.controller.signal }); + this._connected(); + for await (const event of stream) { + __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event); + } + if (stream.controller.signal?.aborted) { + throw new error_1.APIUserAbortError(); + } + return this._addRun(__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this)); + } + async _createAssistantStream(run, threadId, params, options) { + const signal = options?.signal; + if (signal) { + if (signal.aborted) + this.controller.abort(); + signal.addEventListener('abort', () => this.controller.abort()); + } + const body = { ...params, stream: true }; + const stream = await run.create(threadId, body, { ...options, signal: this.controller.signal }); + this._connected(); + for await (const event of stream) { + __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event); + } + if (stream.controller.signal?.aborted) { + throw new error_1.APIUserAbortError(); + } + return this._addRun(__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this)); + } + static accumulateDelta(acc, delta) { + for (const [key, deltaValue] of Object.entries(delta)) { + if (!acc.hasOwnProperty(key)) { + acc[key] = deltaValue; + continue; + } + let accValue = acc[key]; + if (accValue === null || accValue === undefined) { + acc[key] = deltaValue; + continue; + } + // We don't accumulate these special properties + if (key === 'index' || key === 'type') { + acc[key] = deltaValue; + continue; + } + // Type-specific accumulation logic + if (typeof accValue === 'string' && typeof deltaValue === 'string') { + accValue += deltaValue; + } + else if (typeof accValue === 'number' && typeof deltaValue === 'number') { + accValue += deltaValue; + } + else if (Core.isObj(accValue) && Core.isObj(deltaValue)) { + accValue = this.accumulateDelta(accValue, deltaValue); + } + else if (Array.isArray(accValue) && Array.isArray(deltaValue)) { + if (accValue.every((x) => typeof x === 'string' || typeof x === 'number')) { + accValue.push(...deltaValue); // Use spread syntax for efficient addition + continue; + } + } + else { + throw Error(`Unhandled record type: ${key}, deltaValue: ${deltaValue}, accValue: ${accValue}`); + } + acc[key] = accValue; + } + return acc; + } +} +exports.AssistantStream = AssistantStream; +_AssistantStream_addEvent = function _AssistantStream_addEvent(event) { + if (this.ended) + return; + __classPrivateFieldSet(this, _AssistantStream_currentEvent, event, "f"); + __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleEvent).call(this, event); + switch (event.event) { + case 'thread.created': + //No action on this event. + break; + case 'thread.run.created': + case 'thread.run.queued': + case 'thread.run.in_progress': + case 'thread.run.requires_action': + case 'thread.run.completed': + case 'thread.run.failed': + case 'thread.run.cancelling': + case 'thread.run.cancelled': + case 'thread.run.expired': + __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleRun).call(this, event); + break; + case 'thread.run.step.created': + case 'thread.run.step.in_progress': + case 'thread.run.step.delta': + case 'thread.run.step.completed': + case 'thread.run.step.failed': + case 'thread.run.step.cancelled': + case 'thread.run.step.expired': + __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleRunStep).call(this, event); + break; + case 'thread.message.created': + case 'thread.message.in_progress': + case 'thread.message.delta': + case 'thread.message.completed': + case 'thread.message.incomplete': + __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleMessage).call(this, event); + break; + case 'error': + //This is included for completeness, but errors are processed in the SSE event processing so this should not occur + throw new Error('Encountered an error event in event processing - errors should be processed earlier'); + } +}, _AssistantStream_endRequest = function _AssistantStream_endRequest() { + if (this.ended) { + throw new error_1.OpenAIError(`stream has ended, this shouldn't happen`); + } + if (!__classPrivateFieldGet(this, _AssistantStream_finalRun, "f")) + throw Error('Final run has not been received'); + return __classPrivateFieldGet(this, _AssistantStream_finalRun, "f"); +}, _AssistantStream_handleMessage = function _AssistantStream_handleMessage(event) { + const [accumulatedMessage, newContent] = __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_accumulateMessage).call(this, event, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")); + __classPrivateFieldSet(this, _AssistantStream_messageSnapshot, accumulatedMessage, "f"); + __classPrivateFieldGet(this, _AssistantStream_messageSnapshots, "f")[accumulatedMessage.id] = accumulatedMessage; + for (const content of newContent) { + const snapshotContent = accumulatedMessage.content[content.index]; + if (snapshotContent?.type == 'text') { + this._emit('textCreated', snapshotContent.text); + } + } + switch (event.event) { + case 'thread.message.created': + this._emit('messageCreated', event.data); + break; + case 'thread.message.in_progress': + break; + case 'thread.message.delta': + this._emit('messageDelta', event.data.delta, accumulatedMessage); + if (event.data.delta.content) { + for (const content of event.data.delta.content) { + //If it is text delta, emit a text delta event + if (content.type == 'text' && content.text) { + let textDelta = content.text; + let snapshot = accumulatedMessage.content[content.index]; + if (snapshot && snapshot.type == 'text') { + this._emit('textDelta', textDelta, snapshot.text); + } + else { + throw Error('The snapshot associated with this text delta is not text or missing'); + } + } + if (content.index != __classPrivateFieldGet(this, _AssistantStream_currentContentIndex, "f")) { + //See if we have in progress content + if (__classPrivateFieldGet(this, _AssistantStream_currentContent, "f")) { + switch (__classPrivateFieldGet(this, _AssistantStream_currentContent, "f").type) { + case 'text': + this._emit('textDone', __classPrivateFieldGet(this, _AssistantStream_currentContent, "f").text, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")); + break; + case 'image_file': + this._emit('imageFileDone', __classPrivateFieldGet(this, _AssistantStream_currentContent, "f").image_file, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")); + break; + } + } + __classPrivateFieldSet(this, _AssistantStream_currentContentIndex, content.index, "f"); + } + __classPrivateFieldSet(this, _AssistantStream_currentContent, accumulatedMessage.content[content.index], "f"); + } + } + break; + case 'thread.message.completed': + case 'thread.message.incomplete': + //We emit the latest content we were working on on completion (including incomplete) + if (__classPrivateFieldGet(this, _AssistantStream_currentContentIndex, "f") !== undefined) { + const currentContent = event.data.content[__classPrivateFieldGet(this, _AssistantStream_currentContentIndex, "f")]; + if (currentContent) { + switch (currentContent.type) { + case 'image_file': + this._emit('imageFileDone', currentContent.image_file, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")); + break; + case 'text': + this._emit('textDone', currentContent.text, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")); + break; + } + } + } + if (__classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")) { + this._emit('messageDone', event.data); + } + __classPrivateFieldSet(this, _AssistantStream_messageSnapshot, undefined, "f"); + } +}, _AssistantStream_handleRunStep = function _AssistantStream_handleRunStep(event) { + const accumulatedRunStep = __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_accumulateRunStep).call(this, event); + __classPrivateFieldSet(this, _AssistantStream_currentRunStepSnapshot, accumulatedRunStep, "f"); + switch (event.event) { + case 'thread.run.step.created': + this._emit('runStepCreated', event.data); + break; + case 'thread.run.step.delta': + const delta = event.data.delta; + if (delta.step_details && + delta.step_details.type == 'tool_calls' && + delta.step_details.tool_calls && + accumulatedRunStep.step_details.type == 'tool_calls') { + for (const toolCall of delta.step_details.tool_calls) { + if (toolCall.index == __classPrivateFieldGet(this, _AssistantStream_currentToolCallIndex, "f")) { + this._emit('toolCallDelta', toolCall, accumulatedRunStep.step_details.tool_calls[toolCall.index]); + } + else { + if (__classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")) { + this._emit('toolCallDone', __classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")); + } + __classPrivateFieldSet(this, _AssistantStream_currentToolCallIndex, toolCall.index, "f"); + __classPrivateFieldSet(this, _AssistantStream_currentToolCall, accumulatedRunStep.step_details.tool_calls[toolCall.index], "f"); + if (__classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")) + this._emit('toolCallCreated', __classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")); + } + } + } + this._emit('runStepDelta', event.data.delta, accumulatedRunStep); + break; + case 'thread.run.step.completed': + case 'thread.run.step.failed': + case 'thread.run.step.cancelled': + case 'thread.run.step.expired': + __classPrivateFieldSet(this, _AssistantStream_currentRunStepSnapshot, undefined, "f"); + const details = event.data.step_details; + if (details.type == 'tool_calls') { + if (__classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")) { + this._emit('toolCallDone', __classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")); + __classPrivateFieldSet(this, _AssistantStream_currentToolCall, undefined, "f"); + } + } + this._emit('runStepDone', event.data, accumulatedRunStep); + break; + case 'thread.run.step.in_progress': + break; + } +}, _AssistantStream_handleEvent = function _AssistantStream_handleEvent(event) { + __classPrivateFieldGet(this, _AssistantStream_events, "f").push(event); + this._emit('event', event); +}, _AssistantStream_accumulateRunStep = function _AssistantStream_accumulateRunStep(event) { + switch (event.event) { + case 'thread.run.step.created': + __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = event.data; + return event.data; + case 'thread.run.step.delta': + let snapshot = __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id]; + if (!snapshot) { + throw Error('Received a RunStepDelta before creation of a snapshot'); + } + let data = event.data; + if (data.delta) { + const accumulated = AssistantStream.accumulateDelta(snapshot, data.delta); + __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = accumulated; + } + return __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id]; + case 'thread.run.step.completed': + case 'thread.run.step.failed': + case 'thread.run.step.cancelled': + case 'thread.run.step.expired': + case 'thread.run.step.in_progress': + __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = event.data; + break; + } + if (__classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id]) + return __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id]; + throw new Error('No snapshot available'); +}, _AssistantStream_accumulateMessage = function _AssistantStream_accumulateMessage(event, snapshot) { + let newContent = []; + switch (event.event) { + case 'thread.message.created': + //On creation the snapshot is just the initial message + return [event.data, newContent]; + case 'thread.message.delta': + if (!snapshot) { + throw Error('Received a delta with no existing snapshot (there should be one from message creation)'); + } + let data = event.data; + //If this delta does not have content, nothing to process + if (data.delta.content) { + for (const contentElement of data.delta.content) { + if (contentElement.index in snapshot.content) { + let currentContent = snapshot.content[contentElement.index]; + snapshot.content[contentElement.index] = __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_accumulateContent).call(this, contentElement, currentContent); + } + else { + snapshot.content[contentElement.index] = contentElement; + //This is a new element + newContent.push(contentElement); + } + } + } + return [snapshot, newContent]; + case 'thread.message.in_progress': + case 'thread.message.completed': + case 'thread.message.incomplete': + //No changes on other thread events + if (snapshot) { + return [snapshot, newContent]; + } + else { + throw Error('Received thread message event with no existing snapshot'); + } + } + throw Error('Tried to accumulate a non-message event'); +}, _AssistantStream_accumulateContent = function _AssistantStream_accumulateContent(contentElement, currentContent) { + return AssistantStream.accumulateDelta(currentContent, contentElement); +}, _AssistantStream_handleRun = function _AssistantStream_handleRun(event) { + __classPrivateFieldSet(this, _AssistantStream_currentRunSnapshot, event.data, "f"); + switch (event.event) { + case 'thread.run.created': + break; + case 'thread.run.queued': + break; + case 'thread.run.in_progress': + break; + case 'thread.run.requires_action': + case 'thread.run.cancelled': + case 'thread.run.failed': + case 'thread.run.completed': + case 'thread.run.expired': + __classPrivateFieldSet(this, _AssistantStream_finalRun, event.data, "f"); + if (__classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")) { + this._emit('toolCallDone', __classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")); + __classPrivateFieldSet(this, _AssistantStream_currentToolCall, undefined, "f"); + } + break; + case 'thread.run.cancelling': + break; + } +}; +//# sourceMappingURL=AssistantStream.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/lib/AssistantStream.js.map b/backend/node_modules/openai/lib/AssistantStream.js.map new file mode 100644 index 0000000000000000000000000000000000000000..22c37a5be479c2d24fdd84c88e97dfca9f2b8169 --- /dev/null +++ b/backend/node_modules/openai/lib/AssistantStream.js.map @@ -0,0 +1 @@ +{"version":3,"file":"AssistantStream.js","sourceRoot":"","sources":["../src/lib/AssistantStream.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAUA,kDAAoC;AAUpC,sFAGyC;AAEzC,gDAA0C;AAC1C,wCAA8D;AAiD9D,MAAa,eACX,SAAQ,6DAAoD;IAD9D;;;QAIE,iDAAiD;QACjD,kCAAkC,EAAE,EAAC;QAErC,2BAA2B;QAC3B,gEAAgE;QAChE,4CAAoD,EAAE,EAAC;QACvD,4CAA+C,EAAE,EAAC;QAClD,mDAAsC;QACtC,4CAA2B;QAC3B,uDAAyC;QACzC,kDAAsE;QACtE,wDAA0C;QAC1C,mDAA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KACJ;IACD,MAAM,KAAK,CAAC,yCAAyC,CAAC,CAAC;AACzD,CAAC,mFAGC,cAAmC,EACnC,cAAoE;IAEpE,OAAO,eAAe,CAAC,eAAe,CAAC,cAA6C,EAAE,cAAc,CAE3E,CAAC;AAC5B,CAAC,mEA0CU,KAAqB;IAC9B,uBAAA,IAAI,uCAAuB,KAAK,CAAC,IAAI,MAAA,CAAC;IACtC,QAAQ,KAAK,CAAC,KAAK,EAAE;QACnB,KAAK,oBAAoB;YACvB,MAAM;QACR,KAAK,mBAAmB;YACtB,MAAM;QACR,KAAK,wBAAwB;YAC3B,MAAM;QACR,KAAK,4BAA4B,CAAC;QAClC,KAAK,sBAAsB,CAAC;QAC5B,KAAK,mBAAmB,CAAC;QACzB,KAAK,sBAAsB,CAAC;QAC5B,KAAK,oBAAoB;YACvB,uBAAA,IAAI,6BAAa,KAAK,CAAC,IAAI,MAAA,CAAC;YAC5B,IAAI,uBAAA,IAAI,wCAAiB,EAAE;gBACzB,IAAI,CAAC,KAAK,CAAC,cAAc,EAAE,uBAAA,IAAI,wCAAiB,CAAC,CAAC;gBAClD,uBAAA,IAAI,oCAAoB,SAAS,MAAA,CAAC;aACnC;YACD,MAAM;QACR,KAAK,uBAAuB;YAC1B,MAAM;KACT;AACH,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/openai/lib/AssistantStream.mjs b/backend/node_modules/openai/lib/AssistantStream.mjs new file mode 100644 index 0000000000000000000000000000000000000000..96a74a8d3ba6824fa33caa886df9f99a6406b25a --- /dev/null +++ b/backend/node_modules/openai/lib/AssistantStream.mjs @@ -0,0 +1,521 @@ +var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +}; +var _AssistantStream_instances, _AssistantStream_events, _AssistantStream_runStepSnapshots, _AssistantStream_messageSnapshots, _AssistantStream_messageSnapshot, _AssistantStream_finalRun, _AssistantStream_currentContentIndex, _AssistantStream_currentContent, _AssistantStream_currentToolCallIndex, _AssistantStream_currentToolCall, _AssistantStream_currentEvent, _AssistantStream_currentRunSnapshot, _AssistantStream_currentRunStepSnapshot, _AssistantStream_addEvent, _AssistantStream_endRequest, _AssistantStream_handleMessage, _AssistantStream_handleRunStep, _AssistantStream_handleEvent, _AssistantStream_accumulateRunStep, _AssistantStream_accumulateMessage, _AssistantStream_accumulateContent, _AssistantStream_handleRun; +import * as Core from 'openai/core'; +import { AbstractAssistantStreamRunner, } from "./AbstractAssistantStreamRunner.mjs"; +import { Stream } from 'openai/streaming'; +import { APIUserAbortError, OpenAIError } from 'openai/error'; +export class AssistantStream extends AbstractAssistantStreamRunner { + constructor() { + super(...arguments); + _AssistantStream_instances.add(this); + //Track all events in a single list for reference + _AssistantStream_events.set(this, []); + //Used to accumulate deltas + //We are accumulating many types so the value here is not strict + _AssistantStream_runStepSnapshots.set(this, {}); + _AssistantStream_messageSnapshots.set(this, {}); + _AssistantStream_messageSnapshot.set(this, void 0); + _AssistantStream_finalRun.set(this, void 0); + _AssistantStream_currentContentIndex.set(this, void 0); + _AssistantStream_currentContent.set(this, void 0); + _AssistantStream_currentToolCallIndex.set(this, void 0); + _AssistantStream_currentToolCall.set(this, void 0); + //For current snapshot methods + _AssistantStream_currentEvent.set(this, void 0); + _AssistantStream_currentRunSnapshot.set(this, void 0); + _AssistantStream_currentRunStepSnapshot.set(this, void 0); + } + [(_AssistantStream_events = new WeakMap(), _AssistantStream_runStepSnapshots = new WeakMap(), _AssistantStream_messageSnapshots = new WeakMap(), _AssistantStream_messageSnapshot = new WeakMap(), _AssistantStream_finalRun = new WeakMap(), _AssistantStream_currentContentIndex = new WeakMap(), _AssistantStream_currentContent = new WeakMap(), _AssistantStream_currentToolCallIndex = new WeakMap(), _AssistantStream_currentToolCall = new WeakMap(), _AssistantStream_currentEvent = new WeakMap(), _AssistantStream_currentRunSnapshot = new WeakMap(), _AssistantStream_currentRunStepSnapshot = new WeakMap(), _AssistantStream_instances = new WeakSet(), Symbol.asyncIterator)]() { + const pushQueue = []; + const readQueue = []; + let done = false; + //Catch all for passing along all events + this.on('event', (event) => { + const reader = readQueue.shift(); + if (reader) { + reader.resolve(event); + } + else { + pushQueue.push(event); + } + }); + this.on('end', () => { + done = true; + for (const reader of readQueue) { + reader.resolve(undefined); + } + readQueue.length = 0; + }); + this.on('abort', (err) => { + done = true; + for (const reader of readQueue) { + reader.reject(err); + } + readQueue.length = 0; + }); + this.on('error', (err) => { + done = true; + for (const reader of readQueue) { + reader.reject(err); + } + readQueue.length = 0; + }); + return { + next: async () => { + if (!pushQueue.length) { + if (done) { + return { value: undefined, done: true }; + } + return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((chunk) => (chunk ? { value: chunk, done: false } : { value: undefined, done: true })); + } + const chunk = pushQueue.shift(); + return { value: chunk, done: false }; + }, + return: async () => { + this.abort(); + return { value: undefined, done: true }; + }, + }; + } + static fromReadableStream(stream) { + const runner = new AssistantStream(); + runner._run(() => runner._fromReadableStream(stream)); + return runner; + } + async _fromReadableStream(readableStream, options) { + const signal = options?.signal; + if (signal) { + if (signal.aborted) + this.controller.abort(); + signal.addEventListener('abort', () => this.controller.abort()); + } + this._connected(); + const stream = Stream.fromReadableStream(readableStream, this.controller); + for await (const event of stream) { + __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event); + } + if (stream.controller.signal?.aborted) { + throw new APIUserAbortError(); + } + return this._addRun(__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this)); + } + toReadableStream() { + const stream = new Stream(this[Symbol.asyncIterator].bind(this), this.controller); + return stream.toReadableStream(); + } + static createToolAssistantStream(threadId, runId, runs, body, options) { + const runner = new AssistantStream(); + runner._run(() => runner._runToolAssistantStream(threadId, runId, runs, body, { + ...options, + headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' }, + })); + return runner; + } + async _createToolAssistantStream(run, threadId, runId, params, options) { + const signal = options?.signal; + if (signal) { + if (signal.aborted) + this.controller.abort(); + signal.addEventListener('abort', () => this.controller.abort()); + } + const body = { ...params, stream: true }; + const stream = await run.submitToolOutputs(threadId, runId, body, { + ...options, + signal: this.controller.signal, + }); + this._connected(); + for await (const event of stream) { + __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event); + } + if (stream.controller.signal?.aborted) { + throw new APIUserAbortError(); + } + return this._addRun(__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this)); + } + static createThreadAssistantStream(body, thread, options) { + const runner = new AssistantStream(); + runner._run(() => runner._threadAssistantStream(body, thread, { + ...options, + headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' }, + })); + return runner; + } + static createAssistantStream(threadId, runs, params, options) { + const runner = new AssistantStream(); + runner._run(() => runner._runAssistantStream(threadId, runs, params, { + ...options, + headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' }, + })); + return runner; + } + currentEvent() { + return __classPrivateFieldGet(this, _AssistantStream_currentEvent, "f"); + } + currentRun() { + return __classPrivateFieldGet(this, _AssistantStream_currentRunSnapshot, "f"); + } + currentMessageSnapshot() { + return __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f"); + } + currentRunStepSnapshot() { + return __classPrivateFieldGet(this, _AssistantStream_currentRunStepSnapshot, "f"); + } + async finalRunSteps() { + await this.done(); + return Object.values(__classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")); + } + async finalMessages() { + await this.done(); + return Object.values(__classPrivateFieldGet(this, _AssistantStream_messageSnapshots, "f")); + } + async finalRun() { + await this.done(); + if (!__classPrivateFieldGet(this, _AssistantStream_finalRun, "f")) + throw Error('Final run was not received.'); + return __classPrivateFieldGet(this, _AssistantStream_finalRun, "f"); + } + async _createThreadAssistantStream(thread, params, options) { + const signal = options?.signal; + if (signal) { + if (signal.aborted) + this.controller.abort(); + signal.addEventListener('abort', () => this.controller.abort()); + } + const body = { ...params, stream: true }; + const stream = await thread.createAndRun(body, { ...options, signal: this.controller.signal }); + this._connected(); + for await (const event of stream) { + __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event); + } + if (stream.controller.signal?.aborted) { + throw new APIUserAbortError(); + } + return this._addRun(__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this)); + } + async _createAssistantStream(run, threadId, params, options) { + const signal = options?.signal; + if (signal) { + if (signal.aborted) + this.controller.abort(); + signal.addEventListener('abort', () => this.controller.abort()); + } + const body = { ...params, stream: true }; + const stream = await run.create(threadId, body, { ...options, signal: this.controller.signal }); + this._connected(); + for await (const event of stream) { + __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event); + } + if (stream.controller.signal?.aborted) { + throw new APIUserAbortError(); + } + return this._addRun(__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this)); + } + static accumulateDelta(acc, delta) { + for (const [key, deltaValue] of Object.entries(delta)) { + if (!acc.hasOwnProperty(key)) { + acc[key] = deltaValue; + continue; + } + let accValue = acc[key]; + if (accValue === null || accValue === undefined) { + acc[key] = deltaValue; + continue; + } + // We don't accumulate these special properties + if (key === 'index' || key === 'type') { + acc[key] = deltaValue; + continue; + } + // Type-specific accumulation logic + if (typeof accValue === 'string' && typeof deltaValue === 'string') { + accValue += deltaValue; + } + else if (typeof accValue === 'number' && typeof deltaValue === 'number') { + accValue += deltaValue; + } + else if (Core.isObj(accValue) && Core.isObj(deltaValue)) { + accValue = this.accumulateDelta(accValue, deltaValue); + } + else if (Array.isArray(accValue) && Array.isArray(deltaValue)) { + if (accValue.every((x) => typeof x === 'string' || typeof x === 'number')) { + accValue.push(...deltaValue); // Use spread syntax for efficient addition + continue; + } + } + else { + throw Error(`Unhandled record type: ${key}, deltaValue: ${deltaValue}, accValue: ${accValue}`); + } + acc[key] = accValue; + } + return acc; + } +} +_AssistantStream_addEvent = function _AssistantStream_addEvent(event) { + if (this.ended) + return; + __classPrivateFieldSet(this, _AssistantStream_currentEvent, event, "f"); + __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleEvent).call(this, event); + switch (event.event) { + case 'thread.created': + //No action on this event. + break; + case 'thread.run.created': + case 'thread.run.queued': + case 'thread.run.in_progress': + case 'thread.run.requires_action': + case 'thread.run.completed': + case 'thread.run.failed': + case 'thread.run.cancelling': + case 'thread.run.cancelled': + case 'thread.run.expired': + __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleRun).call(this, event); + break; + case 'thread.run.step.created': + case 'thread.run.step.in_progress': + case 'thread.run.step.delta': + case 'thread.run.step.completed': + case 'thread.run.step.failed': + case 'thread.run.step.cancelled': + case 'thread.run.step.expired': + __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleRunStep).call(this, event); + break; + case 'thread.message.created': + case 'thread.message.in_progress': + case 'thread.message.delta': + case 'thread.message.completed': + case 'thread.message.incomplete': + __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleMessage).call(this, event); + break; + case 'error': + //This is included for completeness, but errors are processed in the SSE event processing so this should not occur + throw new Error('Encountered an error event in event processing - errors should be processed earlier'); + } +}, _AssistantStream_endRequest = function _AssistantStream_endRequest() { + if (this.ended) { + throw new OpenAIError(`stream has ended, this shouldn't happen`); + } + if (!__classPrivateFieldGet(this, _AssistantStream_finalRun, "f")) + throw Error('Final run has not been received'); + return __classPrivateFieldGet(this, _AssistantStream_finalRun, "f"); +}, _AssistantStream_handleMessage = function _AssistantStream_handleMessage(event) { + const [accumulatedMessage, newContent] = __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_accumulateMessage).call(this, event, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")); + __classPrivateFieldSet(this, _AssistantStream_messageSnapshot, accumulatedMessage, "f"); + __classPrivateFieldGet(this, _AssistantStream_messageSnapshots, "f")[accumulatedMessage.id] = accumulatedMessage; + for (const content of newContent) { + const snapshotContent = accumulatedMessage.content[content.index]; + if (snapshotContent?.type == 'text') { + this._emit('textCreated', snapshotContent.text); + } + } + switch (event.event) { + case 'thread.message.created': + this._emit('messageCreated', event.data); + break; + case 'thread.message.in_progress': + break; + case 'thread.message.delta': + this._emit('messageDelta', event.data.delta, accumulatedMessage); + if (event.data.delta.content) { + for (const content of event.data.delta.content) { + //If it is text delta, emit a text delta event + if (content.type == 'text' && content.text) { + let textDelta = content.text; + let snapshot = accumulatedMessage.content[content.index]; + if (snapshot && snapshot.type == 'text') { + this._emit('textDelta', textDelta, snapshot.text); + } + else { + throw Error('The snapshot associated with this text delta is not text or missing'); + } + } + if (content.index != __classPrivateFieldGet(this, _AssistantStream_currentContentIndex, "f")) { + //See if we have in progress content + if (__classPrivateFieldGet(this, _AssistantStream_currentContent, "f")) { + switch (__classPrivateFieldGet(this, _AssistantStream_currentContent, "f").type) { + case 'text': + this._emit('textDone', __classPrivateFieldGet(this, _AssistantStream_currentContent, "f").text, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")); + break; + case 'image_file': + this._emit('imageFileDone', __classPrivateFieldGet(this, _AssistantStream_currentContent, "f").image_file, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")); + break; + } + } + __classPrivateFieldSet(this, _AssistantStream_currentContentIndex, content.index, "f"); + } + __classPrivateFieldSet(this, _AssistantStream_currentContent, accumulatedMessage.content[content.index], "f"); + } + } + break; + case 'thread.message.completed': + case 'thread.message.incomplete': + //We emit the latest content we were working on on completion (including incomplete) + if (__classPrivateFieldGet(this, _AssistantStream_currentContentIndex, "f") !== undefined) { + const currentContent = event.data.content[__classPrivateFieldGet(this, _AssistantStream_currentContentIndex, "f")]; + if (currentContent) { + switch (currentContent.type) { + case 'image_file': + this._emit('imageFileDone', currentContent.image_file, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")); + break; + case 'text': + this._emit('textDone', currentContent.text, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")); + break; + } + } + } + if (__classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")) { + this._emit('messageDone', event.data); + } + __classPrivateFieldSet(this, _AssistantStream_messageSnapshot, undefined, "f"); + } +}, _AssistantStream_handleRunStep = function _AssistantStream_handleRunStep(event) { + const accumulatedRunStep = __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_accumulateRunStep).call(this, event); + __classPrivateFieldSet(this, _AssistantStream_currentRunStepSnapshot, accumulatedRunStep, "f"); + switch (event.event) { + case 'thread.run.step.created': + this._emit('runStepCreated', event.data); + break; + case 'thread.run.step.delta': + const delta = event.data.delta; + if (delta.step_details && + delta.step_details.type == 'tool_calls' && + delta.step_details.tool_calls && + accumulatedRunStep.step_details.type == 'tool_calls') { + for (const toolCall of delta.step_details.tool_calls) { + if (toolCall.index == __classPrivateFieldGet(this, _AssistantStream_currentToolCallIndex, "f")) { + this._emit('toolCallDelta', toolCall, accumulatedRunStep.step_details.tool_calls[toolCall.index]); + } + else { + if (__classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")) { + this._emit('toolCallDone', __classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")); + } + __classPrivateFieldSet(this, _AssistantStream_currentToolCallIndex, toolCall.index, "f"); + __classPrivateFieldSet(this, _AssistantStream_currentToolCall, accumulatedRunStep.step_details.tool_calls[toolCall.index], "f"); + if (__classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")) + this._emit('toolCallCreated', __classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")); + } + } + } + this._emit('runStepDelta', event.data.delta, accumulatedRunStep); + break; + case 'thread.run.step.completed': + case 'thread.run.step.failed': + case 'thread.run.step.cancelled': + case 'thread.run.step.expired': + __classPrivateFieldSet(this, _AssistantStream_currentRunStepSnapshot, undefined, "f"); + const details = event.data.step_details; + if (details.type == 'tool_calls') { + if (__classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")) { + this._emit('toolCallDone', __classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")); + __classPrivateFieldSet(this, _AssistantStream_currentToolCall, undefined, "f"); + } + } + this._emit('runStepDone', event.data, accumulatedRunStep); + break; + case 'thread.run.step.in_progress': + break; + } +}, _AssistantStream_handleEvent = function _AssistantStream_handleEvent(event) { + __classPrivateFieldGet(this, _AssistantStream_events, "f").push(event); + this._emit('event', event); +}, _AssistantStream_accumulateRunStep = function _AssistantStream_accumulateRunStep(event) { + switch (event.event) { + case 'thread.run.step.created': + __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = event.data; + return event.data; + case 'thread.run.step.delta': + let snapshot = __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id]; + if (!snapshot) { + throw Error('Received a RunStepDelta before creation of a snapshot'); + } + let data = event.data; + if (data.delta) { + const accumulated = AssistantStream.accumulateDelta(snapshot, data.delta); + __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = accumulated; + } + return __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id]; + case 'thread.run.step.completed': + case 'thread.run.step.failed': + case 'thread.run.step.cancelled': + case 'thread.run.step.expired': + case 'thread.run.step.in_progress': + __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = event.data; + break; + } + if (__classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id]) + return __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id]; + throw new Error('No snapshot available'); +}, _AssistantStream_accumulateMessage = function _AssistantStream_accumulateMessage(event, snapshot) { + let newContent = []; + switch (event.event) { + case 'thread.message.created': + //On creation the snapshot is just the initial message + return [event.data, newContent]; + case 'thread.message.delta': + if (!snapshot) { + throw Error('Received a delta with no existing snapshot (there should be one from message creation)'); + } + let data = event.data; + //If this delta does not have content, nothing to process + if (data.delta.content) { + for (const contentElement of data.delta.content) { + if (contentElement.index in snapshot.content) { + let currentContent = snapshot.content[contentElement.index]; + snapshot.content[contentElement.index] = __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_accumulateContent).call(this, contentElement, currentContent); + } + else { + snapshot.content[contentElement.index] = contentElement; + //This is a new element + newContent.push(contentElement); + } + } + } + return [snapshot, newContent]; + case 'thread.message.in_progress': + case 'thread.message.completed': + case 'thread.message.incomplete': + //No changes on other thread events + if (snapshot) { + return [snapshot, newContent]; + } + else { + throw Error('Received thread message event with no existing snapshot'); + } + } + throw Error('Tried to accumulate a non-message event'); +}, _AssistantStream_accumulateContent = function _AssistantStream_accumulateContent(contentElement, currentContent) { + return AssistantStream.accumulateDelta(currentContent, contentElement); +}, _AssistantStream_handleRun = function _AssistantStream_handleRun(event) { + __classPrivateFieldSet(this, _AssistantStream_currentRunSnapshot, event.data, "f"); + switch (event.event) { + case 'thread.run.created': + break; + case 'thread.run.queued': + break; + case 'thread.run.in_progress': + break; + case 'thread.run.requires_action': + case 'thread.run.cancelled': + case 'thread.run.failed': + case 'thread.run.completed': + case 'thread.run.expired': + __classPrivateFieldSet(this, _AssistantStream_finalRun, event.data, "f"); + if (__classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")) { + this._emit('toolCallDone', __classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")); + __classPrivateFieldSet(this, _AssistantStream_currentToolCall, undefined, "f"); + } + break; + case 'thread.run.cancelling': + break; + } +}; +//# sourceMappingURL=AssistantStream.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/lib/AssistantStream.mjs.map b/backend/node_modules/openai/lib/AssistantStream.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..d30093b1f568b3443cb09ab970e1b7ef47f9d29c --- /dev/null +++ b/backend/node_modules/openai/lib/AssistantStream.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"AssistantStream.mjs","sourceRoot":"","sources":["../src/lib/AssistantStream.ts"],"names":[],"mappings":";;;;;;;;;;;;OAUO,KAAK,IAAI,MAAM,aAAa;OAU5B,EAEL,6BAA6B,GAC9B;OAEM,EAAE,MAAM,EAAE,MAAM,kBAAkB;OAClC,EAAE,iBAAiB,EAAE,WAAW,EAAE,MAAM,cAAc;AAiD7D,MAAM,OAAO,eACX,SAAQ,6BAAoD;IAD9D;;;QAIE,iDAAiD;QACjD,kCAAkC,EAAE,EAAC;QAErC,2BAA2B;QAC3B,gEAAgE;QAChE,4CAAoD,EAAE,EAAC;QACvD,4CAA+C,EAAE,EAAC;QAClD,mDAAsC;QACtC,4CAA2B;QAC3B,uDAAyC;QACzC,kDAAsE;QACtE,wDAA0C;QAC1C,mDAAuC;QAEvC,8BAA8B;QAC9B,gDAAgD;QAChD,sDAAqC;QACrC,0DAAkD;IAmnBpD,CAAC;IAjnBC,uoBAAC,MAAM,CAAC,aAAa,EAAC;QACpB,MAAM,SAAS,GAA2B,EAAE,CAAC;QAC7C,MAAM,SAAS,GAGT,EAAE,CAAC;QACT,IAAI,IAAI,GAAG,KAAK,CAAC;QAEjB,wCAAwC;QACxC,IAAI,CAAC,EAAE,CAAC,OAAO,EAAE,CAAC,KAAK,EAAE,EAAE;YACzB,MAAM,MAAM,GAAG,SAAS,CAAC,KAAK,EAAE,CAAC;YACjC,IAAI,MAAM,EAAE;gBACV,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;aACvB;iBAAM;gBACL,SAAS,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;aAC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AI,6BAAa,KAAK,CAAC,IAAI,MAAA,CAAC;YAC5B,IAAI,uBAAA,IAAI,wCAAiB,EAAE;gBACzB,IAAI,CAAC,KAAK,CAAC,cAAc,EAAE,uBAAA,IAAI,wCAAiB,CAAC,CAAC;gBAClD,uBAAA,IAAI,oCAAoB,SAAS,MAAA,CAAC;aACnC;YACD,MAAM;QACR,KAAK,uBAAuB;YAC1B,MAAM;KACT;AACH,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/openai/lib/ChatCompletionRunFunctions.test.d.ts b/backend/node_modules/openai/lib/ChatCompletionRunFunctions.test.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fb36c76944806c7936f2c179ef288a72f669c225 --- /dev/null +++ b/backend/node_modules/openai/lib/ChatCompletionRunFunctions.test.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=ChatCompletionRunFunctions.test.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/lib/ChatCompletionRunFunctions.test.d.ts.map b/backend/node_modules/openai/lib/ChatCompletionRunFunctions.test.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..6841ba8c42bdca271cc9c4d300944c5e9389b431 --- /dev/null +++ b/backend/node_modules/openai/lib/ChatCompletionRunFunctions.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ChatCompletionRunFunctions.test.d.ts","sourceRoot":"","sources":["../src/lib/ChatCompletionRunFunctions.test.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/backend/node_modules/openai/lib/ChatCompletionRunFunctions.test.js b/backend/node_modules/openai/lib/ChatCompletionRunFunctions.test.js new file mode 100644 index 0000000000000000000000000000000000000000..7d28c05e5ab900d36e6b402bf6ce75ebb731c80f --- /dev/null +++ b/backend/node_modules/openai/lib/ChatCompletionRunFunctions.test.js @@ -0,0 +1,2177 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const openai_1 = __importDefault(require("openai")); +const error_1 = require("openai/error"); +const stream_1 = require("stream"); +const completions_1 = require("openai/resources/beta/chat/completions"); +const node_fetch_1 = require("node-fetch"); +const chatCompletionUtils_1 = require("./chatCompletionUtils.js"); +/** + * Creates a mock `fetch` function and a `handleRequest` function for intercepting `fetch` calls. + * + * You call `handleRequest` with a callback function that handles the next `fetch` call. + * It returns a Promise that: + * - waits for the next call to `fetch` + * - calls the callback with the `fetch` arguments + * - resolves `fetch` with the callback output + */ +function mockFetch() { + const fetchQueue = []; + const handlerQueue = []; + const enqueueHandler = () => { + handlerQueue.push(new Promise((resolve) => { + fetchQueue.push((handle) => { + enqueueHandler(); + resolve(handle); + }); + })); + }; + enqueueHandler(); + async function fetch(req, init) { + const handler = await handlerQueue.shift(); + if (!handler) + throw new Error('expected handler to be defined'); + const signal = init?.signal; + if (!signal) + return await handler(req, init); + return await Promise.race([ + handler(req, init), + new Promise((resolve, reject) => { + if (signal.aborted) { + // @ts-ignore does exist in Node + reject(new DOMException('The user aborted a request.', 'AbortError')); + return; + } + signal.addEventListener('abort', (e) => { + // @ts-ignore does exist in Node + reject(new DOMException('The user aborted a request.', 'AbortError')); + }); + }), + ]); + } + function handleRequest(handle) { + return new Promise((resolve, reject) => { + fetchQueue.shift()?.(async (req, init) => { + try { + return await handle(req, init); + } + catch (err) { + reject(err); + return err; + } + finally { + resolve(); + } + }); + }); + } + return { fetch, handleRequest }; +} +// mockChatCompletionFetch is like mockFetch, but with better a more convenient handleRequest to mock +// chat completion request/responses. +function mockChatCompletionFetch() { + const { fetch, handleRequest: handleRawRequest } = mockFetch(); + function handleRequest(handler) { + return handleRawRequest(async (req, init) => { + const rawBody = init?.body; + if (typeof rawBody !== 'string') + throw new Error(`expected init.body to be a string`); + const body = JSON.parse(rawBody); + return new node_fetch_1.Response(JSON.stringify(await handler(body)), { + headers: { 'Content-Type': 'application/json' }, + }); + }); + } + return { fetch, handleRequest }; +} +// mockStreamingChatCompletionFetch is like mockFetch, but with better a more convenient handleRequest to mock +// streaming chat completion request/responses. +function mockStreamingChatCompletionFetch() { + const { fetch, handleRequest: handleRawRequest } = mockFetch(); + function handleRequest(handler) { + return handleRawRequest(async (req, init) => { + const rawBody = init?.body; + if (typeof rawBody !== 'string') + throw new Error(`expected init.body to be a string`); + const body = JSON.parse(rawBody); + const stream = new stream_1.PassThrough(); + (async () => { + for await (const chunk of handler(body)) { + stream.write(`data: ${JSON.stringify(chunk)}\n\n`); + } + stream.end(`data: [DONE]\n\n`); + })(); + return new node_fetch_1.Response(stream, { + headers: { + 'Content-Type': 'text/event-stream', + 'Transfer-Encoding': 'chunked', + }, + }); + }); + } + return { fetch, handleRequest }; +} +// contentChoiceDeltas returns an async iterator which mocks a delta stream of a by splitting the +// argument into chunks separated by whitespace. +function* contentChoiceDeltas(content, { index = 0, role = 'assistant', } = {}) { + const deltas = content.split(/\s+/g); + for (let i = 0; i < deltas.length; i++) { + yield { + index, + finish_reason: i === deltas.length - 1 ? 'stop' : null, + logprobs: null, + delta: { + role, + content: deltas[i] ? `${deltas[i]}${i === deltas.length - 1 ? '' : ' '}` : null, + }, + }; + } +} +// functionCallDeltas returns an async iterator which mocks a delta stream of a functionCall by splitting +// the argument into chunks separated by whitespace. +function* functionCallDeltas(args, { index = 0, id = '123', name, role = 'assistant', }) { + const deltas = args.split(/\s+/g); + for (let i = 0; i < deltas.length; i++) { + yield { + index, + finish_reason: i === deltas.length - 1 ? 'function_call' : null, + delta: { + role, + tool_calls: [ + { + type: 'function', + index: 0, + id, + function: { + arguments: `${deltas[i] || ''}${i === deltas.length - 1 ? '' : ' '}`, + ...(i === deltas.length - 1 ? { name } : null), + }, + }, + ], + }, + }; + } +} +class RunnerListener { + constructor(runner) { + this.runner = runner; + this.contents = []; + this.messages = []; + this.chatCompletions = []; + this.functionCalls = []; + this.functionCallResults = []; + this.finalContent = null; + this.gotConnect = false; + this.gotAbort = false; + this.gotEnd = false; + this.onceMessageCallCount = 0; + runner + .on('connect', () => (this.gotConnect = true)) + .on('content', (content) => this.contents.push(content)) + .on('message', (message) => this.messages.push(message)) + .on('chatCompletion', (completion) => this.chatCompletions.push(completion)) + .on('functionCall', (functionCall) => this.functionCalls.push(functionCall)) + .on('functionCallResult', (result) => this.functionCallResults.push(result)) + .on('finalContent', (content) => (this.finalContent = content)) + .on('finalMessage', (message) => (this.finalMessage = message)) + .on('finalChatCompletion', (completion) => (this.finalChatCompletion = completion)) + .on('finalFunctionCall', (functionCall) => (this.finalFunctionCall = functionCall)) + .on('finalFunctionCallResult', (result) => (this.finalFunctionCallResult = result)) + .on('totalUsage', (usage) => (this.totalUsage = usage)) + .on('error', (error) => (this.error = error)) + .on('abort', (error) => ((this.error = error), (this.gotAbort = true))) + .on('end', () => (this.gotEnd = true)) + .once('message', () => this.onceMessageCallCount++); + } + async sanityCheck({ error } = {}) { + expect(this.onceMessageCallCount).toBeLessThanOrEqual(1); + expect(this.gotAbort).toEqual(this.runner.aborted); + if (this.runner.aborted) + expect(this.runner.errored).toBe(true); + if (error) { + expect(this.error?.message).toEqual(error); + expect(this.runner.errored).toBe(true); + await expect(this.runner.finalChatCompletion()).rejects.toThrow(error); + await expect(this.runner.finalMessage()).rejects.toThrow(error); + await expect(this.runner.finalContent()).rejects.toThrow(error); + await expect(this.runner.finalFunctionCall()).rejects.toThrow(error); + await expect(this.runner.finalFunctionCallResult()).rejects.toThrow(error); + await expect(this.runner.totalUsage()).rejects.toThrow(error); + await expect(this.runner.done()).rejects.toThrow(error); + } + else { + expect(this.error).toBeUndefined(); + expect(this.runner.errored).toBe(false); + } + if (!this.gotConnect) { + expect(this.contents).toEqual([]); + expect(this.messages).toEqual([]); + expect(this.chatCompletions).toEqual([]); + expect(this.functionCalls).toEqual([]); + expect(this.functionCallResults).toEqual([]); + expect(this.finalContent).toBeUndefined(); + expect(this.finalMessage).toBeUndefined(); + expect(this.finalChatCompletion).toBeUndefined(); + expect(this.finalFunctionCall).toBeUndefined(); + expect(this.finalFunctionCallResult).toBeUndefined(); + expect(this.totalUsage).toBeUndefined(); + expect(this.gotEnd).toBe(true); + return; + } + if (error) + return; + const expectedContents = this.messages + .filter(chatCompletionUtils_1.isAssistantMessage) + .map((m) => m.content) + .filter(Boolean); + expect(this.contents).toEqual(expectedContents); + expect(this.finalMessage).toEqual([...this.messages].reverse().find((x) => x.role === 'assistant')); + expect(await this.runner.finalMessage()).toEqual(this.finalMessage); + expect(this.finalContent).toEqual(expectedContents[expectedContents.length - 1] ?? null); + expect(await this.runner.finalContent()).toEqual(this.finalContent); + expect(this.finalChatCompletion).toEqual(this.chatCompletions[this.chatCompletions.length - 1]); + expect(await this.runner.finalChatCompletion()).toEqual(this.finalChatCompletion); + expect(this.finalFunctionCall).toEqual(this.functionCalls[this.functionCalls.length - 1]); + expect(await this.runner.finalFunctionCall()).toEqual(this.finalFunctionCall); + expect(this.finalFunctionCallResult).toEqual(this.functionCallResults[this.functionCallResults.length - 1]); + expect(await this.runner.finalFunctionCallResult()).toEqual(this.finalFunctionCallResult); + expect(this.chatCompletions).toEqual(this.runner.allChatCompletions()); + expect(this.messages).toEqual(this.runner.messages.slice(-this.messages.length)); + if (this.chatCompletions.some((c) => c.usage)) { + const totalUsage = { + completion_tokens: 0, + prompt_tokens: 0, + total_tokens: 0, + }; + for (const { usage } of this.chatCompletions) { + if (usage) { + totalUsage.completion_tokens += usage.completion_tokens; + totalUsage.prompt_tokens += usage.prompt_tokens; + totalUsage.total_tokens += usage.total_tokens; + } + } + expect(this.totalUsage).toEqual(totalUsage); + expect(await this.runner.totalUsage()).toEqual(totalUsage); + } + expect(this.gotEnd).toBe(true); + } +} +class StreamingRunnerListener { + constructor(runner) { + this.runner = runner; + this.eventChunks = []; + this.eventContents = []; + this.eventMessages = []; + this.eventChatCompletions = []; + this.eventFunctionCalls = []; + this.eventFunctionCallResults = []; + this.finalContent = null; + this.gotConnect = false; + this.gotEnd = false; + runner + .on('connect', () => (this.gotConnect = true)) + .on('chunk', (chunk) => this.eventChunks.push(chunk)) + .on('content', (delta, snapshot) => this.eventContents.push([delta, snapshot])) + .on('message', (message) => this.eventMessages.push(message)) + .on('chatCompletion', (completion) => this.eventChatCompletions.push(completion)) + .on('functionCall', (functionCall) => this.eventFunctionCalls.push(functionCall)) + .on('functionCallResult', (result) => this.eventFunctionCallResults.push(result)) + .on('finalContent', (content) => (this.finalContent = content)) + .on('finalMessage', (message) => (this.finalMessage = message)) + .on('finalChatCompletion', (completion) => (this.finalChatCompletion = completion)) + .on('finalFunctionCall', (functionCall) => (this.finalFunctionCall = functionCall)) + .on('finalFunctionCallResult', (result) => (this.finalFunctionCallResult = result)) + .on('error', (error) => (this.error = error)) + .on('abort', (abort) => (this.error = abort)) + .on('end', () => (this.gotEnd = true)); + } + async sanityCheck({ error } = {}) { + if (error) { + expect(this.error?.message).toEqual(error); + expect(this.runner.errored).toBe(true); + await expect(this.runner.finalChatCompletion()).rejects.toThrow(error); + await expect(this.runner.finalMessage()).rejects.toThrow(error); + await expect(this.runner.finalContent()).rejects.toThrow(error); + await expect(this.runner.finalFunctionCall()).rejects.toThrow(error); + await expect(this.runner.finalFunctionCallResult()).rejects.toThrow(error); + await expect(this.runner.done()).rejects.toThrow(error); + } + else { + expect(this.error).toBeUndefined(); + expect(this.runner.errored).toBe(false); + } + if (!this.gotConnect) { + expect(this.eventContents).toEqual([]); + expect(this.eventMessages).toEqual([]); + expect(this.eventChatCompletions).toEqual([]); + expect(this.eventFunctionCalls).toEqual([]); + expect(this.eventFunctionCallResults).toEqual([]); + expect(this.finalContent).toBeUndefined(); + expect(this.finalMessage).toBeUndefined(); + expect(this.finalChatCompletion).toBeUndefined(); + expect(this.finalFunctionCall).toBeUndefined(); + expect(this.finalFunctionCallResult).toBeUndefined(); + expect(this.gotEnd).toBe(true); + return; + } + if (error) + return; + if (this.eventContents.length) + expect(this.eventChunks.length).toBeGreaterThan(0); + expect(this.finalMessage).toEqual([...this.eventMessages].reverse().find((x) => x.role === 'assistant')); + expect(await this.runner.finalMessage()).toEqual(this.finalMessage); + expect(this.finalContent).toEqual(this.eventContents[this.eventContents.length - 1]?.[1] ?? null); + expect(await this.runner.finalContent()).toEqual(this.finalContent); + expect(this.finalChatCompletion).toEqual(this.eventChatCompletions[this.eventChatCompletions.length - 1]); + expect(await this.runner.finalChatCompletion()).toEqual(this.finalChatCompletion); + expect(this.finalFunctionCall).toEqual(this.eventFunctionCalls[this.eventFunctionCalls.length - 1]); + expect(await this.runner.finalFunctionCall()).toEqual(this.finalFunctionCall); + expect(this.finalFunctionCallResult).toEqual(this.eventFunctionCallResults[this.eventFunctionCallResults.length - 1]); + expect(await this.runner.finalFunctionCallResult()).toEqual(this.finalFunctionCallResult); + expect(this.eventChatCompletions).toEqual(this.runner.allChatCompletions()); + expect(this.eventMessages).toEqual(this.runner.messages.slice(-this.eventMessages.length)); + if (error) { + expect(this.error?.message).toEqual(error); + expect(this.runner.errored).toBe(true); + } + else { + expect(this.error).toBeUndefined(); + expect(this.runner.errored).toBe(false); + } + expect(this.gotEnd).toBe(true); + } +} +function _typeTests() { + const openai = new openai_1.default(); + openai.beta.chat.completions.runTools({ + messages: [ + { role: 'user', content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}' }, + ], + model: 'gpt-3.5-turbo', + tools: [ + { + type: 'function', + function: { + name: 'numProperties', + function: (obj) => String(Object.keys(obj).length), + parameters: { type: 'object' }, + parse: (str) => { + const result = JSON.parse(str); + if (!(result instanceof Object) || Array.isArray(result)) { + throw new Error('must be an object'); + } + return result; + }, + description: 'gets the number of properties on an object', + }, + }, + { + type: 'function', + function: { + function: (str) => String(str.length), + parameters: { type: 'string' }, + description: 'gets the length of a string', + }, + }, + { + type: 'function', + // @ts-expect-error function must accept string if parse is omitted + function: { + function: (obj) => String(Object.keys(obj).length), + parameters: { type: 'object' }, + description: 'gets the number of properties on an object', + }, + }, + ], + }); + openai.beta.chat.completions.runTools({ + messages: [ + { role: 'user', content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}' }, + ], + model: 'gpt-3.5-turbo', + tools: [ + new completions_1.ParsingToolFunction({ + name: 'numProperties', + // @ts-expect-error parse and function don't match + parse: (str) => str, + function: (obj) => String(Object.keys(obj).length), + parameters: { type: 'object' }, + description: 'gets the number of properties on an object', + }), + ], + }); + openai.beta.chat.completions.runTools({ + messages: [ + { role: 'user', content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}' }, + ], + model: 'gpt-3.5-turbo', + tools: [ + new completions_1.ParsingToolFunction({ + name: 'numProperties', + parse: (str) => { + const result = JSON.parse(str); + if (!(result instanceof Object) || Array.isArray(result)) { + throw new Error('must be an object'); + } + return result; + }, + function: (obj) => String(Object.keys(obj).length), + parameters: { type: 'object' }, + description: 'gets the number of properties on an object', + }), + new completions_1.ParsingToolFunction({ + name: 'keys', + parse: (str) => { + const result = JSON.parse(str); + if (!(result instanceof Object)) { + throw new Error('must be an Object'); + } + return result; + }, + function: (obj) => Object.keys(obj).join(', '), + parameters: { type: 'object' }, + description: 'gets the number of properties on an object', + }), + new completions_1.ParsingToolFunction({ + name: 'len2', + // @ts-expect-error parse and function don't match + parse: (str) => str, + function: (obj) => String(Object.keys(obj).length), + parameters: { type: 'object' }, + description: 'gets the number of properties on an object', + }), + ], + }); + openai.beta.chat.completions.runTools({ + messages: [ + { role: 'user', content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}' }, + ], + model: 'gpt-3.5-turbo', + // @ts-ignore error occurs here in TS 4 + tools: [ + { + type: 'function', + function: { + name: 'numProperties', + parse: (str) => { + const result = JSON.parse(str); + if (!(result instanceof Object) || Array.isArray(result)) { + throw new Error('must be an object'); + } + return result; + }, + function: (obj) => String(Object.keys(obj).length), + parameters: { type: 'object' }, + description: 'gets the number of properties on an object', + }, + }, + { + type: 'function', + function: { + name: 'keys', + parse: (str) => { + const result = JSON.parse(str); + if (!(result instanceof Object)) { + throw new Error('must be an Object'); + } + return result; + }, + function: (obj) => Object.keys(obj).join(', '), + parameters: { type: 'object' }, + description: 'gets the number of properties on an object', + }, + }, + { + type: 'function', + function: { + name: 'len2', + parse: (str) => str, + // @ts-ignore error occurs here in TS 5 + // function input doesn't match parse output + function: (obj) => String(Object.keys(obj).length), + parameters: { type: 'object' }, + description: 'gets the number of properties on an object', + }, + }, + ], + }); +} +describe('resource completions', () => { + describe('runTools with stream: false', () => { + test('successful flow', async () => { + const { fetch, handleRequest } = mockChatCompletionFetch(); + const openai = new openai_1.default({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + const runner = openai.beta.chat.completions.runTools({ + messages: [{ role: 'user', content: 'tell me what the weather is like' }], + model: 'gpt-3.5-turbo', + tools: [ + { + type: 'function', + function: { + function: function getWeather() { + return `it's raining`; + }, + parameters: {}, + description: 'gets the weather', + }, + }, + ], + }); + const listener = new RunnerListener(runner); + await handleRequest(async (request) => { + expect(request.messages).toEqual([{ role: 'user', content: 'tell me what the weather is like' }]); + return { + id: '1', + choices: [ + { + index: 0, + finish_reason: 'function_call', + logprobs: null, + message: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion', + }; + }); + await handleRequest(async (request) => { + expect(request.messages).toEqual([ + { role: 'user', content: 'tell me what the weather is like' }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + { + role: 'tool', + content: `it's raining`, + tool_call_id: '123', + }, + ]); + return { + id: '2', + choices: [ + { + index: 0, + finish_reason: 'stop', + logprobs: null, + message: { + role: 'assistant', + content: `it's raining`, + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion', + }; + }); + await runner.done(); + expect(listener.messages).toEqual([ + { role: 'user', content: 'tell me what the weather is like' }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + { role: 'tool', content: `it's raining`, tool_call_id: '123' }, + { role: 'assistant', content: "it's raining" }, + ]); + expect(listener.functionCallResults).toEqual([`it's raining`]); + await listener.sanityCheck(); + }); + test('flow with abort', async () => { + const { fetch, handleRequest } = mockChatCompletionFetch(); + const openai = new openai_1.default({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + const controller = new AbortController(); + const runner = openai.beta.chat.completions.runTools({ + messages: [{ role: 'user', content: 'tell me what the weather is like' }], + model: 'gpt-3.5-turbo', + tools: [ + { + type: 'function', + function: { + function: function getWeather() { + return `it's raining`; + }, + parameters: {}, + description: 'gets the weather', + }, + }, + ], + }, { signal: controller.signal }); + const listener = new RunnerListener(runner); + await handleRequest(async (request) => { + expect(request.messages).toEqual([{ role: 'user', content: 'tell me what the weather is like' }]); + return { + id: '1', + choices: [ + { + index: 0, + finish_reason: 'function_call', + logprobs: null, + message: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion', + }; + }); + controller.abort(); + await runner.done().catch(() => { }); + expect(listener.messages).toEqual([ + { role: 'user', content: 'tell me what the weather is like' }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + { role: 'tool', content: `it's raining`, tool_call_id: '123' }, + ]); + expect(listener.functionCallResults).toEqual([`it's raining`]); + await listener.sanityCheck({ error: 'Request was aborted.' }); + expect(runner.aborted).toBe(true); + }); + test('successful flow with parse', async () => { + const { fetch, handleRequest } = mockChatCompletionFetch(); + const openai = new openai_1.default({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + const runner = openai.beta.chat.completions.runTools({ + messages: [ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + ], + model: 'gpt-3.5-turbo', + tools: [ + new completions_1.ParsingToolFunction({ + name: 'numProperties', + function: (obj) => String(Object.keys(obj).length), + parameters: { type: 'object' }, + parse: (str) => { + const result = JSON.parse(str); + if (!(result instanceof Object) || Array.isArray(result)) { + throw new Error('must be an object'); + } + return result; + }, + description: 'gets the number of properties on an object', + }), + ], + }); + const listener = new RunnerListener(runner); + await handleRequest(async (request) => { + expect(request.messages).toEqual([ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + ]); + return { + id: '1', + choices: [ + { + index: 0, + finish_reason: 'function_call', + logprobs: null, + message: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '{"a": 1, "b": 2, "c": 3}', + name: 'numProperties', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion', + usage: { + completion_tokens: 5, + prompt_tokens: 20, + total_tokens: 25, + }, + }; + }); + await handleRequest(async (request) => { + expect(request.messages).toEqual([ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '{"a": 1, "b": 2, "c": 3}', + name: 'numProperties', + }, + }, + ], + }, + { + role: 'tool', + content: '3', + tool_call_id: '123', + }, + ]); + return { + id: '2', + choices: [ + { + index: 0, + finish_reason: 'stop', + logprobs: null, + message: { + role: 'assistant', + content: `there are 3 properties in {"a": 1, "b": 2, "c": 3}`, + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion', + usage: { + completion_tokens: 10, + prompt_tokens: 25, + total_tokens: 35, + }, + }; + }); + await runner.done(); + expect(listener.messages).toEqual([ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { name: 'numProperties', arguments: '{"a": 1, "b": 2, "c": 3}' }, + }, + ], + }, + { role: 'tool', content: '3', tool_call_id: '123' }, + { role: 'assistant', content: 'there are 3 properties in {"a": 1, "b": 2, "c": 3}' }, + ]); + expect(listener.functionCallResults).toEqual(['3']); + await listener.sanityCheck(); + }); + test('flow with parse error', async () => { + const { fetch, handleRequest } = mockChatCompletionFetch(); + const openai = new openai_1.default({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + const runner = openai.beta.chat.completions.runTools({ + messages: [ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + ], + model: 'gpt-3.5-turbo', + tools: [ + new completions_1.ParsingToolFunction({ + name: 'numProperties', + function: (obj) => String(Object.keys(obj).length), + parameters: { type: 'object' }, + parse: (str) => { + const result = JSON.parse(str); + if (!(result instanceof Object) || Array.isArray(result)) { + throw new Error('must be an object'); + } + return result; + }, + description: 'gets the number of properties on an object', + }), + ], + }); + const listener = new RunnerListener(runner); + await Promise.all([ + handleRequest(async (request) => { + expect(request.messages).toEqual([ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + ]); + return { + id: '1', + choices: [ + { + index: 0, + finish_reason: 'function_call', + logprobs: null, + message: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '[{"a": 1, "b": 2, "c": 3}]', + name: 'numProperties', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion', + }; + }), + handleRequest(async (request) => { + expect(request.messages).toEqual([ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '[{"a": 1, "b": 2, "c": 3}]', + name: 'numProperties', + }, + }, + ], + }, + { + role: 'tool', + content: `must be an object`, + tool_call_id: '123', + }, + ]); + return { + id: '2', + choices: [ + { + index: 0, + finish_reason: 'function_call', + logprobs: null, + message: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '1234', + function: { + arguments: '{"a": 1, "b": 2, "c": 3}', + name: 'numProperties', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion', + }; + }), + handleRequest(async (request) => { + expect(request.messages).toEqual([ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '[{"a": 1, "b": 2, "c": 3}]', + name: 'numProperties', + }, + }, + ], + }, + { + role: 'tool', + content: `must be an object`, + tool_call_id: '123', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '1234', + function: { + arguments: '{"a": 1, "b": 2, "c": 3}', + name: 'numProperties', + }, + }, + ], + }, + { + role: 'tool', + content: '3', + tool_call_id: '1234', + }, + ]); + return { + id: '3', + choices: [ + { + index: 0, + finish_reason: 'stop', + logprobs: null, + message: { + role: 'assistant', + content: `there are 3 properties in {"a": 1, "b": 2, "c": 3}`, + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion', + }; + }), + runner.done(), + ]); + expect(listener.messages).toEqual([ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { name: 'numProperties', arguments: '[{"a": 1, "b": 2, "c": 3}]' }, + }, + ], + }, + { role: 'tool', content: `must be an object`, tool_call_id: '123' }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '1234', + function: { name: 'numProperties', arguments: '{"a": 1, "b": 2, "c": 3}' }, + }, + ], + }, + { role: 'tool', content: '3', tool_call_id: '1234' }, + { role: 'assistant', content: 'there are 3 properties in {"a": 1, "b": 2, "c": 3}' }, + ]); + expect(listener.functionCallResults).toEqual([`must be an object`, '3']); + await listener.sanityCheck(); + }); + test('single function call', async () => { + const { fetch, handleRequest } = mockChatCompletionFetch(); + const openai = new openai_1.default({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + const runner = openai.beta.chat.completions.runTools({ + messages: [{ role: 'user', content: 'tell me what the weather is like' }], + model: 'gpt-3.5-turbo', + tool_choice: { + type: 'function', + function: { + name: 'getWeather', + }, + }, + tools: [ + { + type: 'function', + function: { + function: function getWeather() { + return `it's raining`; + }, + parameters: {}, + description: 'gets the weather', + }, + }, + ], + }); + const listener = new RunnerListener(runner); + await Promise.all([ + handleRequest(async (request) => { + expect(request.messages).toEqual([{ role: 'user', content: 'tell me what the weather is like' }]); + return { + id: '1', + choices: [ + { + index: 0, + finish_reason: 'function_call', + logprobs: null, + message: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion', + }; + }), + runner.done(), + ]); + expect(listener.messages).toEqual([ + { role: 'user', content: 'tell me what the weather is like' }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + { role: 'tool', content: `it's raining`, tool_call_id: '123' }, + ]); + expect(listener.functionCallResults).toEqual([`it's raining`]); + await listener.sanityCheck(); + }); + test('wrong function name', async () => { + const { fetch, handleRequest } = mockChatCompletionFetch(); + const openai = new openai_1.default({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + const runner = openai.beta.chat.completions.runTools({ + messages: [{ role: 'user', content: 'tell me what the weather is like' }], + model: 'gpt-3.5-turbo', + tools: [ + { + type: 'function', + function: { + function: function getWeather() { + return `it's raining`; + }, + parameters: {}, + description: 'gets the weather', + }, + }, + ], + }); + const listener = new RunnerListener(runner); + await Promise.all([ + handleRequest(async (request) => { + expect(request.messages).toEqual([{ role: 'user', content: 'tell me what the weather is like' }]); + return { + id: '1', + choices: [ + { + index: 0, + finish_reason: 'function_call', + logprobs: null, + message: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'get_weather', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion', + }; + }), + handleRequest(async (request) => { + expect(request.messages).toEqual([ + { role: 'user', content: 'tell me what the weather is like' }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'get_weather', + }, + }, + ], + }, + { + role: 'tool', + content: `Invalid tool_call: "get_weather". Available options are: "getWeather". Please try again`, + tool_call_id: '123', + }, + ]); + return { + id: '2', + choices: [ + { + index: 0, + finish_reason: 'function_call', + logprobs: null, + message: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '1234', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion', + }; + }), + handleRequest(async (request) => { + expect(request.messages).toEqual([ + { role: 'user', content: 'tell me what the weather is like' }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'get_weather', + }, + }, + ], + }, + { + role: 'tool', + content: `Invalid tool_call: "get_weather". Available options are: "getWeather". Please try again`, + tool_call_id: '123', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '1234', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + { + role: 'tool', + content: `it's raining`, + tool_call_id: '1234', + }, + ]); + return { + id: '3', + choices: [ + { + index: 0, + finish_reason: 'stop', + logprobs: null, + message: { + role: 'assistant', + content: `it's raining`, + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion', + }; + }), + runner.done(), + ]); + expect(listener.messages).toEqual([ + { role: 'user', content: 'tell me what the weather is like' }, + { + role: 'assistant', + content: null, + tool_calls: [{ type: 'function', id: '123', function: { name: 'get_weather', arguments: '' } }], + }, + { + role: 'tool', + content: `Invalid tool_call: "get_weather". Available options are: "getWeather". Please try again`, + tool_call_id: '123', + }, + { + role: 'assistant', + content: null, + tool_calls: [{ type: 'function', id: '1234', function: { name: 'getWeather', arguments: '' } }], + }, + { role: 'tool', content: `it's raining`, tool_call_id: '1234' }, + { role: 'assistant', content: "it's raining" }, + ]); + expect(listener.functionCallResults).toEqual([ + `Invalid tool_call: "get_weather". Available options are: "getWeather". Please try again`, + `it's raining`, + ]); + await listener.sanityCheck(); + }); + }); + describe('runTools with stream: true', () => { + test('successful flow', async () => { + const { fetch, handleRequest } = mockStreamingChatCompletionFetch(); + const openai = new openai_1.default({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + const runner = openai.beta.chat.completions.runTools({ + stream: true, + messages: [{ role: 'user', content: 'tell me what the weather is like' }], + model: 'gpt-3.5-turbo', + tools: [ + { + type: 'function', + function: { + function: function getWeather() { + return `it's raining`; + }, + parameters: {}, + description: 'gets the weather', + }, + }, + ], + }); + const listener = new StreamingRunnerListener(runner); + await Promise.all([ + handleRequest(async function* (request) { + expect(request.messages).toEqual([{ role: 'user', content: 'tell me what the weather is like' }]); + yield { + id: '1', + choices: [ + { + index: 0, + finish_reason: 'function_call', + logprobs: null, + delta: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + index: 0, + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + }), + handleRequest(async function* (request) { + expect(request.messages).toEqual([ + { role: 'user', content: 'tell me what the weather is like' }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + { + role: 'tool', + content: `it's raining`, + tool_call_id: '123', + }, + ]); + for (const choice of contentChoiceDeltas(`it's raining`)) { + yield { + id: '2', + choices: [choice], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + } + }), + runner.done(), + ]); + expect(listener.eventMessages).toEqual([ + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + { role: 'tool', content: `it's raining`, tool_call_id: '123' }, + { role: 'assistant', content: "it's raining" }, + ]); + expect(listener.eventFunctionCallResults).toEqual([`it's raining`]); + await listener.sanityCheck(); + }); + test('flow with abort', async () => { + const { fetch, handleRequest } = mockStreamingChatCompletionFetch(); + const openai = new openai_1.default({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + const controller = new AbortController(); + const runner = openai.beta.chat.completions.runTools({ + stream: true, + messages: [{ role: 'user', content: 'tell me what the weather is like' }], + model: 'gpt-3.5-turbo', + tools: [ + { + type: 'function', + function: { + function: function getWeather() { + return `it's raining`; + }, + parameters: {}, + description: 'gets the weather', + }, + }, + ], + }, { signal: controller.signal }); + runner.on('functionCallResult', () => controller.abort()); + const listener = new StreamingRunnerListener(runner); + await handleRequest(async function* (request) { + expect(request.messages).toEqual([{ role: 'user', content: 'tell me what the weather is like' }]); + yield { + id: '1', + choices: [ + { + index: 0, + finish_reason: 'function_call', + delta: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + index: 0, + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + }); + await runner.done().catch(() => { }); + expect(listener.eventMessages).toEqual([ + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + { role: 'tool', content: `it's raining`, tool_call_id: '123' }, + ]); + expect(listener.eventFunctionCallResults).toEqual([`it's raining`]); + await listener.sanityCheck({ error: 'Request was aborted.' }); + expect(runner.aborted).toBe(true); + }); + test('successful flow with parse', async () => { + const { fetch, handleRequest } = mockStreamingChatCompletionFetch(); + const openai = new openai_1.default({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + const runner = openai.beta.chat.completions.runTools({ + stream: true, + messages: [ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + ], + model: 'gpt-3.5-turbo', + tools: [ + new completions_1.ParsingToolFunction({ + name: 'numProperties', + function: (obj) => String(Object.keys(obj).length), + parameters: { type: 'object' }, + parse: (str) => { + const result = JSON.parse(str); + if (!(result instanceof Object) || Array.isArray(result)) { + throw new Error('must be an object'); + } + return result; + }, + description: 'gets the number of properties on an object', + }), + ], + }); + const listener = new StreamingRunnerListener(runner); + await Promise.all([ + handleRequest(async function* (request) { + expect(request.messages).toEqual([ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + ]); + yield { + id: '1', + choices: [ + { + index: 0, + finish_reason: 'function_call', + delta: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + index: 0, + function: { + arguments: '{"a": 1, "b": 2, "c": 3}', + name: 'numProperties', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + }), + handleRequest(async function* (request) { + expect(request.messages).toEqual([ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '{"a": 1, "b": 2, "c": 3}', + name: 'numProperties', + }, + }, + ], + }, + { + role: 'tool', + content: '3', + tool_call_id: '123', + }, + ]); + for (const choice of contentChoiceDeltas(`there are 3 properties in {"a": 1, "b": 2, "c": 3}`)) { + yield { + id: '2', + choices: [choice], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + } + }), + runner.done(), + ]); + expect(listener.eventMessages).toEqual([ + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { name: 'numProperties', arguments: '{"a": 1, "b": 2, "c": 3}' }, + }, + ], + }, + { role: 'tool', content: '3', tool_call_id: '123' }, + { role: 'assistant', content: 'there are 3 properties in {"a": 1, "b": 2, "c": 3}' }, + ]); + expect(listener.eventFunctionCallResults).toEqual(['3']); + await listener.sanityCheck(); + }); + test('flow with parse error', async () => { + const { fetch, handleRequest } = mockStreamingChatCompletionFetch(); + const openai = new openai_1.default({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + const runner = openai.beta.chat.completions.runTools({ + stream: true, + messages: [ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + ], + model: 'gpt-3.5-turbo', + tools: [ + new completions_1.ParsingToolFunction({ + name: 'numProperties', + function: (obj) => String(Object.keys(obj).length), + parameters: { type: 'object' }, + parse: (str) => { + const result = JSON.parse(str); + if (!(result instanceof Object) || Array.isArray(result)) { + throw new Error('must be an object'); + } + return result; + }, + description: 'gets the number of properties on an object', + }), + ], + }); + const listener = new StreamingRunnerListener(runner); + await Promise.all([ + handleRequest(async function* (request) { + expect(request.messages).toEqual([ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + ]); + for (const choice of functionCallDeltas('[{"a": 1, "b": 2, "c": 3}]', { + name: 'numProperties', + id: '123', + })) { + yield { + id: '1', + choices: [choice], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + } + }), + handleRequest(async function* (request) { + expect(request.messages).toEqual([ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '[{"a": 1, "b": 2, "c": 3}]', + name: 'numProperties', + }, + }, + ], + }, + { + role: 'tool', + content: `must be an object`, + tool_call_id: '123', + }, + ]); + for (const choice of functionCallDeltas('{"a": 1, "b": 2, "c": 3}', { + name: 'numProperties', + id: '1234', + })) { + yield { + id: '2', + choices: [choice], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + } + }), + handleRequest(async function* (request) { + expect(request.messages).toEqual([ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '[{"a": 1, "b": 2, "c": 3}]', + name: 'numProperties', + }, + }, + ], + }, + { + role: 'tool', + content: `must be an object`, + tool_call_id: '123', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '1234', + function: { + arguments: '{"a": 1, "b": 2, "c": 3}', + name: 'numProperties', + }, + }, + ], + }, + { + role: 'tool', + content: '3', + tool_call_id: '1234', + }, + ]); + for (const choice of contentChoiceDeltas(`there are 3 properties in {"a": 1, "b": 2, "c": 3}`)) { + yield { + id: '3', + choices: [choice], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + } + }), + runner.done(), + ]); + expect(listener.eventMessages).toEqual([ + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { name: 'numProperties', arguments: '[{"a": 1, "b": 2, "c": 3}]' }, + }, + ], + }, + { role: 'tool', content: `must be an object`, tool_call_id: '123' }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '1234', + function: { name: 'numProperties', arguments: '{"a": 1, "b": 2, "c": 3}' }, + }, + ], + }, + { role: 'tool', content: '3', tool_call_id: '1234' }, + { role: 'assistant', content: 'there are 3 properties in {"a": 1, "b": 2, "c": 3}' }, + ]); + expect(listener.eventFunctionCallResults).toEqual([`must be an object`, '3']); + await listener.sanityCheck(); + }); + test('single function call', async () => { + const { fetch, handleRequest } = mockStreamingChatCompletionFetch(); + const openai = new openai_1.default({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + const runner = openai.beta.chat.completions.runTools({ + stream: true, + messages: [{ role: 'user', content: 'tell me what the weather is like' }], + model: 'gpt-3.5-turbo', + tool_choice: { + type: 'function', + function: { + name: 'getWeather', + }, + }, + tools: [ + { + type: 'function', + function: { + function: function getWeather() { + return `it's raining`; + }, + parameters: {}, + description: 'gets the weather', + }, + }, + ], + }); + const listener = new StreamingRunnerListener(runner); + await Promise.all([ + handleRequest(async function* (request) { + expect(request.messages).toEqual([{ role: 'user', content: 'tell me what the weather is like' }]); + yield { + id: '1', + choices: [ + { + index: 0, + finish_reason: 'function_call', + delta: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + index: 0, + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + }), + runner.done(), + ]); + expect(listener.eventMessages).toEqual([ + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + { role: 'tool', tool_call_id: '123', content: `it's raining` }, + ]); + expect(listener.eventFunctionCallResults).toEqual([`it's raining`]); + await listener.sanityCheck(); + }); + test('wrong function name', async () => { + const { fetch, handleRequest } = mockStreamingChatCompletionFetch(); + const openai = new openai_1.default({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + const runner = openai.beta.chat.completions.runTools({ + stream: true, + messages: [{ role: 'user', content: 'tell me what the weather is like' }], + model: 'gpt-3.5-turbo', + tools: [ + { + type: 'function', + function: { + function: function getWeather() { + return `it's raining`; + }, + parameters: {}, + description: 'gets the weather', + }, + }, + ], + }); + const listener = new StreamingRunnerListener(runner); + await Promise.all([ + handleRequest(async function* (request) { + expect(request.messages).toEqual([{ role: 'user', content: 'tell me what the weather is like' }]); + yield { + id: '1', + choices: [ + { + index: 0, + finish_reason: 'function_call', + delta: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + index: 0, + id: '123', + function: { + arguments: '', + name: 'get_weather', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + }), + handleRequest(async function* (request) { + expect(request.messages).toEqual([ + { role: 'user', content: 'tell me what the weather is like' }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'get_weather', + }, + }, + ], + }, + { + role: 'tool', + content: `Invalid tool_call: "get_weather". Available options are: "getWeather". Please try again`, + tool_call_id: '123', + }, + ]); + yield { + id: '2', + choices: [ + { + index: 0, + finish_reason: 'function_call', + logprobs: null, + delta: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + index: 0, + id: '1234', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + }), + handleRequest(async function* (request) { + expect(request.messages).toEqual([ + { role: 'user', content: 'tell me what the weather is like' }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'get_weather', + }, + }, + ], + }, + { + role: 'tool', + content: `Invalid tool_call: "get_weather". Available options are: "getWeather". Please try again`, + tool_call_id: '123', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '1234', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + { + role: 'tool', + content: `it's raining`, + tool_call_id: '1234', + }, + ]); + for (const choice of contentChoiceDeltas(`it's raining`)) { + yield { + id: '3', + choices: [choice], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + } + }), + runner.done(), + ]); + expect(listener.eventMessages).toEqual([ + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'get_weather', + }, + }, + ], + }, + { + role: 'tool', + content: `Invalid tool_call: "get_weather". Available options are: "getWeather". Please try again`, + tool_call_id: '123', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '1234', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + { role: 'tool', content: `it's raining`, tool_call_id: '1234' }, + { role: 'assistant', content: "it's raining" }, + ]); + expect(listener.eventFunctionCallResults).toEqual([ + `Invalid tool_call: "get_weather". Available options are: "getWeather". Please try again`, + `it's raining`, + ]); + await listener.sanityCheck(); + }); + }); + describe('stream', () => { + test('successful flow', async () => { + const { fetch, handleRequest } = mockStreamingChatCompletionFetch(); + const openai = new openai_1.default({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + const runner = openai.beta.chat.completions.stream({ + stream: true, + messages: [{ role: 'user', content: 'tell me what the weather is like' }], + model: 'gpt-3.5-turbo', + }); + const listener = new StreamingRunnerListener(runner); + await Promise.all([ + handleRequest(async function* (request) { + expect(request.messages).toEqual([{ role: 'user', content: 'tell me what the weather is like' }]); + for (const choice of contentChoiceDeltas(`The weather is great today!`)) { + yield { + id: '1', + choices: [choice], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + } + }), + runner.done(), + ]); + expect(listener.finalMessage).toEqual({ role: 'assistant', content: 'The weather is great today!' }); + await listener.sanityCheck(); + }); + test('toReadableStream and fromReadableStream', async () => { + const { fetch, handleRequest } = mockStreamingChatCompletionFetch(); + const openai = new openai_1.default({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + const runner = openai.beta.chat.completions.stream({ + stream: true, + messages: [{ role: 'user', content: 'tell me what the weather is like' }], + model: 'gpt-3.5-turbo', + }); + const proxied = completions_1.ChatCompletionStreamingRunner.fromReadableStream(runner.toReadableStream()); + const listener = new StreamingRunnerListener(proxied); + await Promise.all([ + handleRequest(async function* (request) { + expect(request.messages).toEqual([{ role: 'user', content: 'tell me what the weather is like' }]); + for (const choice of contentChoiceDeltas(`The weather is great today!`)) { + yield { + id: '1', + choices: [choice], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + } + }), + proxied.done(), + ]); + expect(listener.finalMessage).toEqual({ role: 'assistant', content: 'The weather is great today!' }); + await listener.sanityCheck(); + }); + test('handles network errors', async () => { + const { fetch, handleRequest } = mockFetch(); + const openai = new openai_1.default({ apiKey: '...', fetch }); + const stream = openai.beta.chat.completions.stream({ + max_tokens: 1024, + model: 'gpt-3.5-turbo', + messages: [{ role: 'user', content: 'Say hello there!' }], + }, { maxRetries: 0 }); + handleRequest(async () => { + throw new Error('mock request error'); + }).catch(() => { }); + async function runStream() { + await stream.done(); + } + await expect(runStream).rejects.toThrow(error_1.APIConnectionError); + }); + test('handles network errors on async iterator', async () => { + const { fetch, handleRequest } = mockFetch(); + const openai = new openai_1.default({ apiKey: '...', fetch }); + const stream = openai.beta.chat.completions.stream({ + max_tokens: 1024, + model: 'gpt-3.5-turbo', + messages: [{ role: 'user', content: 'Say hello there!' }], + }, { maxRetries: 0 }); + handleRequest(async () => { + throw new Error('mock request error'); + }).catch(() => { }); + async function runStream() { + for await (const _event of stream) { + continue; + } + } + await expect(runStream).rejects.toThrow(error_1.APIConnectionError); + }); + }); +}); +//# sourceMappingURL=ChatCompletionRunFunctions.test.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/lib/ChatCompletionRunFunctions.test.js.map b/backend/node_modules/openai/lib/ChatCompletionRunFunctions.test.js.map new file mode 100644 index 0000000000000000000000000000000000000000..bd9d549a7ff3e14f43f7489794a8d05ddadae738 --- /dev/null +++ b/backend/node_modules/openai/lib/ChatCompletionRunFunctions.test.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ChatCompletionRunFunctions.test.js","sourceRoot":"","sources":["../src/lib/ChatCompletionRunFunctions.test.ts"],"names":[],"mappings":";;;;;AAAA,oDAA4B;AAC5B,wCAA+D;AAC/D,mCAAqC;AACrC,wEAMgD;AAIhD,2CAAsC;AACtC,kEAA2D;AAI3D;;;;;;;;GAQG;AACH,SAAS,SAAS;IAChB,MAAM,UAAU,GAAwC,EAAE,CAAC;IAC3D,MAAM,YAAY,GAA4B,EAAE,CAAC;IAEjD,MAAM,cAAc,GAAG,GAAG,EAAE;QAC1B,YAAY,CAAC,IAAI,CACf,IAAI,OAAO,CAAe,CAAC,OAAO,EAAE,EAAE;YACpC,UAAU,CAAC,IAAI,CAAC,CAAC,MAAoB,EAAE,EAAE;gBACvC,cAAc,EAAE,CAAC;gBACjB,OAAO,CAAC,MAAM,CAAC,CAAC;YAClB,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CACH,CAAC;IACJ,CAAC,CAAC;IACF,cAAc,EAAE,CAAC;IAEjB,KAAK,UAAU,KAAK,CAAC,GAAyB,EAAE,IAAkB;QAChE,MAAM,OAAO,GAAG,MAAM,YAAY,CAAC,KAAK,EAAE,CAAC;QAC3C,IAAI,CAAC,OAAO;YAAE,MAAM,IAAI,KAAK,CAAC,gCAAgC,CAAC,CAAC;QAChE,MAAM,MAAM,GAAG,IAAI,EAAE,MAAM,CAAC;QAC5B,IAAI,CAAC,MAAM;YAAE,OAAO,MAAM,OAAO,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;QAC7C,OAAO,MAAM,OAAO,CAAC,IAAI,CAAC;YACxB,OAAO,CAAC,GAAG,EAAE,IAAI,CAAC;YAClB,IAAI,OAAO,CAAW,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;gBACxC,IAAI,MAAM,CAAC,OAAO,EAAE;oBA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vB,MAAM,IAAI,KAAK,CAAC,oBAAoB,CAAC,CAAC;YACxC,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;YAEnB,KAAK,UAAU,SAAS;gBACtB,IAAI,KAAK,EAAE,MAAM,MAAM,IAAI,MAAM,EAAE;oBACjC,SAAS;iBACV;YACH,CAAC;YAED,MAAM,MAAM,CAAC,SAAS,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC,0BAAkB,CAAC,CAAC;QAC9D,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/openai/lib/ChatCompletionRunFunctions.test.mjs b/backend/node_modules/openai/lib/ChatCompletionRunFunctions.test.mjs new file mode 100644 index 0000000000000000000000000000000000000000..3f4bbabee611de79293133bf203ac865efb95c94 --- /dev/null +++ b/backend/node_modules/openai/lib/ChatCompletionRunFunctions.test.mjs @@ -0,0 +1,2172 @@ +import OpenAI from 'openai'; +import { APIConnectionError } from 'openai/error'; +import { PassThrough } from 'stream'; +import { ParsingToolFunction, ChatCompletionStreamingRunner, } from 'openai/resources/beta/chat/completions'; +import { Response } from 'node-fetch'; +import { isAssistantMessage } from "./chatCompletionUtils.mjs"; +/** + * Creates a mock `fetch` function and a `handleRequest` function for intercepting `fetch` calls. + * + * You call `handleRequest` with a callback function that handles the next `fetch` call. + * It returns a Promise that: + * - waits for the next call to `fetch` + * - calls the callback with the `fetch` arguments + * - resolves `fetch` with the callback output + */ +function mockFetch() { + const fetchQueue = []; + const handlerQueue = []; + const enqueueHandler = () => { + handlerQueue.push(new Promise((resolve) => { + fetchQueue.push((handle) => { + enqueueHandler(); + resolve(handle); + }); + })); + }; + enqueueHandler(); + async function fetch(req, init) { + const handler = await handlerQueue.shift(); + if (!handler) + throw new Error('expected handler to be defined'); + const signal = init?.signal; + if (!signal) + return await handler(req, init); + return await Promise.race([ + handler(req, init), + new Promise((resolve, reject) => { + if (signal.aborted) { + // @ts-ignore does exist in Node + reject(new DOMException('The user aborted a request.', 'AbortError')); + return; + } + signal.addEventListener('abort', (e) => { + // @ts-ignore does exist in Node + reject(new DOMException('The user aborted a request.', 'AbortError')); + }); + }), + ]); + } + function handleRequest(handle) { + return new Promise((resolve, reject) => { + fetchQueue.shift()?.(async (req, init) => { + try { + return await handle(req, init); + } + catch (err) { + reject(err); + return err; + } + finally { + resolve(); + } + }); + }); + } + return { fetch, handleRequest }; +} +// mockChatCompletionFetch is like mockFetch, but with better a more convenient handleRequest to mock +// chat completion request/responses. +function mockChatCompletionFetch() { + const { fetch, handleRequest: handleRawRequest } = mockFetch(); + function handleRequest(handler) { + return handleRawRequest(async (req, init) => { + const rawBody = init?.body; + if (typeof rawBody !== 'string') + throw new Error(`expected init.body to be a string`); + const body = JSON.parse(rawBody); + return new Response(JSON.stringify(await handler(body)), { + headers: { 'Content-Type': 'application/json' }, + }); + }); + } + return { fetch, handleRequest }; +} +// mockStreamingChatCompletionFetch is like mockFetch, but with better a more convenient handleRequest to mock +// streaming chat completion request/responses. +function mockStreamingChatCompletionFetch() { + const { fetch, handleRequest: handleRawRequest } = mockFetch(); + function handleRequest(handler) { + return handleRawRequest(async (req, init) => { + const rawBody = init?.body; + if (typeof rawBody !== 'string') + throw new Error(`expected init.body to be a string`); + const body = JSON.parse(rawBody); + const stream = new PassThrough(); + (async () => { + for await (const chunk of handler(body)) { + stream.write(`data: ${JSON.stringify(chunk)}\n\n`); + } + stream.end(`data: [DONE]\n\n`); + })(); + return new Response(stream, { + headers: { + 'Content-Type': 'text/event-stream', + 'Transfer-Encoding': 'chunked', + }, + }); + }); + } + return { fetch, handleRequest }; +} +// contentChoiceDeltas returns an async iterator which mocks a delta stream of a by splitting the +// argument into chunks separated by whitespace. +function* contentChoiceDeltas(content, { index = 0, role = 'assistant', } = {}) { + const deltas = content.split(/\s+/g); + for (let i = 0; i < deltas.length; i++) { + yield { + index, + finish_reason: i === deltas.length - 1 ? 'stop' : null, + logprobs: null, + delta: { + role, + content: deltas[i] ? `${deltas[i]}${i === deltas.length - 1 ? '' : ' '}` : null, + }, + }; + } +} +// functionCallDeltas returns an async iterator which mocks a delta stream of a functionCall by splitting +// the argument into chunks separated by whitespace. +function* functionCallDeltas(args, { index = 0, id = '123', name, role = 'assistant', }) { + const deltas = args.split(/\s+/g); + for (let i = 0; i < deltas.length; i++) { + yield { + index, + finish_reason: i === deltas.length - 1 ? 'function_call' : null, + delta: { + role, + tool_calls: [ + { + type: 'function', + index: 0, + id, + function: { + arguments: `${deltas[i] || ''}${i === deltas.length - 1 ? '' : ' '}`, + ...(i === deltas.length - 1 ? { name } : null), + }, + }, + ], + }, + }; + } +} +class RunnerListener { + constructor(runner) { + this.runner = runner; + this.contents = []; + this.messages = []; + this.chatCompletions = []; + this.functionCalls = []; + this.functionCallResults = []; + this.finalContent = null; + this.gotConnect = false; + this.gotAbort = false; + this.gotEnd = false; + this.onceMessageCallCount = 0; + runner + .on('connect', () => (this.gotConnect = true)) + .on('content', (content) => this.contents.push(content)) + .on('message', (message) => this.messages.push(message)) + .on('chatCompletion', (completion) => this.chatCompletions.push(completion)) + .on('functionCall', (functionCall) => this.functionCalls.push(functionCall)) + .on('functionCallResult', (result) => this.functionCallResults.push(result)) + .on('finalContent', (content) => (this.finalContent = content)) + .on('finalMessage', (message) => (this.finalMessage = message)) + .on('finalChatCompletion', (completion) => (this.finalChatCompletion = completion)) + .on('finalFunctionCall', (functionCall) => (this.finalFunctionCall = functionCall)) + .on('finalFunctionCallResult', (result) => (this.finalFunctionCallResult = result)) + .on('totalUsage', (usage) => (this.totalUsage = usage)) + .on('error', (error) => (this.error = error)) + .on('abort', (error) => ((this.error = error), (this.gotAbort = true))) + .on('end', () => (this.gotEnd = true)) + .once('message', () => this.onceMessageCallCount++); + } + async sanityCheck({ error } = {}) { + expect(this.onceMessageCallCount).toBeLessThanOrEqual(1); + expect(this.gotAbort).toEqual(this.runner.aborted); + if (this.runner.aborted) + expect(this.runner.errored).toBe(true); + if (error) { + expect(this.error?.message).toEqual(error); + expect(this.runner.errored).toBe(true); + await expect(this.runner.finalChatCompletion()).rejects.toThrow(error); + await expect(this.runner.finalMessage()).rejects.toThrow(error); + await expect(this.runner.finalContent()).rejects.toThrow(error); + await expect(this.runner.finalFunctionCall()).rejects.toThrow(error); + await expect(this.runner.finalFunctionCallResult()).rejects.toThrow(error); + await expect(this.runner.totalUsage()).rejects.toThrow(error); + await expect(this.runner.done()).rejects.toThrow(error); + } + else { + expect(this.error).toBeUndefined(); + expect(this.runner.errored).toBe(false); + } + if (!this.gotConnect) { + expect(this.contents).toEqual([]); + expect(this.messages).toEqual([]); + expect(this.chatCompletions).toEqual([]); + expect(this.functionCalls).toEqual([]); + expect(this.functionCallResults).toEqual([]); + expect(this.finalContent).toBeUndefined(); + expect(this.finalMessage).toBeUndefined(); + expect(this.finalChatCompletion).toBeUndefined(); + expect(this.finalFunctionCall).toBeUndefined(); + expect(this.finalFunctionCallResult).toBeUndefined(); + expect(this.totalUsage).toBeUndefined(); + expect(this.gotEnd).toBe(true); + return; + } + if (error) + return; + const expectedContents = this.messages + .filter(isAssistantMessage) + .map((m) => m.content) + .filter(Boolean); + expect(this.contents).toEqual(expectedContents); + expect(this.finalMessage).toEqual([...this.messages].reverse().find((x) => x.role === 'assistant')); + expect(await this.runner.finalMessage()).toEqual(this.finalMessage); + expect(this.finalContent).toEqual(expectedContents[expectedContents.length - 1] ?? null); + expect(await this.runner.finalContent()).toEqual(this.finalContent); + expect(this.finalChatCompletion).toEqual(this.chatCompletions[this.chatCompletions.length - 1]); + expect(await this.runner.finalChatCompletion()).toEqual(this.finalChatCompletion); + expect(this.finalFunctionCall).toEqual(this.functionCalls[this.functionCalls.length - 1]); + expect(await this.runner.finalFunctionCall()).toEqual(this.finalFunctionCall); + expect(this.finalFunctionCallResult).toEqual(this.functionCallResults[this.functionCallResults.length - 1]); + expect(await this.runner.finalFunctionCallResult()).toEqual(this.finalFunctionCallResult); + expect(this.chatCompletions).toEqual(this.runner.allChatCompletions()); + expect(this.messages).toEqual(this.runner.messages.slice(-this.messages.length)); + if (this.chatCompletions.some((c) => c.usage)) { + const totalUsage = { + completion_tokens: 0, + prompt_tokens: 0, + total_tokens: 0, + }; + for (const { usage } of this.chatCompletions) { + if (usage) { + totalUsage.completion_tokens += usage.completion_tokens; + totalUsage.prompt_tokens += usage.prompt_tokens; + totalUsage.total_tokens += usage.total_tokens; + } + } + expect(this.totalUsage).toEqual(totalUsage); + expect(await this.runner.totalUsage()).toEqual(totalUsage); + } + expect(this.gotEnd).toBe(true); + } +} +class StreamingRunnerListener { + constructor(runner) { + this.runner = runner; + this.eventChunks = []; + this.eventContents = []; + this.eventMessages = []; + this.eventChatCompletions = []; + this.eventFunctionCalls = []; + this.eventFunctionCallResults = []; + this.finalContent = null; + this.gotConnect = false; + this.gotEnd = false; + runner + .on('connect', () => (this.gotConnect = true)) + .on('chunk', (chunk) => this.eventChunks.push(chunk)) + .on('content', (delta, snapshot) => this.eventContents.push([delta, snapshot])) + .on('message', (message) => this.eventMessages.push(message)) + .on('chatCompletion', (completion) => this.eventChatCompletions.push(completion)) + .on('functionCall', (functionCall) => this.eventFunctionCalls.push(functionCall)) + .on('functionCallResult', (result) => this.eventFunctionCallResults.push(result)) + .on('finalContent', (content) => (this.finalContent = content)) + .on('finalMessage', (message) => (this.finalMessage = message)) + .on('finalChatCompletion', (completion) => (this.finalChatCompletion = completion)) + .on('finalFunctionCall', (functionCall) => (this.finalFunctionCall = functionCall)) + .on('finalFunctionCallResult', (result) => (this.finalFunctionCallResult = result)) + .on('error', (error) => (this.error = error)) + .on('abort', (abort) => (this.error = abort)) + .on('end', () => (this.gotEnd = true)); + } + async sanityCheck({ error } = {}) { + if (error) { + expect(this.error?.message).toEqual(error); + expect(this.runner.errored).toBe(true); + await expect(this.runner.finalChatCompletion()).rejects.toThrow(error); + await expect(this.runner.finalMessage()).rejects.toThrow(error); + await expect(this.runner.finalContent()).rejects.toThrow(error); + await expect(this.runner.finalFunctionCall()).rejects.toThrow(error); + await expect(this.runner.finalFunctionCallResult()).rejects.toThrow(error); + await expect(this.runner.done()).rejects.toThrow(error); + } + else { + expect(this.error).toBeUndefined(); + expect(this.runner.errored).toBe(false); + } + if (!this.gotConnect) { + expect(this.eventContents).toEqual([]); + expect(this.eventMessages).toEqual([]); + expect(this.eventChatCompletions).toEqual([]); + expect(this.eventFunctionCalls).toEqual([]); + expect(this.eventFunctionCallResults).toEqual([]); + expect(this.finalContent).toBeUndefined(); + expect(this.finalMessage).toBeUndefined(); + expect(this.finalChatCompletion).toBeUndefined(); + expect(this.finalFunctionCall).toBeUndefined(); + expect(this.finalFunctionCallResult).toBeUndefined(); + expect(this.gotEnd).toBe(true); + return; + } + if (error) + return; + if (this.eventContents.length) + expect(this.eventChunks.length).toBeGreaterThan(0); + expect(this.finalMessage).toEqual([...this.eventMessages].reverse().find((x) => x.role === 'assistant')); + expect(await this.runner.finalMessage()).toEqual(this.finalMessage); + expect(this.finalContent).toEqual(this.eventContents[this.eventContents.length - 1]?.[1] ?? null); + expect(await this.runner.finalContent()).toEqual(this.finalContent); + expect(this.finalChatCompletion).toEqual(this.eventChatCompletions[this.eventChatCompletions.length - 1]); + expect(await this.runner.finalChatCompletion()).toEqual(this.finalChatCompletion); + expect(this.finalFunctionCall).toEqual(this.eventFunctionCalls[this.eventFunctionCalls.length - 1]); + expect(await this.runner.finalFunctionCall()).toEqual(this.finalFunctionCall); + expect(this.finalFunctionCallResult).toEqual(this.eventFunctionCallResults[this.eventFunctionCallResults.length - 1]); + expect(await this.runner.finalFunctionCallResult()).toEqual(this.finalFunctionCallResult); + expect(this.eventChatCompletions).toEqual(this.runner.allChatCompletions()); + expect(this.eventMessages).toEqual(this.runner.messages.slice(-this.eventMessages.length)); + if (error) { + expect(this.error?.message).toEqual(error); + expect(this.runner.errored).toBe(true); + } + else { + expect(this.error).toBeUndefined(); + expect(this.runner.errored).toBe(false); + } + expect(this.gotEnd).toBe(true); + } +} +function _typeTests() { + const openai = new OpenAI(); + openai.beta.chat.completions.runTools({ + messages: [ + { role: 'user', content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}' }, + ], + model: 'gpt-3.5-turbo', + tools: [ + { + type: 'function', + function: { + name: 'numProperties', + function: (obj) => String(Object.keys(obj).length), + parameters: { type: 'object' }, + parse: (str) => { + const result = JSON.parse(str); + if (!(result instanceof Object) || Array.isArray(result)) { + throw new Error('must be an object'); + } + return result; + }, + description: 'gets the number of properties on an object', + }, + }, + { + type: 'function', + function: { + function: (str) => String(str.length), + parameters: { type: 'string' }, + description: 'gets the length of a string', + }, + }, + { + type: 'function', + // @ts-expect-error function must accept string if parse is omitted + function: { + function: (obj) => String(Object.keys(obj).length), + parameters: { type: 'object' }, + description: 'gets the number of properties on an object', + }, + }, + ], + }); + openai.beta.chat.completions.runTools({ + messages: [ + { role: 'user', content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}' }, + ], + model: 'gpt-3.5-turbo', + tools: [ + new ParsingToolFunction({ + name: 'numProperties', + // @ts-expect-error parse and function don't match + parse: (str) => str, + function: (obj) => String(Object.keys(obj).length), + parameters: { type: 'object' }, + description: 'gets the number of properties on an object', + }), + ], + }); + openai.beta.chat.completions.runTools({ + messages: [ + { role: 'user', content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}' }, + ], + model: 'gpt-3.5-turbo', + tools: [ + new ParsingToolFunction({ + name: 'numProperties', + parse: (str) => { + const result = JSON.parse(str); + if (!(result instanceof Object) || Array.isArray(result)) { + throw new Error('must be an object'); + } + return result; + }, + function: (obj) => String(Object.keys(obj).length), + parameters: { type: 'object' }, + description: 'gets the number of properties on an object', + }), + new ParsingToolFunction({ + name: 'keys', + parse: (str) => { + const result = JSON.parse(str); + if (!(result instanceof Object)) { + throw new Error('must be an Object'); + } + return result; + }, + function: (obj) => Object.keys(obj).join(', '), + parameters: { type: 'object' }, + description: 'gets the number of properties on an object', + }), + new ParsingToolFunction({ + name: 'len2', + // @ts-expect-error parse and function don't match + parse: (str) => str, + function: (obj) => String(Object.keys(obj).length), + parameters: { type: 'object' }, + description: 'gets the number of properties on an object', + }), + ], + }); + openai.beta.chat.completions.runTools({ + messages: [ + { role: 'user', content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}' }, + ], + model: 'gpt-3.5-turbo', + // @ts-ignore error occurs here in TS 4 + tools: [ + { + type: 'function', + function: { + name: 'numProperties', + parse: (str) => { + const result = JSON.parse(str); + if (!(result instanceof Object) || Array.isArray(result)) { + throw new Error('must be an object'); + } + return result; + }, + function: (obj) => String(Object.keys(obj).length), + parameters: { type: 'object' }, + description: 'gets the number of properties on an object', + }, + }, + { + type: 'function', + function: { + name: 'keys', + parse: (str) => { + const result = JSON.parse(str); + if (!(result instanceof Object)) { + throw new Error('must be an Object'); + } + return result; + }, + function: (obj) => Object.keys(obj).join(', '), + parameters: { type: 'object' }, + description: 'gets the number of properties on an object', + }, + }, + { + type: 'function', + function: { + name: 'len2', + parse: (str) => str, + // @ts-ignore error occurs here in TS 5 + // function input doesn't match parse output + function: (obj) => String(Object.keys(obj).length), + parameters: { type: 'object' }, + description: 'gets the number of properties on an object', + }, + }, + ], + }); +} +describe('resource completions', () => { + describe('runTools with stream: false', () => { + test('successful flow', async () => { + const { fetch, handleRequest } = mockChatCompletionFetch(); + const openai = new OpenAI({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + const runner = openai.beta.chat.completions.runTools({ + messages: [{ role: 'user', content: 'tell me what the weather is like' }], + model: 'gpt-3.5-turbo', + tools: [ + { + type: 'function', + function: { + function: function getWeather() { + return `it's raining`; + }, + parameters: {}, + description: 'gets the weather', + }, + }, + ], + }); + const listener = new RunnerListener(runner); + await handleRequest(async (request) => { + expect(request.messages).toEqual([{ role: 'user', content: 'tell me what the weather is like' }]); + return { + id: '1', + choices: [ + { + index: 0, + finish_reason: 'function_call', + logprobs: null, + message: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion', + }; + }); + await handleRequest(async (request) => { + expect(request.messages).toEqual([ + { role: 'user', content: 'tell me what the weather is like' }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + { + role: 'tool', + content: `it's raining`, + tool_call_id: '123', + }, + ]); + return { + id: '2', + choices: [ + { + index: 0, + finish_reason: 'stop', + logprobs: null, + message: { + role: 'assistant', + content: `it's raining`, + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion', + }; + }); + await runner.done(); + expect(listener.messages).toEqual([ + { role: 'user', content: 'tell me what the weather is like' }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + { role: 'tool', content: `it's raining`, tool_call_id: '123' }, + { role: 'assistant', content: "it's raining" }, + ]); + expect(listener.functionCallResults).toEqual([`it's raining`]); + await listener.sanityCheck(); + }); + test('flow with abort', async () => { + const { fetch, handleRequest } = mockChatCompletionFetch(); + const openai = new OpenAI({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + const controller = new AbortController(); + const runner = openai.beta.chat.completions.runTools({ + messages: [{ role: 'user', content: 'tell me what the weather is like' }], + model: 'gpt-3.5-turbo', + tools: [ + { + type: 'function', + function: { + function: function getWeather() { + return `it's raining`; + }, + parameters: {}, + description: 'gets the weather', + }, + }, + ], + }, { signal: controller.signal }); + const listener = new RunnerListener(runner); + await handleRequest(async (request) => { + expect(request.messages).toEqual([{ role: 'user', content: 'tell me what the weather is like' }]); + return { + id: '1', + choices: [ + { + index: 0, + finish_reason: 'function_call', + logprobs: null, + message: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion', + }; + }); + controller.abort(); + await runner.done().catch(() => { }); + expect(listener.messages).toEqual([ + { role: 'user', content: 'tell me what the weather is like' }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + { role: 'tool', content: `it's raining`, tool_call_id: '123' }, + ]); + expect(listener.functionCallResults).toEqual([`it's raining`]); + await listener.sanityCheck({ error: 'Request was aborted.' }); + expect(runner.aborted).toBe(true); + }); + test('successful flow with parse', async () => { + const { fetch, handleRequest } = mockChatCompletionFetch(); + const openai = new OpenAI({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + const runner = openai.beta.chat.completions.runTools({ + messages: [ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + ], + model: 'gpt-3.5-turbo', + tools: [ + new ParsingToolFunction({ + name: 'numProperties', + function: (obj) => String(Object.keys(obj).length), + parameters: { type: 'object' }, + parse: (str) => { + const result = JSON.parse(str); + if (!(result instanceof Object) || Array.isArray(result)) { + throw new Error('must be an object'); + } + return result; + }, + description: 'gets the number of properties on an object', + }), + ], + }); + const listener = new RunnerListener(runner); + await handleRequest(async (request) => { + expect(request.messages).toEqual([ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + ]); + return { + id: '1', + choices: [ + { + index: 0, + finish_reason: 'function_call', + logprobs: null, + message: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '{"a": 1, "b": 2, "c": 3}', + name: 'numProperties', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion', + usage: { + completion_tokens: 5, + prompt_tokens: 20, + total_tokens: 25, + }, + }; + }); + await handleRequest(async (request) => { + expect(request.messages).toEqual([ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '{"a": 1, "b": 2, "c": 3}', + name: 'numProperties', + }, + }, + ], + }, + { + role: 'tool', + content: '3', + tool_call_id: '123', + }, + ]); + return { + id: '2', + choices: [ + { + index: 0, + finish_reason: 'stop', + logprobs: null, + message: { + role: 'assistant', + content: `there are 3 properties in {"a": 1, "b": 2, "c": 3}`, + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion', + usage: { + completion_tokens: 10, + prompt_tokens: 25, + total_tokens: 35, + }, + }; + }); + await runner.done(); + expect(listener.messages).toEqual([ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { name: 'numProperties', arguments: '{"a": 1, "b": 2, "c": 3}' }, + }, + ], + }, + { role: 'tool', content: '3', tool_call_id: '123' }, + { role: 'assistant', content: 'there are 3 properties in {"a": 1, "b": 2, "c": 3}' }, + ]); + expect(listener.functionCallResults).toEqual(['3']); + await listener.sanityCheck(); + }); + test('flow with parse error', async () => { + const { fetch, handleRequest } = mockChatCompletionFetch(); + const openai = new OpenAI({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + const runner = openai.beta.chat.completions.runTools({ + messages: [ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + ], + model: 'gpt-3.5-turbo', + tools: [ + new ParsingToolFunction({ + name: 'numProperties', + function: (obj) => String(Object.keys(obj).length), + parameters: { type: 'object' }, + parse: (str) => { + const result = JSON.parse(str); + if (!(result instanceof Object) || Array.isArray(result)) { + throw new Error('must be an object'); + } + return result; + }, + description: 'gets the number of properties on an object', + }), + ], + }); + const listener = new RunnerListener(runner); + await Promise.all([ + handleRequest(async (request) => { + expect(request.messages).toEqual([ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + ]); + return { + id: '1', + choices: [ + { + index: 0, + finish_reason: 'function_call', + logprobs: null, + message: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '[{"a": 1, "b": 2, "c": 3}]', + name: 'numProperties', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion', + }; + }), + handleRequest(async (request) => { + expect(request.messages).toEqual([ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '[{"a": 1, "b": 2, "c": 3}]', + name: 'numProperties', + }, + }, + ], + }, + { + role: 'tool', + content: `must be an object`, + tool_call_id: '123', + }, + ]); + return { + id: '2', + choices: [ + { + index: 0, + finish_reason: 'function_call', + logprobs: null, + message: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '1234', + function: { + arguments: '{"a": 1, "b": 2, "c": 3}', + name: 'numProperties', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion', + }; + }), + handleRequest(async (request) => { + expect(request.messages).toEqual([ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '[{"a": 1, "b": 2, "c": 3}]', + name: 'numProperties', + }, + }, + ], + }, + { + role: 'tool', + content: `must be an object`, + tool_call_id: '123', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '1234', + function: { + arguments: '{"a": 1, "b": 2, "c": 3}', + name: 'numProperties', + }, + }, + ], + }, + { + role: 'tool', + content: '3', + tool_call_id: '1234', + }, + ]); + return { + id: '3', + choices: [ + { + index: 0, + finish_reason: 'stop', + logprobs: null, + message: { + role: 'assistant', + content: `there are 3 properties in {"a": 1, "b": 2, "c": 3}`, + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion', + }; + }), + runner.done(), + ]); + expect(listener.messages).toEqual([ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { name: 'numProperties', arguments: '[{"a": 1, "b": 2, "c": 3}]' }, + }, + ], + }, + { role: 'tool', content: `must be an object`, tool_call_id: '123' }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '1234', + function: { name: 'numProperties', arguments: '{"a": 1, "b": 2, "c": 3}' }, + }, + ], + }, + { role: 'tool', content: '3', tool_call_id: '1234' }, + { role: 'assistant', content: 'there are 3 properties in {"a": 1, "b": 2, "c": 3}' }, + ]); + expect(listener.functionCallResults).toEqual([`must be an object`, '3']); + await listener.sanityCheck(); + }); + test('single function call', async () => { + const { fetch, handleRequest } = mockChatCompletionFetch(); + const openai = new OpenAI({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + const runner = openai.beta.chat.completions.runTools({ + messages: [{ role: 'user', content: 'tell me what the weather is like' }], + model: 'gpt-3.5-turbo', + tool_choice: { + type: 'function', + function: { + name: 'getWeather', + }, + }, + tools: [ + { + type: 'function', + function: { + function: function getWeather() { + return `it's raining`; + }, + parameters: {}, + description: 'gets the weather', + }, + }, + ], + }); + const listener = new RunnerListener(runner); + await Promise.all([ + handleRequest(async (request) => { + expect(request.messages).toEqual([{ role: 'user', content: 'tell me what the weather is like' }]); + return { + id: '1', + choices: [ + { + index: 0, + finish_reason: 'function_call', + logprobs: null, + message: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion', + }; + }), + runner.done(), + ]); + expect(listener.messages).toEqual([ + { role: 'user', content: 'tell me what the weather is like' }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + { role: 'tool', content: `it's raining`, tool_call_id: '123' }, + ]); + expect(listener.functionCallResults).toEqual([`it's raining`]); + await listener.sanityCheck(); + }); + test('wrong function name', async () => { + const { fetch, handleRequest } = mockChatCompletionFetch(); + const openai = new OpenAI({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + const runner = openai.beta.chat.completions.runTools({ + messages: [{ role: 'user', content: 'tell me what the weather is like' }], + model: 'gpt-3.5-turbo', + tools: [ + { + type: 'function', + function: { + function: function getWeather() { + return `it's raining`; + }, + parameters: {}, + description: 'gets the weather', + }, + }, + ], + }); + const listener = new RunnerListener(runner); + await Promise.all([ + handleRequest(async (request) => { + expect(request.messages).toEqual([{ role: 'user', content: 'tell me what the weather is like' }]); + return { + id: '1', + choices: [ + { + index: 0, + finish_reason: 'function_call', + logprobs: null, + message: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'get_weather', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion', + }; + }), + handleRequest(async (request) => { + expect(request.messages).toEqual([ + { role: 'user', content: 'tell me what the weather is like' }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'get_weather', + }, + }, + ], + }, + { + role: 'tool', + content: `Invalid tool_call: "get_weather". Available options are: "getWeather". Please try again`, + tool_call_id: '123', + }, + ]); + return { + id: '2', + choices: [ + { + index: 0, + finish_reason: 'function_call', + logprobs: null, + message: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '1234', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion', + }; + }), + handleRequest(async (request) => { + expect(request.messages).toEqual([ + { role: 'user', content: 'tell me what the weather is like' }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'get_weather', + }, + }, + ], + }, + { + role: 'tool', + content: `Invalid tool_call: "get_weather". Available options are: "getWeather". Please try again`, + tool_call_id: '123', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '1234', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + { + role: 'tool', + content: `it's raining`, + tool_call_id: '1234', + }, + ]); + return { + id: '3', + choices: [ + { + index: 0, + finish_reason: 'stop', + logprobs: null, + message: { + role: 'assistant', + content: `it's raining`, + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion', + }; + }), + runner.done(), + ]); + expect(listener.messages).toEqual([ + { role: 'user', content: 'tell me what the weather is like' }, + { + role: 'assistant', + content: null, + tool_calls: [{ type: 'function', id: '123', function: { name: 'get_weather', arguments: '' } }], + }, + { + role: 'tool', + content: `Invalid tool_call: "get_weather". Available options are: "getWeather". Please try again`, + tool_call_id: '123', + }, + { + role: 'assistant', + content: null, + tool_calls: [{ type: 'function', id: '1234', function: { name: 'getWeather', arguments: '' } }], + }, + { role: 'tool', content: `it's raining`, tool_call_id: '1234' }, + { role: 'assistant', content: "it's raining" }, + ]); + expect(listener.functionCallResults).toEqual([ + `Invalid tool_call: "get_weather". Available options are: "getWeather". Please try again`, + `it's raining`, + ]); + await listener.sanityCheck(); + }); + }); + describe('runTools with stream: true', () => { + test('successful flow', async () => { + const { fetch, handleRequest } = mockStreamingChatCompletionFetch(); + const openai = new OpenAI({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + const runner = openai.beta.chat.completions.runTools({ + stream: true, + messages: [{ role: 'user', content: 'tell me what the weather is like' }], + model: 'gpt-3.5-turbo', + tools: [ + { + type: 'function', + function: { + function: function getWeather() { + return `it's raining`; + }, + parameters: {}, + description: 'gets the weather', + }, + }, + ], + }); + const listener = new StreamingRunnerListener(runner); + await Promise.all([ + handleRequest(async function* (request) { + expect(request.messages).toEqual([{ role: 'user', content: 'tell me what the weather is like' }]); + yield { + id: '1', + choices: [ + { + index: 0, + finish_reason: 'function_call', + logprobs: null, + delta: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + index: 0, + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + }), + handleRequest(async function* (request) { + expect(request.messages).toEqual([ + { role: 'user', content: 'tell me what the weather is like' }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + { + role: 'tool', + content: `it's raining`, + tool_call_id: '123', + }, + ]); + for (const choice of contentChoiceDeltas(`it's raining`)) { + yield { + id: '2', + choices: [choice], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + } + }), + runner.done(), + ]); + expect(listener.eventMessages).toEqual([ + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + { role: 'tool', content: `it's raining`, tool_call_id: '123' }, + { role: 'assistant', content: "it's raining" }, + ]); + expect(listener.eventFunctionCallResults).toEqual([`it's raining`]); + await listener.sanityCheck(); + }); + test('flow with abort', async () => { + const { fetch, handleRequest } = mockStreamingChatCompletionFetch(); + const openai = new OpenAI({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + const controller = new AbortController(); + const runner = openai.beta.chat.completions.runTools({ + stream: true, + messages: [{ role: 'user', content: 'tell me what the weather is like' }], + model: 'gpt-3.5-turbo', + tools: [ + { + type: 'function', + function: { + function: function getWeather() { + return `it's raining`; + }, + parameters: {}, + description: 'gets the weather', + }, + }, + ], + }, { signal: controller.signal }); + runner.on('functionCallResult', () => controller.abort()); + const listener = new StreamingRunnerListener(runner); + await handleRequest(async function* (request) { + expect(request.messages).toEqual([{ role: 'user', content: 'tell me what the weather is like' }]); + yield { + id: '1', + choices: [ + { + index: 0, + finish_reason: 'function_call', + delta: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + index: 0, + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + }); + await runner.done().catch(() => { }); + expect(listener.eventMessages).toEqual([ + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + { role: 'tool', content: `it's raining`, tool_call_id: '123' }, + ]); + expect(listener.eventFunctionCallResults).toEqual([`it's raining`]); + await listener.sanityCheck({ error: 'Request was aborted.' }); + expect(runner.aborted).toBe(true); + }); + test('successful flow with parse', async () => { + const { fetch, handleRequest } = mockStreamingChatCompletionFetch(); + const openai = new OpenAI({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + const runner = openai.beta.chat.completions.runTools({ + stream: true, + messages: [ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + ], + model: 'gpt-3.5-turbo', + tools: [ + new ParsingToolFunction({ + name: 'numProperties', + function: (obj) => String(Object.keys(obj).length), + parameters: { type: 'object' }, + parse: (str) => { + const result = JSON.parse(str); + if (!(result instanceof Object) || Array.isArray(result)) { + throw new Error('must be an object'); + } + return result; + }, + description: 'gets the number of properties on an object', + }), + ], + }); + const listener = new StreamingRunnerListener(runner); + await Promise.all([ + handleRequest(async function* (request) { + expect(request.messages).toEqual([ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + ]); + yield { + id: '1', + choices: [ + { + index: 0, + finish_reason: 'function_call', + delta: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + index: 0, + function: { + arguments: '{"a": 1, "b": 2, "c": 3}', + name: 'numProperties', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + }), + handleRequest(async function* (request) { + expect(request.messages).toEqual([ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '{"a": 1, "b": 2, "c": 3}', + name: 'numProperties', + }, + }, + ], + }, + { + role: 'tool', + content: '3', + tool_call_id: '123', + }, + ]); + for (const choice of contentChoiceDeltas(`there are 3 properties in {"a": 1, "b": 2, "c": 3}`)) { + yield { + id: '2', + choices: [choice], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + } + }), + runner.done(), + ]); + expect(listener.eventMessages).toEqual([ + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { name: 'numProperties', arguments: '{"a": 1, "b": 2, "c": 3}' }, + }, + ], + }, + { role: 'tool', content: '3', tool_call_id: '123' }, + { role: 'assistant', content: 'there are 3 properties in {"a": 1, "b": 2, "c": 3}' }, + ]); + expect(listener.eventFunctionCallResults).toEqual(['3']); + await listener.sanityCheck(); + }); + test('flow with parse error', async () => { + const { fetch, handleRequest } = mockStreamingChatCompletionFetch(); + const openai = new OpenAI({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + const runner = openai.beta.chat.completions.runTools({ + stream: true, + messages: [ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + ], + model: 'gpt-3.5-turbo', + tools: [ + new ParsingToolFunction({ + name: 'numProperties', + function: (obj) => String(Object.keys(obj).length), + parameters: { type: 'object' }, + parse: (str) => { + const result = JSON.parse(str); + if (!(result instanceof Object) || Array.isArray(result)) { + throw new Error('must be an object'); + } + return result; + }, + description: 'gets the number of properties on an object', + }), + ], + }); + const listener = new StreamingRunnerListener(runner); + await Promise.all([ + handleRequest(async function* (request) { + expect(request.messages).toEqual([ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + ]); + for (const choice of functionCallDeltas('[{"a": 1, "b": 2, "c": 3}]', { + name: 'numProperties', + id: '123', + })) { + yield { + id: '1', + choices: [choice], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + } + }), + handleRequest(async function* (request) { + expect(request.messages).toEqual([ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '[{"a": 1, "b": 2, "c": 3}]', + name: 'numProperties', + }, + }, + ], + }, + { + role: 'tool', + content: `must be an object`, + tool_call_id: '123', + }, + ]); + for (const choice of functionCallDeltas('{"a": 1, "b": 2, "c": 3}', { + name: 'numProperties', + id: '1234', + })) { + yield { + id: '2', + choices: [choice], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + } + }), + handleRequest(async function* (request) { + expect(request.messages).toEqual([ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '[{"a": 1, "b": 2, "c": 3}]', + name: 'numProperties', + }, + }, + ], + }, + { + role: 'tool', + content: `must be an object`, + tool_call_id: '123', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '1234', + function: { + arguments: '{"a": 1, "b": 2, "c": 3}', + name: 'numProperties', + }, + }, + ], + }, + { + role: 'tool', + content: '3', + tool_call_id: '1234', + }, + ]); + for (const choice of contentChoiceDeltas(`there are 3 properties in {"a": 1, "b": 2, "c": 3}`)) { + yield { + id: '3', + choices: [choice], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + } + }), + runner.done(), + ]); + expect(listener.eventMessages).toEqual([ + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { name: 'numProperties', arguments: '[{"a": 1, "b": 2, "c": 3}]' }, + }, + ], + }, + { role: 'tool', content: `must be an object`, tool_call_id: '123' }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '1234', + function: { name: 'numProperties', arguments: '{"a": 1, "b": 2, "c": 3}' }, + }, + ], + }, + { role: 'tool', content: '3', tool_call_id: '1234' }, + { role: 'assistant', content: 'there are 3 properties in {"a": 1, "b": 2, "c": 3}' }, + ]); + expect(listener.eventFunctionCallResults).toEqual([`must be an object`, '3']); + await listener.sanityCheck(); + }); + test('single function call', async () => { + const { fetch, handleRequest } = mockStreamingChatCompletionFetch(); + const openai = new OpenAI({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + const runner = openai.beta.chat.completions.runTools({ + stream: true, + messages: [{ role: 'user', content: 'tell me what the weather is like' }], + model: 'gpt-3.5-turbo', + tool_choice: { + type: 'function', + function: { + name: 'getWeather', + }, + }, + tools: [ + { + type: 'function', + function: { + function: function getWeather() { + return `it's raining`; + }, + parameters: {}, + description: 'gets the weather', + }, + }, + ], + }); + const listener = new StreamingRunnerListener(runner); + await Promise.all([ + handleRequest(async function* (request) { + expect(request.messages).toEqual([{ role: 'user', content: 'tell me what the weather is like' }]); + yield { + id: '1', + choices: [ + { + index: 0, + finish_reason: 'function_call', + delta: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + index: 0, + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + }), + runner.done(), + ]); + expect(listener.eventMessages).toEqual([ + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + { role: 'tool', tool_call_id: '123', content: `it's raining` }, + ]); + expect(listener.eventFunctionCallResults).toEqual([`it's raining`]); + await listener.sanityCheck(); + }); + test('wrong function name', async () => { + const { fetch, handleRequest } = mockStreamingChatCompletionFetch(); + const openai = new OpenAI({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + const runner = openai.beta.chat.completions.runTools({ + stream: true, + messages: [{ role: 'user', content: 'tell me what the weather is like' }], + model: 'gpt-3.5-turbo', + tools: [ + { + type: 'function', + function: { + function: function getWeather() { + return `it's raining`; + }, + parameters: {}, + description: 'gets the weather', + }, + }, + ], + }); + const listener = new StreamingRunnerListener(runner); + await Promise.all([ + handleRequest(async function* (request) { + expect(request.messages).toEqual([{ role: 'user', content: 'tell me what the weather is like' }]); + yield { + id: '1', + choices: [ + { + index: 0, + finish_reason: 'function_call', + delta: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + index: 0, + id: '123', + function: { + arguments: '', + name: 'get_weather', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + }), + handleRequest(async function* (request) { + expect(request.messages).toEqual([ + { role: 'user', content: 'tell me what the weather is like' }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'get_weather', + }, + }, + ], + }, + { + role: 'tool', + content: `Invalid tool_call: "get_weather". Available options are: "getWeather". Please try again`, + tool_call_id: '123', + }, + ]); + yield { + id: '2', + choices: [ + { + index: 0, + finish_reason: 'function_call', + logprobs: null, + delta: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + index: 0, + id: '1234', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + }), + handleRequest(async function* (request) { + expect(request.messages).toEqual([ + { role: 'user', content: 'tell me what the weather is like' }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'get_weather', + }, + }, + ], + }, + { + role: 'tool', + content: `Invalid tool_call: "get_weather". Available options are: "getWeather". Please try again`, + tool_call_id: '123', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '1234', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + { + role: 'tool', + content: `it's raining`, + tool_call_id: '1234', + }, + ]); + for (const choice of contentChoiceDeltas(`it's raining`)) { + yield { + id: '3', + choices: [choice], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + } + }), + runner.done(), + ]); + expect(listener.eventMessages).toEqual([ + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'get_weather', + }, + }, + ], + }, + { + role: 'tool', + content: `Invalid tool_call: "get_weather". Available options are: "getWeather". Please try again`, + tool_call_id: '123', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '1234', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + { role: 'tool', content: `it's raining`, tool_call_id: '1234' }, + { role: 'assistant', content: "it's raining" }, + ]); + expect(listener.eventFunctionCallResults).toEqual([ + `Invalid tool_call: "get_weather". Available options are: "getWeather". Please try again`, + `it's raining`, + ]); + await listener.sanityCheck(); + }); + }); + describe('stream', () => { + test('successful flow', async () => { + const { fetch, handleRequest } = mockStreamingChatCompletionFetch(); + const openai = new OpenAI({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + const runner = openai.beta.chat.completions.stream({ + stream: true, + messages: [{ role: 'user', content: 'tell me what the weather is like' }], + model: 'gpt-3.5-turbo', + }); + const listener = new StreamingRunnerListener(runner); + await Promise.all([ + handleRequest(async function* (request) { + expect(request.messages).toEqual([{ role: 'user', content: 'tell me what the weather is like' }]); + for (const choice of contentChoiceDeltas(`The weather is great today!`)) { + yield { + id: '1', + choices: [choice], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + } + }), + runner.done(), + ]); + expect(listener.finalMessage).toEqual({ role: 'assistant', content: 'The weather is great today!' }); + await listener.sanityCheck(); + }); + test('toReadableStream and fromReadableStream', async () => { + const { fetch, handleRequest } = mockStreamingChatCompletionFetch(); + const openai = new OpenAI({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + const runner = openai.beta.chat.completions.stream({ + stream: true, + messages: [{ role: 'user', content: 'tell me what the weather is like' }], + model: 'gpt-3.5-turbo', + }); + const proxied = ChatCompletionStreamingRunner.fromReadableStream(runner.toReadableStream()); + const listener = new StreamingRunnerListener(proxied); + await Promise.all([ + handleRequest(async function* (request) { + expect(request.messages).toEqual([{ role: 'user', content: 'tell me what the weather is like' }]); + for (const choice of contentChoiceDeltas(`The weather is great today!`)) { + yield { + id: '1', + choices: [choice], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + } + }), + proxied.done(), + ]); + expect(listener.finalMessage).toEqual({ role: 'assistant', content: 'The weather is great today!' }); + await listener.sanityCheck(); + }); + test('handles network errors', async () => { + const { fetch, handleRequest } = mockFetch(); + const openai = new OpenAI({ apiKey: '...', fetch }); + const stream = openai.beta.chat.completions.stream({ + max_tokens: 1024, + model: 'gpt-3.5-turbo', + messages: [{ role: 'user', content: 'Say hello there!' }], + }, { maxRetries: 0 }); + handleRequest(async () => { + throw new Error('mock request error'); + }).catch(() => { }); + async function runStream() { + await stream.done(); + } + await expect(runStream).rejects.toThrow(APIConnectionError); + }); + test('handles network errors on async iterator', async () => { + const { fetch, handleRequest } = mockFetch(); + const openai = new OpenAI({ apiKey: '...', fetch }); + const stream = openai.beta.chat.completions.stream({ + max_tokens: 1024, + model: 'gpt-3.5-turbo', + messages: [{ role: 'user', content: 'Say hello there!' }], + }, { maxRetries: 0 }); + handleRequest(async () => { + throw new Error('mock request error'); + }).catch(() => { }); + async function runStream() { + for await (const _event of stream) { + continue; + } + } + await expect(runStream).rejects.toThrow(APIConnectionError); + }); + }); +}); +//# sourceMappingURL=ChatCompletionRunFunctions.test.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/lib/ChatCompletionRunFunctions.test.mjs.map b/backend/node_modules/openai/lib/ChatCompletionRunFunctions.test.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..13ef7a79d42091ff79999698a33a6874cb75926e --- /dev/null +++ b/backend/node_modules/openai/lib/ChatCompletionRunFunctions.test.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"ChatCompletionRunFunctions.test.mjs","sourceRoot":"","sources":["../src/lib/ChatCompletionRunFunctions.test.ts"],"names":[],"mappings":"OAAO,MAAM,MAAM,QAAQ;OACpB,EAAe,kBAAkB,EAAE,MAAM,cAAc;OACvD,EAAE,WAAW,EAAE,MAAM,QAAQ;OAC7B,EACL,mBAAmB,EAGnB,6BAA6B,GAE9B,MAAM,wCAAwC;OAIxC,EAAE,QAAQ,EAAE,MAAM,YAAY;OAC9B,EAAE,kBAAkB,EAAE;AAI7B;;;;;;;;GAQG;AACH,SAAS,SAAS;IAChB,MAAM,UAAU,GAAwC,EAAE,CAAC;IAC3D,MAAM,YAAY,GAA4B,EAAE,CAAC;IAEjD,MAAM,cAAc,GAAG,GAAG,EAAE;QAC1B,YAAY,CAAC,IAAI,CACf,IAAI,OAAO,CAAe,CAAC,OAAO,EAAE,EAAE;YACpC,UAAU,CAAC,IAAI,CAAC,CAAC,MAAoB,EAAE,EAAE;gBACvC,cAAc,EAAE,CAAC;gBACjB,OAAO,CAAC,MAAM,CAAC,CAAC;YAClB,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CACH,CAAC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AAI,CAAC,0CAA0C,EAAE,KAAK,IAAI,EAAE;YAC1D,MAAM,EAAE,KAAK,EAAE,aAAa,EAAE,GAAG,SAAS,EAAE,CAAC;YAE7C,MAAM,MAAM,GAAG,IAAI,MAAM,CAAC,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;YAEpD,MAAM,MAAM,GAAG,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,WAAW,CAAC,MAAM,CAChD;gBACE,UAAU,EAAE,IAAI;gBAChB,KAAK,EAAE,eAAe;gBACtB,QAAQ,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,kBAAkB,EAAE,CAAC;aAC1D,EACD,EAAE,UAAU,EAAE,CAAC,EAAE,CAClB,CAAC;YAEF,aAAa,CAAC,KAAK,IAAI,EAAE;gBACvB,MAAM,IAAI,KAAK,CAAC,oBAAoB,CAAC,CAAC;YACxC,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;YAEnB,KAAK,UAAU,SAAS;gBACtB,IAAI,KAAK,EAAE,MAAM,MAAM,IAAI,MAAM,EAAE;oBACjC,SAAS;iBACV;YACH,CAAC;YAED,MAAM,MAAM,CAAC,SAAS,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC,kBAAkB,CAAC,CAAC;QAC9D,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/openai/lib/ChatCompletionRunner.d.ts b/backend/node_modules/openai/lib/ChatCompletionRunner.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..73a44a99d625135f030b82e5b916e2efc547243a --- /dev/null +++ b/backend/node_modules/openai/lib/ChatCompletionRunner.d.ts @@ -0,0 +1,19 @@ +import { type Completions, type ChatCompletionMessageParam, type ChatCompletionCreateParamsNonStreaming } from 'openai/resources/chat/completions'; +import { type RunnableFunctions, type BaseFunctionsArgs, RunnableTools } from "./RunnableFunction.js"; +import { AbstractChatCompletionRunner, AbstractChatCompletionRunnerEvents, RunnerOptions } from "./AbstractChatCompletionRunner.js"; +export interface ChatCompletionRunnerEvents extends AbstractChatCompletionRunnerEvents { + content: (content: string) => void; +} +export type ChatCompletionFunctionRunnerParams = Omit & { + functions: RunnableFunctions; +}; +export type ChatCompletionToolRunnerParams = Omit & { + tools: RunnableTools; +}; +export declare class ChatCompletionRunner extends AbstractChatCompletionRunner { + /** @deprecated - please use `runTools` instead. */ + static runFunctions(completions: Completions, params: ChatCompletionFunctionRunnerParams, options?: RunnerOptions): ChatCompletionRunner; + static runTools(completions: Completions, params: ChatCompletionToolRunnerParams, options?: RunnerOptions): ChatCompletionRunner; + _addMessage(message: ChatCompletionMessageParam): void; +} +//# sourceMappingURL=ChatCompletionRunner.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/lib/ChatCompletionRunner.d.ts.map b/backend/node_modules/openai/lib/ChatCompletionRunner.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..3ca4c2d0332e47520c337582590d1db25300299b --- /dev/null +++ b/backend/node_modules/openai/lib/ChatCompletionRunner.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ChatCompletionRunner.d.ts","sourceRoot":"","sources":["../src/lib/ChatCompletionRunner.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,WAAW,EAChB,KAAK,0BAA0B,EAC/B,KAAK,sCAAsC,EAC5C,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAE,KAAK,iBAAiB,EAAE,KAAK,iBAAiB,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnG,OAAO,EACL,4BAA4B,EAC5B,kCAAkC,EAClC,aAAa,EACd,MAAM,gCAAgC,CAAC;AAGxC,MAAM,WAAW,0BAA2B,SAAQ,kCAAkC;IACpF,OAAO,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;CACpC;AAED,MAAM,MAAM,kCAAkC,CAAC,aAAa,SAAS,iBAAiB,IAAI,IAAI,CAC5F,sCAAsC,EACtC,WAAW,CACZ,GAAG;IACF,SAAS,EAAE,iBAAiB,CAAC,aAAa,CAAC,CAAC;CAC7C,CAAC;AAEF,MAAM,MAAM,8BAA8B,CAAC,aAAa,SAAS,iBAAiB,IAAI,IAAI,CACxF,sCAAsC,EACtC,OAAO,CACR,GAAG;IACF,KAAK,EAAE,aAAa,CAAC,aAAa,CAAC,CAAC;CACrC,CAAC;AAEF,qBAAa,oBAAqB,SAAQ,4BAA4B,CAAC,0BAA0B,CAAC;IAChG,mDAAmD;IACnD,MAAM,CAAC,YAAY,CACjB,WAAW,EAAE,WAAW,EACxB,MAAM,EAAE,kCAAkC,CAAC,GAAG,EAAE,CAAC,EACjD,OAAO,CAAC,EAAE,aAAa,GACtB,oBAAoB;IAUvB,MAAM,CAAC,QAAQ,CACb,WAAW,EAAE,WAAW,EACxB,MAAM,EAAE,8BAA8B,CAAC,GAAG,EAAE,CAAC,EAC7C,OAAO,CAAC,EAAE,aAAa,GACtB,oBAAoB;IAUd,WAAW,CAAC,OAAO,EAAE,0BAA0B;CAMzD"} \ No newline at end of file diff --git a/backend/node_modules/openai/lib/ChatCompletionRunner.js b/backend/node_modules/openai/lib/ChatCompletionRunner.js new file mode 100644 index 0000000000000000000000000000000000000000..c85a1dd1bdb18ecc8791a05e6dd6f183b8671db3 --- /dev/null +++ b/backend/node_modules/openai/lib/ChatCompletionRunner.js @@ -0,0 +1,34 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ChatCompletionRunner = void 0; +const AbstractChatCompletionRunner_1 = require("./AbstractChatCompletionRunner.js"); +const chatCompletionUtils_1 = require("./chatCompletionUtils.js"); +class ChatCompletionRunner extends AbstractChatCompletionRunner_1.AbstractChatCompletionRunner { + /** @deprecated - please use `runTools` instead. */ + static runFunctions(completions, params, options) { + const runner = new ChatCompletionRunner(); + const opts = { + ...options, + headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'runFunctions' }, + }; + runner._run(() => runner._runFunctions(completions, params, opts)); + return runner; + } + static runTools(completions, params, options) { + const runner = new ChatCompletionRunner(); + const opts = { + ...options, + headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'runTools' }, + }; + runner._run(() => runner._runTools(completions, params, opts)); + return runner; + } + _addMessage(message) { + super._addMessage(message); + if ((0, chatCompletionUtils_1.isAssistantMessage)(message) && message.content) { + this._emit('content', message.content); + } + } +} +exports.ChatCompletionRunner = ChatCompletionRunner; +//# sourceMappingURL=ChatCompletionRunner.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/lib/ChatCompletionRunner.js.map b/backend/node_modules/openai/lib/ChatCompletionRunner.js.map new file mode 100644 index 0000000000000000000000000000000000000000..24ec3e0bb4bcb2b14f8947b5aaa27281fe7ebef7 --- /dev/null +++ b/backend/node_modules/openai/lib/ChatCompletionRunner.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ChatCompletionRunner.js","sourceRoot":"","sources":["../src/lib/ChatCompletionRunner.ts"],"names":[],"mappings":";;;AAMA,oFAIwC;AACxC,kEAA2D;AAoB3D,MAAa,oBAAqB,SAAQ,2DAAwD;IAChG,mDAAmD;IACnD,MAAM,CAAC,YAAY,CACjB,WAAwB,EACxB,MAAiD,EACjD,OAAuB;QAEvB,MAAM,MAAM,GAAG,IAAI,oBAAoB,EAAE,CAAC;QAC1C,MAAM,IAAI,GAAG;YACX,GAAG,OAAO;YACV,OAAO,EAAE,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE,2BAA2B,EAAE,cAAc,EAAE;SAC9E,CAAC;QACF,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,aAAa,CAAC,WAAW,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC,CAAC;QACnE,OAAO,MAAM,CAAC;IAChB,CAAC;IAED,MAAM,CAAC,QAAQ,CACb,WAAwB,EACxB,MAA6C,EAC7C,OAAuB;QAEvB,MAAM,MAAM,GAAG,IAAI,oBAAoB,EAAE,CAAC;QAC1C,MAAM,IAAI,GAAG;YACX,GAAG,OAAO;YACV,OAAO,EAAE,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE,2BAA2B,EAAE,UAAU,EAAE;SAC1E,CAAC;QACF,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,SAAS,CAAC,WAAW,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC,CAAC;QAC/D,OAAO,MAAM,CAAC;IAChB,CAAC;IAEQ,WAAW,CAAC,OAAmC;QACtD,KAAK,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;QAC3B,IAAI,IAAA,wCAAkB,EAAC,OAAO,CAAC,IAAI,OAAO,CAAC,OAAO,EAAE;YAClD,IAAI,CAAC,KAAK,CAAC,SAAS,EAAE,OAAO,CAAC,OAAiB,CAAC,CAAC;SAClD;IACH,CAAC;CACF;AApCD,oDAoCC"} \ No newline at end of file diff --git a/backend/node_modules/openai/lib/ChatCompletionRunner.mjs b/backend/node_modules/openai/lib/ChatCompletionRunner.mjs new file mode 100644 index 0000000000000000000000000000000000000000..354355cdfb79e9d6585c2661586385a64ccd6fdf --- /dev/null +++ b/backend/node_modules/openai/lib/ChatCompletionRunner.mjs @@ -0,0 +1,30 @@ +import { AbstractChatCompletionRunner, } from "./AbstractChatCompletionRunner.mjs"; +import { isAssistantMessage } from "./chatCompletionUtils.mjs"; +export class ChatCompletionRunner extends AbstractChatCompletionRunner { + /** @deprecated - please use `runTools` instead. */ + static runFunctions(completions, params, options) { + const runner = new ChatCompletionRunner(); + const opts = { + ...options, + headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'runFunctions' }, + }; + runner._run(() => runner._runFunctions(completions, params, opts)); + return runner; + } + static runTools(completions, params, options) { + const runner = new ChatCompletionRunner(); + const opts = { + ...options, + headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'runTools' }, + }; + runner._run(() => runner._runTools(completions, params, opts)); + return runner; + } + _addMessage(message) { + super._addMessage(message); + if (isAssistantMessage(message) && message.content) { + this._emit('content', message.content); + } + } +} +//# sourceMappingURL=ChatCompletionRunner.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/lib/ChatCompletionRunner.mjs.map b/backend/node_modules/openai/lib/ChatCompletionRunner.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..144b8e7b968519c264dea8655d1be6af085210fd --- /dev/null +++ b/backend/node_modules/openai/lib/ChatCompletionRunner.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"ChatCompletionRunner.mjs","sourceRoot":"","sources":["../src/lib/ChatCompletionRunner.ts"],"names":[],"mappings":"OAMO,EACL,4BAA4B,GAG7B;OACM,EAAE,kBAAkB,EAAE;AAoB7B,MAAM,OAAO,oBAAqB,SAAQ,4BAAwD;IAChG,mDAAmD;IACnD,MAAM,CAAC,YAAY,CACjB,WAAwB,EACxB,MAAiD,EACjD,OAAuB;QAEvB,MAAM,MAAM,GAAG,IAAI,oBAAoB,EAAE,CAAC;QAC1C,MAAM,IAAI,GAAG;YACX,GAAG,OAAO;YACV,OAAO,EAAE,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE,2BAA2B,EAAE,cAAc,EAAE;SAC9E,CAAC;QACF,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,aAAa,CAAC,WAAW,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC,CAAC;QACnE,OAAO,MAAM,CAAC;IAChB,CAAC;IAED,MAAM,CAAC,QAAQ,CACb,WAAwB,EACxB,MAA6C,EAC7C,OAAuB;QAEvB,MAAM,MAAM,GAAG,IAAI,oBAAoB,EAAE,CAAC;QAC1C,MAAM,IAAI,GAAG;YACX,GAAG,OAAO;YACV,OAAO,EAAE,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE,2BAA2B,EAAE,UAAU,EAAE;SAC1E,CAAC;QACF,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,SAAS,CAAC,WAAW,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC,CAAC;QAC/D,OAAO,MAAM,CAAC;IAChB,CAAC;IAEQ,WAAW,CAAC,OAAmC;QACtD,KAAK,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;QAC3B,IAAI,kBAAkB,CAAC,OAAO,CAAC,IAAI,OAAO,CAAC,OAAO,EAAE;YAClD,IAAI,CAAC,KAAK,CAAC,SAAS,EAAE,OAAO,CAAC,OAAiB,CAAC,CAAC;SAClD;IACH,CAAC;CACF"} \ No newline at end of file diff --git a/backend/node_modules/openai/lib/ChatCompletionStream.d.ts b/backend/node_modules/openai/lib/ChatCompletionStream.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3402c38607c75505a05567be3808991413c20567 --- /dev/null +++ b/backend/node_modules/openai/lib/ChatCompletionStream.d.ts @@ -0,0 +1,149 @@ +import * as Core from 'openai/core'; +import { Completions, type ChatCompletion, type ChatCompletionChunk, type ChatCompletionCreateParams, type ChatCompletionCreateParamsBase } from 'openai/resources/chat/completions'; +import { AbstractChatCompletionRunner, type AbstractChatCompletionRunnerEvents } from "./AbstractChatCompletionRunner.js"; +import { type ReadableStream } from 'openai/_shims/index'; +export interface ChatCompletionStreamEvents extends AbstractChatCompletionRunnerEvents { + content: (contentDelta: string, contentSnapshot: string) => void; + chunk: (chunk: ChatCompletionChunk, snapshot: ChatCompletionSnapshot) => void; +} +export type ChatCompletionStreamParams = Omit & { + stream?: true; +}; +export declare class ChatCompletionStream extends AbstractChatCompletionRunner implements AsyncIterable { + #private; + get currentChatCompletionSnapshot(): ChatCompletionSnapshot | undefined; + /** + * Intended for use on the frontend, consuming a stream produced with + * `.toReadableStream()` on the backend. + * + * Note that messages sent to the model do not appear in `.on('message')` + * in this context. + */ + static fromReadableStream(stream: ReadableStream): ChatCompletionStream; + static createChatCompletion(completions: Completions, params: ChatCompletionStreamParams, options?: Core.RequestOptions): ChatCompletionStream; + protected _createChatCompletion(completions: Completions, params: ChatCompletionCreateParams, options?: Core.RequestOptions): Promise; + protected _fromReadableStream(readableStream: ReadableStream, options?: Core.RequestOptions): Promise; + [Symbol.asyncIterator](): AsyncIterator; + toReadableStream(): ReadableStream; +} +/** + * Represents a streamed chunk of a chat completion response returned by model, + * based on the provided input. + */ +export interface ChatCompletionSnapshot { + /** + * A unique identifier for the chat completion. + */ + id: string; + /** + * A list of chat completion choices. Can be more than one if `n` is greater + * than 1. + */ + choices: Array; + /** + * The Unix timestamp (in seconds) of when the chat completion was created. + */ + created: number; + /** + * The model to generate the completion. + */ + model: string; + /** + * This fingerprint represents the backend configuration that the model runs with. + * + * Can be used in conjunction with the `seed` request parameter to understand when + * backend changes have been made that might impact determinism. + */ + system_fingerprint?: string; +} +export declare namespace ChatCompletionSnapshot { + interface Choice { + /** + * A chat completion delta generated by streamed model responses. + */ + message: Choice.Message; + /** + * The reason the model stopped generating tokens. This will be `stop` if the model + * hit a natural stop point or a provided stop sequence, `length` if the maximum + * number of tokens specified in the request was reached, `content_filter` if + * content was omitted due to a flag from our content filters, or `function_call` + * if the model called a function. + */ + finish_reason: ChatCompletion.Choice['finish_reason'] | null; + /** + * Log probability information for the choice. + */ + logprobs: ChatCompletion.Choice.Logprobs | null; + /** + * The index of the choice in the list of choices. + */ + index: number; + } + namespace Choice { + /** + * A chat completion delta generated by streamed model responses. + */ + interface Message { + /** + * The contents of the chunk message. + */ + content?: string | null; + /** + * The name and arguments of a function that should be called, as generated by the + * model. + */ + function_call?: Message.FunctionCall; + tool_calls?: Array; + /** + * The role of the author of this message. + */ + role?: 'system' | 'user' | 'assistant' | 'function' | 'tool'; + } + namespace Message { + interface ToolCall { + /** + * The ID of the tool call. + */ + id?: string; + function?: ToolCall.Function; + /** + * The type of the tool. + */ + type?: 'function'; + } + namespace ToolCall { + interface Function { + /** + * The arguments to call the function with, as generated by the model in JSON + * format. Note that the model does not always generate valid JSON, and may + * hallucinate parameters not defined by your function schema. Validate the + * arguments in your code before calling your function. + */ + arguments?: string; + /** + * The name of the function to call. + */ + name?: string; + } + } + /** + * The name and arguments of a function that should be called, as generated by the + * model. + */ + interface FunctionCall { + /** + * The arguments to call the function with, as generated by the model in JSON + * format. Note that the model does not always generate valid JSON, and may + * hallucinate parameters not defined by your function schema. Validate the + * arguments in your code before calling your function. + */ + arguments?: string; + /** + * The name of the function to call. + */ + name?: string; + } + } + } +} +//# sourceMappingURL=ChatCompletionStream.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/lib/ChatCompletionStream.d.ts.map b/backend/node_modules/openai/lib/ChatCompletionStream.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..90b8a52e28536d1b9e69b489704d0cecc7918852 --- /dev/null +++ b/backend/node_modules/openai/lib/ChatCompletionStream.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ChatCompletionStream.d.ts","sourceRoot":"","sources":["../src/lib/ChatCompletionStream.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,IAAI,MAAM,aAAa,CAAC;AAEpC,OAAO,EACL,WAAW,EACX,KAAK,cAAc,EACnB,KAAK,mBAAmB,EACxB,KAAK,0BAA0B,EAC/B,KAAK,8BAA8B,EACpC,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EACL,4BAA4B,EAC5B,KAAK,kCAAkC,EACxC,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,KAAK,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAG1D,MAAM,WAAW,0BAA2B,SAAQ,kCAAkC;IACpF,OAAO,EAAE,CAAC,YAAY,EAAE,MAAM,EAAE,eAAe,EAAE,MAAM,KAAK,IAAI,CAAC;IACjE,KAAK,EAAE,CAAC,KAAK,EAAE,mBAAmB,EAAE,QAAQ,EAAE,sBAAsB,KAAK,IAAI,CAAC;CAC/E;AAED,MAAM,MAAM,0BAA0B,GAAG,IAAI,CAAC,8BAA8B,EAAE,QAAQ,CAAC,GAAG;IACxF,MAAM,CAAC,EAAE,IAAI,CAAC;CACf,CAAC;AAEF,qBAAa,oBAC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AE,cAAc,CAAC,MAAM,CAAC,QAAQ,GAAG,IAAI,CAAC;QAEhD;;WAEG;QACH,KAAK,EAAE,MAAM,CAAC;KACf;IAED,UAAiB,MAAM,CAAC;QACtB;;WAEG;QACH,UAAiB,OAAO;YACtB;;eAEG;YACH,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;YAExB;;;eAGG;YACH,aAAa,CAAC,EAAE,OAAO,CAAC,YAAY,CAAC;YAErC,UAAU,CAAC,EAAE,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;YAErC;;eAEG;YACH,IAAI,CAAC,EAAE,QAAQ,GAAG,MAAM,GAAG,WAAW,GAAG,UAAU,GAAG,MAAM,CAAC;SAC9D;QAED,UAAiB,OAAO,CAAC;YACvB,UAAiB,QAAQ;gBACvB;;mBAEG;gBACH,EAAE,CAAC,EAAE,MAAM,CAAC;gBAEZ,QAAQ,CAAC,EAAE,QAAQ,CAAC,QAAQ,CAAC;gBAE7B;;mBAEG;gBACH,IAAI,CAAC,EAAE,UAAU,CAAC;aACnB;YAED,UAAiB,QAAQ,CAAC;gBACxB,UAAiB,QAAQ;oBACvB;;;;;uBAKG;oBACH,SAAS,CAAC,EAAE,MAAM,CAAC;oBAEnB;;uBAEG;oBACH,IAAI,CAAC,EAAE,MAAM,CAAC;iBACf;aACF;YAED;;;eAGG;YACH,UAAiB,YAAY;gBAC3B;;;;;mBAKG;gBACH,SAAS,CAAC,EAAE,MAAM,CAAC;gBAEnB;;mBAEG;gBACH,IAAI,CAAC,EAAE,MAAM,CAAC;aACf;SACF;KACF;CACF"} \ No newline at end of file diff --git a/backend/node_modules/openai/lib/ChatCompletionStream.js b/backend/node_modules/openai/lib/ChatCompletionStream.js new file mode 100644 index 0000000000000000000000000000000000000000..db5c3e6f194579b616721281124828723d72721c --- /dev/null +++ b/backend/node_modules/openai/lib/ChatCompletionStream.js @@ -0,0 +1,312 @@ +"use strict"; +var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +}; +var _ChatCompletionStream_instances, _ChatCompletionStream_currentChatCompletionSnapshot, _ChatCompletionStream_beginRequest, _ChatCompletionStream_addChunk, _ChatCompletionStream_endRequest, _ChatCompletionStream_accumulateChatCompletion; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ChatCompletionStream = void 0; +const error_1 = require("openai/error"); +const AbstractChatCompletionRunner_1 = require("./AbstractChatCompletionRunner.js"); +const streaming_1 = require("openai/streaming"); +class ChatCompletionStream extends AbstractChatCompletionRunner_1.AbstractChatCompletionRunner { + constructor() { + super(...arguments); + _ChatCompletionStream_instances.add(this); + _ChatCompletionStream_currentChatCompletionSnapshot.set(this, void 0); + } + get currentChatCompletionSnapshot() { + return __classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f"); + } + /** + * Intended for use on the frontend, consuming a stream produced with + * `.toReadableStream()` on the backend. + * + * Note that messages sent to the model do not appear in `.on('message')` + * in this context. + */ + static fromReadableStream(stream) { + const runner = new ChatCompletionStream(); + runner._run(() => runner._fromReadableStream(stream)); + return runner; + } + static createChatCompletion(completions, params, options) { + const runner = new ChatCompletionStream(); + runner._run(() => runner._runChatCompletion(completions, { ...params, stream: true }, { ...options, headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' } })); + return runner; + } + async _createChatCompletion(completions, params, options) { + const signal = options?.signal; + if (signal) { + if (signal.aborted) + this.controller.abort(); + signal.addEventListener('abort', () => this.controller.abort()); + } + __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this); + const stream = await completions.create({ ...params, stream: true }, { ...options, signal: this.controller.signal }); + this._connected(); + for await (const chunk of stream) { + __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk); + } + if (stream.controller.signal?.aborted) { + throw new error_1.APIUserAbortError(); + } + return this._addChatCompletion(__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this)); + } + async _fromReadableStream(readableStream, options) { + const signal = options?.signal; + if (signal) { + if (signal.aborted) + this.controller.abort(); + signal.addEventListener('abort', () => this.controller.abort()); + } + __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this); + this._connected(); + const stream = streaming_1.Stream.fromReadableStream(readableStream, this.controller); + let chatId; + for await (const chunk of stream) { + if (chatId && chatId !== chunk.id) { + // A new request has been made. + this._addChatCompletion(__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this)); + } + __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk); + chatId = chunk.id; + } + if (stream.controller.signal?.aborted) { + throw new error_1.APIUserAbortError(); + } + return this._addChatCompletion(__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this)); + } + [(_ChatCompletionStream_currentChatCompletionSnapshot = new WeakMap(), _ChatCompletionStream_instances = new WeakSet(), _ChatCompletionStream_beginRequest = function _ChatCompletionStream_beginRequest() { + if (this.ended) + return; + __classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, undefined, "f"); + }, _ChatCompletionStream_addChunk = function _ChatCompletionStream_addChunk(chunk) { + if (this.ended) + return; + const completion = __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_accumulateChatCompletion).call(this, chunk); + this._emit('chunk', chunk, completion); + const delta = chunk.choices[0]?.delta?.content; + const snapshot = completion.choices[0]?.message; + if (delta != null && snapshot?.role === 'assistant' && snapshot?.content) { + this._emit('content', delta, snapshot.content); + } + }, _ChatCompletionStream_endRequest = function _ChatCompletionStream_endRequest() { + if (this.ended) { + throw new error_1.OpenAIError(`stream has ended, this shouldn't happen`); + } + const snapshot = __classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f"); + if (!snapshot) { + throw new error_1.OpenAIError(`request ended without sending any chunks`); + } + __classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, undefined, "f"); + return finalizeChatCompletion(snapshot); + }, _ChatCompletionStream_accumulateChatCompletion = function _ChatCompletionStream_accumulateChatCompletion(chunk) { + var _a, _b, _c; + let snapshot = __classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f"); + const { choices, ...rest } = chunk; + if (!snapshot) { + snapshot = __classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, { + ...rest, + choices: [], + }, "f"); + } + else { + Object.assign(snapshot, rest); + } + for (const { delta, finish_reason, index, logprobs = null, ...other } of chunk.choices) { + let choice = snapshot.choices[index]; + if (!choice) { + choice = snapshot.choices[index] = { finish_reason, index, message: {}, logprobs, ...other }; + } + if (logprobs) { + if (!choice.logprobs) { + choice.logprobs = Object.assign({}, logprobs); + } + else { + const { content, ...rest } = logprobs; + Object.assign(choice.logprobs, rest); + if (content) { + (_a = choice.logprobs).content ?? (_a.content = []); + choice.logprobs.content.push(...content); + } + } + } + if (finish_reason) + choice.finish_reason = finish_reason; + Object.assign(choice, other); + if (!delta) + continue; // Shouldn't happen; just in case. + const { content, function_call, role, tool_calls, ...rest } = delta; + Object.assign(choice.message, rest); + if (content) + choice.message.content = (choice.message.content || '') + content; + if (role) + choice.message.role = role; + if (function_call) { + if (!choice.message.function_call) { + choice.message.function_call = function_call; + } + else { + if (function_call.name) + choice.message.function_call.name = function_call.name; + if (function_call.arguments) { + (_b = choice.message.function_call).arguments ?? (_b.arguments = ''); + choice.message.function_call.arguments += function_call.arguments; + } + } + } + if (tool_calls) { + if (!choice.message.tool_calls) + choice.message.tool_calls = []; + for (const { index, id, type, function: fn, ...rest } of tool_calls) { + const tool_call = ((_c = choice.message.tool_calls)[index] ?? (_c[index] = {})); + Object.assign(tool_call, rest); + if (id) + tool_call.id = id; + if (type) + tool_call.type = type; + if (fn) + tool_call.function ?? (tool_call.function = { arguments: '' }); + if (fn?.name) + tool_call.function.name = fn.name; + if (fn?.arguments) + tool_call.function.arguments += fn.arguments; + } + } + } + return snapshot; + }, Symbol.asyncIterator)]() { + const pushQueue = []; + const readQueue = []; + let done = false; + this.on('chunk', (chunk) => { + const reader = readQueue.shift(); + if (reader) { + reader.resolve(chunk); + } + else { + pushQueue.push(chunk); + } + }); + this.on('end', () => { + done = true; + for (const reader of readQueue) { + reader.resolve(undefined); + } + readQueue.length = 0; + }); + this.on('abort', (err) => { + done = true; + for (const reader of readQueue) { + reader.reject(err); + } + readQueue.length = 0; + }); + this.on('error', (err) => { + done = true; + for (const reader of readQueue) { + reader.reject(err); + } + readQueue.length = 0; + }); + return { + next: async () => { + if (!pushQueue.length) { + if (done) { + return { value: undefined, done: true }; + } + return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((chunk) => (chunk ? { value: chunk, done: false } : { value: undefined, done: true })); + } + const chunk = pushQueue.shift(); + return { value: chunk, done: false }; + }, + return: async () => { + this.abort(); + return { value: undefined, done: true }; + }, + }; + } + toReadableStream() { + const stream = new streaming_1.Stream(this[Symbol.asyncIterator].bind(this), this.controller); + return stream.toReadableStream(); + } +} +exports.ChatCompletionStream = ChatCompletionStream; +function finalizeChatCompletion(snapshot) { + const { id, choices, created, model, system_fingerprint, ...rest } = snapshot; + return { + ...rest, + id, + choices: choices.map(({ message, finish_reason, index, logprobs, ...choiceRest }) => { + if (!finish_reason) + throw new error_1.OpenAIError(`missing finish_reason for choice ${index}`); + const { content = null, function_call, tool_calls, ...messageRest } = message; + const role = message.role; // this is what we expect; in theory it could be different which would make our types a slight lie but would be fine. + if (!role) + throw new error_1.OpenAIError(`missing role for choice ${index}`); + if (function_call) { + const { arguments: args, name } = function_call; + if (args == null) + throw new error_1.OpenAIError(`missing function_call.arguments for choice ${index}`); + if (!name) + throw new error_1.OpenAIError(`missing function_call.name for choice ${index}`); + return { + ...choiceRest, + message: { content, function_call: { arguments: args, name }, role }, + finish_reason, + index, + logprobs, + }; + } + if (tool_calls) { + return { + ...choiceRest, + index, + finish_reason, + logprobs, + message: { + ...messageRest, + role, + content, + tool_calls: tool_calls.map((tool_call, i) => { + const { function: fn, type, id, ...toolRest } = tool_call; + const { arguments: args, name, ...fnRest } = fn || {}; + if (id == null) + throw new error_1.OpenAIError(`missing choices[${index}].tool_calls[${i}].id\n${str(snapshot)}`); + if (type == null) + throw new error_1.OpenAIError(`missing choices[${index}].tool_calls[${i}].type\n${str(snapshot)}`); + if (name == null) + throw new error_1.OpenAIError(`missing choices[${index}].tool_calls[${i}].function.name\n${str(snapshot)}`); + if (args == null) + throw new error_1.OpenAIError(`missing choices[${index}].tool_calls[${i}].function.arguments\n${str(snapshot)}`); + return { ...toolRest, id, type, function: { ...fnRest, name, arguments: args } }; + }), + }, + }; + } + return { + ...choiceRest, + message: { ...messageRest, content, role }, + finish_reason, + index, + logprobs, + }; + }), + created, + model, + object: 'chat.completion', + ...(system_fingerprint ? { system_fingerprint } : {}), + }; +} +function str(x) { + return JSON.stringify(x); +} +//# sourceMappingURL=ChatCompletionStream.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/lib/ChatCompletionStream.js.map b/backend/node_modules/openai/lib/ChatCompletionStream.js.map new file mode 100644 index 0000000000000000000000000000000000000000..7c01260bfd1f63075c4f31b4ff29152b77dd5f0f --- /dev/null +++ b/backend/node_modules/openai/lib/ChatCompletionStream.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ChatCompletionStream.js","sourceRoot":"","sources":["../src/lib/ChatCompletionStream.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AACA,wCAA8D;AAQ9D,oFAGwC;AAExC,gDAA0C;AAW1C,MAAa,oBACX,SAAQ,2DAAwD;IADlE;;;QAIE,sEAAmE;IAsPrE,CAAC;IApPC,IAAI,6BAA6B;QAC/B,OAAO,uBAAA,IAAI,2DAA+B,CAAC;IAC7C,CAAC;IAED;;;;;;OAMG;IACH,MAAM,CAAC,kBAAkB,CAAC,MAAsB;QAC9C,MAAM,MAAM,GAAG,IAAI,oBAAoB,EAAE,CAAC;QAC1C,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,mBAAmB,CAAC,MAAM,CAAC,CAAC,CAAC;QACtD,OAAO,MAAM,CAAC;IAChB,CAAC;IAED,MAAM,CAAC,oBAAoB,CACzB,WAAwB,EACxB,MAAkC,EAClC,OAA6B;QAE7B,MAAM,MAAM,GAAG,IAAI,oBAAoB,EAAE,CAAC;QAC1C,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,CACf,MAAM,CAAC,kBAAkB,CACvB,WAAW,EACX,EAAE,GAAG,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,EAC3B,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE,2BAA2B,EAAE,QAAQ,EAAE,EAAE,CACxF,CACF,CAAC;QACF,OAAO,MAAM,CAAC;IAChB,CAAC;IA4BkB,KAAK,CAAC,qBAAqB,CAC5C,WAAwB,EACxB,MAAkC,EAClC,OAA6B;QAE7B,MAAM,MAAM,GAAG,OAAO,EAAE,MAAM,CAAC;QAC/B,IAAI,MAAM,EAAE;YACV,IAAI,MAAM,CAAC,OAAO;gBAAE,IAAI,CAAC,UAAU,CAAC,KAAK,EAAE,CAAC;YAC5C,MAAM,CAAC,gBAAgB,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AAC3B,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/openai/lib/ChatCompletionStream.mjs b/backend/node_modules/openai/lib/ChatCompletionStream.mjs new file mode 100644 index 0000000000000000000000000000000000000000..95fe845bcf73ff8897386b4179fdbbde3421732b --- /dev/null +++ b/backend/node_modules/openai/lib/ChatCompletionStream.mjs @@ -0,0 +1,308 @@ +var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +}; +var _ChatCompletionStream_instances, _ChatCompletionStream_currentChatCompletionSnapshot, _ChatCompletionStream_beginRequest, _ChatCompletionStream_addChunk, _ChatCompletionStream_endRequest, _ChatCompletionStream_accumulateChatCompletion; +import { OpenAIError, APIUserAbortError } from 'openai/error'; +import { AbstractChatCompletionRunner, } from "./AbstractChatCompletionRunner.mjs"; +import { Stream } from 'openai/streaming'; +export class ChatCompletionStream extends AbstractChatCompletionRunner { + constructor() { + super(...arguments); + _ChatCompletionStream_instances.add(this); + _ChatCompletionStream_currentChatCompletionSnapshot.set(this, void 0); + } + get currentChatCompletionSnapshot() { + return __classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f"); + } + /** + * Intended for use on the frontend, consuming a stream produced with + * `.toReadableStream()` on the backend. + * + * Note that messages sent to the model do not appear in `.on('message')` + * in this context. + */ + static fromReadableStream(stream) { + const runner = new ChatCompletionStream(); + runner._run(() => runner._fromReadableStream(stream)); + return runner; + } + static createChatCompletion(completions, params, options) { + const runner = new ChatCompletionStream(); + runner._run(() => runner._runChatCompletion(completions, { ...params, stream: true }, { ...options, headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' } })); + return runner; + } + async _createChatCompletion(completions, params, options) { + const signal = options?.signal; + if (signal) { + if (signal.aborted) + this.controller.abort(); + signal.addEventListener('abort', () => this.controller.abort()); + } + __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this); + const stream = await completions.create({ ...params, stream: true }, { ...options, signal: this.controller.signal }); + this._connected(); + for await (const chunk of stream) { + __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk); + } + if (stream.controller.signal?.aborted) { + throw new APIUserAbortError(); + } + return this._addChatCompletion(__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this)); + } + async _fromReadableStream(readableStream, options) { + const signal = options?.signal; + if (signal) { + if (signal.aborted) + this.controller.abort(); + signal.addEventListener('abort', () => this.controller.abort()); + } + __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this); + this._connected(); + const stream = Stream.fromReadableStream(readableStream, this.controller); + let chatId; + for await (const chunk of stream) { + if (chatId && chatId !== chunk.id) { + // A new request has been made. + this._addChatCompletion(__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this)); + } + __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk); + chatId = chunk.id; + } + if (stream.controller.signal?.aborted) { + throw new APIUserAbortError(); + } + return this._addChatCompletion(__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this)); + } + [(_ChatCompletionStream_currentChatCompletionSnapshot = new WeakMap(), _ChatCompletionStream_instances = new WeakSet(), _ChatCompletionStream_beginRequest = function _ChatCompletionStream_beginRequest() { + if (this.ended) + return; + __classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, undefined, "f"); + }, _ChatCompletionStream_addChunk = function _ChatCompletionStream_addChunk(chunk) { + if (this.ended) + return; + const completion = __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_accumulateChatCompletion).call(this, chunk); + this._emit('chunk', chunk, completion); + const delta = chunk.choices[0]?.delta?.content; + const snapshot = completion.choices[0]?.message; + if (delta != null && snapshot?.role === 'assistant' && snapshot?.content) { + this._emit('content', delta, snapshot.content); + } + }, _ChatCompletionStream_endRequest = function _ChatCompletionStream_endRequest() { + if (this.ended) { + throw new OpenAIError(`stream has ended, this shouldn't happen`); + } + const snapshot = __classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f"); + if (!snapshot) { + throw new OpenAIError(`request ended without sending any chunks`); + } + __classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, undefined, "f"); + return finalizeChatCompletion(snapshot); + }, _ChatCompletionStream_accumulateChatCompletion = function _ChatCompletionStream_accumulateChatCompletion(chunk) { + var _a, _b, _c; + let snapshot = __classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f"); + const { choices, ...rest } = chunk; + if (!snapshot) { + snapshot = __classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, { + ...rest, + choices: [], + }, "f"); + } + else { + Object.assign(snapshot, rest); + } + for (const { delta, finish_reason, index, logprobs = null, ...other } of chunk.choices) { + let choice = snapshot.choices[index]; + if (!choice) { + choice = snapshot.choices[index] = { finish_reason, index, message: {}, logprobs, ...other }; + } + if (logprobs) { + if (!choice.logprobs) { + choice.logprobs = Object.assign({}, logprobs); + } + else { + const { content, ...rest } = logprobs; + Object.assign(choice.logprobs, rest); + if (content) { + (_a = choice.logprobs).content ?? (_a.content = []); + choice.logprobs.content.push(...content); + } + } + } + if (finish_reason) + choice.finish_reason = finish_reason; + Object.assign(choice, other); + if (!delta) + continue; // Shouldn't happen; just in case. + const { content, function_call, role, tool_calls, ...rest } = delta; + Object.assign(choice.message, rest); + if (content) + choice.message.content = (choice.message.content || '') + content; + if (role) + choice.message.role = role; + if (function_call) { + if (!choice.message.function_call) { + choice.message.function_call = function_call; + } + else { + if (function_call.name) + choice.message.function_call.name = function_call.name; + if (function_call.arguments) { + (_b = choice.message.function_call).arguments ?? (_b.arguments = ''); + choice.message.function_call.arguments += function_call.arguments; + } + } + } + if (tool_calls) { + if (!choice.message.tool_calls) + choice.message.tool_calls = []; + for (const { index, id, type, function: fn, ...rest } of tool_calls) { + const tool_call = ((_c = choice.message.tool_calls)[index] ?? (_c[index] = {})); + Object.assign(tool_call, rest); + if (id) + tool_call.id = id; + if (type) + tool_call.type = type; + if (fn) + tool_call.function ?? (tool_call.function = { arguments: '' }); + if (fn?.name) + tool_call.function.name = fn.name; + if (fn?.arguments) + tool_call.function.arguments += fn.arguments; + } + } + } + return snapshot; + }, Symbol.asyncIterator)]() { + const pushQueue = []; + const readQueue = []; + let done = false; + this.on('chunk', (chunk) => { + const reader = readQueue.shift(); + if (reader) { + reader.resolve(chunk); + } + else { + pushQueue.push(chunk); + } + }); + this.on('end', () => { + done = true; + for (const reader of readQueue) { + reader.resolve(undefined); + } + readQueue.length = 0; + }); + this.on('abort', (err) => { + done = true; + for (const reader of readQueue) { + reader.reject(err); + } + readQueue.length = 0; + }); + this.on('error', (err) => { + done = true; + for (const reader of readQueue) { + reader.reject(err); + } + readQueue.length = 0; + }); + return { + next: async () => { + if (!pushQueue.length) { + if (done) { + return { value: undefined, done: true }; + } + return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((chunk) => (chunk ? { value: chunk, done: false } : { value: undefined, done: true })); + } + const chunk = pushQueue.shift(); + return { value: chunk, done: false }; + }, + return: async () => { + this.abort(); + return { value: undefined, done: true }; + }, + }; + } + toReadableStream() { + const stream = new Stream(this[Symbol.asyncIterator].bind(this), this.controller); + return stream.toReadableStream(); + } +} +function finalizeChatCompletion(snapshot) { + const { id, choices, created, model, system_fingerprint, ...rest } = snapshot; + return { + ...rest, + id, + choices: choices.map(({ message, finish_reason, index, logprobs, ...choiceRest }) => { + if (!finish_reason) + throw new OpenAIError(`missing finish_reason for choice ${index}`); + const { content = null, function_call, tool_calls, ...messageRest } = message; + const role = message.role; // this is what we expect; in theory it could be different which would make our types a slight lie but would be fine. + if (!role) + throw new OpenAIError(`missing role for choice ${index}`); + if (function_call) { + const { arguments: args, name } = function_call; + if (args == null) + throw new OpenAIError(`missing function_call.arguments for choice ${index}`); + if (!name) + throw new OpenAIError(`missing function_call.name for choice ${index}`); + return { + ...choiceRest, + message: { content, function_call: { arguments: args, name }, role }, + finish_reason, + index, + logprobs, + }; + } + if (tool_calls) { + return { + ...choiceRest, + index, + finish_reason, + logprobs, + message: { + ...messageRest, + role, + content, + tool_calls: tool_calls.map((tool_call, i) => { + const { function: fn, type, id, ...toolRest } = tool_call; + const { arguments: args, name, ...fnRest } = fn || {}; + if (id == null) + throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].id\n${str(snapshot)}`); + if (type == null) + throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].type\n${str(snapshot)}`); + if (name == null) + throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].function.name\n${str(snapshot)}`); + if (args == null) + throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].function.arguments\n${str(snapshot)}`); + return { ...toolRest, id, type, function: { ...fnRest, name, arguments: args } }; + }), + }, + }; + } + return { + ...choiceRest, + message: { ...messageRest, content, role }, + finish_reason, + index, + logprobs, + }; + }), + created, + model, + object: 'chat.completion', + ...(system_fingerprint ? { system_fingerprint } : {}), + }; +} +function str(x) { + return JSON.stringify(x); +} +//# sourceMappingURL=ChatCompletionStream.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/lib/ChatCompletionStream.mjs.map b/backend/node_modules/openai/lib/ChatCompletionStream.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..32776dcf9a15fa3f8984e4fe1b19325a38855725 --- /dev/null +++ b/backend/node_modules/openai/lib/ChatCompletionStream.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"ChatCompletionStream.mjs","sourceRoot":"","sources":["../src/lib/ChatCompletionStream.ts"],"names":[],"mappings":";;;;;;;;;;;;OACO,EAAE,WAAW,EAAE,iBAAiB,EAAE,MAAM,cAAc;OAQtD,EACL,4BAA4B,GAE7B;OAEM,EAAE,MAAM,EAAE,MAAM,kBAAkB;AAWzC,MAAM,OAAO,oBACX,SAAQ,4BAAwD;IADlE;;;QAIE,sEAAmE;IAsPrE,CAAC;IApPC,IAAI,6BAA6B;QAC/B,OAAO,uBAAA,IAAI,2DAA+B,CAAC;IAC7C,CAAC;IAED;;;;;;OAMG;IACH,MAAM,CAAC,kBAAkB,CAAC,MAAsB;QAC9C,MAAM,MAAM,GAAG,IAAI,oBAAoB,EAAE,CAAC;QAC1C,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,mBAAmB,CAAC,MAAM,CAAC,CAAC,CAAC;QACtD,OAAO,MAAM,CAAC;IAChB,CAAC;IAED,MAAM,CAAC,oBAAoB,CACzB,WAAwB,EACxB,MAAkC,EAClC,OAA6B;QAE7B,MAAM,MAAM,GAAG,IAAI,oBAAoB,EAAE,CAAC;QAC1C,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,CACf,MAAM,CAAC,kBAAkB,CACvB,WAAW,EACX,EAAE,GAAG,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,EAC3B,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE,2BAA2B,EAAE,QAAQ,EAAE,EAAE,CACxF,CACF,CAAC;QACF,OAAO,MAAM,CAAC;IAChB,CAAC;IA4BkB,KAAK,CAAC,qBAAqB,CAC5C,WAAwB,EACxB,MAAkC,E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AAC,EAAE,kBAAkB,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KACtD,CAAC;AACJ,CAAC;AAED,SAAS,GAAG,CAAC,CAAU;IACrB,OAAO,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;AAC3B,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/openai/lib/ChatCompletionStreamingRunner.d.ts b/backend/node_modules/openai/lib/ChatCompletionStreamingRunner.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..98b53e2e15f51fb50c6a27f4500afebccf61469d --- /dev/null +++ b/backend/node_modules/openai/lib/ChatCompletionStreamingRunner.d.ts @@ -0,0 +1,22 @@ +import { Completions, type ChatCompletionChunk, type ChatCompletionCreateParamsStreaming } from 'openai/resources/chat/completions'; +import { RunnerOptions, type AbstractChatCompletionRunnerEvents } from "./AbstractChatCompletionRunner.js"; +import { type ReadableStream } from 'openai/_shims/index'; +import { RunnableTools, type BaseFunctionsArgs, type RunnableFunctions } from "./RunnableFunction.js"; +import { ChatCompletionSnapshot, ChatCompletionStream } from "./ChatCompletionStream.js"; +export interface ChatCompletionStreamEvents extends AbstractChatCompletionRunnerEvents { + content: (contentDelta: string, contentSnapshot: string) => void; + chunk: (chunk: ChatCompletionChunk, snapshot: ChatCompletionSnapshot) => void; +} +export type ChatCompletionStreamingFunctionRunnerParams = Omit & { + functions: RunnableFunctions; +}; +export type ChatCompletionStreamingToolRunnerParams = Omit & { + tools: RunnableTools; +}; +export declare class ChatCompletionStreamingRunner extends ChatCompletionStream implements AsyncIterable { + static fromReadableStream(stream: ReadableStream): ChatCompletionStreamingRunner; + /** @deprecated - please use `runTools` instead. */ + static runFunctions(completions: Completions, params: ChatCompletionStreamingFunctionRunnerParams, options?: RunnerOptions): ChatCompletionStreamingRunner; + static runTools(completions: Completions, params: ChatCompletionStreamingToolRunnerParams, options?: RunnerOptions): ChatCompletionStreamingRunner; +} +//# sourceMappingURL=ChatCompletionStreamingRunner.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/lib/ChatCompletionStreamingRunner.d.ts.map b/backend/node_modules/openai/lib/ChatCompletionStreamingRunner.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..868a35f581198c223d42ad455b8ccd869315ae2b --- /dev/null +++ b/backend/node_modules/openai/lib/ChatCompletionStreamingRunner.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ChatCompletionStreamingRunner.d.ts","sourceRoot":"","sources":["../src/lib/ChatCompletionStreamingRunner.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,WAAW,EACX,KAAK,mBAAmB,EACxB,KAAK,mCAAmC,EACzC,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAE,aAAa,EAAE,KAAK,kCAAkC,EAAE,MAAM,gCAAgC,CAAC;AACxG,OAAO,EAAE,KAAK,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAC1D,OAAO,EAAE,aAAa,EAAE,KAAK,iBAAiB,EAAE,KAAK,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACnG,OAAO,EAAE,sBAAsB,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAEtF,MAAM,WAAW,0BAA2B,SAAQ,kCAAkC;IACpF,OAAO,EAAE,CAAC,YAAY,EAAE,MAAM,EAAE,eAAe,EAAE,MAAM,KAAK,IAAI,CAAC;IACjE,KAAK,EAAE,CAAC,KAAK,EAAE,mBAAmB,EAAE,QAAQ,EAAE,sBAAsB,KAAK,IAAI,CAAC;CAC/E;AAED,MAAM,MAAM,2CAA2C,CAAC,aAAa,SAAS,iBAAiB,IAAI,IAAI,CACrG,mCAAmC,EACnC,WAAW,CACZ,GAAG;IACF,SAAS,EAAE,iBAAiB,CAAC,aAAa,CAAC,CAAC;CAC7C,CAAC;AAEF,MAAM,MAAM,uCAAuC,CAAC,aAAa,SAAS,iBAAiB,IAAI,IAAI,CACjG,mCAAmC,EACnC,OAAO,CACR,GAAG;IACF,KAAK,EAAE,aAAa,CAAC,aAAa,CAAC,CAAC;CACrC,CAAC;AAEF,qBAAa,6BACX,SAAQ,oBACR,YAAW,aAAa,CAAC,mBAAmB,CAAC;WAE7B,kBAAkB,CAAC,MAAM,EAAE,cAAc,GAAG,6BAA6B;IAMzF,mDAAmD;IACnD,MAAM,CAAC,YAAY,CAAC,CAAC,SAAS,CAAC,MAAM,GAAG,MAAM,CAAC,EAAE,EAC/C,WAAW,EAAE,WAAW,EACxB,MAAM,EAAE,2CAA2C,CAAC,CAAC,CAAC,EACtD,OAAO,CAAC,EAAE,aAAa,GACtB,6BAA6B;IAUhC,MAAM,CAAC,QAAQ,CAAC,CAAC,SAAS,CAAC,MAAM,GAAG,MAAM,CAAC,EAAE,EAC3C,WAAW,EAAE,WAAW,EACxB,MAAM,EAAE,uCAAuC,CAAC,CAAC,CAAC,EAClD,OAAO,CAAC,EAAE,aAAa,GACtB,6BAA6B;CASjC"} \ No newline at end of file diff --git a/backend/node_modules/openai/lib/ChatCompletionStreamingRunner.js b/backend/node_modules/openai/lib/ChatCompletionStreamingRunner.js new file mode 100644 index 0000000000000000000000000000000000000000..e926b27242534d827ef4b3b2ed8e9eed0335e4dd --- /dev/null +++ b/backend/node_modules/openai/lib/ChatCompletionStreamingRunner.js @@ -0,0 +1,32 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ChatCompletionStreamingRunner = void 0; +const ChatCompletionStream_1 = require("./ChatCompletionStream.js"); +class ChatCompletionStreamingRunner extends ChatCompletionStream_1.ChatCompletionStream { + static fromReadableStream(stream) { + const runner = new ChatCompletionStreamingRunner(); + runner._run(() => runner._fromReadableStream(stream)); + return runner; + } + /** @deprecated - please use `runTools` instead. */ + static runFunctions(completions, params, options) { + const runner = new ChatCompletionStreamingRunner(); + const opts = { + ...options, + headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'runFunctions' }, + }; + runner._run(() => runner._runFunctions(completions, params, opts)); + return runner; + } + static runTools(completions, params, options) { + const runner = new ChatCompletionStreamingRunner(); + const opts = { + ...options, + headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'runTools' }, + }; + runner._run(() => runner._runTools(completions, params, opts)); + return runner; + } +} +exports.ChatCompletionStreamingRunner = ChatCompletionStreamingRunner; +//# sourceMappingURL=ChatCompletionStreamingRunner.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/lib/ChatCompletionStreamingRunner.js.map b/backend/node_modules/openai/lib/ChatCompletionStreamingRunner.js.map new file mode 100644 index 0000000000000000000000000000000000000000..2f1c6eb523bbe94632a3b3a1013e44c38a16183e --- /dev/null +++ b/backend/node_modules/openai/lib/ChatCompletionStreamingRunner.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ChatCompletionStreamingRunner.js","sourceRoot":"","sources":["../src/lib/ChatCompletionStreamingRunner.ts"],"names":[],"mappings":";;;AAQA,oEAAsF;AAqBtF,MAAa,6BACX,SAAQ,2CAAoB;IAG5B,MAAM,CAAU,kBAAkB,CAAC,MAAsB;QACvD,MAAM,MAAM,GAAG,IAAI,6BAA6B,EAAE,CAAC;QACnD,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,mBAAmB,CAAC,MAAM,CAAC,CAAC,CAAC;QACtD,OAAO,MAAM,CAAC;IAChB,CAAC;IAED,mDAAmD;IACnD,MAAM,CAAC,YAAY,CACjB,WAAwB,EACxB,MAAsD,EACtD,OAAuB;QAEvB,MAAM,MAAM,GAAG,IAAI,6BAA6B,EAAE,CAAC;QACnD,MAAM,IAAI,GAAG;YACX,GAAG,OAAO;YACV,OAAO,EAAE,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE,2BAA2B,EAAE,cAAc,EAAE;SAC9E,CAAC;QACF,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,aAAa,CAAC,WAAW,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC,CAAC;QACnE,OAAO,MAAM,CAAC;IAChB,CAAC;IAED,MAAM,CAAC,QAAQ,CACb,WAAwB,EACxB,MAAkD,EAClD,OAAuB;QAEvB,MAAM,MAAM,GAAG,IAAI,6BAA6B,EAAE,CAAC;QACnD,MAAM,IAAI,GAAG;YACX,GAAG,OAAO;YACV,OAAO,EAAE,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE,2BAA2B,EAAE,UAAU,EAAE;SAC1E,CAAC;QACF,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,SAAS,CAAC,WAAW,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC,CAAC;QAC/D,OAAO,MAAM,CAAC;IAChB,CAAC;CACF;AAtCD,sEAsCC"} \ No newline at end of file diff --git a/backend/node_modules/openai/lib/ChatCompletionStreamingRunner.mjs b/backend/node_modules/openai/lib/ChatCompletionStreamingRunner.mjs new file mode 100644 index 0000000000000000000000000000000000000000..8860e662b5745f7049068e5b3a614b622f8d2b61 --- /dev/null +++ b/backend/node_modules/openai/lib/ChatCompletionStreamingRunner.mjs @@ -0,0 +1,28 @@ +import { ChatCompletionStream } from "./ChatCompletionStream.mjs"; +export class ChatCompletionStreamingRunner extends ChatCompletionStream { + static fromReadableStream(stream) { + const runner = new ChatCompletionStreamingRunner(); + runner._run(() => runner._fromReadableStream(stream)); + return runner; + } + /** @deprecated - please use `runTools` instead. */ + static runFunctions(completions, params, options) { + const runner = new ChatCompletionStreamingRunner(); + const opts = { + ...options, + headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'runFunctions' }, + }; + runner._run(() => runner._runFunctions(completions, params, opts)); + return runner; + } + static runTools(completions, params, options) { + const runner = new ChatCompletionStreamingRunner(); + const opts = { + ...options, + headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'runTools' }, + }; + runner._run(() => runner._runTools(completions, params, opts)); + return runner; + } +} +//# sourceMappingURL=ChatCompletionStreamingRunner.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/lib/ChatCompletionStreamingRunner.mjs.map b/backend/node_modules/openai/lib/ChatCompletionStreamingRunner.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..9df8909c1e9701f551fd377c29f71a49c18f9a19 --- /dev/null +++ b/backend/node_modules/openai/lib/ChatCompletionStreamingRunner.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"ChatCompletionStreamingRunner.mjs","sourceRoot":"","sources":["../src/lib/ChatCompletionStreamingRunner.ts"],"names":[],"mappings":"OAQO,EAA0B,oBAAoB,EAAE;AAqBvD,MAAM,OAAO,6BACX,SAAQ,oBAAoB;IAG5B,MAAM,CAAU,kBAAkB,CAAC,MAAsB;QACvD,MAAM,MAAM,GAAG,IAAI,6BAA6B,EAAE,CAAC;QACnD,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,mBAAmB,CAAC,MAAM,CAAC,CAAC,CAAC;QACtD,OAAO,MAAM,CAAC;IAChB,CAAC;IAED,mDAAmD;IACnD,MAAM,CAAC,YAAY,CACjB,WAAwB,EACxB,MAAsD,EACtD,OAAuB;QAEvB,MAAM,MAAM,GAAG,IAAI,6BAA6B,EAAE,CAAC;QACnD,MAAM,IAAI,GAAG;YACX,GAAG,OAAO;YACV,OAAO,EAAE,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE,2BAA2B,EAAE,cAAc,EAAE;SAC9E,CAAC;QACF,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,aAAa,CAAC,WAAW,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC,CAAC;QACnE,OAAO,MAAM,CAAC;IAChB,CAAC;IAED,MAAM,CAAC,QAAQ,CACb,WAAwB,EACxB,MAAkD,EAClD,OAAuB;QAEvB,MAAM,MAAM,GAAG,IAAI,6BAA6B,EAAE,CAAC;QACnD,MAAM,IAAI,GAAG;YACX,GAAG,OAAO;YACV,OAAO,EAAE,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE,2BAA2B,EAAE,UAAU,EAAE;SAC1E,CAAC;QACF,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,SAAS,CAAC,WAAW,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC,CAAC;QAC/D,OAAO,MAAM,CAAC;IAChB,CAAC;CACF"} \ No newline at end of file diff --git a/backend/node_modules/openai/lib/RunnableFunction.d.ts b/backend/node_modules/openai/lib/RunnableFunction.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..832560450d8d4c277494a829ebad40093fd89e66 --- /dev/null +++ b/backend/node_modules/openai/lib/RunnableFunction.d.ts @@ -0,0 +1,95 @@ +import { type ChatCompletionRunner } from "./ChatCompletionRunner.js"; +import { type ChatCompletionStreamingRunner } from "./ChatCompletionStreamingRunner.js"; +import { JSONSchema } from "./jsonschema.js"; +type PromiseOrValue = T | Promise; +export type RunnableFunctionWithParse = { + /** + * @param args the return value from `parse`. + * @param runner the runner evaluating this callback. + * @returns a string to send back to OpenAI. + */ + function: (args: Args, runner: ChatCompletionRunner | ChatCompletionStreamingRunner) => PromiseOrValue; + /** + * @param input the raw args from the OpenAI function call. + * @returns the parsed arguments to pass to `function` + */ + parse: (input: string) => PromiseOrValue; + /** + * The parameters the function accepts, describes as a JSON Schema object. + */ + parameters: JSONSchema; + /** + * A description of what the function does, used by the model to choose when and how to call the function. + */ + description: string; + /** + * The name of the function to be called. Will default to function.name if omitted. + */ + name?: string | undefined; +}; +export type RunnableFunctionWithoutParse = { + /** + * @param args the raw args from the OpenAI function call. + * @returns a string to send back to OpenAI + */ + function: (args: string, runner: ChatCompletionRunner | ChatCompletionStreamingRunner) => PromiseOrValue; + /** + * The parameters the function accepts, describes as a JSON Schema object. + */ + parameters: JSONSchema; + /** + * A description of what the function does, used by the model to choose when and how to call the function. + */ + description: string; + /** + * The name of the function to be called. Will default to function.name if omitted. + */ + name?: string | undefined; +}; +export type RunnableFunction = Args extends string ? RunnableFunctionWithoutParse : Args extends object ? RunnableFunctionWithParse : never; +export type RunnableToolFunction = Args extends string ? RunnableToolFunctionWithoutParse : Args extends object ? RunnableToolFunctionWithParse : never; +export type RunnableToolFunctionWithoutParse = { + type: 'function'; + function: RunnableFunctionWithoutParse; +}; +export type RunnableToolFunctionWithParse = { + type: 'function'; + function: RunnableFunctionWithParse; +}; +export declare function isRunnableFunctionWithParse(fn: any): fn is RunnableFunctionWithParse; +export type BaseFunctionsArgs = readonly (object | string)[]; +export type RunnableFunctions = [ + any[] +] extends [FunctionsArgs] ? readonly RunnableFunction[] : { + [Index in keyof FunctionsArgs]: Index extends number ? RunnableFunction : FunctionsArgs[Index]; +}; +export type RunnableTools = [ + any[] +] extends [FunctionsArgs] ? readonly RunnableToolFunction[] : { + [Index in keyof FunctionsArgs]: Index extends number ? RunnableToolFunction : FunctionsArgs[Index]; +}; +/** + * This is helper class for passing a `function` and `parse` where the `function` + * argument type matches the `parse` return type. + * + * @deprecated - please use ParsingToolFunction instead. + */ +export declare class ParsingFunction { + function: RunnableFunctionWithParse['function']; + parse: RunnableFunctionWithParse['parse']; + parameters: RunnableFunctionWithParse['parameters']; + description: RunnableFunctionWithParse['description']; + name?: RunnableFunctionWithParse['name']; + constructor(input: RunnableFunctionWithParse); +} +/** + * This is helper class for passing a `function` and `parse` where the `function` + * argument type matches the `parse` return type. + */ +export declare class ParsingToolFunction { + type: 'function'; + function: RunnableFunctionWithParse; + constructor(input: RunnableFunctionWithParse); +} +export {}; +//# sourceMappingURL=RunnableFunction.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/lib/RunnableFunction.d.ts.map b/backend/node_modules/openai/lib/RunnableFunction.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..2969604a2613306dea277ee11280b671745c47c8 --- /dev/null +++ b/backend/node_modules/openai/lib/RunnableFunction.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"RunnableFunction.d.ts","sourceRoot":"","sources":["../src/lib/RunnableFunction.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AACnE,OAAO,EAAE,KAAK,6BAA6B,EAAE,MAAM,iCA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KAAK,EAAE,yBAAyB,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC,CAAC;IAChD,UAAU,EAAE,yBAAyB,CAAC,IAAI,CAAC,CAAC,YAAY,CAAC,CAAC;IAC1D,WAAW,EAAE,yBAAyB,CAAC,IAAI,CAAC,CAAC,aAAa,CAAC,CAAC;IAC5D,IAAI,CAAC,EAAE,yBAAyB,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,CAAC;gBAEnC,KAAK,EAAE,yBAAyB,CAAC,IAAI,CAAC;CAOnD;AAED;;;GAGG;AACH,qBAAa,mBAAmB,CAAC,IAAI,SAAS,MAAM;IAClD,IAAI,EAAE,UAAU,CAAC;IACjB,QAAQ,EAAE,yBAAyB,CAAC,IAAI,CAAC,CAAC;gBAE9B,KAAK,EAAE,yBAAyB,CAAC,IAAI,CAAC;CAInD"} \ No newline at end of file diff --git a/backend/node_modules/openai/lib/RunnableFunction.js b/backend/node_modules/openai/lib/RunnableFunction.js new file mode 100644 index 0000000000000000000000000000000000000000..a0792692c23050a3615b42226eb9934521e31dde --- /dev/null +++ b/backend/node_modules/openai/lib/RunnableFunction.js @@ -0,0 +1,35 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ParsingToolFunction = exports.ParsingFunction = exports.isRunnableFunctionWithParse = void 0; +function isRunnableFunctionWithParse(fn) { + return typeof fn.parse === 'function'; +} +exports.isRunnableFunctionWithParse = isRunnableFunctionWithParse; +/** + * This is helper class for passing a `function` and `parse` where the `function` + * argument type matches the `parse` return type. + * + * @deprecated - please use ParsingToolFunction instead. + */ +class ParsingFunction { + constructor(input) { + this.function = input.function; + this.parse = input.parse; + this.parameters = input.parameters; + this.description = input.description; + this.name = input.name; + } +} +exports.ParsingFunction = ParsingFunction; +/** + * This is helper class for passing a `function` and `parse` where the `function` + * argument type matches the `parse` return type. + */ +class ParsingToolFunction { + constructor(input) { + this.type = 'function'; + this.function = input; + } +} +exports.ParsingToolFunction = ParsingToolFunction; +//# sourceMappingURL=RunnableFunction.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/lib/RunnableFunction.js.map b/backend/node_modules/openai/lib/RunnableFunction.js.map new file mode 100644 index 0000000000000000000000000000000000000000..df6ac8b9f0cce2757839727e82e8b3b6fa54d733 --- /dev/null +++ b/backend/node_modules/openai/lib/RunnableFunction.js.map @@ -0,0 +1 @@ +{"version":3,"file":"RunnableFunction.js","sourceRoot":"","sources":["../src/lib/RunnableFunction.ts"],"names":[],"mappings":";;;AA6EA,SAAgB,2BAA2B,CACzC,EAAO;IAEP,OAAO,OAAQ,EAAU,CAAC,KAAK,KAAK,UAAU,CAAC;AACjD,CAAC;AAJD,kEAIC;AAkBD;;;;;GAKG;AACH,MAAa,eAAe;IAO1B,YAAY,KAAsC;QAChD,IAAI,CAAC,QAAQ,GAAG,KAAK,CAAC,QAAQ,CAAC;QAC/B,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC;QACzB,IAAI,CAAC,UAAU,GAAG,KAAK,CAAC,UAAU,CAAC;QACnC,IAAI,CAAC,WAAW,GAAG,KAAK,CAAC,WAAW,CAAC;QACrC,IAAI,CAAC,IAAI,GAAG,KAAK,CAAC,IAAI,CAAC;IACzB,CAAC;CACF;AAdD,0CAcC;AAED;;;GAGG;AACH,MAAa,mBAAmB;IAI9B,YAAY,KAAsC;QAChD,IAAI,CAAC,IAAI,GAAG,UAAU,CAAC;QACvB,IAAI,CAAC,QAAQ,GAAG,KAAK,CAAC;IACxB,CAAC;CACF;AARD,kDAQC"} \ No newline at end of file diff --git a/backend/node_modules/openai/lib/RunnableFunction.mjs b/backend/node_modules/openai/lib/RunnableFunction.mjs new file mode 100644 index 0000000000000000000000000000000000000000..c9ef11324dd56f2f2b7af4209b8d28d057b45c76 --- /dev/null +++ b/backend/node_modules/openai/lib/RunnableFunction.mjs @@ -0,0 +1,29 @@ +export function isRunnableFunctionWithParse(fn) { + return typeof fn.parse === 'function'; +} +/** + * This is helper class for passing a `function` and `parse` where the `function` + * argument type matches the `parse` return type. + * + * @deprecated - please use ParsingToolFunction instead. + */ +export class ParsingFunction { + constructor(input) { + this.function = input.function; + this.parse = input.parse; + this.parameters = input.parameters; + this.description = input.description; + this.name = input.name; + } +} +/** + * This is helper class for passing a `function` and `parse` where the `function` + * argument type matches the `parse` return type. + */ +export class ParsingToolFunction { + constructor(input) { + this.type = 'function'; + this.function = input; + } +} +//# sourceMappingURL=RunnableFunction.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/lib/RunnableFunction.mjs.map b/backend/node_modules/openai/lib/RunnableFunction.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..df60b15814dc29f385f96390cdc54ed7fb7f175e --- /dev/null +++ b/backend/node_modules/openai/lib/RunnableFunction.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"RunnableFunction.mjs","sourceRoot":"","sources":["../src/lib/RunnableFunction.ts"],"names":[],"mappings":"AA6EA,MAAM,UAAU,2BAA2B,CACzC,EAAO;IAEP,OAAO,OAAQ,EAAU,CAAC,KAAK,KAAK,UAAU,CAAC;AACjD,CAAC;AAkBD;;;;;GAKG;AACH,MAAM,OAAO,eAAe;IAO1B,YAAY,KAAsC;QAChD,IAAI,CAAC,QAAQ,GAAG,KAAK,CAAC,QAAQ,CAAC;QAC/B,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC;QACzB,IAAI,CAAC,UAAU,GAAG,KAAK,CAAC,UAAU,CAAC;QACnC,IAAI,CAAC,WAAW,GAAG,KAAK,CAAC,WAAW,CAAC;QACrC,IAAI,CAAC,IAAI,GAAG,KAAK,CAAC,IAAI,CAAC;IACzB,CAAC;CACF;AAED;;;GAGG;AACH,MAAM,OAAO,mBAAmB;IAI9B,YAAY,KAAsC;QAChD,IAAI,CAAC,IAAI,GAAG,UAAU,CAAC;QACvB,IAAI,CAAC,QAAQ,GAAG,KAAK,CAAC;IACxB,CAAC;CACF"} \ No newline at end of file diff --git a/backend/node_modules/openai/lib/chatCompletionUtils.d.ts b/backend/node_modules/openai/lib/chatCompletionUtils.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fcc1b3dee1729c0439f200e69dfb5a402a5bacad --- /dev/null +++ b/backend/node_modules/openai/lib/chatCompletionUtils.d.ts @@ -0,0 +1,6 @@ +import { type ChatCompletionAssistantMessageParam, type ChatCompletionFunctionMessageParam, type ChatCompletionMessageParam, type ChatCompletionToolMessageParam } from 'openai/resources'; +export declare const isAssistantMessage: (message: ChatCompletionMessageParam | null | undefined) => message is ChatCompletionAssistantMessageParam; +export declare const isFunctionMessage: (message: ChatCompletionMessageParam | null | undefined) => message is ChatCompletionFunctionMessageParam; +export declare const isToolMessage: (message: ChatCompletionMessageParam | null | undefined) => message is ChatCompletionToolMessageParam; +export declare function isPresent(obj: T | null | undefined): obj is T; +//# sourceMappingURL=chatCompletionUtils.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/lib/chatCompletionUtils.d.ts.map b/backend/node_modules/openai/lib/chatCompletionUtils.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..62b23b329e9a2b20e9c66e2d336e2f45bcc29440 --- /dev/null +++ b/backend/node_modules/openai/lib/chatCompletionUtils.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"chatCompletionUtils.d.ts","sourceRoot":"","sources":["../src/lib/chatCompletionUtils.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,mCAAmC,EACxC,KAAK,kCAAkC,EACvC,KAAK,0BAA0B,EAC/B,KAAK,8BAA8B,EACpC,MAAM,kBAAkB,CAAC;AAE1B,eAAO,MAAM,kBAAkB,YACpB,0BAA0B,GAAG,IAAI,GAAG,SAAS,mDAGvD,CAAC;AAEF,eAAO,MAAM,iBAAiB,YACnB,0BAA0B,GAAG,IAAI,GAAG,SAAS,kDAGvD,CAAC;AAEF,eAAO,MAAM,aAAa,YACf,0BAA0B,GAAG,IAAI,GAAG,SAAS,8CAGvD,CAAC;AAEF,wBAAgB,SAAS,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,GAAG,IAAI,GAAG,SAAS,GAAG,GAAG,IAAI,CAAC,CAEhE"} \ No newline at end of file diff --git a/backend/node_modules/openai/lib/chatCompletionUtils.js b/backend/node_modules/openai/lib/chatCompletionUtils.js new file mode 100644 index 0000000000000000000000000000000000000000..911545f02613572754028ae63555dcbdfda2c67e --- /dev/null +++ b/backend/node_modules/openai/lib/chatCompletionUtils.js @@ -0,0 +1,20 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isPresent = exports.isToolMessage = exports.isFunctionMessage = exports.isAssistantMessage = void 0; +const isAssistantMessage = (message) => { + return message?.role === 'assistant'; +}; +exports.isAssistantMessage = isAssistantMessage; +const isFunctionMessage = (message) => { + return message?.role === 'function'; +}; +exports.isFunctionMessage = isFunctionMessage; +const isToolMessage = (message) => { + return message?.role === 'tool'; +}; +exports.isToolMessage = isToolMessage; +function isPresent(obj) { + return obj != null; +} +exports.isPresent = isPresent; +//# sourceMappingURL=chatCompletionUtils.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/lib/chatCompletionUtils.js.map b/backend/node_modules/openai/lib/chatCompletionUtils.js.map new file mode 100644 index 0000000000000000000000000000000000000000..574356f45af5899ad4690e02e05c4bc4e40a738a --- /dev/null +++ b/backend/node_modules/openai/lib/chatCompletionUtils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"chatCompletionUtils.js","sourceRoot":"","sources":["../src/lib/chatCompletionUtils.ts"],"names":[],"mappings":";;;AAOO,MAAM,kBAAkB,GAAG,CAChC,OAAsD,EACN,EAAE;IAClD,OAAO,OAAO,EAAE,IAAI,KAAK,WAAW,CAAC;AACvC,CAAC,CAAC;AAJW,QAAA,kBAAkB,sBAI7B;AAEK,MAAM,iBAAiB,GAAG,CAC/B,OAAsD,EACP,EAAE;IACjD,OAAO,OAAO,EAAE,IAAI,KAAK,UAAU,CAAC;AACtC,CAAC,CAAC;AAJW,QAAA,iBAAiB,qBAI5B;AAEK,MAAM,aAAa,GAAG,CAC3B,OAAsD,EACX,EAAE;IAC7C,OAAO,OAAO,EAAE,IAAI,KAAK,MAAM,CAAC;AAClC,CAAC,CAAC;AAJW,QAAA,aAAa,iBAIxB;AAEF,SAAgB,SAAS,CAAI,GAAyB;IACpD,OAAO,GAAG,IAAI,IAAI,CAAC;AACrB,CAAC;AAFD,8BAEC"} \ No newline at end of file diff --git a/backend/node_modules/openai/lib/chatCompletionUtils.mjs b/backend/node_modules/openai/lib/chatCompletionUtils.mjs new file mode 100644 index 0000000000000000000000000000000000000000..b28342918554974867ccdc939f54a7d88af7f676 --- /dev/null +++ b/backend/node_modules/openai/lib/chatCompletionUtils.mjs @@ -0,0 +1,13 @@ +export const isAssistantMessage = (message) => { + return message?.role === 'assistant'; +}; +export const isFunctionMessage = (message) => { + return message?.role === 'function'; +}; +export const isToolMessage = (message) => { + return message?.role === 'tool'; +}; +export function isPresent(obj) { + return obj != null; +} +//# sourceMappingURL=chatCompletionUtils.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/lib/chatCompletionUtils.mjs.map b/backend/node_modules/openai/lib/chatCompletionUtils.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..00e60f662b766c34f113312819de307ba986400f --- /dev/null +++ b/backend/node_modules/openai/lib/chatCompletionUtils.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"chatCompletionUtils.mjs","sourceRoot":"","sources":["../src/lib/chatCompletionUtils.ts"],"names":[],"mappings":"AAOA,MAAM,CAAC,MAAM,kBAAkB,GAAG,CAChC,OAAsD,EACN,EAAE;IAClD,OAAO,OAAO,EAAE,IAAI,KAAK,WAAW,CAAC;AACvC,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAC/B,OAAsD,EACP,EAAE;IACjD,OAAO,OAAO,EAAE,IAAI,KAAK,UAAU,CAAC;AACtC,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,aAAa,GAAG,CAC3B,OAAsD,EACX,EAAE;IAC7C,OAAO,OAAO,EAAE,IAAI,KAAK,MAAM,CAAC;AAClC,CAAC,CAAC;AAEF,MAAM,UAAU,SAAS,CAAI,GAAyB;IACpD,OAAO,GAAG,IAAI,IAAI,CAAC;AACrB,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/openai/lib/jsonschema.d.ts b/backend/node_modules/openai/lib/jsonschema.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0a569e988ccd6a70cf18e659d3410ef0a2160ffc --- /dev/null +++ b/backend/node_modules/openai/lib/jsonschema.d.ts @@ -0,0 +1,106 @@ +/** + * Primitive type + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.1.1 + */ +export type JSONSchemaTypeName = ({} & string) | 'string' | 'number' | 'integer' | 'boolean' | 'object' | 'array' | 'null'; +/** + * Primitive type + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.1.1 + */ +export type JSONSchemaType = string | number | boolean | JSONSchemaObject | JSONSchemaArray | null; +export interface JSONSchemaObject { + [key: string]: JSONSchemaType; +} +export interface JSONSchemaArray extends Array { +} +/** + * Meta schema + * + * Recommended values: + * - 'http://json-schema.org/schema#' + * - 'http://json-schema.org/hyper-schema#' + * - 'http://json-schema.org/draft-07/schema#' + * - 'http://json-schema.org/draft-07/hyper-schema#' + * + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-5 + */ +export type JSONSchemaVersion = string; +/** + * JSON Schema v7 + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01 + */ +export type JSONSchemaDefinition = JSONSchema | boolean; +export interface JSONSchema { + $id?: string | undefined; + $comment?: string | undefined; + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.1 + */ + type?: JSONSchemaTypeName | JSONSchemaTypeName[] | undefined; + enum?: JSONSchemaType[] | undefined; + const?: JSONSchemaType | undefined; + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.2 + */ + multipleOf?: number | undefined; + maximum?: number | undefined; + exclusiveMaximum?: number | undefined; + minimum?: number | undefined; + exclusiveMinimum?: number | undefined; + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.3 + */ + maxLength?: number | undefined; + minLength?: number | undefined; + pattern?: string | undefined; + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.4 + */ + items?: JSONSchemaDefinition | JSONSchemaDefinition[] | undefined; + additionalItems?: JSONSchemaDefinition | undefined; + maxItems?: number | undefined; + minItems?: number | undefined; + uniqueItems?: boolean | undefined; + contains?: JSONSchemaDefinition | undefined; + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.5 + */ + maxProperties?: number | undefined; + minProperties?: number | undefined; + required?: string[] | undefined; + properties?: { + [key: string]: JSONSchemaDefinition; + } | undefined; + patternProperties?: { + [key: string]: JSONSchemaDefinition; + } | undefined; + additionalProperties?: JSONSchemaDefinition | undefined; + propertyNames?: JSONSchemaDefinition | undefined; + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.6 + */ + if?: JSONSchemaDefinition | undefined; + then?: JSONSchemaDefinition | undefined; + else?: JSONSchemaDefinition | undefined; + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.7 + */ + allOf?: JSONSchemaDefinition[] | undefined; + anyOf?: JSONSchemaDefinition[] | undefined; + oneOf?: JSONSchemaDefinition[] | undefined; + not?: JSONSchemaDefinition | undefined; + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-7 + */ + format?: string | undefined; + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-10 + */ + title?: string | undefined; + description?: string | undefined; + default?: JSONSchemaType | undefined; + readOnly?: boolean | undefined; + writeOnly?: boolean | undefined; + examples?: JSONSchemaType | undefined; +} +//# sourceMappingURL=jsonschema.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/lib/jsonschema.d.ts.map b/backend/node_modules/openai/lib/jsonschema.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..6e5c62320e76bfd2bb89d1ac464717d649f69848 --- /dev/null +++ b/backend/node_modules/openai/lib/jsonschema.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"jsonschema.d.ts","sourceRoot":"","sources":["../src/lib/jsonschema.ts"],"names":[],"mappings":"AASA;;;GAGG;AACH,MAAM,MAAM,kBAAkB,GAC1B,CAAC,EAAE,GAAG,MAAM,CAAC,GACb,QAAQ,GACR,QAAQ,GACR,SAAS,GACT,SAAS,GACT,QAAQ,GACR,OAAO,GACP,MAAM,CAAC;AAEX;;;GAGG;AACH,MAAM,MAAM,cAAc,GACtB,MAAM,GACN,MAAM,GACN,OAAO,GACP,gBAAgB,GAChB,eAAe,GACf,IAAI,CAAC;AAGT,MAAM,WAAW,gBAAgB;IAC/B,CAAC,GAAG,EAAE,MAAM,GAAG,cAAc,CAAC;CAC/B;AAID,MAAM,WAAW,eAAgB,SAAQ,KAAK,CAAC,cAAc,CAAC;CAAG;AAEjE;;;;;;;;;;GAUG;AACH,MAAM,MAAM,iBAAiB,GAAG,MAAM,CAAC;AAEvC;;;GAGG;AACH,MAAM,MAAM,oBAAoB,GAAG,UAAU,GAAG,OAAO,CAAC;AACxD,MAAM,WAAW,UAAU;IACzB,GAAG,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IACzB,QAAQ,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAE9B;;OAEG;IACH,IAAI,CAAC,EAAE,kBAAkB,GAAG,kBAAkB,EAAE,GAAG,SAAS,CAAC;IAC7D,IAAI,CAAC,EAAE,cAAc,EAAE,GAAG,SAAS,CAAC;IACpC,KAAK,CAAC,EAAE,cAAc,GAAG,SAAS,CAAC;IAEnC;;OAEG;IACH,UAAU,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAChC,OAAO,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAC7B,gBAAgB,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IACtC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KAAK,CAAC,EAAE,oBAAoB,EAAE,GAAG,SAAS,CAAC;IAC3C,KAAK,CAAC,EAAE,oBAAoB,EAAE,GAAG,SAAS,CAAC;IAC3C,KAAK,CAAC,EAAE,oBAAoB,EAAE,GAAG,SAAS,CAAC;IAC3C,GAAG,CAAC,EAAE,oBAAoB,GAAG,SAAS,CAAC;IAEvC;;OAEG;IACH,MAAM,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAE5B;;OAEG;IACH,KAAK,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAC3B,WAAW,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IACjC,OAAO,CAAC,EAAE,cAAc,GAAG,SAAS,CAAC;IACrC,QAAQ,CAAC,EAAE,OAAO,GAAG,SAAS,CAAC;IAC/B,SAAS,CAAC,EAAE,OAAO,GAAG,SAAS,CAAC;IAChC,QAAQ,CAAC,EAAE,cAAc,GAAG,SAAS,CAAC;CACvC"} \ No newline at end of file diff --git a/backend/node_modules/openai/lib/jsonschema.js b/backend/node_modules/openai/lib/jsonschema.js new file mode 100644 index 0000000000000000000000000000000000000000..bf2a34ee44823c32fb7b0920d0560672d50b8c21 --- /dev/null +++ b/backend/node_modules/openai/lib/jsonschema.js @@ -0,0 +1,11 @@ +"use strict"; +// File mostly copied from @types/json-schema, but stripped down a bit for brevity +// https://github.com/DefinitelyTyped/DefinitelyTyped/blob/817274f3280152ba2929a6067c93df8b34c4c9aa/types/json-schema/index.d.ts +// +// ================================================================================================== +// JSON Schema Draft 07 +// ================================================================================================== +// https://tools.ietf.org/html/draft-handrews-json-schema-validation-01 +// -------------------------------------------------------------------------------------------------- +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=jsonschema.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/lib/jsonschema.js.map b/backend/node_modules/openai/lib/jsonschema.js.map new file mode 100644 index 0000000000000000000000000000000000000000..30d08a7f5061e96fe4bb3ea72ce44e108a419e38 --- /dev/null +++ b/backend/node_modules/openai/lib/jsonschema.js.map @@ -0,0 +1 @@ +{"version":3,"file":"jsonschema.js","sourceRoot":"","sources":["../src/lib/jsonschema.ts"],"names":[],"mappings":";AAAA,kFAAkF;AAClF,gIAAgI;AAChI,EAAE;AACF,qGAAqG;AACrG,uBAAuB;AACvB,qGAAqG;AACrG,uEAAuE;AACvE,qGAAqG"} \ No newline at end of file diff --git a/backend/node_modules/openai/lib/jsonschema.mjs b/backend/node_modules/openai/lib/jsonschema.mjs new file mode 100644 index 0000000000000000000000000000000000000000..047481bc9fa71e2139df2d7ea80f0b01268c9428 --- /dev/null +++ b/backend/node_modules/openai/lib/jsonschema.mjs @@ -0,0 +1,10 @@ +// File mostly copied from @types/json-schema, but stripped down a bit for brevity +// https://github.com/DefinitelyTyped/DefinitelyTyped/blob/817274f3280152ba2929a6067c93df8b34c4c9aa/types/json-schema/index.d.ts +// +// ================================================================================================== +// JSON Schema Draft 07 +// ================================================================================================== +// https://tools.ietf.org/html/draft-handrews-json-schema-validation-01 +// -------------------------------------------------------------------------------------------------- +export {}; +//# sourceMappingURL=jsonschema.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/lib/jsonschema.mjs.map b/backend/node_modules/openai/lib/jsonschema.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..4603e805e95e94107a60537c2b2f92f8431f732d --- /dev/null +++ b/backend/node_modules/openai/lib/jsonschema.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"jsonschema.mjs","sourceRoot":"","sources":["../src/lib/jsonschema.ts"],"names":[],"mappings":"AAAA,kFAAkF;AAClF,gIAAgI;AAChI,EAAE;AACF,qGAAqG;AACrG,uBAAuB;AACvB,qGAAqG;AACrG,uEAAuE;AACvE,qGAAqG"} \ No newline at end of file diff --git a/backend/node_modules/openai/package.json b/backend/node_modules/openai/package.json new file mode 100644 index 0000000000000000000000000000000000000000..fc7967eb58157b8147fdf727ab5e9bd60242083b --- /dev/null +++ b/backend/node_modules/openai/package.json @@ -0,0 +1,105 @@ +{ + "name": "openai", + "version": "4.35.0", + "description": "The official TypeScript library for the OpenAI API", + "author": "OpenAI ", + "types": "./index.d.ts", + "main": "./index.js", + "type": "commonjs", + "repository": "github:openai/openai-node", + "license": "Apache-2.0", + "packageManager": "yarn@1.22.22", + "files": [ + "*" + ], + "private": false, + "scripts": { + "test": "bin/check-test-server && yarn jest", + "build": "bash ./build", + "format": "prettier --write --cache --cache-strategy metadata . !dist", + "tsn": "ts-node -r tsconfig-paths/register", + "lint": "eslint --ext ts,js .", + "fix": "eslint --fix --ext ts,js ." + }, + "dependencies": { + "@types/node": "^18.11.18", + "@types/node-fetch": "^2.6.4", + "abort-controller": "^3.0.0", + "agentkeepalive": "^4.2.1", + "form-data-encoder": "1.7.2", + "formdata-node": "^4.3.2", + "node-fetch": "^2.6.7", + "web-streams-polyfill": "^3.2.1" + }, + "sideEffects": [ + "./_shims/index.js", + "./_shims/index.mjs", + "./shims/node.js", + "./shims/node.mjs", + "./shims/web.js", + "./shims/web.mjs" + ], + "imports": { + "openai": ".", + "openai/*": "./src/*" + }, + "exports": { + "./_shims/auto/*": { + "deno": { + "types": "./_shims/auto/*.d.ts", + "require": "./_shims/auto/*.js", + "default": "./_shims/auto/*.mjs" + }, + "bun": { + "types": "./_shims/auto/*.d.ts", + "require": "./_shims/auto/*-bun.js", + "default": "./_shims/auto/*-bun.mjs" + }, + "browser": { + "types": "./_shims/auto/*.d.ts", + "require": "./_shims/auto/*.js", + "default": "./_shims/auto/*.mjs" + }, + "worker": { + "types": "./_shims/auto/*.d.ts", + "require": "./_shims/auto/*.js", + "default": "./_shims/auto/*.mjs" + }, + "workerd": { + "types": "./_shims/auto/*.d.ts", + "require": "./_shims/auto/*.js", + "default": "./_shims/auto/*.mjs" + }, + "node": { + "types": "./_shims/auto/*-node.d.ts", + "require": "./_shims/auto/*-node.js", + "default": "./_shims/auto/*-node.mjs" + }, + "types": "./_shims/auto/*.d.ts", + "require": "./_shims/auto/*.js", + "default": "./_shims/auto/*.mjs" + }, + ".": { + "require": { + "types": "./index.d.ts", + "default": "./index.js" + }, + "types": "./index.d.mts", + "default": "./index.mjs" + }, + "./*.mjs": { + "types": "./*.d.ts", + "default": "./*.mjs" + }, + "./*.js": { + "types": "./*.d.ts", + "default": "./*.js" + }, + "./*": { + "types": "./*.d.ts", + "require": "./*.js", + "default": "./*.mjs" + } + }, + "bin": "./bin/cli" +} diff --git a/backend/node_modules/openai/pagination.d.ts b/backend/node_modules/openai/pagination.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b320a14a010a3bce1e86003890efbd1dacdf5539 --- /dev/null +++ b/backend/node_modules/openai/pagination.d.ts @@ -0,0 +1,37 @@ +import { AbstractPage, Response, APIClient, FinalRequestOptions, PageInfo } from "./core.js"; +export interface PageResponse { + data: Array; + object: string; +} +/** + * Note: no pagination actually occurs yet, this is for forwards-compatibility. + */ +export declare class Page extends AbstractPage implements PageResponse { + data: Array; + object: string; + constructor(client: APIClient, response: Response, body: PageResponse, options: FinalRequestOptions); + getPaginatedItems(): Item[]; + /** + * This page represents a response that isn't actually paginated at the API level + * so there will never be any next page params. + */ + nextPageParams(): null; + nextPageInfo(): null; +} +export interface CursorPageResponse { + data: Array; +} +export interface CursorPageParams { + after?: string; + limit?: number; +} +export declare class CursorPage extends AbstractPage implements CursorPageResponse { + data: Array; + constructor(client: APIClient, response: Response, body: CursorPageResponse, options: FinalRequestOptions); + getPaginatedItems(): Item[]; + nextPageParams(): Partial | null; + nextPageInfo(): PageInfo | null; +} +//# sourceMappingURL=pagination.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/pagination.d.ts.map b/backend/node_modules/openai/pagination.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..b7512d1ee42750b3b47ef92bac6feb02679388fe --- /dev/null +++ b/backend/node_modules/openai/pagination.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"pagination.d.ts","sourceRoot":"","sources":["src/pagination.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,YA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IAAI,QAAQ,GAAG,IAAI;CAahC"} \ No newline at end of file diff --git a/backend/node_modules/openai/pagination.js b/backend/node_modules/openai/pagination.js new file mode 100644 index 0000000000000000000000000000000000000000..d5978798dd83f4e2e3ddf2b2d55a6cff3e962168 --- /dev/null +++ b/backend/node_modules/openai/pagination.js @@ -0,0 +1,64 @@ +"use strict"; +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CursorPage = exports.Page = void 0; +const core_1 = require("./core.js"); +/** + * Note: no pagination actually occurs yet, this is for forwards-compatibility. + */ +class Page extends core_1.AbstractPage { + constructor(client, response, body, options) { + super(client, response, body, options); + this.data = body.data || []; + this.object = body.object; + } + getPaginatedItems() { + return this.data ?? []; + } + // @deprecated Please use `nextPageInfo()` instead + /** + * This page represents a response that isn't actually paginated at the API level + * so there will never be any next page params. + */ + nextPageParams() { + return null; + } + nextPageInfo() { + return null; + } +} +exports.Page = Page; +class CursorPage extends core_1.AbstractPage { + constructor(client, response, body, options) { + super(client, response, body, options); + this.data = body.data || []; + } + getPaginatedItems() { + return this.data ?? []; + } + // @deprecated Please use `nextPageInfo()` instead + nextPageParams() { + const info = this.nextPageInfo(); + if (!info) + return null; + if ('params' in info) + return info.params; + const params = Object.fromEntries(info.url.searchParams); + if (!Object.keys(params).length) + return null; + return params; + } + nextPageInfo() { + const data = this.getPaginatedItems(); + if (!data.length) { + return null; + } + const id = data[data.length - 1]?.id; + if (!id) { + return null; + } + return { params: { after: id } }; + } +} +exports.CursorPage = CursorPage; +//# sourceMappingURL=pagination.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/pagination.js.map b/backend/node_modules/openai/pagination.js.map new file mode 100644 index 0000000000000000000000000000000000000000..dbc1787c69fd9e766cae937d67ca075511fe0dd5 --- /dev/null +++ b/backend/node_modules/openai/pagination.js.map @@ -0,0 +1 @@ +{"version":3,"file":"pagination.js","sourceRoot":"","sources":["src/pagination.ts"],"names":[],"mappings":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;YAAE,OAAO,IAAI,CAAC;QAC7C,OAAO,MAAM,CAAC;IAChB,CAAC;IAED,YAAY;QACV,MAAM,IAAI,GAAG,IAAI,CAAC,iBAAiB,EAAE,CAAC;QACtC,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE;YAChB,OAAO,IAAI,CAAC;SACb;QAED,MAAM,EAAE,GAAG,IAAI,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,EAAE,EAAE,CAAC;QACrC,IAAI,CAAC,EAAE,EAAE;YACP,OAAO,IAAI,CAAC;SACb;QAED,OAAO,EAAE,MAAM,EAAE,EAAE,KAAK,EAAE,EAAE,EAAE,EAAE,CAAC;IACnC,CAAC;CACF;AA5CD,gCA4CC"} \ No newline at end of file diff --git a/backend/node_modules/openai/pagination.mjs b/backend/node_modules/openai/pagination.mjs new file mode 100644 index 0000000000000000000000000000000000000000..bbacf0fa746e2ccb6521bc91d8a2ca3e0bb072f4 --- /dev/null +++ b/backend/node_modules/openai/pagination.mjs @@ -0,0 +1,59 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +import { AbstractPage } from "./core.mjs"; +/** + * Note: no pagination actually occurs yet, this is for forwards-compatibility. + */ +export class Page extends AbstractPage { + constructor(client, response, body, options) { + super(client, response, body, options); + this.data = body.data || []; + this.object = body.object; + } + getPaginatedItems() { + return this.data ?? []; + } + // @deprecated Please use `nextPageInfo()` instead + /** + * This page represents a response that isn't actually paginated at the API level + * so there will never be any next page params. + */ + nextPageParams() { + return null; + } + nextPageInfo() { + return null; + } +} +export class CursorPage extends AbstractPage { + constructor(client, response, body, options) { + super(client, response, body, options); + this.data = body.data || []; + } + getPaginatedItems() { + return this.data ?? []; + } + // @deprecated Please use `nextPageInfo()` instead + nextPageParams() { + const info = this.nextPageInfo(); + if (!info) + return null; + if ('params' in info) + return info.params; + const params = Object.fromEntries(info.url.searchParams); + if (!Object.keys(params).length) + return null; + return params; + } + nextPageInfo() { + const data = this.getPaginatedItems(); + if (!data.length) { + return null; + } + const id = data[data.length - 1]?.id; + if (!id) { + return null; + } + return { params: { after: id } }; + } +} +//# sourceMappingURL=pagination.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/pagination.mjs.map b/backend/node_modules/openai/pagination.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..352ce1ba4b63f5955eb22e602dbf4aac1b539ebd --- /dev/null +++ b/backend/node_modules/openai/pagination.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"pagination.mjs","sourceRoot":"","sources":["src/pagination.ts"],"names":[],"mappings":"AAAA,sFAAsF;OAE/E,EAAE,YAAY,EAAsD;AAQ3E;;GAEG;AACH,MAAM,OAAO,IAAW,SAAQ,YAAkB;IAKhD,YAAY,MAAiB,EAAE,QAAkB,EAAE,IAAwB,EAAE,OAA4B;QACvG,KAAK,CAAC,MAAM,EAAE,QAAQ,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC;QAEvC,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,IAAI,EAAE,CAAC;QAC5B,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC;IAC5B,CAAC;IAED,iBAAiB;QACf,OAAO,IAAI,CAAC,IAAI,IAAI,EAAE,CAAC;IACzB,CAAC;IAED,kDAAkD;IAClD;;;OAGG;IACH,cAAc;QACZ,OAAO,IAAI,CAAC;IACd,CAAC;IAED,YAAY;QACV,OAAO,IAAI,CAAC;IACd,CAAC;CACF;AAYD,MAAM,OAAO,UACX,SAAQ,YAAkB;IAK1B,YACE,MAAiB,EACjB,QAAkB,EAClB,IAA8B,EAC9B,OAA4B;QAE5B,KAAK,CAAC,MAAM,EAAE,QAAQ,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC;QAEvC,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,IAAI,EAAE,CAAC;IAC9B,CAAC;IAED,iBAAiB;QACf,OAAO,IAAI,CAAC,IAAI,IAAI,EAAE,CAAC;IACzB,CAAC;IAED,kDAAkD;IAClD,cAAc;QACZ,MAAM,IAAI,GAAG,IAAI,CAAC,YAAY,EAAE,CAAC;QACjC,IAAI,CAAC,IAAI;YAAE,OAAO,IAAI,CAAC;QACvB,IAAI,QAAQ,IAAI,IAAI;YAAE,OAAO,IAAI,CAAC,MAAM,CAAC;QACzC,MAAM,MAAM,GAAG,MAAM,CAAC,WAAW,CAAC,IAAI,CAAC,GAAG,CAAC,YAAY,CAAC,CAAC;QACzD,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,MAAM;YAAE,OAAO,IAAI,CAAC;QAC7C,OAAO,MAAM,CAAC;IAChB,CAAC;IAED,YAAY;QACV,MAAM,IAAI,GAAG,IAAI,CAAC,iBAAiB,EAAE,CAAC;QACtC,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE;YAChB,OAAO,IAAI,CAAC;SACb;QAED,MAAM,EAAE,GAAG,IAAI,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,EAAE,EAAE,CAAC;QACrC,IAAI,CAAC,EAAE,EAAE;YACP,OAAO,IAAI,CAAC;SACb;QAED,OAAO,EAAE,MAAM,EAAE,EAAE,KAAK,EAAE,EAAE,EAAE,EAAE,CAAC;IACnC,CAAC;CACF"} \ No newline at end of file diff --git a/backend/node_modules/openai/resource.d.ts b/backend/node_modules/openai/resource.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c20cf1047765b53cad9e1c16fdd4c9ae87281199 --- /dev/null +++ b/backend/node_modules/openai/resource.d.ts @@ -0,0 +1,6 @@ +import type { OpenAI } from "./index.js"; +export declare class APIResource { + protected _client: OpenAI; + constructor(client: OpenAI); +} +//# sourceMappingURL=resource.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/resource.d.ts.map b/backend/node_modules/openai/resource.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..7441ff7ca9b546852e65bdd739f995ae1490414c --- /dev/null +++ b/backend/node_modules/openai/resource.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"resource.d.ts","sourceRoot":"","sources":["src/resource.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AAEtC,qBAAa,WAAW;IACtB,SAAS,CAAC,OAAO,EAAE,MAAM,CAAC;gBAEd,MAAM,EAAE,MAAM;CAG3B"} \ No newline at end of file diff --git a/backend/node_modules/openai/resource.js b/backend/node_modules/openai/resource.js new file mode 100644 index 0000000000000000000000000000000000000000..edccb482a6fd3bebc374ba12133cef050cf02704 --- /dev/null +++ b/backend/node_modules/openai/resource.js @@ -0,0 +1,11 @@ +"use strict"; +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.APIResource = void 0; +class APIResource { + constructor(client) { + this._client = client; + } +} +exports.APIResource = APIResource; +//# sourceMappingURL=resource.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/resource.js.map b/backend/node_modules/openai/resource.js.map new file mode 100644 index 0000000000000000000000000000000000000000..537778de564e8c544d00194dcd6e96733a6a0d72 --- /dev/null +++ b/backend/node_modules/openai/resource.js.map @@ -0,0 +1 @@ +{"version":3,"file":"resource.js","sourceRoot":"","sources":["src/resource.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;AAItF,MAAa,WAAW;IAGtB,YAAY,MAAc;QACxB,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC;IACxB,CAAC;CACF;AAND,kCAMC"} \ No newline at end of file diff --git a/backend/node_modules/openai/resource.mjs b/backend/node_modules/openai/resource.mjs new file mode 100644 index 0000000000000000000000000000000000000000..98ee0dc70a7b08c430bbc459f342952753844668 --- /dev/null +++ b/backend/node_modules/openai/resource.mjs @@ -0,0 +1,7 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +export class APIResource { + constructor(client) { + this._client = client; + } +} +//# sourceMappingURL=resource.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/resource.mjs.map b/backend/node_modules/openai/resource.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..05061fc81e6daa802ed675387370c073545dd6fa --- /dev/null +++ b/backend/node_modules/openai/resource.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"resource.mjs","sourceRoot":"","sources":["src/resource.ts"],"names":[],"mappings":"AAAA,sFAAsF;AAItF,MAAM,OAAO,WAAW;IAGtB,YAAY,MAAc;QACxB,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC;IACxB,CAAC;CACF"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/audio/audio.d.ts b/backend/node_modules/openai/resources/audio/audio.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0e923443c7c6252ca4eade7ad41b9af8768268e8 --- /dev/null +++ b/backend/node_modules/openai/resources/audio/audio.d.ts @@ -0,0 +1,20 @@ +import { APIResource } from 'openai/resource'; +import * as SpeechAPI from 'openai/resources/audio/speech'; +import * as TranscriptionsAPI from 'openai/resources/audio/transcriptions'; +import * as TranslationsAPI from 'openai/resources/audio/translations'; +export declare class Audio extends APIResource { + transcriptions: TranscriptionsAPI.Transcriptions; + translations: TranslationsAPI.Translations; + speech: SpeechAPI.Speech; +} +export declare namespace Audio { + export import Transcriptions = TranscriptionsAPI.Transcriptions; + export import Transcription = TranscriptionsAPI.Transcription; + export import TranscriptionCreateParams = TranscriptionsAPI.TranscriptionCreateParams; + export import Translations = TranslationsAPI.Translations; + export import Translation = TranslationsAPI.Translation; + export import TranslationCreateParams = TranslationsAPI.TranslationCreateParams; + export import Speech = SpeechAPI.Speech; + export import SpeechCreateParams = SpeechAPI.SpeechCreateParams; +} +//# sourceMappingURL=audio.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/audio/audio.d.ts.map b/backend/node_modules/openai/resources/audio/audio.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..46a8fc85266c9189ddca7f2d92e75c8dfcbcaee7 --- /dev/null +++ b/backend/node_modules/openai/resources/audio/audio.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"audio.d.ts","sourceRoot":"","sources":["../../src/resources/audio/audio.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAC9C,OAAO,KAAK,SAAS,MAAM,+BAA+B,CAAC;AAC3D,OAAO,KAAK,iBAAiB,MAAM,uCAAuC,CAAC;AAC3E,OAAO,KAAK,eAAe,MAAM,qCAAqC,CAAC;AAEvE,qBAAa,KAAM,SAAQ,WAAW;IACpC,cAAc,EAAE,iBAAiB,CAAC,cAAc,CAAsD;IACtG,YAAY,EAAE,eAAe,CAAC,YAAY,CAAkD;IAC5F,MAAM,EAAE,SAAS,CAAC,MAAM,CAAsC;CAC/D;AAED,yBAAiB,KAAK,CAAC;IACrB,MAAM,QAAQ,cAAc,GAAG,iBAAiB,CAAC,cAAc,CAAC;IAChE,MAAM,QAAQ,aAAa,GAAG,iBAAiB,CAAC,aAAa,CAAC;IAC9D,MAAM,QAAQ,yBAAyB,GAAG,iBAAiB,CAAC,yBAAyB,CAAC;IACtF,MAAM,QAAQ,YAAY,GAAG,eAAe,CAAC,YAAY,CAAC;IAC1D,MAAM,QAAQ,WAAW,GAAG,eAAe,CAAC,WAAW,CAAC;IACxD,MAAM,QAAQ,uBAAuB,GAAG,eAAe,CAAC,uBAAuB,CAAC;IAChF,MAAM,QAAQ,MAAM,GAAG,SAAS,CAAC,MAAM,CAAC;IACxC,MAAM,QAAQ,kBAAkB,GAAG,SAAS,CAAC,kBAAkB,CAAC;CACjE"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/audio/audio.js b/backend/node_modules/openai/resources/audio/audio.js new file mode 100644 index 0000000000000000000000000000000000000000..974b84259f38aa4829877a84e97ff64856c9eec1 --- /dev/null +++ b/backend/node_modules/openai/resources/audio/audio.js @@ -0,0 +1,46 @@ +"use strict"; +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Audio = void 0; +const resource_1 = require("openai/resource"); +const SpeechAPI = __importStar(require("openai/resources/audio/speech")); +const TranscriptionsAPI = __importStar(require("openai/resources/audio/transcriptions")); +const TranslationsAPI = __importStar(require("openai/resources/audio/translations")); +class Audio extends resource_1.APIResource { + constructor() { + super(...arguments); + this.transcriptions = new TranscriptionsAPI.Transcriptions(this._client); + this.translations = new TranslationsAPI.Translations(this._client); + this.speech = new SpeechAPI.Speech(this._client); + } +} +exports.Audio = Audio; +(function (Audio) { + Audio.Transcriptions = TranscriptionsAPI.Transcriptions; + Audio.Translations = TranslationsAPI.Translations; + Audio.Speech = SpeechAPI.Speech; +})(Audio = exports.Audio || (exports.Audio = {})); +//# sourceMappingURL=audio.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/audio/audio.js.map b/backend/node_modules/openai/resources/audio/audio.js.map new file mode 100644 index 0000000000000000000000000000000000000000..7708e3decef195cc6e350258bbdd5cf6c313192c --- /dev/null +++ b/backend/node_modules/openai/resources/audio/audio.js.map @@ -0,0 +1 @@ +{"version":3,"file":"audio.js","sourceRoot":"","sources":["../../src/resources/audio/audio.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;;;;;;;;;;;;;;;;;;;;;;;;AAEtF,8CAA8C;AAC9C,yEAA2D;AAC3D,yFAA2E;AAC3E,qFAAuE;AAEvE,MAAa,KAAM,SAAQ,sBAAW;IAAtC;;QACE,mBAAc,GAAqC,IAAI,iBAAiB,CAAC,cAAc,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QACtG,iBAAY,GAAiC,IAAI,eAAe,CAAC,YAAY,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QAC5F,WAAM,GAAqB,IAAI,SAAS,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IAChE,CAAC;CAAA;AAJD,sBAIC;AAED,WAAiB,KAAK;IACN,oBAAc,GAAG,iBAAiB,CAAC,cAAc,CAAC;IAGlD,kBAAY,GAAG,eAAe,CAAC,YAAY,CAAC;IAG5C,YAAM,GAAG,SAAS,CAAC,MAAM,CAAC;AAE1C,CAAC,EATgB,KAAK,GAAL,aAAK,KAAL,aAAK,QASrB"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/audio/audio.mjs b/backend/node_modules/openai/resources/audio/audio.mjs new file mode 100644 index 0000000000000000000000000000000000000000..a2e20b449a1739996c192537b08d4cdcdcb9141c --- /dev/null +++ b/backend/node_modules/openai/resources/audio/audio.mjs @@ -0,0 +1,19 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +import { APIResource } from 'openai/resource'; +import * as SpeechAPI from 'openai/resources/audio/speech'; +import * as TranscriptionsAPI from 'openai/resources/audio/transcriptions'; +import * as TranslationsAPI from 'openai/resources/audio/translations'; +export class Audio extends APIResource { + constructor() { + super(...arguments); + this.transcriptions = new TranscriptionsAPI.Transcriptions(this._client); + this.translations = new TranslationsAPI.Translations(this._client); + this.speech = new SpeechAPI.Speech(this._client); + } +} +(function (Audio) { + Audio.Transcriptions = TranscriptionsAPI.Transcriptions; + Audio.Translations = TranslationsAPI.Translations; + Audio.Speech = SpeechAPI.Speech; +})(Audio || (Audio = {})); +//# sourceMappingURL=audio.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/audio/audio.mjs.map b/backend/node_modules/openai/resources/audio/audio.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..be13c0b9526600a05f4f273758b55d4bd23ae068 --- /dev/null +++ b/backend/node_modules/openai/resources/audio/audio.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"audio.mjs","sourceRoot":"","sources":["../../src/resources/audio/audio.ts"],"names":[],"mappings":"AAAA,sFAAsF;OAE/E,EAAE,WAAW,EAAE,MAAM,iBAAiB;OACtC,KAAK,SAAS,MAAM,+BAA+B;OACnD,KAAK,iBAAiB,MAAM,uCAAuC;OACnE,KAAK,eAAe,MAAM,qCAAqC;AAEtE,MAAM,OAAO,KAAM,SAAQ,WAAW;IAAtC;;QACE,mBAAc,GAAqC,IAAI,iBAAiB,CAAC,cAAc,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QACtG,iBAAY,GAAiC,IAAI,eAAe,CAAC,YAAY,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QAC5F,WAAM,GAAqB,IAAI,SAAS,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IAChE,CAAC;CAAA;AAED,WAAiB,KAAK;IACN,oBAAc,GAAG,iBAAiB,CAAC,cAAc,CAAC;IAGlD,kBAAY,GAAG,eAAe,CAAC,YAAY,CAAC;IAG5C,YAAM,GAAG,SAAS,CAAC,MAAM,CAAC;AAE1C,CAAC,EATgB,KAAK,KAAL,KAAK,QASrB"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/audio/index.d.ts b/backend/node_modules/openai/resources/audio/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c8a4262e9eb48882ca1f8eed941f2b4196d3c9b6 --- /dev/null +++ b/backend/node_modules/openai/resources/audio/index.d.ts @@ -0,0 +1,5 @@ +export { Audio } from "./audio.js"; +export { SpeechCreateParams, Speech } from "./speech.js"; +export { Transcription, TranscriptionCreateParams, Transcriptions } from "./transcriptions.js"; +export { Translation, TranslationCreateParams, Translations } from "./translations.js"; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/audio/index.d.ts.map b/backend/node_modules/openai/resources/audio/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..893c4dd31f10e68e998e1dda1684e2b8c599980e --- /dev/null +++ b/backend/node_modules/openai/resources/audio/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/resources/audio/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAChC,OAAO,EAAE,kBAAkB,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AACtD,OAAO,EAAE,aAAa,EAAE,yBAAyB,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAC5F,OAAO,EAAE,WAAW,EAAE,uBAAuB,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/audio/index.js b/backend/node_modules/openai/resources/audio/index.js new file mode 100644 index 0000000000000000000000000000000000000000..1e38c2f2bd86a480901a29c7fc7787142364f066 --- /dev/null +++ b/backend/node_modules/openai/resources/audio/index.js @@ -0,0 +1,13 @@ +"use strict"; +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Translations = exports.Transcriptions = exports.Speech = exports.Audio = void 0; +var audio_1 = require("./audio.js"); +Object.defineProperty(exports, "Audio", { enumerable: true, get: function () { return audio_1.Audio; } }); +var speech_1 = require("./speech.js"); +Object.defineProperty(exports, "Speech", { enumerable: true, get: function () { return speech_1.Speech; } }); +var transcriptions_1 = require("./transcriptions.js"); +Object.defineProperty(exports, "Transcriptions", { enumerable: true, get: function () { return transcriptions_1.Transcriptions; } }); +var translations_1 = require("./translations.js"); +Object.defineProperty(exports, "Translations", { enumerable: true, get: function () { return translations_1.Translations; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/audio/index.js.map b/backend/node_modules/openai/resources/audio/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..2dcdf424a2b66ade515e733e491b95489d3d115e --- /dev/null +++ b/backend/node_modules/openai/resources/audio/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/resources/audio/index.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;AAEtF,oCAAgC;AAAvB,8FAAA,KAAK,OAAA;AACd,sCAAsD;AAAzB,gGAAA,MAAM,OAAA;AACnC,sDAA4F;AAAzC,gHAAA,cAAc,OAAA;AACjE,kDAAoF;AAArC,4GAAA,YAAY,OAAA"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/audio/index.mjs b/backend/node_modules/openai/resources/audio/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..ef00b530f8ebc082044e4a102ffad0d734b43d6b --- /dev/null +++ b/backend/node_modules/openai/resources/audio/index.mjs @@ -0,0 +1,6 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +export { Audio } from "./audio.mjs"; +export { Speech } from "./speech.mjs"; +export { Transcriptions } from "./transcriptions.mjs"; +export { Translations } from "./translations.mjs"; +//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/audio/index.mjs.map b/backend/node_modules/openai/resources/audio/index.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..1de907fccf34f12598bb02eaac09558f0c6fda8b --- /dev/null +++ b/backend/node_modules/openai/resources/audio/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"index.mjs","sourceRoot":"","sources":["../../src/resources/audio/index.ts"],"names":[],"mappings":"AAAA,sFAAsF;OAE/E,EAAE,KAAK,EAAE;OACT,EAAsB,MAAM,EAAE;OAC9B,EAA4C,cAAc,EAAE;OAC5D,EAAwC,YAAY,EAAE"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/audio/speech.d.ts b/backend/node_modules/openai/resources/audio/speech.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8ae6edd06afd53adb2f3330bed028337e6e26d47 --- /dev/null +++ b/backend/node_modules/openai/resources/audio/speech.d.ts @@ -0,0 +1,42 @@ +import * as Core from 'openai/core'; +import { APIResource } from 'openai/resource'; +import { type Response } from 'openai/_shims/index'; +import * as SpeechAPI from 'openai/resources/audio/speech'; +export declare class Speech extends APIResource { + /** + * Generates audio from the input text. + */ + create(body: SpeechCreateParams, options?: Core.RequestOptions): Core.APIPromise; +} +export interface SpeechCreateParams { + /** + * The text to generate audio for. The maximum length is 4096 characters. + */ + input: string; + /** + * One of the available [TTS models](https://platform.openai.com/docs/models/tts): + * `tts-1` or `tts-1-hd` + */ + model: (string & {}) | 'tts-1' | 'tts-1-hd'; + /** + * The voice to use when generating the audio. Supported voices are `alloy`, + * `echo`, `fable`, `onyx`, `nova`, and `shimmer`. Previews of the voices are + * available in the + * [Text to speech guide](https://platform.openai.com/docs/guides/text-to-speech/voice-options). + */ + voice: 'alloy' | 'echo' | 'fable' | 'onyx' | 'nova' | 'shimmer'; + /** + * The format to audio in. Supported formats are `mp3`, `opus`, `aac`, `flac`, + * `wav`, and `pcm`. + */ + response_format?: 'mp3' | 'opus' | 'aac' | 'flac' | 'wav' | 'pcm'; + /** + * The speed of the generated audio. Select a value from `0.25` to `4.0`. `1.0` is + * the default. + */ + speed?: number; +} +export declare namespace Speech { + export import SpeechCreateParams = SpeechAPI.SpeechCreateParams; +} +//# sourceMappingURL=speech.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/audio/speech.d.ts.map b/backend/node_modules/openai/resources/audio/speech.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..d037f9e5bccb0bf771c01196984fceca274b70f6 --- /dev/null +++ b/backend/node_modules/openai/resources/audio/speech.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"speech.d.ts","sourceRoot":"","sources":["../../src/resources/audio/speech.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,IAAI,MAAM,aAAa,CAAC;AACpC,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAC9C,OAAO,EAAE,KAAK,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,KAAK,SAAS,MAAM,+BAA+B,CAAC;AAE3D,qBAAa,MAAO,SAAQ,WAAW;IACrC;;OAEG;IACH,MAAM,CAAC,IAAI,EAAE,kBAAkB,EAAE,OAAO,CAAC,EAAE,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC;CAG3F;AAED,MAAM,WAAW,kBAAkB;IACjC;;OAEG;IACH,KAAK,EAAE,MAAM,CAAC;IAEd;;;OAGG;IACH,KAAK,EAAE,CAAC,MAAM,GAAG,EAAE,CAAC,GAAG,OAAO,GAAG,UAAU,CAAC;IAE5C;;;;;OAKG;IACH,KAAK,EAAE,OAAO,GAAG,MAAM,GAAG,OAAO,GAAG,MAAM,GAAG,MAAM,GAAG,SAAS,CAAC;IAEhE;;;OAGG;IACH,eAAe,CAAC,EAAE,KAAK,GAAG,MAAM,GAAG,KAAK,GAAG,MAAM,GAAG,KAAK,GAAG,KAAK,CAAC;IAElE;;;OAGG;IACH,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,yBAAiB,MAAM,CAAC;IACtB,MAAM,QAAQ,kBAAkB,GAAG,SAAS,CAAC,kBAAkB,CAAC;CACjE"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/audio/speech.js b/backend/node_modules/openai/resources/audio/speech.js new file mode 100644 index 0000000000000000000000000000000000000000..1969f6826984b152d558bba0e95aaca194997cb1 --- /dev/null +++ b/backend/node_modules/openai/resources/audio/speech.js @@ -0,0 +1,17 @@ +"use strict"; +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Speech = void 0; +const resource_1 = require("openai/resource"); +class Speech extends resource_1.APIResource { + /** + * Generates audio from the input text. + */ + create(body, options) { + return this._client.post('/audio/speech', { body, ...options, __binaryResponse: true }); + } +} +exports.Speech = Speech; +(function (Speech) { +})(Speech = exports.Speech || (exports.Speech = {})); +//# sourceMappingURL=speech.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/audio/speech.js.map b/backend/node_modules/openai/resources/audio/speech.js.map new file mode 100644 index 0000000000000000000000000000000000000000..bfbb4ed47aa32775fe48c755369b105c3f987ae0 --- /dev/null +++ b/backend/node_modules/openai/resources/audio/speech.js.map @@ -0,0 +1 @@ +{"version":3,"file":"speech.js","sourceRoot":"","sources":["../../src/resources/audio/speech.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;AAGtF,8CAA8C;AAI9C,MAAa,MAAO,SAAQ,sBAAW;IACrC;;OAEG;IACH,MAAM,CAAC,IAAwB,EAAE,OAA6B;QAC5D,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,eAAe,EAAE,EAAE,IAAI,EAAE,GAAG,OAAO,EAAE,gBAAgB,EAAE,IAAI,EAAE,CAAC,CAAC;IAC1F,CAAC;CACF;AAPD,wBAOC;AAmCD,WAAiB,MAAM;AAEvB,CAAC,EAFgB,MAAM,GAAN,cAAM,KAAN,cAAM,QAEtB"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/audio/speech.mjs b/backend/node_modules/openai/resources/audio/speech.mjs new file mode 100644 index 0000000000000000000000000000000000000000..be8164a246d950fd74e9b49f32c8b8cd3c1cab4a --- /dev/null +++ b/backend/node_modules/openai/resources/audio/speech.mjs @@ -0,0 +1,13 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +import { APIResource } from 'openai/resource'; +export class Speech extends APIResource { + /** + * Generates audio from the input text. + */ + create(body, options) { + return this._client.post('/audio/speech', { body, ...options, __binaryResponse: true }); + } +} +(function (Speech) { +})(Speech || (Speech = {})); +//# sourceMappingURL=speech.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/audio/speech.mjs.map b/backend/node_modules/openai/resources/audio/speech.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..2d4c10dac7c208474a43d30e316ebac30cfad92e --- /dev/null +++ b/backend/node_modules/openai/resources/audio/speech.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"speech.mjs","sourceRoot":"","sources":["../../src/resources/audio/speech.ts"],"names":[],"mappings":"AAAA,sFAAsF;OAG/E,EAAE,WAAW,EAAE,MAAM,iBAAiB;AAI7C,MAAM,OAAO,MAAO,SAAQ,WAAW;IACrC;;OAEG;IACH,MAAM,CAAC,IAAwB,EAAE,OAA6B;QAC5D,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,eAAe,EAAE,EAAE,IAAI,EAAE,GAAG,OAAO,EAAE,gBAAgB,EAAE,IAAI,EAAE,CAAC,CAAC;IAC1F,CAAC;CACF;AAmCD,WAAiB,MAAM;AAEvB,CAAC,EAFgB,MAAM,KAAN,MAAM,QAEtB"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/audio/transcriptions.d.ts b/backend/node_modules/openai/resources/audio/transcriptions.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1d727007328142f0c7949e6ca49078368580b894 --- /dev/null +++ b/backend/node_modules/openai/resources/audio/transcriptions.d.ts @@ -0,0 +1,71 @@ +import * as Core from 'openai/core'; +import { APIResource } from 'openai/resource'; +import * as TranscriptionsAPI from 'openai/resources/audio/transcriptions'; +import { type Uploadable } from 'openai/core'; +export declare class Transcriptions extends APIResource { + /** + * Transcribes audio into the input language. + */ + create(body: TranscriptionCreateParams, options?: Core.RequestOptions): Core.APIPromise; +} +/** + * Represents a transcription response returned by model, based on the provided + * input. + */ +export interface Transcription { + /** + * The transcribed text. + */ + text: string; +} +export interface TranscriptionCreateParams { + /** + * The audio file object (not file name) to transcribe, in one of these formats: + * flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm. + */ + file: Uploadable; + /** + * ID of the model to use. Only `whisper-1` (which is powered by our open source + * Whisper V2 model) is currently available. + */ + model: (string & {}) | 'whisper-1'; + /** + * The language of the input audio. Supplying the input language in + * [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) format will + * improve accuracy and latency. + */ + language?: string; + /** + * An optional text to guide the model's style or continue a previous audio + * segment. The + * [prompt](https://platform.openai.com/docs/guides/speech-to-text/prompting) + * should match the audio language. + */ + prompt?: string; + /** + * The format of the transcript output, in one of these options: `json`, `text`, + * `srt`, `verbose_json`, or `vtt`. + */ + response_format?: 'json' | 'text' | 'srt' | 'verbose_json' | 'vtt'; + /** + * The sampling temperature, between 0 and 1. Higher values like 0.8 will make the + * output more random, while lower values like 0.2 will make it more focused and + * deterministic. If set to 0, the model will use + * [log probability](https://en.wikipedia.org/wiki/Log_probability) to + * automatically increase the temperature until certain thresholds are hit. + */ + temperature?: number; + /** + * The timestamp granularities to populate for this transcription. + * `response_format` must be set `verbose_json` to use timestamp granularities. + * Either or both of these options are supported: `word`, or `segment`. Note: There + * is no additional latency for segment timestamps, but generating word timestamps + * incurs additional latency. + */ + timestamp_granularities?: Array<'word' | 'segment'>; +} +export declare namespace Transcriptions { + export import Transcription = TranscriptionsAPI.Transcription; + export import TranscriptionCreateParams = TranscriptionsAPI.TranscriptionCreateParams; +} +//# sourceMappingURL=transcriptions.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/audio/transcriptions.d.ts.map b/backend/node_modules/openai/resources/audio/transcriptions.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..24650141120b4734fe1ac475073b2e3bdacf7f5a --- /dev/null +++ b/backend/node_modules/openai/resources/audio/transcriptions.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"transcriptions.d.ts","sourceRoot":"","sources":["../../src/resources/audio/transcriptions.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,IAAI,MAAM,aAAa,CAAC;AACpC,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAC9C,OAAO,KAAK,iBAAiB,MAAM,uCAAuC,CAAC;AAC3E,OAAO,EAAE,KAAK,UAAU,EAA+B,MAAM,aAAa,CAAC;AAE3E,qBAAa,cAAe,SAAQ,WAAW;IAC7C;;OAEG;IACH,MAAM,CAAC,IAAI,EAAE,yBAAyB,EAAE,OAAO,CAAC,EAAE,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC,UAAU,CAAC,aAAa,CAAC;CAGvG;AAED;;;GAGG;AACH,MAAM,WAAW,aAAa;IAC5B;;OAEG;IACH,IAAI,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,yBAAyB;IACxC;;;OAGG;IACH,IAAI,EAAE,UAAU,CAAC;IAEjB;;;OAGG;IACH,KAAK,EAAE,CAAC,MAAM,GAAG,EAAE,CAAC,GAAG,WAAW,CAAC;IAEnC;;;;OAIG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAElB;;;;;OAKG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAEhB;;;OAGG;IACH,eAAe,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,KAAK,GAAG,cAAc,GAAG,KAAK,CAAC;IAEnE;;;;;;OAMG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IAErB;;;;;;OAMG;IACH,uBAAuB,CAAC,EAAE,KAAK,CAAC,MAAM,GAAG,SAAS,CAAC,CAAC;CACrD;AAED,yBAAiB,cAAc,CAAC;IAC9B,MAAM,QAAQ,aAAa,GAAG,iBAAiB,CAAC,aAAa,CAAC;IAC9D,MAAM,QAAQ,yBAAyB,GAAG,iBAAiB,CAAC,yBAAyB,CAAC;CACvF"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/audio/transcriptions.js b/backend/node_modules/openai/resources/audio/transcriptions.js new file mode 100644 index 0000000000000000000000000000000000000000..e9fda8b3b34a325c9c3aa8c7b1553480b9b9f8b1 --- /dev/null +++ b/backend/node_modules/openai/resources/audio/transcriptions.js @@ -0,0 +1,18 @@ +"use strict"; +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Transcriptions = void 0; +const resource_1 = require("openai/resource"); +const core_1 = require("openai/core"); +class Transcriptions extends resource_1.APIResource { + /** + * Transcribes audio into the input language. + */ + create(body, options) { + return this._client.post('/audio/transcriptions', (0, core_1.multipartFormRequestOptions)({ body, ...options })); + } +} +exports.Transcriptions = Transcriptions; +(function (Transcriptions) { +})(Transcriptions = exports.Transcriptions || (exports.Transcriptions = {})); +//# sourceMappingURL=transcriptions.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/audio/transcriptions.js.map b/backend/node_modules/openai/resources/audio/transcriptions.js.map new file mode 100644 index 0000000000000000000000000000000000000000..2fb3d1d91552f6c67b35cf8b0105f0a4678e384f --- /dev/null +++ b/backend/node_modules/openai/resources/audio/transcriptions.js.map @@ -0,0 +1 @@ +{"version":3,"file":"transcriptions.js","sourceRoot":"","sources":["../../src/resources/audio/transcriptions.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;AAGtF,8CAA8C;AAE9C,sCAA2E;AAE3E,MAAa,cAAe,SAAQ,sBAAW;IAC7C;;OAEG;IACH,MAAM,CAAC,IAA+B,EAAE,OAA6B;QACnE,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,uBAAuB,EAAE,IAAA,kCAA2B,EAAC,EAAE,IAAI,EAAE,GAAG,OAAO,EAAE,CAAC,CAAC,CAAC;IACvG,CAAC;CACF;AAPD,wCAOC;AAkED,WAAiB,cAAc;AAG/B,CAAC,EAHgB,cAAc,GAAd,sBAAc,KAAd,sBAAc,QAG9B"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/audio/transcriptions.mjs b/backend/node_modules/openai/resources/audio/transcriptions.mjs new file mode 100644 index 0000000000000000000000000000000000000000..c13acade29a2c6ee21319023e9d1958c78b2f523 --- /dev/null +++ b/backend/node_modules/openai/resources/audio/transcriptions.mjs @@ -0,0 +1,14 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +import { APIResource } from 'openai/resource'; +import { multipartFormRequestOptions } from 'openai/core'; +export class Transcriptions extends APIResource { + /** + * Transcribes audio into the input language. + */ + create(body, options) { + return this._client.post('/audio/transcriptions', multipartFormRequestOptions({ body, ...options })); + } +} +(function (Transcriptions) { +})(Transcriptions || (Transcriptions = {})); +//# sourceMappingURL=transcriptions.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/audio/transcriptions.mjs.map b/backend/node_modules/openai/resources/audio/transcriptions.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..a3635b919886e8f2a31a46ec6091fa2ba0c73323 --- /dev/null +++ b/backend/node_modules/openai/resources/audio/transcriptions.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"transcriptions.mjs","sourceRoot":"","sources":["../../src/resources/audio/transcriptions.ts"],"names":[],"mappings":"AAAA,sFAAsF;OAG/E,EAAE,WAAW,EAAE,MAAM,iBAAiB;OAEtC,EAAmB,2BAA2B,EAAE,MAAM,aAAa;AAE1E,MAAM,OAAO,cAAe,SAAQ,WAAW;IAC7C;;OAEG;IACH,MAAM,CAAC,IAA+B,EAAE,OAA6B;QACnE,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,uBAAuB,EAAE,2BAA2B,CAAC,EAAE,IAAI,EAAE,GAAG,OAAO,EAAE,CAAC,CAAC,CAAC;IACvG,CAAC;CACF;AAkED,WAAiB,cAAc;AAG/B,CAAC,EAHgB,cAAc,KAAd,cAAc,QAG9B"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/audio/translations.d.ts b/backend/node_modules/openai/resources/audio/translations.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d9ebac2da4ab7e0e6f6a910e1411100a6ecd2f12 --- /dev/null +++ b/backend/node_modules/openai/resources/audio/translations.d.ts @@ -0,0 +1,50 @@ +import * as Core from 'openai/core'; +import { APIResource } from 'openai/resource'; +import * as TranslationsAPI from 'openai/resources/audio/translations'; +import { type Uploadable } from 'openai/core'; +export declare class Translations extends APIResource { + /** + * Translates audio into English. + */ + create(body: TranslationCreateParams, options?: Core.RequestOptions): Core.APIPromise; +} +export interface Translation { + text: string; +} +export interface TranslationCreateParams { + /** + * The audio file object (not file name) translate, in one of these formats: flac, + * mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm. + */ + file: Uploadable; + /** + * ID of the model to use. Only `whisper-1` (which is powered by our open source + * Whisper V2 model) is currently available. + */ + model: (string & {}) | 'whisper-1'; + /** + * An optional text to guide the model's style or continue a previous audio + * segment. The + * [prompt](https://platform.openai.com/docs/guides/speech-to-text/prompting) + * should be in English. + */ + prompt?: string; + /** + * The format of the transcript output, in one of these options: `json`, `text`, + * `srt`, `verbose_json`, or `vtt`. + */ + response_format?: string; + /** + * The sampling temperature, between 0 and 1. Higher values like 0.8 will make the + * output more random, while lower values like 0.2 will make it more focused and + * deterministic. If set to 0, the model will use + * [log probability](https://en.wikipedia.org/wiki/Log_probability) to + * automatically increase the temperature until certain thresholds are hit. + */ + temperature?: number; +} +export declare namespace Translations { + export import Translation = TranslationsAPI.Translation; + export import TranslationCreateParams = TranslationsAPI.TranslationCreateParams; +} +//# sourceMappingURL=translations.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/audio/translations.d.ts.map b/backend/node_modules/openai/resources/audio/translations.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..3009e631ff3634b60f6ea603a337306afc107513 --- /dev/null +++ b/backend/node_modules/openai/resources/audio/translations.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"translations.d.ts","sourceRoot":"","sources":["../../src/resources/audio/translations.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,IAAI,MAAM,aAAa,CAAC;AACpC,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAC9C,OAAO,KAAK,eAAe,MAAM,qCAAqC,CAAC;AACvE,OAAO,EAAE,KAAK,UAAU,EAA+B,MAAM,aAAa,CAAC;AAE3E,qBAAa,YAAa,SAAQ,WAAW;IAC3C;;OAEG;IACH,MAAM,CAAC,IAAI,EAAE,uBAAuB,EAAE,OAAO,CAAC,EAAE,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC,UAAU,CAAC,WAAW,CAAC;CAGnG;AAED,MAAM,WAAW,WAAW;IAC1B,IAAI,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,uBAAuB;IACtC;;;OAGG;IACH,IAAI,EAAE,UAAU,CAAC;IAEjB;;;OAGG;IACH,KAAK,EAAE,CAAC,MAAM,GAAG,EAAE,CAAC,GAAG,WAAW,CAAC;IAEnC;;;;;OAKG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAEhB;;;OAGG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;IAEzB;;;;;;OAMG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,yBAAiB,YAAY,CAAC;IAC5B,MAAM,QAAQ,WAAW,GAAG,eAAe,CAAC,WAAW,CAAC;IACxD,MAAM,QAAQ,uBAAuB,GAAG,eAAe,CAAC,uBAAuB,CAAC;CACjF"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/audio/translations.js b/backend/node_modules/openai/resources/audio/translations.js new file mode 100644 index 0000000000000000000000000000000000000000..98272a38d5b5d30e8d813cf9255fa1be9575dd9a --- /dev/null +++ b/backend/node_modules/openai/resources/audio/translations.js @@ -0,0 +1,18 @@ +"use strict"; +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Translations = void 0; +const resource_1 = require("openai/resource"); +const core_1 = require("openai/core"); +class Translations extends resource_1.APIResource { + /** + * Translates audio into English. + */ + create(body, options) { + return this._client.post('/audio/translations', (0, core_1.multipartFormRequestOptions)({ body, ...options })); + } +} +exports.Translations = Translations; +(function (Translations) { +})(Translations = exports.Translations || (exports.Translations = {})); +//# sourceMappingURL=translations.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/audio/translations.js.map b/backend/node_modules/openai/resources/audio/translations.js.map new file mode 100644 index 0000000000000000000000000000000000000000..163bfef8cd2f48ce885239c0c6b79cb289ddc224 --- /dev/null +++ b/backend/node_modules/openai/resources/audio/translations.js.map @@ -0,0 +1 @@ +{"version":3,"file":"translations.js","sourceRoot":"","sources":["../../src/resources/audio/translations.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;AAGtF,8CAA8C;AAE9C,sCAA2E;AAE3E,MAAa,YAAa,SAAQ,sBAAW;IAC3C;;OAEG;IACH,MAAM,CAAC,IAA6B,EAAE,OAA6B;QACjE,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,qBAAqB,EAAE,IAAA,kCAA2B,EAAC,EAAE,IAAI,EAAE,GAAG,OAAO,EAAE,CAAC,CAAC,CAAC;IACrG,CAAC;CACF;AAPD,oCAOC;AA2CD,WAAiB,YAAY;AAG7B,CAAC,EAHgB,YAAY,GAAZ,oBAAY,KAAZ,oBAAY,QAG5B"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/audio/translations.mjs b/backend/node_modules/openai/resources/audio/translations.mjs new file mode 100644 index 0000000000000000000000000000000000000000..1677343ba11de3844188738c16da7dda3f264e4c --- /dev/null +++ b/backend/node_modules/openai/resources/audio/translations.mjs @@ -0,0 +1,14 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +import { APIResource } from 'openai/resource'; +import { multipartFormRequestOptions } from 'openai/core'; +export class Translations extends APIResource { + /** + * Translates audio into English. + */ + create(body, options) { + return this._client.post('/audio/translations', multipartFormRequestOptions({ body, ...options })); + } +} +(function (Translations) { +})(Translations || (Translations = {})); +//# sourceMappingURL=translations.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/audio/translations.mjs.map b/backend/node_modules/openai/resources/audio/translations.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..e7d55e30ee168daf86cbc3618b767b90553f185a --- /dev/null +++ b/backend/node_modules/openai/resources/audio/translations.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"translations.mjs","sourceRoot":"","sources":["../../src/resources/audio/translations.ts"],"names":[],"mappings":"AAAA,sFAAsF;OAG/E,EAAE,WAAW,EAAE,MAAM,iBAAiB;OAEtC,EAAmB,2BAA2B,EAAE,MAAM,aAAa;AAE1E,MAAM,OAAO,YAAa,SAAQ,WAAW;IAC3C;;OAEG;IACH,MAAM,CAAC,IAA6B,EAAE,OAA6B;QACjE,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,qBAAqB,EAAE,2BAA2B,CAAC,EAAE,IAAI,EAAE,GAAG,OAAO,EAAE,CAAC,CAAC,CAAC;IACrG,CAAC;CACF;AA2CD,WAAiB,YAAY;AAG7B,CAAC,EAHgB,YAAY,KAAZ,YAAY,QAG5B"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/batches.d.ts b/backend/node_modules/openai/resources/batches.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..17f9d6dcbdb14fdbc85f6554c511604b864fef59 --- /dev/null +++ b/backend/node_modules/openai/resources/batches.d.ts @@ -0,0 +1,173 @@ +import * as Core from 'openai/core'; +import { APIResource } from 'openai/resource'; +import * as BatchesAPI from 'openai/resources/batches'; +export declare class Batches extends APIResource { + /** + * Creates and executes a batch from an uploaded file of requests + */ + create(body: BatchCreateParams, options?: Core.RequestOptions): Core.APIPromise; + /** + * Retrieves a batch. + */ + retrieve(batchId: string, options?: Core.RequestOptions): Core.APIPromise; + /** + * Cancels an in-progress batch. + */ + cancel(batchId: string, options?: Core.RequestOptions): Core.APIPromise; +} +export interface Batch { + id: string; + /** + * The time frame within which the batch should be processed. + */ + completion_window: string; + /** + * The Unix timestamp (in seconds) for when the batch was created. + */ + created_at: string; + /** + * The OpenAI API endpoint used by the batch. + */ + endpoint: string; + /** + * The ID of the input file for the batch. + */ + input_file_id: string; + /** + * The object type, which is always `batch`. + */ + object: 'batch'; + /** + * The current status of the batch. + */ + status: 'validating' | 'failed' | 'in_progress' | 'finalizing' | 'completed' | 'expired' | 'cancelling' | 'cancelled'; + /** + * The Unix timestamp (in seconds) for when the batch was cancelled. + */ + cancelled_at?: string; + /** + * The Unix timestamp (in seconds) for when the batch started cancelling. + */ + cancelling_at?: string; + /** + * The Unix timestamp (in seconds) for when the batch was completed. + */ + completed_at?: string; + /** + * The ID of the file containing the outputs of requests with errors. + */ + error_file_id?: string; + errors?: Batch.Errors; + /** + * The Unix timestamp (in seconds) for when the batch expired. + */ + expired_at?: string; + /** + * The Unix timestamp (in seconds) for when the batch will expire. + */ + expires_at?: string; + /** + * The Unix timestamp (in seconds) for when the batch failed. + */ + failed_at?: string; + /** + * The Unix timestamp (in seconds) for when the batch started finalizing. + */ + finalizing_at?: string; + /** + * The Unix timestamp (in seconds) for when the batch started processing. + */ + in_progress_at?: string; + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata?: unknown | null; + /** + * The ID of the file containing the outputs of successfully executed requests. + */ + output_file_id?: string; + /** + * The request counts for different statuses within the batch. + */ + request_counts?: BatchRequestCounts; +} +export declare namespace Batch { + interface Errors { + data?: Array; + /** + * The object type, which is always `list`. + */ + object?: string; + } +} +export interface BatchError { + /** + * An error code identifying the error type. + */ + code?: string; + /** + * The line number of the input file where the error occurred, if applicable. + */ + line?: number | null; + /** + * A human-readable message providing more details about the error. + */ + message?: string; + /** + * The name of the parameter that caused the error, if applicable. + */ + param?: string | null; +} +/** + * The request counts for different statuses within the batch. + */ +export interface BatchRequestCounts { + /** + * Number of requests that have been completed successfully. + */ + completed: number; + /** + * Number of requests that have failed. + */ + failed: number; + /** + * Total number of requests in the batch. + */ + total: number; +} +export interface BatchCreateParams { + /** + * The time frame within which the batch should be processed. Currently only `24h` + * is supported. + */ + completion_window: '24h'; + /** + * The endpoint to be used for all requests in the batch. Currently only + * `/v1/chat/completions` is supported. + */ + endpoint: '/v1/chat/completions'; + /** + * The ID of an uploaded file that contains requests for the new batch. + * + * See [upload file](https://platform.openai.com/docs/api-reference/files/create) + * for how to upload a file. + * + * Your input file must be formatted as a JSONL file, and must be uploaded with the + * purpose `batch`. + */ + input_file_id: string; + /** + * Optional custom metadata for the batch. + */ + metadata?: Record | null; +} +export declare namespace Batches { + export import Batch = BatchesAPI.Batch; + export import BatchError = BatchesAPI.BatchError; + export import BatchRequestCounts = BatchesAPI.BatchRequestCounts; + export import BatchCreateParams = BatchesAPI.BatchCreateParams; +} +//# sourceMappingURL=batches.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/batches.d.ts.map b/backend/node_modules/openai/resources/batches.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..566167838b568a66f4cec4764e8ee90a8c3c03d6 --- /dev/null +++ b/backend/node_modules/openai/resources/batches.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"batches.d.ts","sourceRoot":"","sources":["../src/resources/batches.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,IAAI,MAAM,aAAa,CAAC;AACpC,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAC9C,OAAO,KAAK,UAAU,MAAM,0BAA0B,CAAC;AAEvD,qBAAa,OAAQ,SAAQ,WAAW;IACtC;;OAEG;IACH,MAAM,CAAC,IAAI,EAAE,iBAAiB,EAAE,OAAO,CAAC,EAAE,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC;IAItF;;OAEG;IACH,QAAQ,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC;IAIhF;;OAEG;IACH,MAAM,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC;CAG/E;AAED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AAM,WAAW,UAAU;IACzB;;OAEG;IACH,IAAI,CAAC,EAAE,MAAM,CAAC;IAEd;;OAEG;IACH,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAErB;;OAEG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IAEjB;;OAEG;IACH,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CACvB;AAED;;GAEG;AACH,MAAM,WAAW,kBAAkB;IACjC;;OAEG;IACH,SAAS,EAAE,MAAM,CAAC;IAElB;;OAEG;IACH,MAAM,EAAE,MAAM,CAAC;IAEf;;OAEG;IACH,KAAK,EAAE,MAAM,CAAC;CACf;AAED,MAAM,WAAW,iBAAiB;IAChC;;;OAGG;IACH,iBAAiB,EAAE,KAAK,CAAC;IAEzB;;;OAGG;IACH,QAAQ,EAAE,sBAAsB,CAAC;IAEjC;;;;;;;;OAQG;IACH,aAAa,EAAE,MAAM,CAAC;IAEtB;;OAEG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,IAAI,CAAC;CAC1C;AAED,yBAAiB,OAAO,CAAC;IACvB,MAAM,QAAQ,KAAK,GAAG,UAAU,CAAC,KAAK,CAAC;IACvC,MAAM,QAAQ,UAAU,GAAG,UAAU,CAAC,UAAU,CAAC;IACjD,MAAM,QAAQ,kBAAkB,GAAG,UAAU,CAAC,kBAAkB,CAAC;IACjE,MAAM,QAAQ,iBAAiB,GAAG,UAAU,CAAC,iBAAiB,CAAC;CAChE"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/batches.js b/backend/node_modules/openai/resources/batches.js new file mode 100644 index 0000000000000000000000000000000000000000..4aebb63fd3db941184e586a454f328cdc2d266b5 --- /dev/null +++ b/backend/node_modules/openai/resources/batches.js @@ -0,0 +1,29 @@ +"use strict"; +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Batches = void 0; +const resource_1 = require("openai/resource"); +class Batches extends resource_1.APIResource { + /** + * Creates and executes a batch from an uploaded file of requests + */ + create(body, options) { + return this._client.post('/batches', { body, ...options }); + } + /** + * Retrieves a batch. + */ + retrieve(batchId, options) { + return this._client.get(`/batches/${batchId}`, options); + } + /** + * Cancels an in-progress batch. + */ + cancel(batchId, options) { + return this._client.post(`/batches/${batchId}/cancel`, options); + } +} +exports.Batches = Batches; +(function (Batches) { +})(Batches = exports.Batches || (exports.Batches = {})); +//# sourceMappingURL=batches.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/batches.js.map b/backend/node_modules/openai/resources/batches.js.map new file mode 100644 index 0000000000000000000000000000000000000000..40e2362440ed93a8f157ab511c2a82293259f4f8 --- /dev/null +++ b/backend/node_modules/openai/resources/batches.js.map @@ -0,0 +1 @@ +{"version":3,"file":"batches.js","sourceRoot":"","sources":["../src/resources/batches.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;AAGtF,8CAA8C;AAG9C,MAAa,OAAQ,SAAQ,sBAAW;IACtC;;OAEG;IACH,MAAM,CAAC,IAAuB,EAAE,OAA6B;QAC3D,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,UAAU,EAAE,EAAE,IAAI,EAAE,GAAG,OAAO,EAAE,CAAC,CAAC;IAC7D,CAAC;IAED;;OAEG;IACH,QAAQ,CAAC,OAAe,EAAE,OAA6B;QACrD,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,YAAY,OAAO,EAAE,EAAE,OAAO,CAAC,CAAC;IAC1D,CAAC;IAED;;OAEG;IACH,MAAM,CAAC,OAAe,EAAE,OAA6B;QACnD,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,YAAY,OAAO,SAAS,EAAE,OAAO,CAAC,CAAC;IAClE,CAAC;CACF;AArBD,0BAqBC;AAgMD,WAAiB,OAAO;AAKxB,CAAC,EALgB,OAAO,GAAP,eAAO,KAAP,eAAO,QAKvB"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/batches.mjs b/backend/node_modules/openai/resources/batches.mjs new file mode 100644 index 0000000000000000000000000000000000000000..57e383453247320a308ca70e2a8f47ba166e6faf --- /dev/null +++ b/backend/node_modules/openai/resources/batches.mjs @@ -0,0 +1,25 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +import { APIResource } from 'openai/resource'; +export class Batches extends APIResource { + /** + * Creates and executes a batch from an uploaded file of requests + */ + create(body, options) { + return this._client.post('/batches', { body, ...options }); + } + /** + * Retrieves a batch. + */ + retrieve(batchId, options) { + return this._client.get(`/batches/${batchId}`, options); + } + /** + * Cancels an in-progress batch. + */ + cancel(batchId, options) { + return this._client.post(`/batches/${batchId}/cancel`, options); + } +} +(function (Batches) { +})(Batches || (Batches = {})); +//# sourceMappingURL=batches.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/batches.mjs.map b/backend/node_modules/openai/resources/batches.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..3da5e24d08371ad66b597fbc6d7504dfdd0e866a --- /dev/null +++ b/backend/node_modules/openai/resources/batches.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"batches.mjs","sourceRoot":"","sources":["../src/resources/batches.ts"],"names":[],"mappings":"AAAA,sFAAsF;OAG/E,EAAE,WAAW,EAAE,MAAM,iBAAiB;AAG7C,MAAM,OAAO,OAAQ,SAAQ,WAAW;IACtC;;OAEG;IACH,MAAM,CAAC,IAAuB,EAAE,OAA6B;QAC3D,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,UAAU,EAAE,EAAE,IAAI,EAAE,GAAG,OAAO,EAAE,CAAC,CAAC;IAC7D,CAAC;IAED;;OAEG;IACH,QAAQ,CAAC,OAAe,EAAE,OAA6B;QACrD,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,YAAY,OAAO,EAAE,EAAE,OAAO,CAAC,CAAC;IAC1D,CAAC;IAED;;OAEG;IACH,MAAM,CAAC,OAAe,EAAE,OAA6B;QACnD,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,YAAY,OAAO,SAAS,EAAE,OAAO,CAAC,CAAC;IAClE,CAAC;CACF;AAgMD,WAAiB,OAAO;AAKxB,CAAC,EALgB,OAAO,KAAP,OAAO,QAKvB"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/assistants/assistants.d.ts b/backend/node_modules/openai/resources/beta/assistants/assistants.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..37f5a929fdf0cd9136b590c2b7861f4f5e606250 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/assistants/assistants.d.ts @@ -0,0 +1,838 @@ +import * as Core from 'openai/core'; +import { APIResource } from 'openai/resource'; +import * as AssistantsAPI from 'openai/resources/beta/assistants/assistants'; +import * as Shared from 'openai/resources/shared'; +import * as FilesAPI from 'openai/resources/beta/assistants/files'; +import * as ThreadsAPI from 'openai/resources/beta/threads/threads'; +import * as MessagesAPI from 'openai/resources/beta/threads/messages/messages'; +import * as RunsAPI from 'openai/resources/beta/threads/runs/runs'; +import * as StepsAPI from 'openai/resources/beta/threads/runs/steps'; +import { CursorPage, type CursorPageParams } from 'openai/pagination'; +export declare class Assistants extends APIResource { + files: FilesAPI.Files; + /** + * Create an assistant with a model and instructions. + */ + create(body: AssistantCreateParams, options?: Core.RequestOptions): Core.APIPromise; + /** + * Retrieves an assistant. + */ + retrieve(assistantId: string, options?: Core.RequestOptions): Core.APIPromise; + /** + * Modifies an assistant. + */ + update(assistantId: string, body: AssistantUpdateParams, options?: Core.RequestOptions): Core.APIPromise; + /** + * Returns a list of assistants. + */ + list(query?: AssistantListParams, options?: Core.RequestOptions): Core.PagePromise; + list(options?: Core.RequestOptions): Core.PagePromise; + /** + * Delete an assistant. + */ + del(assistantId: string, options?: Core.RequestOptions): Core.APIPromise; +} +export declare class AssistantsPage extends CursorPage { +} +/** + * Represents an `assistant` that can call the model and use tools. + */ +export interface Assistant { + /** + * The identifier, which can be referenced in API endpoints. + */ + id: string; + /** + * The Unix timestamp (in seconds) for when the assistant was created. + */ + created_at: number; + /** + * The description of the assistant. The maximum length is 512 characters. + */ + description: string | null; + /** + * A list of [file](https://platform.openai.com/docs/api-reference/files) IDs + * attached to this assistant. There can be a maximum of 20 files attached to the + * assistant. Files are ordered by their creation date in ascending order. + */ + file_ids: Array; + /** + * The system instructions that the assistant uses. The maximum length is 256,000 + * characters. + */ + instructions: string | null; + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata: unknown | null; + /** + * ID of the model to use. You can use the + * [List models](https://platform.openai.com/docs/api-reference/models/list) API to + * see all of your available models, or see our + * [Model overview](https://platform.openai.com/docs/models/overview) for + * descriptions of them. + */ + model: string; + /** + * The name of the assistant. The maximum length is 256 characters. + */ + name: string | null; + /** + * The object type, which is always `assistant`. + */ + object: 'assistant'; + /** + * A list of tool enabled on the assistant. There can be a maximum of 128 tools per + * assistant. Tools can be of types `code_interpreter`, `retrieval`, or `function`. + */ + tools: Array; +} +export interface AssistantDeleted { + id: string; + deleted: boolean; + object: 'assistant.deleted'; +} +/** + * Represents an event emitted when streaming a Run. + * + * Each event in a server-sent events stream has an `event` and `data` property: + * + * ``` + * event: thread.created + * data: {"id": "thread_123", "object": "thread", ...} + * ``` + * + * We emit events whenever a new object is created, transitions to a new state, or + * is being streamed in parts (deltas). For example, we emit `thread.run.created` + * when a new run is created, `thread.run.completed` when a run completes, and so + * on. When an Assistant chooses to create a message during a run, we emit a + * `thread.message.created event`, a `thread.message.in_progress` event, many + * `thread.message.delta` events, and finally a `thread.message.completed` event. + * + * We may add additional events over time, so we recommend handling unknown events + * gracefully in your code. See the + * [Assistants API quickstart](https://platform.openai.com/docs/assistants/overview) + * to learn how to integrate the Assistants API with streaming. + */ +export type AssistantStreamEvent = AssistantStreamEvent.ThreadCreated | AssistantStreamEvent.ThreadRunCreated | AssistantStreamEvent.ThreadRunQueued | AssistantStreamEvent.ThreadRunInProgress | AssistantStreamEvent.ThreadRunRequiresAction | AssistantStreamEvent.ThreadRunCompleted | AssistantStreamEvent.ThreadRunFailed | AssistantStreamEvent.ThreadRunCancelling | AssistantStreamEvent.ThreadRunCancelled | AssistantStreamEvent.ThreadRunExpired | AssistantStreamEvent.ThreadRunStepCreated | AssistantStreamEvent.ThreadRunStepInProgress | AssistantStreamEvent.ThreadRunStepDelta | AssistantStreamEvent.ThreadRunStepCompleted | AssistantStreamEvent.ThreadRunStepFailed | AssistantStreamEvent.ThreadRunStepCancelled | AssistantStreamEvent.ThreadRunStepExpired | AssistantStreamEvent.ThreadMessageCreated | AssistantStreamEvent.ThreadMessageInProgress | AssistantStreamEvent.ThreadMessageDelta | AssistantStreamEvent.ThreadMessageCompleted | AssistantStreamEvent.ThreadMessageIncomplete | AssistantStreamEvent.ErrorEvent; +export declare namespace AssistantStreamEvent { + /** + * Occurs when a new + * [thread](https://platform.openai.com/docs/api-reference/threads/object) is + * created. + */ + interface ThreadCreated { + /** + * Represents a thread that contains + * [messages](https://platform.openai.com/docs/api-reference/messages). + */ + data: ThreadsAPI.Thread; + event: 'thread.created'; + } + /** + * Occurs when a new + * [run](https://platform.openai.com/docs/api-reference/runs/object) is created. + */ + interface ThreadRunCreated { + /** + * Represents an execution run on a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: RunsAPI.Run; + event: 'thread.run.created'; + } + /** + * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) + * moves to a `queued` status. + */ + interface ThreadRunQueued { + /** + * Represents an execution run on a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: RunsAPI.Run; + event: 'thread.run.queued'; + } + /** + * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) + * moves to an `in_progress` status. + */ + interface ThreadRunInProgress { + /** + * Represents an execution run on a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: RunsAPI.Run; + event: 'thread.run.in_progress'; + } + /** + * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) + * moves to a `requires_action` status. + */ + interface ThreadRunRequiresAction { + /** + * Represents an execution run on a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: RunsAPI.Run; + event: 'thread.run.requires_action'; + } + /** + * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) + * is completed. + */ + interface ThreadRunCompleted { + /** + * Represents an execution run on a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: RunsAPI.Run; + event: 'thread.run.completed'; + } + /** + * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) + * fails. + */ + interface ThreadRunFailed { + /** + * Represents an execution run on a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: RunsAPI.Run; + event: 'thread.run.failed'; + } + /** + * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) + * moves to a `cancelling` status. + */ + interface ThreadRunCancelling { + /** + * Represents an execution run on a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: RunsAPI.Run; + event: 'thread.run.cancelling'; + } + /** + * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) + * is cancelled. + */ + interface ThreadRunCancelled { + /** + * Represents an execution run on a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: RunsAPI.Run; + event: 'thread.run.cancelled'; + } + /** + * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) + * expires. + */ + interface ThreadRunExpired { + /** + * Represents an execution run on a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: RunsAPI.Run; + event: 'thread.run.expired'; + } + /** + * Occurs when a + * [run step](https://platform.openai.com/docs/api-reference/runs/step-object) is + * created. + */ + interface ThreadRunStepCreated { + /** + * Represents a step in execution of a run. + */ + data: StepsAPI.RunStep; + event: 'thread.run.step.created'; + } + /** + * Occurs when a + * [run step](https://platform.openai.com/docs/api-reference/runs/step-object) + * moves to an `in_progress` state. + */ + interface ThreadRunStepInProgress { + /** + * Represents a step in execution of a run. + */ + data: StepsAPI.RunStep; + event: 'thread.run.step.in_progress'; + } + /** + * Occurs when parts of a + * [run step](https://platform.openai.com/docs/api-reference/runs/step-object) are + * being streamed. + */ + interface ThreadRunStepDelta { + /** + * Represents a run step delta i.e. any changed fields on a run step during + * streaming. + */ + data: StepsAPI.RunStepDeltaEvent; + event: 'thread.run.step.delta'; + } + /** + * Occurs when a + * [run step](https://platform.openai.com/docs/api-reference/runs/step-object) is + * completed. + */ + interface ThreadRunStepCompleted { + /** + * Represents a step in execution of a run. + */ + data: StepsAPI.RunStep; + event: 'thread.run.step.completed'; + } + /** + * Occurs when a + * [run step](https://platform.openai.com/docs/api-reference/runs/step-object) + * fails. + */ + interface ThreadRunStepFailed { + /** + * Represents a step in execution of a run. + */ + data: StepsAPI.RunStep; + event: 'thread.run.step.failed'; + } + /** + * Occurs when a + * [run step](https://platform.openai.com/docs/api-reference/runs/step-object) is + * cancelled. + */ + interface ThreadRunStepCancelled { + /** + * Represents a step in execution of a run. + */ + data: StepsAPI.RunStep; + event: 'thread.run.step.cancelled'; + } + /** + * Occurs when a + * [run step](https://platform.openai.com/docs/api-reference/runs/step-object) + * expires. + */ + interface ThreadRunStepExpired { + /** + * Represents a step in execution of a run. + */ + data: StepsAPI.RunStep; + event: 'thread.run.step.expired'; + } + /** + * Occurs when a + * [message](https://platform.openai.com/docs/api-reference/messages/object) is + * created. + */ + interface ThreadMessageCreated { + /** + * Represents a message within a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: MessagesAPI.Message; + event: 'thread.message.created'; + } + /** + * Occurs when a + * [message](https://platform.openai.com/docs/api-reference/messages/object) moves + * to an `in_progress` state. + */ + interface ThreadMessageInProgress { + /** + * Represents a message within a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: MessagesAPI.Message; + event: 'thread.message.in_progress'; + } + /** + * Occurs when parts of a + * [Message](https://platform.openai.com/docs/api-reference/messages/object) are + * being streamed. + */ + interface ThreadMessageDelta { + /** + * Represents a message delta i.e. any changed fields on a message during + * streaming. + */ + data: MessagesAPI.MessageDeltaEvent; + event: 'thread.message.delta'; + } + /** + * Occurs when a + * [message](https://platform.openai.com/docs/api-reference/messages/object) is + * completed. + */ + interface ThreadMessageCompleted { + /** + * Represents a message within a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: MessagesAPI.Message; + event: 'thread.message.completed'; + } + /** + * Occurs when a + * [message](https://platform.openai.com/docs/api-reference/messages/object) ends + * before it is completed. + */ + interface ThreadMessageIncomplete { + /** + * Represents a message within a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: MessagesAPI.Message; + event: 'thread.message.incomplete'; + } + /** + * Occurs when an + * [error](https://platform.openai.com/docs/guides/error-codes/api-errors) occurs. + * This can happen due to an internal server error or a timeout. + */ + interface ErrorEvent { + data: Shared.ErrorObject; + event: 'error'; + } +} +export type AssistantTool = CodeInterpreterTool | RetrievalTool | FunctionTool; +export interface CodeInterpreterTool { + /** + * The type of tool being defined: `code_interpreter` + */ + type: 'code_interpreter'; +} +export interface FunctionTool { + function: Shared.FunctionDefinition; + /** + * The type of tool being defined: `function` + */ + type: 'function'; +} +/** + * Occurs when a + * [message](https://platform.openai.com/docs/api-reference/messages/object) is + * created. + */ +export type MessageStreamEvent = MessageStreamEvent.ThreadMessageCreated | MessageStreamEvent.ThreadMessageInProgress | MessageStreamEvent.ThreadMessageDelta | MessageStreamEvent.ThreadMessageCompleted | MessageStreamEvent.ThreadMessageIncomplete; +export declare namespace MessageStreamEvent { + /** + * Occurs when a + * [message](https://platform.openai.com/docs/api-reference/messages/object) is + * created. + */ + interface ThreadMessageCreated { + /** + * Represents a message within a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: MessagesAPI.Message; + event: 'thread.message.created'; + } + /** + * Occurs when a + * [message](https://platform.openai.com/docs/api-reference/messages/object) moves + * to an `in_progress` state. + */ + interface ThreadMessageInProgress { + /** + * Represents a message within a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: MessagesAPI.Message; + event: 'thread.message.in_progress'; + } + /** + * Occurs when parts of a + * [Message](https://platform.openai.com/docs/api-reference/messages/object) are + * being streamed. + */ + interface ThreadMessageDelta { + /** + * Represents a message delta i.e. any changed fields on a message during + * streaming. + */ + data: MessagesAPI.MessageDeltaEvent; + event: 'thread.message.delta'; + } + /** + * Occurs when a + * [message](https://platform.openai.com/docs/api-reference/messages/object) is + * completed. + */ + interface ThreadMessageCompleted { + /** + * Represents a message within a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: MessagesAPI.Message; + event: 'thread.message.completed'; + } + /** + * Occurs when a + * [message](https://platform.openai.com/docs/api-reference/messages/object) ends + * before it is completed. + */ + interface ThreadMessageIncomplete { + /** + * Represents a message within a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: MessagesAPI.Message; + event: 'thread.message.incomplete'; + } +} +export interface RetrievalTool { + /** + * The type of tool being defined: `retrieval` + */ + type: 'retrieval'; +} +/** + * Occurs when a + * [run step](https://platform.openai.com/docs/api-reference/runs/step-object) is + * created. + */ +export type RunStepStreamEvent = RunStepStreamEvent.ThreadRunStepCreated | RunStepStreamEvent.ThreadRunStepInProgress | RunStepStreamEvent.ThreadRunStepDelta | RunStepStreamEvent.ThreadRunStepCompleted | RunStepStreamEvent.ThreadRunStepFailed | RunStepStreamEvent.ThreadRunStepCancelled | RunStepStreamEvent.ThreadRunStepExpired; +export declare namespace RunStepStreamEvent { + /** + * Occurs when a + * [run step](https://platform.openai.com/docs/api-reference/runs/step-object) is + * created. + */ + interface ThreadRunStepCreated { + /** + * Represents a step in execution of a run. + */ + data: StepsAPI.RunStep; + event: 'thread.run.step.created'; + } + /** + * Occurs when a + * [run step](https://platform.openai.com/docs/api-reference/runs/step-object) + * moves to an `in_progress` state. + */ + interface ThreadRunStepInProgress { + /** + * Represents a step in execution of a run. + */ + data: StepsAPI.RunStep; + event: 'thread.run.step.in_progress'; + } + /** + * Occurs when parts of a + * [run step](https://platform.openai.com/docs/api-reference/runs/step-object) are + * being streamed. + */ + interface ThreadRunStepDelta { + /** + * Represents a run step delta i.e. any changed fields on a run step during + * streaming. + */ + data: StepsAPI.RunStepDeltaEvent; + event: 'thread.run.step.delta'; + } + /** + * Occurs when a + * [run step](https://platform.openai.com/docs/api-reference/runs/step-object) is + * completed. + */ + interface ThreadRunStepCompleted { + /** + * Represents a step in execution of a run. + */ + data: StepsAPI.RunStep; + event: 'thread.run.step.completed'; + } + /** + * Occurs when a + * [run step](https://platform.openai.com/docs/api-reference/runs/step-object) + * fails. + */ + interface ThreadRunStepFailed { + /** + * Represents a step in execution of a run. + */ + data: StepsAPI.RunStep; + event: 'thread.run.step.failed'; + } + /** + * Occurs when a + * [run step](https://platform.openai.com/docs/api-reference/runs/step-object) is + * cancelled. + */ + interface ThreadRunStepCancelled { + /** + * Represents a step in execution of a run. + */ + data: StepsAPI.RunStep; + event: 'thread.run.step.cancelled'; + } + /** + * Occurs when a + * [run step](https://platform.openai.com/docs/api-reference/runs/step-object) + * expires. + */ + interface ThreadRunStepExpired { + /** + * Represents a step in execution of a run. + */ + data: StepsAPI.RunStep; + event: 'thread.run.step.expired'; + } +} +/** + * Occurs when a new + * [run](https://platform.openai.com/docs/api-reference/runs/object) is created. + */ +export type RunStreamEvent = RunStreamEvent.ThreadRunCreated | RunStreamEvent.ThreadRunQueued | RunStreamEvent.ThreadRunInProgress | RunStreamEvent.ThreadRunRequiresAction | RunStreamEvent.ThreadRunCompleted | RunStreamEvent.ThreadRunFailed | RunStreamEvent.ThreadRunCancelling | RunStreamEvent.ThreadRunCancelled | RunStreamEvent.ThreadRunExpired; +export declare namespace RunStreamEvent { + /** + * Occurs when a new + * [run](https://platform.openai.com/docs/api-reference/runs/object) is created. + */ + interface ThreadRunCreated { + /** + * Represents an execution run on a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: RunsAPI.Run; + event: 'thread.run.created'; + } + /** + * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) + * moves to a `queued` status. + */ + interface ThreadRunQueued { + /** + * Represents an execution run on a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: RunsAPI.Run; + event: 'thread.run.queued'; + } + /** + * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) + * moves to an `in_progress` status. + */ + interface ThreadRunInProgress { + /** + * Represents an execution run on a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: RunsAPI.Run; + event: 'thread.run.in_progress'; + } + /** + * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) + * moves to a `requires_action` status. + */ + interface ThreadRunRequiresAction { + /** + * Represents an execution run on a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: RunsAPI.Run; + event: 'thread.run.requires_action'; + } + /** + * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) + * is completed. + */ + interface ThreadRunCompleted { + /** + * Represents an execution run on a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: RunsAPI.Run; + event: 'thread.run.completed'; + } + /** + * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) + * fails. + */ + interface ThreadRunFailed { + /** + * Represents an execution run on a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: RunsAPI.Run; + event: 'thread.run.failed'; + } + /** + * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) + * moves to a `cancelling` status. + */ + interface ThreadRunCancelling { + /** + * Represents an execution run on a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: RunsAPI.Run; + event: 'thread.run.cancelling'; + } + /** + * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) + * is cancelled. + */ + interface ThreadRunCancelled { + /** + * Represents an execution run on a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: RunsAPI.Run; + event: 'thread.run.cancelled'; + } + /** + * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) + * expires. + */ + interface ThreadRunExpired { + /** + * Represents an execution run on a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: RunsAPI.Run; + event: 'thread.run.expired'; + } +} +/** + * Occurs when a new + * [thread](https://platform.openai.com/docs/api-reference/threads/object) is + * created. + */ +export interface ThreadStreamEvent { + /** + * Represents a thread that contains + * [messages](https://platform.openai.com/docs/api-reference/messages). + */ + data: ThreadsAPI.Thread; + event: 'thread.created'; +} +export interface AssistantCreateParams { + /** + * ID of the model to use. You can use the + * [List models](https://platform.openai.com/docs/api-reference/models/list) API to + * see all of your available models, or see our + * [Model overview](https://platform.openai.com/docs/models/overview) for + * descriptions of them. + */ + model: (string & {}) | 'gpt-4-turbo' | 'gpt-4-turbo-2024-04-09' | 'gpt-4-0125-preview' | 'gpt-4-turbo-preview' | 'gpt-4-1106-preview' | 'gpt-4-vision-preview' | 'gpt-4' | 'gpt-4-0314' | 'gpt-4-0613' | 'gpt-4-32k' | 'gpt-4-32k-0314' | 'gpt-4-32k-0613' | 'gpt-3.5-turbo' | 'gpt-3.5-turbo-16k' | 'gpt-3.5-turbo-0613' | 'gpt-3.5-turbo-1106' | 'gpt-3.5-turbo-0125' | 'gpt-3.5-turbo-16k-0613'; + /** + * The description of the assistant. The maximum length is 512 characters. + */ + description?: string | null; + /** + * A list of [file](https://platform.openai.com/docs/api-reference/files) IDs + * attached to this assistant. There can be a maximum of 20 files attached to the + * assistant. Files are ordered by their creation date in ascending order. + */ + file_ids?: Array; + /** + * The system instructions that the assistant uses. The maximum length is 256,000 + * characters. + */ + instructions?: string | null; + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata?: unknown | null; + /** + * The name of the assistant. The maximum length is 256 characters. + */ + name?: string | null; + /** + * A list of tool enabled on the assistant. There can be a maximum of 128 tools per + * assistant. Tools can be of types `code_interpreter`, `retrieval`, or `function`. + */ + tools?: Array; +} +export interface AssistantUpdateParams { + /** + * The description of the assistant. The maximum length is 512 characters. + */ + description?: string | null; + /** + * A list of [File](https://platform.openai.com/docs/api-reference/files) IDs + * attached to this assistant. There can be a maximum of 20 files attached to the + * assistant. Files are ordered by their creation date in ascending order. If a + * file was previously attached to the list but does not show up in the list, it + * will be deleted from the assistant. + */ + file_ids?: Array; + /** + * The system instructions that the assistant uses. The maximum length is 256,000 + * characters. + */ + instructions?: string | null; + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata?: unknown | null; + /** + * ID of the model to use. You can use the + * [List models](https://platform.openai.com/docs/api-reference/models/list) API to + * see all of your available models, or see our + * [Model overview](https://platform.openai.com/docs/models/overview) for + * descriptions of them. + */ + model?: string; + /** + * The name of the assistant. The maximum length is 256 characters. + */ + name?: string | null; + /** + * A list of tool enabled on the assistant. There can be a maximum of 128 tools per + * assistant. Tools can be of types `code_interpreter`, `retrieval`, or `function`. + */ + tools?: Array; +} +export interface AssistantListParams extends CursorPageParams { + /** + * A cursor for use in pagination. `before` is an object ID that defines your place + * in the list. For instance, if you make a list request and receive 100 objects, + * ending with obj_foo, your subsequent call can include before=obj_foo in order to + * fetch the previous page of the list. + */ + before?: string; + /** + * Sort order by the `created_at` timestamp of the objects. `asc` for ascending + * order and `desc` for descending order. + */ + order?: 'asc' | 'desc'; +} +export declare namespace Assistants { + export import Assistant = AssistantsAPI.Assistant; + export import AssistantDeleted = AssistantsAPI.AssistantDeleted; + export import AssistantStreamEvent = AssistantsAPI.AssistantStreamEvent; + export import AssistantTool = AssistantsAPI.AssistantTool; + export import CodeInterpreterTool = AssistantsAPI.CodeInterpreterTool; + export import FunctionTool = AssistantsAPI.FunctionTool; + export import MessageStreamEvent = AssistantsAPI.MessageStreamEvent; + export import RetrievalTool = AssistantsAPI.RetrievalTool; + export import RunStepStreamEvent = AssistantsAPI.RunStepStreamEvent; + export import RunStreamEvent = AssistantsAPI.RunStreamEvent; + export import ThreadStreamEvent = AssistantsAPI.ThreadStreamEvent; + export import AssistantsPage = AssistantsAPI.AssistantsPage; + export import AssistantCreateParams = AssistantsAPI.AssistantCreateParams; + export import AssistantUpdateParams = AssistantsAPI.AssistantUpdateParams; + export import AssistantListParams = AssistantsAPI.AssistantListParams; + export import Files = FilesAPI.Files; + export import AssistantFile = FilesAPI.AssistantFile; + export import FileDeleteResponse = FilesAPI.FileDeleteResponse; + export import AssistantFilesPage = FilesAPI.AssistantFilesPage; + export import FileCreateParams = FilesAPI.FileCreateParams; + export import FileListParams = FilesAPI.FileListParams; +} +//# sourceMappingURL=assistants.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/assistants/assistants.d.ts.map b/backend/node_modules/openai/resources/beta/assistants/assistants.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..6fa16cd3f991217e0c712baf4158b865bc1013a7 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/assistants/assistants.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"assistants.d.ts","sourceRoot":"","sources":["../../../src/resources/beta/assistants/assistants.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,IAAI,MAAM,aAAa,CAAC;AACpC,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAE9C,OAAO,KAAK,aAAa,MAAM,6CAA6C,CAAC;AAC7E,OAAO,KAAK,MAAM,MAAM,yBAAyB,CAAC;AAClD,OAAO,KAAK,QAAQ,MAAM,wCAAwC,CAAC;AACnE,OAAO,KAAK,UAAU,MAAM,uCAAuC,CAAC;AACpE,OAAO,KAAK,WAAW,MAAM,iDAAiD,CAAC;AAC/E,OAAO,KAAK,OAAO,MAAM,yCAAyC,CAAC;AACnE,OAAO,KAAK,QAAQ,MAAM,0CAA0C,CAAC;AACrE,OAAO,EAAE,UAAU,EAAE,KAAK,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAEtE,qBAAa,UAAW,SAAQ,WAAW;IACzC,KAAK,EAAE,QAAQ,CAAC,KAAK,CAAoC;IAEzD;;OAEG;IACH,MAAM,CAAC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B,GAAG,aAAa,CAAC,kBAAkB,CAAC;IACpE,MAAM,QAAQ,aAAa,GAAG,aAAa,CAAC,aAAa,CAAC;IAC1D,MAAM,QAAQ,kBAAkB,GAAG,aAAa,CAAC,kBAAkB,CAAC;IACpE,MAAM,QAAQ,cAAc,GAAG,aAAa,CAAC,cAAc,CAAC;IAC5D,MAAM,QAAQ,iBAAiB,GAAG,aAAa,CAAC,iBAAiB,CAAC;IAClE,MAAM,QAAQ,cAAc,GAAG,aAAa,CAAC,cAAc,CAAC;IAC5D,MAAM,QAAQ,qBAAqB,GAAG,aAAa,CAAC,qBAAqB,CAAC;IAC1E,MAAM,QAAQ,qBAAqB,GAAG,aAAa,CAAC,qBAAqB,CAAC;IAC1E,MAAM,QAAQ,mBAAmB,GAAG,aAAa,CAAC,mBAAmB,CAAC;IACtE,MAAM,QAAQ,KAAK,GAAG,QAAQ,CAAC,KAAK,CAAC;IACrC,MAAM,QAAQ,aAAa,GAAG,QAAQ,CAAC,aAAa,CAAC;IACrD,MAAM,QAAQ,kBAAkB,GAAG,QAAQ,CAAC,kBAAkB,CAAC;IAC/D,MAAM,QAAQ,kBAAkB,GAAG,QAAQ,CAAC,kBAAkB,CAAC;IAC/D,MAAM,QAAQ,gBAAgB,GAAG,QAAQ,CAAC,gBAAgB,CAAC;IAC3D,MAAM,QAAQ,cAAc,GAAG,QAAQ,CAAC,cAAc,CAAC;CACxD"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/assistants/assistants.js b/backend/node_modules/openai/resources/beta/assistants/assistants.js new file mode 100644 index 0000000000000000000000000000000000000000..1996183cef19f6d2cc46f64ed64bd4c1ac9dd727 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/assistants/assistants.js @@ -0,0 +1,96 @@ +"use strict"; +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AssistantsPage = exports.Assistants = void 0; +const resource_1 = require("openai/resource"); +const core_1 = require("openai/core"); +const AssistantsAPI = __importStar(require("openai/resources/beta/assistants/assistants")); +const FilesAPI = __importStar(require("openai/resources/beta/assistants/files")); +const pagination_1 = require("openai/pagination"); +class Assistants extends resource_1.APIResource { + constructor() { + super(...arguments); + this.files = new FilesAPI.Files(this._client); + } + /** + * Create an assistant with a model and instructions. + */ + create(body, options) { + return this._client.post('/assistants', { + body, + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } + /** + * Retrieves an assistant. + */ + retrieve(assistantId, options) { + return this._client.get(`/assistants/${assistantId}`, { + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } + /** + * Modifies an assistant. + */ + update(assistantId, body, options) { + return this._client.post(`/assistants/${assistantId}`, { + body, + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } + list(query = {}, options) { + if ((0, core_1.isRequestOptions)(query)) { + return this.list({}, query); + } + return this._client.getAPIList('/assistants', AssistantsPage, { + query, + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } + /** + * Delete an assistant. + */ + del(assistantId, options) { + return this._client.delete(`/assistants/${assistantId}`, { + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } +} +exports.Assistants = Assistants; +class AssistantsPage extends pagination_1.CursorPage { +} +exports.AssistantsPage = AssistantsPage; +(function (Assistants) { + Assistants.AssistantsPage = AssistantsAPI.AssistantsPage; + Assistants.Files = FilesAPI.Files; + Assistants.AssistantFilesPage = FilesAPI.AssistantFilesPage; +})(Assistants = exports.Assistants || (exports.Assistants = {})); +//# sourceMappingURL=assistants.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/assistants/assistants.js.map b/backend/node_modules/openai/resources/beta/assistants/assistants.js.map new file mode 100644 index 0000000000000000000000000000000000000000..2e2276de7ecaeb209412a12e37631edd384701e8 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/assistants/assistants.js.map @@ -0,0 +1 @@ +{"version":3,"file":"assistants.js","sourceRoot":"","sources":["../../../src/resources/beta/assistants/assistants.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;;;;;;;;;;;;;;;;;;;;;;;;AAGtF,8CAA8C;AAC9C,sCAA+C;AAC/C,2FAA6E;AAE7E,iFAAmE;AAKnE,kDAAsE;AAEtE,MAAa,UAAW,SAAQ,sBAAW;IAA3C;;QACE,UAAK,GAAmB,IAAI,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IAqE3D,CAAC;IAnEC;;OAEG;IACH,MAAM,CAAC,IAA2B,EAAE,OAA6B;QAC/D,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,aAAa,EAAE;YACtC,IAAI;YACJ,GAAG,OAAO;YACV,OAAO,EAAE,EAAE,aAAa,EAAE,eAAe,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE;SACjE,CAAC,CAAC;IACL,CAAC;IAED;;OAEG;IACH,QAAQ,CAAC,WAAmB,EAAE,OAA6B;QACzD,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,eAAe,WA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B,GAAG,QAAQ,CAAC,kBAAkB,CAAC;AAGjE,CAAC,EAtBgB,UAAU,GAAV,kBAAU,KAAV,kBAAU,QAsB1B"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/assistants/assistants.mjs b/backend/node_modules/openai/resources/beta/assistants/assistants.mjs new file mode 100644 index 0000000000000000000000000000000000000000..cac5df0a9f28641b16447196bcf8e629e087a825 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/assistants/assistants.mjs @@ -0,0 +1,68 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +import { APIResource } from 'openai/resource'; +import { isRequestOptions } from 'openai/core'; +import * as AssistantsAPI from 'openai/resources/beta/assistants/assistants'; +import * as FilesAPI from 'openai/resources/beta/assistants/files'; +import { CursorPage } from 'openai/pagination'; +export class Assistants extends APIResource { + constructor() { + super(...arguments); + this.files = new FilesAPI.Files(this._client); + } + /** + * Create an assistant with a model and instructions. + */ + create(body, options) { + return this._client.post('/assistants', { + body, + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } + /** + * Retrieves an assistant. + */ + retrieve(assistantId, options) { + return this._client.get(`/assistants/${assistantId}`, { + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } + /** + * Modifies an assistant. + */ + update(assistantId, body, options) { + return this._client.post(`/assistants/${assistantId}`, { + body, + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } + list(query = {}, options) { + if (isRequestOptions(query)) { + return this.list({}, query); + } + return this._client.getAPIList('/assistants', AssistantsPage, { + query, + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } + /** + * Delete an assistant. + */ + del(assistantId, options) { + return this._client.delete(`/assistants/${assistantId}`, { + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } +} +export class AssistantsPage extends CursorPage { +} +(function (Assistants) { + Assistants.AssistantsPage = AssistantsAPI.AssistantsPage; + Assistants.Files = FilesAPI.Files; + Assistants.AssistantFilesPage = FilesAPI.AssistantFilesPage; +})(Assistants || (Assistants = {})); +//# sourceMappingURL=assistants.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/assistants/assistants.mjs.map b/backend/node_modules/openai/resources/beta/assistants/assistants.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..b58073a096469c409f0693a29992f26c5d6509c1 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/assistants/assistants.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"assistants.mjs","sourceRoot":"","sources":["../../../src/resources/beta/assistants/assistants.ts"],"names":[],"mappings":"AAAA,sFAAsF;OAG/E,EAAE,WAAW,EAAE,MAAM,iBAAiB;OACtC,EAAE,gBAAgB,EAAE,MAAM,aAAa;OACvC,KAAK,aAAa,MAAM,6CAA6C;OAErE,KAAK,QAAQ,MAAM,wCAAwC;OAK3D,EAAE,UAAU,EAAyB,MAAM,mBAAmB;AAErE,MAAM,OAAO,UAAW,SAAQ,WAAW;IAA3C;;QACE,UAAK,GAAmB,IAAI,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IAqE3D,CAAC;IAnEC;;OAEG;IACH,MAAM,CAAC,IAA2B,EAAE,OAA6B;QAC/D,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,aAAa,EAAE;YACtC,IAAI;YACJ,GAAG,OAAO;YACV,OAAO,EAAE,EAAE,aAAa,EAAE,eAAe,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE;SACjE,CAAC,CAAC;IACL,CAAC;IAED;;OAEG;IACH,QAAQ,CAAC,WAAmB,EAAE,OAA6B;QACzD,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,eAAe,WAAW,EAAE,EAAE;YACpD,GAAG,OAAO;YACV,OAAO,EAAE,EAAE,aAAa,EAAE,eAAe,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE;SACjE,CAAC,CAAC;IACL,CAAC;IAED;;OAEG;IACH,MAAM,CACJ,WAAmB,EACnB,IAA2B,EAC3B,OAA6B;QAE7B,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,eAAe,WAAW,EAAE,EAAE;YACrD,IAAI;YACJ,GAAG,OAAO;YACV,OAAO,EAAE,EAAE,aAAa,EAAE,eAAe,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE;SACjE,CAAC,CAAC;IACL,CAAC;IAUD,IAAI,CACF,QAAmD,EAAE,EACrD,OAA6B;QAE7B,IAAI,gBAAgB,CAAC,KAAK,CAAC,EAAE;YAC3B,OAAO,IAAI,CAAC,IAAI,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC;SAC7B;QACD,OAAO,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,aAAa,EAAE,cAAc,EAAE;YAC5D,KAAK;YACL,GAAG,OAAO;YACV,OAAO,EAAE,EAAE,aAAa,EAAE,eAAe,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE;SACjE,CAAC,CAAC;IACL,CAAC;IAED;;OAEG;IACH,GAAG,CAAC,WAAmB,EAAE,OAA6B;QACpD,OAAO,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,eAAe,WAAW,EAAE,EAAE;YACvD,GAAG,OAAO;YACV,OAAO,EAAE,EAAE,aAAa,EAAE,eAAe,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE;SACjE,CAAC,CAAC;IACL,CAAC;CACF;AAED,MAAM,OAAO,cAAe,SAAQ,UAAqB;CAAG;AA28B5D,WAAiB,UAAU;IAYX,yBAAc,GAAG,aAAa,CAAC,cAAc,CAAC;IAI9C,gBAAK,GAAG,QAAQ,CAAC,KAAK,CAAC;IAGvB,6BAAkB,GAAG,QAAQ,CAAC,kBAAkB,CAAC;AAGjE,CAAC,EAtBgB,UAAU,KAAV,UAAU,QAsB1B"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/assistants/files.d.ts b/backend/node_modules/openai/resources/beta/assistants/files.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d6aec3e48ef153cb41d1511c18a4ed21bdd2e981 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/assistants/files.d.ts @@ -0,0 +1,88 @@ +import * as Core from 'openai/core'; +import { APIResource } from 'openai/resource'; +import * as FilesAPI from 'openai/resources/beta/assistants/files'; +import { CursorPage, type CursorPageParams } from 'openai/pagination'; +export declare class Files extends APIResource { + /** + * Create an assistant file by attaching a + * [File](https://platform.openai.com/docs/api-reference/files) to an + * [assistant](https://platform.openai.com/docs/api-reference/assistants). + */ + create(assistantId: string, body: FileCreateParams, options?: Core.RequestOptions): Core.APIPromise; + /** + * Retrieves an AssistantFile. + */ + retrieve(assistantId: string, fileId: string, options?: Core.RequestOptions): Core.APIPromise; + /** + * Returns a list of assistant files. + */ + list(assistantId: string, query?: FileListParams, options?: Core.RequestOptions): Core.PagePromise; + list(assistantId: string, options?: Core.RequestOptions): Core.PagePromise; + /** + * Delete an assistant file. + */ + del(assistantId: string, fileId: string, options?: Core.RequestOptions): Core.APIPromise; +} +export declare class AssistantFilesPage extends CursorPage { +} +/** + * A list of [Files](https://platform.openai.com/docs/api-reference/files) attached + * to an `assistant`. + */ +export interface AssistantFile { + /** + * The identifier, which can be referenced in API endpoints. + */ + id: string; + /** + * The assistant ID that the file is attached to. + */ + assistant_id: string; + /** + * The Unix timestamp (in seconds) for when the assistant file was created. + */ + created_at: number; + /** + * The object type, which is always `assistant.file`. + */ + object: 'assistant.file'; +} +/** + * Deletes the association between the assistant and the file, but does not delete + * the [File](https://platform.openai.com/docs/api-reference/files) object itself. + */ +export interface FileDeleteResponse { + id: string; + deleted: boolean; + object: 'assistant.file.deleted'; +} +export interface FileCreateParams { + /** + * A [File](https://platform.openai.com/docs/api-reference/files) ID (with + * `purpose="assistants"`) that the assistant should use. Useful for tools like + * `retrieval` and `code_interpreter` that can access files. + */ + file_id: string; +} +export interface FileListParams extends CursorPageParams { + /** + * A cursor for use in pagination. `before` is an object ID that defines your place + * in the list. For instance, if you make a list request and receive 100 objects, + * ending with obj_foo, your subsequent call can include before=obj_foo in order to + * fetch the previous page of the list. + */ + before?: string; + /** + * Sort order by the `created_at` timestamp of the objects. `asc` for ascending + * order and `desc` for descending order. + */ + order?: 'asc' | 'desc'; +} +export declare namespace Files { + export import AssistantFile = FilesAPI.AssistantFile; + export import FileDeleteResponse = FilesAPI.FileDeleteResponse; + export import AssistantFilesPage = FilesAPI.AssistantFilesPage; + export import FileCreateParams = FilesAPI.FileCreateParams; + export import FileListParams = FilesAPI.FileListParams; +} +//# sourceMappingURL=files.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/assistants/files.d.ts.map b/backend/node_modules/openai/resources/beta/assistants/files.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..c62a32fabaec2f2a50290e9210d15187c29ee0d2 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/assistants/files.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"files.d.ts","sourceRoot":"","sources":["../../../src/resources/beta/assistants/files.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,IAAI,MAAM,aAAa,CAAC;AACpC,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAE9C,OAAO,KAAK,QAAQ,MAAM,wCAAwC,CAAC;AACnE,OAAO,EAAE,UAAU,EAAE,KAAK,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAEtE,qBAAa,KAAM,SAAQ,WAAW;IACpC;;;;OAIG;IACH,MAAM,CACJ,WAAW,EAAE,MAAM,EACnB,IAAI,EAAE,gBAAgB,EACtB,OAAO,CAAC,EAAE,IAAI,CAAC,cAAc,GAC5B,IAAI,CAAC,UAAU,CAAC,aAAa,CAAC;IAQjC;;OAEG;IACH,QAAQ,CACN,WAAW,EAAE,MAAM,EACnB,MAAM,EAAE,MAAM,EACd,OAAO,CAAC,EAAE,IAAI,CAAC,cAAc,GAC5B,IAAI,CAAC,UAAU,CA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D,MAAM,QAAQ,kBAAkB,GAAG,QAAQ,CAAC,kBAAkB,CAAC;IAC/D,MAAM,QAAQ,kBAAkB,GAAG,QAAQ,CAAC,kBAAkB,CAAC;IAC/D,MAAM,QAAQ,gBAAgB,GAAG,QAAQ,CAAC,gBAAgB,CAAC;IAC3D,MAAM,QAAQ,cAAc,GAAG,QAAQ,CAAC,cAAc,CAAC;CACxD"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/assistants/files.js b/backend/node_modules/openai/resources/beta/assistants/files.js new file mode 100644 index 0000000000000000000000000000000000000000..c638edcf15c79783659374e8d31f42258f7669d6 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/assistants/files.js @@ -0,0 +1,81 @@ +"use strict"; +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AssistantFilesPage = exports.Files = void 0; +const resource_1 = require("openai/resource"); +const core_1 = require("openai/core"); +const FilesAPI = __importStar(require("openai/resources/beta/assistants/files")); +const pagination_1 = require("openai/pagination"); +class Files extends resource_1.APIResource { + /** + * Create an assistant file by attaching a + * [File](https://platform.openai.com/docs/api-reference/files) to an + * [assistant](https://platform.openai.com/docs/api-reference/assistants). + */ + create(assistantId, body, options) { + return this._client.post(`/assistants/${assistantId}/files`, { + body, + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } + /** + * Retrieves an AssistantFile. + */ + retrieve(assistantId, fileId, options) { + return this._client.get(`/assistants/${assistantId}/files/${fileId}`, { + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } + list(assistantId, query = {}, options) { + if ((0, core_1.isRequestOptions)(query)) { + return this.list(assistantId, {}, query); + } + return this._client.getAPIList(`/assistants/${assistantId}/files`, AssistantFilesPage, { + query, + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } + /** + * Delete an assistant file. + */ + del(assistantId, fileId, options) { + return this._client.delete(`/assistants/${assistantId}/files/${fileId}`, { + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } +} +exports.Files = Files; +class AssistantFilesPage extends pagination_1.CursorPage { +} +exports.AssistantFilesPage = AssistantFilesPage; +(function (Files) { + Files.AssistantFilesPage = FilesAPI.AssistantFilesPage; +})(Files = exports.Files || (exports.Files = {})); +//# sourceMappingURL=files.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/assistants/files.js.map b/backend/node_modules/openai/resources/beta/assistants/files.js.map new file mode 100644 index 0000000000000000000000000000000000000000..acc46731055e09ffbd10a07de1c8c8f633dd4697 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/assistants/files.js.map @@ -0,0 +1 @@ +{"version":3,"file":"files.js","sourceRoot":"","sources":["../../../src/resources/beta/assistants/files.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;;;;;;;;;;;;;;;;;;;;;;;;AAGtF,8CAA8C;AAC9C,sCAA+C;AAC/C,iFAAmE;AACnE,kDAAsE;AAEtE,MAAa,KAAM,SAAQ,sBAAW;IACpC;;;;OAIG;IACH,MAAM,C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a,kBAAmB,SAAQ,uBAAyB;CAAG;AAApE,gDAAoE;AAiEpE,WAAiB,KAAK;IAGN,wBAAkB,GAAG,QAAQ,CAAC,kBAAkB,CAAC;AAGjE,CAAC,EANgB,KAAK,GAAL,aAAK,KAAL,aAAK,QAMrB"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/assistants/files.mjs b/backend/node_modules/openai/resources/beta/assistants/files.mjs new file mode 100644 index 0000000000000000000000000000000000000000..01067f927203285c699459711ae8035bce1761f2 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/assistants/files.mjs @@ -0,0 +1,53 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +import { APIResource } from 'openai/resource'; +import { isRequestOptions } from 'openai/core'; +import * as FilesAPI from 'openai/resources/beta/assistants/files'; +import { CursorPage } from 'openai/pagination'; +export class Files extends APIResource { + /** + * Create an assistant file by attaching a + * [File](https://platform.openai.com/docs/api-reference/files) to an + * [assistant](https://platform.openai.com/docs/api-reference/assistants). + */ + create(assistantId, body, options) { + return this._client.post(`/assistants/${assistantId}/files`, { + body, + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } + /** + * Retrieves an AssistantFile. + */ + retrieve(assistantId, fileId, options) { + return this._client.get(`/assistants/${assistantId}/files/${fileId}`, { + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } + list(assistantId, query = {}, options) { + if (isRequestOptions(query)) { + return this.list(assistantId, {}, query); + } + return this._client.getAPIList(`/assistants/${assistantId}/files`, AssistantFilesPage, { + query, + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } + /** + * Delete an assistant file. + */ + del(assistantId, fileId, options) { + return this._client.delete(`/assistants/${assistantId}/files/${fileId}`, { + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } +} +export class AssistantFilesPage extends CursorPage { +} +(function (Files) { + Files.AssistantFilesPage = FilesAPI.AssistantFilesPage; +})(Files || (Files = {})); +//# sourceMappingURL=files.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/assistants/files.mjs.map b/backend/node_modules/openai/resources/beta/assistants/files.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..a7d041298591e7bfc0bd7f8328edba2175134720 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/assistants/files.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"files.mjs","sourceRoot":"","sources":["../../../src/resources/beta/assistants/files.ts"],"names":[],"mappings":"AAAA,sFAAsF;OAG/E,EAAE,WAAW,EAAE,MAAM,iBAAiB;OACtC,EAAE,gBAAgB,EAAE,MAAM,aAAa;OACvC,KAAK,QAAQ,MAAM,wCAAwC;OAC3D,EAAE,UAAU,EAAyB,MAAM,mBAAmB;AAErE,MAAM,OAAO,KAAM,SAAQ,WAAW;IACpC;;;;OAIG;IACH,MAAM,CACJ,WAAmB,EACnB,IAAsB,EACtB,OAA6B;QAE7B,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,eAAe,WAAW,QAAQ,EAAE;YAC3D,IAAI;YACJ,GAAG,OAAO;YACV,OAAO,EAAE,EAAE,aAAa,EAAE,eAAe,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE;SACjE,CAAC,CAAC;IACL,CAAC;IAED;;OAEG;IACH,QAAQ,CACN,WAAmB,EACnB,MAAc,EACd,OAA6B;QAE7B,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,eAAe,WAAW,UAAU,MAAM,EAAE,EAAE;YACpE,GAAG,OAAO;YACV,OAAO,EAAE,EAAE,aAAa,EAAE,eAAe,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE;SACjE,CAAC,CAAC;IACL,CAAC;IAcD,IAAI,CACF,WAAmB,EACnB,QAA8C,EAAE,EAChD,OAA6B;QAE7B,IAAI,gBAAgB,CAAC,KAAK,CAAC,EAAE;YAC3B,OAAO,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE,EAAE,EAAE,KAAK,CAAC,CAAC;SAC1C;QACD,OAAO,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,eAAe,WAAW,QAAQ,EAAE,kBAAkB,EAAE;YACrF,KAAK;YACL,GAAG,OAAO;YACV,OAAO,EAAE,EAAE,aAAa,EAAE,eAAe,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE;SACjE,CAAC,CAAC;IACL,CAAC;IAED;;OAEG;IACH,GAAG,CACD,WAAmB,EACnB,MAAc,EACd,OAA6B;QAE7B,OAAO,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,eAAe,WAAW,UAAU,MAAM,EAAE,EAAE;YACvE,GAAG,OAAO;YACV,OAAO,EAAE,EAAE,aAAa,EAAE,eAAe,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE;SACjE,CAAC,CAAC;IACL,CAAC;CACF;AAED,MAAM,OAAO,kBAAmB,SAAQ,UAAyB;CAAG;AAiEpE,WAAiB,KAAK;IAGN,wBAAkB,GAAG,QAAQ,CAAC,kBAAkB,CAAC;AAGjE,CAAC,EANgB,KAAK,KAAL,KAAK,QAMrB"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/assistants/index.d.ts b/backend/node_modules/openai/resources/beta/assistants/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..081cca0f9caa24f7a12f7406b4983ece7ff63bf2 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/assistants/index.d.ts @@ -0,0 +1,3 @@ +export { Assistant, AssistantDeleted, AssistantStreamEvent, AssistantTool, CodeInterpreterTool, FunctionTool, MessageStreamEvent, RetrievalTool, RunStepStreamEvent, RunStreamEvent, ThreadStreamEvent, AssistantCreateParams, AssistantUpdateParams, AssistantListParams, AssistantsPage, Assistants, } from "./assistants.js"; +export { AssistantFile, FileDeleteResponse, FileCreateParams, FileListParams, AssistantFilesPage, Files, } from "./files.js"; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/assistants/index.d.ts.map b/backend/node_modules/openai/resources/beta/assistants/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..bafc6d00cea4a27ea4f9217a3be18349e110b310 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/assistants/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/resources/beta/assistants/index.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,SAAS,EACT,gBAAgB,EAChB,oBAAoB,EACpB,aAAa,EACb,mBAAmB,EACnB,YAAY,EACZ,kBAAkB,EAClB,aAAa,EACb,kBAAkB,EAClB,cAAc,EACd,iBAAiB,EACjB,qBAAqB,EACrB,qBAAqB,EACrB,mBAAmB,EACnB,cAAc,EACd,UAAU,GACX,MAAM,cAAc,CAAC;AACtB,OAAO,EACL,aAAa,EACb,kBAAkB,EAClB,gBAAgB,EAChB,cAAc,EACd,kBAAkB,EAClB,KAAK,GACN,MAAM,SAAS,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/assistants/index.js b/backend/node_modules/openai/resources/beta/assistants/index.js new file mode 100644 index 0000000000000000000000000000000000000000..d563667c5d5eb6ceb123b775d3d413894aa5f561 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/assistants/index.js @@ -0,0 +1,11 @@ +"use strict"; +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Files = exports.AssistantFilesPage = exports.Assistants = exports.AssistantsPage = void 0; +var assistants_1 = require("./assistants.js"); +Object.defineProperty(exports, "AssistantsPage", { enumerable: true, get: function () { return assistants_1.AssistantsPage; } }); +Object.defineProperty(exports, "Assistants", { enumerable: true, get: function () { return assistants_1.Assistants; } }); +var files_1 = require("./files.js"); +Object.defineProperty(exports, "AssistantFilesPage", { enumerable: true, get: function () { return files_1.AssistantFilesPage; } }); +Object.defineProperty(exports, "Files", { enumerable: true, get: function () { return files_1.Files; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/assistants/index.js.map b/backend/node_modules/openai/resources/beta/assistants/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..880a88286ba00b5808acbe04c9236bb930087be2 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/assistants/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/resources/beta/assistants/index.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;AAEtF,8CAiBsB;AAFpB,4GAAA,cAAc,OAAA;AACd,wGAAA,UAAU,OAAA;AAEZ,oCAOiB;AAFf,2GAAA,kBAAkB,OAAA;AAClB,8FAAA,KAAK,OAAA"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/assistants/index.mjs b/backend/node_modules/openai/resources/beta/assistants/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..1dd0076255bfb39caa5d37d8aa31085b09e35673 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/assistants/index.mjs @@ -0,0 +1,4 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +export { AssistantsPage, Assistants, } from "./assistants.mjs"; +export { AssistantFilesPage, Files, } from "./files.mjs"; +//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/assistants/index.mjs.map b/backend/node_modules/openai/resources/beta/assistants/index.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..34390ac483e4781af735b6070d885b007f5afd71 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/assistants/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"index.mjs","sourceRoot":"","sources":["../../../src/resources/beta/assistants/index.ts"],"names":[],"mappings":"AAAA,sFAAsF;OAE/E,EAeL,cAAc,EACd,UAAU,GACX;OACM,EAKL,kBAAkB,EAClB,KAAK,GACN"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/beta.d.ts b/backend/node_modules/openai/resources/beta/beta.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..82722a3be5555d439f45b5960d0290c48dde7051 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/beta.d.ts @@ -0,0 +1,44 @@ +import { APIResource } from 'openai/resource'; +import * as AssistantsAPI from 'openai/resources/beta/assistants/assistants'; +import * as ChatAPI from 'openai/resources/beta/chat/chat'; +import * as ThreadsAPI from 'openai/resources/beta/threads/threads'; +export declare class Beta extends APIResource { + chat: ChatAPI.Chat; + assistants: AssistantsAPI.Assistants; + threads: ThreadsAPI.Threads; +} +export declare namespace Beta { + export import Chat = ChatAPI.Chat; + export import Assistants = AssistantsAPI.Assistants; + export import Assistant = AssistantsAPI.Assistant; + export import AssistantDeleted = AssistantsAPI.AssistantDeleted; + export import AssistantStreamEvent = AssistantsAPI.AssistantStreamEvent; + export import AssistantTool = AssistantsAPI.AssistantTool; + export import CodeInterpreterTool = AssistantsAPI.CodeInterpreterTool; + export import FunctionTool = AssistantsAPI.FunctionTool; + export import MessageStreamEvent = AssistantsAPI.MessageStreamEvent; + export import RetrievalTool = AssistantsAPI.RetrievalTool; + export import RunStepStreamEvent = AssistantsAPI.RunStepStreamEvent; + export import RunStreamEvent = AssistantsAPI.RunStreamEvent; + export import ThreadStreamEvent = AssistantsAPI.ThreadStreamEvent; + export import AssistantsPage = AssistantsAPI.AssistantsPage; + export import AssistantCreateParams = AssistantsAPI.AssistantCreateParams; + export import AssistantUpdateParams = AssistantsAPI.AssistantUpdateParams; + export import AssistantListParams = AssistantsAPI.AssistantListParams; + export import Threads = ThreadsAPI.Threads; + export import AssistantResponseFormat = ThreadsAPI.AssistantResponseFormat; + export import AssistantResponseFormatOption = ThreadsAPI.AssistantResponseFormatOption; + export import AssistantToolChoice = ThreadsAPI.AssistantToolChoice; + export import AssistantToolChoiceFunction = ThreadsAPI.AssistantToolChoiceFunction; + export import AssistantToolChoiceOption = ThreadsAPI.AssistantToolChoiceOption; + export import Thread = ThreadsAPI.Thread; + export import ThreadDeleted = ThreadsAPI.ThreadDeleted; + export import ThreadCreateParams = ThreadsAPI.ThreadCreateParams; + export import ThreadUpdateParams = ThreadsAPI.ThreadUpdateParams; + export import ThreadCreateAndRunParams = ThreadsAPI.ThreadCreateAndRunParams; + export import ThreadCreateAndRunParamsNonStreaming = ThreadsAPI.ThreadCreateAndRunParamsNonStreaming; + export import ThreadCreateAndRunParamsStreaming = ThreadsAPI.ThreadCreateAndRunParamsStreaming; + export import ThreadCreateAndRunPollParams = ThreadsAPI.ThreadCreateAndRunPollParams; + export import ThreadCreateAndRunStreamParams = ThreadsAPI.ThreadCreateAndRunStreamParams; +} +//# sourceMappingURL=beta.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/beta.d.ts.map b/backend/node_modules/openai/resources/beta/beta.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..3999f5f12535170696d8741581100bba74b0a2b6 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/beta.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"beta.d.ts","sourceRoot":"","sources":["../../src/resources/beta/beta.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAC9C,OAAO,KAAK,aAAa,MAAM,6CAA6C,CAAC;AAC7E,OAAO,KAAK,OAAO,MAAM,iCAAiC,CAAC;AAC3D,OAAO,KAAK,UAAU,MAAM,uCAAuC,CAAC;AAEpE,qBAAa,IAAK,SAAQ,WAAW;IACnC,IAAI,EAAE,OAAO,CAAC,IAAI,CAAkC;IACpD,UAAU,EAAE,aAAa,CAAC,UAAU,CAA8C;IAClF,OAAO,EAAE,UAAU,CAAC,OAAO,CAAwC;CACpE;AAED,yBAAiB,IAAI,CAAC;IACpB,MAAM,QAAQ,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;IAClC,MAAM,QAAQ,UAAU,GAAG,aAAa,CAAC,UAAU,CAAC;IACpD,MAAM,QAAQ,SAAS,GAAG,aAAa,CAAC,SAAS,CA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MAAM,CAAC;IACzC,MAAM,QAAQ,aAAa,GAAG,UAAU,CAAC,aAAa,CAAC;IACvD,MAAM,QAAQ,kBAAkB,GAAG,UAAU,CAAC,kBAAkB,CAAC;IACjE,MAAM,QAAQ,kBAAkB,GAAG,UAAU,CAAC,kBAAkB,CAAC;IACjE,MAAM,QAAQ,wBAAwB,GAAG,UAAU,CAAC,wBAAwB,CAAC;IAC7E,MAAM,QAAQ,oCAAoC,GAAG,UAAU,CAAC,oCAAoC,CAAC;IACrG,MAAM,QAAQ,iCAAiC,GAAG,UAAU,CAAC,iCAAiC,CAAC;IAC/F,MAAM,QAAQ,4BAA4B,GAAG,UAAU,CAAC,4BAA4B,CAAC;IACrF,MAAM,QAAQ,8BAA8B,GAAG,UAAU,CAAC,8BAA8B,CAAC;CAC1F"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/beta.js b/backend/node_modules/openai/resources/beta/beta.js new file mode 100644 index 0000000000000000000000000000000000000000..ad9fdf6bff6b8c73fe0039b4d237bcd626504705 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/beta.js @@ -0,0 +1,47 @@ +"use strict"; +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Beta = void 0; +const resource_1 = require("openai/resource"); +const AssistantsAPI = __importStar(require("openai/resources/beta/assistants/assistants")); +const ChatAPI = __importStar(require("openai/resources/beta/chat/chat")); +const ThreadsAPI = __importStar(require("openai/resources/beta/threads/threads")); +class Beta extends resource_1.APIResource { + constructor() { + super(...arguments); + this.chat = new ChatAPI.Chat(this._client); + this.assistants = new AssistantsAPI.Assistants(this._client); + this.threads = new ThreadsAPI.Threads(this._client); + } +} +exports.Beta = Beta; +(function (Beta) { + Beta.Chat = ChatAPI.Chat; + Beta.Assistants = AssistantsAPI.Assistants; + Beta.AssistantsPage = AssistantsAPI.AssistantsPage; + Beta.Threads = ThreadsAPI.Threads; +})(Beta = exports.Beta || (exports.Beta = {})); +//# sourceMappingURL=beta.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/beta.js.map b/backend/node_modules/openai/resources/beta/beta.js.map new file mode 100644 index 0000000000000000000000000000000000000000..d1f058b3223f2da4f74c4abd3f965ac8b8bf7847 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/beta.js.map @@ -0,0 +1 @@ +{"version":3,"file":"beta.js","sourceRoot":"","sources":["../../src/resources/beta/beta.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;;;;;;;;;;;;;;;;;;;;;;;;AAEtF,8CAA8C;AAC9C,2FAA6E;AAC7E,yEAA2D;AAC3D,kFAAoE;AAEpE,MAAa,IAAK,SAAQ,sBAAW;IAArC;;QACE,SAAI,GAAiB,IAAI,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QACpD,eAAU,GAA6B,IAAI,aAAa,CAAC,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QAClF,YAAO,GAAuB,IAAI,UAAU,CAAC,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IACrE,CAAC;CAAA;AAJD,oBAIC;AAED,WAAiB,IAAI;IACL,SAAI,GAAG,OAAO,CAAC,IAAI,CAAC;IACpB,eAAU,GAAG,aAAa,CAAC,UAAU,CAAC;IAYtC,mBAAc,GAAG,aAAa,CAAC,cAAc,CAAC;IAI9C,YAAO,GAAG,UAAU,CAAC,OAAO,CAAC;AAe7C,CAAC,EAjCgB,IAAI,GAAJ,YAAI,KAAJ,YAAI,QAiCpB"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/beta.mjs b/backend/node_modules/openai/resources/beta/beta.mjs new file mode 100644 index 0000000000000000000000000000000000000000..f1f895df9e7a2de8c5c67664712daa6d1e07b7f8 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/beta.mjs @@ -0,0 +1,20 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +import { APIResource } from 'openai/resource'; +import * as AssistantsAPI from 'openai/resources/beta/assistants/assistants'; +import * as ChatAPI from 'openai/resources/beta/chat/chat'; +import * as ThreadsAPI from 'openai/resources/beta/threads/threads'; +export class Beta extends APIResource { + constructor() { + super(...arguments); + this.chat = new ChatAPI.Chat(this._client); + this.assistants = new AssistantsAPI.Assistants(this._client); + this.threads = new ThreadsAPI.Threads(this._client); + } +} +(function (Beta) { + Beta.Chat = ChatAPI.Chat; + Beta.Assistants = AssistantsAPI.Assistants; + Beta.AssistantsPage = AssistantsAPI.AssistantsPage; + Beta.Threads = ThreadsAPI.Threads; +})(Beta || (Beta = {})); +//# sourceMappingURL=beta.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/beta.mjs.map b/backend/node_modules/openai/resources/beta/beta.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..977391a0882c325b5b9abf0ff91552920b8be403 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/beta.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"beta.mjs","sourceRoot":"","sources":["../../src/resources/beta/beta.ts"],"names":[],"mappings":"AAAA,sFAAsF;OAE/E,EAAE,WAAW,EAAE,MAAM,iBAAiB;OACtC,KAAK,aAAa,MAAM,6CAA6C;OACrE,KAAK,OAAO,MAAM,iCAAiC;OACnD,KAAK,UAAU,MAAM,uCAAuC;AAEnE,MAAM,OAAO,IAAK,SAAQ,WAAW;IAArC;;QACE,SAAI,GAAiB,IAAI,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QACpD,eAAU,GAA6B,IAAI,aAAa,CAAC,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QAClF,YAAO,GAAuB,IAAI,UAAU,CAAC,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IACrE,CAAC;CAAA;AAED,WAAiB,IAAI;IACL,SAAI,GAAG,OAAO,CAAC,IAAI,CAAC;IACpB,eAAU,GAAG,aAAa,CAAC,UAAU,CAAC;IAYtC,mBAAc,GAAG,aAAa,CAAC,cAAc,CAAC;IAI9C,YAAO,GAAG,UAAU,CAAC,OAAO,CAAC;AAe7C,CAAC,EAjCgB,IAAI,KAAJ,IAAI,QAiCpB"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/chat/chat.d.ts b/backend/node_modules/openai/resources/beta/chat/chat.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6e6664c6df78d7c68eae14ab2e79ab28c6f6949f --- /dev/null +++ b/backend/node_modules/openai/resources/beta/chat/chat.d.ts @@ -0,0 +1,9 @@ +import { APIResource } from 'openai/resource'; +import * as CompletionsAPI from 'openai/resources/beta/chat/completions'; +export declare class Chat extends APIResource { + completions: CompletionsAPI.Completions; +} +export declare namespace Chat { + export import Completions = CompletionsAPI.Completions; +} +//# sourceMappingURL=chat.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/chat/chat.d.ts.map b/backend/node_modules/openai/resources/beta/chat/chat.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..f71822c51ad9f825712ec41b2aaf8da0a15ebb16 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/chat/chat.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"chat.d.ts","sourceRoot":"","sources":["../../../src/resources/beta/chat/chat.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAC9C,OAAO,KAAK,cAAc,MAAM,wCAAwC,CAAC;AAEzE,qBAAa,IAAK,SAAQ,WAAW;IACnC,WAAW,EAAE,cAAc,CAAC,WAAW,CAAgD;CACxF;AAED,yBAAiB,IAAI,CAAC;IACpB,MAAM,QAAQ,WAAW,GAAG,cAAc,CAAC,WAAW,CAAC;CACxD"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/chat/chat.js b/backend/node_modules/openai/resources/beta/chat/chat.js new file mode 100644 index 0000000000000000000000000000000000000000..b0e7c93835055fee26e55ebcefb88ee08a0097a7 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/chat/chat.js @@ -0,0 +1,40 @@ +"use strict"; +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Chat = void 0; +const resource_1 = require("openai/resource"); +const CompletionsAPI = __importStar(require("openai/resources/beta/chat/completions")); +class Chat extends resource_1.APIResource { + constructor() { + super(...arguments); + this.completions = new CompletionsAPI.Completions(this._client); + } +} +exports.Chat = Chat; +(function (Chat) { + Chat.Completions = CompletionsAPI.Completions; +})(Chat = exports.Chat || (exports.Chat = {})); +//# sourceMappingURL=chat.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/chat/chat.js.map b/backend/node_modules/openai/resources/beta/chat/chat.js.map new file mode 100644 index 0000000000000000000000000000000000000000..cbc16c2151446eb03cab13e674267064272e84f1 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/chat/chat.js.map @@ -0,0 +1 @@ +{"version":3,"file":"chat.js","sourceRoot":"","sources":["../../../src/resources/beta/chat/chat.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;;;;;;;;;;;;;;;;;;;;;;;;AAEtF,8CAA8C;AAC9C,uFAAyE;AAEzE,MAAa,IAAK,SAAQ,sBAAW;IAArC;;QACE,gBAAW,GAA+B,IAAI,cAAc,CAAC,WAAW,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IACzF,CAAC;CAAA;AAFD,oBAEC;AAED,WAAiB,IAAI;IACL,gBAAW,GAAG,cAAc,CAAC,WAAW,CAAC;AACzD,CAAC,EAFgB,IAAI,GAAJ,YAAI,KAAJ,YAAI,QAEpB"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/chat/chat.mjs b/backend/node_modules/openai/resources/beta/chat/chat.mjs new file mode 100644 index 0000000000000000000000000000000000000000..f3147f651c5c063cac3bbbedb6d4012a069b57e5 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/chat/chat.mjs @@ -0,0 +1,13 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +import { APIResource } from 'openai/resource'; +import * as CompletionsAPI from 'openai/resources/beta/chat/completions'; +export class Chat extends APIResource { + constructor() { + super(...arguments); + this.completions = new CompletionsAPI.Completions(this._client); + } +} +(function (Chat) { + Chat.Completions = CompletionsAPI.Completions; +})(Chat || (Chat = {})); +//# sourceMappingURL=chat.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/chat/chat.mjs.map b/backend/node_modules/openai/resources/beta/chat/chat.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..d3b5a03245e58efd4c09ad926f37d0c522c7fb78 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/chat/chat.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"chat.mjs","sourceRoot":"","sources":["../../../src/resources/beta/chat/chat.ts"],"names":[],"mappings":"AAAA,sFAAsF;OAE/E,EAAE,WAAW,EAAE,MAAM,iBAAiB;OACtC,KAAK,cAAc,MAAM,wCAAwC;AAExE,MAAM,OAAO,IAAK,SAAQ,WAAW;IAArC;;QACE,gBAAW,GAA+B,IAAI,cAAc,CAAC,WAAW,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IACzF,CAAC;CAAA;AAED,WAAiB,IAAI;IACL,gBAAW,GAAG,cAAc,CAAC,WAAW,CAAC;AACzD,CAAC,EAFgB,IAAI,KAAJ,IAAI,QAEpB"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/chat/completions.d.ts b/backend/node_modules/openai/resources/beta/chat/completions.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..05500ebe0b6529173a0b82ae1be98c5944eb434d --- /dev/null +++ b/backend/node_modules/openai/resources/beta/chat/completions.d.ts @@ -0,0 +1,37 @@ +import * as Core from 'openai/core'; +import { APIResource } from 'openai/resource'; +import { ChatCompletionRunner, ChatCompletionFunctionRunnerParams } from 'openai/lib/ChatCompletionRunner'; +export { ChatCompletionRunner, ChatCompletionFunctionRunnerParams } from 'openai/lib/ChatCompletionRunner'; +import { ChatCompletionStreamingRunner, ChatCompletionStreamingFunctionRunnerParams } from 'openai/lib/ChatCompletionStreamingRunner'; +export { ChatCompletionStreamingRunner, ChatCompletionStreamingFunctionRunnerParams, } from 'openai/lib/ChatCompletionStreamingRunner'; +import { BaseFunctionsArgs } from 'openai/lib/RunnableFunction'; +export { RunnableFunction, RunnableFunctions, RunnableFunctionWithParse, RunnableFunctionWithoutParse, ParsingFunction, ParsingToolFunction, } from 'openai/lib/RunnableFunction'; +import { ChatCompletionToolRunnerParams } from 'openai/lib/ChatCompletionRunner'; +export { ChatCompletionToolRunnerParams } from 'openai/lib/ChatCompletionRunner'; +import { ChatCompletionStreamingToolRunnerParams } from 'openai/lib/ChatCompletionStreamingRunner'; +export { ChatCompletionStreamingToolRunnerParams } from 'openai/lib/ChatCompletionStreamingRunner'; +import { ChatCompletionStream, type ChatCompletionStreamParams } from 'openai/lib/ChatCompletionStream'; +export { ChatCompletionStream, type ChatCompletionStreamParams } from 'openai/lib/ChatCompletionStream'; +export declare class Completions extends APIResource { + /** + * @deprecated - use `runTools` instead. + */ + runFunctions(body: ChatCompletionFunctionRunnerParams, options?: Core.RequestOptions): ChatCompletionRunner; + runFunctions(body: ChatCompletionStreamingFunctionRunnerParams, options?: Core.RequestOptions): ChatCompletionStreamingRunner; + /** + * A convenience helper for using tool calls with the /chat/completions endpoint + * which automatically calls the JavaScript functions you provide and sends their + * results back to the /chat/completions endpoint, looping as long as the model + * requests function calls. + * + * For more details and examples, see + * [the docs](https://github.com/openai/openai-node#automated-function-calls) + */ + runTools(body: ChatCompletionToolRunnerParams, options?: Core.RequestOptions): ChatCompletionRunner; + runTools(body: ChatCompletionStreamingToolRunnerParams, options?: Core.RequestOptions): ChatCompletionStreamingRunner; + /** + * Creates a chat completion stream + */ + stream(body: ChatCompletionStreamParams, options?: Core.RequestOptions): ChatCompletionStream; +} +//# sourceMappingURL=completions.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/chat/completions.d.ts.map b/backend/node_modules/openai/resources/beta/chat/completions.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..40c0f8e2d543f6d133cac490a65ac690255a83f6 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/chat/completions.d.ts.map @@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E,2CAA2C,CAAC,aAAa,CAAC,EAChE,OAAO,CAAC,EAAE,IAAI,CAAC,cAAc,GAC5B,6BAA6B;IAqBhC;;;;;;;;OAQG;IACH,QAAQ,CAAC,aAAa,SAAS,iBAAiB,EAC9C,IAAI,EAAE,8BAA8B,CAAC,aAAa,CAAC,EACnD,OAAO,CAAC,EAAE,IAAI,CAAC,cAAc,GAC5B,oBAAoB;IACvB,QAAQ,CAAC,aAAa,SAAS,iBAAiB,EAC9C,IAAI,EAAE,uCAAuC,CAAC,aAAa,CAAC,EAC5D,OAAO,CAAC,EAAE,IAAI,CAAC,cAAc,GAC5B,6BAA6B;IAqBhC;;OAEG;IACH,MAAM,CAAC,IAAI,EAAE,0BAA0B,EAAE,OAAO,CAAC,EAAE,IAAI,CAAC,cAAc,GAAG,oBAAoB;CAG9F"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/chat/completions.js b/backend/node_modules/openai/resources/beta/chat/completions.js new file mode 100644 index 0000000000000000000000000000000000000000..e472488d304daf8a2e2c0cac9965febb58b6898e --- /dev/null +++ b/backend/node_modules/openai/resources/beta/chat/completions.js @@ -0,0 +1,39 @@ +"use strict"; +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Completions = exports.ChatCompletionStream = exports.ParsingToolFunction = exports.ParsingFunction = exports.ChatCompletionStreamingRunner = exports.ChatCompletionRunner = void 0; +const resource_1 = require("openai/resource"); +const ChatCompletionRunner_1 = require("openai/lib/ChatCompletionRunner"); +var ChatCompletionRunner_2 = require("openai/lib/ChatCompletionRunner"); +Object.defineProperty(exports, "ChatCompletionRunner", { enumerable: true, get: function () { return ChatCompletionRunner_2.ChatCompletionRunner; } }); +const ChatCompletionStreamingRunner_1 = require("openai/lib/ChatCompletionStreamingRunner"); +var ChatCompletionStreamingRunner_2 = require("openai/lib/ChatCompletionStreamingRunner"); +Object.defineProperty(exports, "ChatCompletionStreamingRunner", { enumerable: true, get: function () { return ChatCompletionStreamingRunner_2.ChatCompletionStreamingRunner; } }); +var RunnableFunction_1 = require("openai/lib/RunnableFunction"); +Object.defineProperty(exports, "ParsingFunction", { enumerable: true, get: function () { return RunnableFunction_1.ParsingFunction; } }); +Object.defineProperty(exports, "ParsingToolFunction", { enumerable: true, get: function () { return RunnableFunction_1.ParsingToolFunction; } }); +const ChatCompletionStream_1 = require("openai/lib/ChatCompletionStream"); +var ChatCompletionStream_2 = require("openai/lib/ChatCompletionStream"); +Object.defineProperty(exports, "ChatCompletionStream", { enumerable: true, get: function () { return ChatCompletionStream_2.ChatCompletionStream; } }); +class Completions extends resource_1.APIResource { + runFunctions(body, options) { + if (body.stream) { + return ChatCompletionStreamingRunner_1.ChatCompletionStreamingRunner.runFunctions(this._client.chat.completions, body, options); + } + return ChatCompletionRunner_1.ChatCompletionRunner.runFunctions(this._client.chat.completions, body, options); + } + runTools(body, options) { + if (body.stream) { + return ChatCompletionStreamingRunner_1.ChatCompletionStreamingRunner.runTools(this._client.chat.completions, body, options); + } + return ChatCompletionRunner_1.ChatCompletionRunner.runTools(this._client.chat.completions, body, options); + } + /** + * Creates a chat completion stream + */ + stream(body, options) { + return ChatCompletionStream_1.ChatCompletionStream.createChatCompletion(this._client.chat.completions, body, options); + } +} +exports.Completions = Completions; +//# sourceMappingURL=completions.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/chat/completions.js.map b/backend/node_modules/openai/resources/beta/chat/completions.js.map new file mode 100644 index 0000000000000000000000000000000000000000..fb92562585884f60bdc115d0237140dabc7ab512 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/chat/completions.js.map @@ -0,0 +1 @@ +{"version":3,"file":"completions.js","sourceRoot":"","sources":["../../../src/resources/beta/chat/completions.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;AAGtF,8CAA8C;AAC9C,0EAA2G;AAC3G,wEAA2G;AAAlG,4HAAA,oBAAoB,OAAA;AAC7B,4FAGkD;AAClD,0FAGkD;AAFhD,8IAAA,6BAA6B,OAAA;AAI/B,gEAOqC;AAFnC,mHAAA,eAAe,OAAA;AACf,uHAAA,mBAAmB,OAAA;AAMrB,0EAAwG;AACxG,wEAAwG;AAA/F,4HAAA,oBAAoB,OAAA;AAE7B,MAAa,WAAY,SAAQ,sBAAW;IAY1C,YAAY,CACV,IAE8D,EAC9D,OAA6B;QAE7B,IAAI,IAAI,CAAC,MAAM,EAAE;YACf,OAAO,6DAA6B,CAAC,YAAY,CAC/C,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,WAAW,EAC7B,IAAkE,EAClE,OAAO,CACR,CAAC;SACH;QACD,OAAO,2CAAoB,CAAC,YAAY,CACtC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,WAAW,EAC7B,IAAyD,EACzD,OAAO,CACR,CAAC;IACJ,CAAC;IAmBD,QAAQ,CACN,IAE0D,EAC1D,OAA6B;QAE7B,IAAI,IAAI,CAAC,MAAM,EAAE;YACf,OAAO,6DAA6B,CAAC,QAAQ,CAC3C,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,WAAW,EAC7B,IAA8D,EAC9D,OAAO,CACR,CAAC;SACH;QACD,OAAO,2CAAoB,CAAC,QAAQ,CAClC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,WAAW,EAC7B,IAAqD,EACrD,OAAO,CACR,CAAC;IACJ,CAAC;IAED;;OAEG;IACH,MAAM,CAAC,IAAgC,EAAE,OAA6B;QACpE,OAAO,2CAAoB,CAAC,oBAAoB,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,WAAW,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC;IACjG,CAAC;CACF;AA3ED,kCA2EC"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/chat/completions.mjs b/backend/node_modules/openai/resources/beta/chat/completions.mjs new file mode 100644 index 0000000000000000000000000000000000000000..a8f3fdcce1c620324f8f2921a80091cd74de9896 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/chat/completions.mjs @@ -0,0 +1,30 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +import { APIResource } from 'openai/resource'; +import { ChatCompletionRunner } from 'openai/lib/ChatCompletionRunner'; +export { ChatCompletionRunner } from 'openai/lib/ChatCompletionRunner'; +import { ChatCompletionStreamingRunner, } from 'openai/lib/ChatCompletionStreamingRunner'; +export { ChatCompletionStreamingRunner, } from 'openai/lib/ChatCompletionStreamingRunner'; +export { ParsingFunction, ParsingToolFunction, } from 'openai/lib/RunnableFunction'; +import { ChatCompletionStream } from 'openai/lib/ChatCompletionStream'; +export { ChatCompletionStream } from 'openai/lib/ChatCompletionStream'; +export class Completions extends APIResource { + runFunctions(body, options) { + if (body.stream) { + return ChatCompletionStreamingRunner.runFunctions(this._client.chat.completions, body, options); + } + return ChatCompletionRunner.runFunctions(this._client.chat.completions, body, options); + } + runTools(body, options) { + if (body.stream) { + return ChatCompletionStreamingRunner.runTools(this._client.chat.completions, body, options); + } + return ChatCompletionRunner.runTools(this._client.chat.completions, body, options); + } + /** + * Creates a chat completion stream + */ + stream(body, options) { + return ChatCompletionStream.createChatCompletion(this._client.chat.completions, body, options); + } +} +//# sourceMappingURL=completions.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/chat/completions.mjs.map b/backend/node_modules/openai/resources/beta/chat/completions.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..e54e1cb0e68d2478101019b364db7fb281212208 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/chat/completions.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"completions.mjs","sourceRoot":"","sources":["../../../src/resources/beta/chat/completions.ts"],"names":[],"mappings":"AAAA,sFAAsF;OAG/E,EAAE,WAAW,EAAE,MAAM,iBAAiB;OACtC,EAAE,oBAAoB,EAAsC,MAAM,iCAAiC;OACnG,EAAE,oBAAoB,EAAsC,MAAM,iCAAiC;OACnG,EACL,6BAA6B,GAE9B,MAAM,0CAA0C;OAC1C,EACL,6BAA6B,GAE9B,MAAM,0CAA0C;OAE1C,EAKL,eAAe,EACf,mBAAmB,GACpB,MAAM,6BAA6B;OAK7B,EAAE,oBAAoB,EAAmC,MAAM,iCAAiC;OAChG,EAAE,oBAAoB,EAAmC,MAAM,iCAAiC;AAEvG,MAAM,OAAO,WAAY,SAAQ,WAAW;IAY1C,YAAY,CACV,IAE8D,EAC9D,OAA6B;QAE7B,IAAI,IAAI,CAAC,MAAM,EAAE;YACf,OAAO,6BAA6B,CAAC,YAAY,CAC/C,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,WAAW,EAC7B,IAAkE,EAClE,OAAO,CACR,CAAC;SACH;QACD,OAAO,oBAAoB,CAAC,YAAY,CACtC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,WAAW,EAC7B,IAAyD,EACzD,OAAO,CACR,CAAC;IACJ,CAAC;IAmBD,QAAQ,CACN,IAE0D,EAC1D,OAA6B;QAE7B,IAAI,IAAI,CAAC,MAAM,EAAE;YACf,OAAO,6BAA6B,CAAC,QAAQ,CAC3C,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,WAAW,EAC7B,IAA8D,EAC9D,OAAO,CACR,CAAC;SACH;QACD,OAAO,oBAAoB,CAAC,QAAQ,CAClC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,WAAW,EAC7B,IAAqD,EACrD,OAAO,CACR,CAAC;IACJ,CAAC;IAED;;OAEG;IACH,MAAM,CAAC,IAAgC,EAAE,OAA6B;QACpE,OAAO,oBAAoB,CAAC,oBAAoB,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,WAAW,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC;IACjG,CAAC;CACF"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/chat/index.d.ts b/backend/node_modules/openai/resources/beta/chat/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3e7542698712b1ee464c7421c151b69dfbe2ec1e --- /dev/null +++ b/backend/node_modules/openai/resources/beta/chat/index.d.ts @@ -0,0 +1,3 @@ +export { Chat } from "./chat.js"; +export { Completions } from "./completions.js"; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/chat/index.d.ts.map b/backend/node_modules/openai/resources/beta/chat/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..fd2699a5838a79ef37c12112c02295c92199c34c --- /dev/null +++ b/backend/node_modules/openai/resources/beta/chat/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/resources/beta/chat/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,IAAI,EAAE,MAAM,QAAQ,CAAC;AAC9B,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/chat/index.js b/backend/node_modules/openai/resources/beta/chat/index.js new file mode 100644 index 0000000000000000000000000000000000000000..53c3d1685f0e49779252b74b3ca16e0f203ac3e6 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/chat/index.js @@ -0,0 +1,9 @@ +"use strict"; +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Completions = exports.Chat = void 0; +var chat_1 = require("./chat.js"); +Object.defineProperty(exports, "Chat", { enumerable: true, get: function () { return chat_1.Chat; } }); +var completions_1 = require("./completions.js"); +Object.defineProperty(exports, "Completions", { enumerable: true, get: function () { return completions_1.Completions; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/chat/index.js.map b/backend/node_modules/openai/resources/beta/chat/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..ea2dec045696d4b6e4f1f168158b56d92d2fafd6 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/chat/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/resources/beta/chat/index.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;AAEtF,kCAA8B;AAArB,4FAAA,IAAI,OAAA;AACb,gDAA4C;AAAnC,0GAAA,WAAW,OAAA"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/chat/index.mjs b/backend/node_modules/openai/resources/beta/chat/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..b91c862d8ede00dc5ee71717ce358e69ac63b8f7 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/chat/index.mjs @@ -0,0 +1,4 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +export { Chat } from "./chat.mjs"; +export { Completions } from "./completions.mjs"; +//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/chat/index.mjs.map b/backend/node_modules/openai/resources/beta/chat/index.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..8357372c67ca17d6d08c4279dadc25e383154724 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/chat/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"index.mjs","sourceRoot":"","sources":["../../../src/resources/beta/chat/index.ts"],"names":[],"mappings":"AAAA,sFAAsF;OAE/E,EAAE,IAAI,EAAE;OACR,EAAE,WAAW,EAAE"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/index.d.ts b/backend/node_modules/openai/resources/beta/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b4ffafe4570b22c172b1cf2c4b96473fd616e7ea --- /dev/null +++ b/backend/node_modules/openai/resources/beta/index.d.ts @@ -0,0 +1,5 @@ +export { Assistant, AssistantDeleted, AssistantStreamEvent, AssistantTool, CodeInterpreterTool, FunctionTool, MessageStreamEvent, RetrievalTool, RunStepStreamEvent, RunStreamEvent, ThreadStreamEvent, AssistantCreateParams, AssistantUpdateParams, AssistantListParams, AssistantsPage, Assistants, } from "./assistants/index.js"; +export { AssistantResponseFormat, AssistantResponseFormatOption, AssistantToolChoice, AssistantToolChoiceFunction, AssistantToolChoiceOption, Thread, ThreadDeleted, ThreadCreateParams, ThreadUpdateParams, ThreadCreateAndRunParams, ThreadCreateAndRunParamsNonStreaming, ThreadCreateAndRunParamsStreaming, ThreadCreateAndRunPollParams, ThreadCreateAndRunStreamParams, Threads, } from "./threads/index.js"; +export { Beta } from "./beta.js"; +export { Chat } from "./chat/index.js"; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/index.d.ts.map b/backend/node_modules/openai/resources/beta/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..83c2d64113c35a9c9e8e4f275dfa46e542b21dfa --- /dev/null +++ b/backend/node_modules/openai/resources/beta/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/resources/beta/index.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,SAAS,EACT,gBAAgB,EAChB,oBAAoB,EACpB,aAAa,EACb,mBAAmB,EACnB,YAAY,EACZ,kBAAkB,EAClB,aAAa,EACb,kBAAkB,EAClB,cAAc,EACd,iBAAiB,EACjB,qBAAqB,EACrB,qBAAqB,EACrB,mBAAmB,EACnB,cAAc,EACd,UAAU,GACX,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EACL,uBAAuB,EACvB,6BAA6B,EAC7B,mBAAmB,EACnB,2BAA2B,EAC3B,yBAAyB,EACzB,MAAM,EACN,aAAa,EACb,kBAAkB,EAClB,kBAAkB,EAClB,wBAAwB,EACxB,oCAAoC,EACpC,iCAAiC,EACjC,4BAA4B,EAC5B,8BAA8B,EAC9B,OAAO,GACR,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,IAAI,EAAE,MAAM,QAAQ,CAAC;AAC9B,OAAO,EAAE,IAAI,EAAE,MAAM,cAAc,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/index.js b/backend/node_modules/openai/resources/beta/index.js new file mode 100644 index 0000000000000000000000000000000000000000..303cb329de2d25f939282d01d5e079eea7696938 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/index.js @@ -0,0 +1,14 @@ +"use strict"; +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Chat = exports.Beta = exports.Threads = exports.Assistants = exports.AssistantsPage = void 0; +var index_1 = require("./assistants/index.js"); +Object.defineProperty(exports, "AssistantsPage", { enumerable: true, get: function () { return index_1.AssistantsPage; } }); +Object.defineProperty(exports, "Assistants", { enumerable: true, get: function () { return index_1.Assistants; } }); +var index_2 = require("./threads/index.js"); +Object.defineProperty(exports, "Threads", { enumerable: true, get: function () { return index_2.Threads; } }); +var beta_1 = require("./beta.js"); +Object.defineProperty(exports, "Beta", { enumerable: true, get: function () { return beta_1.Beta; } }); +var index_3 = require("./chat/index.js"); +Object.defineProperty(exports, "Chat", { enumerable: true, get: function () { return index_3.Chat; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/index.js.map b/backend/node_modules/openai/resources/beta/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..e983a6ed84b0722fc557d1aabb9fe145c89c2be0 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/resources/beta/index.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;AAEtF,+CAiB4B;AAF1B,uGAAA,cAAc,OAAA;AACd,mGAAA,UAAU,OAAA;AAEZ,4CAgByB;AADvB,gGAAA,OAAO,OAAA;AAET,kCAA8B;AAArB,4FAAA,IAAI,OAAA;AACb,yCAAoC;AAA3B,6FAAA,IAAI,OAAA"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/index.mjs b/backend/node_modules/openai/resources/beta/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..8db0b3e0eb2add47b2647b2ebd360a73b301e4d8 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/index.mjs @@ -0,0 +1,6 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +export { AssistantsPage, Assistants, } from "./assistants/index.mjs"; +export { Threads, } from "./threads/index.mjs"; +export { Beta } from "./beta.mjs"; +export { Chat } from "./chat/index.mjs"; +//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/index.mjs.map b/backend/node_modules/openai/resources/beta/index.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..d42876d70bba745c21718664297925d682a37dfd --- /dev/null +++ b/backend/node_modules/openai/resources/beta/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"index.mjs","sourceRoot":"","sources":["../../src/resources/beta/index.ts"],"names":[],"mappings":"AAAA,sFAAsF;OAE/E,EAeL,cAAc,EACd,UAAU,GACX;OACM,EAeL,OAAO,GACR;OACM,EAAE,IAAI,EAAE;OACR,EAAE,IAAI,EAAE"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/threads/index.d.ts b/backend/node_modules/openai/resources/beta/threads/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0a05dbcc96d8145fdd68cc547ddb5159758dab6a --- /dev/null +++ b/backend/node_modules/openai/resources/beta/threads/index.d.ts @@ -0,0 +1,4 @@ +export { Annotation, AnnotationDelta, FileCitationAnnotation, FileCitationDeltaAnnotation, FilePathAnnotation, FilePathDeltaAnnotation, ImageFile, ImageFileContentBlock, ImageFileDelta, ImageFileDeltaBlock, Message, MessageContent, MessageContentDelta, MessageDeleted, MessageDelta, MessageDeltaEvent, Text, TextContentBlock, TextDelta, TextDeltaBlock, MessageCreateParams, MessageUpdateParams, MessageListParams, MessagesPage, Messages, } from "./messages/index.js"; +export { AssistantResponseFormat, AssistantResponseFormatOption, AssistantToolChoice, AssistantToolChoiceFunction, AssistantToolChoiceOption, Thread, ThreadDeleted, ThreadCreateParams, ThreadUpdateParams, ThreadCreateAndRunParams, ThreadCreateAndRunParamsNonStreaming, ThreadCreateAndRunParamsStreaming, ThreadCreateAndRunPollParams, ThreadCreateAndRunStreamParams, Threads, } from "./threads.js"; +export { RequiredActionFunctionToolCall, Run, RunStatus, RunCreateParams, RunCreateParamsNonStreaming, RunCreateParamsStreaming, RunUpdateParams, RunListParams, RunCreateAndPollParams, RunCreateAndStreamParams, RunStreamParams, RunSubmitToolOutputsParams, RunSubmitToolOutputsParamsNonStreaming, RunSubmitToolOutputsParamsStreaming, RunSubmitToolOutputsAndPollParams, RunSubmitToolOutputsStreamParams, RunsPage, Runs, } from "./runs/index.js"; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/threads/index.d.ts.map b/backend/node_modules/openai/resources/beta/threads/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..e3aa389bb7de6ea8692024db42c2eed7d5be9010 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/threads/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/resources/beta/threads/index.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,UAAU,EACV,eAAe,EACf,sBAAsB,EACtB,2BAA2B,EAC3B,kBAAkB,EAClB,uBAAuB,EACvB,SAAS,EACT,qBAAqB,EACrB,cAAc,EACd,mBAAmB,EACnB,OAAO,EACP,cAAc,EACd,mBAAmB,EACnB,cAAc,EACd,YAAY,EACZ,iBAAiB,EACjB,IAAI,EACJ,gBAAgB,EAChB,SAAS,EACT,cAAc,EACd,mBAAmB,EACnB,mBAAmB,EACnB,iBAAiB,EACjB,YAAY,EACZ,QAAQ,GACT,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EACL,uBAAuB,EACvB,6BAA6B,EAC7B,mBAAmB,EACnB,2BAA2B,EAC3B,yBAAyB,EACzB,MAAM,EACN,aAAa,EACb,kBAAkB,EAClB,kBAAkB,EAClB,wBAAwB,EACxB,oCAAoC,EACpC,iCAAiC,EACjC,4BAA4B,EAC5B,8BAA8B,EAC9B,OAAO,GACR,MAAM,WAAW,CAAC;AACnB,OAAO,EACL,8BAA8B,EAC9B,GAAG,EACH,SAAS,EACT,eAAe,EACf,2BAA2B,EAC3B,wBAAwB,EACxB,eAAe,EACf,aAAa,EACb,sBAAsB,EACtB,wBAAwB,EACxB,eAAe,EACf,0BAA0B,EAC1B,sCAAsC,EACtC,mCAAmC,EACnC,iCAAiC,EACjC,gCAAgC,EAChC,QAAQ,EACR,IAAI,GACL,MAAM,cAAc,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/threads/index.js b/backend/node_modules/openai/resources/beta/threads/index.js new file mode 100644 index 0000000000000000000000000000000000000000..7f2a9579e2307de40eabdedeb12734bebb241a4d --- /dev/null +++ b/backend/node_modules/openai/resources/beta/threads/index.js @@ -0,0 +1,13 @@ +"use strict"; +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Runs = exports.RunsPage = exports.Threads = exports.Messages = exports.MessagesPage = void 0; +var index_1 = require("./messages/index.js"); +Object.defineProperty(exports, "MessagesPage", { enumerable: true, get: function () { return index_1.MessagesPage; } }); +Object.defineProperty(exports, "Messages", { enumerable: true, get: function () { return index_1.Messages; } }); +var threads_1 = require("./threads.js"); +Object.defineProperty(exports, "Threads", { enumerable: true, get: function () { return threads_1.Threads; } }); +var index_2 = require("./runs/index.js"); +Object.defineProperty(exports, "RunsPage", { enumerable: true, get: function () { return index_2.RunsPage; } }); +Object.defineProperty(exports, "Runs", { enumerable: true, get: function () { return index_2.Runs; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/threads/index.js.map b/backend/node_modules/openai/resources/beta/threads/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..675f4fabba0ae7f3712a715f4bb5013cefdbccc0 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/threads/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/resources/beta/threads/index.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;AAEtF,6CA0B0B;AAFxB,qGAAA,YAAY,OAAA;AACZ,iGAAA,QAAQ,OAAA;AAEV,wCAgBmB;AADjB,kGAAA,OAAO,OAAA;AAET,yCAmBsB;AAFpB,iGAAA,QAAQ,OAAA;AACR,6FAAA,IAAI,OAAA"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/threads/index.mjs b/backend/node_modules/openai/resources/beta/threads/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..e1b6e38bb2a95b7a524d451ef849894325bf7fb3 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/threads/index.mjs @@ -0,0 +1,5 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +export { MessagesPage, Messages, } from "./messages/index.mjs"; +export { Threads, } from "./threads.mjs"; +export { RunsPage, Runs, } from "./runs/index.mjs"; +//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/threads/index.mjs.map b/backend/node_modules/openai/resources/beta/threads/index.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..400c00256ad0ac4a1c64ec708943732b5b0699db --- /dev/null +++ b/backend/node_modules/openai/resources/beta/threads/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"index.mjs","sourceRoot":"","sources":["../../../src/resources/beta/threads/index.ts"],"names":[],"mappings":"AAAA,sFAAsF;OAE/E,EAwBL,YAAY,EACZ,QAAQ,GACT;OACM,EAeL,OAAO,GACR;OACM,EAiBL,QAAQ,EACR,IAAI,GACL"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/threads/messages/files.d.ts b/backend/node_modules/openai/resources/beta/threads/messages/files.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..74f8bb7af6bdcc497971f5c9d381effb1a971166 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/threads/messages/files.d.ts @@ -0,0 +1,60 @@ +import * as Core from 'openai/core'; +import { APIResource } from 'openai/resource'; +import * as FilesAPI from 'openai/resources/beta/threads/messages/files'; +import { CursorPage, type CursorPageParams } from 'openai/pagination'; +export declare class Files extends APIResource { + /** + * Retrieves a message file. + */ + retrieve(threadId: string, messageId: string, fileId: string, options?: Core.RequestOptions): Core.APIPromise; + /** + * Returns a list of message files. + */ + list(threadId: string, messageId: string, query?: FileListParams, options?: Core.RequestOptions): Core.PagePromise; + list(threadId: string, messageId: string, options?: Core.RequestOptions): Core.PagePromise; +} +export declare class MessageFilesPage extends CursorPage { +} +/** + * A list of files attached to a `message`. + */ +export interface MessageFile { + /** + * The identifier, which can be referenced in API endpoints. + */ + id: string; + /** + * The Unix timestamp (in seconds) for when the message file was created. + */ + created_at: number; + /** + * The ID of the [message](https://platform.openai.com/docs/api-reference/messages) + * that the [File](https://platform.openai.com/docs/api-reference/files) is + * attached to. + */ + message_id: string; + /** + * The object type, which is always `thread.message.file`. + */ + object: 'thread.message.file'; +} +export interface FileListParams extends CursorPageParams { + /** + * A cursor for use in pagination. `before` is an object ID that defines your place + * in the list. For instance, if you make a list request and receive 100 objects, + * ending with obj_foo, your subsequent call can include before=obj_foo in order to + * fetch the previous page of the list. + */ + before?: string; + /** + * Sort order by the `created_at` timestamp of the objects. `asc` for ascending + * order and `desc` for descending order. + */ + order?: 'asc' | 'desc'; +} +export declare namespace Files { + export import MessageFile = FilesAPI.MessageFile; + export import MessageFilesPage = FilesAPI.MessageFilesPage; + export import FileListParams = FilesAPI.FileListParams; +} +//# sourceMappingURL=files.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/threads/messages/files.d.ts.map b/backend/node_modules/openai/resources/beta/threads/messages/files.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..c64e824fde64069505183fd13941bceed4d57926 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/threads/messages/files.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"files.d.ts","sourceRoot":"","sources":["../../../../src/resources/beta/threads/messages/files.ts"],"names":[],"mappings":"AAEA,OA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yBAAiB,KAAK,CAAC;IACrB,MAAM,QAAQ,WAAW,GAAG,QAAQ,CAAC,WAAW,CAAC;IACjD,MAAM,QAAQ,gBAAgB,GAAG,QAAQ,CAAC,gBAAgB,CAAC;IAC3D,MAAM,QAAQ,cAAc,GAAG,QAAQ,CAAC,cAAc,CAAC;CACxD"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/threads/messages/files.js b/backend/node_modules/openai/resources/beta/threads/messages/files.js new file mode 100644 index 0000000000000000000000000000000000000000..845fe44d3bfb2b5ffed45f71d11311b399609c12 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/threads/messages/files.js @@ -0,0 +1,60 @@ +"use strict"; +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MessageFilesPage = exports.Files = void 0; +const resource_1 = require("openai/resource"); +const core_1 = require("openai/core"); +const FilesAPI = __importStar(require("openai/resources/beta/threads/messages/files")); +const pagination_1 = require("openai/pagination"); +class Files extends resource_1.APIResource { + /** + * Retrieves a message file. + */ + retrieve(threadId, messageId, fileId, options) { + return this._client.get(`/threads/${threadId}/messages/${messageId}/files/${fileId}`, { + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } + list(threadId, messageId, query = {}, options) { + if ((0, core_1.isRequestOptions)(query)) { + return this.list(threadId, messageId, {}, query); + } + return this._client.getAPIList(`/threads/${threadId}/messages/${messageId}/files`, MessageFilesPage, { + query, + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } +} +exports.Files = Files; +class MessageFilesPage extends pagination_1.CursorPage { +} +exports.MessageFilesPage = MessageFilesPage; +(function (Files) { + Files.MessageFilesPage = FilesAPI.MessageFilesPage; +})(Files = exports.Files || (exports.Files = {})); +//# sourceMappingURL=files.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/threads/messages/files.js.map b/backend/node_modules/openai/resources/beta/threads/messages/files.js.map new file mode 100644 index 0000000000000000000000000000000000000000..54de04df893cd1b56808bdef7a53e10a8c2fca26 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/threads/messages/files.js.map @@ -0,0 +1 @@ +{"version":3,"file":"files.js","sourceRoot":"","sources":["../../../../src/resources/beta/threads/messages/files.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;;;;;;;;;;;;;;;;;;;;;;;;AAGtF,8CAA8C;AAC9C,sCAA+C;AAC/C,uFAAyE;AACzE,kDAAsE;AAEtE,MAAa,KAAM,SAAQ,sBAAW;IACpC;;OAEG;IACH,QAAQ,CACN,QAAgB,EAChB,SAAiB,EACjB,MAAc,EACd,OAA6B;QAE7B,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,YAAY,QAAQ,aAAa,SAAS,UAAU,MAAM,EAAE,EAAE;YACpF,GAAG,OAAO;YACV,OAAO,EAAE,EAAE,aAAa,EAAE,eAAe,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE;SACjE,CAAC,CAAC;IACL,CAAC;IAgBD,IAAI,CACF,QAAgB,EAChB,SAAiB,EACjB,QAA8C,EAAE,EAChD,OAA6B;QAE7B,IAAI,IAAA,uBAAgB,EAAC,KAAK,CAAC,EAAE;YAC3B,OAAO,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,SAAS,EAAE,EAAE,EAAE,KAAK,CAAC,CAAC;SAClD;QACD,OAAO,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,YAAY,QAAQ,aAAa,SAAS,QAAQ,EAAE,gBAAgB,EAAE;YACnG,KAAK;YACL,GAAG,OAAO;YACV,OAAO,EAAE,EAAE,aAAa,EAAE,eAAe,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE;SACjE,CAAC,CAAC;IACL,CAAC;CACF;AA7CD,sBA6CC;AAED,MAAa,gBAAiB,SAAQ,uBAAuB;CAAG;AAAhE,4CAAgE;AA6ChE,WAAiB,KAAK;IAEN,sBAAgB,GAAG,QAAQ,CAAC,gBAAgB,CAAC;AAE7D,CAAC,EAJgB,KAAK,GAAL,aAAK,KAAL,aAAK,QAIrB"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/threads/messages/files.mjs b/backend/node_modules/openai/resources/beta/threads/messages/files.mjs new file mode 100644 index 0000000000000000000000000000000000000000..64bf7fba6394429a6b253c4b21abf9cf60111ee3 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/threads/messages/files.mjs @@ -0,0 +1,32 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +import { APIResource } from 'openai/resource'; +import { isRequestOptions } from 'openai/core'; +import * as FilesAPI from 'openai/resources/beta/threads/messages/files'; +import { CursorPage } from 'openai/pagination'; +export class Files extends APIResource { + /** + * Retrieves a message file. + */ + retrieve(threadId, messageId, fileId, options) { + return this._client.get(`/threads/${threadId}/messages/${messageId}/files/${fileId}`, { + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } + list(threadId, messageId, query = {}, options) { + if (isRequestOptions(query)) { + return this.list(threadId, messageId, {}, query); + } + return this._client.getAPIList(`/threads/${threadId}/messages/${messageId}/files`, MessageFilesPage, { + query, + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } +} +export class MessageFilesPage extends CursorPage { +} +(function (Files) { + Files.MessageFilesPage = FilesAPI.MessageFilesPage; +})(Files || (Files = {})); +//# sourceMappingURL=files.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/threads/messages/files.mjs.map b/backend/node_modules/openai/resources/beta/threads/messages/files.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..190774db673321613a18f5e10d864173c6cdd9b8 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/threads/messages/files.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"files.mjs","sourceRoot":"","sources":["../../../../src/resources/beta/threads/messages/files.ts"],"names":[],"mappings":"AAAA,sFAAsF;OAG/E,EAAE,WAAW,EAAE,MAAM,iBAAiB;OACtC,EAAE,gBAAgB,EAAE,MAAM,aAAa;OACvC,KAAK,QAAQ,MAAM,8CAA8C;OACjE,EAAE,UAAU,EAAyB,MAAM,mBAAmB;AAErE,MAAM,OAAO,KAAM,SAAQ,WAAW;IACpC;;OAEG;IACH,QAAQ,CACN,QAAgB,EAChB,SAAiB,EACjB,MAAc,EACd,OAA6B;QAE7B,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,YAAY,QAAQ,aAAa,SAAS,UAAU,MAAM,EAAE,EAAE;YACpF,GAAG,OAAO;YACV,OAAO,EAAE,EAAE,aAAa,EAAE,eAAe,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE;SACjE,CAAC,CAAC;IACL,CAAC;IAgBD,IAAI,CACF,QAAgB,EAChB,SAAiB,EACjB,QAA8C,EAAE,EAChD,OAA6B;QAE7B,IAAI,gBAAgB,CAAC,KAAK,CAAC,EAAE;YAC3B,OAAO,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,SAAS,EAAE,EAAE,EAAE,KAAK,CAAC,CAAC;SAClD;QACD,OAAO,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,YAAY,QAAQ,aAAa,SAAS,QAAQ,EAAE,gBAAgB,EAAE;YACnG,KAAK;YACL,GAAG,OAAO;YACV,OAAO,EAAE,EAAE,aAAa,EAAE,eAAe,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE;SACjE,CAAC,CAAC;IACL,CAAC;CACF;AAED,MAAM,OAAO,gBAAiB,SAAQ,UAAuB;CAAG;AA6ChE,WAAiB,KAAK;IAEN,sBAAgB,GAAG,QAAQ,CAAC,gBAAgB,CAAC;AAE7D,CAAC,EAJgB,KAAK,KAAL,KAAK,QAIrB"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/threads/messages/index.d.ts b/backend/node_modules/openai/resources/beta/threads/messages/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..846e94c390b77b83a721382ba6b8ecc70fea1b33 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/threads/messages/index.d.ts @@ -0,0 +1,3 @@ +export { Annotation, AnnotationDelta, FileCitationAnnotation, FileCitationDeltaAnnotation, FilePathAnnotation, FilePathDeltaAnnotation, ImageFile, ImageFileContentBlock, ImageFileDelta, ImageFileDeltaBlock, Message, MessageContent, MessageContentDelta, MessageDeleted, MessageDelta, MessageDeltaEvent, Text, TextContentBlock, TextDelta, TextDeltaBlock, MessageCreateParams, MessageUpdateParams, MessageListParams, MessagesPage, Messages, } from "./messages.js"; +export { MessageFile, FileListParams, MessageFilesPage, Files } from "./files.js"; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/threads/messages/index.d.ts.map b/backend/node_modules/openai/resources/beta/threads/messages/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..371dc9bb0a6ecfcfd50e9adcadcdddc606c91f55 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/threads/messages/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/resources/beta/threads/messages/index.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,UAAU,EACV,eAAe,EACf,sBAAsB,EACtB,2BAA2B,EAC3B,kBAAkB,EAClB,uBAAuB,EACvB,SAAS,EACT,qBAAqB,EACrB,cAAc,EACd,mBAAmB,EACnB,OAAO,EACP,cAAc,EACd,mBAAmB,EACnB,cAAc,EACd,YAAY,EACZ,iBAAiB,EACjB,IAAI,EACJ,gBAAgB,EAChB,SAAS,EACT,cAAc,EACd,mBAAmB,EACnB,mBAAmB,EACnB,iBAAiB,EACjB,YAAY,EACZ,QAAQ,GACT,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,WAAW,EAAE,cAAc,EAAE,gBAAgB,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/threads/messages/index.js b/backend/node_modules/openai/resources/beta/threads/messages/index.js new file mode 100644 index 0000000000000000000000000000000000000000..2ef8d9b1777f424549dd5f355936b9cd03b3ba61 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/threads/messages/index.js @@ -0,0 +1,11 @@ +"use strict"; +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Files = exports.MessageFilesPage = exports.Messages = exports.MessagesPage = void 0; +var messages_1 = require("./messages.js"); +Object.defineProperty(exports, "MessagesPage", { enumerable: true, get: function () { return messages_1.MessagesPage; } }); +Object.defineProperty(exports, "Messages", { enumerable: true, get: function () { return messages_1.Messages; } }); +var files_1 = require("./files.js"); +Object.defineProperty(exports, "MessageFilesPage", { enumerable: true, get: function () { return files_1.MessageFilesPage; } }); +Object.defineProperty(exports, "Files", { enumerable: true, get: function () { return files_1.Files; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/threads/messages/index.js.map b/backend/node_modules/openai/resources/beta/threads/messages/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..af2fe71e29ad13ed848e5513c70470db320996ca --- /dev/null +++ b/backend/node_modules/openai/resources/beta/threads/messages/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/resources/beta/threads/messages/index.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;AAEtF,0CA0BoB;AAFlB,wGAAA,YAAY,OAAA;AACZ,oGAAA,QAAQ,OAAA;AAEV,oCAA+E;AAAzC,yGAAA,gBAAgB,OAAA;AAAE,8FAAA,KAAK,OAAA"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/threads/messages/index.mjs b/backend/node_modules/openai/resources/beta/threads/messages/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..a60a275018081e916aa5a86b2d9d482bdc2e4f32 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/threads/messages/index.mjs @@ -0,0 +1,4 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +export { MessagesPage, Messages, } from "./messages.mjs"; +export { MessageFilesPage, Files } from "./files.mjs"; +//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/threads/messages/index.mjs.map b/backend/node_modules/openai/resources/beta/threads/messages/index.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..42b476bffc1029eec59b3aa513c11d8c181e4d6b --- /dev/null +++ b/backend/node_modules/openai/resources/beta/threads/messages/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"index.mjs","sourceRoot":"","sources":["../../../../src/resources/beta/threads/messages/index.ts"],"names":[],"mappings":"AAAA,sFAAsF;OAE/E,EAwBL,YAAY,EACZ,QAAQ,GACT;OACM,EAA+B,gBAAgB,EAAE,KAAK,EAAE"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/threads/messages/messages.d.ts b/backend/node_modules/openai/resources/beta/threads/messages/messages.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..43fe1f0da4cdc2803b3e97136188879107cf75b7 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/threads/messages/messages.d.ts @@ -0,0 +1,458 @@ +import * as Core from 'openai/core'; +import { APIResource } from 'openai/resource'; +import * as MessagesAPI from 'openai/resources/beta/threads/messages/messages'; +import * as FilesAPI from 'openai/resources/beta/threads/messages/files'; +import { CursorPage, type CursorPageParams } from 'openai/pagination'; +export declare class Messages extends APIResource { + files: FilesAPI.Files; + /** + * Create a message. + */ + create(threadId: string, body: MessageCreateParams, options?: Core.RequestOptions): Core.APIPromise; + /** + * Retrieve a message. + */ + retrieve(threadId: string, messageId: string, options?: Core.RequestOptions): Core.APIPromise; + /** + * Modifies a message. + */ + update(threadId: string, messageId: string, body: MessageUpdateParams, options?: Core.RequestOptions): Core.APIPromise; + /** + * Returns a list of messages for a given thread. + */ + list(threadId: string, query?: MessageListParams, options?: Core.RequestOptions): Core.PagePromise; + list(threadId: string, options?: Core.RequestOptions): Core.PagePromise; +} +export declare class MessagesPage extends CursorPage { +} +/** + * A citation within the message that points to a specific quote from a specific + * File associated with the assistant or the message. Generated when the assistant + * uses the "retrieval" tool to search files. + */ +export type Annotation = FileCitationAnnotation | FilePathAnnotation; +/** + * A citation within the message that points to a specific quote from a specific + * File associated with the assistant or the message. Generated when the assistant + * uses the "retrieval" tool to search files. + */ +export type AnnotationDelta = FileCitationDeltaAnnotation | FilePathDeltaAnnotation; +/** + * A citation within the message that points to a specific quote from a specific + * File associated with the assistant or the message. Generated when the assistant + * uses the "retrieval" tool to search files. + */ +export interface FileCitationAnnotation { + end_index: number; + file_citation: FileCitationAnnotation.FileCitation; + start_index: number; + /** + * The text in the message content that needs to be replaced. + */ + text: string; + /** + * Always `file_citation`. + */ + type: 'file_citation'; +} +export declare namespace FileCitationAnnotation { + interface FileCitation { + /** + * The ID of the specific File the citation is from. + */ + file_id: string; + /** + * The specific quote in the file. + */ + quote: string; + } +} +/** + * A citation within the message that points to a specific quote from a specific + * File associated with the assistant or the message. Generated when the assistant + * uses the "retrieval" tool to search files. + */ +export interface FileCitationDeltaAnnotation { + /** + * The index of the annotation in the text content part. + */ + index: number; + /** + * Always `file_citation`. + */ + type: 'file_citation'; + end_index?: number; + file_citation?: FileCitationDeltaAnnotation.FileCitation; + start_index?: number; + /** + * The text in the message content that needs to be replaced. + */ + text?: string; +} +export declare namespace FileCitationDeltaAnnotation { + interface FileCitation { + /** + * The ID of the specific File the citation is from. + */ + file_id?: string; + /** + * The specific quote in the file. + */ + quote?: string; + } +} +/** + * A URL for the file that's generated when the assistant used the + * `code_interpreter` tool to generate a file. + */ +export interface FilePathAnnotation { + end_index: number; + file_path: FilePathAnnotation.FilePath; + start_index: number; + /** + * The text in the message content that needs to be replaced. + */ + text: string; + /** + * Always `file_path`. + */ + type: 'file_path'; +} +export declare namespace FilePathAnnotation { + interface FilePath { + /** + * The ID of the file that was generated. + */ + file_id: string; + } +} +/** + * A URL for the file that's generated when the assistant used the + * `code_interpreter` tool to generate a file. + */ +export interface FilePathDeltaAnnotation { + /** + * The index of the annotation in the text content part. + */ + index: number; + /** + * Always `file_path`. + */ + type: 'file_path'; + end_index?: number; + file_path?: FilePathDeltaAnnotation.FilePath; + start_index?: number; + /** + * The text in the message content that needs to be replaced. + */ + text?: string; +} +export declare namespace FilePathDeltaAnnotation { + interface FilePath { + /** + * The ID of the file that was generated. + */ + file_id?: string; + } +} +export interface ImageFile { + /** + * The [File](https://platform.openai.com/docs/api-reference/files) ID of the image + * in the message content. + */ + file_id: string; +} +/** + * References an image [File](https://platform.openai.com/docs/api-reference/files) + * in the content of a message. + */ +export interface ImageFileContentBlock { + image_file: ImageFile; + /** + * Always `image_file`. + */ + type: 'image_file'; +} +export interface ImageFileDelta { + /** + * The [File](https://platform.openai.com/docs/api-reference/files) ID of the image + * in the message content. + */ + file_id?: string; +} +/** + * References an image [File](https://platform.openai.com/docs/api-reference/files) + * in the content of a message. + */ +export interface ImageFileDeltaBlock { + /** + * The index of the content part in the message. + */ + index: number; + /** + * Always `image_file`. + */ + type: 'image_file'; + image_file?: ImageFileDelta; +} +/** + * Represents a message within a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ +export interface Message { + /** + * The identifier, which can be referenced in API endpoints. + */ + id: string; + /** + * If applicable, the ID of the + * [assistant](https://platform.openai.com/docs/api-reference/assistants) that + * authored this message. + */ + assistant_id: string | null; + /** + * The Unix timestamp (in seconds) for when the message was completed. + */ + completed_at: number | null; + /** + * The content of the message in array of text and/or images. + */ + content: Array; + /** + * The Unix timestamp (in seconds) for when the message was created. + */ + created_at: number; + /** + * A list of [file](https://platform.openai.com/docs/api-reference/files) IDs that + * the assistant should use. Useful for tools like retrieval and code_interpreter + * that can access files. A maximum of 10 files can be attached to a message. + */ + file_ids: Array; + /** + * The Unix timestamp (in seconds) for when the message was marked as incomplete. + */ + incomplete_at: number | null; + /** + * On an incomplete message, details about why the message is incomplete. + */ + incomplete_details: Message.IncompleteDetails | null; + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata: unknown | null; + /** + * The object type, which is always `thread.message`. + */ + object: 'thread.message'; + /** + * The entity that produced the message. One of `user` or `assistant`. + */ + role: 'user' | 'assistant'; + /** + * The ID of the [run](https://platform.openai.com/docs/api-reference/runs) + * associated with the creation of this message. Value is `null` when messages are + * created manually using the create message or create thread endpoints. + */ + run_id: string | null; + /** + * The status of the message, which can be either `in_progress`, `incomplete`, or + * `completed`. + */ + status: 'in_progress' | 'incomplete' | 'completed'; + /** + * The [thread](https://platform.openai.com/docs/api-reference/threads) ID that + * this message belongs to. + */ + thread_id: string; +} +export declare namespace Message { + /** + * On an incomplete message, details about why the message is incomplete. + */ + interface IncompleteDetails { + /** + * The reason the message is incomplete. + */ + reason: 'content_filter' | 'max_tokens' | 'run_cancelled' | 'run_expired' | 'run_failed'; + } +} +/** + * References an image [File](https://platform.openai.com/docs/api-reference/files) + * in the content of a message. + */ +export type MessageContent = ImageFileContentBlock | TextContentBlock; +/** + * References an image [File](https://platform.openai.com/docs/api-reference/files) + * in the content of a message. + */ +export type MessageContentDelta = ImageFileDeltaBlock | TextDeltaBlock; +export interface MessageDeleted { + id: string; + deleted: boolean; + object: 'thread.message.deleted'; +} +/** + * The delta containing the fields that have changed on the Message. + */ +export interface MessageDelta { + /** + * The content of the message in array of text and/or images. + */ + content?: Array; + /** + * A list of [file](https://platform.openai.com/docs/api-reference/files) IDs that + * the assistant should use. Useful for tools like retrieval and code_interpreter + * that can access files. A maximum of 10 files can be attached to a message. + */ + file_ids?: Array; + /** + * The entity that produced the message. One of `user` or `assistant`. + */ + role?: 'user' | 'assistant'; +} +/** + * Represents a message delta i.e. any changed fields on a message during + * streaming. + */ +export interface MessageDeltaEvent { + /** + * The identifier of the message, which can be referenced in API endpoints. + */ + id: string; + /** + * The delta containing the fields that have changed on the Message. + */ + delta: MessageDelta; + /** + * The object type, which is always `thread.message.delta`. + */ + object: 'thread.message.delta'; +} +export interface Text { + annotations: Array; + /** + * The data that makes up the text. + */ + value: string; +} +/** + * The text content that is part of a message. + */ +export interface TextContentBlock { + text: Text; + /** + * Always `text`. + */ + type: 'text'; +} +export interface TextDelta { + annotations?: Array; + /** + * The data that makes up the text. + */ + value?: string; +} +/** + * The text content that is part of a message. + */ +export interface TextDeltaBlock { + /** + * The index of the content part in the message. + */ + index: number; + /** + * Always `text`. + */ + type: 'text'; + text?: TextDelta; +} +export interface MessageCreateParams { + /** + * The content of the message. + */ + content: string; + /** + * The role of the entity that is creating the message. Allowed values include: + * + * - `user`: Indicates the message is sent by an actual user and should be used in + * most cases to represent user-generated messages. + * - `assistant`: Indicates the message is generated by the assistant. Use this + * value to insert messages from the assistant into the conversation. + */ + role: 'user' | 'assistant'; + /** + * A list of [File](https://platform.openai.com/docs/api-reference/files) IDs that + * the message should use. There can be a maximum of 10 files attached to a + * message. Useful for tools like `retrieval` and `code_interpreter` that can + * access and use files. + */ + file_ids?: Array; + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata?: unknown | null; +} +export interface MessageUpdateParams { + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata?: unknown | null; +} +export interface MessageListParams extends CursorPageParams { + /** + * A cursor for use in pagination. `before` is an object ID that defines your place + * in the list. For instance, if you make a list request and receive 100 objects, + * ending with obj_foo, your subsequent call can include before=obj_foo in order to + * fetch the previous page of the list. + */ + before?: string; + /** + * Sort order by the `created_at` timestamp of the objects. `asc` for ascending + * order and `desc` for descending order. + */ + order?: 'asc' | 'desc'; + /** + * Filter messages by the run ID that generated them. + */ + run_id?: string; +} +export declare namespace Messages { + export import Annotation = MessagesAPI.Annotation; + export import AnnotationDelta = MessagesAPI.AnnotationDelta; + export import FileCitationAnnotation = MessagesAPI.FileCitationAnnotation; + export import FileCitationDeltaAnnotation = MessagesAPI.FileCitationDeltaAnnotation; + export import FilePathAnnotation = MessagesAPI.FilePathAnnotation; + export import FilePathDeltaAnnotation = MessagesAPI.FilePathDeltaAnnotation; + export import ImageFile = MessagesAPI.ImageFile; + export import ImageFileContentBlock = MessagesAPI.ImageFileContentBlock; + export import ImageFileDelta = MessagesAPI.ImageFileDelta; + export import ImageFileDeltaBlock = MessagesAPI.ImageFileDeltaBlock; + export import Message = MessagesAPI.Message; + export import MessageContent = MessagesAPI.MessageContent; + export import MessageContentDelta = MessagesAPI.MessageContentDelta; + export import MessageDeleted = MessagesAPI.MessageDeleted; + export import MessageDelta = MessagesAPI.MessageDelta; + export import MessageDeltaEvent = MessagesAPI.MessageDeltaEvent; + export import Text = MessagesAPI.Text; + export import TextContentBlock = MessagesAPI.TextContentBlock; + export import TextDelta = MessagesAPI.TextDelta; + export import TextDeltaBlock = MessagesAPI.TextDeltaBlock; + export import MessagesPage = MessagesAPI.MessagesPage; + export import MessageCreateParams = MessagesAPI.MessageCreateParams; + export import MessageUpdateParams = MessagesAPI.MessageUpdateParams; + export import MessageListParams = MessagesAPI.MessageListParams; + export import Files = FilesAPI.Files; + export import MessageFile = FilesAPI.MessageFile; + export import MessageFilesPage = FilesAPI.MessageFilesPage; + export import FileListParams = FilesAPI.FileListParams; +} +//# sourceMappingURL=messages.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/threads/messages/messages.d.ts.map b/backend/node_modules/openai/resources/beta/threads/messages/messages.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..b71ea9af3fa0b3a85285108f7cf90c0fde0ce467 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/threads/messages/messages.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"messages.d.ts","sourceRoot":"","sources":["../../../../src/resources/beta/threads/messages/messages.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,IAAI,MAAM,aAAa,CAAC;AACpC,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAE9C,OAAO,KAAK,WAAW,MAAM,iDAAiD,CAAC;AAC/E,OAAO,KAAK,QAAQ,MAAM,8CAA8C,CAAC;AACzE,OAAO,EAAE,UAAU,EAAE,KAAK,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAEtE,qBAAa,QAAS,SAAQ,WAAW;IACvC,KAAK,EAAE,QAAQ,CAAC,KAAK,CAAoC;IAEzD;;OAEG;IACH,MAAM,CACJ,QAAQ,EAAE,MAAM,EAChB,IAAI,EAAE,mBAAmB,EACzB,OAAO,CAAC,EAAE,IAAI,CAAC,cAAc,GAC5B,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC;IAQ3B;;OAEG;IACH,QAAQ,CAAC,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC;IAOtG;;OAEG;IACH,MAAM,CACJ,QAAQ,EAAE,MAAM,EAChB,SAAS,EAAE,MAAM,EAC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,cAAc,CAAC;IAC1D,MAAM,QAAQ,mBAAmB,GAAG,WAAW,CAAC,mBAAmB,CAAC;IACpE,MAAM,QAAQ,cAAc,GAAG,WAAW,CAAC,cAAc,CAAC;IAC1D,MAAM,QAAQ,YAAY,GAAG,WAAW,CAAC,YAAY,CAAC;IACtD,MAAM,QAAQ,iBAAiB,GAAG,WAAW,CAAC,iBAAiB,CAAC;IAChE,MAAM,QAAQ,IAAI,GAAG,WAAW,CAAC,IAAI,CAAC;IACtC,MAAM,QAAQ,gBAAgB,GAAG,WAAW,CAAC,gBAAgB,CAAC;IAC9D,MAAM,QAAQ,SAAS,GAAG,WAAW,CAAC,SAAS,CAAC;IAChD,MAAM,QAAQ,cAAc,GAAG,WAAW,CAAC,cAAc,CAAC;IAC1D,MAAM,QAAQ,YAAY,GAAG,WAAW,CAAC,YAAY,CAAC;IACtD,MAAM,QAAQ,mBAAmB,GAAG,WAAW,CAAC,mBAAmB,CAAC;IACpE,MAAM,QAAQ,mBAAmB,GAAG,WAAW,CAAC,mBAAmB,CAAC;IACpE,MAAM,QAAQ,iBAAiB,GAAG,WAAW,CAAC,iBAAiB,CAAC;IAChE,MAAM,QAAQ,KAAK,GAAG,QAAQ,CAAC,KAAK,CAAC;IACrC,MAAM,QAAQ,WAAW,GAAG,QAAQ,CAAC,WAAW,CAAC;IACjD,MAAM,QAAQ,gBAAgB,GAAG,QAAQ,CAAC,gBAAgB,CAAC;IAC3D,MAAM,QAAQ,cAAc,GAAG,QAAQ,CAAC,cAAc,CAAC;CACxD"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/threads/messages/messages.js b/backend/node_modules/openai/resources/beta/threads/messages/messages.js new file mode 100644 index 0000000000000000000000000000000000000000..306a4b2413a079851a95daede2e78c0699d7eaa0 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/threads/messages/messages.js @@ -0,0 +1,87 @@ +"use strict"; +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MessagesPage = exports.Messages = void 0; +const resource_1 = require("openai/resource"); +const core_1 = require("openai/core"); +const MessagesAPI = __importStar(require("openai/resources/beta/threads/messages/messages")); +const FilesAPI = __importStar(require("openai/resources/beta/threads/messages/files")); +const pagination_1 = require("openai/pagination"); +class Messages extends resource_1.APIResource { + constructor() { + super(...arguments); + this.files = new FilesAPI.Files(this._client); + } + /** + * Create a message. + */ + create(threadId, body, options) { + return this._client.post(`/threads/${threadId}/messages`, { + body, + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } + /** + * Retrieve a message. + */ + retrieve(threadId, messageId, options) { + return this._client.get(`/threads/${threadId}/messages/${messageId}`, { + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } + /** + * Modifies a message. + */ + update(threadId, messageId, body, options) { + return this._client.post(`/threads/${threadId}/messages/${messageId}`, { + body, + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } + list(threadId, query = {}, options) { + if ((0, core_1.isRequestOptions)(query)) { + return this.list(threadId, {}, query); + } + return this._client.getAPIList(`/threads/${threadId}/messages`, MessagesPage, { + query, + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } +} +exports.Messages = Messages; +class MessagesPage extends pagination_1.CursorPage { +} +exports.MessagesPage = MessagesPage; +(function (Messages) { + Messages.MessagesPage = MessagesAPI.MessagesPage; + Messages.Files = FilesAPI.Files; + Messages.MessageFilesPage = FilesAPI.MessageFilesPage; +})(Messages = exports.Messages || (exports.Messages = {})); +//# sourceMappingURL=messages.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/threads/messages/messages.js.map b/backend/node_modules/openai/resources/beta/threads/messages/messages.js.map new file mode 100644 index 0000000000000000000000000000000000000000..d27a5aa6ce0128fb036600e86c91494792564f71 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/threads/messages/messages.js.map @@ -0,0 +1 @@ +{"version":3,"file":"messages.js","sourceRoot":"","sources":["../../../../src/resources/beta/threads/messages/messages.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;;;;;;;;;;;;;;;;;;;;;;;;AAGtF,8CAA8C;AAC9C,sCAA+C;AAC/C,6FAA+E;AAC/E,uFAAyE;AACzE,kDAAsE;AAEtE,MAAa,QAAS,SAAQ,sBAAW;IAAzC;;QACE,UAAK,GAAmB,IAAI,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IAkE3D,CAAC;IAhEC;;OAEG;IACH,MAAM,CACJ,QAAgB,EAChB,IAAyB,EACzB,OAA6B;QAE7B,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,YAAY,QAAQ,WAAW,EAAE;YACxD,IAAI;YACJ,GAAG,OAAO;YACV,OAAO,EAAE,EAAE,aAAa,EAAE,eAAe,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE;SACjE,CAAC,CAAC;IACL,CAAC;IAED;;OAEG;IACH,QAAQ,CAAC,QAAgB,EAAE,SAAiB,EAAE,OAA6B;QACzE,OAAO,IAAI,CAAC,OAA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ta/threads/messages/messages.mjs b/backend/node_modules/openai/resources/beta/threads/messages/messages.mjs new file mode 100644 index 0000000000000000000000000000000000000000..54442b7bf30c1c74bcc00fc48fbff60743f5f7b3 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/threads/messages/messages.mjs @@ -0,0 +1,59 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +import { APIResource } from 'openai/resource'; +import { isRequestOptions } from 'openai/core'; +import * as MessagesAPI from 'openai/resources/beta/threads/messages/messages'; +import * as FilesAPI from 'openai/resources/beta/threads/messages/files'; +import { CursorPage } from 'openai/pagination'; +export class Messages extends APIResource { + constructor() { + super(...arguments); + this.files = new FilesAPI.Files(this._client); + } + /** + * Create a message. + */ + create(threadId, body, options) { + return this._client.post(`/threads/${threadId}/messages`, { + body, + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } + /** + * Retrieve a message. + */ + retrieve(threadId, messageId, options) { + return this._client.get(`/threads/${threadId}/messages/${messageId}`, { + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } + /** + * Modifies a message. + */ + update(threadId, messageId, body, options) { + return this._client.post(`/threads/${threadId}/messages/${messageId}`, { + body, + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } + list(threadId, query = {}, options) { + if (isRequestOptions(query)) { + return this.list(threadId, {}, query); + } + return this._client.getAPIList(`/threads/${threadId}/messages`, MessagesPage, { + query, + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } +} +export class MessagesPage extends CursorPage { +} +(function (Messages) { + Messages.MessagesPage = MessagesAPI.MessagesPage; + Messages.Files = FilesAPI.Files; + Messages.MessageFilesPage = FilesAPI.MessageFilesPage; +})(Messages || (Messages = {})); +//# sourceMappingURL=messages.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/threads/messages/messages.mjs.map b/backend/node_modules/openai/resources/beta/threads/messages/messages.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..28537cd0a743d73acd53617a65c49a8bec40034a --- /dev/null +++ b/backend/node_modules/openai/resources/beta/threads/messages/messages.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"messages.mjs","sourceRoot":"","sources":["../../../../src/resources/beta/threads/messages/messages.ts"],"names":[],"mappings":"AAAA,sFAAsF;OAG/E,EAAE,WAAW,EAAE,MAAM,iBAAiB;OACtC,EAAE,gBAAgB,EAAE,MAAM,aAAa;OACvC,KAAK,WAAW,MAAM,iDAAiD;OACvE,KAAK,QAAQ,MAAM,8CAA8C;OACjE,EAAE,UAAU,EAAyB,MAAM,mBAAmB;AAErE,MAAM,OAAO,QAAS,SAAQ,WAAW;IAAzC;;QACE,UAAK,GAAmB,IAAI,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IAkE3D,CAAC;IAhEC;;OAEG;IACH,MAAM,CACJ,QAAgB,EAChB,IAAyB,EACzB,OAA6B;QAE7B,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,YAAY,QAAQ,WAAW,EAAE;YACxD,IAAI;YACJ,GAAG,OAAO;YACV,OAAO,EAAE,EAAE,aAAa,EAAE,eAAe,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE;SACjE,CAAC,CAAC;IACL,CAAC;IAED;;OAEG;IACH,QAAQ,CAAC,QAAgB,EAAE,SAAiB,EAAE,OAA6B;QACzE,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,YAAY,QAAQ,aAAa,SAAS,EAAE,EAAE;YACpE,GAAG,OAAO;YACV,OAAO,EAAE,EAAE,aAAa,EAAE,eAAe,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE;SACjE,CAAC,CAAC;IACL,CAAC;IAED;;OAEG;IACH,MAAM,CACJ,QAAgB,EAChB,SAAiB,EACjB,IAAyB,EACzB,OAA6B;QAE7B,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,YAAY,QAAQ,aAAa,SAAS,EAAE,EAAE;YACrE,IAAI;YACJ,GAAG,OAAO;YACV,OAAO,EAAE,EAAE,aAAa,EAAE,eAAe,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE;SACjE,CAAC,CAAC;IACL,CAAC;IAWD,IAAI,CACF,QAAgB,EAChB,QAAiD,EAAE,EACnD,OAA6B;QAE7B,IAAI,gBAAgB,CAAC,KAAK,CAAC,EAAE;YAC3B,OAAO,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,EAAE,EAAE,KAAK,CAAC,CAAC;SACvC;QACD,OAAO,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,YAAY,QAAQ,WAAW,EAAE,YAAY,EAAE;YAC5E,KAAK;YACL,GAAG,OAAO;YACV,OAAO,EAAE,EAAE,aAAa,EAAE,eAAe,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE;SACjE,CAAC,CAAC;IACL,CAAC;CACF;AAED,MAAM,OAAO,YAAa,SAAQ,UAAmB;CAAG;AAkexD,WAAiB,QAAQ;IAqBT,qBAAY,GAAG,WAAW,CAAC,YAAY,CAAC;IAIxC,cAAK,GAAG,QAAQ,CAAC,KAAK,CAAC;IAEvB,yBAAgB,GAAG,QAAQ,CAAC,gBAAgB,CAAC;AAE7D,CAAC,EA7BgB,QAAQ,KAAR,QAAQ,QA6BxB"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/threads/runs/index.d.ts b/backend/node_modules/openai/resources/beta/threads/runs/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9bb5646a28467af2c2079ebf53b40d3b1976e86f --- /dev/null +++ b/backend/node_modules/openai/resources/beta/threads/runs/index.d.ts @@ -0,0 +1,3 @@ +export { CodeInterpreterLogs, CodeInterpreterOutputImage, CodeInterpreterToolCall, CodeInterpreterToolCallDelta, FunctionToolCall, FunctionToolCallDelta, MessageCreationStepDetails, RetrievalToolCall, RetrievalToolCallDelta, RunStep, RunStepDelta, RunStepDeltaEvent, RunStepDeltaMessageDelta, ToolCall, ToolCallDelta, ToolCallDeltaObject, ToolCallsStepDetails, StepListParams, RunStepsPage, Steps, } from "./steps.js"; +export { RequiredActionFunctionToolCall, Run, RunStatus, RunCreateParams, RunCreateParamsNonStreaming, RunCreateParamsStreaming, RunUpdateParams, RunListParams, RunCreateAndPollParams, RunCreateAndStreamParams, RunStreamParams, RunSubmitToolOutputsParams, RunSubmitToolOutputsParamsNonStreaming, RunSubmitToolOutputsParamsStreaming, RunSubmitToolOutputsAndPollParams, RunSubmitToolOutputsStreamParams, RunsPage, Runs, } from "./runs.js"; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/threads/runs/index.d.ts.map b/backend/node_modules/openai/resources/beta/threads/runs/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..fe57c02c7152721d27432903622e3452cb6e9f61 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/threads/runs/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/resources/beta/threads/runs/index.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,mBAAmB,EACnB,0BAA0B,EAC1B,uBAAuB,EACvB,4BAA4B,EAC5B,gBAAgB,EAChB,qBAAqB,EACrB,0BAA0B,EAC1B,iBAAiB,EACjB,sBAAsB,EACtB,OAAO,EACP,YAAY,EACZ,iBAAiB,EACjB,wBAAwB,EACxB,QAAQ,EACR,aAAa,EACb,mBAAmB,EACnB,oBAAoB,EACpB,cAAc,EACd,YAAY,EACZ,KAAK,GACN,MAAM,SAAS,CAAC;AACjB,OAAO,EACL,8BAA8B,EAC9B,GAAG,EACH,SAAS,EACT,eAAe,EACf,2BAA2B,EAC3B,wBAAwB,EACxB,eAAe,EACf,aAAa,EACb,sBAAsB,EACtB,wBAAwB,EACxB,eAAe,EACf,0BAA0B,EAC1B,sCAAsC,EACtC,mCAAmC,EACnC,iCAAiC,EACjC,gCAAgC,EAChC,QAAQ,EACR,IAAI,GACL,MAAM,QAAQ,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/threads/runs/index.js b/backend/node_modules/openai/resources/beta/threads/runs/index.js new file mode 100644 index 0000000000000000000000000000000000000000..d4f1789c75abd61815a04f2204c0ff1ee5068887 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/threads/runs/index.js @@ -0,0 +1,11 @@ +"use strict"; +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Runs = exports.RunsPage = exports.Steps = exports.RunStepsPage = void 0; +var steps_1 = require("./steps.js"); +Object.defineProperty(exports, "RunStepsPage", { enumerable: true, get: function () { return steps_1.RunStepsPage; } }); +Object.defineProperty(exports, "Steps", { enumerable: true, get: function () { return steps_1.Steps; } }); +var runs_1 = require("./runs.js"); +Object.defineProperty(exports, "RunsPage", { enumerable: true, get: function () { return runs_1.RunsPage; } }); +Object.defineProperty(exports, "Runs", { enumerable: true, get: function () { return runs_1.Runs; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/threads/runs/index.js.map b/backend/node_modules/openai/resources/beta/threads/runs/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..b8478b1753bccb693f1c3a693893231b89b5d94b --- /dev/null +++ b/backend/node_modules/openai/resources/beta/threads/runs/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/resources/beta/threads/runs/index.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;AAEtF,oCAqBiB;AAFf,qGAAA,YAAY,OAAA;AACZ,8FAAA,KAAK,OAAA;AAEP,kCAmBgB;AAFd,gGAAA,QAAQ,OAAA;AACR,4FAAA,IAAI,OAAA"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/threads/runs/index.mjs b/backend/node_modules/openai/resources/beta/threads/runs/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..6d13e81c4912eba993fe6b372a829ff65a95fd60 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/threads/runs/index.mjs @@ -0,0 +1,4 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +export { RunStepsPage, Steps, } from "./steps.mjs"; +export { RunsPage, Runs, } from "./runs.mjs"; +//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/threads/runs/index.mjs.map b/backend/node_modules/openai/resources/beta/threads/runs/index.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..9cf8a948fdf761bf4fa105142a157effa6d5c1ea --- /dev/null +++ b/backend/node_modules/openai/resources/beta/threads/runs/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"index.mjs","sourceRoot":"","sources":["../../../../src/resources/beta/threads/runs/index.ts"],"names":[],"mappings":"AAAA,sFAAsF;OAE/E,EAmBL,YAAY,EACZ,KAAK,GACN;OACM,EAiBL,QAAQ,EACR,IAAI,GACL"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/threads/runs/runs.d.ts b/backend/node_modules/openai/resources/beta/threads/runs/runs.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d03006c88ec7ea3ed2c775819ee3eb27ae320a7a --- /dev/null +++ b/backend/node_modules/openai/resources/beta/threads/runs/runs.d.ts @@ -0,0 +1,1077 @@ +import * as Core from 'openai/core'; +import { APIPromise } from 'openai/core'; +import { APIResource } from 'openai/resource'; +import { AssistantStream, RunCreateParamsBaseStream } from 'openai/lib/AssistantStream'; +import { RunSubmitToolOutputsParamsStream } from 'openai/lib/AssistantStream'; +import * as RunsAPI from 'openai/resources/beta/threads/runs/runs'; +import * as AssistantsAPI from 'openai/resources/beta/assistants/assistants'; +import * as ThreadsAPI from 'openai/resources/beta/threads/threads'; +import * as StepsAPI from 'openai/resources/beta/threads/runs/steps'; +import { CursorPage, type CursorPageParams } from 'openai/pagination'; +import { Stream } from 'openai/streaming'; +export declare class Runs extends APIResource { + steps: StepsAPI.Steps; + /** + * Create a run. + */ + create(threadId: string, body: RunCreateParamsNonStreaming, options?: Core.RequestOptions): APIPromise; + create(threadId: string, body: RunCreateParamsStreaming, options?: Core.RequestOptions): APIPromise>; + create(threadId: string, body: RunCreateParamsBase, options?: Core.RequestOptions): APIPromise | Run>; + /** + * Retrieves a run. + */ + retrieve(threadId: string, runId: string, options?: Core.RequestOptions): Core.APIPromise; + /** + * Modifies a run. + */ + update(threadId: string, runId: string, body: RunUpdateParams, options?: Core.RequestOptions): Core.APIPromise; + /** + * Returns a list of runs belonging to a thread. + */ + list(threadId: string, query?: RunListParams, options?: Core.RequestOptions): Core.PagePromise; + list(threadId: string, options?: Core.RequestOptions): Core.PagePromise; + /** + * Cancels a run that is `in_progress`. + */ + cancel(threadId: string, runId: string, options?: Core.RequestOptions): Core.APIPromise; + /** + * A helper to create a run an poll for a terminal state. More information on Run + * lifecycles can be found here: + * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps + */ + createAndPoll(threadId: string, body: RunCreateParamsNonStreaming, options?: Core.RequestOptions & { + pollIntervalMs?: number; + }): Promise; + /** + * Create a Run stream + * + * @deprecated use `stream` instead + */ + createAndStream(threadId: string, body: RunCreateParamsBaseStream, options?: Core.RequestOptions): AssistantStream; + /** + * A helper to poll a run status until it reaches a terminal state. More + * information on Run lifecycles can be found here: + * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps + */ + poll(threadId: string, runId: string, options?: Core.RequestOptions & { + pollIntervalMs?: number; + }): Promise; + /** + * Create a Run stream + */ + stream(threadId: string, body: RunCreateParamsBaseStream, options?: Core.RequestOptions): AssistantStream; + /** + * When a run has the `status: "requires_action"` and `required_action.type` is + * `submit_tool_outputs`, this endpoint can be used to submit the outputs from the + * tool calls once they're all completed. All outputs must be submitted in a single + * request. + */ + submitToolOutputs(threadId: string, runId: string, body: RunSubmitToolOutputsParamsNonStreaming, options?: Core.RequestOptions): APIPromise; + submitToolOutputs(threadId: string, runId: string, body: RunSubmitToolOutputsParamsStreaming, options?: Core.RequestOptions): APIPromise>; + submitToolOutputs(threadId: string, runId: string, body: RunSubmitToolOutputsParamsBase, options?: Core.RequestOptions): APIPromise | Run>; + /** + * A helper to submit a tool output to a run and poll for a terminal run state. + * More information on Run lifecycles can be found here: + * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps + */ + submitToolOutputsAndPoll(threadId: string, runId: string, body: RunSubmitToolOutputsParamsNonStreaming, options?: Core.RequestOptions & { + pollIntervalMs?: number; + }): Promise; + /** + * Submit the tool outputs from a previous run and stream the run to a terminal + * state. More information on Run lifecycles can be found here: + * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps + */ + submitToolOutputsStream(threadId: string, runId: string, body: RunSubmitToolOutputsParamsStream, options?: Core.RequestOptions): AssistantStream; +} +export declare class RunsPage extends CursorPage { +} +/** + * Tool call objects + */ +export interface RequiredActionFunctionToolCall { + /** + * The ID of the tool call. This ID must be referenced when you submit the tool + * outputs in using the + * [Submit tool outputs to run](https://platform.openai.com/docs/api-reference/runs/submitToolOutputs) + * endpoint. + */ + id: string; + /** + * The function definition. + */ + function: RequiredActionFunctionToolCall.Function; + /** + * The type of tool call the output is required for. For now, this is always + * `function`. + */ + type: 'function'; +} +export declare namespace RequiredActionFunctionToolCall { + /** + * The function definition. + */ + interface Function { + /** + * The arguments that the model expects you to pass to the function. + */ + arguments: string; + /** + * The name of the function. + */ + name: string; + } +} +/** + * Represents an execution run on a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ +export interface Run { + /** + * The identifier, which can be referenced in API endpoints. + */ + id: string; + /** + * The ID of the + * [assistant](https://platform.openai.com/docs/api-reference/assistants) used for + * execution of this run. + */ + assistant_id: string; + /** + * The Unix timestamp (in seconds) for when the run was cancelled. + */ + cancelled_at: number | null; + /** + * The Unix timestamp (in seconds) for when the run was completed. + */ + completed_at: number | null; + /** + * The Unix timestamp (in seconds) for when the run was created. + */ + created_at: number; + /** + * The Unix timestamp (in seconds) for when the run will expire. + */ + expires_at: number | null; + /** + * The Unix timestamp (in seconds) for when the run failed. + */ + failed_at: number | null; + /** + * The list of [File](https://platform.openai.com/docs/api-reference/files) IDs the + * [assistant](https://platform.openai.com/docs/api-reference/assistants) used for + * this run. + */ + file_ids: Array; + /** + * Details on why the run is incomplete. Will be `null` if the run is not + * incomplete. + */ + incomplete_details: Run.IncompleteDetails | null; + /** + * The instructions that the + * [assistant](https://platform.openai.com/docs/api-reference/assistants) used for + * this run. + */ + instructions: string; + /** + * The last error associated with this run. Will be `null` if there are no errors. + */ + last_error: Run.LastError | null; + /** + * The maximum number of completion tokens specified to have been used over the + * course of the run. + */ + max_completion_tokens: number | null; + /** + * The maximum number of prompt tokens specified to have been used over the course + * of the run. + */ + max_prompt_tokens: number | null; + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata: unknown | null; + /** + * The model that the + * [assistant](https://platform.openai.com/docs/api-reference/assistants) used for + * this run. + */ + model: string; + /** + * The object type, which is always `thread.run`. + */ + object: 'thread.run'; + /** + * Details on the action required to continue the run. Will be `null` if no action + * is required. + */ + required_action: Run.RequiredAction | null; + /** + * Specifies the format that the model must output. Compatible with + * [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and + * all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + * + * Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + * message the model generates is valid JSON. + * + * **Important:** when using JSON mode, you **must** also instruct the model to + * produce JSON yourself via a system or user message. Without this, the model may + * generate an unending stream of whitespace until the generation reaches the token + * limit, resulting in a long-running and seemingly "stuck" request. Also note that + * the message content may be partially cut off if `finish_reason="length"`, which + * indicates the generation exceeded `max_tokens` or the conversation exceeded the + * max context length. + */ + response_format: ThreadsAPI.AssistantResponseFormatOption | null; + /** + * The Unix timestamp (in seconds) for when the run was started. + */ + started_at: number | null; + /** + * The status of the run, which can be either `queued`, `in_progress`, + * `requires_action`, `cancelling`, `cancelled`, `failed`, `completed`, or + * `expired`. + */ + status: RunStatus; + /** + * The ID of the [thread](https://platform.openai.com/docs/api-reference/threads) + * that was executed on as a part of this run. + */ + thread_id: string; + /** + * Controls which (if any) tool is called by the model. `none` means the model will + * not call any tools and instead generates a message. `auto` is the default value + * and means the model can pick between generating a message or calling a tool. + * Specifying a particular tool like `{"type": "TOOL_TYPE"}` or + * `{"type": "function", "function": {"name": "my_function"}}` forces the model to + * call that tool. + */ + tool_choice: ThreadsAPI.AssistantToolChoiceOption | null; + /** + * The list of tools that the + * [assistant](https://platform.openai.com/docs/api-reference/assistants) used for + * this run. + */ + tools: Array; + truncation_strategy: Run.TruncationStrategy | null; + /** + * Usage statistics related to the run. This value will be `null` if the run is not + * in a terminal state (i.e. `in_progress`, `queued`, etc.). + */ + usage: Run.Usage | null; + /** + * The sampling temperature used for this run. If not set, defaults to 1. + */ + temperature?: number | null; +} +export declare namespace Run { + /** + * Details on why the run is incomplete. Will be `null` if the run is not + * incomplete. + */ + interface IncompleteDetails { + /** + * The reason why the run is incomplete. This will point to which specific token + * limit was reached over the course of the run. + */ + reason?: 'max_completion_tokens' | 'max_prompt_tokens'; + } + /** + * The last error associated with this run. Will be `null` if there are no errors. + */ + interface LastError { + /** + * One of `server_error`, `rate_limit_exceeded`, or `invalid_prompt`. + */ + code: 'server_error' | 'rate_limit_exceeded' | 'invalid_prompt'; + /** + * A human-readable description of the error. + */ + message: string; + } + /** + * Details on the action required to continue the run. Will be `null` if no action + * is required. + */ + interface RequiredAction { + /** + * Details on the tool outputs needed for this run to continue. + */ + submit_tool_outputs: RequiredAction.SubmitToolOutputs; + /** + * For now, this is always `submit_tool_outputs`. + */ + type: 'submit_tool_outputs'; + } + namespace RequiredAction { + /** + * Details on the tool outputs needed for this run to continue. + */ + interface SubmitToolOutputs { + /** + * A list of the relevant tool calls. + */ + tool_calls: Array; + } + } + interface TruncationStrategy { + /** + * The truncation strategy to use for the thread. The default is `auto`. If set to + * `last_messages`, the thread will be truncated to the n most recent messages in + * the thread. When set to `auto`, messages in the middle of the thread will be + * dropped to fit the context length of the model, `max_prompt_tokens`. + */ + type: 'auto' | 'last_messages'; + /** + * The number of most recent messages from the thread when constructing the context + * for the run. + */ + last_messages?: number | null; + } + /** + * Usage statistics related to the run. This value will be `null` if the run is not + * in a terminal state (i.e. `in_progress`, `queued`, etc.). + */ + interface Usage { + /** + * Number of completion tokens used over the course of the run. + */ + completion_tokens: number; + /** + * Number of prompt tokens used over the course of the run. + */ + prompt_tokens: number; + /** + * Total number of tokens used (prompt + completion). + */ + total_tokens: number; + } +} +/** + * The status of the run, which can be either `queued`, `in_progress`, + * `requires_action`, `cancelling`, `cancelled`, `failed`, `completed`, or + * `expired`. + */ +export type RunStatus = 'queued' | 'in_progress' | 'requires_action' | 'cancelling' | 'cancelled' | 'failed' | 'completed' | 'expired'; +export type RunCreateParams = RunCreateParamsNonStreaming | RunCreateParamsStreaming; +export interface RunCreateParamsBase { + /** + * The ID of the + * [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to + * execute this run. + */ + assistant_id: string; + /** + * Appends additional instructions at the end of the instructions for the run. This + * is useful for modifying the behavior on a per-run basis without overriding other + * instructions. + */ + additional_instructions?: string | null; + /** + * Adds additional messages to the thread before creating the run. + */ + additional_messages?: Array | null; + /** + * Overrides the + * [instructions](https://platform.openai.com/docs/api-reference/assistants/createAssistant) + * of the assistant. This is useful for modifying the behavior on a per-run basis. + */ + instructions?: string | null; + /** + * The maximum number of completion tokens that may be used over the course of the + * run. The run will make a best effort to use only the number of completion tokens + * specified, across multiple turns of the run. If the run exceeds the number of + * completion tokens specified, the run will end with status `complete`. See + * `incomplete_details` for more info. + */ + max_completion_tokens?: number | null; + /** + * The maximum number of prompt tokens that may be used over the course of the run. + * The run will make a best effort to use only the number of prompt tokens + * specified, across multiple turns of the run. If the run exceeds the number of + * prompt tokens specified, the run will end with status `complete`. See + * `incomplete_details` for more info. + */ + max_prompt_tokens?: number | null; + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata?: unknown | null; + /** + * The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to + * be used to execute this run. If a value is provided here, it will override the + * model associated with the assistant. If not, the model associated with the + * assistant will be used. + */ + model?: (string & {}) | 'gpt-4-turbo' | 'gpt-4-turbo-2024-04-09' | 'gpt-4-0125-preview' | 'gpt-4-turbo-preview' | 'gpt-4-1106-preview' | 'gpt-4-vision-preview' | 'gpt-4' | 'gpt-4-0314' | 'gpt-4-0613' | 'gpt-4-32k' | 'gpt-4-32k-0314' | 'gpt-4-32k-0613' | 'gpt-3.5-turbo' | 'gpt-3.5-turbo-16k' | 'gpt-3.5-turbo-0613' | 'gpt-3.5-turbo-1106' | 'gpt-3.5-turbo-0125' | 'gpt-3.5-turbo-16k-0613' | null; + /** + * Specifies the format that the model must output. Compatible with + * [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and + * all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + * + * Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + * message the model generates is valid JSON. + * + * **Important:** when using JSON mode, you **must** also instruct the model to + * produce JSON yourself via a system or user message. Without this, the model may + * generate an unending stream of whitespace until the generation reaches the token + * limit, resulting in a long-running and seemingly "stuck" request. Also note that + * the message content may be partially cut off if `finish_reason="length"`, which + * indicates the generation exceeded `max_tokens` or the conversation exceeded the + * max context length. + */ + response_format?: ThreadsAPI.AssistantResponseFormatOption | null; + /** + * If `true`, returns a stream of events that happen during the Run as server-sent + * events, terminating when the Run enters a terminal state with a `data: [DONE]` + * message. + */ + stream?: boolean | null; + /** + * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + * make the output more random, while lower values like 0.2 will make it more + * focused and deterministic. + */ + temperature?: number | null; + /** + * Controls which (if any) tool is called by the model. `none` means the model will + * not call any tools and instead generates a message. `auto` is the default value + * and means the model can pick between generating a message or calling a tool. + * Specifying a particular tool like `{"type": "TOOL_TYPE"}` or + * `{"type": "function", "function": {"name": "my_function"}}` forces the model to + * call that tool. + */ + tool_choice?: ThreadsAPI.AssistantToolChoiceOption | null; + /** + * Override the tools the assistant can use for this run. This is useful for + * modifying the behavior on a per-run basis. + */ + tools?: Array | null; + truncation_strategy?: RunCreateParams.TruncationStrategy | null; +} +export declare namespace RunCreateParams { + interface AdditionalMessage { + /** + * The content of the message. + */ + content: string; + /** + * The role of the entity that is creating the message. Allowed values include: + * + * - `user`: Indicates the message is sent by an actual user and should be used in + * most cases to represent user-generated messages. + * - `assistant`: Indicates the message is generated by the assistant. Use this + * value to insert messages from the assistant into the conversation. + */ + role: 'user' | 'assistant'; + /** + * A list of [File](https://platform.openai.com/docs/api-reference/files) IDs that + * the message should use. There can be a maximum of 10 files attached to a + * message. Useful for tools like `retrieval` and `code_interpreter` that can + * access and use files. + */ + file_ids?: Array; + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata?: unknown | null; + } + interface TruncationStrategy { + /** + * The truncation strategy to use for the thread. The default is `auto`. If set to + * `last_messages`, the thread will be truncated to the n most recent messages in + * the thread. When set to `auto`, messages in the middle of the thread will be + * dropped to fit the context length of the model, `max_prompt_tokens`. + */ + type: 'auto' | 'last_messages'; + /** + * The number of most recent messages from the thread when constructing the context + * for the run. + */ + last_messages?: number | null; + } + type RunCreateParamsNonStreaming = RunsAPI.RunCreateParamsNonStreaming; + type RunCreateParamsStreaming = RunsAPI.RunCreateParamsStreaming; +} +export interface RunCreateParamsNonStreaming extends RunCreateParamsBase { + /** + * If `true`, returns a stream of events that happen during the Run as server-sent + * events, terminating when the Run enters a terminal state with a `data: [DONE]` + * message. + */ + stream?: false | null; +} +export interface RunCreateParamsStreaming extends RunCreateParamsBase { + /** + * If `true`, returns a stream of events that happen during the Run as server-sent + * events, terminating when the Run enters a terminal state with a `data: [DONE]` + * message. + */ + stream: true; +} +export interface RunUpdateParams { + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata?: unknown | null; +} +export interface RunListParams extends CursorPageParams { + /** + * A cursor for use in pagination. `before` is an object ID that defines your place + * in the list. For instance, if you make a list request and receive 100 objects, + * ending with obj_foo, your subsequent call can include before=obj_foo in order to + * fetch the previous page of the list. + */ + before?: string; + /** + * Sort order by the `created_at` timestamp of the objects. `asc` for ascending + * order and `desc` for descending order. + */ + order?: 'asc' | 'desc'; +} +export interface RunCreateAndPollParams { + /** + * The ID of the + * [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to + * execute this run. + */ + assistant_id: string; + /** + * Appends additional instructions at the end of the instructions for the run. This + * is useful for modifying the behavior on a per-run basis without overriding other + * instructions. + */ + additional_instructions?: string | null; + /** + * Adds additional messages to the thread before creating the run. + */ + additional_messages?: Array | null; + /** + * Overrides the + * [instructions](https://platform.openai.com/docs/api-reference/assistants/createAssistant) + * of the assistant. This is useful for modifying the behavior on a per-run basis. + */ + instructions?: string | null; + /** + * The maximum number of completion tokens that may be used over the course of the + * run. The run will make a best effort to use only the number of completion tokens + * specified, across multiple turns of the run. If the run exceeds the number of + * completion tokens specified, the run will end with status `complete`. See + * `incomplete_details` for more info. + */ + max_completion_tokens?: number | null; + /** + * The maximum number of prompt tokens that may be used over the course of the run. + * The run will make a best effort to use only the number of prompt tokens + * specified, across multiple turns of the run. If the run exceeds the number of + * prompt tokens specified, the run will end with status `complete`. See + * `incomplete_details` for more info. + */ + max_prompt_tokens?: number | null; + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata?: unknown | null; + /** + * The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to + * be used to execute this run. If a value is provided here, it will override the + * model associated with the assistant. If not, the model associated with the + * assistant will be used. + */ + model?: (string & {}) | 'gpt-4-turbo' | 'gpt-4-turbo-2024-04-09' | 'gpt-4-0125-preview' | 'gpt-4-turbo-preview' | 'gpt-4-1106-preview' | 'gpt-4-vision-preview' | 'gpt-4' | 'gpt-4-0314' | 'gpt-4-0613' | 'gpt-4-32k' | 'gpt-4-32k-0314' | 'gpt-4-32k-0613' | 'gpt-3.5-turbo' | 'gpt-3.5-turbo-16k' | 'gpt-3.5-turbo-0613' | 'gpt-3.5-turbo-1106' | 'gpt-3.5-turbo-0125' | 'gpt-3.5-turbo-16k-0613' | null; + /** + * Specifies the format that the model must output. Compatible with + * [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and + * all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + * + * Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + * message the model generates is valid JSON. + * + * **Important:** when using JSON mode, you **must** also instruct the model to + * produce JSON yourself via a system or user message. Without this, the model may + * generate an unending stream of whitespace until the generation reaches the token + * limit, resulting in a long-running and seemingly "stuck" request. Also note that + * the message content may be partially cut off if `finish_reason="length"`, which + * indicates the generation exceeded `max_tokens` or the conversation exceeded the + * max context length. + */ + response_format?: ThreadsAPI.AssistantResponseFormatOption | null; + /** + * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + * make the output more random, while lower values like 0.2 will make it more + * focused and deterministic. + */ + temperature?: number | null; + /** + * Controls which (if any) tool is called by the model. `none` means the model will + * not call any tools and instead generates a message. `auto` is the default value + * and means the model can pick between generating a message or calling a tool. + * Specifying a particular tool like `{"type": "TOOL_TYPE"}` or + * `{"type": "function", "function": {"name": "my_function"}}` forces the model to + * call that tool. + */ + tool_choice?: ThreadsAPI.AssistantToolChoiceOption | null; + /** + * Override the tools the assistant can use for this run. This is useful for + * modifying the behavior on a per-run basis. + */ + tools?: Array | null; + truncation_strategy?: RunCreateAndPollParams.TruncationStrategy | null; +} +export declare namespace RunCreateAndPollParams { + interface AdditionalMessage { + /** + * The content of the message. + */ + content: string; + /** + * The role of the entity that is creating the message. Allowed values include: + * + * - `user`: Indicates the message is sent by an actual user and should be used in + * most cases to represent user-generated messages. + * - `assistant`: Indicates the message is generated by the assistant. Use this + * value to insert messages from the assistant into the conversation. + */ + role: 'user' | 'assistant'; + /** + * A list of [File](https://platform.openai.com/docs/api-reference/files) IDs that + * the message should use. There can be a maximum of 10 files attached to a + * message. Useful for tools like `retrieval` and `code_interpreter` that can + * access and use files. + */ + file_ids?: Array; + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata?: unknown | null; + } + interface TruncationStrategy { + /** + * The truncation strategy to use for the thread. The default is `auto`. If set to + * `last_messages`, the thread will be truncated to the n most recent messages in + * the thread. When set to `auto`, messages in the middle of the thread will be + * dropped to fit the context length of the model, `max_prompt_tokens`. + */ + type: 'auto' | 'last_messages'; + /** + * The number of most recent messages from the thread when constructing the context + * for the run. + */ + last_messages?: number | null; + } +} +export interface RunCreateAndStreamParams { + /** + * The ID of the + * [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to + * execute this run. + */ + assistant_id: string; + /** + * Appends additional instructions at the end of the instructions for the run. This + * is useful for modifying the behavior on a per-run basis without overriding other + * instructions. + */ + additional_instructions?: string | null; + /** + * Adds additional messages to the thread before creating the run. + */ + additional_messages?: Array | null; + /** + * Overrides the + * [instructions](https://platform.openai.com/docs/api-reference/assistants/createAssistant) + * of the assistant. This is useful for modifying the behavior on a per-run basis. + */ + instructions?: string | null; + /** + * The maximum number of completion tokens that may be used over the course of the + * run. The run will make a best effort to use only the number of completion tokens + * specified, across multiple turns of the run. If the run exceeds the number of + * completion tokens specified, the run will end with status `complete`. See + * `incomplete_details` for more info. + */ + max_completion_tokens?: number | null; + /** + * The maximum number of prompt tokens that may be used over the course of the run. + * The run will make a best effort to use only the number of prompt tokens + * specified, across multiple turns of the run. If the run exceeds the number of + * prompt tokens specified, the run will end with status `complete`. See + * `incomplete_details` for more info. + */ + max_prompt_tokens?: number | null; + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata?: unknown | null; + /** + * The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to + * be used to execute this run. If a value is provided here, it will override the + * model associated with the assistant. If not, the model associated with the + * assistant will be used. + */ + model?: (string & {}) | 'gpt-4-turbo' | 'gpt-4-turbo-2024-04-09' | 'gpt-4-0125-preview' | 'gpt-4-turbo-preview' | 'gpt-4-1106-preview' | 'gpt-4-vision-preview' | 'gpt-4' | 'gpt-4-0314' | 'gpt-4-0613' | 'gpt-4-32k' | 'gpt-4-32k-0314' | 'gpt-4-32k-0613' | 'gpt-3.5-turbo' | 'gpt-3.5-turbo-16k' | 'gpt-3.5-turbo-0613' | 'gpt-3.5-turbo-1106' | 'gpt-3.5-turbo-0125' | 'gpt-3.5-turbo-16k-0613' | null; + /** + * Specifies the format that the model must output. Compatible with + * [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and + * all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + * + * Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + * message the model generates is valid JSON. + * + * **Important:** when using JSON mode, you **must** also instruct the model to + * produce JSON yourself via a system or user message. Without this, the model may + * generate an unending stream of whitespace until the generation reaches the token + * limit, resulting in a long-running and seemingly "stuck" request. Also note that + * the message content may be partially cut off if `finish_reason="length"`, which + * indicates the generation exceeded `max_tokens` or the conversation exceeded the + * max context length. + */ + response_format?: ThreadsAPI.AssistantResponseFormatOption | null; + /** + * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + * make the output more random, while lower values like 0.2 will make it more + * focused and deterministic. + */ + temperature?: number | null; + /** + * Controls which (if any) tool is called by the model. `none` means the model will + * not call any tools and instead generates a message. `auto` is the default value + * and means the model can pick between generating a message or calling a tool. + * Specifying a particular tool like `{"type": "TOOL_TYPE"}` or + * `{"type": "function", "function": {"name": "my_function"}}` forces the model to + * call that tool. + */ + tool_choice?: ThreadsAPI.AssistantToolChoiceOption | null; + /** + * Override the tools the assistant can use for this run. This is useful for + * modifying the behavior on a per-run basis. + */ + tools?: Array | null; + truncation_strategy?: RunCreateAndStreamParams.TruncationStrategy | null; +} +export declare namespace RunCreateAndStreamParams { + interface AdditionalMessage { + /** + * The content of the message. + */ + content: string; + /** + * The role of the entity that is creating the message. Allowed values include: + * + * - `user`: Indicates the message is sent by an actual user and should be used in + * most cases to represent user-generated messages. + * - `assistant`: Indicates the message is generated by the assistant. Use this + * value to insert messages from the assistant into the conversation. + */ + role: 'user' | 'assistant'; + /** + * A list of [File](https://platform.openai.com/docs/api-reference/files) IDs that + * the message should use. There can be a maximum of 10 files attached to a + * message. Useful for tools like `retrieval` and `code_interpreter` that can + * access and use files. + */ + file_ids?: Array; + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata?: unknown | null; + } + interface TruncationStrategy { + /** + * The truncation strategy to use for the thread. The default is `auto`. If set to + * `last_messages`, the thread will be truncated to the n most recent messages in + * the thread. When set to `auto`, messages in the middle of the thread will be + * dropped to fit the context length of the model, `max_prompt_tokens`. + */ + type: 'auto' | 'last_messages'; + /** + * The number of most recent messages from the thread when constructing the context + * for the run. + */ + last_messages?: number | null; + } +} +export interface RunStreamParams { + /** + * The ID of the + * [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to + * execute this run. + */ + assistant_id: string; + /** + * Appends additional instructions at the end of the instructions for the run. This + * is useful for modifying the behavior on a per-run basis without overriding other + * instructions. + */ + additional_instructions?: string | null; + /** + * Adds additional messages to the thread before creating the run. + */ + additional_messages?: Array | null; + /** + * Overrides the + * [instructions](https://platform.openai.com/docs/api-reference/assistants/createAssistant) + * of the assistant. This is useful for modifying the behavior on a per-run basis. + */ + instructions?: string | null; + /** + * The maximum number of completion tokens that may be used over the course of the + * run. The run will make a best effort to use only the number of completion tokens + * specified, across multiple turns of the run. If the run exceeds the number of + * completion tokens specified, the run will end with status `complete`. See + * `incomplete_details` for more info. + */ + max_completion_tokens?: number | null; + /** + * The maximum number of prompt tokens that may be used over the course of the run. + * The run will make a best effort to use only the number of prompt tokens + * specified, across multiple turns of the run. If the run exceeds the number of + * prompt tokens specified, the run will end with status `complete`. See + * `incomplete_details` for more info. + */ + max_prompt_tokens?: number | null; + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata?: unknown | null; + /** + * The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to + * be used to execute this run. If a value is provided here, it will override the + * model associated with the assistant. If not, the model associated with the + * assistant will be used. + */ + model?: (string & {}) | 'gpt-4-turbo' | 'gpt-4-turbo-2024-04-09' | 'gpt-4-0125-preview' | 'gpt-4-turbo-preview' | 'gpt-4-1106-preview' | 'gpt-4-vision-preview' | 'gpt-4' | 'gpt-4-0314' | 'gpt-4-0613' | 'gpt-4-32k' | 'gpt-4-32k-0314' | 'gpt-4-32k-0613' | 'gpt-3.5-turbo' | 'gpt-3.5-turbo-16k' | 'gpt-3.5-turbo-0613' | 'gpt-3.5-turbo-1106' | 'gpt-3.5-turbo-0125' | 'gpt-3.5-turbo-16k-0613' | null; + /** + * Specifies the format that the model must output. Compatible with + * [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and + * all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + * + * Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + * message the model generates is valid JSON. + * + * **Important:** when using JSON mode, you **must** also instruct the model to + * produce JSON yourself via a system or user message. Without this, the model may + * generate an unending stream of whitespace until the generation reaches the token + * limit, resulting in a long-running and seemingly "stuck" request. Also note that + * the message content may be partially cut off if `finish_reason="length"`, which + * indicates the generation exceeded `max_tokens` or the conversation exceeded the + * max context length. + */ + response_format?: ThreadsAPI.AssistantResponseFormatOption | null; + /** + * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + * make the output more random, while lower values like 0.2 will make it more + * focused and deterministic. + */ + temperature?: number | null; + /** + * Controls which (if any) tool is called by the model. `none` means the model will + * not call any tools and instead generates a message. `auto` is the default value + * and means the model can pick between generating a message or calling a tool. + * Specifying a particular tool like `{"type": "TOOL_TYPE"}` or + * `{"type": "function", "function": {"name": "my_function"}}` forces the model to + * call that tool. + */ + tool_choice?: ThreadsAPI.AssistantToolChoiceOption | null; + /** + * Override the tools the assistant can use for this run. This is useful for + * modifying the behavior on a per-run basis. + */ + tools?: Array | null; + truncation_strategy?: RunStreamParams.TruncationStrategy | null; +} +export declare namespace RunStreamParams { + interface AdditionalMessage { + /** + * The content of the message. + */ + content: string; + /** + * The role of the entity that is creating the message. Allowed values include: + * + * - `user`: Indicates the message is sent by an actual user and should be used in + * most cases to represent user-generated messages. + * - `assistant`: Indicates the message is generated by the assistant. Use this + * value to insert messages from the assistant into the conversation. + */ + role: 'user' | 'assistant'; + /** + * A list of [File](https://platform.openai.com/docs/api-reference/files) IDs that + * the message should use. There can be a maximum of 10 files attached to a + * message. Useful for tools like `retrieval` and `code_interpreter` that can + * access and use files. + */ + file_ids?: Array; + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata?: unknown | null; + } + interface TruncationStrategy { + /** + * The truncation strategy to use for the thread. The default is `auto`. If set to + * `last_messages`, the thread will be truncated to the n most recent messages in + * the thread. When set to `auto`, messages in the middle of the thread will be + * dropped to fit the context length of the model, `max_prompt_tokens`. + */ + type: 'auto' | 'last_messages'; + /** + * The number of most recent messages from the thread when constructing the context + * for the run. + */ + last_messages?: number | null; + } +} +export type RunSubmitToolOutputsParams = RunSubmitToolOutputsParamsNonStreaming | RunSubmitToolOutputsParamsStreaming; +export interface RunSubmitToolOutputsParamsBase { + /** + * A list of tools for which the outputs are being submitted. + */ + tool_outputs: Array; + /** + * If `true`, returns a stream of events that happen during the Run as server-sent + * events, terminating when the Run enters a terminal state with a `data: [DONE]` + * message. + */ + stream?: boolean | null; +} +export declare namespace RunSubmitToolOutputsParams { + interface ToolOutput { + /** + * The output of the tool call to be submitted to continue the run. + */ + output?: string; + /** + * The ID of the tool call in the `required_action` object within the run object + * the output is being submitted for. + */ + tool_call_id?: string; + } + type RunSubmitToolOutputsParamsNonStreaming = RunsAPI.RunSubmitToolOutputsParamsNonStreaming; + type RunSubmitToolOutputsParamsStreaming = RunsAPI.RunSubmitToolOutputsParamsStreaming; +} +export interface RunSubmitToolOutputsParamsNonStreaming extends RunSubmitToolOutputsParamsBase { + /** + * If `true`, returns a stream of events that happen during the Run as server-sent + * events, terminating when the Run enters a terminal state with a `data: [DONE]` + * message. + */ + stream?: false | null; +} +export interface RunSubmitToolOutputsParamsStreaming extends RunSubmitToolOutputsParamsBase { + /** + * If `true`, returns a stream of events that happen during the Run as server-sent + * events, terminating when the Run enters a terminal state with a `data: [DONE]` + * message. + */ + stream: true; +} +export interface RunSubmitToolOutputsAndPollParams { + /** + * A list of tools for which the outputs are being submitted. + */ + tool_outputs: Array; +} +export declare namespace RunSubmitToolOutputsAndPollParams { + interface ToolOutput { + /** + * The output of the tool call to be submitted to continue the run. + */ + output?: string; + /** + * The ID of the tool call in the `required_action` object within the run object + * the output is being submitted for. + */ + tool_call_id?: string; + } +} +export interface RunSubmitToolOutputsStreamParams { + /** + * A list of tools for which the outputs are being submitted. + */ + tool_outputs: Array; +} +export declare namespace RunSubmitToolOutputsStreamParams { + interface ToolOutput { + /** + * The output of the tool call to be submitted to continue the run. + */ + output?: string; + /** + * The ID of the tool call in the `required_action` object within the run object + * the output is being submitted for. + */ + tool_call_id?: string; + } +} +export declare namespace Runs { + export import RequiredActionFunctionToolCall = RunsAPI.RequiredActionFunctionToolCall; + export import Run = RunsAPI.Run; + export import RunStatus = RunsAPI.RunStatus; + export import RunsPage = RunsAPI.RunsPage; + export import RunCreateParams = RunsAPI.RunCreateParams; + export import RunCreateParamsNonStreaming = RunsAPI.RunCreateParamsNonStreaming; + export import RunCreateParamsStreaming = RunsAPI.RunCreateParamsStreaming; + export import RunUpdateParams = RunsAPI.RunUpdateParams; + export import RunListParams = RunsAPI.RunListParams; + export import RunCreateAndPollParams = RunsAPI.RunCreateAndPollParams; + export import RunCreateAndStreamParams = RunsAPI.RunCreateAndStreamParams; + export import RunStreamParams = RunsAPI.RunStreamParams; + export import RunSubmitToolOutputsParams = RunsAPI.RunSubmitToolOutputsParams; + export import RunSubmitToolOutputsParamsNonStreaming = RunsAPI.RunSubmitToolOutputsParamsNonStreaming; + export import RunSubmitToolOutputsParamsStreaming = RunsAPI.RunSubmitToolOutputsParamsStreaming; + export import RunSubmitToolOutputsAndPollParams = RunsAPI.RunSubmitToolOutputsAndPollParams; + export import RunSubmitToolOutputsStreamParams = RunsAPI.RunSubmitToolOutputsStreamParams; + export import Steps = StepsAPI.Steps; + export import CodeInterpreterLogs = StepsAPI.CodeInterpreterLogs; + export import CodeInterpreterOutputImage = StepsAPI.CodeInterpreterOutputImage; + export import CodeInterpreterToolCall = StepsAPI.CodeInterpreterToolCall; + export import CodeInterpreterToolCallDelta = StepsAPI.CodeInterpreterToolCallDelta; + export import FunctionToolCall = StepsAPI.FunctionToolCall; + export import FunctionToolCallDelta = StepsAPI.FunctionToolCallDelta; + export import MessageCreationStepDetails = StepsAPI.MessageCreationStepDetails; + export import RetrievalToolCall = StepsAPI.RetrievalToolCall; + export import RetrievalToolCallDelta = StepsAPI.RetrievalToolCallDelta; + export import RunStep = StepsAPI.RunStep; + export import RunStepDelta = StepsAPI.RunStepDelta; + export import RunStepDeltaEvent = StepsAPI.RunStepDeltaEvent; + export import RunStepDeltaMessageDelta = StepsAPI.RunStepDeltaMessageDelta; + export import ToolCall = StepsAPI.ToolCall; + export import ToolCallDelta = StepsAPI.ToolCallDelta; + export import ToolCallDeltaObject = StepsAPI.ToolCallDeltaObject; + export import ToolCallsStepDetails = StepsAPI.ToolCallsStepDetails; + export import RunStepsPage = StepsAPI.RunStepsPage; + export import StepListParams = StepsAPI.StepListParams; +} +//# sourceMappingURL=runs.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/threads/runs/runs.d.ts.map b/backend/node_modules/openai/resources/beta/threads/runs/runs.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..e7cda5ec423b432aeebecd7cdb2eea665abb2108 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/threads/runs/runs.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"runs.d.ts","sourceRoot":"","sources":["../../../../src/resources/beta/threads/runs/runs.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,IAAI,MAAM,aAAa,CAAC;AACpC,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAE9C,OAAO,EAAE,eAAe,EAAE,yBAAyB,EAAE,MAAM,4BAA4B,CAAC;AAExF,OAAO,EAAE,gCAAgC,EAAE,MAAM,4BAA4B,CAAC;AAC9E,OAAO,KAAK,OAAO,MAAM,yCAAyC,CAAC;AACnE,OAAO,KAAK,aAAa,MAAM,6CAA6C,CAAC;AAC7E,OAAO,KAAK,UAAU,MAAM,uCAAuC,CAAC;AACpE,OAAO,KAAK,QAAQ,MAAM,0CAA0C,CAAC;AACrE,OAAO,EAAE,UAAU,EAAE,KAAK,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AACtE,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAE1C,qBAAa,IAAK,SAAQ,WAAW;IACnC,KAAK,EAA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IACrE,MAAM,QAAQ,0BAA0B,GAAG,QAAQ,CAAC,0BAA0B,CAAC;IAC/E,MAAM,QAAQ,iBAAiB,GAAG,QAAQ,CAAC,iBAAiB,CAAC;IAC7D,MAAM,QAAQ,sBAAsB,GAAG,QAAQ,CAAC,sBAAsB,CAAC;IACvE,MAAM,QAAQ,OAAO,GAAG,QAAQ,CAAC,OAAO,CAAC;IACzC,MAAM,QAAQ,YAAY,GAAG,QAAQ,CAAC,YAAY,CAAC;IACnD,MAAM,QAAQ,iBAAiB,GAAG,QAAQ,CAAC,iBAAiB,CAAC;IAC7D,MAAM,QAAQ,wBAAwB,GAAG,QAAQ,CAAC,wBAAwB,CAAC;IAC3E,MAAM,QAAQ,QAAQ,GAAG,QAAQ,CAAC,QAAQ,CAAC;IAC3C,MAAM,QAAQ,aAAa,GAAG,QAAQ,CAAC,aAAa,CAAC;IACrD,MAAM,QAAQ,mBAAmB,GAAG,QAAQ,CAAC,mBAAmB,CAAC;IACjE,MAAM,QAAQ,oBAAoB,GAAG,QAAQ,CAAC,oBAAoB,CAAC;IACnE,MAAM,QAAQ,YAAY,GAAG,QAAQ,CAAC,YAAY,CAAC;IACnD,MAAM,QAAQ,cAAc,GAAG,QAAQ,CAAC,cAAc,CAAC;CACxD"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/threads/runs/runs.js b/backend/node_modules/openai/resources/beta/threads/runs/runs.js new file mode 100644 index 0000000000000000000000000000000000000000..482cf93bd9a2e01fe74616955b3e2203b8dfd2b6 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/threads/runs/runs.js @@ -0,0 +1,189 @@ +"use strict"; +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.RunsPage = exports.Runs = void 0; +const resource_1 = require("openai/resource"); +const core_1 = require("openai/core"); +const AssistantStream_1 = require("openai/lib/AssistantStream"); +const core_2 = require("openai/core"); +const RunsAPI = __importStar(require("openai/resources/beta/threads/runs/runs")); +const StepsAPI = __importStar(require("openai/resources/beta/threads/runs/steps")); +const pagination_1 = require("openai/pagination"); +class Runs extends resource_1.APIResource { + constructor() { + super(...arguments); + this.steps = new StepsAPI.Steps(this._client); + } + create(threadId, body, options) { + return this._client.post(`/threads/${threadId}/runs`, { + body, + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + stream: body.stream ?? false, + }); + } + /** + * Retrieves a run. + */ + retrieve(threadId, runId, options) { + return this._client.get(`/threads/${threadId}/runs/${runId}`, { + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } + /** + * Modifies a run. + */ + update(threadId, runId, body, options) { + return this._client.post(`/threads/${threadId}/runs/${runId}`, { + body, + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } + list(threadId, query = {}, options) { + if ((0, core_1.isRequestOptions)(query)) { + return this.list(threadId, {}, query); + } + return this._client.getAPIList(`/threads/${threadId}/runs`, RunsPage, { + query, + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } + /** + * Cancels a run that is `in_progress`. + */ + cancel(threadId, runId, options) { + return this._client.post(`/threads/${threadId}/runs/${runId}/cancel`, { + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } + /** + * A helper to create a run an poll for a terminal state. More information on Run + * lifecycles can be found here: + * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps + */ + async createAndPoll(threadId, body, options) { + const run = await this.create(threadId, body, options); + return await this.poll(threadId, run.id, options); + } + /** + * Create a Run stream + * + * @deprecated use `stream` instead + */ + createAndStream(threadId, body, options) { + return AssistantStream_1.AssistantStream.createAssistantStream(threadId, this._client.beta.threads.runs, body, options); + } + /** + * A helper to poll a run status until it reaches a terminal state. More + * information on Run lifecycles can be found here: + * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps + */ + async poll(threadId, runId, options) { + const headers = { ...options?.headers, 'X-Stainless-Poll-Helper': 'true' }; + if (options?.pollIntervalMs) { + headers['X-Stainless-Custom-Poll-Interval'] = options.pollIntervalMs.toString(); + } + while (true) { + const { data: run, response } = await this.retrieve(threadId, runId, { + ...options, + headers: { ...options?.headers, ...headers }, + }).withResponse(); + switch (run.status) { + //If we are in any sort of intermediate state we poll + case 'queued': + case 'in_progress': + case 'cancelling': + let sleepInterval = 5000; + if (options?.pollIntervalMs) { + sleepInterval = options.pollIntervalMs; + } + else { + const headerInterval = response.headers.get('openai-poll-after-ms'); + if (headerInterval) { + const headerIntervalMs = parseInt(headerInterval); + if (!isNaN(headerIntervalMs)) { + sleepInterval = headerIntervalMs; + } + } + } + await (0, core_2.sleep)(sleepInterval); + break; + //We return the run in any terminal state. + case 'requires_action': + case 'cancelled': + case 'completed': + case 'failed': + case 'expired': + return run; + } + } + } + /** + * Create a Run stream + */ + stream(threadId, body, options) { + return AssistantStream_1.AssistantStream.createAssistantStream(threadId, this._client.beta.threads.runs, body, options); + } + submitToolOutputs(threadId, runId, body, options) { + return this._client.post(`/threads/${threadId}/runs/${runId}/submit_tool_outputs`, { + body, + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + stream: body.stream ?? false, + }); + } + /** + * A helper to submit a tool output to a run and poll for a terminal run state. + * More information on Run lifecycles can be found here: + * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps + */ + async submitToolOutputsAndPoll(threadId, runId, body, options) { + const run = await this.submitToolOutputs(threadId, runId, body, options); + return await this.poll(threadId, run.id, options); + } + /** + * Submit the tool outputs from a previous run and stream the run to a terminal + * state. More information on Run lifecycles can be found here: + * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps + */ + submitToolOutputsStream(threadId, runId, body, options) { + return AssistantStream_1.AssistantStream.createToolAssistantStream(threadId, runId, this._client.beta.threads.runs, body, options); + } +} +exports.Runs = Runs; +class RunsPage extends pagination_1.CursorPage { +} +exports.RunsPage = RunsPage; +(function (Runs) { + Runs.RunsPage = RunsAPI.RunsPage; + Runs.Steps = StepsAPI.Steps; + Runs.RunStepsPage = StepsAPI.RunStepsPage; +})(Runs = exports.Runs || (exports.Runs = {})); +//# sourceMappingURL=runs.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/threads/runs/runs.js.map b/backend/node_modules/openai/resources/beta/threads/runs/runs.js.map new file mode 100644 index 0000000000000000000000000000000000000000..58558da1ad561cc2b275ce506360e9e984400c8b --- /dev/null +++ b/backend/node_modules/openai/resources/beta/threads/runs/runs.js.map @@ -0,0 +1 @@ +{"version":3,"file":"runs.js","sourceRoot":"","sources":["../../../../src/resources/beta/threads/runs/runs.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;;;;;;;;;;;;;;;;;;;;;;;;AAItF,8CAA8C;AAC9C,sCAA+C;AAC/C,gEAAwF;AACxF,sCAAoC;AAEpC,iFAAmE;AAGnE,mFAAqE;AACrE,kDAAsE;AAGtE,MAAa,IAAK,SAAQ,sBAAW;IAArC;;QACE,UAAK,GAAmB,IAAI,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IAwP3D,CAA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AA6B;QAE7B,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,YAAY,QAAQ,SAAS,KAAK,sBAAsB,EAAE;YACjF,IAAI;YACJ,GAAG,OAAO;YACV,OAAO,EAAE,EAAE,aAAa,EAAE,eAAe,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE;YAChE,MAAM,EAAE,IAAI,CAAC,MAAM,IAAI,KAAK;SAC7B,CAA6E,CAAC;IACjF,CAAC;IAED;;;;OAIG;IACH,KAAK,CAAC,wBAAwB,CAC5B,QAAgB,EAChB,KAAa,EACb,IAA4C,EAC5C,OAA2D;QAE3D,MAAM,GAAG,GAAG,MAAM,IAAI,CAAC,iBAAiB,CAAC,QAAQ,EAAE,KAAK,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC;QACzE,OAAO,MAAM,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,GAAG,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;IACpD,CAAC;IAED;;;;OAIG;IACH,uBAAuB,CACrB,QAAgB,EAChB,KAAa,EACb,IAAsC,EACtC,OAA6B;QAE7B,OAAO,iCAAe,CAAC,yBAAyB,CAC9C,QAAQ,EACR,KAAK,EACL,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,EAC9B,IAAI,EACJ,OAAO,CACR,CAAC;IACJ,CAAC;CACF;AAzPD,oBAyPC;AAED,MAAa,QAAS,SAAQ,uBAAe;CAAG;AAAhD,4BAAgD;AA8pChD,WAAiB,IAAI;IAIL,aAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC;IAc5B,UAAK,GAAG,QAAQ,CAAC,KAAK,CAAC;IAkBvB,iBAAY,GAAG,QAAQ,CAAC,YAAY,CAAC;AAErD,CAAC,EAtCgB,IAAI,GAAJ,YAAI,KAAJ,YAAI,QAsCpB"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/threads/runs/runs.mjs b/backend/node_modules/openai/resources/beta/threads/runs/runs.mjs new file mode 100644 index 0000000000000000000000000000000000000000..d45c7b86154c1daf3a797a064e384e1de345cc3f --- /dev/null +++ b/backend/node_modules/openai/resources/beta/threads/runs/runs.mjs @@ -0,0 +1,161 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +import { APIResource } from 'openai/resource'; +import { isRequestOptions } from 'openai/core'; +import { AssistantStream } from 'openai/lib/AssistantStream'; +import { sleep } from 'openai/core'; +import * as RunsAPI from 'openai/resources/beta/threads/runs/runs'; +import * as StepsAPI from 'openai/resources/beta/threads/runs/steps'; +import { CursorPage } from 'openai/pagination'; +export class Runs extends APIResource { + constructor() { + super(...arguments); + this.steps = new StepsAPI.Steps(this._client); + } + create(threadId, body, options) { + return this._client.post(`/threads/${threadId}/runs`, { + body, + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + stream: body.stream ?? false, + }); + } + /** + * Retrieves a run. + */ + retrieve(threadId, runId, options) { + return this._client.get(`/threads/${threadId}/runs/${runId}`, { + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } + /** + * Modifies a run. + */ + update(threadId, runId, body, options) { + return this._client.post(`/threads/${threadId}/runs/${runId}`, { + body, + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } + list(threadId, query = {}, options) { + if (isRequestOptions(query)) { + return this.list(threadId, {}, query); + } + return this._client.getAPIList(`/threads/${threadId}/runs`, RunsPage, { + query, + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } + /** + * Cancels a run that is `in_progress`. + */ + cancel(threadId, runId, options) { + return this._client.post(`/threads/${threadId}/runs/${runId}/cancel`, { + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } + /** + * A helper to create a run an poll for a terminal state. More information on Run + * lifecycles can be found here: + * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps + */ + async createAndPoll(threadId, body, options) { + const run = await this.create(threadId, body, options); + return await this.poll(threadId, run.id, options); + } + /** + * Create a Run stream + * + * @deprecated use `stream` instead + */ + createAndStream(threadId, body, options) { + return AssistantStream.createAssistantStream(threadId, this._client.beta.threads.runs, body, options); + } + /** + * A helper to poll a run status until it reaches a terminal state. More + * information on Run lifecycles can be found here: + * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps + */ + async poll(threadId, runId, options) { + const headers = { ...options?.headers, 'X-Stainless-Poll-Helper': 'true' }; + if (options?.pollIntervalMs) { + headers['X-Stainless-Custom-Poll-Interval'] = options.pollIntervalMs.toString(); + } + while (true) { + const { data: run, response } = await this.retrieve(threadId, runId, { + ...options, + headers: { ...options?.headers, ...headers }, + }).withResponse(); + switch (run.status) { + //If we are in any sort of intermediate state we poll + case 'queued': + case 'in_progress': + case 'cancelling': + let sleepInterval = 5000; + if (options?.pollIntervalMs) { + sleepInterval = options.pollIntervalMs; + } + else { + const headerInterval = response.headers.get('openai-poll-after-ms'); + if (headerInterval) { + const headerIntervalMs = parseInt(headerInterval); + if (!isNaN(headerIntervalMs)) { + sleepInterval = headerIntervalMs; + } + } + } + await sleep(sleepInterval); + break; + //We return the run in any terminal state. + case 'requires_action': + case 'cancelled': + case 'completed': + case 'failed': + case 'expired': + return run; + } + } + } + /** + * Create a Run stream + */ + stream(threadId, body, options) { + return AssistantStream.createAssistantStream(threadId, this._client.beta.threads.runs, body, options); + } + submitToolOutputs(threadId, runId, body, options) { + return this._client.post(`/threads/${threadId}/runs/${runId}/submit_tool_outputs`, { + body, + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + stream: body.stream ?? false, + }); + } + /** + * A helper to submit a tool output to a run and poll for a terminal run state. + * More information on Run lifecycles can be found here: + * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps + */ + async submitToolOutputsAndPoll(threadId, runId, body, options) { + const run = await this.submitToolOutputs(threadId, runId, body, options); + return await this.poll(threadId, run.id, options); + } + /** + * Submit the tool outputs from a previous run and stream the run to a terminal + * state. More information on Run lifecycles can be found here: + * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps + */ + submitToolOutputsStream(threadId, runId, body, options) { + return AssistantStream.createToolAssistantStream(threadId, runId, this._client.beta.threads.runs, body, options); + } +} +export class RunsPage extends CursorPage { +} +(function (Runs) { + Runs.RunsPage = RunsAPI.RunsPage; + Runs.Steps = StepsAPI.Steps; + Runs.RunStepsPage = StepsAPI.RunStepsPage; +})(Runs || (Runs = {})); +//# sourceMappingURL=runs.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/threads/runs/runs.mjs.map b/backend/node_modules/openai/resources/beta/threads/runs/runs.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..1d69c1c248947f8f9ec2ae31786f7f7fe0c913d1 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/threads/runs/runs.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"runs.mjs","sourceRoot":"","sources":["../../../../src/resources/beta/threads/runs/runs.ts"],"names":[],"mappings":"AAAA,sFAAsF;OAI/E,EAAE,WAAW,EAAE,MAAM,iBAAiB;OACtC,EAAE,gBAAgB,EAAE,MAAM,aAAa;OACvC,EAAE,eAAe,EAA6B,MAAM,4BAA4B;OAChF,EAAE,KAAK,EAAE,MAAM,aAAa;OAE5B,KAAK,OAAO,MAAM,yCAAyC;OAG3D,KAAK,QAAQ,MAAM,0CAA0C;OAC7D,EAAE,UAAU,EAAyB,MAAM,mBAAmB;AAGrE,MAAM,OAAO,IAAK,SAAQ,WAAW;IAArC;;QACE,UAAK,GAAmB,IAAI,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IAwP3D,CAAC;IAxOC,MAAM,CACJ,QAAgB,EAChB,IAAqB,EACrB,OAA6B;QAE7B,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,YAAY,QAAQ,OAAO,EAAE;YACpD,IAAI;YACJ,GAAG,OAAO;YACV,OAAO,EAAE,EAAE,aAAa,EAAE,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AAM,EAAE,IAAI,CAAC,MAAM,IAAI,KAAK;SAC7B,CAA6E,CAAC;IACjF,CAAC;IAED;;;;OAIG;IACH,KAAK,CAAC,wBAAwB,CAC5B,QAAgB,EAChB,KAAa,EACb,IAA4C,EAC5C,OAA2D;QAE3D,MAAM,GAAG,GAAG,MAAM,IAAI,CAAC,iBAAiB,CAAC,QAAQ,EAAE,KAAK,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC;QACzE,OAAO,MAAM,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,GAAG,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;IACpD,CAAC;IAED;;;;OAIG;IACH,uBAAuB,CACrB,QAAgB,EAChB,KAAa,EACb,IAAsC,EACtC,OAA6B;QAE7B,OAAO,eAAe,CAAC,yBAAyB,CAC9C,QAAQ,EACR,KAAK,EACL,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,EAC9B,IAAI,EACJ,OAAO,CACR,CAAC;IACJ,CAAC;CACF;AAED,MAAM,OAAO,QAAS,SAAQ,UAAe;CAAG;AA8pChD,WAAiB,IAAI;IAIL,aAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC;IAc5B,UAAK,GAAG,QAAQ,CAAC,KAAK,CAAC;IAkBvB,iBAAY,GAAG,QAAQ,CAAC,YAAY,CAAC;AAErD,CAAC,EAtCgB,IAAI,KAAJ,IAAI,QAsCpB"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/threads/runs/steps.d.ts b/backend/node_modules/openai/resources/beta/threads/runs/steps.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1f319db92ba5ea4c006001227bfe9a1641ca7ba1 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/threads/runs/steps.d.ts @@ -0,0 +1,520 @@ +import * as Core from 'openai/core'; +import { APIResource } from 'openai/resource'; +import * as StepsAPI from 'openai/resources/beta/threads/runs/steps'; +import { CursorPage, type CursorPageParams } from 'openai/pagination'; +export declare class Steps extends APIResource { + /** + * Retrieves a run step. + */ + retrieve(threadId: string, runId: string, stepId: string, options?: Core.RequestOptions): Core.APIPromise; + /** + * Returns a list of run steps belonging to a run. + */ + list(threadId: string, runId: string, query?: StepListParams, options?: Core.RequestOptions): Core.PagePromise; + list(threadId: string, runId: string, options?: Core.RequestOptions): Core.PagePromise; +} +export declare class RunStepsPage extends CursorPage { +} +/** + * Text output from the Code Interpreter tool call as part of a run step. + */ +export interface CodeInterpreterLogs { + /** + * The index of the output in the outputs array. + */ + index: number; + /** + * Always `logs`. + */ + type: 'logs'; + /** + * The text output from the Code Interpreter tool call. + */ + logs?: string; +} +export interface CodeInterpreterOutputImage { + /** + * The index of the output in the outputs array. + */ + index: number; + /** + * Always `image`. + */ + type: 'image'; + image?: CodeInterpreterOutputImage.Image; +} +export declare namespace CodeInterpreterOutputImage { + interface Image { + /** + * The [file](https://platform.openai.com/docs/api-reference/files) ID of the + * image. + */ + file_id?: string; + } +} +/** + * Details of the Code Interpreter tool call the run step was involved in. + */ +export interface CodeInterpreterToolCall { + /** + * The ID of the tool call. + */ + id: string; + /** + * The Code Interpreter tool call definition. + */ + code_interpreter: CodeInterpreterToolCall.CodeInterpreter; + /** + * The type of tool call. This is always going to be `code_interpreter` for this + * type of tool call. + */ + type: 'code_interpreter'; +} +export declare namespace CodeInterpreterToolCall { + /** + * The Code Interpreter tool call definition. + */ + interface CodeInterpreter { + /** + * The input to the Code Interpreter tool call. + */ + input: string; + /** + * The outputs from the Code Interpreter tool call. Code Interpreter can output one + * or more items, including text (`logs`) or images (`image`). Each of these are + * represented by a different object type. + */ + outputs: Array; + } + namespace CodeInterpreter { + /** + * Text output from the Code Interpreter tool call as part of a run step. + */ + interface Logs { + /** + * The text output from the Code Interpreter tool call. + */ + logs: string; + /** + * Always `logs`. + */ + type: 'logs'; + } + interface Image { + image: Image.Image; + /** + * Always `image`. + */ + type: 'image'; + } + namespace Image { + interface Image { + /** + * The [file](https://platform.openai.com/docs/api-reference/files) ID of the + * image. + */ + file_id: string; + } + } + } +} +/** + * Details of the Code Interpreter tool call the run step was involved in. + */ +export interface CodeInterpreterToolCallDelta { + /** + * The index of the tool call in the tool calls array. + */ + index: number; + /** + * The type of tool call. This is always going to be `code_interpreter` for this + * type of tool call. + */ + type: 'code_interpreter'; + /** + * The ID of the tool call. + */ + id?: string; + /** + * The Code Interpreter tool call definition. + */ + code_interpreter?: CodeInterpreterToolCallDelta.CodeInterpreter; +} +export declare namespace CodeInterpreterToolCallDelta { + /** + * The Code Interpreter tool call definition. + */ + interface CodeInterpreter { + /** + * The input to the Code Interpreter tool call. + */ + input?: string; + /** + * The outputs from the Code Interpreter tool call. Code Interpreter can output one + * or more items, including text (`logs`) or images (`image`). Each of these are + * represented by a different object type. + */ + outputs?: Array; + } +} +export interface FunctionToolCall { + /** + * The ID of the tool call object. + */ + id: string; + /** + * The definition of the function that was called. + */ + function: FunctionToolCall.Function; + /** + * The type of tool call. This is always going to be `function` for this type of + * tool call. + */ + type: 'function'; +} +export declare namespace FunctionToolCall { + /** + * The definition of the function that was called. + */ + interface Function { + /** + * The arguments passed to the function. + */ + arguments: string; + /** + * The name of the function. + */ + name: string; + /** + * The output of the function. This will be `null` if the outputs have not been + * [submitted](https://platform.openai.com/docs/api-reference/runs/submitToolOutputs) + * yet. + */ + output: string | null; + } +} +export interface FunctionToolCallDelta { + /** + * The index of the tool call in the tool calls array. + */ + index: number; + /** + * The type of tool call. This is always going to be `function` for this type of + * tool call. + */ + type: 'function'; + /** + * The ID of the tool call object. + */ + id?: string; + /** + * The definition of the function that was called. + */ + function?: FunctionToolCallDelta.Function; +} +export declare namespace FunctionToolCallDelta { + /** + * The definition of the function that was called. + */ + interface Function { + /** + * The arguments passed to the function. + */ + arguments?: string; + /** + * The name of the function. + */ + name?: string; + /** + * The output of the function. This will be `null` if the outputs have not been + * [submitted](https://platform.openai.com/docs/api-reference/runs/submitToolOutputs) + * yet. + */ + output?: string | null; + } +} +/** + * Details of the message creation by the run step. + */ +export interface MessageCreationStepDetails { + message_creation: MessageCreationStepDetails.MessageCreation; + /** + * Always `message_creation`. + */ + type: 'message_creation'; +} +export declare namespace MessageCreationStepDetails { + interface MessageCreation { + /** + * The ID of the message that was created by this run step. + */ + message_id: string; + } +} +export interface RetrievalToolCall { + /** + * The ID of the tool call object. + */ + id: string; + /** + * For now, this is always going to be an empty object. + */ + retrieval: unknown; + /** + * The type of tool call. This is always going to be `retrieval` for this type of + * tool call. + */ + type: 'retrieval'; +} +export interface RetrievalToolCallDelta { + /** + * The index of the tool call in the tool calls array. + */ + index: number; + /** + * The type of tool call. This is always going to be `retrieval` for this type of + * tool call. + */ + type: 'retrieval'; + /** + * The ID of the tool call object. + */ + id?: string; + /** + * For now, this is always going to be an empty object. + */ + retrieval?: unknown; +} +/** + * Represents a step in execution of a run. + */ +export interface RunStep { + /** + * The identifier of the run step, which can be referenced in API endpoints. + */ + id: string; + /** + * The ID of the + * [assistant](https://platform.openai.com/docs/api-reference/assistants) + * associated with the run step. + */ + assistant_id: string; + /** + * The Unix timestamp (in seconds) for when the run step was cancelled. + */ + cancelled_at: number | null; + /** + * The Unix timestamp (in seconds) for when the run step completed. + */ + completed_at: number | null; + /** + * The Unix timestamp (in seconds) for when the run step was created. + */ + created_at: number; + /** + * The Unix timestamp (in seconds) for when the run step expired. A step is + * considered expired if the parent run is expired. + */ + expired_at: number | null; + /** + * The Unix timestamp (in seconds) for when the run step failed. + */ + failed_at: number | null; + /** + * The last error associated with this run step. Will be `null` if there are no + * errors. + */ + last_error: RunStep.LastError | null; + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata: unknown | null; + /** + * The object type, which is always `thread.run.step`. + */ + object: 'thread.run.step'; + /** + * The ID of the [run](https://platform.openai.com/docs/api-reference/runs) that + * this run step is a part of. + */ + run_id: string; + /** + * The status of the run step, which can be either `in_progress`, `cancelled`, + * `failed`, `completed`, or `expired`. + */ + status: 'in_progress' | 'cancelled' | 'failed' | 'completed' | 'expired'; + /** + * The details of the run step. + */ + step_details: MessageCreationStepDetails | ToolCallsStepDetails; + /** + * The ID of the [thread](https://platform.openai.com/docs/api-reference/threads) + * that was run. + */ + thread_id: string; + /** + * The type of run step, which can be either `message_creation` or `tool_calls`. + */ + type: 'message_creation' | 'tool_calls'; + /** + * Usage statistics related to the run step. This value will be `null` while the + * run step's status is `in_progress`. + */ + usage: RunStep.Usage | null; +} +export declare namespace RunStep { + /** + * The last error associated with this run step. Will be `null` if there are no + * errors. + */ + interface LastError { + /** + * One of `server_error` or `rate_limit_exceeded`. + */ + code: 'server_error' | 'rate_limit_exceeded'; + /** + * A human-readable description of the error. + */ + message: string; + } + /** + * Usage statistics related to the run step. This value will be `null` while the + * run step's status is `in_progress`. + */ + interface Usage { + /** + * Number of completion tokens used over the course of the run step. + */ + completion_tokens: number; + /** + * Number of prompt tokens used over the course of the run step. + */ + prompt_tokens: number; + /** + * Total number of tokens used (prompt + completion). + */ + total_tokens: number; + } +} +/** + * The delta containing the fields that have changed on the run step. + */ +export interface RunStepDelta { + /** + * The details of the run step. + */ + step_details?: RunStepDeltaMessageDelta | ToolCallDeltaObject; +} +/** + * Represents a run step delta i.e. any changed fields on a run step during + * streaming. + */ +export interface RunStepDeltaEvent { + /** + * The identifier of the run step, which can be referenced in API endpoints. + */ + id: string; + /** + * The delta containing the fields that have changed on the run step. + */ + delta: RunStepDelta; + /** + * The object type, which is always `thread.run.step.delta`. + */ + object: 'thread.run.step.delta'; +} +/** + * Details of the message creation by the run step. + */ +export interface RunStepDeltaMessageDelta { + /** + * Always `message_creation`. + */ + type: 'message_creation'; + message_creation?: RunStepDeltaMessageDelta.MessageCreation; +} +export declare namespace RunStepDeltaMessageDelta { + interface MessageCreation { + /** + * The ID of the message that was created by this run step. + */ + message_id?: string; + } +} +/** + * Details of the Code Interpreter tool call the run step was involved in. + */ +export type ToolCall = CodeInterpreterToolCall | RetrievalToolCall | FunctionToolCall; +/** + * Details of the Code Interpreter tool call the run step was involved in. + */ +export type ToolCallDelta = CodeInterpreterToolCallDelta | RetrievalToolCallDelta | FunctionToolCallDelta; +/** + * Details of the tool call. + */ +export interface ToolCallDeltaObject { + /** + * Always `tool_calls`. + */ + type: 'tool_calls'; + /** + * An array of tool calls the run step was involved in. These can be associated + * with one of three types of tools: `code_interpreter`, `retrieval`, or + * `function`. + */ + tool_calls?: Array; +} +/** + * Details of the tool call. + */ +export interface ToolCallsStepDetails { + /** + * An array of tool calls the run step was involved in. These can be associated + * with one of three types of tools: `code_interpreter`, `retrieval`, or + * `function`. + */ + tool_calls: Array; + /** + * Always `tool_calls`. + */ + type: 'tool_calls'; +} +export interface StepListParams extends CursorPageParams { + /** + * A cursor for use in pagination. `before` is an object ID that defines your place + * in the list. For instance, if you make a list request and receive 100 objects, + * ending with obj_foo, your subsequent call can include before=obj_foo in order to + * fetch the previous page of the list. + */ + before?: string; + /** + * Sort order by the `created_at` timestamp of the objects. `asc` for ascending + * order and `desc` for descending order. + */ + order?: 'asc' | 'desc'; +} +export declare namespace Steps { + export import CodeInterpreterLogs = StepsAPI.CodeInterpreterLogs; + export import CodeInterpreterOutputImage = StepsAPI.CodeInterpreterOutputImage; + export import CodeInterpreterToolCall = StepsAPI.CodeInterpreterToolCall; + export import CodeInterpreterToolCallDelta = StepsAPI.CodeInterpreterToolCallDelta; + export import FunctionToolCall = StepsAPI.FunctionToolCall; + export import FunctionToolCallDelta = StepsAPI.FunctionToolCallDelta; + export import MessageCreationStepDetails = StepsAPI.MessageCreationStepDetails; + export import RetrievalToolCall = StepsAPI.RetrievalToolCall; + export import RetrievalToolCallDelta = StepsAPI.RetrievalToolCallDelta; + export import RunStep = StepsAPI.RunStep; + export import RunStepDelta = StepsAPI.RunStepDelta; + export import RunStepDeltaEvent = StepsAPI.RunStepDeltaEvent; + export import RunStepDeltaMessageDelta = StepsAPI.RunStepDeltaMessageDelta; + export import ToolCall = StepsAPI.ToolCall; + export import ToolCallDelta = StepsAPI.ToolCallDelta; + export import ToolCallDeltaObject = StepsAPI.ToolCallDeltaObject; + export import ToolCallsStepDetails = StepsAPI.ToolCallsStepDetails; + export import RunStepsPage = StepsAPI.RunStepsPage; + export import StepListParams = StepsAPI.StepListParams; +} +//# sourceMappingURL=steps.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/threads/runs/steps.d.ts.map b/backend/node_modules/openai/resources/beta/threads/runs/steps.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..8df2e01050d4ac0b958663675ae30ec96ff108d7 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/threads/runs/steps.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"steps.d.ts","sourceRoot":"","sources":["../../../../src/resources/beta/threads/runs/steps.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,IAAI,MAAM,aAAa,CAAC;AACpC,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAE9C,OAAO,KAAK,QAAQ,MAAM,0CAA0C,CAAC;AACrE,OAAO,EAAE,UAAU,EAAE,KAAK,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAEtE,qBAAa,KAAM,SAAQ,WAAW;IACpC;;OAEG;IACH,QAAQ,CACN,QAAQ,EAAE,MAAM,EAChB,KAAK,EAAE,MAAM,EACb,MAAM,EAAE,MAAM,EACd,OAAO,CAAC,EAAE,IAAI,CAAC,cAAc,GAC5B,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC;IAO3B;;OAEG;IACH,IAAI,CACF,QAAQ,EAAE,MAAM,EAChB,KAAK,EAAE,MAAM,EACb,KAAK,CAAC,EAAE,cAAc,EACtB,OAAO,CAAC,EAAE,IAAI,CAAC,cAAc,GAC5B,IAAI,CAAC,WAAW,CAAC,YAAY,EAAE,OAAO,CAAC;IAC1C,IAAI,CACF,QAAQ,EAAE,MAAM,EAChB,KAAK,EAAE,MAAM,EACb,OAAO,CAAC,EAAE,IAAI,C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AAG,QAAQ,CAAC,0BAA0B,CAAC;IAC/E,MAAM,QAAQ,iBAAiB,GAAG,QAAQ,CAAC,iBAAiB,CAAC;IAC7D,MAAM,QAAQ,sBAAsB,GAAG,QAAQ,CAAC,sBAAsB,CAAC;IACvE,MAAM,QAAQ,OAAO,GAAG,QAAQ,CAAC,OAAO,CAAC;IACzC,MAAM,QAAQ,YAAY,GAAG,QAAQ,CAAC,YAAY,CAAC;IACnD,MAAM,QAAQ,iBAAiB,GAAG,QAAQ,CAAC,iBAAiB,CAAC;IAC7D,MAAM,QAAQ,wBAAwB,GAAG,QAAQ,CAAC,wBAAwB,CAAC;IAC3E,MAAM,QAAQ,QAAQ,GAAG,QAAQ,CAAC,QAAQ,CAAC;IAC3C,MAAM,QAAQ,aAAa,GAAG,QAAQ,CAAC,aAAa,CAAC;IACrD,MAAM,QAAQ,mBAAmB,GAAG,QAAQ,CAAC,mBAAmB,CAAC;IACjE,MAAM,QAAQ,oBAAoB,GAAG,QAAQ,CAAC,oBAAoB,CAAC;IACnE,MAAM,QAAQ,YAAY,GAAG,QAAQ,CAAC,YAAY,CAAC;IACnD,MAAM,QAAQ,cAAc,GAAG,QAAQ,CAAC,cAAc,CAAC;CACxD"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/threads/runs/steps.js b/backend/node_modules/openai/resources/beta/threads/runs/steps.js new file mode 100644 index 0000000000000000000000000000000000000000..ad66ad3223da9bb88069940089b00be2386e4f56 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/threads/runs/steps.js @@ -0,0 +1,60 @@ +"use strict"; +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.RunStepsPage = exports.Steps = void 0; +const resource_1 = require("openai/resource"); +const core_1 = require("openai/core"); +const StepsAPI = __importStar(require("openai/resources/beta/threads/runs/steps")); +const pagination_1 = require("openai/pagination"); +class Steps extends resource_1.APIResource { + /** + * Retrieves a run step. + */ + retrieve(threadId, runId, stepId, options) { + return this._client.get(`/threads/${threadId}/runs/${runId}/steps/${stepId}`, { + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } + list(threadId, runId, query = {}, options) { + if ((0, core_1.isRequestOptions)(query)) { + return this.list(threadId, runId, {}, query); + } + return this._client.getAPIList(`/threads/${threadId}/runs/${runId}/steps`, RunStepsPage, { + query, + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } +} +exports.Steps = Steps; +class RunStepsPage extends pagination_1.CursorPage { +} +exports.RunStepsPage = RunStepsPage; +(function (Steps) { + Steps.RunStepsPage = StepsAPI.RunStepsPage; +})(Steps = exports.Steps || (exports.Steps = {})); +//# sourceMappingURL=steps.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/threads/runs/steps.js.map b/backend/node_modules/openai/resources/beta/threads/runs/steps.js.map new file mode 100644 index 0000000000000000000000000000000000000000..c9909d203d01729b3910d48e561ed2a933c3bd20 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/threads/runs/steps.js.map @@ -0,0 +1 @@ +{"version":3,"file":"steps.js","sourceRoot":"","sources":["../../../../src/resources/beta/threads/runs/steps.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;;;;;;;;;;;;;;;;;;;;;;;;AAGtF,8CAA8C;AAC9C,sCAA+C;AAC/C,mFAAqE;AACrE,kDAAsE;AAEtE,MAAa,KAAM,SAAQ,sBAAW;IACpC;;OAEG;IACH,QAAQ,CACN,QAAgB,EAChB,KAAa,EACb,MAAc,EACd,OAA6B;QAE7B,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,YAAY,QAAQ,SAAS,KAAK,UAAU,MAAM,EAAE,EAAE;YAC5E,GAAG,OAAO;YACV,OAAO,EAAE,EAAE,aAAa,EAAE,eAAe,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE;SACjE,CAAC,CAAC;IACL,CAAC;IAgBD,IAAI,CACF,QAAgB,EAChB,KAAa,EACb,QAA8C,EAAE,EAChD,OAA6B;QAE7B,IAAI,IAAA,uBAAgB,EAAC,KAAK,CAAC,EAAE;YAC3B,OAAO,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,KAAK,EAAE,EAAE,EAAE,KAAK,CAAC,CAAC;SAC9C;QACD,OAAO,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,YAAY,QAAQ,SAAS,KAAK,QAAQ,EAAE,YAAY,EAAE;YACvF,KAAK;YACL,GAAG,OAAO;YACV,OAAO,EAAE,EAAE,aAAa,EAAE,eAAe,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE;SACjE,CAAC,CAAC;IACL,CAAC;CACF;AA7CD,sBA6CC;AAED,MAAa,YAAa,SAAQ,uBAAmB;CAAG;AAAxD,oCAAwD;AAqjBxD,WAAiB,KAAK;IAkBN,kBAAY,GAAG,QAAQ,CAAC,YAAY,CAAC;AAErD,CAAC,EApBgB,KAAK,GAAL,aAAK,KAAL,aAAK,QAoBrB"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/threads/runs/steps.mjs b/backend/node_modules/openai/resources/beta/threads/runs/steps.mjs new file mode 100644 index 0000000000000000000000000000000000000000..e71c42f01eb9a7dcaf4dc515c10266f436b18be8 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/threads/runs/steps.mjs @@ -0,0 +1,32 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +import { APIResource } from 'openai/resource'; +import { isRequestOptions } from 'openai/core'; +import * as StepsAPI from 'openai/resources/beta/threads/runs/steps'; +import { CursorPage } from 'openai/pagination'; +export class Steps extends APIResource { + /** + * Retrieves a run step. + */ + retrieve(threadId, runId, stepId, options) { + return this._client.get(`/threads/${threadId}/runs/${runId}/steps/${stepId}`, { + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } + list(threadId, runId, query = {}, options) { + if (isRequestOptions(query)) { + return this.list(threadId, runId, {}, query); + } + return this._client.getAPIList(`/threads/${threadId}/runs/${runId}/steps`, RunStepsPage, { + query, + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } +} +export class RunStepsPage extends CursorPage { +} +(function (Steps) { + Steps.RunStepsPage = StepsAPI.RunStepsPage; +})(Steps || (Steps = {})); +//# sourceMappingURL=steps.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/threads/runs/steps.mjs.map b/backend/node_modules/openai/resources/beta/threads/runs/steps.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..e2ca87af6c01b57f68a368f15f5ea2d5e2c367ba --- /dev/null +++ b/backend/node_modules/openai/resources/beta/threads/runs/steps.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"steps.mjs","sourceRoot":"","sources":["../../../../src/resources/beta/threads/runs/steps.ts"],"names":[],"mappings":"AAAA,sFAAsF;OAG/E,EAAE,WAAW,EAAE,MAAM,iBAAiB;OACtC,EAAE,gBAAgB,EAAE,MAAM,aAAa;OACvC,KAAK,QAAQ,MAAM,0CAA0C;OAC7D,EAAE,UAAU,EAAyB,MAAM,mBAAmB;AAErE,MAAM,OAAO,KAAM,SAAQ,WAAW;IACpC;;OAEG;IACH,QAAQ,CACN,QAAgB,EAChB,KAAa,EACb,MAAc,EACd,OAA6B;QAE7B,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,YAAY,QAAQ,SAAS,KAAK,UAAU,MAAM,EAAE,EAAE;YAC5E,GAAG,OAAO;YACV,OAAO,EAAE,EAAE,aAAa,EAAE,eAAe,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE;SACjE,CAAC,CAAC;IACL,CAAC;IAgBD,IAAI,CACF,QAAgB,EAChB,KAAa,EACb,QAA8C,EAAE,EAChD,OAA6B;QAE7B,IAAI,gBAAgB,CAAC,KAAK,CAAC,EAAE;YAC3B,OAAO,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,KAAK,EAAE,EAAE,EAAE,KAAK,CAAC,CAAC;SAC9C;QACD,OAAO,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,YAAY,QAAQ,SAAS,KAAK,QAAQ,EAAE,YAAY,EAAE;YACvF,KAAK;YACL,GAAG,OAAO;YACV,OAAO,EAAE,EAAE,aAAa,EAAE,eAAe,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE;SACjE,CAAC,CAAC;IACL,CAAC;CACF;AAED,MAAM,OAAO,YAAa,SAAQ,UAAmB;CAAG;AAqjBxD,WAAiB,KAAK;IAkBN,kBAAY,GAAG,QAAQ,CAAC,YAAY,CAAC;AAErD,CAAC,EApBgB,KAAK,KAAL,KAAK,QAoBrB"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/threads/threads.d.ts b/backend/node_modules/openai/resources/beta/threads/threads.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..718fa635d2d189bd4185fcfba79a2ba4dcd58229 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/threads/threads.d.ts @@ -0,0 +1,718 @@ +import * as Core from 'openai/core'; +import { APIPromise } from 'openai/core'; +import { APIResource } from 'openai/resource'; +import { AssistantStream, ThreadCreateAndRunParamsBaseStream } from 'openai/lib/AssistantStream'; +import * as ThreadsAPI from 'openai/resources/beta/threads/threads'; +import * as AssistantsAPI from 'openai/resources/beta/assistants/assistants'; +import * as MessagesAPI from 'openai/resources/beta/threads/messages/messages'; +import * as RunsAPI from 'openai/resources/beta/threads/runs/runs'; +import { Stream } from 'openai/streaming'; +export declare class Threads extends APIResource { + runs: RunsAPI.Runs; + messages: MessagesAPI.Messages; + /** + * Create a thread. + */ + create(body?: ThreadCreateParams, options?: Core.RequestOptions): Core.APIPromise; + create(options?: Core.RequestOptions): Core.APIPromise; + /** + * Retrieves a thread. + */ + retrieve(threadId: string, options?: Core.RequestOptions): Core.APIPromise; + /** + * Modifies a thread. + */ + update(threadId: string, body: ThreadUpdateParams, options?: Core.RequestOptions): Core.APIPromise; + /** + * Delete a thread. + */ + del(threadId: string, options?: Core.RequestOptions): Core.APIPromise; + /** + * Create a thread and run it in one request. + */ + createAndRun(body: ThreadCreateAndRunParamsNonStreaming, options?: Core.RequestOptions): APIPromise; + createAndRun(body: ThreadCreateAndRunParamsStreaming, options?: Core.RequestOptions): APIPromise>; + createAndRun(body: ThreadCreateAndRunParamsBase, options?: Core.RequestOptions): APIPromise | RunsAPI.Run>; + /** + * A helper to create a thread, start a run and then poll for a terminal state. + * More information on Run lifecycles can be found here: + * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps + */ + createAndRunPoll(body: ThreadCreateAndRunParamsNonStreaming, options?: Core.RequestOptions & { + pollIntervalMs?: number; + }): Promise; + /** + * Create a thread and stream the run back + */ + createAndRunStream(body: ThreadCreateAndRunParamsBaseStream, options?: Core.RequestOptions): AssistantStream; +} +/** + * An object describing the expected output of the model. If `json_object` only + * `function` type `tools` are allowed to be passed to the Run. If `text` the model + * can return text or any value needed. + */ +export interface AssistantResponseFormat { + /** + * Must be one of `text` or `json_object`. + */ + type?: 'text' | 'json_object'; +} +/** + * Specifies the format that the model must output. Compatible with + * [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and + * all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + * + * Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + * message the model generates is valid JSON. + * + * **Important:** when using JSON mode, you **must** also instruct the model to + * produce JSON yourself via a system or user message. Without this, the model may + * generate an unending stream of whitespace until the generation reaches the token + * limit, resulting in a long-running and seemingly "stuck" request. Also note that + * the message content may be partially cut off if `finish_reason="length"`, which + * indicates the generation exceeded `max_tokens` or the conversation exceeded the + * max context length. + */ +export type AssistantResponseFormatOption = 'none' | 'auto' | AssistantResponseFormat; +/** + * Specifies a tool the model should use. Use to force the model to call a specific + * tool. + */ +export interface AssistantToolChoice { + /** + * The type of the tool. If type is `function`, the function name must be set + */ + type: 'function' | 'code_interpreter' | 'retrieval'; + function?: AssistantToolChoiceFunction; +} +export interface AssistantToolChoiceFunction { + /** + * The name of the function to call. + */ + name: string; +} +/** + * Controls which (if any) tool is called by the model. `none` means the model will + * not call any tools and instead generates a message. `auto` is the default value + * and means the model can pick between generating a message or calling a tool. + * Specifying a particular tool like `{"type": "TOOL_TYPE"}` or + * `{"type": "function", "function": {"name": "my_function"}}` forces the model to + * call that tool. + */ +export type AssistantToolChoiceOption = 'none' | 'auto' | AssistantToolChoice; +/** + * Represents a thread that contains + * [messages](https://platform.openai.com/docs/api-reference/messages). + */ +export interface Thread { + /** + * The identifier, which can be referenced in API endpoints. + */ + id: string; + /** + * The Unix timestamp (in seconds) for when the thread was created. + */ + created_at: number; + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata: unknown | null; + /** + * The object type, which is always `thread`. + */ + object: 'thread'; +} +export interface ThreadDeleted { + id: string; + deleted: boolean; + object: 'thread.deleted'; +} +export interface ThreadCreateParams { + /** + * A list of [messages](https://platform.openai.com/docs/api-reference/messages) to + * start the thread with. + */ + messages?: Array; + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata?: unknown | null; +} +export declare namespace ThreadCreateParams { + interface Message { + /** + * The content of the message. + */ + content: string; + /** + * The role of the entity that is creating the message. Allowed values include: + * + * - `user`: Indicates the message is sent by an actual user and should be used in + * most cases to represent user-generated messages. + * - `assistant`: Indicates the message is generated by the assistant. Use this + * value to insert messages from the assistant into the conversation. + */ + role: 'user' | 'assistant'; + /** + * A list of [File](https://platform.openai.com/docs/api-reference/files) IDs that + * the message should use. There can be a maximum of 10 files attached to a + * message. Useful for tools like `retrieval` and `code_interpreter` that can + * access and use files. + */ + file_ids?: Array; + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata?: unknown | null; + } +} +export interface ThreadUpdateParams { + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata?: unknown | null; +} +export type ThreadCreateAndRunParams = ThreadCreateAndRunParamsNonStreaming | ThreadCreateAndRunParamsStreaming; +export interface ThreadCreateAndRunParamsBase { + /** + * The ID of the + * [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to + * execute this run. + */ + assistant_id: string; + /** + * Override the default system message of the assistant. This is useful for + * modifying the behavior on a per-run basis. + */ + instructions?: string | null; + /** + * The maximum number of completion tokens that may be used over the course of the + * run. The run will make a best effort to use only the number of completion tokens + * specified, across multiple turns of the run. If the run exceeds the number of + * completion tokens specified, the run will end with status `complete`. See + * `incomplete_details` for more info. + */ + max_completion_tokens?: number | null; + /** + * The maximum number of prompt tokens that may be used over the course of the run. + * The run will make a best effort to use only the number of prompt tokens + * specified, across multiple turns of the run. If the run exceeds the number of + * prompt tokens specified, the run will end with status `complete`. See + * `incomplete_details` for more info. + */ + max_prompt_tokens?: number | null; + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata?: unknown | null; + /** + * The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to + * be used to execute this run. If a value is provided here, it will override the + * model associated with the assistant. If not, the model associated with the + * assistant will be used. + */ + model?: (string & {}) | 'gpt-4-turbo' | 'gpt-4-turbo-2024-04-09' | 'gpt-4-0125-preview' | 'gpt-4-turbo-preview' | 'gpt-4-1106-preview' | 'gpt-4-vision-preview' | 'gpt-4' | 'gpt-4-0314' | 'gpt-4-0613' | 'gpt-4-32k' | 'gpt-4-32k-0314' | 'gpt-4-32k-0613' | 'gpt-3.5-turbo' | 'gpt-3.5-turbo-16k' | 'gpt-3.5-turbo-0613' | 'gpt-3.5-turbo-1106' | 'gpt-3.5-turbo-0125' | 'gpt-3.5-turbo-16k-0613' | null; + /** + * Specifies the format that the model must output. Compatible with + * [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and + * all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + * + * Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + * message the model generates is valid JSON. + * + * **Important:** when using JSON mode, you **must** also instruct the model to + * produce JSON yourself via a system or user message. Without this, the model may + * generate an unending stream of whitespace until the generation reaches the token + * limit, resulting in a long-running and seemingly "stuck" request. Also note that + * the message content may be partially cut off if `finish_reason="length"`, which + * indicates the generation exceeded `max_tokens` or the conversation exceeded the + * max context length. + */ + response_format?: AssistantResponseFormatOption | null; + /** + * If `true`, returns a stream of events that happen during the Run as server-sent + * events, terminating when the Run enters a terminal state with a `data: [DONE]` + * message. + */ + stream?: boolean | null; + /** + * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + * make the output more random, while lower values like 0.2 will make it more + * focused and deterministic. + */ + temperature?: number | null; + /** + * If no thread is provided, an empty thread will be created. + */ + thread?: ThreadCreateAndRunParams.Thread; + /** + * Controls which (if any) tool is called by the model. `none` means the model will + * not call any tools and instead generates a message. `auto` is the default value + * and means the model can pick between generating a message or calling a tool. + * Specifying a particular tool like `{"type": "TOOL_TYPE"}` or + * `{"type": "function", "function": {"name": "my_function"}}` forces the model to + * call that tool. + */ + tool_choice?: AssistantToolChoiceOption | null; + /** + * Override the tools the assistant can use for this run. This is useful for + * modifying the behavior on a per-run basis. + */ + tools?: Array | null; + truncation_strategy?: ThreadCreateAndRunParams.TruncationStrategy | null; +} +export declare namespace ThreadCreateAndRunParams { + /** + * If no thread is provided, an empty thread will be created. + */ + interface Thread { + /** + * A list of [messages](https://platform.openai.com/docs/api-reference/messages) to + * start the thread with. + */ + messages?: Array; + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata?: unknown | null; + } + namespace Thread { + interface Message { + /** + * The content of the message. + */ + content: string; + /** + * The role of the entity that is creating the message. Allowed values include: + * + * - `user`: Indicates the message is sent by an actual user and should be used in + * most cases to represent user-generated messages. + * - `assistant`: Indicates the message is generated by the assistant. Use this + * value to insert messages from the assistant into the conversation. + */ + role: 'user' | 'assistant'; + /** + * A list of [File](https://platform.openai.com/docs/api-reference/files) IDs that + * the message should use. There can be a maximum of 10 files attached to a + * message. Useful for tools like `retrieval` and `code_interpreter` that can + * access and use files. + */ + file_ids?: Array; + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata?: unknown | null; + } + } + interface TruncationStrategy { + /** + * The truncation strategy to use for the thread. The default is `auto`. If set to + * `last_messages`, the thread will be truncated to the n most recent messages in + * the thread. When set to `auto`, messages in the middle of the thread will be + * dropped to fit the context length of the model, `max_prompt_tokens`. + */ + type: 'auto' | 'last_messages'; + /** + * The number of most recent messages from the thread when constructing the context + * for the run. + */ + last_messages?: number | null; + } + type ThreadCreateAndRunParamsNonStreaming = ThreadsAPI.ThreadCreateAndRunParamsNonStreaming; + type ThreadCreateAndRunParamsStreaming = ThreadsAPI.ThreadCreateAndRunParamsStreaming; +} +export interface ThreadCreateAndRunParamsNonStreaming extends ThreadCreateAndRunParamsBase { + /** + * If `true`, returns a stream of events that happen during the Run as server-sent + * events, terminating when the Run enters a terminal state with a `data: [DONE]` + * message. + */ + stream?: false | null; +} +export interface ThreadCreateAndRunParamsStreaming extends ThreadCreateAndRunParamsBase { + /** + * If `true`, returns a stream of events that happen during the Run as server-sent + * events, terminating when the Run enters a terminal state with a `data: [DONE]` + * message. + */ + stream: true; +} +export interface ThreadCreateAndRunPollParams { + /** + * The ID of the + * [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to + * execute this run. + */ + assistant_id: string; + /** + * Override the default system message of the assistant. This is useful for + * modifying the behavior on a per-run basis. + */ + instructions?: string | null; + /** + * The maximum number of completion tokens that may be used over the course of the + * run. The run will make a best effort to use only the number of completion tokens + * specified, across multiple turns of the run. If the run exceeds the number of + * completion tokens specified, the run will end with status `complete`. See + * `incomplete_details` for more info. + */ + max_completion_tokens?: number | null; + /** + * The maximum number of prompt tokens that may be used over the course of the run. + * The run will make a best effort to use only the number of prompt tokens + * specified, across multiple turns of the run. If the run exceeds the number of + * prompt tokens specified, the run will end with status `complete`. See + * `incomplete_details` for more info. + */ + max_prompt_tokens?: number | null; + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata?: unknown | null; + /** + * The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to + * be used to execute this run. If a value is provided here, it will override the + * model associated with the assistant. If not, the model associated with the + * assistant will be used. + */ + model?: (string & {}) | 'gpt-4-turbo' | 'gpt-4-turbo-2024-04-09' | 'gpt-4-0125-preview' | 'gpt-4-turbo-preview' | 'gpt-4-1106-preview' | 'gpt-4-vision-preview' | 'gpt-4' | 'gpt-4-0314' | 'gpt-4-0613' | 'gpt-4-32k' | 'gpt-4-32k-0314' | 'gpt-4-32k-0613' | 'gpt-3.5-turbo' | 'gpt-3.5-turbo-16k' | 'gpt-3.5-turbo-0613' | 'gpt-3.5-turbo-1106' | 'gpt-3.5-turbo-0125' | 'gpt-3.5-turbo-16k-0613' | null; + /** + * Specifies the format that the model must output. Compatible with + * [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and + * all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + * + * Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + * message the model generates is valid JSON. + * + * **Important:** when using JSON mode, you **must** also instruct the model to + * produce JSON yourself via a system or user message. Without this, the model may + * generate an unending stream of whitespace until the generation reaches the token + * limit, resulting in a long-running and seemingly "stuck" request. Also note that + * the message content may be partially cut off if `finish_reason="length"`, which + * indicates the generation exceeded `max_tokens` or the conversation exceeded the + * max context length. + */ + response_format?: AssistantResponseFormatOption | null; + /** + * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + * make the output more random, while lower values like 0.2 will make it more + * focused and deterministic. + */ + temperature?: number | null; + /** + * If no thread is provided, an empty thread will be created. + */ + thread?: ThreadCreateAndRunPollParams.Thread; + /** + * Controls which (if any) tool is called by the model. `none` means the model will + * not call any tools and instead generates a message. `auto` is the default value + * and means the model can pick between generating a message or calling a tool. + * Specifying a particular tool like `{"type": "TOOL_TYPE"}` or + * `{"type": "function", "function": {"name": "my_function"}}` forces the model to + * call that tool. + */ + tool_choice?: AssistantToolChoiceOption | null; + /** + * Override the tools the assistant can use for this run. This is useful for + * modifying the behavior on a per-run basis. + */ + tools?: Array | null; + truncation_strategy?: ThreadCreateAndRunPollParams.TruncationStrategy | null; +} +export declare namespace ThreadCreateAndRunPollParams { + /** + * If no thread is provided, an empty thread will be created. + */ + interface Thread { + /** + * A list of [messages](https://platform.openai.com/docs/api-reference/messages) to + * start the thread with. + */ + messages?: Array; + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata?: unknown | null; + } + namespace Thread { + interface Message { + /** + * The content of the message. + */ + content: string; + /** + * The role of the entity that is creating the message. Allowed values include: + * + * - `user`: Indicates the message is sent by an actual user and should be used in + * most cases to represent user-generated messages. + * - `assistant`: Indicates the message is generated by the assistant. Use this + * value to insert messages from the assistant into the conversation. + */ + role: 'user' | 'assistant'; + /** + * A list of [File](https://platform.openai.com/docs/api-reference/files) IDs that + * the message should use. There can be a maximum of 10 files attached to a + * message. Useful for tools like `retrieval` and `code_interpreter` that can + * access and use files. + */ + file_ids?: Array; + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata?: unknown | null; + } + } + interface TruncationStrategy { + /** + * The truncation strategy to use for the thread. The default is `auto`. If set to + * `last_messages`, the thread will be truncated to the n most recent messages in + * the thread. When set to `auto`, messages in the middle of the thread will be + * dropped to fit the context length of the model, `max_prompt_tokens`. + */ + type: 'auto' | 'last_messages'; + /** + * The number of most recent messages from the thread when constructing the context + * for the run. + */ + last_messages?: number | null; + } +} +export interface ThreadCreateAndRunStreamParams { + /** + * The ID of the + * [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to + * execute this run. + */ + assistant_id: string; + /** + * Override the default system message of the assistant. This is useful for + * modifying the behavior on a per-run basis. + */ + instructions?: string | null; + /** + * The maximum number of completion tokens that may be used over the course of the + * run. The run will make a best effort to use only the number of completion tokens + * specified, across multiple turns of the run. If the run exceeds the number of + * completion tokens specified, the run will end with status `complete`. See + * `incomplete_details` for more info. + */ + max_completion_tokens?: number | null; + /** + * The maximum number of prompt tokens that may be used over the course of the run. + * The run will make a best effort to use only the number of prompt tokens + * specified, across multiple turns of the run. If the run exceeds the number of + * prompt tokens specified, the run will end with status `complete`. See + * `incomplete_details` for more info. + */ + max_prompt_tokens?: number | null; + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata?: unknown | null; + /** + * The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to + * be used to execute this run. If a value is provided here, it will override the + * model associated with the assistant. If not, the model associated with the + * assistant will be used. + */ + model?: (string & {}) | 'gpt-4-turbo' | 'gpt-4-turbo-2024-04-09' | 'gpt-4-0125-preview' | 'gpt-4-turbo-preview' | 'gpt-4-1106-preview' | 'gpt-4-vision-preview' | 'gpt-4' | 'gpt-4-0314' | 'gpt-4-0613' | 'gpt-4-32k' | 'gpt-4-32k-0314' | 'gpt-4-32k-0613' | 'gpt-3.5-turbo' | 'gpt-3.5-turbo-16k' | 'gpt-3.5-turbo-0613' | 'gpt-3.5-turbo-1106' | 'gpt-3.5-turbo-0125' | 'gpt-3.5-turbo-16k-0613' | null; + /** + * Specifies the format that the model must output. Compatible with + * [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and + * all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + * + * Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + * message the model generates is valid JSON. + * + * **Important:** when using JSON mode, you **must** also instruct the model to + * produce JSON yourself via a system or user message. Without this, the model may + * generate an unending stream of whitespace until the generation reaches the token + * limit, resulting in a long-running and seemingly "stuck" request. Also note that + * the message content may be partially cut off if `finish_reason="length"`, which + * indicates the generation exceeded `max_tokens` or the conversation exceeded the + * max context length. + */ + response_format?: AssistantResponseFormatOption | null; + /** + * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + * make the output more random, while lower values like 0.2 will make it more + * focused and deterministic. + */ + temperature?: number | null; + /** + * If no thread is provided, an empty thread will be created. + */ + thread?: ThreadCreateAndRunStreamParams.Thread; + /** + * Controls which (if any) tool is called by the model. `none` means the model will + * not call any tools and instead generates a message. `auto` is the default value + * and means the model can pick between generating a message or calling a tool. + * Specifying a particular tool like `{"type": "TOOL_TYPE"}` or + * `{"type": "function", "function": {"name": "my_function"}}` forces the model to + * call that tool. + */ + tool_choice?: AssistantToolChoiceOption | null; + /** + * Override the tools the assistant can use for this run. This is useful for + * modifying the behavior on a per-run basis. + */ + tools?: Array | null; + truncation_strategy?: ThreadCreateAndRunStreamParams.TruncationStrategy | null; +} +export declare namespace ThreadCreateAndRunStreamParams { + /** + * If no thread is provided, an empty thread will be created. + */ + interface Thread { + /** + * A list of [messages](https://platform.openai.com/docs/api-reference/messages) to + * start the thread with. + */ + messages?: Array; + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata?: unknown | null; + } + namespace Thread { + interface Message { + /** + * The content of the message. + */ + content: string; + /** + * The role of the entity that is creating the message. Allowed values include: + * + * - `user`: Indicates the message is sent by an actual user and should be used in + * most cases to represent user-generated messages. + * - `assistant`: Indicates the message is generated by the assistant. Use this + * value to insert messages from the assistant into the conversation. + */ + role: 'user' | 'assistant'; + /** + * A list of [File](https://platform.openai.com/docs/api-reference/files) IDs that + * the message should use. There can be a maximum of 10 files attached to a + * message. Useful for tools like `retrieval` and `code_interpreter` that can + * access and use files. + */ + file_ids?: Array; + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata?: unknown | null; + } + } + interface TruncationStrategy { + /** + * The truncation strategy to use for the thread. The default is `auto`. If set to + * `last_messages`, the thread will be truncated to the n most recent messages in + * the thread. When set to `auto`, messages in the middle of the thread will be + * dropped to fit the context length of the model, `max_prompt_tokens`. + */ + type: 'auto' | 'last_messages'; + /** + * The number of most recent messages from the thread when constructing the context + * for the run. + */ + last_messages?: number | null; + } +} +export declare namespace Threads { + export import AssistantResponseFormat = ThreadsAPI.AssistantResponseFormat; + export import AssistantResponseFormatOption = ThreadsAPI.AssistantResponseFormatOption; + export import AssistantToolChoice = ThreadsAPI.AssistantToolChoice; + export import AssistantToolChoiceFunction = ThreadsAPI.AssistantToolChoiceFunction; + export import AssistantToolChoiceOption = ThreadsAPI.AssistantToolChoiceOption; + export import Thread = ThreadsAPI.Thread; + export import ThreadDeleted = ThreadsAPI.ThreadDeleted; + export import ThreadCreateParams = ThreadsAPI.ThreadCreateParams; + export import ThreadUpdateParams = ThreadsAPI.ThreadUpdateParams; + export import ThreadCreateAndRunParams = ThreadsAPI.ThreadCreateAndRunParams; + export import ThreadCreateAndRunParamsNonStreaming = ThreadsAPI.ThreadCreateAndRunParamsNonStreaming; + export import ThreadCreateAndRunParamsStreaming = ThreadsAPI.ThreadCreateAndRunParamsStreaming; + export import ThreadCreateAndRunPollParams = ThreadsAPI.ThreadCreateAndRunPollParams; + export import ThreadCreateAndRunStreamParams = ThreadsAPI.ThreadCreateAndRunStreamParams; + export import Runs = RunsAPI.Runs; + export import RequiredActionFunctionToolCall = RunsAPI.RequiredActionFunctionToolCall; + export import Run = RunsAPI.Run; + export import RunStatus = RunsAPI.RunStatus; + export import RunsPage = RunsAPI.RunsPage; + export import RunCreateParams = RunsAPI.RunCreateParams; + export import RunCreateParamsNonStreaming = RunsAPI.RunCreateParamsNonStreaming; + export import RunCreateParamsStreaming = RunsAPI.RunCreateParamsStreaming; + export import RunUpdateParams = RunsAPI.RunUpdateParams; + export import RunListParams = RunsAPI.RunListParams; + export import RunCreateAndPollParams = RunsAPI.RunCreateAndPollParams; + export import RunCreateAndStreamParams = RunsAPI.RunCreateAndStreamParams; + export import RunStreamParams = RunsAPI.RunStreamParams; + export import RunSubmitToolOutputsParams = RunsAPI.RunSubmitToolOutputsParams; + export import RunSubmitToolOutputsParamsNonStreaming = RunsAPI.RunSubmitToolOutputsParamsNonStreaming; + export import RunSubmitToolOutputsParamsStreaming = RunsAPI.RunSubmitToolOutputsParamsStreaming; + export import RunSubmitToolOutputsAndPollParams = RunsAPI.RunSubmitToolOutputsAndPollParams; + export import RunSubmitToolOutputsStreamParams = RunsAPI.RunSubmitToolOutputsStreamParams; + export import Messages = MessagesAPI.Messages; + export import Annotation = MessagesAPI.Annotation; + export import AnnotationDelta = MessagesAPI.AnnotationDelta; + export import FileCitationAnnotation = MessagesAPI.FileCitationAnnotation; + export import FileCitationDeltaAnnotation = MessagesAPI.FileCitationDeltaAnnotation; + export import FilePathAnnotation = MessagesAPI.FilePathAnnotation; + export import FilePathDeltaAnnotation = MessagesAPI.FilePathDeltaAnnotation; + export import ImageFile = MessagesAPI.ImageFile; + export import ImageFileContentBlock = MessagesAPI.ImageFileContentBlock; + export import ImageFileDelta = MessagesAPI.ImageFileDelta; + export import ImageFileDeltaBlock = MessagesAPI.ImageFileDeltaBlock; + export import Message = MessagesAPI.Message; + export import MessageContent = MessagesAPI.MessageContent; + export import MessageContentDelta = MessagesAPI.MessageContentDelta; + export import MessageDeleted = MessagesAPI.MessageDeleted; + export import MessageDelta = MessagesAPI.MessageDelta; + export import MessageDeltaEvent = MessagesAPI.MessageDeltaEvent; + export import Text = MessagesAPI.Text; + export import TextContentBlock = MessagesAPI.TextContentBlock; + export import TextDelta = MessagesAPI.TextDelta; + export import TextDeltaBlock = MessagesAPI.TextDeltaBlock; + export import MessagesPage = MessagesAPI.MessagesPage; + export import MessageCreateParams = MessagesAPI.MessageCreateParams; + export import MessageUpdateParams = MessagesAPI.MessageUpdateParams; + export import MessageListParams = MessagesAPI.MessageListParams; +} +//# sourceMappingURL=threads.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/threads/threads.d.ts.map b/backend/node_modules/openai/resources/beta/threads/threads.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..1bdf41ae7430b3399372cf092bb18c697f2b47af --- /dev/null +++ b/backend/node_modules/openai/resources/beta/threads/threads.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"threads.d.ts","sourceRo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W,CAAC,IAAI,CAAC;IACtC,MAAM,QAAQ,gBAAgB,GAAG,WAAW,CAAC,gBAAgB,CAAC;IAC9D,MAAM,QAAQ,SAAS,GAAG,WAAW,CAAC,SAAS,CAAC;IAChD,MAAM,QAAQ,cAAc,GAAG,WAAW,CAAC,cAAc,CAAC;IAC1D,MAAM,QAAQ,YAAY,GAAG,WAAW,CAAC,YAAY,CAAC;IACtD,MAAM,QAAQ,mBAAmB,GAAG,WAAW,CAAC,mBAAmB,CAAC;IACpE,MAAM,QAAQ,mBAAmB,GAAG,WAAW,CAAC,mBAAmB,CAAC;IACpE,MAAM,QAAQ,iBAAiB,GAAG,WAAW,CAAC,iBAAiB,CAAC;CACjE"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/threads/threads.js b/backend/node_modules/openai/resources/beta/threads/threads.js new file mode 100644 index 0000000000000000000000000000000000000000..6d6041429a083ba8ac85d51e97a1621e2b84ab0e --- /dev/null +++ b/backend/node_modules/openai/resources/beta/threads/threads.js @@ -0,0 +1,108 @@ +"use strict"; +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Threads = void 0; +const resource_1 = require("openai/resource"); +const core_1 = require("openai/core"); +const AssistantStream_1 = require("openai/lib/AssistantStream"); +const MessagesAPI = __importStar(require("openai/resources/beta/threads/messages/messages")); +const RunsAPI = __importStar(require("openai/resources/beta/threads/runs/runs")); +class Threads extends resource_1.APIResource { + constructor() { + super(...arguments); + this.runs = new RunsAPI.Runs(this._client); + this.messages = new MessagesAPI.Messages(this._client); + } + create(body = {}, options) { + if ((0, core_1.isRequestOptions)(body)) { + return this.create({}, body); + } + return this._client.post('/threads', { + body, + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } + /** + * Retrieves a thread. + */ + retrieve(threadId, options) { + return this._client.get(`/threads/${threadId}`, { + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } + /** + * Modifies a thread. + */ + update(threadId, body, options) { + return this._client.post(`/threads/${threadId}`, { + body, + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } + /** + * Delete a thread. + */ + del(threadId, options) { + return this._client.delete(`/threads/${threadId}`, { + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } + createAndRun(body, options) { + return this._client.post('/threads/runs', { + body, + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + stream: body.stream ?? false, + }); + } + /** + * A helper to create a thread, start a run and then poll for a terminal state. + * More information on Run lifecycles can be found here: + * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps + */ + async createAndRunPoll(body, options) { + const run = await this.createAndRun(body, options); + return await this.runs.poll(run.thread_id, run.id, options); + } + /** + * Create a thread and stream the run back + */ + createAndRunStream(body, options) { + return AssistantStream_1.AssistantStream.createThreadAssistantStream(body, this._client.beta.threads, options); + } +} +exports.Threads = Threads; +(function (Threads) { + Threads.Runs = RunsAPI.Runs; + Threads.RunsPage = RunsAPI.RunsPage; + Threads.Messages = MessagesAPI.Messages; + Threads.MessagesPage = MessagesAPI.MessagesPage; +})(Threads = exports.Threads || (exports.Threads = {})); +//# sourceMappingURL=threads.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/threads/threads.js.map b/backend/node_modules/openai/resources/beta/threads/threads.js.map new file mode 100644 index 0000000000000000000000000000000000000000..b2b80407367fc984ea30e50b599e92ecb2129ed5 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/threads/threads.js.map @@ -0,0 +1 @@ +{"version":3,"file":"threads.js","sourceRoot":"","sources":["../../../src/resources/beta/threads/threads.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;;;;;;;;;;;;;;;;;;;;;;;;AAItF,8CAA8C;AAC9C,sCAA+C;AAC/C,gEAAiG;AAGjG,6FAA+E;AAC/E,iFAAmE;AAGnE,MAAa,OAAQ,SAAQ,sBAAW;IAAxC;;QACE,SAAI,GAAiB,IAAI,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QACpD,aAAQ,GAAyB,IAAI,WAAW,CAAC,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IAqG1E,CAAC;IA9FC,MAAM,CACJ,OAAiD,EAAE,EACnD,OAA6B;QAE7B,IAAI,IAAA,uBAAgB,EAAC,IAAI,CAAC,EAAE;YAC1B,OAAO,IAAI,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,CAAC;SAC9B;QACD,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,UAAU,EAAE;YACnC,IAAI;YACJ,GAAG,OAAO;YACV,OAAO,EAAE,EAAE,aAAa,EAAE,eAAe,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE;SACjE,CAAC,CAAC;IACL,CAAC;IAED;;OAEG;IACH,QAAQ,CAAC,QAAgB,EAAE,OAA6B;QACtD,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,YAAY,QAAQ,EAAE,EAAE;YAC9C,GAAG,OAAO;YACV,OAAO,E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C,OAA6B;QAE7B,OAAO,iCAAe,CAAC,2BAA2B,CAAC,IAAI,EAAE,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;IAC/F,CAAC;CACF;AAvGD,0BAuGC;AA6vBD,WAAiB,OAAO;IAeR,YAAI,GAAG,OAAO,CAAC,IAAI,CAAC;IAIpB,gBAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC;IAc5B,gBAAQ,GAAG,WAAW,CAAC,QAAQ,CAAC;IAqBhC,oBAAY,GAAG,WAAW,CAAC,YAAY,CAAC;AAIxD,CAAC,EA1DgB,OAAO,GAAP,eAAO,KAAP,eAAO,QA0DvB"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/threads/threads.mjs b/backend/node_modules/openai/resources/beta/threads/threads.mjs new file mode 100644 index 0000000000000000000000000000000000000000..008baef8bdb5b3e27dc07e617c1833d8a065c29d --- /dev/null +++ b/backend/node_modules/openai/resources/beta/threads/threads.mjs @@ -0,0 +1,81 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +import { APIResource } from 'openai/resource'; +import { isRequestOptions } from 'openai/core'; +import { AssistantStream } from 'openai/lib/AssistantStream'; +import * as MessagesAPI from 'openai/resources/beta/threads/messages/messages'; +import * as RunsAPI from 'openai/resources/beta/threads/runs/runs'; +export class Threads extends APIResource { + constructor() { + super(...arguments); + this.runs = new RunsAPI.Runs(this._client); + this.messages = new MessagesAPI.Messages(this._client); + } + create(body = {}, options) { + if (isRequestOptions(body)) { + return this.create({}, body); + } + return this._client.post('/threads', { + body, + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } + /** + * Retrieves a thread. + */ + retrieve(threadId, options) { + return this._client.get(`/threads/${threadId}`, { + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } + /** + * Modifies a thread. + */ + update(threadId, body, options) { + return this._client.post(`/threads/${threadId}`, { + body, + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } + /** + * Delete a thread. + */ + del(threadId, options) { + return this._client.delete(`/threads/${threadId}`, { + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } + createAndRun(body, options) { + return this._client.post('/threads/runs', { + body, + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + stream: body.stream ?? false, + }); + } + /** + * A helper to create a thread, start a run and then poll for a terminal state. + * More information on Run lifecycles can be found here: + * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps + */ + async createAndRunPoll(body, options) { + const run = await this.createAndRun(body, options); + return await this.runs.poll(run.thread_id, run.id, options); + } + /** + * Create a thread and stream the run back + */ + createAndRunStream(body, options) { + return AssistantStream.createThreadAssistantStream(body, this._client.beta.threads, options); + } +} +(function (Threads) { + Threads.Runs = RunsAPI.Runs; + Threads.RunsPage = RunsAPI.RunsPage; + Threads.Messages = MessagesAPI.Messages; + Threads.MessagesPage = MessagesAPI.MessagesPage; +})(Threads || (Threads = {})); +//# sourceMappingURL=threads.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/beta/threads/threads.mjs.map b/backend/node_modules/openai/resources/beta/threads/threads.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..8bb4962957740d858d339a8541ebc7164f658279 --- /dev/null +++ b/backend/node_modules/openai/resources/beta/threads/threads.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"threads.mjs","sourceRoot":"","sources":["../../../src/resources/beta/threads/threads.ts"],"names":[],"mappings":"AAAA,sFAAsF;OAI/E,EAAE,WAAW,EAAE,MAAM,iBAAiB;OACtC,EAAE,gBAAgB,EAAE,MAAM,aAAa;OACvC,EAAE,eAAe,EAAsC,MAAM,4BAA4B;OAGzF,KAAK,WAAW,MAAM,iDAAiD;OACvE,KAAK,OAAO,MAAM,yCAAyC;AAGlE,MAAM,OAAO,OAAQ,SAAQ,WAAW;IAAxC;;QACE,SAAI,GAAiB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AG,OAAO,EAAE,OAAO,EAAE;SACjE,CAAC,CAAC;IACL,CAAC;IAiBD,YAAY,CACV,IAA8B,EAC9B,OAA6B;QAE7B,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,eAAe,EAAE;YACxC,IAAI;YACJ,GAAG,OAAO;YACV,OAAO,EAAE,EAAE,aAAa,EAAE,eAAe,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE;YAChE,MAAM,EAAE,IAAI,CAAC,MAAM,IAAI,KAAK;SAC7B,CAAqF,CAAC;IACzF,CAAC;IAED;;;;OAIG;IACH,KAAK,CAAC,gBAAgB,CACpB,IAA0C,EAC1C,OAA2D;QAE3D,MAAM,GAAG,GAAG,MAAM,IAAI,CAAC,YAAY,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;QACnD,OAAO,MAAM,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,SAAS,EAAE,GAAG,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;IAC9D,CAAC;IAED;;OAEG;IACH,kBAAkB,CAChB,IAAwC,EACxC,OAA6B;QAE7B,OAAO,eAAe,CAAC,2BAA2B,CAAC,IAAI,EAAE,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;IAC/F,CAAC;CACF;AA6vBD,WAAiB,OAAO;IAeR,YAAI,GAAG,OAAO,CAAC,IAAI,CAAC;IAIpB,gBAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC;IAc5B,gBAAQ,GAAG,WAAW,CAAC,QAAQ,CAAC;IAqBhC,oBAAY,GAAG,WAAW,CAAC,YAAY,CAAC;AAIxD,CAAC,EA1DgB,OAAO,KAAP,OAAO,QA0DvB"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/chat/chat.d.ts b/backend/node_modules/openai/resources/chat/chat.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c96a1f51b1bf1e3acf1bb6490df112c72c4cff1c --- /dev/null +++ b/backend/node_modules/openai/resources/chat/chat.d.ts @@ -0,0 +1,38 @@ +import { APIResource } from 'openai/resource'; +import * as CompletionsAPI from 'openai/resources/chat/completions'; +export declare class Chat extends APIResource { + completions: CompletionsAPI.Completions; +} +export declare namespace Chat { + export import Completions = CompletionsAPI.Completions; + export import ChatCompletion = CompletionsAPI.ChatCompletion; + export import ChatCompletionAssistantMessageParam = CompletionsAPI.ChatCompletionAssistantMessageParam; + export import ChatCompletionChunk = CompletionsAPI.ChatCompletionChunk; + export import ChatCompletionContentPart = CompletionsAPI.ChatCompletionContentPart; + export import ChatCompletionContentPartImage = CompletionsAPI.ChatCompletionContentPartImage; + export import ChatCompletionContentPartText = CompletionsAPI.ChatCompletionContentPartText; + export import ChatCompletionFunctionCallOption = CompletionsAPI.ChatCompletionFunctionCallOption; + export import ChatCompletionFunctionMessageParam = CompletionsAPI.ChatCompletionFunctionMessageParam; + export import ChatCompletionMessage = CompletionsAPI.ChatCompletionMessage; + export import ChatCompletionMessageParam = CompletionsAPI.ChatCompletionMessageParam; + export import ChatCompletionMessageToolCall = CompletionsAPI.ChatCompletionMessageToolCall; + export import ChatCompletionNamedToolChoice = CompletionsAPI.ChatCompletionNamedToolChoice; + export import ChatCompletionRole = CompletionsAPI.ChatCompletionRole; + export import ChatCompletionSystemMessageParam = CompletionsAPI.ChatCompletionSystemMessageParam; + export import ChatCompletionTokenLogprob = CompletionsAPI.ChatCompletionTokenLogprob; + export import ChatCompletionTool = CompletionsAPI.ChatCompletionTool; + export import ChatCompletionToolChoiceOption = CompletionsAPI.ChatCompletionToolChoiceOption; + export import ChatCompletionToolMessageParam = CompletionsAPI.ChatCompletionToolMessageParam; + export import ChatCompletionUserMessageParam = CompletionsAPI.ChatCompletionUserMessageParam; + /** + * @deprecated ChatCompletionMessageParam should be used instead + */ + export import CreateChatCompletionRequestMessage = CompletionsAPI.CreateChatCompletionRequestMessage; + export import ChatCompletionCreateParams = CompletionsAPI.ChatCompletionCreateParams; + export import CompletionCreateParams = CompletionsAPI.CompletionCreateParams; + export import ChatCompletionCreateParamsNonStreaming = CompletionsAPI.ChatCompletionCreateParamsNonStreaming; + export import CompletionCreateParamsNonStreaming = CompletionsAPI.CompletionCreateParamsNonStreaming; + export import ChatCompletionCreateParamsStreaming = CompletionsAPI.ChatCompletionCreateParamsStreaming; + export import CompletionCreateParamsStreaming = CompletionsAPI.CompletionCreateParamsStreaming; +} +//# sourceMappingURL=chat.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/chat/chat.d.ts.map b/backend/node_modules/openai/resources/chat/chat.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..c8e3d7cfe58e6d1f726d02ec9298bc452887666d --- /dev/null +++ b/backend/node_modules/openai/resources/chat/chat.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"chat.d.ts","sourceRoot":"","sources":["../../src/resources/chat/chat.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAC9C,OAAO,KAAK,cAAc,MAAM,mCAAmC,CAAC;AAEpE,qBAAa,IAAK,SAAQ,WAAW;IACnC,WAAW,EAAE,cAAc,CAAC,WAAW,CAAgD;CACxF;AAED,yBAAiB,IAAI,CAAC;IACpB,MAAM,QAAQ,WAAW,GAAG,cAAc,CAAC,WAAW,CAAC;IACvD,MAAM,QAAQ,cAAc,GAAG,cAAc,CAAC,cAAc,CAAC;IAC7D,MAAM,QAAQ,mCAAmC,GAAG,cAAc,CAAC,mCAAmC,CAAC;IACvG,MAAM,QAAQ,mBAAmB,GAAG,cAAc,CAAC,mBAAmB,CAAC;IACvE,MAAM,QAAQ,yBAAyB,GAAG,cAAc,CAAC,yBAAyB,CAAC;IACnF,MAAM,QAAQ,8BAA8B,GAAG,cAAc,CAAC,8BAA8B,CAAC;IAC7F,MAAM,QAAQ,6BAA6B,GAAG,cAAc,CAAC,6BAA6B,CAAC;IAC3F,MAAM,QAAQ,gCAAgC,GAAG,cAAc,CAAC,gCAAgC,C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openai/resources/chat/chat.js new file mode 100644 index 0000000000000000000000000000000000000000..6480b4bf41a63a7d52f8f84f697078ee1e4bf026 --- /dev/null +++ b/backend/node_modules/openai/resources/chat/chat.js @@ -0,0 +1,40 @@ +"use strict"; +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Chat = void 0; +const resource_1 = require("openai/resource"); +const CompletionsAPI = __importStar(require("openai/resources/chat/completions")); +class Chat extends resource_1.APIResource { + constructor() { + super(...arguments); + this.completions = new CompletionsAPI.Completions(this._client); + } +} +exports.Chat = Chat; +(function (Chat) { + Chat.Completions = CompletionsAPI.Completions; +})(Chat = exports.Chat || (exports.Chat = {})); +//# sourceMappingURL=chat.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/chat/chat.js.map b/backend/node_modules/openai/resources/chat/chat.js.map new file mode 100644 index 0000000000000000000000000000000000000000..06d181a3060d09cdbf5b79135d2ca3f16599d6da --- /dev/null +++ b/backend/node_modules/openai/resources/chat/chat.js.map @@ -0,0 +1 @@ +{"version":3,"file":"chat.js","sourceRoot":"","sources":["../../src/resources/chat/chat.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;;;;;;;;;;;;;;;;;;;;;;;;AAEtF,8CAA8C;AAC9C,kFAAoE;AAEpE,MAAa,IAAK,SAAQ,sBAAW;IAArC;;QACE,gBAAW,GAA+B,IAAI,cAAc,CAAC,WAAW,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IACzF,CAAC;CAAA;AAFD,oBAEC;AAED,WAAiB,IAAI;IACL,gBAAW,GAAG,cAAc,CAAC,WAAW,CAAC;AA8BzD,CAAC,EA/BgB,IAAI,GAAJ,YAAI,KAAJ,YAAI,QA+BpB"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/chat/chat.mjs b/backend/node_modules/openai/resources/chat/chat.mjs new file mode 100644 index 0000000000000000000000000000000000000000..b6e9a31cfe6ab8ef308ee2cee9184fae080d661f --- /dev/null +++ b/backend/node_modules/openai/resources/chat/chat.mjs @@ -0,0 +1,13 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +import { APIResource } from 'openai/resource'; +import * as CompletionsAPI from 'openai/resources/chat/completions'; +export class Chat extends APIResource { + constructor() { + super(...arguments); + this.completions = new CompletionsAPI.Completions(this._client); + } +} +(function (Chat) { + Chat.Completions = CompletionsAPI.Completions; +})(Chat || (Chat = {})); +//# sourceMappingURL=chat.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/chat/chat.mjs.map b/backend/node_modules/openai/resources/chat/chat.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..74b84438d2fb92054154e63bde99247888275d62 --- /dev/null +++ b/backend/node_modules/openai/resources/chat/chat.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"chat.mjs","sourceRoot":"","sources":["../../src/resources/chat/chat.ts"],"names":[],"mappings":"AAAA,sFAAsF;OAE/E,EAAE,WAAW,EAAE,MAAM,iBAAiB;OACtC,KAAK,cAAc,MAAM,mCAAmC;AAEnE,MAAM,OAAO,IAAK,SAAQ,WAAW;IAArC;;QACE,gBAAW,GAA+B,IAAI,cAAc,CAAC,WAAW,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IACzF,CAAC;CAAA;AAED,WAAiB,IAAI;IACL,gBAAW,GAAG,cAAc,CAAC,WAAW,CAAC;AA8BzD,CAAC,EA/BgB,IAAI,KAAJ,IAAI,QA+BpB"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/chat/completions.d.ts b/backend/node_modules/openai/resources/chat/completions.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..65239c83d859055929e971502c4cbe6e2941637a --- /dev/null +++ b/backend/node_modules/openai/resources/chat/completions.d.ts @@ -0,0 +1,819 @@ +import * as Core from 'openai/core'; +import { APIPromise } from 'openai/core'; +import { APIResource } from 'openai/resource'; +import * as ChatCompletionsAPI from 'openai/resources/chat/completions'; +import * as CompletionsAPI from 'openai/resources/completions'; +import * as Shared from 'openai/resources/shared'; +import { Stream } from 'openai/streaming'; +export declare class Completions extends APIResource { + /** + * Creates a model response for the given chat conversation. + */ + create(body: ChatCompletionCreateParamsNonStreaming, options?: Core.RequestOptions): APIPromise; + create(body: ChatCompletionCreateParamsStreaming, options?: Core.RequestOptions): APIPromise>; + create(body: ChatCompletionCreateParamsBase, options?: Core.RequestOptions): APIPromise | ChatCompletion>; +} +/** + * Represents a chat completion response returned by model, based on the provided + * input. + */ +export interface ChatCompletion { + /** + * A unique identifier for the chat completion. + */ + id: string; + /** + * A list of chat completion choices. Can be more than one if `n` is greater + * than 1. + */ + choices: Array; + /** + * The Unix timestamp (in seconds) of when the chat completion was created. + */ + created: number; + /** + * The model used for the chat completion. + */ + model: string; + /** + * The object type, which is always `chat.completion`. + */ + object: 'chat.completion'; + /** + * This fingerprint represents the backend configuration that the model runs with. + * + * Can be used in conjunction with the `seed` request parameter to understand when + * backend changes have been made that might impact determinism. + */ + system_fingerprint?: string; + /** + * Usage statistics for the completion request. + */ + usage?: CompletionsAPI.CompletionUsage; +} +export declare namespace ChatCompletion { + interface Choice { + /** + * The reason the model stopped generating tokens. This will be `stop` if the model + * hit a natural stop point or a provided stop sequence, `length` if the maximum + * number of tokens specified in the request was reached, `content_filter` if + * content was omitted due to a flag from our content filters, `tool_calls` if the + * model called a tool, or `function_call` (deprecated) if the model called a + * function. + */ + finish_reason: 'stop' | 'length' | 'tool_calls' | 'content_filter' | 'function_call'; + /** + * The index of the choice in the list of choices. + */ + index: number; + /** + * Log probability information for the choice. + */ + logprobs: Choice.Logprobs | null; + /** + * A chat completion message generated by the model. + */ + message: ChatCompletionsAPI.ChatCompletionMessage; + } + namespace Choice { + /** + * Log probability information for the choice. + */ + interface Logprobs { + /** + * A list of message content tokens with log probability information. + */ + content: Array | null; + } + } +} +export interface ChatCompletionAssistantMessageParam { + /** + * The role of the messages author, in this case `assistant`. + */ + role: 'assistant'; + /** + * The contents of the assistant message. Required unless `tool_calls` or + * `function_call` is specified. + */ + content?: string | null; + /** + * @deprecated: Deprecated and replaced by `tool_calls`. The name and arguments of + * a function that should be called, as generated by the model. + */ + function_call?: ChatCompletionAssistantMessageParam.FunctionCall; + /** + * An optional name for the participant. Provides the model information to + * differentiate between participants of the same role. + */ + name?: string; + /** + * The tool calls generated by the model, such as function calls. + */ + tool_calls?: Array; +} +export declare namespace ChatCompletionAssistantMessageParam { + /** + * @deprecated: Deprecated and replaced by `tool_calls`. The name and arguments of + * a function that should be called, as generated by the model. + */ + interface FunctionCall { + /** + * The arguments to call the function with, as generated by the model in JSON + * format. Note that the model does not always generate valid JSON, and may + * hallucinate parameters not defined by your function schema. Validate the + * arguments in your code before calling your function. + */ + arguments: string; + /** + * The name of the function to call. + */ + name: string; + } +} +/** + * Represents a streamed chunk of a chat completion response returned by model, + * based on the provided input. + */ +export interface ChatCompletionChunk { + /** + * A unique identifier for the chat completion. Each chunk has the same ID. + */ + id: string; + /** + * A list of chat completion choices. Can be more than one if `n` is greater + * than 1. + */ + choices: Array; + /** + * The Unix timestamp (in seconds) of when the chat completion was created. Each + * chunk has the same timestamp. + */ + created: number; + /** + * The model to generate the completion. + */ + model: string; + /** + * The object type, which is always `chat.completion.chunk`. + */ + object: 'chat.completion.chunk'; + /** + * This fingerprint represents the backend configuration that the model runs with. + * Can be used in conjunction with the `seed` request parameter to understand when + * backend changes have been made that might impact determinism. + */ + system_fingerprint?: string; +} +export declare namespace ChatCompletionChunk { + interface Choice { + /** + * A chat completion delta generated by streamed model responses. + */ + delta: Choice.Delta; + /** + * The reason the model stopped generating tokens. This will be `stop` if the model + * hit a natural stop point or a provided stop sequence, `length` if the maximum + * number of tokens specified in the request was reached, `content_filter` if + * content was omitted due to a flag from our content filters, `tool_calls` if the + * model called a tool, or `function_call` (deprecated) if the model called a + * function. + */ + finish_reason: 'stop' | 'length' | 'tool_calls' | 'content_filter' | 'function_call' | null; + /** + * The index of the choice in the list of choices. + */ + index: number; + /** + * Log probability information for the choice. + */ + logprobs?: Choice.Logprobs | null; + } + namespace Choice { + /** + * A chat completion delta generated by streamed model responses. + */ + interface Delta { + /** + * The contents of the chunk message. + */ + content?: string | null; + /** + * @deprecated: Deprecated and replaced by `tool_calls`. The name and arguments of + * a function that should be called, as generated by the model. + */ + function_call?: Delta.FunctionCall; + /** + * The role of the author of this message. + */ + role?: 'system' | 'user' | 'assistant' | 'tool'; + tool_calls?: Array; + } + namespace Delta { + /** + * @deprecated: Deprecated and replaced by `tool_calls`. The name and arguments of + * a function that should be called, as generated by the model. + */ + interface FunctionCall { + /** + * The arguments to call the function with, as generated by the model in JSON + * format. Note that the model does not always generate valid JSON, and may + * hallucinate parameters not defined by your function schema. Validate the + * arguments in your code before calling your function. + */ + arguments?: string; + /** + * The name of the function to call. + */ + name?: string; + } + interface ToolCall { + index: number; + /** + * The ID of the tool call. + */ + id?: string; + function?: ToolCall.Function; + /** + * The type of the tool. Currently, only `function` is supported. + */ + type?: 'function'; + } + namespace ToolCall { + interface Function { + /** + * The arguments to call the function with, as generated by the model in JSON + * format. Note that the model does not always generate valid JSON, and may + * hallucinate parameters not defined by your function schema. Validate the + * arguments in your code before calling your function. + */ + arguments?: string; + /** + * The name of the function to call. + */ + name?: string; + } + } + } + /** + * Log probability information for the choice. + */ + interface Logprobs { + /** + * A list of message content tokens with log probability information. + */ + content: Array | null; + } + } +} +export type ChatCompletionContentPart = ChatCompletionContentPartText | ChatCompletionContentPartImage; +export interface ChatCompletionContentPartImage { + image_url: ChatCompletionContentPartImage.ImageURL; + /** + * The type of the content part. + */ + type: 'image_url'; +} +export declare namespace ChatCompletionContentPartImage { + interface ImageURL { + /** + * Either a URL of the image or the base64 encoded image data. + */ + url: string; + /** + * Specifies the detail level of the image. Learn more in the + * [Vision guide](https://platform.openai.com/docs/guides/vision/low-or-high-fidelity-image-understanding). + */ + detail?: 'auto' | 'low' | 'high'; + } +} +export interface ChatCompletionContentPartText { + /** + * The text content. + */ + text: string; + /** + * The type of the content part. + */ + type: 'text'; +} +/** + * Specifying a particular function via `{"name": "my_function"}` forces the model + * to call that function. + */ +export interface ChatCompletionFunctionCallOption { + /** + * The name of the function to call. + */ + name: string; +} +/** + * @deprecated + */ +export interface ChatCompletionFunctionMessageParam { + /** + * The contents of the function message. + */ + content: string | null; + /** + * The name of the function to call. + */ + name: string; + /** + * The role of the messages author, in this case `function`. + */ + role: 'function'; +} +/** + * A chat completion message generated by the model. + */ +export interface ChatCompletionMessage { + /** + * The contents of the message. + */ + content: string | null; + /** + * The role of the author of this message. + */ + role: 'assistant'; + /** + * @deprecated: Deprecated and replaced by `tool_calls`. The name and arguments of + * a function that should be called, as generated by the model. + */ + function_call?: ChatCompletionMessage.FunctionCall; + /** + * The tool calls generated by the model, such as function calls. + */ + tool_calls?: Array; +} +export declare namespace ChatCompletionMessage { + /** + * @deprecated: Deprecated and replaced by `tool_calls`. The name and arguments of + * a function that should be called, as generated by the model. + */ + interface FunctionCall { + /** + * The arguments to call the function with, as generated by the model in JSON + * format. Note that the model does not always generate valid JSON, and may + * hallucinate parameters not defined by your function schema. Validate the + * arguments in your code before calling your function. + */ + arguments: string; + /** + * The name of the function to call. + */ + name: string; + } +} +export type ChatCompletionMessageParam = ChatCompletionSystemMessageParam | ChatCompletionUserMessageParam | ChatCompletionAssistantMessageParam | ChatCompletionToolMessageParam | ChatCompletionFunctionMessageParam; +export interface ChatCompletionMessageToolCall { + /** + * The ID of the tool call. + */ + id: string; + /** + * The function that the model called. + */ + function: ChatCompletionMessageToolCall.Function; + /** + * The type of the tool. Currently, only `function` is supported. + */ + type: 'function'; +} +export declare namespace ChatCompletionMessageToolCall { + /** + * The function that the model called. + */ + interface Function { + /** + * The arguments to call the function with, as generated by the model in JSON + * format. Note that the model does not always generate valid JSON, and may + * hallucinate parameters not defined by your function schema. Validate the + * arguments in your code before calling your function. + */ + arguments: string; + /** + * The name of the function to call. + */ + name: string; + } +} +/** + * Specifies a tool the model should use. Use to force the model to call a specific + * function. + */ +export interface ChatCompletionNamedToolChoice { + function: ChatCompletionNamedToolChoice.Function; + /** + * The type of the tool. Currently, only `function` is supported. + */ + type: 'function'; +} +export declare namespace ChatCompletionNamedToolChoice { + interface Function { + /** + * The name of the function to call. + */ + name: string; + } +} +/** + * The role of the author of a message + */ +export type ChatCompletionRole = 'system' | 'user' | 'assistant' | 'tool' | 'function'; +export interface ChatCompletionSystemMessageParam { + /** + * The contents of the system message. + */ + content: string; + /** + * The role of the messages author, in this case `system`. + */ + role: 'system'; + /** + * An optional name for the participant. Provides the model information to + * differentiate between participants of the same role. + */ + name?: string; +} +export interface ChatCompletionTokenLogprob { + /** + * The token. + */ + token: string; + /** + * A list of integers representing the UTF-8 bytes representation of the token. + * Useful in instances where characters are represented by multiple tokens and + * their byte representations must be combined to generate the correct text + * representation. Can be `null` if there is no bytes representation for the token. + */ + bytes: Array | null; + /** + * The log probability of this token, if it is within the top 20 most likely + * tokens. Otherwise, the value `-9999.0` is used to signify that the token is very + * unlikely. + */ + logprob: number; + /** + * List of the most likely tokens and their log probability, at this token + * position. In rare cases, there may be fewer than the number of requested + * `top_logprobs` returned. + */ + top_logprobs: Array; +} +export declare namespace ChatCompletionTokenLogprob { + interface TopLogprob { + /** + * The token. + */ + token: string; + /** + * A list of integers representing the UTF-8 bytes representation of the token. + * Useful in instances where characters are represented by multiple tokens and + * their byte representations must be combined to generate the correct text + * representation. Can be `null` if there is no bytes representation for the token. + */ + bytes: Array | null; + /** + * The log probability of this token, if it is within the top 20 most likely + * tokens. Otherwise, the value `-9999.0` is used to signify that the token is very + * unlikely. + */ + logprob: number; + } +} +export interface ChatCompletionTool { + function: Shared.FunctionDefinition; + /** + * The type of the tool. Currently, only `function` is supported. + */ + type: 'function'; +} +/** + * Controls which (if any) function is called by the model. `none` means the model + * will not call a function and instead generates a message. `auto` means the model + * can pick between generating a message or calling a function. Specifying a + * particular function via + * `{"type": "function", "function": {"name": "my_function"}}` forces the model to + * call that function. + * + * `none` is the default when no functions are present. `auto` is the default if + * functions are present. + */ +export type ChatCompletionToolChoiceOption = 'none' | 'auto' | ChatCompletionNamedToolChoice; +export interface ChatCompletionToolMessageParam { + /** + * The contents of the tool message. + */ + content: string; + /** + * The role of the messages author, in this case `tool`. + */ + role: 'tool'; + /** + * Tool call that this message is responding to. + */ + tool_call_id: string; +} +export interface ChatCompletionUserMessageParam { + /** + * The contents of the user message. + */ + content: string | Array; + /** + * The role of the messages author, in this case `user`. + */ + role: 'user'; + /** + * An optional name for the participant. Provides the model information to + * differentiate between participants of the same role. + */ + name?: string; +} +/** + * @deprecated ChatCompletionMessageParam should be used instead + */ +export type CreateChatCompletionRequestMessage = ChatCompletionMessageParam; +export type ChatCompletionCreateParams = ChatCompletionCreateParamsNonStreaming | ChatCompletionCreateParamsStreaming; +export interface ChatCompletionCreateParamsBase { + /** + * A list of messages comprising the conversation so far. + * [Example Python code](https://cookbook.openai.com/examples/how_to_format_inputs_to_chatgpt_models). + */ + messages: Array; + /** + * ID of the model to use. See the + * [model endpoint compatibility](https://platform.openai.com/docs/models/model-endpoint-compatibility) + * table for details on which models work with the Chat API. + */ + model: (string & {}) | 'gpt-4-turbo' | 'gpt-4-turbo-2024-04-09' | 'gpt-4-0125-preview' | 'gpt-4-turbo-preview' | 'gpt-4-1106-preview' | 'gpt-4-vision-preview' | 'gpt-4' | 'gpt-4-0314' | 'gpt-4-0613' | 'gpt-4-32k' | 'gpt-4-32k-0314' | 'gpt-4-32k-0613' | 'gpt-3.5-turbo' | 'gpt-3.5-turbo-16k' | 'gpt-3.5-turbo-0301' | 'gpt-3.5-turbo-0613' | 'gpt-3.5-turbo-1106' | 'gpt-3.5-turbo-0125' | 'gpt-3.5-turbo-16k-0613'; + /** + * Number between -2.0 and 2.0. Positive values penalize new tokens based on their + * existing frequency in the text so far, decreasing the model's likelihood to + * repeat the same line verbatim. + * + * [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) + */ + frequency_penalty?: number | null; + /** + * Deprecated in favor of `tool_choice`. + * + * Controls which (if any) function is called by the model. `none` means the model + * will not call a function and instead generates a message. `auto` means the model + * can pick between generating a message or calling a function. Specifying a + * particular function via `{"name": "my_function"}` forces the model to call that + * function. + * + * `none` is the default when no functions are present. `auto` is the default if + * functions are present. + */ + function_call?: 'none' | 'auto' | ChatCompletionFunctionCallOption; + /** + * Deprecated in favor of `tools`. + * + * A list of functions the model may generate JSON inputs for. + */ + functions?: Array; + /** + * Modify the likelihood of specified tokens appearing in the completion. + * + * Accepts a JSON object that maps tokens (specified by their token ID in the + * tokenizer) to an associated bias value from -100 to 100. Mathematically, the + * bias is added to the logits generated by the model prior to sampling. The exact + * effect will vary per model, but values between -1 and 1 should decrease or + * increase likelihood of selection; values like -100 or 100 should result in a ban + * or exclusive selection of the relevant token. + */ + logit_bias?: Record | null; + /** + * Whether to return log probabilities of the output tokens or not. If true, + * returns the log probabilities of each output token returned in the `content` of + * `message`. + */ + logprobs?: boolean | null; + /** + * The maximum number of [tokens](/tokenizer) that can be generated in the chat + * completion. + * + * The total length of input tokens and generated tokens is limited by the model's + * context length. + * [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) + * for counting tokens. + */ + max_tokens?: number | null; + /** + * How many chat completion choices to generate for each input message. Note that + * you will be charged based on the number of generated tokens across all of the + * choices. Keep `n` as `1` to minimize costs. + */ + n?: number | null; + /** + * Number between -2.0 and 2.0. Positive values penalize new tokens based on + * whether they appear in the text so far, increasing the model's likelihood to + * talk about new topics. + * + * [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) + */ + presence_penalty?: number | null; + /** + * An object specifying the format that the model must output. Compatible with + * [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and + * all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + * + * Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + * message the model generates is valid JSON. + * + * **Important:** when using JSON mode, you **must** also instruct the model to + * produce JSON yourself via a system or user message. Without this, the model may + * generate an unending stream of whitespace until the generation reaches the token + * limit, resulting in a long-running and seemingly "stuck" request. Also note that + * the message content may be partially cut off if `finish_reason="length"`, which + * indicates the generation exceeded `max_tokens` or the conversation exceeded the + * max context length. + */ + response_format?: ChatCompletionCreateParams.ResponseFormat; + /** + * This feature is in Beta. If specified, our system will make a best effort to + * sample deterministically, such that repeated requests with the same `seed` and + * parameters should return the same result. Determinism is not guaranteed, and you + * should refer to the `system_fingerprint` response parameter to monitor changes + * in the backend. + */ + seed?: number | null; + /** + * Up to 4 sequences where the API will stop generating further tokens. + */ + stop?: string | null | Array; + /** + * If set, partial message deltas will be sent, like in ChatGPT. Tokens will be + * sent as data-only + * [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) + * as they become available, with the stream terminated by a `data: [DONE]` + * message. + * [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions). + */ + stream?: boolean | null; + /** + * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + * make the output more random, while lower values like 0.2 will make it more + * focused and deterministic. + * + * We generally recommend altering this or `top_p` but not both. + */ + temperature?: number | null; + /** + * Controls which (if any) function is called by the model. `none` means the model + * will not call a function and instead generates a message. `auto` means the model + * can pick between generating a message or calling a function. Specifying a + * particular function via + * `{"type": "function", "function": {"name": "my_function"}}` forces the model to + * call that function. + * + * `none` is the default when no functions are present. `auto` is the default if + * functions are present. + */ + tool_choice?: ChatCompletionToolChoiceOption; + /** + * A list of tools the model may call. Currently, only functions are supported as a + * tool. Use this to provide a list of functions the model may generate JSON inputs + * for. A max of 128 functions are supported. + */ + tools?: Array; + /** + * An integer between 0 and 20 specifying the number of most likely tokens to + * return at each token position, each with an associated log probability. + * `logprobs` must be set to `true` if this parameter is used. + */ + top_logprobs?: number | null; + /** + * An alternative to sampling with temperature, called nucleus sampling, where the + * model considers the results of the tokens with top_p probability mass. So 0.1 + * means only the tokens comprising the top 10% probability mass are considered. + * + * We generally recommend altering this or `temperature` but not both. + */ + top_p?: number | null; + /** + * A unique identifier representing your end-user, which can help OpenAI to monitor + * and detect abuse. + * [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + */ + user?: string; +} +export declare namespace ChatCompletionCreateParams { + /** + * @deprecated + */ + interface Function { + /** + * The name of the function to be called. Must be a-z, A-Z, 0-9, or contain + * underscores and dashes, with a maximum length of 64. + */ + name: string; + /** + * A description of what the function does, used by the model to choose when and + * how to call the function. + */ + description?: string; + /** + * The parameters the functions accepts, described as a JSON Schema object. See the + * [guide](https://platform.openai.com/docs/guides/text-generation/function-calling) + * for examples, and the + * [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for + * documentation about the format. + * + * Omitting `parameters` defines a function with an empty parameter list. + */ + parameters?: Shared.FunctionParameters; + } + /** + * An object specifying the format that the model must output. Compatible with + * [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and + * all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + * + * Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + * message the model generates is valid JSON. + * + * **Important:** when using JSON mode, you **must** also instruct the model to + * produce JSON yourself via a system or user message. Without this, the model may + * generate an unending stream of whitespace until the generation reaches the token + * limit, resulting in a long-running and seemingly "stuck" request. Also note that + * the message content may be partially cut off if `finish_reason="length"`, which + * indicates the generation exceeded `max_tokens` or the conversation exceeded the + * max context length. + */ + interface ResponseFormat { + /** + * Must be one of `text` or `json_object`. + */ + type?: 'text' | 'json_object'; + } + type ChatCompletionCreateParamsNonStreaming = ChatCompletionsAPI.ChatCompletionCreateParamsNonStreaming; + type ChatCompletionCreateParamsStreaming = ChatCompletionsAPI.ChatCompletionCreateParamsStreaming; +} +/** + * @deprecated Use ChatCompletionCreateParams instead + */ +export type CompletionCreateParams = ChatCompletionCreateParams; +export interface ChatCompletionCreateParamsNonStreaming extends ChatCompletionCreateParamsBase { + /** + * If set, partial message deltas will be sent, like in ChatGPT. Tokens will be + * sent as data-only + * [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) + * as they become available, with the stream terminated by a `data: [DONE]` + * message. + * [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions). + */ + stream?: false | null; +} +/** + * @deprecated Use ChatCompletionCreateParamsNonStreaming instead + */ +export type CompletionCreateParamsNonStreaming = ChatCompletionCreateParamsNonStreaming; +export interface ChatCompletionCreateParamsStreaming extends ChatCompletionCreateParamsBase { + /** + * If set, partial message deltas will be sent, like in ChatGPT. Tokens will be + * sent as data-only + * [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) + * as they become available, with the stream terminated by a `data: [DONE]` + * message. + * [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions). + */ + stream: true; +} +/** + * @deprecated Use ChatCompletionCreateParamsStreaming instead + */ +export type CompletionCreateParamsStreaming = ChatCompletionCreateParamsStreaming; +export declare namespace Completions { + export import ChatCompletion = ChatCompletionsAPI.ChatCompletion; + export import ChatCompletionAssistantMessageParam = ChatCompletionsAPI.ChatCompletionAssistantMessageParam; + export import ChatCompletionChunk = ChatCompletionsAPI.ChatCompletionChunk; + export import ChatCompletionContentPart = ChatCompletionsAPI.ChatCompletionContentPart; + export import ChatCompletionContentPartImage = ChatCompletionsAPI.ChatCompletionContentPartImage; + export import ChatCompletionContentPartText = ChatCompletionsAPI.ChatCompletionContentPartText; + export import ChatCompletionFunctionCallOption = ChatCompletionsAPI.ChatCompletionFunctionCallOption; + export import ChatCompletionFunctionMessageParam = ChatCompletionsAPI.ChatCompletionFunctionMessageParam; + export import ChatCompletionMessage = ChatCompletionsAPI.ChatCompletionMessage; + export import ChatCompletionMessageParam = ChatCompletionsAPI.ChatCompletionMessageParam; + export import ChatCompletionMessageToolCall = ChatCompletionsAPI.ChatCompletionMessageToolCall; + export import ChatCompletionNamedToolChoice = ChatCompletionsAPI.ChatCompletionNamedToolChoice; + export import ChatCompletionRole = ChatCompletionsAPI.ChatCompletionRole; + export import ChatCompletionSystemMessageParam = ChatCompletionsAPI.ChatCompletionSystemMessageParam; + export import ChatCompletionTokenLogprob = ChatCompletionsAPI.ChatCompletionTokenLogprob; + export import ChatCompletionTool = ChatCompletionsAPI.ChatCompletionTool; + export import ChatCompletionToolChoiceOption = ChatCompletionsAPI.ChatCompletionToolChoiceOption; + export import ChatCompletionToolMessageParam = ChatCompletionsAPI.ChatCompletionToolMessageParam; + export import ChatCompletionUserMessageParam = ChatCompletionsAPI.ChatCompletionUserMessageParam; + /** + * @deprecated ChatCompletionMessageParam should be used instead + */ + export import CreateChatCompletionRequestMessage = ChatCompletionsAPI.CreateChatCompletionRequestMessage; + export import ChatCompletionCreateParams = ChatCompletionsAPI.ChatCompletionCreateParams; + export import CompletionCreateParams = ChatCompletionsAPI.CompletionCreateParams; + export import ChatCompletionCreateParamsNonStreaming = ChatCompletionsAPI.ChatCompletionCreateParamsNonStreaming; + export import CompletionCreateParamsNonStreaming = ChatCompletionsAPI.CompletionCreateParamsNonStreaming; + export import ChatCompletionCreateParamsStreaming = ChatCompletionsAPI.ChatCompletionCreateParamsStreaming; + export import CompletionCreateParamsStreaming = ChatCompletionsAPI.CompletionCreateParamsStreaming; +} +//# sourceMappingURL=completions.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/chat/completions.d.ts.map b/backend/node_modules/openai/resources/chat/completions.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..1598bd02469b3b52b62835f6142ad65133b10cd1 --- /dev/null +++ b/backend/node_modules/openai/resources/chat/completions.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"completions.d.ts","sourceRoot":"","sources":["../../src/resources/chat/completions.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,IAAI,MAAM,aAAa,CAAC;AACpC,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAC9C,OAAO,KAAK,kBAAkB,MAAM,mCAAmC,CAAC;AACxE,OAAO,KAAK,cAAc,MAAM,8BAA8B,CAAC;AAC/D,OAAO,KAAK,MAAM,MAAM,yBAAyB,CAAC;AAClD,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAE1C,qBAAa,WAAY,SAAQ,WAAW;IAC1C;;OAEG;IACH,MAAM,CACJ,IAAI,EAAE,sCAAsC,EAC5C,OAAO,CAAC,EAAE,IAAI,CAAC,cAAc,GAC5B,UAAU,CAAC,cAAc,CAAC;IAC7B,MAAM,CACJ,IAAI,EAAE,mCAAmC,EACzC,OAAO,CAAC,EAAE,IAAI,CAAC,cAAc,GAC5B,UAAU,CAAC,MAAM,CAAC,mBAAmB,CAAC,CAAC;IAC1C,MAAM,CACJ,IAAI,EAAE,8BAA8B,EACpC,OAAO,CAAC,EAAE,IAAI,CAAC,cAAc,GAC5B,UAAU,CAAC,MAAM,CAAC,mBAAmB,CAAC,GAAG,cAAc,CAAC;CAS5D;AAED;;;GAGG;AACH,MAAM,WAAW,cAAc;IAC7B;;OAEG;IACH,EAAE,EAAE,MAAM,CAAC;IAEX;;;O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Q,kBAAkB,GAAG,kBAAkB,CAAC,kBAAkB,CAAC;IACzE,MAAM,QAAQ,8BAA8B,GAAG,kBAAkB,CAAC,8BAA8B,CAAC;IACjG,MAAM,QAAQ,8BAA8B,GAAG,kBAAkB,CAAC,8BAA8B,CAAC;IACjG,MAAM,QAAQ,8BAA8B,GAAG,kBAAkB,CAAC,8BAA8B,CAAC;IACjG;;OAEG;IACH,MAAM,QAAQ,kCAAkC,GAAG,kBAAkB,CAAC,kCAAkC,CAAC;IACzG,MAAM,QAAQ,0BAA0B,GAAG,kBAAkB,CAAC,0BAA0B,CAAC;IACzF,MAAM,QAAQ,sBAAsB,GAAG,kBAAkB,CAAC,sBAAsB,CAAC;IACjF,MAAM,QAAQ,sCAAsC,GAAG,kBAAkB,CAAC,sCAAsC,CAAC;IACjH,MAAM,QAAQ,kCAAkC,GAAG,kBAAkB,CAAC,kCAAkC,CAAC;IACzG,MAAM,QAAQ,mCAAmC,GAAG,kBAAkB,CAAC,mCAAmC,CAAC;IAC3G,MAAM,QAAQ,+BAA+B,GAAG,kBAAkB,CAAC,+BAA+B,CAAC;CACpG"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/chat/completions.js b/backend/node_modules/openai/resources/chat/completions.js new file mode 100644 index 0000000000000000000000000000000000000000..83d1f89270bbb227e72a49f0e98f4930301e67ae --- /dev/null +++ b/backend/node_modules/openai/resources/chat/completions.js @@ -0,0 +1,14 @@ +"use strict"; +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Completions = void 0; +const resource_1 = require("openai/resource"); +class Completions extends resource_1.APIResource { + create(body, options) { + return this._client.post('/chat/completions', { body, ...options, stream: body.stream ?? false }); + } +} +exports.Completions = Completions; +(function (Completions) { +})(Completions = exports.Completions || (exports.Completions = {})); +//# sourceMappingURL=completions.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/chat/completions.js.map b/backend/node_modules/openai/resources/chat/completions.js.map new file mode 100644 index 0000000000000000000000000000000000000000..02d30b81b3c07fcf586f532640dee46fb5173863 --- /dev/null +++ b/backend/node_modules/openai/resources/chat/completions.js.map @@ -0,0 +1 @@ +{"version":3,"file":"completions.js","sourceRoot":"","sources":["../../src/resources/chat/completions.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;AAItF,8CAA8C;AAM9C,MAAa,WAAY,SAAQ,sBAAW;IAgB1C,MAAM,CACJ,IAAgC,EAChC,OAA6B;QAE7B,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,mBAAmB,EAAE,EAAE,IAAI,EAAE,GAAG,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,MAAM,IAAI,KAAK,EAAE,CAErD,CAAC;IAC9C,CAAC;CACF;AAxBD,kCAwBC;AA05BD,WAAiB,WAAW;AA8B5B,CAAC,EA9BgB,WAAW,GAAX,mBAAW,KAAX,mBAAW,QA8B3B"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/chat/completions.mjs b/backend/node_modules/openai/resources/chat/completions.mjs new file mode 100644 index 0000000000000000000000000000000000000000..177ab8092ccd2b69e0f9644114196270387c085b --- /dev/null +++ b/backend/node_modules/openai/resources/chat/completions.mjs @@ -0,0 +1,10 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +import { APIResource } from 'openai/resource'; +export class Completions extends APIResource { + create(body, options) { + return this._client.post('/chat/completions', { body, ...options, stream: body.stream ?? false }); + } +} +(function (Completions) { +})(Completions || (Completions = {})); +//# sourceMappingURL=completions.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/chat/completions.mjs.map b/backend/node_modules/openai/resources/chat/completions.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..7c8743d7845206e3ef7037a1710566c9466f4f6c --- /dev/null +++ b/backend/node_modules/openai/resources/chat/completions.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"completions.mjs","sourceRoot":"","sources":["../../src/resources/chat/completions.ts"],"names":[],"mappings":"AAAA,sFAAsF;OAI/E,EAAE,WAAW,EAAE,MAAM,iBAAiB;AAM7C,MAAM,OAAO,WAAY,SAAQ,WAAW;IAgB1C,MAAM,CACJ,IAAgC,EAChC,OAA6B;QAE7B,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,mBAAmB,EAAE,EAAE,IAAI,EAAE,GAAG,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,MAAM,IAAI,KAAK,EAAE,CAErD,CAAC;IAC9C,CAAC;CACF;AA05BD,WAAiB,WAAW;AA8B5B,CAAC,EA9BgB,WAAW,KAAX,WAAW,QA8B3B"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/chat/index.d.ts b/backend/node_modules/openai/resources/chat/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..95b6ab1138fcec481a6e119d202cd2d51037a728 --- /dev/null +++ b/backend/node_modules/openai/resources/chat/index.d.ts @@ -0,0 +1,3 @@ +export { Chat } from "./chat.js"; +export { ChatCompletion, ChatCompletionAssistantMessageParam, ChatCompletionChunk, ChatCompletionContentPart, ChatCompletionContentPartImage, ChatCompletionContentPartText, ChatCompletionFunctionCallOption, ChatCompletionFunctionMessageParam, ChatCompletionMessage, ChatCompletionMessageParam, ChatCompletionMessageToolCall, ChatCompletionNamedToolChoice, ChatCompletionRole, ChatCompletionSystemMessageParam, ChatCompletionTokenLogprob, ChatCompletionTool, ChatCompletionToolChoiceOption, ChatCompletionToolMessageParam, ChatCompletionUserMessageParam, CreateChatCompletionRequestMessage, ChatCompletionCreateParams, CompletionCreateParams, ChatCompletionCreateParamsNonStreaming, CompletionCreateParamsNonStreaming, ChatCompletionCreateParamsStreaming, CompletionCreateParamsStreaming, Completions, } from "./completions.js"; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/chat/index.d.ts.map b/backend/node_modules/openai/resources/chat/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..7e04fb4753e22f676b260540835ace19d6e75a76 --- /dev/null +++ b/backend/node_modules/openai/resources/chat/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/resources/chat/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,IAAI,EAAE,MAAM,QAAQ,CAAC;AAC9B,OAAO,EACL,cAAc,EACd,mCAAmC,EACnC,mBAAmB,EACnB,yBAAyB,EACzB,8BAA8B,EAC9B,6BAA6B,EAC7B,gCAAgC,EAChC,kCAAkC,EAClC,qBAAqB,EACrB,0BAA0B,EAC1B,6BAA6B,EAC7B,6BAA6B,EAC7B,kBAAkB,EAClB,gCAAgC,EAChC,0BAA0B,EAC1B,kBAAkB,EAClB,8BAA8B,EAC9B,8BAA8B,EAC9B,8BAA8B,EAC9B,kCAAkC,EAClC,0BAA0B,EAC1B,sBAAsB,EACtB,sCAAsC,EACtC,kCAAkC,EAClC,mCAAmC,EACnC,+BAA+B,EAC/B,WAAW,GACZ,MAAM,eAAe,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/chat/index.js b/backend/node_modules/openai/resources/chat/index.js new file mode 100644 index 0000000000000000000000000000000000000000..53c3d1685f0e49779252b74b3ca16e0f203ac3e6 --- /dev/null +++ b/backend/node_modules/openai/resources/chat/index.js @@ -0,0 +1,9 @@ +"use strict"; +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Completions = exports.Chat = void 0; +var chat_1 = require("./chat.js"); +Object.defineProperty(exports, "Chat", { enumerable: true, get: function () { return chat_1.Chat; } }); +var completions_1 = require("./completions.js"); +Object.defineProperty(exports, "Completions", { enumerable: true, get: function () { return completions_1.Completions; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/chat/index.js.map b/backend/node_modules/openai/resources/chat/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..6b1c489739e3a31caca21616b8e1a135955a389d --- /dev/null +++ b/backend/node_modules/openai/resources/chat/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/resources/chat/index.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;AAEtF,kCAA8B;AAArB,4FAAA,IAAI,OAAA;AACb,gDA4BuB;AADrB,0GAAA,WAAW,OAAA"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/chat/index.mjs b/backend/node_modules/openai/resources/chat/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..f03ef42f859adaee8a23c4c4563e280b0299eda7 --- /dev/null +++ b/backend/node_modules/openai/resources/chat/index.mjs @@ -0,0 +1,4 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +export { Chat } from "./chat.mjs"; +export { Completions, } from "./completions.mjs"; +//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/chat/index.mjs.map b/backend/node_modules/openai/resources/chat/index.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..3338ac54e72a399c35f6ffa9f3563a9c448d4685 --- /dev/null +++ b/backend/node_modules/openai/resources/chat/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"index.mjs","sourceRoot":"","sources":["../../src/resources/chat/index.ts"],"names":[],"mappings":"AAAA,sFAAsF;OAE/E,EAAE,IAAI,EAAE;OACR,EA2BL,WAAW,GACZ"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/completions.d.ts b/backend/node_modules/openai/resources/completions.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1e3a5936df8d16c17fe92a4bc1b0bab44dac64d4 --- /dev/null +++ b/backend/node_modules/openai/resources/completions.d.ts @@ -0,0 +1,267 @@ +import * as Core from 'openai/core'; +import { APIPromise } from 'openai/core'; +import { APIResource } from 'openai/resource'; +import * as CompletionsAPI from 'openai/resources/completions'; +import { Stream } from 'openai/streaming'; +export declare class Completions extends APIResource { + /** + * Creates a completion for the provided prompt and parameters. + */ + create(body: CompletionCreateParamsNonStreaming, options?: Core.RequestOptions): APIPromise; + create(body: CompletionCreateParamsStreaming, options?: Core.RequestOptions): APIPromise>; + create(body: CompletionCreateParamsBase, options?: Core.RequestOptions): APIPromise | Completion>; +} +/** + * Represents a completion response from the API. Note: both the streamed and + * non-streamed response objects share the same shape (unlike the chat endpoint). + */ +export interface Completion { + /** + * A unique identifier for the completion. + */ + id: string; + /** + * The list of completion choices the model generated for the input prompt. + */ + choices: Array; + /** + * The Unix timestamp (in seconds) of when the completion was created. + */ + created: number; + /** + * The model used for completion. + */ + model: string; + /** + * The object type, which is always "text_completion" + */ + object: 'text_completion'; + /** + * This fingerprint represents the backend configuration that the model runs with. + * + * Can be used in conjunction with the `seed` request parameter to understand when + * backend changes have been made that might impact determinism. + */ + system_fingerprint?: string; + /** + * Usage statistics for the completion request. + */ + usage?: CompletionUsage; +} +export interface CompletionChoice { + /** + * The reason the model stopped generating tokens. This will be `stop` if the model + * hit a natural stop point or a provided stop sequence, `length` if the maximum + * number of tokens specified in the request was reached, or `content_filter` if + * content was omitted due to a flag from our content filters. + */ + finish_reason: 'stop' | 'length' | 'content_filter'; + index: number; + logprobs: CompletionChoice.Logprobs | null; + text: string; +} +export declare namespace CompletionChoice { + interface Logprobs { + text_offset?: Array; + token_logprobs?: Array; + tokens?: Array; + top_logprobs?: Array>; + } +} +/** + * Usage statistics for the completion request. + */ +export interface CompletionUsage { + /** + * Number of tokens in the generated completion. + */ + completion_tokens: number; + /** + * Number of tokens in the prompt. + */ + prompt_tokens: number; + /** + * Total number of tokens used in the request (prompt + completion). + */ + total_tokens: number; +} +export type CompletionCreateParams = CompletionCreateParamsNonStreaming | CompletionCreateParamsStreaming; +export interface CompletionCreateParamsBase { + /** + * ID of the model to use. You can use the + * [List models](https://platform.openai.com/docs/api-reference/models/list) API to + * see all of your available models, or see our + * [Model overview](https://platform.openai.com/docs/models/overview) for + * descriptions of them. + */ + model: (string & {}) | 'gpt-3.5-turbo-instruct' | 'davinci-002' | 'babbage-002'; + /** + * The prompt(s) to generate completions for, encoded as a string, array of + * strings, array of tokens, or array of token arrays. + * + * Note that <|endoftext|> is the document separator that the model sees during + * training, so if a prompt is not specified the model will generate as if from the + * beginning of a new document. + */ + prompt: string | Array | Array | Array> | null; + /** + * Generates `best_of` completions server-side and returns the "best" (the one with + * the highest log probability per token). Results cannot be streamed. + * + * When used with `n`, `best_of` controls the number of candidate completions and + * `n` specifies how many to return – `best_of` must be greater than `n`. + * + * **Note:** Because this parameter generates many completions, it can quickly + * consume your token quota. Use carefully and ensure that you have reasonable + * settings for `max_tokens` and `stop`. + */ + best_of?: number | null; + /** + * Echo back the prompt in addition to the completion + */ + echo?: boolean | null; + /** + * Number between -2.0 and 2.0. Positive values penalize new tokens based on their + * existing frequency in the text so far, decreasing the model's likelihood to + * repeat the same line verbatim. + * + * [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) + */ + frequency_penalty?: number | null; + /** + * Modify the likelihood of specified tokens appearing in the completion. + * + * Accepts a JSON object that maps tokens (specified by their token ID in the GPT + * tokenizer) to an associated bias value from -100 to 100. You can use this + * [tokenizer tool](/tokenizer?view=bpe) to convert text to token IDs. + * Mathematically, the bias is added to the logits generated by the model prior to + * sampling. The exact effect will vary per model, but values between -1 and 1 + * should decrease or increase likelihood of selection; values like -100 or 100 + * should result in a ban or exclusive selection of the relevant token. + * + * As an example, you can pass `{"50256": -100}` to prevent the <|endoftext|> token + * from being generated. + */ + logit_bias?: Record | null; + /** + * Include the log probabilities on the `logprobs` most likely output tokens, as + * well the chosen tokens. For example, if `logprobs` is 5, the API will return a + * list of the 5 most likely tokens. The API will always return the `logprob` of + * the sampled token, so there may be up to `logprobs+1` elements in the response. + * + * The maximum value for `logprobs` is 5. + */ + logprobs?: number | null; + /** + * The maximum number of [tokens](/tokenizer) that can be generated in the + * completion. + * + * The token count of your prompt plus `max_tokens` cannot exceed the model's + * context length. + * [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) + * for counting tokens. + */ + max_tokens?: number | null; + /** + * How many completions to generate for each prompt. + * + * **Note:** Because this parameter generates many completions, it can quickly + * consume your token quota. Use carefully and ensure that you have reasonable + * settings for `max_tokens` and `stop`. + */ + n?: number | null; + /** + * Number between -2.0 and 2.0. Positive values penalize new tokens based on + * whether they appear in the text so far, increasing the model's likelihood to + * talk about new topics. + * + * [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) + */ + presence_penalty?: number | null; + /** + * If specified, our system will make a best effort to sample deterministically, + * such that repeated requests with the same `seed` and parameters should return + * the same result. + * + * Determinism is not guaranteed, and you should refer to the `system_fingerprint` + * response parameter to monitor changes in the backend. + */ + seed?: number | null; + /** + * Up to 4 sequences where the API will stop generating further tokens. The + * returned text will not contain the stop sequence. + */ + stop?: string | null | Array; + /** + * Whether to stream back partial progress. If set, tokens will be sent as + * data-only + * [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) + * as they become available, with the stream terminated by a `data: [DONE]` + * message. + * [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions). + */ + stream?: boolean | null; + /** + * The suffix that comes after a completion of inserted text. + * + * This parameter is only supported for `gpt-3.5-turbo-instruct`. + */ + suffix?: string | null; + /** + * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + * make the output more random, while lower values like 0.2 will make it more + * focused and deterministic. + * + * We generally recommend altering this or `top_p` but not both. + */ + temperature?: number | null; + /** + * An alternative to sampling with temperature, called nucleus sampling, where the + * model considers the results of the tokens with top_p probability mass. So 0.1 + * means only the tokens comprising the top 10% probability mass are considered. + * + * We generally recommend altering this or `temperature` but not both. + */ + top_p?: number | null; + /** + * A unique identifier representing your end-user, which can help OpenAI to monitor + * and detect abuse. + * [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + */ + user?: string; +} +export declare namespace CompletionCreateParams { + type CompletionCreateParamsNonStreaming = CompletionsAPI.CompletionCreateParamsNonStreaming; + type CompletionCreateParamsStreaming = CompletionsAPI.CompletionCreateParamsStreaming; +} +export interface CompletionCreateParamsNonStreaming extends CompletionCreateParamsBase { + /** + * Whether to stream back partial progress. If set, tokens will be sent as + * data-only + * [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) + * as they become available, with the stream terminated by a `data: [DONE]` + * message. + * [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions). + */ + stream?: false | null; +} +export interface CompletionCreateParamsStreaming extends CompletionCreateParamsBase { + /** + * Whether to stream back partial progress. If set, tokens will be sent as + * data-only + * [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) + * as they become available, with the stream terminated by a `data: [DONE]` + * message. + * [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions). + */ + stream: true; +} +export declare namespace Completions { + export import Completion = CompletionsAPI.Completion; + export import CompletionChoice = CompletionsAPI.CompletionChoice; + export import CompletionUsage = CompletionsAPI.CompletionUsage; + export import CompletionCreateParams = CompletionsAPI.CompletionCreateParams; + export import CompletionCreateParamsNonStreaming = CompletionsAPI.CompletionCreateParamsNonStreaming; + export import CompletionCreateParamsStreaming = CompletionsAPI.CompletionCreateParamsStreaming; +} +//# sourceMappingURL=completions.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/completions.d.ts.map b/backend/node_modules/openai/resources/completions.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..46829791a9b0c509409beee095a8b33dda51abb7 --- /dev/null +++ b/backend/node_modules/openai/resources/completions.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"completions.d.ts","sourceRoot":"","sources":["../src/resources/completions.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,IAAI,MAAM,aAAa,CAAC;AACpC,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAC9C,OAAO,KAAK,cAAc,MAAM,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Q,+BAA+B,GAAG,cAAc,CAAC,+BAA+B,CAAC;CAChG"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/completions.js b/backend/node_modules/openai/resources/completions.js new file mode 100644 index 0000000000000000000000000000000000000000..8641ebee1af5134ad3146b512b9b8d8689f0e8ee --- /dev/null +++ b/backend/node_modules/openai/resources/completions.js @@ -0,0 +1,14 @@ +"use strict"; +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Completions = void 0; +const resource_1 = require("openai/resource"); +class Completions extends resource_1.APIResource { + create(body, options) { + return this._client.post('/completions', { body, ...options, stream: body.stream ?? false }); + } +} +exports.Completions = Completions; +(function (Completions) { +})(Completions = exports.Completions || (exports.Completions = {})); +//# sourceMappingURL=completions.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/completions.js.map b/backend/node_modules/openai/resources/completions.js.map new file mode 100644 index 0000000000000000000000000000000000000000..850126e47bd92ce4876fac069ac5da6c55f32245 --- /dev/null +++ b/backend/node_modules/openai/resources/completions.js.map @@ -0,0 +1 @@ +{"version":3,"file":"completions.js","sourceRoot":"","sources":["../src/resources/completions.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;AAItF,8CAA8C;AAI9C,MAAa,WAAY,SAAQ,sBAAW;IAa1C,MAAM,CACJ,IAA4B,EAC5B,OAA6B;QAE7B,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,cAAc,EAAE,EAAE,IAAI,EAAE,GAAG,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,MAAM,IAAI,KAAK,EAAE,CAEzD,CAAC;IACrC,CAAC;CACF;AArBD,kCAqBC;AA8RD,WAAiB,WAAW;AAO5B,CAAC,EAPgB,WAAW,GAAX,mBAAW,KAAX,mBAAW,QAO3B"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/completions.mjs b/backend/node_modules/openai/resources/completions.mjs new file mode 100644 index 0000000000000000000000000000000000000000..371382ed4bdbfc077afb0f6832ea3a55150152c9 --- /dev/null +++ b/backend/node_modules/openai/resources/completions.mjs @@ -0,0 +1,10 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +import { APIResource } from 'openai/resource'; +export class Completions extends APIResource { + create(body, options) { + return this._client.post('/completions', { body, ...options, stream: body.stream ?? false }); + } +} +(function (Completions) { +})(Completions || (Completions = {})); +//# sourceMappingURL=completions.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/completions.mjs.map b/backend/node_modules/openai/resources/completions.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..74b26cbdafbaf4aaf06d8a9b2e4a8db26471d2d5 --- /dev/null +++ b/backend/node_modules/openai/resources/completions.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"completions.mjs","sourceRoot":"","sources":["../src/resources/completions.ts"],"names":[],"mappings":"AAAA,sFAAsF;OAI/E,EAAE,WAAW,EAAE,MAAM,iBAAiB;AAI7C,MAAM,OAAO,WAAY,SAAQ,WAAW;IAa1C,MAAM,CACJ,IAA4B,EAC5B,OAA6B;QAE7B,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,cAAc,EAAE,EAAE,IAAI,EAAE,GAAG,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,MAAM,IAAI,KAAK,EAAE,CAEzD,CAAC;IACrC,CAAC;CACF;AA8RD,WAAiB,WAAW;AAO5B,CAAC,EAPgB,WAAW,KAAX,WAAW,QAO3B"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/embeddings.d.ts b/backend/node_modules/openai/resources/embeddings.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..94dcb7cf4cf05434cb89c521ca6c286f05a16978 --- /dev/null +++ b/backend/node_modules/openai/resources/embeddings.d.ts @@ -0,0 +1,103 @@ +import * as Core from 'openai/core'; +import { APIResource } from 'openai/resource'; +import * as EmbeddingsAPI from 'openai/resources/embeddings'; +export declare class Embeddings extends APIResource { + /** + * Creates an embedding vector representing the input text. + */ + create(body: EmbeddingCreateParams, options?: Core.RequestOptions): Core.APIPromise; +} +export interface CreateEmbeddingResponse { + /** + * The list of embeddings generated by the model. + */ + data: Array; + /** + * The name of the model used to generate the embedding. + */ + model: string; + /** + * The object type, which is always "list". + */ + object: 'list'; + /** + * The usage information for the request. + */ + usage: CreateEmbeddingResponse.Usage; +} +export declare namespace CreateEmbeddingResponse { + /** + * The usage information for the request. + */ + interface Usage { + /** + * The number of tokens used by the prompt. + */ + prompt_tokens: number; + /** + * The total number of tokens used by the request. + */ + total_tokens: number; + } +} +/** + * Represents an embedding vector returned by embedding endpoint. + */ +export interface Embedding { + /** + * The embedding vector, which is a list of floats. The length of vector depends on + * the model as listed in the + * [embedding guide](https://platform.openai.com/docs/guides/embeddings). + */ + embedding: Array; + /** + * The index of the embedding in the list of embeddings. + */ + index: number; + /** + * The object type, which is always "embedding". + */ + object: 'embedding'; +} +export interface EmbeddingCreateParams { + /** + * Input text to embed, encoded as a string or array of tokens. To embed multiple + * inputs in a single request, pass an array of strings or array of token arrays. + * The input must not exceed the max input tokens for the model (8192 tokens for + * `text-embedding-ada-002`), cannot be an empty string, and any array must be 2048 + * dimensions or less. + * [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) + * for counting tokens. + */ + input: string | Array | Array | Array>; + /** + * ID of the model to use. You can use the + * [List models](https://platform.openai.com/docs/api-reference/models/list) API to + * see all of your available models, or see our + * [Model overview](https://platform.openai.com/docs/models/overview) for + * descriptions of them. + */ + model: (string & {}) | 'text-embedding-ada-002' | 'text-embedding-3-small' | 'text-embedding-3-large'; + /** + * The number of dimensions the resulting output embeddings should have. Only + * supported in `text-embedding-3` and later models. + */ + dimensions?: number; + /** + * The format to return the embeddings in. Can be either `float` or + * [`base64`](https://pypi.org/project/pybase64/). + */ + encoding_format?: 'float' | 'base64'; + /** + * A unique identifier representing your end-user, which can help OpenAI to monitor + * and detect abuse. + * [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + */ + user?: string; +} +export declare namespace Embeddings { + export import CreateEmbeddingResponse = EmbeddingsAPI.CreateEmbeddingResponse; + export import Embedding = EmbeddingsAPI.Embedding; + export import EmbeddingCreateParams = EmbeddingsAPI.EmbeddingCreateParams; +} +//# sourceMappingURL=embeddings.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/embeddings.d.ts.map b/backend/node_modules/openai/resources/embeddings.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..98fd7dc69ce18371270357714f8fb1af87c80cad --- /dev/null +++ b/backend/node_modules/openai/resources/embeddings.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"embeddings.d.ts","sourceRoot":"","sources":["../src/resources/embeddings.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,IAAI,MAAM,aAAa,CAAC;AACpC,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAC9C,OAAO,KAAK,aAAa,MAAM,6BAA6B,CAAC;AAE7D,qBAAa,UAAW,SAAQ,WAAW;IACzC;;OAEG;IACH,MAAM,CACJ,IAAI,EAAE,qBAAqB,EAC3B,OAAO,CAAC,EAAE,IAAI,CAAC,cAAc,GAC5B,IAAI,CAAC,UAAU,CAAC,uBAAuB,CAAC;CAG5C;AAED,MAAM,WAAW,uBAAuB;IACtC;;OAEG;IACH,IAAI,EAAE,KAAK,CAAC,SAAS,CAAC,CAAC;IAEvB;;OAEG;IACH,KAAK,EAAE,MAAM,CAAC;IAEd;;OAEG;IACH,MAAM,EAAE,MAAM,CAAC;IAEf;;OAEG;IACH,KAAK,EAAE,uBAAuB,CAAC,KAAK,CAAC;CACtC;AAED,yBAAiB,uBAAuB,CAAC;IACvC;;OAEG;IACH,UAAiB,KAAK;QACpB;;WAEG;QACH,aAAa,EAAE,MAAM,CAAC;QAEtB;;WAEG;QACH,YAAY,EAAE,MAAM,CAAC;KACtB;CACF;AAED;;GAEG;AACH,MAAM,WAAW,SAAS;IACxB;;;;OAIG;IACH,SAAS,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IAEzB;;OAEG;IACH,KAAK,EAAE,MAAM,CAAC;IAEd;;OAEG;IACH,MAAM,EAAE,WAAW,CAAC;CACrB;AAED,MAAM,WAAW,qBAAqB;IACpC;;;;;;;;OAQG;IACH,KAAK,EAAE,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC,GAAG,KAAK,CAAC,MAAM,CAAC,GAAG,KAAK,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC;IAErE;;;;;;OAMG;IACH,KAAK,EAAE,CAAC,MAAM,GAAG,EAAE,CAAC,GAAG,wBAAwB,GAAG,wBAAwB,GAAG,wBAAwB,CAAC;IAEtG;;;OAGG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IAEpB;;;OAGG;IACH,eAAe,CAAC,EAAE,OAAO,GAAG,QAAQ,CAAC;IAErC;;;;OAIG;IACH,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAED,yBAAiB,UAAU,CAAC;IAC1B,MAAM,QAAQ,uBAAuB,GAAG,aAAa,CAAC,uBAAuB,CAAC;IAC9E,MAAM,QAAQ,SAAS,GAAG,aAAa,CAAC,SAAS,CAAC;IAClD,MAAM,QAAQ,qBAAqB,GAAG,aAAa,CAAC,qBAAqB,CAAC;CAC3E"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/embeddings.js b/backend/node_modules/openai/resources/embeddings.js new file mode 100644 index 0000000000000000000000000000000000000000..b8f9d311997e5866b802b7be04fdc915e4adecd9 --- /dev/null +++ b/backend/node_modules/openai/resources/embeddings.js @@ -0,0 +1,17 @@ +"use strict"; +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Embeddings = void 0; +const resource_1 = require("openai/resource"); +class Embeddings extends resource_1.APIResource { + /** + * Creates an embedding vector representing the input text. + */ + create(body, options) { + return this._client.post('/embeddings', { body, ...options }); + } +} +exports.Embeddings = Embeddings; +(function (Embeddings) { +})(Embeddings = exports.Embeddings || (exports.Embeddings = {})); +//# sourceMappingURL=embeddings.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/embeddings.js.map b/backend/node_modules/openai/resources/embeddings.js.map new file mode 100644 index 0000000000000000000000000000000000000000..7a83a4230626285baf6056d5a761f8924a979ee4 --- /dev/null +++ b/backend/node_modules/openai/resources/embeddings.js.map @@ -0,0 +1 @@ +{"version":3,"file":"embeddings.js","sourceRoot":"","sources":["../src/resources/embeddings.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;AAGtF,8CAA8C;AAG9C,MAAa,UAAW,SAAQ,sBAAW;IACzC;;OAEG;IACH,MAAM,CACJ,IAA2B,EAC3B,OAA6B;QAE7B,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,aAAa,EAAE,EAAE,IAAI,EAAE,GAAG,OAAO,EAAE,CAAC,CAAC;IAChE,CAAC;CACF;AAVD,gCAUC;AAwGD,WAAiB,UAAU;AAI3B,CAAC,EAJgB,UAAU,GAAV,kBAAU,KAAV,kBAAU,QAI1B"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/embeddings.mjs b/backend/node_modules/openai/resources/embeddings.mjs new file mode 100644 index 0000000000000000000000000000000000000000..6c1bb7b71f65392312ed740866af9f69a9ab18f0 --- /dev/null +++ b/backend/node_modules/openai/resources/embeddings.mjs @@ -0,0 +1,13 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +import { APIResource } from 'openai/resource'; +export class Embeddings extends APIResource { + /** + * Creates an embedding vector representing the input text. + */ + create(body, options) { + return this._client.post('/embeddings', { body, ...options }); + } +} +(function (Embeddings) { +})(Embeddings || (Embeddings = {})); +//# sourceMappingURL=embeddings.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/embeddings.mjs.map b/backend/node_modules/openai/resources/embeddings.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..d6ab10ba4df74de3f9758e4b116aefaa0cfe039e --- /dev/null +++ b/backend/node_modules/openai/resources/embeddings.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"embeddings.mjs","sourceRoot":"","sources":["../src/resources/embeddings.ts"],"names":[],"mappings":"AAAA,sFAAsF;OAG/E,EAAE,WAAW,EAAE,MAAM,iBAAiB;AAG7C,MAAM,OAAO,UAAW,SAAQ,WAAW;IACzC;;OAEG;IACH,MAAM,CACJ,IAA2B,EAC3B,OAA6B;QAE7B,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,aAAa,EAAE,EAAE,IAAI,EAAE,GAAG,OAAO,EAAE,CAAC,CAAC;IAChE,CAAC;CACF;AAwGD,WAAiB,UAAU;AAI3B,CAAC,EAJgB,UAAU,KAAV,UAAU,QAI1B"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/files.d.ts b/backend/node_modules/openai/resources/files.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..bbfdb79a87a7ab909f2b6f9d51b89740d48c0df6 --- /dev/null +++ b/backend/node_modules/openai/resources/files.d.ts @@ -0,0 +1,135 @@ +import * as Core from 'openai/core'; +import { APIResource } from 'openai/resource'; +import { type Response } from 'openai/_shims/index'; +import * as FilesAPI from 'openai/resources/files'; +import { type Uploadable } from 'openai/core'; +import { Page } from 'openai/pagination'; +export declare class Files extends APIResource { + /** + * Upload a file that can be used across various endpoints. The size of all the + * files uploaded by one organization can be up to 100 GB. + * + * The size of individual files can be a maximum of 512 MB or 2 million tokens for + * Assistants. See the + * [Assistants Tools guide](https://platform.openai.com/docs/assistants/tools) to + * learn more about the types of files supported. The Fine-tuning API only supports + * `.jsonl` files. + * + * Please [contact us](https://help.openai.com/) if you need to increase these + * storage limits. + */ + create(body: FileCreateParams, options?: Core.RequestOptions): Core.APIPromise; + /** + * Returns information about a specific file. + */ + retrieve(fileId: string, options?: Core.RequestOptions): Core.APIPromise; + /** + * Returns a list of files that belong to the user's organization. + */ + list(query?: FileListParams, options?: Core.RequestOptions): Core.PagePromise; + list(options?: Core.RequestOptions): Core.PagePromise; + /** + * Delete a file. + */ + del(fileId: string, options?: Core.RequestOptions): Core.APIPromise; + /** + * Returns the contents of the specified file. + */ + content(fileId: string, options?: Core.RequestOptions): Core.APIPromise; + /** + * Returns the contents of the specified file. + * + * @deprecated The `.content()` method should be used instead + */ + retrieveContent(fileId: string, options?: Core.RequestOptions): Core.APIPromise; + /** + * Waits for the given file to be processed, default timeout is 30 mins. + */ + waitForProcessing(id: string, { pollInterval, maxWait }?: { + pollInterval?: number; + maxWait?: number; + }): Promise; +} +/** + * Note: no pagination actually occurs yet, this is for forwards-compatibility. + */ +export declare class FileObjectsPage extends Page { +} +export type FileContent = string; +export interface FileDeleted { + id: string; + deleted: boolean; + object: 'file'; +} +/** + * The `File` object represents a document that has been uploaded to OpenAI. + */ +export interface FileObject { + /** + * The file identifier, which can be referenced in the API endpoints. + */ + id: string; + /** + * The size of the file, in bytes. + */ + bytes: number; + /** + * The Unix timestamp (in seconds) for when the file was created. + */ + created_at: number; + /** + * The name of the file. + */ + filename: string; + /** + * The object type, which is always `file`. + */ + object: 'file'; + /** + * The intended purpose of the file. Supported values are `fine-tune`, + * `fine-tune-results`, `assistants`, and `assistants_output`. + */ + purpose: 'fine-tune' | 'fine-tune-results' | 'assistants' | 'assistants_output'; + /** + * @deprecated: Deprecated. The current status of the file, which can be either + * `uploaded`, `processed`, or `error`. + */ + status: 'uploaded' | 'processed' | 'error'; + /** + * @deprecated: Deprecated. For details on why a fine-tuning training file failed + * validation, see the `error` field on `fine_tuning.job`. + */ + status_details?: string; +} +export interface FileCreateParams { + /** + * The File object (not file name) to be uploaded. + */ + file: Uploadable; + /** + * The intended purpose of the uploaded file. + * + * Use "fine-tune" for + * [Fine-tuning](https://platform.openai.com/docs/api-reference/fine-tuning) and + * "assistants" for + * [Assistants](https://platform.openai.com/docs/api-reference/assistants) and + * [Messages](https://platform.openai.com/docs/api-reference/messages). This allows + * us to validate the format of the uploaded file is correct for fine-tuning. + */ + purpose: 'fine-tune' | 'assistants'; +} +export interface FileListParams { + /** + * Only return files with the given purpose. + */ + purpose?: string; +} +export declare namespace Files { + export import FileContent = FilesAPI.FileContent; + export import FileDeleted = FilesAPI.FileDeleted; + export import FileObject = FilesAPI.FileObject; + export import FileObjectsPage = FilesAPI.FileObjectsPage; + export import FileCreateParams = FilesAPI.FileCreateParams; + export import FileListParams = FilesAPI.FileListParams; +} +//# sourceMappingURL=files.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/files.d.ts.map b/backend/node_modules/openai/resources/files.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..aee04d8b7674491bb78f85d9fdaf0725ef142a5a --- /dev/null +++ b/backend/node_modules/openai/resources/files.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"files.d.ts","sourceRoot":"","sources":["../src/resources/files.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,IAAI,MAAM,aAAa,CAAC;AACpC,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAE9C,OAAO,EAAE,KAAK,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAGpD,OAAO,KAAK,QAAQ,MAAM,wBAAwB,CAAC;AACnD,OAAO,EAAE,KAAK,UAAU,EAA+B,MAAM,aAAa,CAAC;AAC3E,OAAO,EAAE,IAAI,EAAE,MAAM,mBAAmB,CAAC;AAEzC,qBAAa,KAAM,SAAQ,WAAW;IACpC;;;;;;;;;;;;OAYG;IACH,MAAM,CAAC,IAAI,EAAE,gBAAgB,EAAE,OAAO,CAAC,EAAE,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC,UAAU,CAAC,UAAU,CAAC;IAI1F;;OAEG;IACH,QAAQ,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC,UAAU,CAAC,UAAU,CAAC;IAIpF;;OAEG;IACH,IAAI,CAAC,KAAK,CAAC,EAAE,cAAc,EAAE,OAAO,CAAC,EAAE,IAAI,CAAC,cAAc,G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;IACH,MAAM,EAAE,MAAM,CAAC;IAEf;;;OAGG;IACH,OAAO,EAAE,WAAW,GAAG,mBAAmB,GAAG,YAAY,GAAG,mBAAmB,CAAC;IAEhF;;;OAGG;IACH,MAAM,EAAE,UAAU,GAAG,WAAW,GAAG,OAAO,CAAC;IAE3C;;;OAGG;IACH,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB;AAED,MAAM,WAAW,gBAAgB;IAC/B;;OAEG;IACH,IAAI,EAAE,UAAU,CAAC;IAEjB;;;;;;;;;OASG;IACH,OAAO,EAAE,WAAW,GAAG,YAAY,CAAC;CACrC;AAED,MAAM,WAAW,cAAc;IAC7B;;OAEG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,yBAAiB,KAAK,CAAC;IACrB,MAAM,QAAQ,WAAW,GAAG,QAAQ,CAAC,WAAW,CAAC;IACjD,MAAM,QAAQ,WAAW,GAAG,QAAQ,CAAC,WAAW,CAAC;IACjD,MAAM,QAAQ,UAAU,GAAG,QAAQ,CAAC,UAAU,CAAC;IAC/C,MAAM,QAAQ,eAAe,GAAG,QAAQ,CAAC,eAAe,CAAC;IACzD,MAAM,QAAQ,gBAAgB,GAAG,QAAQ,CAAC,gBAAgB,CAAC;IAC3D,MAAM,QAAQ,cAAc,GAAG,QAAQ,CAAC,cAAc,CAAC;CACxD"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/files.js b/backend/node_modules/openai/resources/files.js new file mode 100644 index 0000000000000000000000000000000000000000..4c652a38f616177ca16b80570d985df06ea9d4f2 --- /dev/null +++ b/backend/node_modules/openai/resources/files.js @@ -0,0 +1,116 @@ +"use strict"; +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FileObjectsPage = exports.Files = void 0; +const resource_1 = require("openai/resource"); +const core_1 = require("openai/core"); +const core_2 = require("openai/core"); +const error_1 = require("openai/error"); +const FilesAPI = __importStar(require("openai/resources/files")); +const core_3 = require("openai/core"); +const pagination_1 = require("openai/pagination"); +class Files extends resource_1.APIResource { + /** + * Upload a file that can be used across various endpoints. The size of all the + * files uploaded by one organization can be up to 100 GB. + * + * The size of individual files can be a maximum of 512 MB or 2 million tokens for + * Assistants. See the + * [Assistants Tools guide](https://platform.openai.com/docs/assistants/tools) to + * learn more about the types of files supported. The Fine-tuning API only supports + * `.jsonl` files. + * + * Please [contact us](https://help.openai.com/) if you need to increase these + * storage limits. + */ + create(body, options) { + return this._client.post('/files', (0, core_3.multipartFormRequestOptions)({ body, ...options })); + } + /** + * Returns information about a specific file. + */ + retrieve(fileId, options) { + return this._client.get(`/files/${fileId}`, options); + } + list(query = {}, options) { + if ((0, core_1.isRequestOptions)(query)) { + return this.list({}, query); + } + return this._client.getAPIList('/files', FileObjectsPage, { query, ...options }); + } + /** + * Delete a file. + */ + del(fileId, options) { + return this._client.delete(`/files/${fileId}`, options); + } + /** + * Returns the contents of the specified file. + */ + content(fileId, options) { + return this._client.get(`/files/${fileId}/content`, { ...options, __binaryResponse: true }); + } + /** + * Returns the contents of the specified file. + * + * @deprecated The `.content()` method should be used instead + */ + retrieveContent(fileId, options) { + return this._client.get(`/files/${fileId}/content`, { + ...options, + headers: { Accept: 'application/json', ...options?.headers }, + }); + } + /** + * Waits for the given file to be processed, default timeout is 30 mins. + */ + async waitForProcessing(id, { pollInterval = 5000, maxWait = 30 * 60 * 1000 } = {}) { + const TERMINAL_STATES = new Set(['processed', 'error', 'deleted']); + const start = Date.now(); + let file = await this.retrieve(id); + while (!file.status || !TERMINAL_STATES.has(file.status)) { + await (0, core_2.sleep)(pollInterval); + file = await this.retrieve(id); + if (Date.now() - start > maxWait) { + throw new error_1.APIConnectionTimeoutError({ + message: `Giving up on waiting for file ${id} to finish processing after ${maxWait} milliseconds.`, + }); + } + } + return file; + } +} +exports.Files = Files; +/** + * Note: no pagination actually occurs yet, this is for forwards-compatibility. + */ +class FileObjectsPage extends pagination_1.Page { +} +exports.FileObjectsPage = FileObjectsPage; +(function (Files) { + Files.FileObjectsPage = FilesAPI.FileObjectsPage; +})(Files = exports.Files || (exports.Files = {})); +//# sourceMappingURL=files.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/files.js.map b/backend/node_modules/openai/resources/files.js.map new file mode 100644 index 0000000000000000000000000000000000000000..6eed106fdea7e80acbc8a4b8c6def611bd96fa92 --- /dev/null +++ b/backend/node_modules/openai/resources/files.js.map @@ -0,0 +1 @@ +{"version":3,"file":"files.js","sourceRoot":"","sources":["../src/resources/files.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;;;;;;;;;;;;;;;;;;;;;;;;AAGtF,8CAA8C;AAC9C,sCAA+C;AAE/C,sCAAoC;AACpC,wCAAyD;AACzD,iEAAmD;AACnD,sCAA2E;AAC3E,kDAAyC;AAEzC,MAAa,KAAM,SAAQ,sBAAW;IACpC;;;;;;;;;;;;OAYG;IACH,MAAM,CAAC,IAAsB,EAAE,OAA6B;QAC1D,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,QAAQ,EAAE,IAAA,kCAA2B,EAAC,EAAE,IAAI,EAAE,GAAG,OAA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QAEnG,MAAM,eAAe,GAAG,IAAI,GAAG,CAAC,CAAC,WAAW,EAAE,OAAO,EAAE,SAAS,CAAC,CAAC,CAAC;QAEnE,MAAM,KAAK,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;QACzB,IAAI,IAAI,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;QAEnC,OAAO,CAAC,IAAI,CAAC,MAAM,IAAI,CAAC,eAAe,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE;YACxD,MAAM,IAAA,YAAK,EAAC,YAAY,CAAC,CAAC;YAE1B,IAAI,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;YAC/B,IAAI,IAAI,CAAC,GAAG,EAAE,GAAG,KAAK,GAAG,OAAO,EAAE;gBAChC,MAAM,IAAI,iCAAyB,CAAC;oBAClC,OAAO,EAAE,iCAAiC,EAAE,+BAA+B,OAAO,gBAAgB;iBACnG,CAAC,CAAC;aACJ;SACF;QAED,OAAO,IAAI,CAAC;IACd,CAAC;CACF;AA3FD,sBA2FC;AAED;;GAEG;AACH,MAAa,eAAgB,SAAQ,iBAAgB;CAAG;AAAxD,0CAAwD;AAsFxD,WAAiB,KAAK;IAIN,qBAAe,GAAG,QAAQ,CAAC,eAAe,CAAC;AAG3D,CAAC,EAPgB,KAAK,GAAL,aAAK,KAAL,aAAK,QAOrB"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/files.mjs b/backend/node_modules/openai/resources/files.mjs new file mode 100644 index 0000000000000000000000000000000000000000..dbfc8974b7e0e73c9254dd2e7b8ba0e6ae788ca3 --- /dev/null +++ b/backend/node_modules/openai/resources/files.mjs @@ -0,0 +1,88 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +import { APIResource } from 'openai/resource'; +import { isRequestOptions } from 'openai/core'; +import { sleep } from 'openai/core'; +import { APIConnectionTimeoutError } from 'openai/error'; +import * as FilesAPI from 'openai/resources/files'; +import { multipartFormRequestOptions } from 'openai/core'; +import { Page } from 'openai/pagination'; +export class Files extends APIResource { + /** + * Upload a file that can be used across various endpoints. The size of all the + * files uploaded by one organization can be up to 100 GB. + * + * The size of individual files can be a maximum of 512 MB or 2 million tokens for + * Assistants. See the + * [Assistants Tools guide](https://platform.openai.com/docs/assistants/tools) to + * learn more about the types of files supported. The Fine-tuning API only supports + * `.jsonl` files. + * + * Please [contact us](https://help.openai.com/) if you need to increase these + * storage limits. + */ + create(body, options) { + return this._client.post('/files', multipartFormRequestOptions({ body, ...options })); + } + /** + * Returns information about a specific file. + */ + retrieve(fileId, options) { + return this._client.get(`/files/${fileId}`, options); + } + list(query = {}, options) { + if (isRequestOptions(query)) { + return this.list({}, query); + } + return this._client.getAPIList('/files', FileObjectsPage, { query, ...options }); + } + /** + * Delete a file. + */ + del(fileId, options) { + return this._client.delete(`/files/${fileId}`, options); + } + /** + * Returns the contents of the specified file. + */ + content(fileId, options) { + return this._client.get(`/files/${fileId}/content`, { ...options, __binaryResponse: true }); + } + /** + * Returns the contents of the specified file. + * + * @deprecated The `.content()` method should be used instead + */ + retrieveContent(fileId, options) { + return this._client.get(`/files/${fileId}/content`, { + ...options, + headers: { Accept: 'application/json', ...options?.headers }, + }); + } + /** + * Waits for the given file to be processed, default timeout is 30 mins. + */ + async waitForProcessing(id, { pollInterval = 5000, maxWait = 30 * 60 * 1000 } = {}) { + const TERMINAL_STATES = new Set(['processed', 'error', 'deleted']); + const start = Date.now(); + let file = await this.retrieve(id); + while (!file.status || !TERMINAL_STATES.has(file.status)) { + await sleep(pollInterval); + file = await this.retrieve(id); + if (Date.now() - start > maxWait) { + throw new APIConnectionTimeoutError({ + message: `Giving up on waiting for file ${id} to finish processing after ${maxWait} milliseconds.`, + }); + } + } + return file; + } +} +/** + * Note: no pagination actually occurs yet, this is for forwards-compatibility. + */ +export class FileObjectsPage extends Page { +} +(function (Files) { + Files.FileObjectsPage = FilesAPI.FileObjectsPage; +})(Files || (Files = {})); +//# sourceMappingURL=files.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/files.mjs.map b/backend/node_modules/openai/resources/files.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..55426aa691af410ce126d64fd8740459fc079619 --- /dev/null +++ b/backend/node_modules/openai/resources/files.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"files.mjs","sourceRoot":"","sources":["../src/resources/files.ts"],"names":[],"mappings":"AAAA,sFAAsF;OAG/E,EAAE,WAAW,EAAE,MAAM,iBAAiB;OACtC,EAAE,gBAAgB,EAAE,MAAM,aAAa;OAEvC,EAAE,KAAK,EAAE,MAAM,aAAa;OAC5B,EAAE,yBAAyB,EAAE,MAAM,cAAc;OACjD,KAAK,QAAQ,MAAM,wBAAwB;OAC3C,EAAmB,2BAA2B,EAAE,MAAM,aAAa;OACnE,EAAE,IAAI,EAAE,MAAM,mBAAmB;AAExC,MAAM,OAAO,KAAM,SAAQ,WAAW;IACpC;;;;;;;;;;;;OAYG;IACH,MAAM,CAAC,IAAsB,EAAE,OAA6B;QAC1D,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,QAAQ,EAAE,2BAA2B,CAAC,EAAE,IAAI,EAAE,GAAG,OAAO,EAAE,CAAC,CAAC,CAAC;IACxF,CAAC;IAED;;OAEG;IACH,QAAQ,CAAC,MAAc,EAAE,OAA6B;QACpD,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,UAAU,MAAM,EAAE,EAAE,OAAO,CAAC,CAAC;IACvD,CAAC;IAOD,IAAI,CACF,QAA8C,EAAE,EAChD,OAA6B;QAE7B,IAAI,gBAAgB,CAAC,KAAK,CAAC,EAAE;YAC3B,OAAO,IAAI,CAAC,IAAI,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC;SAC7B;QACD,OAAO,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,QAAQ,EAAE,eAAe,EAAE,EAAE,KAAK,EAAE,GAAG,OAAO,EAAE,CAAC,C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E,GAAG,KAAK,GAAG,OAAO,EAAE;gBAChC,MAAM,IAAI,yBAAyB,CAAC;oBAClC,OAAO,EAAE,iCAAiC,EAAE,+BAA+B,OAAO,gBAAgB;iBACnG,CAAC,CAAC;aACJ;SACF;QAED,OAAO,IAAI,CAAC;IACd,CAAC;CACF;AAED;;GAEG;AACH,MAAM,OAAO,eAAgB,SAAQ,IAAgB;CAAG;AAsFxD,WAAiB,KAAK;IAIN,qBAAe,GAAG,QAAQ,CAAC,eAAe,CAAC;AAG3D,CAAC,EAPgB,KAAK,KAAL,KAAK,QAOrB"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/fine-tuning/fine-tuning.d.ts b/backend/node_modules/openai/resources/fine-tuning/fine-tuning.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..58d5ce3c4a5411ce7e3738070159d90c144725a9 --- /dev/null +++ b/backend/node_modules/openai/resources/fine-tuning/fine-tuning.d.ts @@ -0,0 +1,19 @@ +import { APIResource } from 'openai/resource'; +import * as JobsAPI from 'openai/resources/fine-tuning/jobs/jobs'; +export declare class FineTuning extends APIResource { + jobs: JobsAPI.Jobs; +} +export declare namespace FineTuning { + export import Jobs = JobsAPI.Jobs; + export import FineTuningJob = JobsAPI.FineTuningJob; + export import FineTuningJobEvent = JobsAPI.FineTuningJobEvent; + export import FineTuningJobIntegration = JobsAPI.FineTuningJobIntegration; + export import FineTuningJobWandbIntegration = JobsAPI.FineTuningJobWandbIntegration; + export import FineTuningJobWandbIntegrationObject = JobsAPI.FineTuningJobWandbIntegrationObject; + export import FineTuningJobsPage = JobsAPI.FineTuningJobsPage; + export import FineTuningJobEventsPage = JobsAPI.FineTuningJobEventsPage; + export import JobCreateParams = JobsAPI.JobCreateParams; + export import JobListParams = JobsAPI.JobListParams; + export import JobListEventsParams = JobsAPI.JobListEventsParams; +} +//# sourceMappingURL=fine-tuning.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/fine-tuning/fine-tuning.d.ts.map b/backend/node_modules/openai/resources/fine-tuning/fine-tuning.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..8bf2fb99c47a3d1772e65e0c69979411527cea53 --- /dev/null +++ b/backend/node_modules/openai/resources/fine-tuning/fine-tuning.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"fine-tuning.d.ts","sourceRoot":"","sources":["../../src/resources/fine-tuning/fine-tuning.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAC9C,OAAO,KAAK,OAAO,MAAM,wCAAwC,CAAC;AAElE,qBAAa,UAAW,SAAQ,WAAW;IACzC,IAAI,EAAE,OAAO,CAAC,IAAI,CAAkC;CACrD;AAED,yBAAiB,UAAU,CAAC;IAC1B,MAAM,QAAQ,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;IAClC,MAAM,QAAQ,aAAa,GAAG,OAAO,CAAC,aAAa,CAAC;IACpD,MAAM,QAAQ,kBAAkB,GAAG,OAAO,CAAC,kBAAkB,CAAC;IAC9D,MAAM,QAAQ,wBAAwB,GAAG,OAAO,CAAC,wBAAwB,CAAC;IAC1E,MAAM,QAAQ,6BAA6B,GAAG,OAAO,CAAC,6BAA6B,CAAC;IACpF,MAAM,QAAQ,mCAAmC,GAAG,OAAO,CAAC,mCAAmC,CAAC;IAChG,MAAM,QAAQ,kBAAkB,GAAG,OAAO,CAAC,kBAAkB,CAAC;IAC9D,MAAM,QAAQ,uBAAuB,GAAG,OAAO,CAAC,uBAAuB,CAAC;IACxE,MAAM,QAAQ,eAAe,GAAG,OAAO,CAAC,eAAe,CAAC;IACxD,MAAM,QAAQ,aAAa,GAAG,OAAO,CAAC,aAAa,CAAC;IACpD,MAAM,QAAQ,mBAAmB,GAAG,OAAO,CAAC,mBAAmB,CAAC;CACjE"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/fine-tuning/fine-tuning.js b/backend/node_modules/openai/resources/fine-tuning/fine-tuning.js new file mode 100644 index 0000000000000000000000000000000000000000..e9199ce17ece371420bcf3fe23aa84143b07070f --- /dev/null +++ b/backend/node_modules/openai/resources/fine-tuning/fine-tuning.js @@ -0,0 +1,42 @@ +"use strict"; +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FineTuning = void 0; +const resource_1 = require("openai/resource"); +const JobsAPI = __importStar(require("openai/resources/fine-tuning/jobs/jobs")); +class FineTuning extends resource_1.APIResource { + constructor() { + super(...arguments); + this.jobs = new JobsAPI.Jobs(this._client); + } +} +exports.FineTuning = FineTuning; +(function (FineTuning) { + FineTuning.Jobs = JobsAPI.Jobs; + FineTuning.FineTuningJobsPage = JobsAPI.FineTuningJobsPage; + FineTuning.FineTuningJobEventsPage = JobsAPI.FineTuningJobEventsPage; +})(FineTuning = exports.FineTuning || (exports.FineTuning = {})); +//# sourceMappingURL=fine-tuning.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/fine-tuning/fine-tuning.js.map b/backend/node_modules/openai/resources/fine-tuning/fine-tuning.js.map new file mode 100644 index 0000000000000000000000000000000000000000..20e52bbce08302be695464158593ba8933d4ccc5 --- /dev/null +++ b/backend/node_modules/openai/resources/fine-tuning/fine-tuning.js.map @@ -0,0 +1 @@ +{"version":3,"file":"fine-tuning.js","sourceRoot":"","sources":["../../src/resources/fine-tuning/fine-tuning.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;;;;;;;;;;;;;;;;;;;;;;;;AAEtF,8CAA8C;AAC9C,gFAAkE;AAElE,MAAa,UAAW,SAAQ,sBAAW;IAA3C;;QACE,SAAI,GAAiB,IAAI,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IACtD,CAAC;CAAA;AAFD,gCAEC;AAED,WAAiB,UAAU;IACX,eAAI,GAAG,OAAO,CAAC,IAAI,CAAC;IAMpB,6BAAkB,GAAG,OAAO,CAAC,kBAAkB,CAAC;IAChD,kCAAuB,GAAG,OAAO,CAAC,uBAAuB,CAAC;AAI1E,CAAC,EAZgB,UAAU,GAAV,kBAAU,KAAV,kBAAU,QAY1B"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/fine-tuning/fine-tuning.mjs b/backend/node_modules/openai/resources/fine-tuning/fine-tuning.mjs new file mode 100644 index 0000000000000000000000000000000000000000..49d104cb8d431b87c99022af7d0510c297187483 --- /dev/null +++ b/backend/node_modules/openai/resources/fine-tuning/fine-tuning.mjs @@ -0,0 +1,15 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +import { APIResource } from 'openai/resource'; +import * as JobsAPI from 'openai/resources/fine-tuning/jobs/jobs'; +export class FineTuning extends APIResource { + constructor() { + super(...arguments); + this.jobs = new JobsAPI.Jobs(this._client); + } +} +(function (FineTuning) { + FineTuning.Jobs = JobsAPI.Jobs; + FineTuning.FineTuningJobsPage = JobsAPI.FineTuningJobsPage; + FineTuning.FineTuningJobEventsPage = JobsAPI.FineTuningJobEventsPage; +})(FineTuning || (FineTuning = {})); +//# sourceMappingURL=fine-tuning.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/fine-tuning/fine-tuning.mjs.map b/backend/node_modules/openai/resources/fine-tuning/fine-tuning.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..a3ab592818e0b1468c76c2c100894a6c3aa34a4b --- /dev/null +++ b/backend/node_modules/openai/resources/fine-tuning/fine-tuning.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"fine-tuning.mjs","sourceRoot":"","sources":["../../src/resources/fine-tuning/fine-tuning.ts"],"names":[],"mappings":"AAAA,sFAAsF;OAE/E,EAAE,WAAW,EAAE,MAAM,iBAAiB;OACtC,KAAK,OAAO,MAAM,wCAAwC;AAEjE,MAAM,OAAO,UAAW,SAAQ,WAAW;IAA3C;;QACE,SAAI,GAAiB,IAAI,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IACtD,CAAC;CAAA;AAED,WAAiB,UAAU;IACX,eAAI,GAAG,OAAO,CAAC,IAAI,CAAC;IAMpB,6BAAkB,GAAG,OAAO,CAAC,kBAAkB,CAAC;IAChD,kCAAuB,GAAG,OAAO,CAAC,uBAAuB,CAAC;AAI1E,CAAC,EAZgB,UAAU,KAAV,UAAU,QAY1B"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/fine-tuning/index.d.ts b/backend/node_modules/openai/resources/fine-tuning/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9888cc4a9c76ccedd9ee9104d13bfa5f07ed8493 --- /dev/null +++ b/backend/node_modules/openai/resources/fine-tuning/index.d.ts @@ -0,0 +1,3 @@ +export { FineTuning } from "./fine-tuning.js"; +export { FineTuningJob, FineTuningJobEvent, FineTuningJobIntegration, FineTuningJobWandbIntegration, FineTuningJobWandbIntegrationObject, JobCreateParams, JobListParams, JobListEventsParams, FineTuningJobsPage, FineTuningJobEventsPage, Jobs, } from "./jobs/index.js"; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/fine-tuning/index.d.ts.map b/backend/node_modules/openai/resources/fine-tuning/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..ec08bf77cce3057cf96d007f86873ca917079e1d --- /dev/null +++ b/backend/node_modules/openai/resources/fine-tuning/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/resources/fine-tuning/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,OAAO,EACL,aAAa,EACb,kBAAkB,EAClB,wBAAwB,EACxB,6BAA6B,EAC7B,mCAAmC,EACnC,eAAe,EACf,aAAa,EACb,mBAAmB,EACnB,kBAAkB,EAClB,uBAAuB,EACvB,IAAI,GACL,MAAM,cAAc,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/fine-tuning/index.js b/backend/node_modules/openai/resources/fine-tuning/index.js new file mode 100644 index 0000000000000000000000000000000000000000..7b187f473cfa5c2cca88791e7dd0e1f961468efa --- /dev/null +++ b/backend/node_modules/openai/resources/fine-tuning/index.js @@ -0,0 +1,11 @@ +"use strict"; +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Jobs = exports.FineTuningJobEventsPage = exports.FineTuningJobsPage = exports.FineTuning = void 0; +var fine_tuning_1 = require("./fine-tuning.js"); +Object.defineProperty(exports, "FineTuning", { enumerable: true, get: function () { return fine_tuning_1.FineTuning; } }); +var index_1 = require("./jobs/index.js"); +Object.defineProperty(exports, "FineTuningJobsPage", { enumerable: true, get: function () { return index_1.FineTuningJobsPage; } }); +Object.defineProperty(exports, "FineTuningJobEventsPage", { enumerable: true, get: function () { return index_1.FineTuningJobEventsPage; } }); +Object.defineProperty(exports, "Jobs", { enumerable: true, get: function () { return index_1.Jobs; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/fine-tuning/index.js.map b/backend/node_modules/openai/resources/fine-tuning/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..966883e51cd663bdb584849c360bb2cc1e4cf78e --- /dev/null +++ b/backend/node_modules/openai/resources/fine-tuning/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/resources/fine-tuning/index.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;AAEtF,gDAA2C;AAAlC,yGAAA,UAAU,OAAA;AACnB,yCAYsB;AAHpB,2GAAA,kBAAkB,OAAA;AAClB,gHAAA,uBAAuB,OAAA;AACvB,6FAAA,IAAI,OAAA"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/fine-tuning/index.mjs b/backend/node_modules/openai/resources/fine-tuning/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..1bf1178fe9bf0d3f5ff515204579149477ca0f04 --- /dev/null +++ b/backend/node_modules/openai/resources/fine-tuning/index.mjs @@ -0,0 +1,4 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +export { FineTuning } from "./fine-tuning.mjs"; +export { FineTuningJobsPage, FineTuningJobEventsPage, Jobs, } from "./jobs/index.mjs"; +//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/fine-tuning/index.mjs.map b/backend/node_modules/openai/resources/fine-tuning/index.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..d6d40b8ca6e7eaa0ecbf875a2a9b3cc2b264a8ec --- /dev/null +++ b/backend/node_modules/openai/resources/fine-tuning/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"index.mjs","sourceRoot":"","sources":["../../src/resources/fine-tuning/index.ts"],"names":[],"mappings":"AAAA,sFAAsF;OAE/E,EAAE,UAAU,EAAE;OACd,EASL,kBAAkB,EAClB,uBAAuB,EACvB,IAAI,GACL"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/fine-tuning/jobs/checkpoints.d.ts b/backend/node_modules/openai/resources/fine-tuning/jobs/checkpoints.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8c9fbc5ca69f4e708d1ea843bf1c8dd01bab14d8 --- /dev/null +++ b/backend/node_modules/openai/resources/fine-tuning/jobs/checkpoints.d.ts @@ -0,0 +1,69 @@ +import * as Core from 'openai/core'; +import { APIResource } from 'openai/resource'; +import * as CheckpointsAPI from 'openai/resources/fine-tuning/jobs/checkpoints'; +import { CursorPage, type CursorPageParams } from 'openai/pagination'; +export declare class Checkpoints extends APIResource { + /** + * List checkpoints for a fine-tuning job. + */ + list(fineTuningJobId: string, query?: CheckpointListParams, options?: Core.RequestOptions): Core.PagePromise; + list(fineTuningJobId: string, options?: Core.RequestOptions): Core.PagePromise; +} +export declare class FineTuningJobCheckpointsPage extends CursorPage { +} +/** + * The `fine_tuning.job.checkpoint` object represents a model checkpoint for a + * fine-tuning job that is ready to use. + */ +export interface FineTuningJobCheckpoint { + /** + * The checkpoint identifier, which can be referenced in the API endpoints. + */ + id: string; + /** + * The Unix timestamp (in seconds) for when the checkpoint was created. + */ + created_at: number; + /** + * The name of the fine-tuned checkpoint model that is created. + */ + fine_tuned_model_checkpoint: string; + /** + * The name of the fine-tuning job that this checkpoint was created from. + */ + fine_tuning_job_id: string; + /** + * Metrics at the step number during the fine-tuning job. + */ + metrics: FineTuningJobCheckpoint.Metrics; + /** + * The object type, which is always "fine_tuning.job.checkpoint". + */ + object: 'fine_tuning.job.checkpoint'; + /** + * The step number that the checkpoint was created at. + */ + step_number: number; +} +export declare namespace FineTuningJobCheckpoint { + /** + * Metrics at the step number during the fine-tuning job. + */ + interface Metrics { + full_valid_loss?: number; + full_valid_mean_token_accuracy?: number; + step?: number; + train_loss?: number; + train_mean_token_accuracy?: number; + valid_loss?: number; + valid_mean_token_accuracy?: number; + } +} +export interface CheckpointListParams extends CursorPageParams { +} +export declare namespace Checkpoints { + export import FineTuningJobCheckpoint = CheckpointsAPI.FineTuningJobCheckpoint; + export import FineTuningJobCheckpointsPage = CheckpointsAPI.FineTuningJobCheckpointsPage; + export import CheckpointListParams = CheckpointsAPI.CheckpointListParams; +} +//# sourceMappingURL=checkpoints.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/fine-tuning/jobs/checkpoints.d.ts.map b/backend/node_modules/openai/resources/fine-tuning/jobs/checkpoints.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..7a3d78f08c09e8986f31c901bcb782841cc65b47 --- /dev/null +++ b/backend/node_modules/openai/resources/fine-tuning/jobs/checkpoints.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"checkpoints.d.ts","sourceRoot":"","sources":["../../../src/resources/fine-tuning/jobs/checkpoints.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,IAAI,MAAM,aAAa,CAAC;AACpC,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAE9C,OAAO,KAAK,cAAc,MAAM,+CAA+C,CAAC;AAChF,OAAO,EAAE,UAAU,EAAE,KAAK,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAEtE,qBAAa,WAAY,SAAQ,WAAW;IAC1C;;OAEG;IACH,IAAI,CACF,eAAe,EAAE,MAAM,EACvB,KAAK,CAAC,EAAE,oBAAoB,EAC5B,OAAO,CAAC,EAAE,IAAI,CAAC,cAAc,GAC5B,IAAI,CAAC,WAAW,CAAC,4BAA4B,EAAE,uBAAuB,CAAC;IAC1E,IAAI,CACF,eAAe,EAAE,MAAM,EACvB,OAAO,CAAC,EAAE,IAAI,CAAC,cAAc,GAC5B,IAAI,CAAC,WAAW,CAAC,4BAA4B,EAAE,uBAAuB,CAAC;CAe3E;AAED,qBAAa,4BAA6B,SAAQ,UAAU,CAAC,uBAAuB,CAAC;CAAG;AAExF;;;GAGG;AACH,MAAM,WAAW,uBAAuB;IACtC;;OAEG;IACH,EAAE,EAAE,MAAM,CAAC;IAEX;;OAEG;IACH,UAAU,EAAE,MAAM,CAAC;IAEnB;;OAEG;IACH,2BAA2B,EAAE,MAAM,CAAC;IAEpC;;OAEG;IACH,kBAAkB,EAAE,MAAM,CAAC;IAE3B;;OAEG;IACH,OAAO,EAAE,uBAAuB,CAAC,OAAO,CAAC;IAEzC;;OAEG;IACH,MAAM,EAAE,4BAA4B,CAAC;IAErC;;OAEG;IACH,WAAW,EAAE,MAAM,CAAC;CACrB;AAED,yBAAiB,uBAAuB,CAAC;IACvC;;OAEG;IACH,UAAiB,OAAO;QACtB,eAAe,CAAC,EAAE,MAAM,CAAC;QAEzB,8BAA8B,CAAC,EAAE,MAAM,CAAC;QAExC,IAAI,CAAC,EAAE,MAAM,CAAC;QAEd,UAAU,CAAC,EAAE,MAAM,CAAC;QAEpB,yBAAyB,CAAC,EAAE,MAAM,CAAC;QAEnC,UAAU,CAAC,EAAE,MAAM,CAAC;QAEpB,yBAAyB,CAAC,EAAE,MAAM,CAAC;KACpC;CACF;AAED,MAAM,WAAW,oBAAqB,SAAQ,gBAAgB;CAAG;AAEjE,yBAAiB,WAAW,CAAC;IAC3B,MAAM,QAAQ,uBAAuB,GAAG,cAAc,CAAC,uBAAuB,CAAC;IAC/E,MAAM,QAAQ,4BAA4B,GAAG,cAAc,CAAC,4BAA4B,CAAC;IACzF,MAAM,QAAQ,oBAAoB,GAAG,cAAc,CAAC,oBAAoB,CAAC;CAC1E"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/fine-tuning/jobs/checkpoints.js b/backend/node_modules/openai/resources/fine-tuning/jobs/checkpoints.js new file mode 100644 index 0000000000000000000000000000000000000000..9d6fec88d61b6bb418b97d5daaa1c2c08c9f677f --- /dev/null +++ b/backend/node_modules/openai/resources/fine-tuning/jobs/checkpoints.js @@ -0,0 +1,47 @@ +"use strict"; +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FineTuningJobCheckpointsPage = exports.Checkpoints = void 0; +const resource_1 = require("openai/resource"); +const core_1 = require("openai/core"); +const CheckpointsAPI = __importStar(require("openai/resources/fine-tuning/jobs/checkpoints")); +const pagination_1 = require("openai/pagination"); +class Checkpoints extends resource_1.APIResource { + list(fineTuningJobId, query = {}, options) { + if ((0, core_1.isRequestOptions)(query)) { + return this.list(fineTuningJobId, {}, query); + } + return this._client.getAPIList(`/fine_tuning/jobs/${fineTuningJobId}/checkpoints`, FineTuningJobCheckpointsPage, { query, ...options }); + } +} +exports.Checkpoints = Checkpoints; +class FineTuningJobCheckpointsPage extends pagination_1.CursorPage { +} +exports.FineTuningJobCheckpointsPage = FineTuningJobCheckpointsPage; +(function (Checkpoints) { + Checkpoints.FineTuningJobCheckpointsPage = CheckpointsAPI.FineTuningJobCheckpointsPage; +})(Checkpoints = exports.Checkpoints || (exports.Checkpoints = {})); +//# sourceMappingURL=checkpoints.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/fine-tuning/jobs/checkpoints.js.map b/backend/node_modules/openai/resources/fine-tuning/jobs/checkpoints.js.map new file mode 100644 index 0000000000000000000000000000000000000000..d5e1df15c2d6f2e26c2624d67e438c9b1bd6e4ce --- /dev/null +++ b/backend/node_modules/openai/resources/fine-tuning/jobs/checkpoints.js.map @@ -0,0 +1 @@ +{"version":3,"file":"checkpoints.js","sourceRoot":"","sources":["../../../src/resources/fine-tuning/jobs/checkpoints.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;;;;;;;;;;;;;;;;;;;;;;;;AAGtF,8CAA8C;AAC9C,sCAA+C;AAC/C,8FAAgF;AAChF,kDAAsE;AAEtE,MAAa,WAAY,SAAQ,sBAAW;IAa1C,IAAI,CACF,eAAuB,EACvB,QAAoD,EAAE,EACtD,OAA6B;QAE7B,IAAI,IAAA,uBAAgB,EAAC,KAAK,CAAC,EAAE;YAC3B,OAAO,IAAI,CAAC,IAAI,CAAC,eAAe,EAAE,EAAE,EAAE,KAAK,CAAC,CAAC;SAC9C;QACD,OAAO,IAAI,CAAC,OAAO,CAAC,UAAU,CAC5B,qBAAqB,eAAe,cAAc,EAClD,4BAA4B,EAC5B,EAAE,KAAK,EAAE,GAAG,OAAO,EAAE,CACtB,CAAC;IACJ,CAAC;CACF;AA3BD,kCA2BC;AAED,MAAa,4BAA6B,SAAQ,uBAAmC;CAAG;AAAxF,oEAAwF;AAkExF,WAAiB,WAAW;IAEZ,wCAA4B,GAAG,cAAc,CAAC,4BAA4B,CAAC;AAE3F,CAAC,EAJgB,WAAW,GAAX,mBAAW,KAAX,mBAAW,QAI3B"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/fine-tuning/jobs/checkpoints.mjs b/backend/node_modules/openai/resources/fine-tuning/jobs/checkpoints.mjs new file mode 100644 index 0000000000000000000000000000000000000000..e3e134594d0d839b4691101eedb773b40c85df69 --- /dev/null +++ b/backend/node_modules/openai/resources/fine-tuning/jobs/checkpoints.mjs @@ -0,0 +1,19 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +import { APIResource } from 'openai/resource'; +import { isRequestOptions } from 'openai/core'; +import * as CheckpointsAPI from 'openai/resources/fine-tuning/jobs/checkpoints'; +import { CursorPage } from 'openai/pagination'; +export class Checkpoints extends APIResource { + list(fineTuningJobId, query = {}, options) { + if (isRequestOptions(query)) { + return this.list(fineTuningJobId, {}, query); + } + return this._client.getAPIList(`/fine_tuning/jobs/${fineTuningJobId}/checkpoints`, FineTuningJobCheckpointsPage, { query, ...options }); + } +} +export class FineTuningJobCheckpointsPage extends CursorPage { +} +(function (Checkpoints) { + Checkpoints.FineTuningJobCheckpointsPage = CheckpointsAPI.FineTuningJobCheckpointsPage; +})(Checkpoints || (Checkpoints = {})); +//# sourceMappingURL=checkpoints.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/fine-tuning/jobs/checkpoints.mjs.map b/backend/node_modules/openai/resources/fine-tuning/jobs/checkpoints.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..427f9b88754518a5c2348ff92c3353a1b3cb2f38 --- /dev/null +++ b/backend/node_modules/openai/resources/fine-tuning/jobs/checkpoints.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"checkpoints.mjs","sourceRoot":"","sources":["../../../src/resources/fine-tuning/jobs/checkpoints.ts"],"names":[],"mappings":"AAAA,sFAAsF;OAG/E,EAAE,WAAW,EAAE,MAAM,iBAAiB;OACtC,EAAE,gBAAgB,EAAE,MAAM,aAAa;OACvC,KAAK,cAAc,MAAM,+CAA+C;OACxE,EAAE,UAAU,EAAyB,MAAM,mBAAmB;AAErE,MAAM,OAAO,WAAY,SAAQ,WAAW;IAa1C,IAAI,CACF,eAAuB,EACvB,QAAoD,EAAE,EACtD,OAA6B;QAE7B,IAAI,gBAAgB,CAAC,KAAK,CAAC,EAAE;YAC3B,OAAO,IAAI,CAAC,IAAI,CAAC,eAAe,EAAE,EAAE,EAAE,KAAK,CAAC,CAAC;SAC9C;QACD,OAAO,IAAI,CAAC,OAAO,CAAC,UAAU,CAC5B,qBAAqB,eAAe,cAAc,EAClD,4BAA4B,EAC5B,EAAE,KAAK,EAAE,GAAG,OAAO,EAAE,CACtB,CAAC;IACJ,CAAC;CACF;AAED,MAAM,OAAO,4BAA6B,SAAQ,UAAmC;CAAG;AAkExF,WAAiB,WAAW;IAEZ,wCAA4B,GAAG,cAAc,CAAC,4BAA4B,CAAC;AAE3F,CAAC,EAJgB,WAAW,KAAX,WAAW,QAI3B"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/fine-tuning/jobs/index.d.ts b/backend/node_modules/openai/resources/fine-tuning/jobs/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d42796acf120700c16308c1e901a45b5160c4140 --- /dev/null +++ b/backend/node_modules/openai/resources/fine-tuning/jobs/index.d.ts @@ -0,0 +1,3 @@ +export { FineTuningJob, FineTuningJobEvent, FineTuningJobIntegration, FineTuningJobWandbIntegration, FineTuningJobWandbIntegrationObject, JobCreateParams, JobListParams, JobListEventsParams, FineTuningJobsPage, FineTuningJobEventsPage, Jobs, } from "./jobs.js"; +export { FineTuningJobCheckpoint, CheckpointListParams, FineTuningJobCheckpointsPage, Checkpoints, } from "./checkpoints.js"; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/fine-tuning/jobs/index.d.ts.map b/backend/node_modules/openai/resources/fine-tuning/jobs/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..228d0f132bb0ef16da61c5003339dc862cbb8af3 --- /dev/null +++ b/backend/node_modules/openai/resources/fine-tuning/jobs/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/resources/fine-tuning/jobs/index.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,aAAa,EACb,kBAAkB,EAClB,wBAAwB,EACxB,6BAA6B,EAC7B,mCAAmC,EACnC,eAAe,EACf,aAAa,EACb,mBAAmB,EACnB,kBAAkB,EAClB,uBAAuB,EACvB,IAAI,GACL,MAAM,QAAQ,CAAC;AAChB,OAAO,EACL,uBAAuB,EACvB,oBAAoB,EACpB,4BAA4B,EAC5B,WAAW,GACZ,MAAM,eAAe,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/fine-tuning/jobs/index.js b/backend/node_modules/openai/resources/fine-tuning/jobs/index.js new file mode 100644 index 0000000000000000000000000000000000000000..b1ebfe9e600d90f1b7f1d126cd9682c0e902387a --- /dev/null +++ b/backend/node_modules/openai/resources/fine-tuning/jobs/index.js @@ -0,0 +1,12 @@ +"use strict"; +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Checkpoints = exports.FineTuningJobCheckpointsPage = exports.Jobs = exports.FineTuningJobEventsPage = exports.FineTuningJobsPage = void 0; +var jobs_1 = require("./jobs.js"); +Object.defineProperty(exports, "FineTuningJobsPage", { enumerable: true, get: function () { return jobs_1.FineTuningJobsPage; } }); +Object.defineProperty(exports, "FineTuningJobEventsPage", { enumerable: true, get: function () { return jobs_1.FineTuningJobEventsPage; } }); +Object.defineProperty(exports, "Jobs", { enumerable: true, get: function () { return jobs_1.Jobs; } }); +var checkpoints_1 = require("./checkpoints.js"); +Object.defineProperty(exports, "FineTuningJobCheckpointsPage", { enumerable: true, get: function () { return checkpoints_1.FineTuningJobCheckpointsPage; } }); +Object.defineProperty(exports, "Checkpoints", { enumerable: true, get: function () { return checkpoints_1.Checkpoints; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/fine-tuning/jobs/index.js.map b/backend/node_modules/openai/resources/fine-tuning/jobs/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..a9b1d7da856648471602cfbc910c1f79479dfd49 --- /dev/null +++ b/backend/node_modules/openai/resources/fine-tuning/jobs/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/resources/fine-tuning/jobs/index.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;AAEtF,kCAYgB;AAHd,0GAAA,kBAAkB,OAAA;AAClB,+GAAA,uBAAuB,OAAA;AACvB,4FAAA,IAAI,OAAA;AAEN,gDAKuB;AAFrB,2HAAA,4BAA4B,OAAA;AAC5B,0GAAA,WAAW,OAAA"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/fine-tuning/jobs/index.mjs b/backend/node_modules/openai/resources/fine-tuning/jobs/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..9d575e0aa359028c5d5dc2ae6d487637774235a6 --- /dev/null +++ b/backend/node_modules/openai/resources/fine-tuning/jobs/index.mjs @@ -0,0 +1,4 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +export { FineTuningJobsPage, FineTuningJobEventsPage, Jobs, } from "./jobs.mjs"; +export { FineTuningJobCheckpointsPage, Checkpoints, } from "./checkpoints.mjs"; +//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/fine-tuning/jobs/index.mjs.map b/backend/node_modules/openai/resources/fine-tuning/jobs/index.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..fb4a2b8e820265b56b373a7d1d8bd8c7a9d2828a --- /dev/null +++ b/backend/node_modules/openai/resources/fine-tuning/jobs/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"index.mjs","sourceRoot":"","sources":["../../../src/resources/fine-tuning/jobs/index.ts"],"names":[],"mappings":"AAAA,sFAAsF;OAE/E,EASL,kBAAkB,EAClB,uBAAuB,EACvB,IAAI,GACL;OACM,EAGL,4BAA4B,EAC5B,WAAW,GACZ"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/fine-tuning/jobs/jobs.d.ts b/backend/node_modules/openai/resources/fine-tuning/jobs/jobs.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d8b8105b3305e4e2a31db52cbb984c86cf69b018 --- /dev/null +++ b/backend/node_modules/openai/resources/fine-tuning/jobs/jobs.d.ts @@ -0,0 +1,357 @@ +import * as Core from 'openai/core'; +import { APIResource } from 'openai/resource'; +import * as JobsAPI from 'openai/resources/fine-tuning/jobs/jobs'; +import * as CheckpointsAPI from 'openai/resources/fine-tuning/jobs/checkpoints'; +import { CursorPage, type CursorPageParams } from 'openai/pagination'; +export declare class Jobs extends APIResource { + checkpoints: CheckpointsAPI.Checkpoints; + /** + * Creates a fine-tuning job which begins the process of creating a new model from + * a given dataset. + * + * Response includes details of the enqueued job including job status and the name + * of the fine-tuned models once complete. + * + * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/fine-tuning) + */ + create(body: JobCreateParams, options?: Core.RequestOptions): Core.APIPromise; + /** + * Get info about a fine-tuning job. + * + * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/fine-tuning) + */ + retrieve(fineTuningJobId: string, options?: Core.RequestOptions): Core.APIPromise; + /** + * List your organization's fine-tuning jobs + */ + list(query?: JobListParams, options?: Core.RequestOptions): Core.PagePromise; + list(options?: Core.RequestOptions): Core.PagePromise; + /** + * Immediately cancel a fine-tune job. + */ + cancel(fineTuningJobId: string, options?: Core.RequestOptions): Core.APIPromise; + /** + * Get status updates for a fine-tuning job. + */ + listEvents(fineTuningJobId: string, query?: JobListEventsParams, options?: Core.RequestOptions): Core.PagePromise; + listEvents(fineTuningJobId: string, options?: Core.RequestOptions): Core.PagePromise; +} +export declare class FineTuningJobsPage extends CursorPage { +} +export declare class FineTuningJobEventsPage extends CursorPage { +} +/** + * The `fine_tuning.job` object represents a fine-tuning job that has been created + * through the API. + */ +export interface FineTuningJob { + /** + * The object identifier, which can be referenced in the API endpoints. + */ + id: string; + /** + * The Unix timestamp (in seconds) for when the fine-tuning job was created. + */ + created_at: number; + /** + * For fine-tuning jobs that have `failed`, this will contain more information on + * the cause of the failure. + */ + error: FineTuningJob.Error | null; + /** + * The name of the fine-tuned model that is being created. The value will be null + * if the fine-tuning job is still running. + */ + fine_tuned_model: string | null; + /** + * The Unix timestamp (in seconds) for when the fine-tuning job was finished. The + * value will be null if the fine-tuning job is still running. + */ + finished_at: number | null; + /** + * The hyperparameters used for the fine-tuning job. See the + * [fine-tuning guide](https://platform.openai.com/docs/guides/fine-tuning) for + * more details. + */ + hyperparameters: FineTuningJob.Hyperparameters; + /** + * The base model that is being fine-tuned. + */ + model: string; + /** + * The object type, which is always "fine_tuning.job". + */ + object: 'fine_tuning.job'; + /** + * The organization that owns the fine-tuning job. + */ + organization_id: string; + /** + * The compiled results file ID(s) for the fine-tuning job. You can retrieve the + * results with the + * [Files API](https://platform.openai.com/docs/api-reference/files/retrieve-contents). + */ + result_files: Array; + /** + * The seed used for the fine-tuning job. + */ + seed: number; + /** + * The current status of the fine-tuning job, which can be either + * `validating_files`, `queued`, `running`, `succeeded`, `failed`, or `cancelled`. + */ + status: 'validating_files' | 'queued' | 'running' | 'succeeded' | 'failed' | 'cancelled'; + /** + * The total number of billable tokens processed by this fine-tuning job. The value + * will be null if the fine-tuning job is still running. + */ + trained_tokens: number | null; + /** + * The file ID used for training. You can retrieve the training data with the + * [Files API](https://platform.openai.com/docs/api-reference/files/retrieve-contents). + */ + training_file: string; + /** + * The file ID used for validation. You can retrieve the validation results with + * the + * [Files API](https://platform.openai.com/docs/api-reference/files/retrieve-contents). + */ + validation_file: string | null; + /** + * A list of integrations to enable for this fine-tuning job. + */ + integrations?: Array | null; +} +export declare namespace FineTuningJob { + /** + * For fine-tuning jobs that have `failed`, this will contain more information on + * the cause of the failure. + */ + interface Error { + /** + * A machine-readable error code. + */ + code: string; + /** + * A human-readable error message. + */ + message: string; + /** + * The parameter that was invalid, usually `training_file` or `validation_file`. + * This field will be null if the failure was not parameter-specific. + */ + param: string | null; + } + /** + * The hyperparameters used for the fine-tuning job. See the + * [fine-tuning guide](https://platform.openai.com/docs/guides/fine-tuning) for + * more details. + */ + interface Hyperparameters { + /** + * The number of epochs to train the model for. An epoch refers to one full cycle + * through the training dataset. "auto" decides the optimal number of epochs based + * on the size of the dataset. If setting the number manually, we support any + * number between 1 and 50 epochs. + */ + n_epochs: 'auto' | number; + } +} +/** + * Fine-tuning job event object + */ +export interface FineTuningJobEvent { + id: string; + created_at: number; + level: 'info' | 'warn' | 'error'; + message: string; + object: 'fine_tuning.job.event'; +} +export type FineTuningJobIntegration = FineTuningJobWandbIntegrationObject; +/** + * The settings for your integration with Weights and Biases. This payload + * specifies the project that metrics will be sent to. Optionally, you can set an + * explicit display name for your run, add tags to your run, and set a default + * entity (team, username, etc) to be associated with your run. + */ +export interface FineTuningJobWandbIntegration { + /** + * The name of the project that the new run will be created under. + */ + project: string; + /** + * The entity to use for the run. This allows you to set the team or username of + * the WandB user that you would like associated with the run. If not set, the + * default entity for the registered WandB API key is used. + */ + entity?: string | null; + /** + * A display name to set for the run. If not set, we will use the Job ID as the + * name. + */ + name?: string | null; + /** + * A list of tags to be attached to the newly created run. These tags are passed + * through directly to WandB. Some default tags are generated by OpenAI: + * "openai/finetune", "openai/{base-model}", "openai/{ftjob-abcdef}". + */ + tags?: Array; +} +export interface FineTuningJobWandbIntegrationObject { + /** + * The type of the integration being enabled for the fine-tuning job + */ + type: 'wandb'; + /** + * The settings for your integration with Weights and Biases. This payload + * specifies the project that metrics will be sent to. Optionally, you can set an + * explicit display name for your run, add tags to your run, and set a default + * entity (team, username, etc) to be associated with your run. + */ + wandb: FineTuningJobWandbIntegration; +} +export interface JobCreateParams { + /** + * The name of the model to fine-tune. You can select one of the + * [supported models](https://platform.openai.com/docs/guides/fine-tuning/what-models-can-be-fine-tuned). + */ + model: (string & {}) | 'babbage-002' | 'davinci-002' | 'gpt-3.5-turbo'; + /** + * The ID of an uploaded file that contains training data. + * + * See [upload file](https://platform.openai.com/docs/api-reference/files/upload) + * for how to upload a file. + * + * Your dataset must be formatted as a JSONL file. Additionally, you must upload + * your file with the purpose `fine-tune`. + * + * See the [fine-tuning guide](https://platform.openai.com/docs/guides/fine-tuning) + * for more details. + */ + training_file: string; + /** + * The hyperparameters used for the fine-tuning job. + */ + hyperparameters?: JobCreateParams.Hyperparameters; + /** + * A list of integrations to enable for your fine-tuning job. + */ + integrations?: Array | null; + /** + * The seed controls the reproducibility of the job. Passing in the same seed and + * job parameters should produce the same results, but may differ in rare cases. If + * a seed is not specified, one will be generated for you. + */ + seed?: number | null; + /** + * A string of up to 18 characters that will be added to your fine-tuned model + * name. + * + * For example, a `suffix` of "custom-model-name" would produce a model name like + * `ft:gpt-3.5-turbo:openai:custom-model-name:7p4lURel`. + */ + suffix?: string | null; + /** + * The ID of an uploaded file that contains validation data. + * + * If you provide this file, the data is used to generate validation metrics + * periodically during fine-tuning. These metrics can be viewed in the fine-tuning + * results file. The same data should not be present in both train and validation + * files. + * + * Your dataset must be formatted as a JSONL file. You must upload your file with + * the purpose `fine-tune`. + * + * See the [fine-tuning guide](https://platform.openai.com/docs/guides/fine-tuning) + * for more details. + */ + validation_file?: string | null; +} +export declare namespace JobCreateParams { + /** + * The hyperparameters used for the fine-tuning job. + */ + interface Hyperparameters { + /** + * Number of examples in each batch. A larger batch size means that model + * parameters are updated less frequently, but with lower variance. + */ + batch_size?: 'auto' | number; + /** + * Scaling factor for the learning rate. A smaller learning rate may be useful to + * avoid overfitting. + */ + learning_rate_multiplier?: 'auto' | number; + /** + * The number of epochs to train the model for. An epoch refers to one full cycle + * through the training dataset. + */ + n_epochs?: 'auto' | number; + } + interface Integration { + /** + * The type of integration to enable. Currently, only "wandb" (Weights and Biases) + * is supported. + */ + type: 'wandb'; + /** + * The settings for your integration with Weights and Biases. This payload + * specifies the project that metrics will be sent to. Optionally, you can set an + * explicit display name for your run, add tags to your run, and set a default + * entity (team, username, etc) to be associated with your run. + */ + wandb: Integration.Wandb; + } + namespace Integration { + /** + * The settings for your integration with Weights and Biases. This payload + * specifies the project that metrics will be sent to. Optionally, you can set an + * explicit display name for your run, add tags to your run, and set a default + * entity (team, username, etc) to be associated with your run. + */ + interface Wandb { + /** + * The name of the project that the new run will be created under. + */ + project: string; + /** + * The entity to use for the run. This allows you to set the team or username of + * the WandB user that you would like associated with the run. If not set, the + * default entity for the registered WandB API key is used. + */ + entity?: string | null; + /** + * A display name to set for the run. If not set, we will use the Job ID as the + * name. + */ + name?: string | null; + /** + * A list of tags to be attached to the newly created run. These tags are passed + * through directly to WandB. Some default tags are generated by OpenAI: + * "openai/finetune", "openai/{base-model}", "openai/{ftjob-abcdef}". + */ + tags?: Array; + } + } +} +export interface JobListParams extends CursorPageParams { +} +export interface JobListEventsParams extends CursorPageParams { +} +export declare namespace Jobs { + export import FineTuningJob = JobsAPI.FineTuningJob; + export import FineTuningJobEvent = JobsAPI.FineTuningJobEvent; + export import FineTuningJobIntegration = JobsAPI.FineTuningJobIntegration; + export import FineTuningJobWandbIntegration = JobsAPI.FineTuningJobWandbIntegration; + export import FineTuningJobWandbIntegrationObject = JobsAPI.FineTuningJobWandbIntegrationObject; + export import FineTuningJobsPage = JobsAPI.FineTuningJobsPage; + export import FineTuningJobEventsPage = JobsAPI.FineTuningJobEventsPage; + export import JobCreateParams = JobsAPI.JobCreateParams; + export import JobListParams = JobsAPI.JobListParams; + export import JobListEventsParams = JobsAPI.JobListEventsParams; + export import Checkpoints = CheckpointsAPI.Checkpoints; + export import FineTuningJobCheckpoint = CheckpointsAPI.FineTuningJobCheckpoint; + export import FineTuningJobCheckpointsPage = CheckpointsAPI.FineTuningJobCheckpointsPage; + export import CheckpointListParams = CheckpointsAPI.CheckpointListParams; +} +//# sourceMappingURL=jobs.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/fine-tuning/jobs/jobs.d.ts.map b/backend/node_modules/openai/resources/fine-tuning/jobs/jobs.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..8e31c88d1bc6ed7fb893ee9e6147086f592a096a --- /dev/null +++ b/backend/node_modules/openai/resources/fine-tuning/jobs/jobs.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"jobs.d.ts","sourceRoot":"","sources":["../../../src/resources/fine-tuning/jobs/jobs.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,IAAI,MAAM,aAAa,CAAC;AACpC,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAE9C,OAAO,KAAK,OAAO,MAAM,wCAAwC,CAAC;AAClE,OAAO,KAAK,cAAc,MAAM,+CAA+C,CAAC;AAChF,OAAO,EAAE,UAAU,EAAE,KAAK,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAEtE,qBAAa,IAAK,SAAQ,WAAW;IACnC,WAAW,EAAE,cAAc,CAAC,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AM,QAAQ,aAAa,GAAG,OAAO,CAAC,aAAa,CAAC;IACpD,MAAM,QAAQ,mBAAmB,GAAG,OAAO,CAAC,mBAAmB,CAAC;IAChE,MAAM,QAAQ,WAAW,GAAG,cAAc,CAAC,WAAW,CAAC;IACvD,MAAM,QAAQ,uBAAuB,GAAG,cAAc,CAAC,uBAAuB,CAAC;IAC/E,MAAM,QAAQ,4BAA4B,GAAG,cAAc,CAAC,4BAA4B,CAAC;IACzF,MAAM,QAAQ,oBAAoB,GAAG,cAAc,CAAC,oBAAoB,CAAC;CAC1E"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/fine-tuning/jobs/jobs.js b/backend/node_modules/openai/resources/fine-tuning/jobs/jobs.js new file mode 100644 index 0000000000000000000000000000000000000000..6b4b12b5a9fbfd8eebcfba1e1d160655b28f3b3b --- /dev/null +++ b/backend/node_modules/openai/resources/fine-tuning/jobs/jobs.js @@ -0,0 +1,93 @@ +"use strict"; +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FineTuningJobEventsPage = exports.FineTuningJobsPage = exports.Jobs = void 0; +const resource_1 = require("openai/resource"); +const core_1 = require("openai/core"); +const JobsAPI = __importStar(require("openai/resources/fine-tuning/jobs/jobs")); +const CheckpointsAPI = __importStar(require("openai/resources/fine-tuning/jobs/checkpoints")); +const pagination_1 = require("openai/pagination"); +class Jobs extends resource_1.APIResource { + constructor() { + super(...arguments); + this.checkpoints = new CheckpointsAPI.Checkpoints(this._client); + } + /** + * Creates a fine-tuning job which begins the process of creating a new model from + * a given dataset. + * + * Response includes details of the enqueued job including job status and the name + * of the fine-tuned models once complete. + * + * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/fine-tuning) + */ + create(body, options) { + return this._client.post('/fine_tuning/jobs', { body, ...options }); + } + /** + * Get info about a fine-tuning job. + * + * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/fine-tuning) + */ + retrieve(fineTuningJobId, options) { + return this._client.get(`/fine_tuning/jobs/${fineTuningJobId}`, options); + } + list(query = {}, options) { + if ((0, core_1.isRequestOptions)(query)) { + return this.list({}, query); + } + return this._client.getAPIList('/fine_tuning/jobs', FineTuningJobsPage, { query, ...options }); + } + /** + * Immediately cancel a fine-tune job. + */ + cancel(fineTuningJobId, options) { + return this._client.post(`/fine_tuning/jobs/${fineTuningJobId}/cancel`, options); + } + listEvents(fineTuningJobId, query = {}, options) { + if ((0, core_1.isRequestOptions)(query)) { + return this.listEvents(fineTuningJobId, {}, query); + } + return this._client.getAPIList(`/fine_tuning/jobs/${fineTuningJobId}/events`, FineTuningJobEventsPage, { + query, + ...options, + }); + } +} +exports.Jobs = Jobs; +class FineTuningJobsPage extends pagination_1.CursorPage { +} +exports.FineTuningJobsPage = FineTuningJobsPage; +class FineTuningJobEventsPage extends pagination_1.CursorPage { +} +exports.FineTuningJobEventsPage = FineTuningJobEventsPage; +(function (Jobs) { + Jobs.FineTuningJobsPage = JobsAPI.FineTuningJobsPage; + Jobs.FineTuningJobEventsPage = JobsAPI.FineTuningJobEventsPage; + Jobs.Checkpoints = CheckpointsAPI.Checkpoints; + Jobs.FineTuningJobCheckpointsPage = CheckpointsAPI.FineTuningJobCheckpointsPage; +})(Jobs = exports.Jobs || (exports.Jobs = {})); +//# sourceMappingURL=jobs.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/fine-tuning/jobs/jobs.js.map b/backend/node_modules/openai/resources/fine-tuning/jobs/jobs.js.map new file mode 100644 index 0000000000000000000000000000000000000000..b5e94e15a384f16f454a77c1c6c38f4f93d973ed --- /dev/null +++ b/backend/node_modules/openai/resources/fine-tuning/jobs/jobs.js.map @@ -0,0 +1 @@ +{"version":3,"file":"jobs.js","sourceRoot":"","sources":["../../../src/resources/fine-tuning/jobs/jobs.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;;;;;;;;;;;;;;;;;;;;;;;;AAGtF,8CAA8C;AAC9C,sCAA+C;AAC/C,gFAAkE;AAClE,8FAAgF;AAChF,kDAAsE;AAEtE,MAAa,IAAK,SAAQ,sBAAW;IAArC;;QACE,gBAAW,GAA+B,IAAI,cAAc,CAAC,WAAW,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IA0EzF,CAAC;IAxEC;;;;;;;;OAQG;IACH,MAAM,CAAC,IAAqB,EAAE,OAA6B;QACzD,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,mBAAmB,EAAE,EAAE,IAAI,EAAE,GAAG,OAAO,EAAE,CAAC,CAAC;IACtE,CAAC;IAED;;;;OAIG;IACH,QAAQ,CAAC,eAAuB,EAAE,OAA6B;QAC7D,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,qBAAqB,eAAe,EAAE,EAAE,OAAO,CAAC,CAAC;IAC3E,CAAC;IAUD,IAAI,CACF,QAA6C,EAAE,EAC/C,OAA6B;QAE7B,IAAI,IAAA,uBAAgB,EAAC,KAAK,CAAC,EAAE;YAC3B,OAAO,IAAI,CAAC,IAAI,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC;SAC7B;QACD,OAAO,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,mBAAmB,EAAE,kBAAkB,EAAE,EAAE,KAAK,EAAE,GAAG,OAAO,EAAE,CAAC,CAAC;IACjG,CAAC;IAED;;OAEG;IACH,MAAM,CAAC,eAAuB,EAAE,OAA6B;QAC3D,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,qBAAqB,eAAe,SAAS,EAAE,OAAO,CAAC,CAAC;IACnF,CAAC;IAcD,UAAU,CACR,eAAuB,EACvB,QAAmD,EAAE,EACrD,OAA6B;QAE7B,IAAI,IAAA,uBAAgB,EAAC,KAAK,CAAC,EAAE;YAC3B,OAAO,IAAI,CAAC,UAAU,CAAC,eAAe,EAAE,EAAE,EAAE,KAAK,CAAC,CAAC;SACpD;QACD,OAAO,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,qBAAqB,eAAe,SAAS,EAAE,uBAAuB,EAAE;YACrG,KAAK;YACL,GAAG,OAAO;SACX,CAAC,CAAC;IACL,CAAC;CACF;AA3ED,oBA2EC;AAED,MAAa,kBAAmB,SAAQ,uBAAyB;CAAG;AAApE,gDAAoE;AAEpE,MAAa,uBAAwB,SAAQ,uBAA8B;CAAG;AAA9E,0DAA8E;AA4V9E,WAAiB,IAAI;IAML,uBAAkB,GAAG,OAAO,CAAC,kBAAkB,CAAC;IAChD,4BAAuB,GAAG,OAAO,CAAC,uBAAuB,CAAC;IAI1D,gBAAW,GAAG,cAAc,CAAC,WAAW,CAAC;IAEzC,iCAA4B,GAAG,cAAc,CAAC,4BAA4B,CAAC;AAE3F,CAAC,EAfgB,IAAI,GAAJ,YAAI,KAAJ,YAAI,QAepB"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/fine-tuning/jobs/jobs.mjs b/backend/node_modules/openai/resources/fine-tuning/jobs/jobs.mjs new file mode 100644 index 0000000000000000000000000000000000000000..2400f11694aef9247922dd89d350edd4a1af1c0e --- /dev/null +++ b/backend/node_modules/openai/resources/fine-tuning/jobs/jobs.mjs @@ -0,0 +1,64 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +import { APIResource } from 'openai/resource'; +import { isRequestOptions } from 'openai/core'; +import * as JobsAPI from 'openai/resources/fine-tuning/jobs/jobs'; +import * as CheckpointsAPI from 'openai/resources/fine-tuning/jobs/checkpoints'; +import { CursorPage } from 'openai/pagination'; +export class Jobs extends APIResource { + constructor() { + super(...arguments); + this.checkpoints = new CheckpointsAPI.Checkpoints(this._client); + } + /** + * Creates a fine-tuning job which begins the process of creating a new model from + * a given dataset. + * + * Response includes details of the enqueued job including job status and the name + * of the fine-tuned models once complete. + * + * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/fine-tuning) + */ + create(body, options) { + return this._client.post('/fine_tuning/jobs', { body, ...options }); + } + /** + * Get info about a fine-tuning job. + * + * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/fine-tuning) + */ + retrieve(fineTuningJobId, options) { + return this._client.get(`/fine_tuning/jobs/${fineTuningJobId}`, options); + } + list(query = {}, options) { + if (isRequestOptions(query)) { + return this.list({}, query); + } + return this._client.getAPIList('/fine_tuning/jobs', FineTuningJobsPage, { query, ...options }); + } + /** + * Immediately cancel a fine-tune job. + */ + cancel(fineTuningJobId, options) { + return this._client.post(`/fine_tuning/jobs/${fineTuningJobId}/cancel`, options); + } + listEvents(fineTuningJobId, query = {}, options) { + if (isRequestOptions(query)) { + return this.listEvents(fineTuningJobId, {}, query); + } + return this._client.getAPIList(`/fine_tuning/jobs/${fineTuningJobId}/events`, FineTuningJobEventsPage, { + query, + ...options, + }); + } +} +export class FineTuningJobsPage extends CursorPage { +} +export class FineTuningJobEventsPage extends CursorPage { +} +(function (Jobs) { + Jobs.FineTuningJobsPage = JobsAPI.FineTuningJobsPage; + Jobs.FineTuningJobEventsPage = JobsAPI.FineTuningJobEventsPage; + Jobs.Checkpoints = CheckpointsAPI.Checkpoints; + Jobs.FineTuningJobCheckpointsPage = CheckpointsAPI.FineTuningJobCheckpointsPage; +})(Jobs || (Jobs = {})); +//# sourceMappingURL=jobs.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/fine-tuning/jobs/jobs.mjs.map b/backend/node_modules/openai/resources/fine-tuning/jobs/jobs.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..6bae2d55ddb37bb0cba7f4ead0eacc57952182ef --- /dev/null +++ b/backend/node_modules/openai/resources/fine-tuning/jobs/jobs.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"jobs.mjs","sourceRoot":"","sources":["../../../src/resources/fine-tuning/jobs/jobs.ts"],"names":[],"mappings":"AAAA,sFAAsF;OAG/E,EAAE,WAAW,EAAE,MAAM,iBAAiB;OACtC,EAAE,gBAAgB,EAAE,MAAM,aAAa;OACvC,KAAK,OAAO,MAAM,wCAAwC;OAC1D,KAAK,cAAc,MAAM,+CAA+C;OACxE,EAAE,UAAU,EAAyB,MAAM,mBAAmB;AAErE,MAAM,OAAO,IAAK,SAAQ,WAAW;IAArC;;QACE,gBAAW,GAA+B,IAAI,cAAc,CAAC,WAAW,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IA0EzF,CAAC;IAxEC;;;;;;;;OAQG;IACH,MAAM,CAAC,IAAqB,EAAE,OAA6B;QACzD,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,mBAAmB,EAAE,EAAE,IAAI,EAAE,GAAG,OAAO,EAAE,CAAC,CAAC;IACtE,CAAC;IAED;;;;OAIG;IACH,QAAQ,CAAC,eAAuB,EAAE,OAA6B;QAC7D,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,qBAAqB,eAAe,EAAE,EAAE,OAAO,CAAC,CAAC;IAC3E,CAAC;IAUD,IAAI,CACF,QAA6C,EAAE,EAC/C,OAA6B;QAE7B,IAAI,gBAAgB,CAAC,KAAK,CAAC,EAAE;YAC3B,OAAO,IAAI,CAAC,IAAI,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC;SAC7B;QACD,OAAO,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,mBAAmB,EAAE,kBAAkB,EAAE,EAAE,KAAK,EAAE,GAAG,OAAO,EAAE,CAAC,CAAC;IACjG,CAAC;IAED;;OAEG;IACH,MAAM,CAAC,eAAuB,EAAE,OAA6B;QAC3D,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,qBAAqB,eAAe,SAAS,EAAE,OAAO,CAAC,CAAC;IACnF,CAAC;IAcD,UAAU,CACR,eAAuB,EACvB,QAAmD,EAAE,EACrD,OAA6B;QAE7B,IAAI,gBAAgB,CAAC,KAAK,CAAC,EAAE;YAC3B,OAAO,IAAI,CAAC,UAAU,CAAC,eAAe,EAAE,EAAE,EAAE,KAAK,CAAC,CAAC;SACpD;QACD,OAAO,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,qBAAqB,eAAe,SAAS,EAAE,uBAAuB,EAAE;YACrG,KAAK;YACL,GAAG,OAAO;SACX,CAAC,CAAC;IACL,CAAC;CACF;AAED,MAAM,OAAO,kBAAmB,SAAQ,UAAyB;CAAG;AAEpE,MAAM,OAAO,uBAAwB,SAAQ,UAA8B;CAAG;AA4V9E,WAAiB,IAAI;IAML,uBAAkB,GAAG,OAAO,CAAC,kBAAkB,CAAC;IAChD,4BAAuB,GAAG,OAAO,CAAC,uBAAuB,CAAC;IAI1D,gBAAW,GAAG,cAAc,CAAC,WAAW,CAAC;IAEzC,iCAA4B,GAAG,cAAc,CAAC,4BAA4B,CAAC;AAE3F,CAAC,EAfgB,IAAI,KAAJ,IAAI,QAepB"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/images.d.ts b/backend/node_modules/openai/resources/images.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..56b70efc6e2085e89858c4b3fc0f080b971194d5 --- /dev/null +++ b/backend/node_modules/openai/resources/images.d.ts @@ -0,0 +1,174 @@ +import * as Core from 'openai/core'; +import { APIResource } from 'openai/resource'; +import * as ImagesAPI from 'openai/resources/images'; +import { type Uploadable } from 'openai/core'; +export declare class Images extends APIResource { + /** + * Creates a variation of a given image. + */ + createVariation(body: ImageCreateVariationParams, options?: Core.RequestOptions): Core.APIPromise; + /** + * Creates an edited or extended image given an original image and a prompt. + */ + edit(body: ImageEditParams, options?: Core.RequestOptions): Core.APIPromise; + /** + * Creates an image given a prompt. + */ + generate(body: ImageGenerateParams, options?: Core.RequestOptions): Core.APIPromise; +} +/** + * Represents the url or the content of an image generated by the OpenAI API. + */ +export interface Image { + /** + * The base64-encoded JSON of the generated image, if `response_format` is + * `b64_json`. + */ + b64_json?: string; + /** + * The prompt that was used to generate the image, if there was any revision to the + * prompt. + */ + revised_prompt?: string; + /** + * The URL of the generated image, if `response_format` is `url` (default). + */ + url?: string; +} +export interface ImagesResponse { + created: number; + data: Array; +} +export interface ImageCreateVariationParams { + /** + * The image to use as the basis for the variation(s). Must be a valid PNG file, + * less than 4MB, and square. + */ + image: Uploadable; + /** + * The model to use for image generation. Only `dall-e-2` is supported at this + * time. + */ + model?: (string & {}) | 'dall-e-2' | null; + /** + * The number of images to generate. Must be between 1 and 10. For `dall-e-3`, only + * `n=1` is supported. + */ + n?: number | null; + /** + * The format in which the generated images are returned. Must be one of `url` or + * `b64_json`. URLs are only valid for 60 minutes after the image has been + * generated. + */ + response_format?: 'url' | 'b64_json' | null; + /** + * The size of the generated images. Must be one of `256x256`, `512x512`, or + * `1024x1024`. + */ + size?: '256x256' | '512x512' | '1024x1024' | null; + /** + * A unique identifier representing your end-user, which can help OpenAI to monitor + * and detect abuse. + * [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + */ + user?: string; +} +export interface ImageEditParams { + /** + * The image to edit. Must be a valid PNG file, less than 4MB, and square. If mask + * is not provided, image must have transparency, which will be used as the mask. + */ + image: Uploadable; + /** + * A text description of the desired image(s). The maximum length is 1000 + * characters. + */ + prompt: string; + /** + * An additional image whose fully transparent areas (e.g. where alpha is zero) + * indicate where `image` should be edited. Must be a valid PNG file, less than + * 4MB, and have the same dimensions as `image`. + */ + mask?: Uploadable; + /** + * The model to use for image generation. Only `dall-e-2` is supported at this + * time. + */ + model?: (string & {}) | 'dall-e-2' | null; + /** + * The number of images to generate. Must be between 1 and 10. + */ + n?: number | null; + /** + * The format in which the generated images are returned. Must be one of `url` or + * `b64_json`. URLs are only valid for 60 minutes after the image has been + * generated. + */ + response_format?: 'url' | 'b64_json' | null; + /** + * The size of the generated images. Must be one of `256x256`, `512x512`, or + * `1024x1024`. + */ + size?: '256x256' | '512x512' | '1024x1024' | null; + /** + * A unique identifier representing your end-user, which can help OpenAI to monitor + * and detect abuse. + * [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + */ + user?: string; +} +export interface ImageGenerateParams { + /** + * A text description of the desired image(s). The maximum length is 1000 + * characters for `dall-e-2` and 4000 characters for `dall-e-3`. + */ + prompt: string; + /** + * The model to use for image generation. + */ + model?: (string & {}) | 'dall-e-2' | 'dall-e-3' | null; + /** + * The number of images to generate. Must be between 1 and 10. For `dall-e-3`, only + * `n=1` is supported. + */ + n?: number | null; + /** + * The quality of the image that will be generated. `hd` creates images with finer + * details and greater consistency across the image. This param is only supported + * for `dall-e-3`. + */ + quality?: 'standard' | 'hd'; + /** + * The format in which the generated images are returned. Must be one of `url` or + * `b64_json`. URLs are only valid for 60 minutes after the image has been + * generated. + */ + response_format?: 'url' | 'b64_json' | null; + /** + * The size of the generated images. Must be one of `256x256`, `512x512`, or + * `1024x1024` for `dall-e-2`. Must be one of `1024x1024`, `1792x1024`, or + * `1024x1792` for `dall-e-3` models. + */ + size?: '256x256' | '512x512' | '1024x1024' | '1792x1024' | '1024x1792' | null; + /** + * The style of the generated images. Must be one of `vivid` or `natural`. Vivid + * causes the model to lean towards generating hyper-real and dramatic images. + * Natural causes the model to produce more natural, less hyper-real looking + * images. This param is only supported for `dall-e-3`. + */ + style?: 'vivid' | 'natural' | null; + /** + * A unique identifier representing your end-user, which can help OpenAI to monitor + * and detect abuse. + * [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + */ + user?: string; +} +export declare namespace Images { + export import Image = ImagesAPI.Image; + export import ImagesResponse = ImagesAPI.ImagesResponse; + export import ImageCreateVariationParams = ImagesAPI.ImageCreateVariationParams; + export import ImageEditParams = ImagesAPI.ImageEditParams; + export import ImageGenerateParams = ImagesAPI.ImageGenerateParams; +} +//# sourceMappingURL=images.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/images.d.ts.map b/backend/node_modules/openai/resources/images.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..db84ba06eb351d14694328ff02fc919cc9683c06 --- /dev/null +++ b/backend/node_modules/openai/resources/images.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"images.d.ts","sourceRoot":"","sources":["../src/resources/images.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,IAAI,MAAM,aAAa,CAAC;AACpC,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAC9C,OAAO,KAAK,SAAS,MAAM,yBAAyB,CAAC;AACrD,OAAO,EAAE,KAAK,UAAU,EAA+B,MAAM,aAAa,CAAC;AAE3E,qBAAa,MAAO,SAAQ,WAAW;IACrC;;OAEG;IACH,eAAe,CACb,IAAI,EAAE,0BAA0B,EAChC,OAAO,CAAC,EAAE,IAAI,CAAC,cAAc,GAC5B,IAAI,CAAC,UAAU,CAAC,cAAc,CAAC;IAIlC;;OAEG;IACH,IAAI,CAAC,IAAI,EAAE,eAAe,EAAE,OAAO,CAAC,EAAE,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC,UAAU,CAAC,cAAc,CAAC;IAI3F;;OAEG;IACH,QAAQ,CAAC,IAAI,EAAE,mBAAmB,EAAE,OAAO,CAAC,EAAE,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC,UAAU,CAAC,cAAc,CAAC;CAGpG;AAED;;GAEG;AACH,MAAM,WAAW,KAAK;IACpB;;;OAGG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAElB;;;OAGG;IACH,cAAc,CAAC,EAA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;;OAEG;IACH,KAAK,CAAC,EAAE,CAAC,MAAM,GAAG,EAAE,CAAC,GAAG,UAAU,GAAG,UAAU,GAAG,IAAI,CAAC;IAEvD;;;OAGG;IACH,CAAC,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAElB;;;;OAIG;IACH,OAAO,CAAC,EAAE,UAAU,GAAG,IAAI,CAAC;IAE5B;;;;OAIG;IACH,eAAe,CAAC,EAAE,KAAK,GAAG,UAAU,GAAG,IAAI,CAAC;IAE5C;;;;OAIG;IACH,IAAI,CAAC,EAAE,SAAS,GAAG,SAAS,GAAG,WAAW,GAAG,WAAW,GAAG,WAAW,GAAG,IAAI,CAAC;IAE9E;;;;;OAKG;IACH,KAAK,CAAC,EAAE,OAAO,GAAG,SAAS,GAAG,IAAI,CAAC;IAEnC;;;;OAIG;IACH,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAED,yBAAiB,MAAM,CAAC;IACtB,MAAM,QAAQ,KAAK,GAAG,SAAS,CAAC,KAAK,CAAC;IACtC,MAAM,QAAQ,cAAc,GAAG,SAAS,CAAC,cAAc,CAAC;IACxD,MAAM,QAAQ,0BAA0B,GAAG,SAAS,CAAC,0BAA0B,CAAC;IAChF,MAAM,QAAQ,eAAe,GAAG,SAAS,CAAC,eAAe,CAAC;IAC1D,MAAM,QAAQ,mBAAmB,GAAG,SAAS,CAAC,mBAAmB,CAAC;CACnE"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/images.js b/backend/node_modules/openai/resources/images.js new file mode 100644 index 0000000000000000000000000000000000000000..56945a4c99fdd5959d3cb0aea98d9c647cc84bfe --- /dev/null +++ b/backend/node_modules/openai/resources/images.js @@ -0,0 +1,30 @@ +"use strict"; +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Images = void 0; +const resource_1 = require("openai/resource"); +const core_1 = require("openai/core"); +class Images extends resource_1.APIResource { + /** + * Creates a variation of a given image. + */ + createVariation(body, options) { + return this._client.post('/images/variations', (0, core_1.multipartFormRequestOptions)({ body, ...options })); + } + /** + * Creates an edited or extended image given an original image and a prompt. + */ + edit(body, options) { + return this._client.post('/images/edits', (0, core_1.multipartFormRequestOptions)({ body, ...options })); + } + /** + * Creates an image given a prompt. + */ + generate(body, options) { + return this._client.post('/images/generations', { body, ...options }); + } +} +exports.Images = Images; +(function (Images) { +})(Images = exports.Images || (exports.Images = {})); +//# sourceMappingURL=images.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/images.js.map b/backend/node_modules/openai/resources/images.js.map new file mode 100644 index 0000000000000000000000000000000000000000..e184713d7c99cae7fdbb37f06dca3164ebe5b85d --- /dev/null +++ b/backend/node_modules/openai/resources/images.js.map @@ -0,0 +1 @@ +{"version":3,"file":"images.js","sourceRoot":"","sources":["../src/resources/images.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;AAGtF,8CAA8C;AAE9C,sCAA2E;AAE3E,MAAa,MAAO,SAAQ,sBAAW;IACrC;;OAEG;IACH,eAAe,CACb,IAAgC,EAChC,OAA6B;QAE7B,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,oBAAoB,EAAE,IAAA,kCAA2B,EAAC,EAAE,IAAI,EAAE,GAAG,OAAO,EAAE,CAAC,CAAC,CAAC;IACpG,CAAC;IAED;;OAEG;IACH,IAAI,CAAC,IAAqB,EAAE,OAA6B;QACvD,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,eAAe,EAAE,IAAA,kCAA2B,EAAC,EAAE,IAAI,EAAE,GAAG,OAAO,EAAE,CAAC,CAAC,CAAC;IAC/F,CAAC;IAED;;OAEG;IACH,QAAQ,CAAC,IAAyB,EAAE,OAA6B;QAC/D,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,qBAAqB,EAAE,EAAE,IAAI,EAAE,GAAG,OAAO,EAAE,CAAC,CAAC;IACxE,CAAC;CACF;AAxBD,wBAwBC;AAiLD,WAAiB,MAAM;AAMvB,CAAC,EANgB,MAAM,GAAN,cAAM,KAAN,cAAM,QAMtB"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/images.mjs b/backend/node_modules/openai/resources/images.mjs new file mode 100644 index 0000000000000000000000000000000000000000..1fbc10d3c76ff69ed167f2a21c503020ffaf78ec --- /dev/null +++ b/backend/node_modules/openai/resources/images.mjs @@ -0,0 +1,26 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +import { APIResource } from 'openai/resource'; +import { multipartFormRequestOptions } from 'openai/core'; +export class Images extends APIResource { + /** + * Creates a variation of a given image. + */ + createVariation(body, options) { + return this._client.post('/images/variations', multipartFormRequestOptions({ body, ...options })); + } + /** + * Creates an edited or extended image given an original image and a prompt. + */ + edit(body, options) { + return this._client.post('/images/edits', multipartFormRequestOptions({ body, ...options })); + } + /** + * Creates an image given a prompt. + */ + generate(body, options) { + return this._client.post('/images/generations', { body, ...options }); + } +} +(function (Images) { +})(Images || (Images = {})); +//# sourceMappingURL=images.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/images.mjs.map b/backend/node_modules/openai/resources/images.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..304f4a5db7b281ae593e2c20f5e808b6fb71f9bd --- /dev/null +++ b/backend/node_modules/openai/resources/images.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"images.mjs","sourceRoot":"","sources":["../src/resources/images.ts"],"names":[],"mappings":"AAAA,sFAAsF;OAG/E,EAAE,WAAW,EAAE,MAAM,iBAAiB;OAEtC,EAAmB,2BAA2B,EAAE,MAAM,aAAa;AAE1E,MAAM,OAAO,MAAO,SAAQ,WAAW;IACrC;;OAEG;IACH,eAAe,CACb,IAAgC,EAChC,OAA6B;QAE7B,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,oBAAoB,EAAE,2BAA2B,CAAC,EAAE,IAAI,EAAE,GAAG,OAAO,EAAE,CAAC,CAAC,CAAC;IACpG,CAAC;IAED;;OAEG;IACH,IAAI,CAAC,IAAqB,EAAE,OAA6B;QACvD,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,eAAe,EAAE,2BAA2B,CAAC,EAAE,IAAI,EAAE,GAAG,OAAO,EAAE,CAAC,CAAC,CAAC;IAC/F,CAAC;IAED;;OAEG;IACH,QAAQ,CAAC,IAAyB,EAAE,OAA6B;QAC/D,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,qBAAqB,EAAE,EAAE,IAAI,EAAE,GAAG,OAAO,EAAE,CAAC,CAAC;IACxE,CAAC;CACF;AAiLD,WAAiB,MAAM;AAMvB,CAAC,EANgB,MAAM,KAAN,MAAM,QAMtB"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/index.d.ts b/backend/node_modules/openai/resources/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..59078f33167469c4d0d17a838d7ca2048fffc43a --- /dev/null +++ b/backend/node_modules/openai/resources/index.d.ts @@ -0,0 +1,13 @@ +export * from "./chat/index.js"; +export * from "./shared.js"; +export { Audio } from "./audio/audio.js"; +export { Batch, BatchError, BatchRequestCounts, BatchCreateParams, Batches } from "./batches.js"; +export { Beta } from "./beta/beta.js"; +export { Completion, CompletionChoice, CompletionUsage, CompletionCreateParams, CompletionCreateParamsNonStreaming, CompletionCreateParamsStreaming, Completions, } from "./completions.js"; +export { CreateEmbeddingResponse, Embedding, EmbeddingCreateParams, Embeddings } from "./embeddings.js"; +export { FileContent, FileDeleted, FileObject, FileCreateParams, FileListParams, FileObjectsPage, Files, } from "./files.js"; +export { FineTuning } from "./fine-tuning/fine-tuning.js"; +export { Image, ImagesResponse, ImageCreateVariationParams, ImageEditParams, ImageGenerateParams, Images, } from "./images.js"; +export { Model, ModelDeleted, ModelsPage, Models } from "./models.js"; +export { Moderation, ModerationCreateResponse, ModerationCreateParams, Moderations } from "./moderations.js"; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/index.d.ts.map b/backend/node_modules/openai/resources/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..5504f9baade123caeb7f2f362783b9011664c455 --- /dev/null +++ b/backend/node_modules/openai/resources/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/resources/index.ts"],"names":[],"mappings":"AAEA,cAAc,cAAc,CAAC;AAC7B,cAAc,UAAU,CAAC;AACzB,OAAO,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AACtC,OAAO,EAAE,KAAK,EAAE,UAAU,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC9F,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAC;AACnC,OAAO,EACL,UAAU,EACV,gBAAgB,EAChB,eAAe,EACf,sBAAsB,EACtB,kCAAkC,EAClC,+BAA+B,EAC/B,WAAW,GACZ,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,uBAAuB,EAAE,SAAS,EAAE,qBAAqB,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AACrG,OAAO,EACL,WAAW,EACX,WAAW,EACX,UAAU,EACV,gBAAgB,EAChB,cAAc,EACd,eAAe,EACf,KAAK,GACN,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAC;AACvD,OAAO,EACL,KAAK,EACL,cAAc,EACd,0BAA0B,EAC1B,eAAe,EACf,mBAAmB,EACnB,MAAM,GACP,MAAM,UAAU,CAAC;AAClB,OAAO,EAAE,KAAK,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AACnE,OAAO,EAAE,UAAU,EAAE,wBAAwB,EAAE,sBAAsB,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/index.js b/backend/node_modules/openai/resources/index.js new file mode 100644 index 0000000000000000000000000000000000000000..adc5aed5ab73f5efab2d764e2097d8c6065109b3 --- /dev/null +++ b/backend/node_modules/openai/resources/index.js @@ -0,0 +1,43 @@ +"use strict"; +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Moderations = exports.Models = exports.ModelsPage = exports.Images = exports.FineTuning = exports.Files = exports.FileObjectsPage = exports.Embeddings = exports.Completions = exports.Beta = exports.Batches = exports.Audio = void 0; +__exportStar(require("./chat/index.js"), exports); +__exportStar(require("./shared.js"), exports); +var audio_1 = require("./audio/audio.js"); +Object.defineProperty(exports, "Audio", { enumerable: true, get: function () { return audio_1.Audio; } }); +var batches_1 = require("./batches.js"); +Object.defineProperty(exports, "Batches", { enumerable: true, get: function () { return batches_1.Batches; } }); +var beta_1 = require("./beta/beta.js"); +Object.defineProperty(exports, "Beta", { enumerable: true, get: function () { return beta_1.Beta; } }); +var completions_1 = require("./completions.js"); +Object.defineProperty(exports, "Completions", { enumerable: true, get: function () { return completions_1.Completions; } }); +var embeddings_1 = require("./embeddings.js"); +Object.defineProperty(exports, "Embeddings", { enumerable: true, get: function () { return embeddings_1.Embeddings; } }); +var files_1 = require("./files.js"); +Object.defineProperty(exports, "FileObjectsPage", { enumerable: true, get: function () { return files_1.FileObjectsPage; } }); +Object.defineProperty(exports, "Files", { enumerable: true, get: function () { return files_1.Files; } }); +var fine_tuning_1 = require("./fine-tuning/fine-tuning.js"); +Object.defineProperty(exports, "FineTuning", { enumerable: true, get: function () { return fine_tuning_1.FineTuning; } }); +var images_1 = require("./images.js"); +Object.defineProperty(exports, "Images", { enumerable: true, get: function () { return images_1.Images; } }); +var models_1 = require("./models.js"); +Object.defineProperty(exports, "ModelsPage", { enumerable: true, get: function () { return models_1.ModelsPage; } }); +Object.defineProperty(exports, "Models", { enumerable: true, get: function () { return models_1.Models; } }); +var moderations_1 = require("./moderations.js"); +Object.defineProperty(exports, "Moderations", { enumerable: true, get: function () { return moderations_1.Moderations; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/index.js.map b/backend/node_modules/openai/resources/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..55f8891893a543f24dc18ec710e519e5bd4a765f --- /dev/null +++ b/backend/node_modules/openai/resources/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/resources/index.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;;;;;;;;;;;;;;;AAEtF,kDAA6B;AAC7B,8CAAyB;AACzB,0CAAsC;AAA7B,8FAAA,KAAK,OAAA;AACd,wCAA8F;AAA3B,kGAAA,OAAO,OAAA;AAC1E,uCAAmC;AAA1B,4FAAA,IAAI,OAAA;AACb,gDAQuB;AADrB,0GAAA,WAAW,OAAA;AAEb,8CAAqG;AAAjC,wGAAA,UAAU,OAAA;AAC9E,oCAQiB;AAFf,wGAAA,eAAe,OAAA;AACf,8FAAA,KAAK,OAAA;AAEP,4DAAuD;AAA9C,yGAAA,UAAU,OAAA;AACnB,sCAOkB;AADhB,gGAAA,MAAM,OAAA;AAER,sCAAmE;AAArC,oGAAA,UAAU,OAAA;AAAE,gGAAA,MAAM,OAAA;AAChD,gDAA0G;AAAnC,0GAAA,WAAW,OAAA"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/index.mjs b/backend/node_modules/openai/resources/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..40c1aa7c8ab02723083e90d5fe3c574a6dbd3cbb --- /dev/null +++ b/backend/node_modules/openai/resources/index.mjs @@ -0,0 +1,14 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +export * from "./chat/index.mjs"; +export * from "./shared.mjs"; +export { Audio } from "./audio/audio.mjs"; +export { Batches } from "./batches.mjs"; +export { Beta } from "./beta/beta.mjs"; +export { Completions, } from "./completions.mjs"; +export { Embeddings } from "./embeddings.mjs"; +export { FileObjectsPage, Files, } from "./files.mjs"; +export { FineTuning } from "./fine-tuning/fine-tuning.mjs"; +export { Images, } from "./images.mjs"; +export { ModelsPage, Models } from "./models.mjs"; +export { Moderations } from "./moderations.mjs"; +//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/index.mjs.map b/backend/node_modules/openai/resources/index.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..de3e7282a426e20f997d125bea84716f5a6ee5fc --- /dev/null +++ b/backend/node_modules/openai/resources/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"index.mjs","sourceRoot":"","sources":["../src/resources/index.ts"],"names":[],"mappings":"AAAA,sFAAsF;;;OAI/E,EAAE,KAAK,EAAE;OACT,EAA4D,OAAO,EAAE;OACrE,EAAE,IAAI,EAAE;OACR,EAOL,WAAW,GACZ;OACM,EAA6D,UAAU,EAAE;OACzE,EAML,eAAe,EACf,KAAK,GACN;OACM,EAAE,UAAU,EAAE;OACd,EAML,MAAM,GACP;OACM,EAAuB,UAAU,EAAE,MAAM,EAAE;OAC3C,EAAgE,WAAW,EAAE"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/models.d.ts b/backend/node_modules/openai/resources/models.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b01dce83570a4c8cf14bef30d374db41a3eb1cbc --- /dev/null +++ b/backend/node_modules/openai/resources/models.d.ts @@ -0,0 +1,58 @@ +import * as Core from 'openai/core'; +import { APIResource } from 'openai/resource'; +import * as ModelsAPI from 'openai/resources/models'; +import { Page } from 'openai/pagination'; +export declare class Models extends APIResource { + /** + * Retrieves a model instance, providing basic information about the model such as + * the owner and permissioning. + */ + retrieve(model: string, options?: Core.RequestOptions): Core.APIPromise; + /** + * Lists the currently available models, and provides basic information about each + * one such as the owner and availability. + */ + list(options?: Core.RequestOptions): Core.PagePromise; + /** + * Delete a fine-tuned model. You must have the Owner role in your organization to + * delete a model. + */ + del(model: string, options?: Core.RequestOptions): Core.APIPromise; +} +/** + * Note: no pagination actually occurs yet, this is for forwards-compatibility. + */ +export declare class ModelsPage extends Page { +} +/** + * Describes an OpenAI model offering that can be used with the API. + */ +export interface Model { + /** + * The model identifier, which can be referenced in the API endpoints. + */ + id: string; + /** + * The Unix timestamp (in seconds) when the model was created. + */ + created: number; + /** + * The object type, which is always "model". + */ + object: 'model'; + /** + * The organization that owns the model. + */ + owned_by: string; +} +export interface ModelDeleted { + id: string; + deleted: boolean; + object: string; +} +export declare namespace Models { + export import Model = ModelsAPI.Model; + export import ModelDeleted = ModelsAPI.ModelDeleted; + export import ModelsPage = ModelsAPI.ModelsPage; +} +//# sourceMappingURL=models.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/models.d.ts.map b/backend/node_modules/openai/resources/models.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..77599a02f2d36566b8e7268b9f75bab0d5600486 --- /dev/null +++ b/backend/node_modules/openai/resources/models.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"models.d.ts","sourceRoot":"","sources":["../src/resources/models.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,IAAI,MAAM,aAAa,CAAC;AACpC,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAC9C,OAAO,KAAK,SAAS,MAAM,yBAAyB,CAAC;AACrD,OAAO,EAAE,IAAI,EAAE,MAAM,mBAAmB,CAAC;AAEzC,qBAAa,MAAO,SAAQ,WAAW;IACrC;;;OAGG;IACH,QAAQ,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC;IAI9E;;;OAGG;IACH,IAAI,CAAC,OAAO,CAAC,EAAE,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC,WAAW,CAAC,UAAU,EAAE,KAAK,CAAC;IAIxE;;;OAGG;IACH,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC,UAAU,CAAC,YAAY,CAAC;CAGjF;AAED;;GAEG;AACH,qBAAa,UAAW,SAAQ,IAAI,CAAC,KAAK,CAAC;CAAG;AAE9C;;GAEG;AACH,MAAM,WAAW,KAAK;IACpB;;OAEG;IACH,EAAE,EAAE,MAAM,CAAC;IAEX;;OAEG;IACH,OAAO,EAAE,MAAM,CAAC;IAEhB;;OAEG;IACH,MAAM,EAAE,OAAO,CAAC;IAEhB;;OAEG;IACH,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,YAAY;IAC3B,EAAE,EAAE,MAAM,CAAC;IAEX,OAAO,EAAE,OAAO,CAAC;IAEjB,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,yBAAiB,MAAM,CAAC;IACtB,MAAM,QAAQ,KAAK,GAAG,SAAS,CAAC,KAAK,CAAC;IACtC,MAAM,QAAQ,YAAY,GAAG,SAAS,CAAC,YAAY,CAAC;IACpD,MAAM,QAAQ,UAAU,GAAG,SAAS,CAAC,UAAU,CAAC;CACjD"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/models.js b/backend/node_modules/openai/resources/models.js new file mode 100644 index 0000000000000000000000000000000000000000..75b99567b8d2e8420d4e74c7920a10352deda47e --- /dev/null +++ b/backend/node_modules/openai/resources/models.js @@ -0,0 +1,64 @@ +"use strict"; +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ModelsPage = exports.Models = void 0; +const resource_1 = require("openai/resource"); +const ModelsAPI = __importStar(require("openai/resources/models")); +const pagination_1 = require("openai/pagination"); +class Models extends resource_1.APIResource { + /** + * Retrieves a model instance, providing basic information about the model such as + * the owner and permissioning. + */ + retrieve(model, options) { + return this._client.get(`/models/${model}`, options); + } + /** + * Lists the currently available models, and provides basic information about each + * one such as the owner and availability. + */ + list(options) { + return this._client.getAPIList('/models', ModelsPage, options); + } + /** + * Delete a fine-tuned model. You must have the Owner role in your organization to + * delete a model. + */ + del(model, options) { + return this._client.delete(`/models/${model}`, options); + } +} +exports.Models = Models; +/** + * Note: no pagination actually occurs yet, this is for forwards-compatibility. + */ +class ModelsPage extends pagination_1.Page { +} +exports.ModelsPage = ModelsPage; +(function (Models) { + Models.ModelsPage = ModelsAPI.ModelsPage; +})(Models = exports.Models || (exports.Models = {})); +//# sourceMappingURL=models.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/models.js.map b/backend/node_modules/openai/resources/models.js.map new file mode 100644 index 0000000000000000000000000000000000000000..ffe2420838bf111b5cf3f4c0da26c99fdc6b8c6c --- /dev/null +++ b/backend/node_modules/openai/resources/models.js.map @@ -0,0 +1 @@ +{"version":3,"file":"models.js","sourceRoot":"","sources":["../src/resources/models.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;;;;;;;;;;;;;;;;;;;;;;;;AAGtF,8CAA8C;AAC9C,mEAAqD;AACrD,kDAAyC;AAEzC,MAAa,MAAO,SAAQ,sBAAW;IACrC;;;OAGG;IACH,QAAQ,CAAC,KAAa,EAAE,OAA6B;QACnD,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,WAAW,KAAK,EAAE,EAAE,OAAO,CAAC,CAAC;IACvD,CAAC;IAED;;;OAGG;IACH,IAAI,CAAC,OAA6B;QAChC,OAAO,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,SAAS,EAAE,UAAU,EAAE,OAAO,CAAC,CAAC;IACjE,CAAC;IAED;;;OAGG;IACH,GAAG,CAAC,KAAa,EAAE,OAA6B;QAC9C,OAAO,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,WAAW,KAAK,EAAE,EAAE,OAAO,CAAC,CAAC;IAC1D,CAAC;CACF;AAxBD,wBAwBC;AAED;;GAEG;AACH,MAAa,UAAW,SAAQ,iBAAW;CAAG;AAA9C,gCAA8C;AAmC9C,WAAiB,MAAM;IAGP,iBAAU,GAAG,SAAS,CAAC,UAAU,CAAC;AAClD,CAAC,EAJgB,MAAM,GAAN,cAAM,KAAN,cAAM,QAItB"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/models.mjs b/backend/node_modules/openai/resources/models.mjs new file mode 100644 index 0000000000000000000000000000000000000000..38cff6f64de1ce20dec7930a5c4a4c4571e2a3d5 --- /dev/null +++ b/backend/node_modules/openai/resources/models.mjs @@ -0,0 +1,36 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +import { APIResource } from 'openai/resource'; +import * as ModelsAPI from 'openai/resources/models'; +import { Page } from 'openai/pagination'; +export class Models extends APIResource { + /** + * Retrieves a model instance, providing basic information about the model such as + * the owner and permissioning. + */ + retrieve(model, options) { + return this._client.get(`/models/${model}`, options); + } + /** + * Lists the currently available models, and provides basic information about each + * one such as the owner and availability. + */ + list(options) { + return this._client.getAPIList('/models', ModelsPage, options); + } + /** + * Delete a fine-tuned model. You must have the Owner role in your organization to + * delete a model. + */ + del(model, options) { + return this._client.delete(`/models/${model}`, options); + } +} +/** + * Note: no pagination actually occurs yet, this is for forwards-compatibility. + */ +export class ModelsPage extends Page { +} +(function (Models) { + Models.ModelsPage = ModelsAPI.ModelsPage; +})(Models || (Models = {})); +//# sourceMappingURL=models.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/models.mjs.map b/backend/node_modules/openai/resources/models.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..07d0df808f903141efec5e583ebd73b0653b3a40 --- /dev/null +++ b/backend/node_modules/openai/resources/models.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"models.mjs","sourceRoot":"","sources":["../src/resources/models.ts"],"names":[],"mappings":"AAAA,sFAAsF;OAG/E,EAAE,WAAW,EAAE,MAAM,iBAAiB;OACtC,KAAK,SAAS,MAAM,yBAAyB;OAC7C,EAAE,IAAI,EAAE,MAAM,mBAAmB;AAExC,MAAM,OAAO,MAAO,SAAQ,WAAW;IACrC;;;OAGG;IACH,QAAQ,CAAC,KAAa,EAAE,OAA6B;QACnD,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,WAAW,KAAK,EAAE,EAAE,OAAO,CAAC,CAAC;IACvD,CAAC;IAED;;;OAGG;IACH,IAAI,CAAC,OAA6B;QAChC,OAAO,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,SAAS,EAAE,UAAU,EAAE,OAAO,CAAC,CAAC;IACjE,CAAC;IAED;;;OAGG;IACH,GAAG,CAAC,KAAa,EAAE,OAA6B;QAC9C,OAAO,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,WAAW,KAAK,EAAE,EAAE,OAAO,CAAC,CAAC;IAC1D,CAAC;CACF;AAED;;GAEG;AACH,MAAM,OAAO,UAAW,SAAQ,IAAW;CAAG;AAmC9C,WAAiB,MAAM;IAGP,iBAAU,GAAG,SAAS,CAAC,UAAU,CAAC;AAClD,CAAC,EAJgB,MAAM,KAAN,MAAM,QAItB"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/moderations.d.ts b/backend/node_modules/openai/resources/moderations.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ac46f9033aef43dee55adba579809507a517812e --- /dev/null +++ b/backend/node_modules/openai/resources/moderations.d.ts @@ -0,0 +1,176 @@ +import * as Core from 'openai/core'; +import { APIResource } from 'openai/resource'; +import * as ModerationsAPI from 'openai/resources/moderations'; +export declare class Moderations extends APIResource { + /** + * Classifies if text is potentially harmful. + */ + create(body: ModerationCreateParams, options?: Core.RequestOptions): Core.APIPromise; +} +export interface Moderation { + /** + * A list of the categories, and whether they are flagged or not. + */ + categories: Moderation.Categories; + /** + * A list of the categories along with their scores as predicted by model. + */ + category_scores: Moderation.CategoryScores; + /** + * Whether any of the below categories are flagged. + */ + flagged: boolean; +} +export declare namespace Moderation { + /** + * A list of the categories, and whether they are flagged or not. + */ + interface Categories { + /** + * Content that expresses, incites, or promotes harassing language towards any + * target. + */ + harassment: boolean; + /** + * Harassment content that also includes violence or serious harm towards any + * target. + */ + 'harassment/threatening': boolean; + /** + * Content that expresses, incites, or promotes hate based on race, gender, + * ethnicity, religion, nationality, sexual orientation, disability status, or + * caste. Hateful content aimed at non-protected groups (e.g., chess players) is + * harassment. + */ + hate: boolean; + /** + * Hateful content that also includes violence or serious harm towards the targeted + * group based on race, gender, ethnicity, religion, nationality, sexual + * orientation, disability status, or caste. + */ + 'hate/threatening': boolean; + /** + * Content that promotes, encourages, or depicts acts of self-harm, such as + * suicide, cutting, and eating disorders. + */ + 'self-harm': boolean; + /** + * Content that encourages performing acts of self-harm, such as suicide, cutting, + * and eating disorders, or that gives instructions or advice on how to commit such + * acts. + */ + 'self-harm/instructions': boolean; + /** + * Content where the speaker expresses that they are engaging or intend to engage + * in acts of self-harm, such as suicide, cutting, and eating disorders. + */ + 'self-harm/intent': boolean; + /** + * Content meant to arouse sexual excitement, such as the description of sexual + * activity, or that promotes sexual services (excluding sex education and + * wellness). + */ + sexual: boolean; + /** + * Sexual content that includes an individual who is under 18 years old. + */ + 'sexual/minors': boolean; + /** + * Content that depicts death, violence, or physical injury. + */ + violence: boolean; + /** + * Content that depicts death, violence, or physical injury in graphic detail. + */ + 'violence/graphic': boolean; + } + /** + * A list of the categories along with their scores as predicted by model. + */ + interface CategoryScores { + /** + * The score for the category 'harassment'. + */ + harassment: number; + /** + * The score for the category 'harassment/threatening'. + */ + 'harassment/threatening': number; + /** + * The score for the category 'hate'. + */ + hate: number; + /** + * The score for the category 'hate/threatening'. + */ + 'hate/threatening': number; + /** + * The score for the category 'self-harm'. + */ + 'self-harm': number; + /** + * The score for the category 'self-harm/instructions'. + */ + 'self-harm/instructions': number; + /** + * The score for the category 'self-harm/intent'. + */ + 'self-harm/intent': number; + /** + * The score for the category 'sexual'. + */ + sexual: number; + /** + * The score for the category 'sexual/minors'. + */ + 'sexual/minors': number; + /** + * The score for the category 'violence'. + */ + violence: number; + /** + * The score for the category 'violence/graphic'. + */ + 'violence/graphic': number; + } +} +/** + * Represents if a given text input is potentially harmful. + */ +export interface ModerationCreateResponse { + /** + * The unique identifier for the moderation request. + */ + id: string; + /** + * The model used to generate the moderation results. + */ + model: string; + /** + * A list of moderation objects. + */ + results: Array; +} +export interface ModerationCreateParams { + /** + * The input text to classify + */ + input: string | Array; + /** + * Two content moderations models are available: `text-moderation-stable` and + * `text-moderation-latest`. + * + * The default is `text-moderation-latest` which will be automatically upgraded + * over time. This ensures you are always using our most accurate model. If you use + * `text-moderation-stable`, we will provide advanced notice before updating the + * model. Accuracy of `text-moderation-stable` may be slightly lower than for + * `text-moderation-latest`. + */ + model?: (string & {}) | 'text-moderation-latest' | 'text-moderation-stable'; +} +export declare namespace Moderations { + export import Moderation = ModerationsAPI.Moderation; + export import ModerationCreateResponse = ModerationsAPI.ModerationCreateResponse; + export import ModerationCreateParams = ModerationsAPI.ModerationCreateParams; +} +//# sourceMappingURL=moderations.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/moderations.d.ts.map b/backend/node_modules/openai/resources/moderations.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..fd3778581054f5f0319d4348cdf171424742218d --- /dev/null +++ b/backend/node_modules/openai/resources/moderations.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"moderations.d.ts","sourceRoot":"","sources":["../src/resources/moderations.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,IAAI,MAAM,aAAa,CAAC;AACpC,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAC9C,OAAO,KAAK,cAAc,MAAM,8BAA8B,CAAC;AAE/D,qBAAa,WAAY,SAAQ,WAAW;IAC1C;;OAEG;IACH,MAAM,CACJ,IAAI,EAAE,sBAAsB,EAC5B,OAAO,CAAC,EAAE,IAAI,CAAC,cAAc,GAC5B,IAAI,CAAC,UAAU,CAAC,wBAAwB,CAAC;CAG7C;AAED,MAAM,WAAW,UAAU;IACzB;;OAEG;IACH,UAAU,EAAE,UAAU,CAAC,UAAU,CAAC;IAElC;;OAEG;IACH,eAAe,EAAE,UAAU,CAAC,cAAc,CAAC;IAE3C;;OAEG;IACH,OAAO,EAAE,OAAO,CAAC;CAClB;AAED,yBAAiB,UAAU,CAAC;IAC1B;;OAEG;IACH,UAAiB,UAAU;QACzB;;;WAGG;QACH,UAAU,EAAE,OAAO,CAAC;QAEpB;;;WAGG;QACH,wBAAwB,EAAE,OAAO,CAAC;QAElC;;;;;WAKG;QACH,IAAI,EAAE,OAAO,CAAC;QAEd;;;;WAIG;QACH,kBAAkB,EAAE,OAAO,CAAC;QAE5B;;;WAGG;QACH,WAAW,EAAE,OAAO,CAAC;QAErB;;;;WAIG;QACH,wBAAwB,EAAE,OAAO,CAAC;QAElC;;;WAGG;QACH,kBAAkB,EAAE,OAAO,CAAC;QAE5B;;;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C,wBAAwB,CAAC;IACjF,MAAM,QAAQ,sBAAsB,GAAG,cAAc,CAAC,sBAAsB,CAAC;CAC9E"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/moderations.js b/backend/node_modules/openai/resources/moderations.js new file mode 100644 index 0000000000000000000000000000000000000000..318ade769e72b17e7c2438e2d5e4d1393f3d7f79 --- /dev/null +++ b/backend/node_modules/openai/resources/moderations.js @@ -0,0 +1,17 @@ +"use strict"; +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Moderations = void 0; +const resource_1 = require("openai/resource"); +class Moderations extends resource_1.APIResource { + /** + * Classifies if text is potentially harmful. + */ + create(body, options) { + return this._client.post('/moderations', { body, ...options }); + } +} +exports.Moderations = Moderations; +(function (Moderations) { +})(Moderations = exports.Moderations || (exports.Moderations = {})); +//# sourceMappingURL=moderations.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/moderations.js.map b/backend/node_modules/openai/resources/moderations.js.map new file mode 100644 index 0000000000000000000000000000000000000000..75dd525b532e69ff8bc895968d564fc693f43d50 --- /dev/null +++ b/backend/node_modules/openai/resources/moderations.js.map @@ -0,0 +1 @@ +{"version":3,"file":"moderations.js","sourceRoot":"","sources":["../src/resources/moderations.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;AAGtF,8CAA8C;AAG9C,MAAa,WAAY,SAAQ,sBAAW;IAC1C;;OAEG;IACH,MAAM,CACJ,IAA4B,EAC5B,OAA6B;QAE7B,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,cAAc,EAAE,EAAE,IAAI,EAAE,GAAG,OAAO,EAAE,CAAC,CAAC;IACjE,CAAC;CACF;AAVD,kCAUC;AAiMD,WAAiB,WAAW;AAI5B,CAAC,EAJgB,WAAW,GAAX,mBAAW,KAAX,mBAAW,QAI3B"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/moderations.mjs b/backend/node_modules/openai/resources/moderations.mjs new file mode 100644 index 0000000000000000000000000000000000000000..dea71c09cf838e5a1d9298f6549ccb0c855db0a2 --- /dev/null +++ b/backend/node_modules/openai/resources/moderations.mjs @@ -0,0 +1,13 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +import { APIResource } from 'openai/resource'; +export class Moderations extends APIResource { + /** + * Classifies if text is potentially harmful. + */ + create(body, options) { + return this._client.post('/moderations', { body, ...options }); + } +} +(function (Moderations) { +})(Moderations || (Moderations = {})); +//# sourceMappingURL=moderations.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/moderations.mjs.map b/backend/node_modules/openai/resources/moderations.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..94c399008151b0cba9133f2c4f407f57a9dc9fc2 --- /dev/null +++ b/backend/node_modules/openai/resources/moderations.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"moderations.mjs","sourceRoot":"","sources":["../src/resources/moderations.ts"],"names":[],"mappings":"AAAA,sFAAsF;OAG/E,EAAE,WAAW,EAAE,MAAM,iBAAiB;AAG7C,MAAM,OAAO,WAAY,SAAQ,WAAW;IAC1C;;OAEG;IACH,MAAM,CACJ,IAA4B,EAC5B,OAA6B;QAE7B,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,cAAc,EAAE,EAAE,IAAI,EAAE,GAAG,OAAO,EAAE,CAAC,CAAC;IACjE,CAAC;CACF;AAiMD,WAAiB,WAAW;AAI5B,CAAC,EAJgB,WAAW,KAAX,WAAW,QAI3B"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/shared.d.ts b/backend/node_modules/openai/resources/shared.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..db6cc520438bd4bd81fe6dd50a848b67d74e4af7 --- /dev/null +++ b/backend/node_modules/openai/resources/shared.d.ts @@ -0,0 +1,39 @@ +export interface ErrorObject { + code: string | null; + message: string; + param: string | null; + type: string; +} +export interface FunctionDefinition { + /** + * The name of the function to be called. Must be a-z, A-Z, 0-9, or contain + * underscores and dashes, with a maximum length of 64. + */ + name: string; + /** + * A description of what the function does, used by the model to choose when and + * how to call the function. + */ + description?: string; + /** + * The parameters the functions accepts, described as a JSON Schema object. See the + * [guide](https://platform.openai.com/docs/guides/text-generation/function-calling) + * for examples, and the + * [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for + * documentation about the format. + * + * Omitting `parameters` defines a function with an empty parameter list. + */ + parameters?: FunctionParameters; +} +/** + * The parameters the functions accepts, described as a JSON Schema object. See the + * [guide](https://platform.openai.com/docs/guides/text-generation/function-calling) + * for examples, and the + * [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for + * documentation about the format. + * + * Omitting `parameters` defines a function with an empty parameter list. + */ +export type FunctionParameters = Record; +//# sourceMappingURL=shared.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/shared.d.ts.map b/backend/node_modules/openai/resources/shared.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..da495fb316c5be6bb055bffda1f88e9b347873d0 --- /dev/null +++ b/backend/node_modules/openai/resources/shared.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"shared.d.ts","sourceRoot":"","sources":["../src/resources/shared.ts"],"names":[],"mappings":"AAEA,MAAM,WAAW,WAAW;IAC1B,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IAEpB,OAAO,EAAE,MAAM,CAAC;IAEhB,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IAErB,IAAI,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,kBAAkB;IACjC;;;OAGG;IACH,IAAI,EAAE,MAAM,CAAC;IAEb;;;OAGG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IAErB;;;;;;;;OAQG;IACH,UAAU,CAAC,EAAE,kBAAkB,CAAC;CACjC;AAED;;;;;;;;GAQG;AACH,MAAM,MAAM,kBAAkB,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/shared.js b/backend/node_modules/openai/resources/shared.js new file mode 100644 index 0000000000000000000000000000000000000000..db0cae177b55b03281ce001453daa9b4874edf2a --- /dev/null +++ b/backend/node_modules/openai/resources/shared.js @@ -0,0 +1,4 @@ +"use strict"; +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=shared.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/shared.js.map b/backend/node_modules/openai/resources/shared.js.map new file mode 100644 index 0000000000000000000000000000000000000000..e532ab2cd75f671cbef8791617e56d4cd0b5e6d8 --- /dev/null +++ b/backend/node_modules/openai/resources/shared.js.map @@ -0,0 +1 @@ +{"version":3,"file":"shared.js","sourceRoot":"","sources":["../src/resources/shared.ts"],"names":[],"mappings":";AAAA,sFAAsF"} \ No newline at end of file diff --git a/backend/node_modules/openai/resources/shared.mjs b/backend/node_modules/openai/resources/shared.mjs new file mode 100644 index 0000000000000000000000000000000000000000..a88d4e1268fb4c84c66b4121e6e0a320586be89e --- /dev/null +++ b/backend/node_modules/openai/resources/shared.mjs @@ -0,0 +1,3 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +export {}; +//# sourceMappingURL=shared.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/resources/shared.mjs.map b/backend/node_modules/openai/resources/shared.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..ac8fa86401f84797458257482e1fcde8109eb235 --- /dev/null +++ b/backend/node_modules/openai/resources/shared.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"shared.mjs","sourceRoot":"","sources":["../src/resources/shared.ts"],"names":[],"mappings":"AAAA,sFAAsF"} \ No newline at end of file diff --git a/backend/node_modules/openai/shims/node.d.ts b/backend/node_modules/openai/shims/node.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..25b736e7a0b65dcc35bde7c4c42999b0f7020bcc --- /dev/null +++ b/backend/node_modules/openai/shims/node.d.ts @@ -0,0 +1,29 @@ + + + +import * as types from "../_shims/node-types.js"; +declare module '../_shims/manual-types' { + namespace manual { + type Agent = types.Agent; + export import fetch = types.fetch; + type Request = types.Request; + type RequestInfo = types.RequestInfo; + type RequestInit = types.RequestInit; + type Response = types.Response; + type ResponseInit = types.ResponseInit; + type ResponseType = types.ResponseType; + type BodyInit = types.BodyInit; + type Headers = types.Headers; + type HeadersInit = types.HeadersInit; + type BlobPropertyBag = types.BlobPropertyBag; + type FilePropertyBag = types.FilePropertyBag; + type FileFromPathOptions = types.FileFromPathOptions; + export import FormData = types.FormData; + export import File = types.File; + export import Blob = types.Blob; + type Readable = types.Readable; + type FsReadStream = types.FsReadStream; + export import ReadableStream = types.ReadableStream; + } +} +//# sourceMappingURL=node.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/shims/node.d.ts.map b/backend/node_modules/openai/shims/node.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..4a3a2ef099b35bb8493266f11966fc7fc1458697 --- /dev/null +++ b/backend/node_modules/openai/shims/node.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"node.d.ts","sourceRoot":"","sources":["../src/shims/node.ts"],"names":[],"mappings":";;;AACA,OAAO,KAAK,KAAK,MAAM,sBAAsB,CAAC;AAK9C,OAAO,QAAQ,wBAAwB,CAAC;IACtC,UAAiB,MAAM,CAAC;QAEtB,KAAY,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC;QAEhC,MAAM,QAAQ,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC;QAElC,KAAY,OAAO,GAAG,KAAK,CAAC,OAAO,CAAC;QAEpC,KAAY,WAAW,GAAG,KAAK,CAAC,WAAW,CAAC;QAE5C,KAAY,WAAW,GAAG,KAAK,CAAC,WAAW,CAAC;QAE5C,KAAY,QAAQ,GAAG,KAAK,CAAC,QAAQ,CAAC;QAEtC,KAAY,YAAY,GAAG,KAAK,CAAC,YAAY,CAAC;QAE9C,KAAY,YAAY,GAAG,KAAK,CAAC,YAAY,CAAC;QAE9C,KAAY,QAAQ,GAAG,KAAK,CAAC,QAAQ,CAAC;QAEtC,KAAY,OAAO,GAAG,KAAK,CAAC,OAAO,CAAC;QAEpC,KAAY,WAAW,GAAG,KAAK,CAAC,WAAW,CAAC;QAE5C,KAAY,eAAe,GAAG,KAAK,CAAC,eAAe,CAAC;QAEpD,KAAY,eAAe,GAAG,KAAK,CAAC,eAAe,CAAC;QAEpD,KAAY,mBAAmB,GAAG,KAAK,CAAC,mBAAmB,CAAC;QAE5D,MAAM,QAAQ,QAAQ,GAAG,KAAK,CAAC,QAAQ,CAAC;QAExC,MAAM,QAAQ,IAAI,GAAG,KAAK,CAAC,IAAI,CAAC;QAEhC,MAAM,QAAQ,IAAI,GAAG,KAAK,CAAC,IAAI,CAAC;QAEhC,KAAY,QAAQ,GAAG,KAAK,CAAC,QAAQ,CAAC;QAEtC,KAAY,YAAY,GAAG,KAAK,CAAC,YAAY,CAAC;QAE9C,MAAM,QAAQ,cAAc,GAAG,KAAK,CAAC,cAAc,CAAC;KACrD;CACF"} \ No newline at end of file diff --git a/backend/node_modules/openai/shims/node.js b/backend/node_modules/openai/shims/node.js new file mode 100644 index 0000000000000000000000000000000000000000..9fb2b0151c44e23c98d6f2d7b5560fead00cb492 --- /dev/null +++ b/backend/node_modules/openai/shims/node.js @@ -0,0 +1,31 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +// @ts-ignore +const types = __importStar(require("../_shims/node-types.js")); +const registry_1 = require("../_shims/registry.js"); +const node_runtime_1 = require("../_shims/node-runtime.js"); +(0, registry_1.setShims)((0, node_runtime_1.getRuntime)()); +//# sourceMappingURL=node.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/shims/node.js.map b/backend/node_modules/openai/shims/node.js.map new file mode 100644 index 0000000000000000000000000000000000000000..181c62ec97d867f09291868dd7306b48ec3c0743 --- /dev/null +++ b/backend/node_modules/openai/shims/node.js.map @@ -0,0 +1 @@ +{"version":3,"file":"node.js","sourceRoot":"","sources":["../src/shims/node.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAAA,aAAa;AACb,+DAA8C;AAC9C,oDAA8C;AAC9C,4DAAoD;AACpD,IAAA,mBAAQ,EAAC,IAAA,yBAAU,GAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/openai/shims/node.mjs b/backend/node_modules/openai/shims/node.mjs new file mode 100644 index 0000000000000000000000000000000000000000..18b446385b77ab097593ece97497010ce2d28f15 --- /dev/null +++ b/backend/node_modules/openai/shims/node.mjs @@ -0,0 +1,5 @@ +import * as types from "../_shims/node-types.mjs"; +import { setShims } from "../_shims/registry.mjs"; +import { getRuntime } from "../_shims/node-runtime.mjs"; +setShims(getRuntime()); +//# sourceMappingURL=node.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/shims/node.mjs.map b/backend/node_modules/openai/shims/node.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..3f0a9f18c1a81cb2ddd2654d21f10456d6ecb587 --- /dev/null +++ b/backend/node_modules/openai/shims/node.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"node.mjs","sourceRoot":"","sources":["../src/shims/node.ts"],"names":[],"mappings":"OACO,KAAK,KAAK;OACV,EAAE,QAAQ,EAAE;OACZ,EAAE,UAAU,EAAE;AACrB,QAAQ,CAAC,UAAU,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/openai/shims/web.d.ts b/backend/node_modules/openai/shims/web.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3248079be9238899ac9cb7c64e7c6f9995b5eaf8 --- /dev/null +++ b/backend/node_modules/openai/shims/web.d.ts @@ -0,0 +1,26 @@ +import * as types from "../_shims/web-types.js"; +declare module '../_shims/manual-types' { + namespace manual { + type Agent = types.Agent; + export import fetch = types.fetch; + type Request = types.Request; + type RequestInfo = types.RequestInfo; + type RequestInit = types.RequestInit; + type Response = types.Response; + type ResponseInit = types.ResponseInit; + type ResponseType = types.ResponseType; + type BodyInit = types.BodyInit; + type Headers = types.Headers; + type HeadersInit = types.HeadersInit; + type BlobPropertyBag = types.BlobPropertyBag; + type FilePropertyBag = types.FilePropertyBag; + type FileFromPathOptions = types.FileFromPathOptions; + export import FormData = types.FormData; + export import File = types.File; + export import Blob = types.Blob; + type Readable = types.Readable; + type FsReadStream = types.FsReadStream; + export import ReadableStream = types.ReadableStream; + } +} +//# sourceMappingURL=web.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/shims/web.d.ts.map b/backend/node_modules/openai/shims/web.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..b478965b998a1700c0d452289985d464c451980b --- /dev/null +++ b/backend/node_modules/openai/shims/web.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"web.d.ts","sourceRoot":"","sources":["../src/shims/web.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,KAAK,MAAM,qBAAqB,CAAC;AAK7C,OAAO,QAAQ,wBAAwB,CAAC;IACtC,UAAiB,MAAM,CAAC;QAEtB,KAAY,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC;QAEhC,MAAM,QAAQ,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC;QAElC,KAAY,OAAO,GAAG,KAAK,CAAC,OAAO,CAAC;QAEpC,KAAY,WAAW,GAAG,KAAK,CAAC,WAAW,CAAC;QAE5C,KAAY,WAAW,GAAG,KAAK,CAAC,WAAW,CAAC;QAE5C,KAAY,QAAQ,GAAG,KAAK,CAAC,QAAQ,CAAC;QAEtC,KAAY,YAAY,GAAG,KAAK,CAAC,YAAY,CAAC;QAE9C,KAAY,YAAY,GAAG,KAAK,CAAC,YAAY,CAAC;QAE9C,KAAY,QAAQ,GAAG,KAAK,CAAC,QAAQ,CAAC;QAEtC,KAAY,OAAO,GAAG,KAAK,CAAC,OAAO,CAAC;QAEpC,KAAY,WAAW,GAAG,KAAK,CAAC,WAAW,CAAC;QAE5C,KAAY,eAAe,GAAG,KAAK,CAAC,eAAe,CAAC;QAEpD,KAAY,eAAe,GAAG,KAAK,CAAC,eAAe,CAAC;QAEpD,KAAY,mBAAmB,GAAG,KAAK,CAAC,mBAAmB,CAAC;QAE5D,MAAM,QAAQ,QAAQ,GAAG,KAAK,CAAC,QAAQ,CAAC;QAExC,MAAM,QAAQ,IAAI,GAAG,KAAK,CAAC,IAAI,CAAC;QAEhC,MAAM,QAAQ,IAAI,GAAG,KAAK,CAAC,IAAI,CAAC;QAEhC,KAAY,QAAQ,GAAG,KAAK,CAAC,QAAQ,CAAC;QAEtC,KAAY,YAAY,GAAG,KAAK,CAAC,YAAY,CAAC;QAE9C,MAAM,QAAQ,cAAc,GAAG,KAAK,CAAC,cAAc,CAAC;KACrD;CACF"} \ No newline at end of file diff --git a/backend/node_modules/openai/shims/web.js b/backend/node_modules/openai/shims/web.js new file mode 100644 index 0000000000000000000000000000000000000000..2a1d019e957c03aa4e765df2f8dcfefd5a00831c --- /dev/null +++ b/backend/node_modules/openai/shims/web.js @@ -0,0 +1,31 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +// @ts-ignore +const types = __importStar(require("../_shims/web-types.js")); +const registry_1 = require("../_shims/registry.js"); +const web_runtime_1 = require("../_shims/web-runtime.js"); +(0, registry_1.setShims)((0, web_runtime_1.getRuntime)({ manuallyImported: true })); +//# sourceMappingURL=web.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/shims/web.js.map b/backend/node_modules/openai/shims/web.js.map new file mode 100644 index 0000000000000000000000000000000000000000..3eb0f4c0c402ef2259b035f5a0acd6080e4cf06f --- /dev/null +++ b/backend/node_modules/openai/shims/web.js.map @@ -0,0 +1 @@ +{"version":3,"file":"web.js","sourceRoot":"","sources":["../src/shims/web.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAAA,aAAa;AACb,8DAA6C;AAC7C,oDAA8C;AAC9C,0DAAmD;AACnD,IAAA,mBAAQ,EAAC,IAAA,wBAAU,EAAC,EAAE,gBAAgB,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/openai/shims/web.mjs b/backend/node_modules/openai/shims/web.mjs new file mode 100644 index 0000000000000000000000000000000000000000..aa1b96f8ef6c36fc577ff2f3cd6acfe26c0e9e4b --- /dev/null +++ b/backend/node_modules/openai/shims/web.mjs @@ -0,0 +1,5 @@ +import * as types from "../_shims/web-types.mjs"; +import { setShims } from "../_shims/registry.mjs"; +import { getRuntime } from "../_shims/web-runtime.mjs"; +setShims(getRuntime({ manuallyImported: true })); +//# sourceMappingURL=web.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/shims/web.mjs.map b/backend/node_modules/openai/shims/web.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..0ccbb72dd0c0b76dfd6addcbbb80ec9f966ef5d8 --- /dev/null +++ b/backend/node_modules/openai/shims/web.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"web.mjs","sourceRoot":"","sources":["../src/shims/web.ts"],"names":[],"mappings":"OACO,KAAK,KAAK;OACV,EAAE,QAAQ,EAAE;OACZ,EAAE,UAAU,EAAE;AACrB,QAAQ,CAAC,UAAU,CAAC,EAAE,gBAAgB,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/openai/src/_shims/MultipartBody.ts b/backend/node_modules/openai/src/_shims/MultipartBody.ts new file mode 100644 index 0000000000000000000000000000000000000000..af3b11188aec98ff0b50e909c6c9ecc2d3da1f30 --- /dev/null +++ b/backend/node_modules/openai/src/_shims/MultipartBody.ts @@ -0,0 +1,9 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ +export class MultipartBody { + constructor(public body: any) {} + get [Symbol.toStringTag](): string { + return 'MultipartBody'; + } +} diff --git a/backend/node_modules/openai/src/_shims/README.md b/backend/node_modules/openai/src/_shims/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b3a349b41b588ba2c9b06d0751a9e8a07375d513 --- /dev/null +++ b/backend/node_modules/openai/src/_shims/README.md @@ -0,0 +1,46 @@ +# 👋 Wondering what everything in here does? + +`openai` supports a wide variety of runtime environments like Node.js, Deno, Bun, browsers, and various +edge runtimes, as well as both CommonJS (CJS) and EcmaScript Modules (ESM). + +To do this, `openai` provides shims for either using `node-fetch` when in Node (because `fetch` is still experimental there) or the global `fetch` API built into the environment when not in Node. + +It uses [conditional exports](https://nodejs.org/api/packages.html#conditional-exports) to +automatically select the correct shims for each environment. However, conditional exports are a fairly new +feature and not supported everywhere. For instance, the TypeScript `"moduleResolution": "node"` + +setting doesn't consult the `exports` map, compared to `"moduleResolution": "nodeNext"`, which does. +Unfortunately that's still the default setting, and it can result in errors like +getting the wrong raw `Response` type from `.asResponse()`, for example. + +The user can work around these issues by manually importing one of: + +- `import 'openai/shims/node'` +- `import 'openai/shims/web'` + +All of the code here in `_shims` handles selecting the automatic default shims or manual overrides. + +### How it works - Runtime + +Runtime shims get installed by calling `setShims` exported by `openai/_shims/registry`. + +Manually importing `openai/shims/node` or `openai/shims/web`, calls `setShims` with the respective runtime shims. + +All client code imports shims from `openai/_shims/index`, which: + +- checks if shims have been set manually +- if not, calls `setShims` with the shims from `openai/_shims/auto/runtime` +- re-exports the installed shims from `openai/_shims/registry`. + +`openai/_shims/auto/runtime` exports web runtime shims. +If the `node` export condition is set, the export map replaces it with `openai/_shims/auto/runtime-node`. + +### How it works - Type time + +All client code imports shim types from `openai/_shims/index`, which selects the manual types from `openai/_shims/manual-types` if they have been declared, otherwise it exports the auto types from `openai/_shims/auto/types`. + +`openai/_shims/manual-types` exports an empty namespace. +Manually importing `openai/shims/node` or `openai/shims/web` merges declarations into this empty namespace, so they get picked up by `openai/_shims/index`. + +`openai/_shims/auto/types` exports web type definitions. +If the `node` export condition is set, the export map replaces it with `openai/_shims/auto/types-node`, though TS only picks this up if `"moduleResolution": "nodenext"` or `"moduleResolution": "bundler"`. diff --git a/backend/node_modules/openai/src/_shims/auto/runtime-bun.ts b/backend/node_modules/openai/src/_shims/auto/runtime-bun.ts new file mode 100644 index 0000000000000000000000000000000000000000..e053254b35e5219b06a26c1c6296158ce66f0f6d --- /dev/null +++ b/backend/node_modules/openai/src/_shims/auto/runtime-bun.ts @@ -0,0 +1,4 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ +export * from '../bun-runtime'; diff --git a/backend/node_modules/openai/src/_shims/auto/runtime-node.ts b/backend/node_modules/openai/src/_shims/auto/runtime-node.ts new file mode 100644 index 0000000000000000000000000000000000000000..0ae2216fe6de50fb8077e9535ea8b373c7474ac1 --- /dev/null +++ b/backend/node_modules/openai/src/_shims/auto/runtime-node.ts @@ -0,0 +1,4 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ +export * from '../node-runtime'; diff --git a/backend/node_modules/openai/src/_shims/auto/runtime.ts b/backend/node_modules/openai/src/_shims/auto/runtime.ts new file mode 100644 index 0000000000000000000000000000000000000000..62b7a39ee71f7c2de99910e2e019121fb85225e7 --- /dev/null +++ b/backend/node_modules/openai/src/_shims/auto/runtime.ts @@ -0,0 +1,4 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ +export * from '../web-runtime'; diff --git a/backend/node_modules/openai/src/_shims/auto/types-node.ts b/backend/node_modules/openai/src/_shims/auto/types-node.ts new file mode 100644 index 0000000000000000000000000000000000000000..2625a8b700c2dcca8e876b2ef1ee16e29308d2b5 --- /dev/null +++ b/backend/node_modules/openai/src/_shims/auto/types-node.ts @@ -0,0 +1,4 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ +export * from '../node-types'; diff --git a/backend/node_modules/openai/src/_shims/auto/types.d.ts b/backend/node_modules/openai/src/_shims/auto/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8fbedac9dd18eaf40506cf08434257f0c85df479 --- /dev/null +++ b/backend/node_modules/openai/src/_shims/auto/types.d.ts @@ -0,0 +1,101 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ +export type Agent = any; + +// @ts-ignore +declare const _fetch: typeof fetch; +export { _fetch as fetch }; + +// @ts-ignore +type _Request = Request; +export { _Request as Request }; + +// @ts-ignore +type _RequestInfo = RequestInfo; +export { type _RequestInfo as RequestInfo }; + +// @ts-ignore +type _RequestInit = RequestInit; +export { type _RequestInit as RequestInit }; + +// @ts-ignore +type _Response = Response; +export { _Response as Response }; + +// @ts-ignore +type _ResponseInit = ResponseInit; +export { type _ResponseInit as ResponseInit }; + +// @ts-ignore +type _ResponseType = ResponseType; +export { type _ResponseType as ResponseType }; + +// @ts-ignore +type _BodyInit = BodyInit; +export { type _BodyInit as BodyInit }; + +// @ts-ignore +type _Headers = Headers; +export { _Headers as Headers }; + +// @ts-ignore +type _HeadersInit = HeadersInit; +export { type _HeadersInit as HeadersInit }; + +type EndingType = 'native' | 'transparent'; + +export interface BlobPropertyBag { + endings?: EndingType; + type?: string; +} + +export interface FilePropertyBag extends BlobPropertyBag { + lastModified?: number; +} + +export type FileFromPathOptions = Omit; + +// @ts-ignore +type _FormData = FormData; +// @ts-ignore +declare const _FormData: typeof FormData; +export { _FormData as FormData }; + +// @ts-ignore +type _File = File; +// @ts-ignore +declare const _File: typeof File; +export { _File as File }; + +// @ts-ignore +type _Blob = Blob; +// @ts-ignore +declare const _Blob: typeof Blob; +export { _Blob as Blob }; + +export declare class Readable { + readable: boolean; + readonly readableEnded: boolean; + readonly readableFlowing: boolean | null; + readonly readableHighWaterMark: number; + readonly readableLength: number; + readonly readableObjectMode: boolean; + destroyed: boolean; + read(size?: number): any; + pause(): this; + resume(): this; + isPaused(): boolean; + destroy(error?: Error): this; + [Symbol.asyncIterator](): AsyncIterableIterator; +} + +export declare class FsReadStream extends Readable { + path: {}; // node type is string | Buffer +} + +// @ts-ignore +type _ReadableStream = ReadableStream; +// @ts-ignore +declare const _ReadableStream: typeof ReadableStream; +export { _ReadableStream as ReadableStream }; diff --git a/backend/node_modules/openai/src/_shims/auto/types.js b/backend/node_modules/openai/src/_shims/auto/types.js new file mode 100644 index 0000000000000000000000000000000000000000..ddbdb799c8d3a5a22f9400270cb1b71b570c202a --- /dev/null +++ b/backend/node_modules/openai/src/_shims/auto/types.js @@ -0,0 +1,3 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ diff --git a/backend/node_modules/openai/src/_shims/auto/types.mjs b/backend/node_modules/openai/src/_shims/auto/types.mjs new file mode 100644 index 0000000000000000000000000000000000000000..ddbdb799c8d3a5a22f9400270cb1b71b570c202a --- /dev/null +++ b/backend/node_modules/openai/src/_shims/auto/types.mjs @@ -0,0 +1,3 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ diff --git a/backend/node_modules/openai/src/_shims/bun-runtime.ts b/backend/node_modules/openai/src/_shims/bun-runtime.ts new file mode 100644 index 0000000000000000000000000000000000000000..8d5aaab0c13a56739f8870baf847a61ac46a68ec --- /dev/null +++ b/backend/node_modules/openai/src/_shims/bun-runtime.ts @@ -0,0 +1,14 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ +import { type Shims } from './registry'; +import { getRuntime as getWebRuntime } from './web-runtime'; +import { ReadStream as FsReadStream } from 'node:fs'; + +export function getRuntime(): Shims { + const runtime = getWebRuntime(); + function isFsReadStream(value: any): value is FsReadStream { + return value instanceof FsReadStream; + } + return { ...runtime, isFsReadStream }; +} diff --git a/backend/node_modules/openai/src/_shims/index.d.ts b/backend/node_modules/openai/src/_shims/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..646e7feee463d49142e358abf42c221ad42101d6 --- /dev/null +++ b/backend/node_modules/openai/src/_shims/index.d.ts @@ -0,0 +1,81 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ +import { manual } from './manual-types'; +import * as auto from "./auto/types"; +import { type RequestOptions } from '../core'; + +type SelectType = unknown extends Manual ? Auto : Manual; + +export const kind: string; + +// @ts-ignore +export type Agent = SelectType; + +// @ts-ignore +export const fetch: SelectType; + +// @ts-ignore +export type Request = SelectType; +// @ts-ignore +export type RequestInfo = SelectType; +// @ts-ignore +export type RequestInit = SelectType; + +// @ts-ignore +export type Response = SelectType; +// @ts-ignore +export type ResponseInit = SelectType; +// @ts-ignore +export type ResponseType = SelectType; +// @ts-ignore +export type BodyInit = SelectType; +// @ts-ignore +export type Headers = SelectType; +// @ts-ignore +export const Headers: SelectType; +// @ts-ignore +export type HeadersInit = SelectType; + +// @ts-ignore +export type BlobPropertyBag = SelectType; +// @ts-ignore +export type FilePropertyBag = SelectType; +// @ts-ignore +export type FileFromPathOptions = SelectType; +// @ts-ignore +export type FormData = SelectType; +// @ts-ignore +export const FormData: SelectType; +// @ts-ignore +export type File = SelectType; +// @ts-ignore +export const File: SelectType; +// @ts-ignore +export type Blob = SelectType; +// @ts-ignore +export const Blob: SelectType; + +// @ts-ignore +export type Readable = SelectType; +// @ts-ignore +export type FsReadStream = SelectType; +// @ts-ignore +export type ReadableStream = SelectType; +// @ts-ignore +export const ReadableStream: SelectType; + +export function getMultipartRequestOptions>( + form: FormData, + opts: RequestOptions, +): Promise>; + +export function getDefaultAgent(url: string): any; + +// @ts-ignore +export type FileFromPathOptions = SelectType; + +export function fileFromPath(path: string, options?: FileFromPathOptions): Promise; +export function fileFromPath(path: string, filename?: string, options?: FileFromPathOptions): Promise; + +export function isFsReadStream(value: any): value is FsReadStream; diff --git a/backend/node_modules/openai/src/_shims/index.js b/backend/node_modules/openai/src/_shims/index.js new file mode 100644 index 0000000000000000000000000000000000000000..b5fc8229e90852a1b61e9442bf87cc2fe3b6ddfb --- /dev/null +++ b/backend/node_modules/openai/src/_shims/index.js @@ -0,0 +1,13 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ +const shims = require('./registry'); +const auto = require('openai/_shims/auto/runtime'); +if (!shims.kind) shims.setShims(auto.getRuntime(), { auto: true }); +for (const property of Object.keys(shims)) { + Object.defineProperty(exports, property, { + get() { + return shims[property]; + }, + }); +} diff --git a/backend/node_modules/openai/src/_shims/index.mjs b/backend/node_modules/openai/src/_shims/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..8d111aa46e1373e1593ff2b97c5cde390f125421 --- /dev/null +++ b/backend/node_modules/openai/src/_shims/index.mjs @@ -0,0 +1,7 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ +import * as shims from './registry.mjs'; +import * as auto from "./auto/runtime"; +if (!shims.kind) shims.setShims(auto.getRuntime(), { auto: true }); +export * from './registry.mjs'; diff --git a/backend/node_modules/openai/src/_shims/manual-types.d.ts b/backend/node_modules/openai/src/_shims/manual-types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3d00fc243378204f80beef898da42c5eaf1f5cf7 --- /dev/null +++ b/backend/node_modules/openai/src/_shims/manual-types.d.ts @@ -0,0 +1,12 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ +/** + * Types will get added to this namespace when you import one of the following: + * + * import 'openai/shims/node' + * import 'openai/shims/web' + * + * Importing more than one will cause type and runtime errors. + */ +export namespace manual {} diff --git a/backend/node_modules/openai/src/_shims/manual-types.js b/backend/node_modules/openai/src/_shims/manual-types.js new file mode 100644 index 0000000000000000000000000000000000000000..ddbdb799c8d3a5a22f9400270cb1b71b570c202a --- /dev/null +++ b/backend/node_modules/openai/src/_shims/manual-types.js @@ -0,0 +1,3 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ diff --git a/backend/node_modules/openai/src/_shims/manual-types.mjs b/backend/node_modules/openai/src/_shims/manual-types.mjs new file mode 100644 index 0000000000000000000000000000000000000000..ddbdb799c8d3a5a22f9400270cb1b71b570c202a --- /dev/null +++ b/backend/node_modules/openai/src/_shims/manual-types.mjs @@ -0,0 +1,3 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ diff --git a/backend/node_modules/openai/src/_shims/node-runtime.ts b/backend/node_modules/openai/src/_shims/node-runtime.ts new file mode 100644 index 0000000000000000000000000000000000000000..a9c42ebeb67ccc037faa41ea3ec5c5c52435c3ba --- /dev/null +++ b/backend/node_modules/openai/src/_shims/node-runtime.ts @@ -0,0 +1,83 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ +import * as nf from 'node-fetch'; +import * as fd from 'formdata-node'; +import { type File, type FilePropertyBag } from 'formdata-node'; +import KeepAliveAgent from 'agentkeepalive'; +import { AbortController as AbortControllerPolyfill } from 'abort-controller'; +import { ReadStream as FsReadStream } from 'node:fs'; +import { type Agent } from 'node:http'; +import { FormDataEncoder } from 'form-data-encoder'; +import { Readable } from 'node:stream'; +import { type RequestOptions } from '../core'; +import { MultipartBody } from './MultipartBody'; +import { type Shims } from './registry'; + +// @ts-ignore (this package does not have proper export maps for this export) +import { ReadableStream } from 'web-streams-polyfill/dist/ponyfill.es2018.js'; + +type FileFromPathOptions = Omit; + +let fileFromPathWarned = false; + +/** + * @deprecated use fs.createReadStream('./my/file.txt') instead + */ +async function fileFromPath(path: string): Promise; +async function fileFromPath(path: string, filename?: string): Promise; +async function fileFromPath(path: string, options?: FileFromPathOptions): Promise; +async function fileFromPath(path: string, filename?: string, options?: FileFromPathOptions): Promise; +async function fileFromPath(path: string, ...args: any[]): Promise { + // this import fails in environments that don't handle export maps correctly, like old versions of Jest + const { fileFromPath: _fileFromPath } = await import('formdata-node/file-from-path'); + + if (!fileFromPathWarned) { + console.warn(`fileFromPath is deprecated; use fs.createReadStream(${JSON.stringify(path)}) instead`); + fileFromPathWarned = true; + } + // @ts-ignore + return await _fileFromPath(path, ...args); +} + +const defaultHttpAgent: Agent = new KeepAliveAgent({ keepAlive: true, timeout: 5 * 60 * 1000 }); +const defaultHttpsAgent: Agent = new KeepAliveAgent.HttpsAgent({ keepAlive: true, timeout: 5 * 60 * 1000 }); + +async function getMultipartRequestOptions>( + form: fd.FormData, + opts: RequestOptions, +): Promise> { + const encoder = new FormDataEncoder(form); + const readable = Readable.from(encoder); + const body = new MultipartBody(readable); + const headers = { + ...opts.headers, + ...encoder.headers, + 'Content-Length': encoder.contentLength, + }; + + return { ...opts, body: body as any, headers }; +} + +export function getRuntime(): Shims { + // Polyfill global object if needed. + if (typeof AbortController === 'undefined') { + // @ts-expect-error (the types are subtly different, but compatible in practice) + globalThis.AbortController = AbortControllerPolyfill; + } + return { + kind: 'node', + fetch: nf.default, + Request: nf.Request, + Response: nf.Response, + Headers: nf.Headers, + FormData: fd.FormData, + Blob: fd.Blob, + File: fd.File, + ReadableStream, + getMultipartRequestOptions, + getDefaultAgent: (url: string): Agent => (url.startsWith('https') ? defaultHttpsAgent : defaultHttpAgent), + fileFromPath, + isFsReadStream: (value: any): value is FsReadStream => value instanceof FsReadStream, + }; +} diff --git a/backend/node_modules/openai/src/_shims/node-types.d.ts b/backend/node_modules/openai/src/_shims/node-types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b31698f780b28f6187a3875497e4df5549c7a15b --- /dev/null +++ b/backend/node_modules/openai/src/_shims/node-types.d.ts @@ -0,0 +1,42 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ +import * as nf from 'node-fetch'; +import * as fd from 'formdata-node'; + +export { type Agent } from 'node:http'; +export { type Readable } from 'node:stream'; +export { type ReadStream as FsReadStream } from 'node:fs'; +export { ReadableStream } from 'web-streams-polyfill'; + +export const fetch: typeof nf.default; + +export type Request = nf.Request; +export type RequestInfo = nf.RequestInfo; +export type RequestInit = nf.RequestInit; + +export type Response = nf.Response; +export type ResponseInit = nf.ResponseInit; +export type ResponseType = nf.ResponseType; +export type BodyInit = nf.BodyInit; +export type Headers = nf.Headers; +export type HeadersInit = nf.HeadersInit; + +type EndingType = 'native' | 'transparent'; +export interface BlobPropertyBag { + endings?: EndingType; + type?: string; +} + +export interface FilePropertyBag extends BlobPropertyBag { + lastModified?: number; +} + +export type FileFromPathOptions = Omit; + +export type FormData = fd.FormData; +export const FormData: typeof fd.FormData; +export type File = fd.File; +export const File: typeof fd.File; +export type Blob = fd.Blob; +export const Blob: typeof fd.Blob; diff --git a/backend/node_modules/openai/src/_shims/node-types.js b/backend/node_modules/openai/src/_shims/node-types.js new file mode 100644 index 0000000000000000000000000000000000000000..ddbdb799c8d3a5a22f9400270cb1b71b570c202a --- /dev/null +++ b/backend/node_modules/openai/src/_shims/node-types.js @@ -0,0 +1,3 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ diff --git a/backend/node_modules/openai/src/_shims/node-types.mjs b/backend/node_modules/openai/src/_shims/node-types.mjs new file mode 100644 index 0000000000000000000000000000000000000000..ddbdb799c8d3a5a22f9400270cb1b71b570c202a --- /dev/null +++ b/backend/node_modules/openai/src/_shims/node-types.mjs @@ -0,0 +1,3 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ diff --git a/backend/node_modules/openai/src/_shims/registry.ts b/backend/node_modules/openai/src/_shims/registry.ts new file mode 100644 index 0000000000000000000000000000000000000000..1fa39642e203325a2e7cb34f60e1c1d7b040c583 --- /dev/null +++ b/backend/node_modules/openai/src/_shims/registry.ts @@ -0,0 +1,65 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ +import { type RequestOptions } from '../core'; + +export interface Shims { + kind: string; + fetch: any; + Request: any; + Response: any; + Headers: any; + FormData: any; + Blob: any; + File: any; + ReadableStream: any; + getMultipartRequestOptions: >( + form: Shims['FormData'], + opts: RequestOptions, + ) => Promise>; + getDefaultAgent: (url: string) => any; + fileFromPath: + | ((path: string, filename?: string, options?: {}) => Promise) + | ((path: string, options?: {}) => Promise); + isFsReadStream: (value: any) => boolean; +} + +export let auto = false; +export let kind: Shims['kind'] | undefined = undefined; +export let fetch: Shims['fetch'] | undefined = undefined; +export let Request: Shims['Request'] | undefined = undefined; +export let Response: Shims['Response'] | undefined = undefined; +export let Headers: Shims['Headers'] | undefined = undefined; +export let FormData: Shims['FormData'] | undefined = undefined; +export let Blob: Shims['Blob'] | undefined = undefined; +export let File: Shims['File'] | undefined = undefined; +export let ReadableStream: Shims['ReadableStream'] | undefined = undefined; +export let getMultipartRequestOptions: Shims['getMultipartRequestOptions'] | undefined = undefined; +export let getDefaultAgent: Shims['getDefaultAgent'] | undefined = undefined; +export let fileFromPath: Shims['fileFromPath'] | undefined = undefined; +export let isFsReadStream: Shims['isFsReadStream'] | undefined = undefined; + +export function setShims(shims: Shims, options: { auto: boolean } = { auto: false }) { + if (auto) { + throw new Error( + `you must \`import 'openai/shims/${shims.kind}'\` before importing anything else from openai`, + ); + } + if (kind) { + throw new Error(`can't \`import 'openai/shims/${shims.kind}'\` after \`import 'openai/shims/${kind}'\``); + } + auto = options.auto; + kind = shims.kind; + fetch = shims.fetch; + Request = shims.Request; + Response = shims.Response; + Headers = shims.Headers; + FormData = shims.FormData; + Blob = shims.Blob; + File = shims.File; + ReadableStream = shims.ReadableStream; + getMultipartRequestOptions = shims.getMultipartRequestOptions; + getDefaultAgent = shims.getDefaultAgent; + fileFromPath = shims.fileFromPath; + isFsReadStream = shims.isFsReadStream; +} diff --git a/backend/node_modules/openai/src/_shims/web-runtime.ts b/backend/node_modules/openai/src/_shims/web-runtime.ts new file mode 100644 index 0000000000000000000000000000000000000000..a5e90bcf8f2b5eb2ebb7521879974b0acc1129ad --- /dev/null +++ b/backend/node_modules/openai/src/_shims/web-runtime.ts @@ -0,0 +1,103 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ +import { MultipartBody } from './MultipartBody'; +import { type RequestOptions } from '../core'; +import { type Shims } from './registry'; + +export function getRuntime({ manuallyImported }: { manuallyImported?: boolean } = {}): Shims { + const recommendation = + manuallyImported ? + `You may need to use polyfills` + : `Add one of these imports before your first \`import … from 'openai'\`: +- \`import 'openai/shims/node'\` (if you're running on Node) +- \`import 'openai/shims/web'\` (otherwise) +`; + + let _fetch, _Request, _Response, _Headers; + try { + // @ts-ignore + _fetch = fetch; + // @ts-ignore + _Request = Request; + // @ts-ignore + _Response = Response; + // @ts-ignore + _Headers = Headers; + } catch (error) { + throw new Error( + `this environment is missing the following Web Fetch API type: ${ + (error as any).message + }. ${recommendation}`, + ); + } + + return { + kind: 'web', + fetch: _fetch, + Request: _Request, + Response: _Response, + Headers: _Headers, + FormData: + // @ts-ignore + typeof FormData !== 'undefined' ? FormData : ( + class FormData { + // @ts-ignore + constructor() { + throw new Error( + `file uploads aren't supported in this environment yet as 'FormData' is undefined. ${recommendation}`, + ); + } + } + ), + Blob: + typeof Blob !== 'undefined' ? Blob : ( + class Blob { + constructor() { + throw new Error( + `file uploads aren't supported in this environment yet as 'Blob' is undefined. ${recommendation}`, + ); + } + } + ), + File: + // @ts-ignore + typeof File !== 'undefined' ? File : ( + class File { + // @ts-ignore + constructor() { + throw new Error( + `file uploads aren't supported in this environment yet as 'File' is undefined. ${recommendation}`, + ); + } + } + ), + ReadableStream: + // @ts-ignore + typeof ReadableStream !== 'undefined' ? ReadableStream : ( + class ReadableStream { + // @ts-ignore + constructor() { + throw new Error( + `streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${recommendation}`, + ); + } + } + ), + getMultipartRequestOptions: async >( + // @ts-ignore + form: FormData, + opts: RequestOptions, + ): Promise> => ({ + ...opts, + body: new MultipartBody(form) as any, + }), + getDefaultAgent: (url: string) => undefined, + fileFromPath: () => { + throw new Error( + 'The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/openai/openai-node#file-uploads', + ); + }, + isFsReadStream: (value: any) => false, + }; +} diff --git a/backend/node_modules/openai/src/_shims/web-types.d.ts b/backend/node_modules/openai/src/_shims/web-types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4ff351383278a4b2ed4afbbfd7d9d134f648f81b --- /dev/null +++ b/backend/node_modules/openai/src/_shims/web-types.d.ts @@ -0,0 +1,83 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ +export type Agent = any; + +declare const _fetch: typeof fetch; +export { _fetch as fetch }; + +type _Request = Request; +export { _Request as Request }; + +type _RequestInfo = RequestInfo; +export { type _RequestInfo as RequestInfo }; + +type _RequestInit = RequestInit; +export { type _RequestInit as RequestInit }; + +type _Response = Response; +export { _Response as Response }; + +type _ResponseInit = ResponseInit; +export { type _ResponseInit as ResponseInit }; + +type _ResponseType = ResponseType; +export { type _ResponseType as ResponseType }; + +type _BodyInit = BodyInit; +export { type _BodyInit as BodyInit }; + +type _Headers = Headers; +export { _Headers as Headers }; + +type _HeadersInit = HeadersInit; +export { type _HeadersInit as HeadersInit }; + +type EndingType = 'native' | 'transparent'; + +export interface BlobPropertyBag { + endings?: EndingType; + type?: string; +} + +export interface FilePropertyBag extends BlobPropertyBag { + lastModified?: number; +} + +export type FileFromPathOptions = Omit; + +type _FormData = FormData; +declare const _FormData: typeof FormData; +export { _FormData as FormData }; + +type _File = File; +declare const _File: typeof File; +export { _File as File }; + +type _Blob = Blob; +declare const _Blob: typeof Blob; +export { _Blob as Blob }; + +export declare class Readable { + readable: boolean; + readonly readableEnded: boolean; + readonly readableFlowing: boolean | null; + readonly readableHighWaterMark: number; + readonly readableLength: number; + readonly readableObjectMode: boolean; + destroyed: boolean; + read(size?: number): any; + pause(): this; + resume(): this; + isPaused(): boolean; + destroy(error?: Error): this; + [Symbol.asyncIterator](): AsyncIterableIterator; +} + +export declare class FsReadStream extends Readable { + path: {}; // node type is string | Buffer +} + +type _ReadableStream = ReadableStream; +declare const _ReadableStream: typeof ReadableStream; +export { _ReadableStream as ReadableStream }; diff --git a/backend/node_modules/openai/src/_shims/web-types.js b/backend/node_modules/openai/src/_shims/web-types.js new file mode 100644 index 0000000000000000000000000000000000000000..ddbdb799c8d3a5a22f9400270cb1b71b570c202a --- /dev/null +++ b/backend/node_modules/openai/src/_shims/web-types.js @@ -0,0 +1,3 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ diff --git a/backend/node_modules/openai/src/_shims/web-types.mjs b/backend/node_modules/openai/src/_shims/web-types.mjs new file mode 100644 index 0000000000000000000000000000000000000000..ddbdb799c8d3a5a22f9400270cb1b71b570c202a --- /dev/null +++ b/backend/node_modules/openai/src/_shims/web-types.mjs @@ -0,0 +1,3 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ diff --git a/backend/node_modules/openai/src/core.ts b/backend/node_modules/openai/src/core.ts new file mode 100644 index 0000000000000000000000000000000000000000..39fe0f97fcff29eb07ea511607a35b2048fe17fd --- /dev/null +++ b/backend/node_modules/openai/src/core.ts @@ -0,0 +1,1162 @@ +import { VERSION } from './version'; +import { Stream } from './streaming'; +import { + OpenAIError, + APIError, + APIConnectionError, + APIConnectionTimeoutError, + APIUserAbortError, +} from './error'; +import { + kind as shimsKind, + type Readable, + getDefaultAgent, + type Agent, + fetch, + type RequestInfo, + type RequestInit, + type Response, + type HeadersInit, +} from './_shims/index'; +export { type Response }; +import { isMultipartBody } from './uploads'; +export { + maybeMultipartFormRequestOptions, + multipartFormRequestOptions, + createForm, + type Uploadable, +} from './uploads'; + +export type Fetch = (url: RequestInfo, init?: RequestInit) => Promise; + +type PromiseOrValue = T | Promise; + +type APIResponseProps = { + response: Response; + options: FinalRequestOptions; + controller: AbortController; +}; + +async function defaultParseResponse(props: APIResponseProps): Promise { + const { response } = props; + if (props.options.stream) { + debug('response', response.status, response.url, response.headers, response.body); + + // Note: there is an invariant here that isn't represented in the type system + // that if you set `stream: true` the response type must also be `Stream` + + if (props.options.__streamClass) { + return props.options.__streamClass.fromSSEResponse(response, props.controller) as any; + } + + return Stream.fromSSEResponse(response, props.controller) as any; + } + + // fetch refuses to read the body when the status code is 204. + if (response.status === 204) { + return null as T; + } + + if (props.options.__binaryResponse) { + return response as unknown as T; + } + + const contentType = response.headers.get('content-type'); + const isJSON = + contentType?.includes('application/json') || contentType?.includes('application/vnd.api+json'); + if (isJSON) { + const json = await response.json(); + + debug('response', response.status, response.url, response.headers, json); + + return json as T; + } + + const text = await response.text(); + debug('response', response.status, response.url, response.headers, text); + + // TODO handle blob, arraybuffer, other content types, etc. + return text as unknown as T; +} + +/** + * A subclass of `Promise` providing additional helper methods + * for interacting with the SDK. + */ +export class APIPromise extends Promise { + private parsedPromise: Promise | undefined; + + constructor( + private responsePromise: Promise, + private parseResponse: (props: APIResponseProps) => PromiseOrValue = defaultParseResponse, + ) { + super((resolve) => { + // this is maybe a bit weird but this has to be a no-op to not implicitly + // parse the response body; instead .then, .catch, .finally are overridden + // to parse the response + resolve(null as any); + }); + } + + _thenUnwrap(transform: (data: T) => U): APIPromise { + return new APIPromise(this.responsePromise, async (props) => transform(await this.parseResponse(props))); + } + + /** + * Gets the raw `Response` instance instead of parsing the response + * data. + * + * If you want to parse the response body but still get the `Response` + * instance, you can use {@link withResponse()}. + * + * 👋 Getting the wrong TypeScript type for `Response`? + * Try setting `"moduleResolution": "NodeNext"` if you can, + * or add one of these imports before your first `import … from 'openai'`: + * - `import 'openai/shims/node'` (if you're running on Node) + * - `import 'openai/shims/web'` (otherwise) + */ + asResponse(): Promise { + return this.responsePromise.then((p) => p.response); + } + /** + * Gets the parsed response data and the raw `Response` instance. + * + * If you just want to get the raw `Response` instance without parsing it, + * you can use {@link asResponse()}. + * + * + * 👋 Getting the wrong TypeScript type for `Response`? + * Try setting `"moduleResolution": "NodeNext"` if you can, + * or add one of these imports before your first `import … from 'openai'`: + * - `import 'openai/shims/node'` (if you're running on Node) + * - `import 'openai/shims/web'` (otherwise) + */ + async withResponse(): Promise<{ data: T; response: Response }> { + const [data, response] = await Promise.all([this.parse(), this.asResponse()]); + return { data, response }; + } + + private parse(): Promise { + if (!this.parsedPromise) { + this.parsedPromise = this.responsePromise.then(this.parseResponse); + } + return this.parsedPromise; + } + + override then( + onfulfilled?: ((value: T) => TResult1 | PromiseLike) | undefined | null, + onrejected?: ((reason: any) => TResult2 | PromiseLike) | undefined | null, + ): Promise { + return this.parse().then(onfulfilled, onrejected); + } + + override catch( + onrejected?: ((reason: any) => TResult | PromiseLike) | undefined | null, + ): Promise { + return this.parse().catch(onrejected); + } + + override finally(onfinally?: (() => void) | undefined | null): Promise { + return this.parse().finally(onfinally); + } +} + +export abstract class APIClient { + baseURL: string; + maxRetries: number; + timeout: number; + httpAgent: Agent | undefined; + + private fetch: Fetch; + protected idempotencyHeader?: string; + + constructor({ + baseURL, + maxRetries = 2, + timeout = 600000, // 10 minutes + httpAgent, + fetch: overridenFetch, + }: { + baseURL: string; + maxRetries?: number | undefined; + timeout: number | undefined; + httpAgent: Agent | undefined; + fetch: Fetch | undefined; + }) { + this.baseURL = baseURL; + this.maxRetries = validatePositiveInteger('maxRetries', maxRetries); + this.timeout = validatePositiveInteger('timeout', timeout); + this.httpAgent = httpAgent; + + this.fetch = overridenFetch ?? fetch; + } + + protected authHeaders(opts: FinalRequestOptions): Headers { + return {}; + } + + /** + * Override this to add your own default headers, for example: + * + * { + * ...super.defaultHeaders(), + * Authorization: 'Bearer 123', + * } + */ + protected defaultHeaders(opts: FinalRequestOptions): Headers { + return { + Accept: 'application/json', + 'Content-Type': 'application/json', + 'User-Agent': this.getUserAgent(), + ...getPlatformHeaders(), + ...this.authHeaders(opts), + }; + } + + protected abstract defaultQuery(): DefaultQuery | undefined; + + /** + * Override this to add your own headers validation: + */ + protected validateHeaders(headers: Headers, customHeaders: Headers) {} + + protected defaultIdempotencyKey(): string { + return `stainless-node-retry-${uuid4()}`; + } + + get(path: string, opts?: PromiseOrValue>): APIPromise { + return this.methodRequest('get', path, opts); + } + + post(path: string, opts?: PromiseOrValue>): APIPromise { + return this.methodRequest('post', path, opts); + } + + patch(path: string, opts?: PromiseOrValue>): APIPromise { + return this.methodRequest('patch', path, opts); + } + + put(path: string, opts?: PromiseOrValue>): APIPromise { + return this.methodRequest('put', path, opts); + } + + delete(path: string, opts?: PromiseOrValue>): APIPromise { + return this.methodRequest('delete', path, opts); + } + + private methodRequest( + method: HTTPMethod, + path: string, + opts?: PromiseOrValue>, + ): APIPromise { + return this.request(Promise.resolve(opts).then((opts) => ({ method, path, ...opts }))); + } + + getAPIList = AbstractPage>( + path: string, + Page: new (...args: any[]) => PageClass, + opts?: RequestOptions, + ): PagePromise { + return this.requestAPIList(Page, { method: 'get', path, ...opts }); + } + + private calculateContentLength(body: unknown): string | null { + if (typeof body === 'string') { + if (typeof Buffer !== 'undefined') { + return Buffer.byteLength(body, 'utf8').toString(); + } + + if (typeof TextEncoder !== 'undefined') { + const encoder = new TextEncoder(); + const encoded = encoder.encode(body); + return encoded.length.toString(); + } + } + + return null; + } + + buildRequest(options: FinalRequestOptions): { req: RequestInit; url: string; timeout: number } { + const { method, path, query, headers: headers = {} } = options; + + const body = + isMultipartBody(options.body) ? options.body.body + : options.body ? JSON.stringify(options.body, null, 2) + : null; + const contentLength = this.calculateContentLength(body); + + const url = this.buildURL(path!, query); + if ('timeout' in options) validatePositiveInteger('timeout', options.timeout); + const timeout = options.timeout ?? this.timeout; + const httpAgent = options.httpAgent ?? this.httpAgent ?? getDefaultAgent(url); + const minAgentTimeout = timeout + 1000; + if ( + typeof (httpAgent as any)?.options?.timeout === 'number' && + minAgentTimeout > ((httpAgent as any).options.timeout ?? 0) + ) { + // Allow any given request to bump our agent active socket timeout. + // This may seem strange, but leaking active sockets should be rare and not particularly problematic, + // and without mutating agent we would need to create more of them. + // This tradeoff optimizes for performance. + (httpAgent as any).options.timeout = minAgentTimeout; + } + + if (this.idempotencyHeader && method !== 'get') { + if (!options.idempotencyKey) options.idempotencyKey = this.defaultIdempotencyKey(); + headers[this.idempotencyHeader] = options.idempotencyKey; + } + + const reqHeaders = this.buildHeaders({ options, headers, contentLength }); + + const req: RequestInit = { + method, + ...(body && { body: body as any }), + headers: reqHeaders, + ...(httpAgent && { agent: httpAgent }), + // @ts-ignore node-fetch uses a custom AbortSignal type that is + // not compatible with standard web types + signal: options.signal ?? null, + }; + + return { req, url, timeout }; + } + + private buildHeaders({ + options, + headers, + contentLength, + }: { + options: FinalRequestOptions; + headers: Record; + contentLength: string | null | undefined; + }): Record { + const reqHeaders: Record = {}; + if (contentLength) { + reqHeaders['content-length'] = contentLength; + } + + const defaultHeaders = this.defaultHeaders(options); + applyHeadersMut(reqHeaders, defaultHeaders); + applyHeadersMut(reqHeaders, headers); + + // let builtin fetch set the Content-Type for multipart bodies + if (isMultipartBody(options.body) && shimsKind !== 'node') { + delete reqHeaders['content-type']; + } + + this.validateHeaders(reqHeaders, headers); + + return reqHeaders; + } + + /** + * Used as a callback for mutating the given `FinalRequestOptions` object. + */ + protected async prepareOptions(options: FinalRequestOptions): Promise {} + + /** + * Used as a callback for mutating the given `RequestInit` object. + * + * This is useful for cases where you want to add certain headers based off of + * the request properties, e.g. `method` or `url`. + */ + protected async prepareRequest( + request: RequestInit, + { url, options }: { url: string; options: FinalRequestOptions }, + ): Promise {} + + protected parseHeaders(headers: HeadersInit | null | undefined): Record { + return ( + !headers ? {} + : Symbol.iterator in headers ? + Object.fromEntries(Array.from(headers as Iterable).map((header) => [...header])) + : { ...headers } + ); + } + + protected makeStatusError( + status: number | undefined, + error: Object | undefined, + message: string | undefined, + headers: Headers | undefined, + ) { + return APIError.generate(status, error, message, headers); + } + + request( + options: PromiseOrValue>, + remainingRetries: number | null = null, + ): APIPromise { + return new APIPromise(this.makeRequest(options, remainingRetries)); + } + + private async makeRequest( + optionsInput: PromiseOrValue>, + retriesRemaining: number | null, + ): Promise { + const options = await optionsInput; + if (retriesRemaining == null) { + retriesRemaining = options.maxRetries ?? this.maxRetries; + } + + await this.prepareOptions(options); + + const { req, url, timeout } = this.buildRequest(options); + + await this.prepareRequest(req, { url, options }); + + debug('request', url, options, req.headers); + + if (options.signal?.aborted) { + throw new APIUserAbortError(); + } + + const controller = new AbortController(); + const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError); + + if (response instanceof Error) { + if (options.signal?.aborted) { + throw new APIUserAbortError(); + } + if (retriesRemaining) { + return this.retryRequest(options, retriesRemaining); + } + if (response.name === 'AbortError') { + throw new APIConnectionTimeoutError(); + } + throw new APIConnectionError({ cause: response }); + } + + const responseHeaders = createResponseHeaders(response.headers); + + if (!response.ok) { + if (retriesRemaining && this.shouldRetry(response)) { + const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; + debug(`response (error; ${retryMessage})`, response.status, url, responseHeaders); + return this.retryRequest(options, retriesRemaining, responseHeaders); + } + + const errText = await response.text().catch((e) => castToError(e).message); + const errJSON = safeJSON(errText); + const errMessage = errJSON ? undefined : errText; + const retryMessage = retriesRemaining ? `(error; no more retries left)` : `(error; not retryable)`; + + debug(`response (error; ${retryMessage})`, response.status, url, responseHeaders, errMessage); + + const err = this.makeStatusError(response.status, errJSON, errMessage, responseHeaders); + throw err; + } + + return { response, options, controller }; + } + + requestAPIList = AbstractPage>( + Page: new (...args: ConstructorParameters) => PageClass, + options: FinalRequestOptions, + ): PagePromise { + const request = this.makeRequest(options, null); + return new PagePromise(this, request, Page); + } + + buildURL(path: string, query: Req | null | undefined): string { + const url = + isAbsoluteURL(path) ? + new URL(path) + : new URL(this.baseURL + (this.baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path)); + + const defaultQuery = this.defaultQuery(); + if (!isEmptyObj(defaultQuery)) { + query = { ...defaultQuery, ...query } as Req; + } + + if (typeof query === 'object' && query && !Array.isArray(query)) { + url.search = this.stringifyQuery(query as Record); + } + + return url.toString(); + } + + protected stringifyQuery(query: Record): string { + return Object.entries(query) + .filter(([_, value]) => typeof value !== 'undefined') + .map(([key, value]) => { + if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { + return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`; + } + if (value === null) { + return `${encodeURIComponent(key)}=`; + } + throw new OpenAIError( + `Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`, + ); + }) + .join('&'); + } + + async fetchWithTimeout( + url: RequestInfo, + init: RequestInit | undefined, + ms: number, + controller: AbortController, + ): Promise { + const { signal, ...options } = init || {}; + if (signal) signal.addEventListener('abort', () => controller.abort()); + + const timeout = setTimeout(() => controller.abort(), ms); + + return ( + this.getRequestClient() + // use undefined this binding; fetch errors if bound to something else in browser/cloudflare + .fetch.call(undefined, url, { signal: controller.signal as any, ...options }) + .finally(() => { + clearTimeout(timeout); + }) + ); + } + + protected getRequestClient(): RequestClient { + return { fetch: this.fetch }; + } + + private shouldRetry(response: Response): boolean { + // Note this is not a standard header. + const shouldRetryHeader = response.headers.get('x-should-retry'); + + // If the server explicitly says whether or not to retry, obey. + if (shouldRetryHeader === 'true') return true; + if (shouldRetryHeader === 'false') return false; + + // Retry on request timeouts. + if (response.status === 408) return true; + + // Retry on lock timeouts. + if (response.status === 409) return true; + + // Retry on rate limits. + if (response.status === 429) return true; + + // Retry internal errors. + if (response.status >= 500) return true; + + return false; + } + + private async retryRequest( + options: FinalRequestOptions, + retriesRemaining: number, + responseHeaders?: Headers | undefined, + ): Promise { + let timeoutMillis: number | undefined; + + // Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it. + const retryAfterMillisHeader = responseHeaders?.['retry-after-ms']; + if (retryAfterMillisHeader) { + const timeoutMs = parseFloat(retryAfterMillisHeader); + if (!Number.isNaN(timeoutMs)) { + timeoutMillis = timeoutMs; + } + } + + // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After + const retryAfterHeader = responseHeaders?.['retry-after']; + if (retryAfterHeader && !timeoutMillis) { + const timeoutSeconds = parseFloat(retryAfterHeader); + if (!Number.isNaN(timeoutSeconds)) { + timeoutMillis = timeoutSeconds * 1000; + } else { + timeoutMillis = Date.parse(retryAfterHeader) - Date.now(); + } + } + + // If the API asks us to wait a certain amount of time (and it's a reasonable amount), + // just do what it says, but otherwise calculate a default + if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) { + const maxRetries = options.maxRetries ?? this.maxRetries; + timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries); + } + await sleep(timeoutMillis); + + return this.makeRequest(options, retriesRemaining - 1); + } + + private calculateDefaultRetryTimeoutMillis(retriesRemaining: number, maxRetries: number): number { + const initialRetryDelay = 0.5; + const maxRetryDelay = 8.0; + + const numRetries = maxRetries - retriesRemaining; + + // Apply exponential backoff, but not more than the max. + const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay); + + // Apply some jitter, take up to at most 25 percent of the retry time. + const jitter = 1 - Math.random() * 0.25; + + return sleepSeconds * jitter * 1000; + } + + private getUserAgent(): string { + return `${this.constructor.name}/JS ${VERSION}`; + } +} + +export type PageInfo = { url: URL } | { params: Record | null }; + +export abstract class AbstractPage implements AsyncIterable { + #client: APIClient; + protected options: FinalRequestOptions; + + protected response: Response; + protected body: unknown; + + constructor(client: APIClient, response: Response, body: unknown, options: FinalRequestOptions) { + this.#client = client; + this.options = options; + this.response = response; + this.body = body; + } + + /** + * @deprecated Use nextPageInfo instead + */ + abstract nextPageParams(): Partial> | null; + abstract nextPageInfo(): PageInfo | null; + + abstract getPaginatedItems(): Item[]; + + hasNextPage(): boolean { + const items = this.getPaginatedItems(); + if (!items.length) return false; + return this.nextPageInfo() != null; + } + + async getNextPage(): Promise { + const nextInfo = this.nextPageInfo(); + if (!nextInfo) { + throw new OpenAIError( + 'No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.', + ); + } + const nextOptions = { ...this.options }; + if ('params' in nextInfo && typeof nextOptions.query === 'object') { + nextOptions.query = { ...nextOptions.query, ...nextInfo.params }; + } else if ('url' in nextInfo) { + const params = [...Object.entries(nextOptions.query || {}), ...nextInfo.url.searchParams.entries()]; + for (const [key, value] of params) { + nextInfo.url.searchParams.set(key, value as any); + } + nextOptions.query = undefined; + nextOptions.path = nextInfo.url.toString(); + } + return await this.#client.requestAPIList(this.constructor as any, nextOptions); + } + + async *iterPages() { + // eslint-disable-next-line @typescript-eslint/no-this-alias + let page: AbstractPage = this; + yield page; + while (page.hasNextPage()) { + page = await page.getNextPage(); + yield page; + } + } + + async *[Symbol.asyncIterator]() { + for await (const page of this.iterPages()) { + for (const item of page.getPaginatedItems()) { + yield item; + } + } + } +} + +/** + * This subclass of Promise will resolve to an instantiated Page once the request completes. + * + * It also implements AsyncIterable to allow auto-paginating iteration on an unawaited list call, eg: + * + * for await (const item of client.items.list()) { + * console.log(item) + * } + */ +export class PagePromise< + PageClass extends AbstractPage, + Item = ReturnType[number], + > + extends APIPromise + implements AsyncIterable +{ + constructor( + client: APIClient, + request: Promise, + Page: new (...args: ConstructorParameters) => PageClass, + ) { + super( + request, + async (props) => new Page(client, props.response, await defaultParseResponse(props), props.options), + ); + } + + /** + * Allow auto-paginating iteration on an unawaited list call, eg: + * + * for await (const item of client.items.list()) { + * console.log(item) + * } + */ + async *[Symbol.asyncIterator]() { + const page = await this; + for await (const item of page) { + yield item; + } + } +} + +export const createResponseHeaders = ( + headers: Awaited>['headers'], +): Record => { + return new Proxy( + Object.fromEntries( + // @ts-ignore + headers.entries(), + ), + { + get(target, name) { + const key = name.toString(); + return target[key.toLowerCase()] || target[key]; + }, + }, + ); +}; + +type HTTPMethod = 'get' | 'post' | 'put' | 'patch' | 'delete'; + +export type RequestClient = { fetch: Fetch }; +export type Headers = Record; +export type DefaultQuery = Record; +export type KeysEnum = { [P in keyof Required]: true }; + +export type RequestOptions | Readable> = { + method?: HTTPMethod; + path?: string; + query?: Req | undefined; + body?: Req | null | undefined; + headers?: Headers | undefined; + + maxRetries?: number; + stream?: boolean | undefined; + timeout?: number; + httpAgent?: Agent; + signal?: AbortSignal | undefined | null; + idempotencyKey?: string; + + __binaryResponse?: boolean | undefined; + __streamClass?: typeof Stream; +}; + +// This is required so that we can determine if a given object matches the RequestOptions +// type at runtime. While this requires duplication, it is enforced by the TypeScript +// compiler such that any missing / extraneous keys will cause an error. +const requestOptionsKeys: KeysEnum = { + method: true, + path: true, + query: true, + body: true, + headers: true, + + maxRetries: true, + stream: true, + timeout: true, + httpAgent: true, + signal: true, + idempotencyKey: true, + + __binaryResponse: true, + __streamClass: true, +}; + +export const isRequestOptions = (obj: unknown): obj is RequestOptions => { + return ( + typeof obj === 'object' && + obj !== null && + !isEmptyObj(obj) && + Object.keys(obj).every((k) => hasOwn(requestOptionsKeys, k)) + ); +}; + +export type FinalRequestOptions | Readable> = RequestOptions & { + method: HTTPMethod; + path: string; +}; + +declare const Deno: any; +declare const EdgeRuntime: any; +type Arch = 'x32' | 'x64' | 'arm' | 'arm64' | `other:${string}` | 'unknown'; +type PlatformName = + | 'MacOS' + | 'Linux' + | 'Windows' + | 'FreeBSD' + | 'OpenBSD' + | 'iOS' + | 'Android' + | `Other:${string}` + | 'Unknown'; +type Browser = 'ie' | 'edge' | 'chrome' | 'firefox' | 'safari'; +type PlatformProperties = { + 'X-Stainless-Lang': 'js'; + 'X-Stainless-Package-Version': string; + 'X-Stainless-OS': PlatformName; + 'X-Stainless-Arch': Arch; + 'X-Stainless-Runtime': 'node' | 'deno' | 'edge' | `browser:${Browser}` | 'unknown'; + 'X-Stainless-Runtime-Version': string; +}; +const getPlatformProperties = (): PlatformProperties => { + if (typeof Deno !== 'undefined' && Deno.build != null) { + return { + 'X-Stainless-Lang': 'js', + 'X-Stainless-Package-Version': VERSION, + 'X-Stainless-OS': normalizePlatform(Deno.build.os), + 'X-Stainless-Arch': normalizeArch(Deno.build.arch), + 'X-Stainless-Runtime': 'deno', + 'X-Stainless-Runtime-Version': + typeof Deno.version === 'string' ? Deno.version : Deno.version?.deno ?? 'unknown', + }; + } + if (typeof EdgeRuntime !== 'undefined') { + return { + 'X-Stainless-Lang': 'js', + 'X-Stainless-Package-Version': VERSION, + 'X-Stainless-OS': 'Unknown', + 'X-Stainless-Arch': `other:${EdgeRuntime}`, + 'X-Stainless-Runtime': 'edge', + 'X-Stainless-Runtime-Version': process.version, + }; + } + // Check if Node.js + if (Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]') { + return { + 'X-Stainless-Lang': 'js', + 'X-Stainless-Package-Version': VERSION, + 'X-Stainless-OS': normalizePlatform(process.platform), + 'X-Stainless-Arch': normalizeArch(process.arch), + 'X-Stainless-Runtime': 'node', + 'X-Stainless-Runtime-Version': process.version, + }; + } + + const browserInfo = getBrowserInfo(); + if (browserInfo) { + return { + 'X-Stainless-Lang': 'js', + 'X-Stainless-Package-Version': VERSION, + 'X-Stainless-OS': 'Unknown', + 'X-Stainless-Arch': 'unknown', + 'X-Stainless-Runtime': `browser:${browserInfo.browser}`, + 'X-Stainless-Runtime-Version': browserInfo.version, + }; + } + + // TODO add support for Cloudflare workers, etc. + return { + 'X-Stainless-Lang': 'js', + 'X-Stainless-Package-Version': VERSION, + 'X-Stainless-OS': 'Unknown', + 'X-Stainless-Arch': 'unknown', + 'X-Stainless-Runtime': 'unknown', + 'X-Stainless-Runtime-Version': 'unknown', + }; +}; + +type BrowserInfo = { + browser: Browser; + version: string; +}; + +declare const navigator: { userAgent: string } | undefined; + +// Note: modified from https://github.com/JS-DevTools/host-environment/blob/b1ab79ecde37db5d6e163c050e54fe7d287d7c92/src/isomorphic.browser.ts +function getBrowserInfo(): BrowserInfo | null { + if (typeof navigator === 'undefined' || !navigator) { + return null; + } + + // NOTE: The order matters here! + const browserPatterns = [ + { key: 'edge' as const, pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'ie' as const, pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'ie' as const, pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'chrome' as const, pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'firefox' as const, pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'safari' as const, pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ }, + ]; + + // Find the FIRST matching browser + for (const { key, pattern } of browserPatterns) { + const match = pattern.exec(navigator.userAgent); + if (match) { + const major = match[1] || 0; + const minor = match[2] || 0; + const patch = match[3] || 0; + + return { browser: key, version: `${major}.${minor}.${patch}` }; + } + } + + return null; +} + +const normalizeArch = (arch: string): Arch => { + // Node docs: + // - https://nodejs.org/api/process.html#processarch + // Deno docs: + // - https://doc.deno.land/deno/stable/~/Deno.build + if (arch === 'x32') return 'x32'; + if (arch === 'x86_64' || arch === 'x64') return 'x64'; + if (arch === 'arm') return 'arm'; + if (arch === 'aarch64' || arch === 'arm64') return 'arm64'; + if (arch) return `other:${arch}`; + return 'unknown'; +}; + +const normalizePlatform = (platform: string): PlatformName => { + // Node platforms: + // - https://nodejs.org/api/process.html#processplatform + // Deno platforms: + // - https://doc.deno.land/deno/stable/~/Deno.build + // - https://github.com/denoland/deno/issues/14799 + + platform = platform.toLowerCase(); + + // NOTE: this iOS check is untested and may not work + // Node does not work natively on IOS, there is a fork at + // https://github.com/nodejs-mobile/nodejs-mobile + // however it is unknown at the time of writing how to detect if it is running + if (platform.includes('ios')) return 'iOS'; + if (platform === 'android') return 'Android'; + if (platform === 'darwin') return 'MacOS'; + if (platform === 'win32') return 'Windows'; + if (platform === 'freebsd') return 'FreeBSD'; + if (platform === 'openbsd') return 'OpenBSD'; + if (platform === 'linux') return 'Linux'; + if (platform) return `Other:${platform}`; + return 'Unknown'; +}; + +let _platformHeaders: PlatformProperties; +const getPlatformHeaders = () => { + return (_platformHeaders ??= getPlatformProperties()); +}; + +export const safeJSON = (text: string) => { + try { + return JSON.parse(text); + } catch (err) { + return undefined; + } +}; + +// https://stackoverflow.com/a/19709846 +const startsWithSchemeRegexp = new RegExp('^(?:[a-z]+:)?//', 'i'); +const isAbsoluteURL = (url: string): boolean => { + return startsWithSchemeRegexp.test(url); +}; + +export const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); + +const validatePositiveInteger = (name: string, n: unknown): number => { + if (typeof n !== 'number' || !Number.isInteger(n)) { + throw new OpenAIError(`${name} must be an integer`); + } + if (n < 0) { + throw new OpenAIError(`${name} must be a positive integer`); + } + return n; +}; + +export const castToError = (err: any): Error => { + if (err instanceof Error) return err; + return new Error(err); +}; + +export const ensurePresent = (value: T | null | undefined): T => { + if (value == null) throw new OpenAIError(`Expected a value to be given but received ${value} instead.`); + return value; +}; + +/** + * Read an environment variable. + * + * Trims beginning and trailing whitespace. + * + * Will return undefined if the environment variable doesn't exist or cannot be accessed. + */ +export const readEnv = (env: string): string | undefined => { + if (typeof process !== 'undefined') { + return process.env?.[env]?.trim() ?? undefined; + } + if (typeof Deno !== 'undefined') { + return Deno.env?.get?.(env)?.trim(); + } + return undefined; +}; + +export const coerceInteger = (value: unknown): number => { + if (typeof value === 'number') return Math.round(value); + if (typeof value === 'string') return parseInt(value, 10); + + throw new OpenAIError(`Could not coerce ${value} (type: ${typeof value}) into a number`); +}; + +export const coerceFloat = (value: unknown): number => { + if (typeof value === 'number') return value; + if (typeof value === 'string') return parseFloat(value); + + throw new OpenAIError(`Could not coerce ${value} (type: ${typeof value}) into a number`); +}; + +export const coerceBoolean = (value: unknown): boolean => { + if (typeof value === 'boolean') return value; + if (typeof value === 'string') return value === 'true'; + return Boolean(value); +}; + +export const maybeCoerceInteger = (value: unknown): number | undefined => { + if (value === undefined) { + return undefined; + } + return coerceInteger(value); +}; + +export const maybeCoerceFloat = (value: unknown): number | undefined => { + if (value === undefined) { + return undefined; + } + return coerceFloat(value); +}; + +export const maybeCoerceBoolean = (value: unknown): boolean | undefined => { + if (value === undefined) { + return undefined; + } + return coerceBoolean(value); +}; + +// https://stackoverflow.com/a/34491287 +export function isEmptyObj(obj: Object | null | undefined): boolean { + if (!obj) return true; + for (const _k in obj) return false; + return true; +} + +// https://eslint.org/docs/latest/rules/no-prototype-builtins +export function hasOwn(obj: Object, key: string): boolean { + return Object.prototype.hasOwnProperty.call(obj, key); +} + +/** + * Copies headers from "newHeaders" onto "targetHeaders", + * using lower-case for all properties, + * ignoring any keys with undefined values, + * and deleting any keys with null values. + */ +function applyHeadersMut(targetHeaders: Headers, newHeaders: Headers): void { + for (const k in newHeaders) { + if (!hasOwn(newHeaders, k)) continue; + const lowerKey = k.toLowerCase(); + if (!lowerKey) continue; + + const val = newHeaders[k]; + + if (val === null) { + delete targetHeaders[lowerKey]; + } else if (val !== undefined) { + targetHeaders[lowerKey] = val; + } + } +} + +export function debug(action: string, ...args: any[]) { + if (typeof process !== 'undefined' && process?.env?.['DEBUG'] === 'true') { + console.log(`OpenAI:DEBUG:${action}`, ...args); + } +} + +/** + * https://stackoverflow.com/a/2117523 + */ +const uuid4 = () => { + return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => { + const r = (Math.random() * 16) | 0; + const v = c === 'x' ? r : (r & 0x3) | 0x8; + return v.toString(16); + }); +}; + +export const isRunningInBrowser = () => { + return ( + // @ts-ignore + typeof window !== 'undefined' && + // @ts-ignore + typeof window.document !== 'undefined' && + // @ts-ignore + typeof navigator !== 'undefined' + ); +}; + +export interface HeadersProtocol { + get: (header: string) => string | null | undefined; +} +export type HeadersLike = Record | HeadersProtocol; + +export const isHeadersProtocol = (headers: any): headers is HeadersProtocol => { + return typeof headers?.get === 'function'; +}; + +export const getRequiredHeader = (headers: HeadersLike, header: string): string => { + const lowerCasedHeader = header.toLowerCase(); + if (isHeadersProtocol(headers)) { + // to deal with the case where the header looks like Stainless-Event-Id + const intercapsHeader = + header[0]?.toUpperCase() + + header.substring(1).replace(/([^\w])(\w)/g, (_m, g1, g2) => g1 + g2.toUpperCase()); + for (const key of [header, lowerCasedHeader, header.toUpperCase(), intercapsHeader]) { + const value = headers.get(key); + if (value) { + return value; + } + } + } + + for (const [key, value] of Object.entries(headers)) { + if (key.toLowerCase() === lowerCasedHeader) { + if (Array.isArray(value)) { + if (value.length <= 1) return value[0]; + console.warn(`Received ${value.length} entries for the ${header} header, using the first entry.`); + return value[0]; + } + return value; + } + } + + throw new Error(`Could not find ${header} header`); +}; + +/** + * Encodes a string to Base64 format. + */ +export const toBase64 = (str: string | null | undefined): string => { + if (!str) return ''; + if (typeof Buffer !== 'undefined') { + return Buffer.from(str).toString('base64'); + } + + if (typeof btoa !== 'undefined') { + return btoa(str); + } + + throw new OpenAIError('Cannot generate b64 string; Expected `Buffer` or `btoa` to be defined'); +}; + +export function isObj(obj: unknown): obj is Record { + return obj != null && typeof obj === 'object' && !Array.isArray(obj); +} diff --git a/backend/node_modules/openai/src/error.ts b/backend/node_modules/openai/src/error.ts new file mode 100644 index 0000000000000000000000000000000000000000..19a60598a45df57a6739bc294dea6efefae2ffe7 --- /dev/null +++ b/backend/node_modules/openai/src/error.ts @@ -0,0 +1,158 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { castToError, Headers } from './core'; + +export class OpenAIError extends Error {} + +export class APIError extends OpenAIError { + readonly status: number | undefined; + readonly headers: Headers | undefined; + readonly error: Object | undefined; + + readonly code: string | null | undefined; + readonly param: string | null | undefined; + readonly type: string | undefined; + + readonly request_id: string | null | undefined; + + constructor( + status: number | undefined, + error: Object | undefined, + message: string | undefined, + headers: Headers | undefined, + ) { + super(`${APIError.makeMessage(status, error, message)}`); + this.status = status; + this.headers = headers; + this.request_id = headers?.['x-request-id']; + + const data = error as Record; + this.error = data; + this.code = data?.['code']; + this.param = data?.['param']; + this.type = data?.['type']; + } + + private static makeMessage(status: number | undefined, error: any, message: string | undefined) { + const msg = + error?.message ? + typeof error.message === 'string' ? + error.message + : JSON.stringify(error.message) + : error ? JSON.stringify(error) + : message; + + if (status && msg) { + return `${status} ${msg}`; + } + if (status) { + return `${status} status code (no body)`; + } + if (msg) { + return msg; + } + return '(no status code or body)'; + } + + static generate( + status: number | undefined, + errorResponse: Object | undefined, + message: string | undefined, + headers: Headers | undefined, + ) { + if (!status) { + return new APIConnectionError({ cause: castToError(errorResponse) }); + } + + const error = (errorResponse as Record)?.['error']; + + if (status === 400) { + return new BadRequestError(status, error, message, headers); + } + + if (status === 401) { + return new AuthenticationError(status, error, message, headers); + } + + if (status === 403) { + return new PermissionDeniedError(status, error, message, headers); + } + + if (status === 404) { + return new NotFoundError(status, error, message, headers); + } + + if (status === 409) { + return new ConflictError(status, error, message, headers); + } + + if (status === 422) { + return new UnprocessableEntityError(status, error, message, headers); + } + + if (status === 429) { + return new RateLimitError(status, error, message, headers); + } + + if (status >= 500) { + return new InternalServerError(status, error, message, headers); + } + + return new APIError(status, error, message, headers); + } +} + +export class APIUserAbortError extends APIError { + override readonly status: undefined = undefined; + + constructor({ message }: { message?: string } = {}) { + super(undefined, undefined, message || 'Request was aborted.', undefined); + } +} + +export class APIConnectionError extends APIError { + override readonly status: undefined = undefined; + + constructor({ message, cause }: { message?: string; cause?: Error | undefined }) { + super(undefined, undefined, message || 'Connection error.', undefined); + // in some environments the 'cause' property is already declared + // @ts-ignore + if (cause) this.cause = cause; + } +} + +export class APIConnectionTimeoutError extends APIConnectionError { + constructor({ message }: { message?: string } = {}) { + super({ message: message ?? 'Request timed out.' }); + } +} + +export class BadRequestError extends APIError { + override readonly status: 400 = 400; +} + +export class AuthenticationError extends APIError { + override readonly status: 401 = 401; +} + +export class PermissionDeniedError extends APIError { + override readonly status: 403 = 403; +} + +export class NotFoundError extends APIError { + override readonly status: 404 = 404; +} + +export class ConflictError extends APIError { + override readonly status: 409 = 409; +} + +export class UnprocessableEntityError extends APIError { + override readonly status: 422 = 422; +} + +export class RateLimitError extends APIError { + override readonly status: 429 = 429; +} + +export class InternalServerError extends APIError {} diff --git a/backend/node_modules/openai/src/index.ts b/backend/node_modules/openai/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..672a55a5d7da28190d60759ecab2c256ea1f8bc9 --- /dev/null +++ b/backend/node_modules/openai/src/index.ts @@ -0,0 +1,300 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import * as Core from './core'; +import * as Errors from './error'; +import { type Agent } from './_shims/index'; +import * as Uploads from './uploads'; +import * as Pagination from "./pagination"; +import * as API from "./resources/index"; + +export interface ClientOptions { + /** + * Defaults to process.env['OPENAI_API_KEY']. + */ + apiKey?: string | undefined; + + /** + * Defaults to process.env['OPENAI_ORG_ID']. + */ + organization?: string | null | undefined; + + /** + * Override the default base URL for the API, e.g., "https://api.example.com/v2/" + * + * Defaults to process.env['OPENAI_BASE_URL']. + */ + baseURL?: string | null | undefined; + + /** + * The maximum amount of time (in milliseconds) that the client should wait for a response + * from the server before timing out a single request. + * + * Note that request timeouts are retried by default, so in a worst-case scenario you may wait + * much longer than this timeout before the promise succeeds or fails. + */ + timeout?: number; + + /** + * An HTTP agent used to manage HTTP(S) connections. + * + * If not provided, an agent will be constructed by default in the Node.js environment, + * otherwise no agent is used. + */ + httpAgent?: Agent; + + /** + * Specify a custom `fetch` function implementation. + * + * If not provided, we use `node-fetch` on Node.js and otherwise expect that `fetch` is + * defined globally. + */ + fetch?: Core.Fetch | undefined; + + /** + * The maximum number of times that the client will retry a request in case of a + * temporary failure, like a network error or a 5XX error from the server. + * + * @default 2 + */ + maxRetries?: number; + + /** + * Default headers to include with every request to the API. + * + * These can be removed in individual requests by explicitly setting the + * header to `undefined` or `null` in request options. + */ + defaultHeaders?: Core.Headers; + + /** + * Default query parameters to include with every request to the API. + * + * These can be removed in individual requests by explicitly setting the + * param to `undefined` in request options. + */ + defaultQuery?: Core.DefaultQuery; + + /** + * By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers. + * Only set this option to `true` if you understand the risks and have appropriate mitigations in place. + */ + dangerouslyAllowBrowser?: boolean; +} + +/** API Client for interfacing with the OpenAI API. */ +export class OpenAI extends Core.APIClient { + apiKey: string; + organization: string | null; + + private _options: ClientOptions; + + /** + * API Client for interfacing with the OpenAI API. + * + * @param {string | undefined} [opts.apiKey=process.env['OPENAI_API_KEY'] ?? undefined] + * @param {string | null | undefined} [opts.organization=process.env['OPENAI_ORG_ID'] ?? null] + * @param {string} [opts.baseURL=process.env['OPENAI_BASE_URL'] ?? https://api.openai.com/v1] - Override the default base URL for the API. + * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. + * @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections. + * @param {Core.Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. + * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. + * @param {Core.Headers} opts.defaultHeaders - Default headers to include with every request to the API. + * @param {Core.DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API. + * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers. + */ + constructor({ + baseURL = Core.readEnv('OPENAI_BASE_URL'), + apiKey = Core.readEnv('OPENAI_API_KEY'), + organization = Core.readEnv('OPENAI_ORG_ID') ?? null, + ...opts + }: ClientOptions = {}) { + if (apiKey === undefined) { + throw new Errors.OpenAIError( + "The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).", + ); + } + + const options: ClientOptions = { + apiKey, + organization, + ...opts, + baseURL: baseURL || `https://api.openai.com/v1`, + }; + + if (!options.dangerouslyAllowBrowser && Core.isRunningInBrowser()) { + throw new Errors.OpenAIError( + "It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n", + ); + } + + super({ + baseURL: options.baseURL!, + timeout: options.timeout ?? 600000 /* 10 minutes */, + httpAgent: options.httpAgent, + maxRetries: options.maxRetries, + fetch: options.fetch, + }); + this._options = options; + + this.apiKey = apiKey; + this.organization = organization; + } + + completions: API.Completions = new API.Completions(this); + chat: API.Chat = new API.Chat(this); + embeddings: API.Embeddings = new API.Embeddings(this); + files: API.Files = new API.Files(this); + images: API.Images = new API.Images(this); + audio: API.Audio = new API.Audio(this); + moderations: API.Moderations = new API.Moderations(this); + models: API.Models = new API.Models(this); + fineTuning: API.FineTuning = new API.FineTuning(this); + beta: API.Beta = new API.Beta(this); + batches: API.Batches = new API.Batches(this); + + protected override defaultQuery(): Core.DefaultQuery | undefined { + return this._options.defaultQuery; + } + + protected override defaultHeaders(opts: Core.FinalRequestOptions): Core.Headers { + return { + ...super.defaultHeaders(opts), + 'OpenAI-Organization': this.organization, + ...this._options.defaultHeaders, + }; + } + + protected override authHeaders(opts: Core.FinalRequestOptions): Core.Headers { + return { Authorization: `Bearer ${this.apiKey}` }; + } + + static OpenAI = this; + + static OpenAIError = Errors.OpenAIError; + static APIError = Errors.APIError; + static APIConnectionError = Errors.APIConnectionError; + static APIConnectionTimeoutError = Errors.APIConnectionTimeoutError; + static APIUserAbortError = Errors.APIUserAbortError; + static NotFoundError = Errors.NotFoundError; + static ConflictError = Errors.ConflictError; + static RateLimitError = Errors.RateLimitError; + static BadRequestError = Errors.BadRequestError; + static AuthenticationError = Errors.AuthenticationError; + static InternalServerError = Errors.InternalServerError; + static PermissionDeniedError = Errors.PermissionDeniedError; + static UnprocessableEntityError = Errors.UnprocessableEntityError; +} + +export const { + OpenAIError, + APIError, + APIConnectionError, + APIConnectionTimeoutError, + APIUserAbortError, + NotFoundError, + ConflictError, + RateLimitError, + BadRequestError, + AuthenticationError, + InternalServerError, + PermissionDeniedError, + UnprocessableEntityError, +} = Errors; + +export import toFile = Uploads.toFile; +export import fileFromPath = Uploads.fileFromPath; + +export namespace OpenAI { + // Helper functions + export import toFile = Uploads.toFile; + export import fileFromPath = Uploads.fileFromPath; + + export import RequestOptions = Core.RequestOptions; + + export import Page = Pagination.Page; + export import PageResponse = Pagination.PageResponse; + + export import CursorPage = Pagination.CursorPage; + export import CursorPageParams = Pagination.CursorPageParams; + export import CursorPageResponse = Pagination.CursorPageResponse; + + export import Completions = API.Completions; + export import Completion = API.Completion; + export import CompletionChoice = API.CompletionChoice; + export import CompletionUsage = API.CompletionUsage; + export import CompletionCreateParams = API.CompletionCreateParams; + export import CompletionCreateParamsNonStreaming = API.CompletionCreateParamsNonStreaming; + export import CompletionCreateParamsStreaming = API.CompletionCreateParamsStreaming; + + export import Chat = API.Chat; + export import ChatCompletion = API.ChatCompletion; + export import ChatCompletionAssistantMessageParam = API.ChatCompletionAssistantMessageParam; + export import ChatCompletionChunk = API.ChatCompletionChunk; + export import ChatCompletionContentPart = API.ChatCompletionContentPart; + export import ChatCompletionContentPartImage = API.ChatCompletionContentPartImage; + export import ChatCompletionContentPartText = API.ChatCompletionContentPartText; + export import ChatCompletionFunctionCallOption = API.ChatCompletionFunctionCallOption; + export import ChatCompletionFunctionMessageParam = API.ChatCompletionFunctionMessageParam; + export import ChatCompletionMessage = API.ChatCompletionMessage; + export import ChatCompletionMessageParam = API.ChatCompletionMessageParam; + export import ChatCompletionMessageToolCall = API.ChatCompletionMessageToolCall; + export import ChatCompletionNamedToolChoice = API.ChatCompletionNamedToolChoice; + export import ChatCompletionRole = API.ChatCompletionRole; + export import ChatCompletionSystemMessageParam = API.ChatCompletionSystemMessageParam; + export import ChatCompletionTokenLogprob = API.ChatCompletionTokenLogprob; + export import ChatCompletionTool = API.ChatCompletionTool; + export import ChatCompletionToolChoiceOption = API.ChatCompletionToolChoiceOption; + export import ChatCompletionToolMessageParam = API.ChatCompletionToolMessageParam; + export import ChatCompletionUserMessageParam = API.ChatCompletionUserMessageParam; + export import ChatCompletionCreateParams = API.ChatCompletionCreateParams; + export import ChatCompletionCreateParamsNonStreaming = API.ChatCompletionCreateParamsNonStreaming; + export import ChatCompletionCreateParamsStreaming = API.ChatCompletionCreateParamsStreaming; + + export import Embeddings = API.Embeddings; + export import CreateEmbeddingResponse = API.CreateEmbeddingResponse; + export import Embedding = API.Embedding; + export import EmbeddingCreateParams = API.EmbeddingCreateParams; + + export import Files = API.Files; + export import FileContent = API.FileContent; + export import FileDeleted = API.FileDeleted; + export import FileObject = API.FileObject; + export import FileObjectsPage = API.FileObjectsPage; + export import FileCreateParams = API.FileCreateParams; + export import FileListParams = API.FileListParams; + + export import Images = API.Images; + export import Image = API.Image; + export import ImagesResponse = API.ImagesResponse; + export import ImageCreateVariationParams = API.ImageCreateVariationParams; + export import ImageEditParams = API.ImageEditParams; + export import ImageGenerateParams = API.ImageGenerateParams; + + export import Audio = API.Audio; + + export import Moderations = API.Moderations; + export import Moderation = API.Moderation; + export import ModerationCreateResponse = API.ModerationCreateResponse; + export import ModerationCreateParams = API.ModerationCreateParams; + + export import Models = API.Models; + export import Model = API.Model; + export import ModelDeleted = API.ModelDeleted; + export import ModelsPage = API.ModelsPage; + + export import FineTuning = API.FineTuning; + + export import Beta = API.Beta; + + export import Batches = API.Batches; + export import Batch = API.Batch; + export import BatchError = API.BatchError; + export import BatchRequestCounts = API.BatchRequestCounts; + export import BatchCreateParams = API.BatchCreateParams; + + export import ErrorObject = API.ErrorObject; + export import FunctionDefinition = API.FunctionDefinition; + export import FunctionParameters = API.FunctionParameters; +} + +export default OpenAI; diff --git a/backend/node_modules/openai/src/lib/.keep b/backend/node_modules/openai/src/lib/.keep new file mode 100644 index 0000000000000000000000000000000000000000..7554f8b20ae58485df49010107f79349db1c5943 --- /dev/null +++ b/backend/node_modules/openai/src/lib/.keep @@ -0,0 +1,4 @@ +File generated from our OpenAPI spec by Stainless. + +This directory can be used to store custom files to expand the SDK. +It is ignored by Stainless code generation and its content (other than this keep file) won't be touched. diff --git a/backend/node_modules/openai/src/lib/AbstractAssistantStreamRunner.ts b/backend/node_modules/openai/src/lib/AbstractAssistantStreamRunner.ts new file mode 100644 index 0000000000000000000000000000000000000000..ebdb86a51e04bf890a961726b578fa759c7e46c8 --- /dev/null +++ b/backend/node_modules/openai/src/lib/AbstractAssistantStreamRunner.ts @@ -0,0 +1,340 @@ +import * as Core from "../core"; +import { APIUserAbortError, OpenAIError } from "../error"; +import { Run, RunSubmitToolOutputsParamsBase } from "../resources/beta/threads/runs/runs"; +import { RunCreateParamsBase, Runs } from "../resources/beta/threads/runs/runs"; +import { ThreadCreateAndRunParamsBase, Threads } from "../resources/beta/threads/threads"; + +export abstract class AbstractAssistantStreamRunner< + Events extends CustomEvents = AbstractAssistantRunnerEvents, +> { + controller: AbortController = new AbortController(); + + #connectedPromise: Promise; + #resolveConnectedPromise: () => void = () => {}; + #rejectConnectedPromise: (error: OpenAIError) => void = () => {}; + + #endPromise: Promise; + #resolveEndPromise: () => void = () => {}; + #rejectEndPromise: (error: OpenAIError) => void = () => {}; + + #listeners: { [Event in keyof Events]?: ListenersForEvent } = {}; + + #ended = false; + #errored = false; + #aborted = false; + #catchingPromiseCreated = false; + + constructor() { + this.#connectedPromise = new Promise((resolve, reject) => { + this.#resolveConnectedPromise = resolve; + this.#rejectConnectedPromise = reject; + }); + + this.#endPromise = new Promise((resolve, reject) => { + this.#resolveEndPromise = resolve; + this.#rejectEndPromise = reject; + }); + + // Don't let these promises cause unhandled rejection errors. + // we will manually cause an unhandled rejection error later + // if the user hasn't registered any error listener or called + // any promise-returning method. + this.#connectedPromise.catch(() => {}); + this.#endPromise.catch(() => {}); + } + + protected _run(executor: () => Promise) { + // Unfortunately if we call `executor()` immediately we get runtime errors about + // references to `this` before the `super()` constructor call returns. + setTimeout(() => { + executor().then(() => { + // this._emitFinal(); + this._emit('end'); + }, this.#handleError); + }, 0); + } + + protected _addRun(run: Run): Run { + return run; + } + + protected _connected() { + if (this.ended) return; + this.#resolveConnectedPromise(); + this._emit('connect'); + } + + get ended(): boolean { + return this.#ended; + } + + get errored(): boolean { + return this.#errored; + } + + get aborted(): boolean { + return this.#aborted; + } + + abort() { + this.controller.abort(); + } + + /** + * Adds the listener function to the end of the listeners array for the event. + * No checks are made to see if the listener has already been added. Multiple calls passing + * the same combination of event and listener will result in the listener being added, and + * called, multiple times. + * @returns this ChatCompletionStream, so that calls can be chained + */ + on(event: Event, listener: ListenerForEvent): this { + const listeners: ListenersForEvent = + this.#listeners[event] || (this.#listeners[event] = []); + listeners.push({ listener }); + return this; + } + + /** + * Removes the specified listener from the listener array for the event. + * off() will remove, at most, one instance of a listener from the listener array. If any single + * listener has been added multiple times to the listener array for the specified event, then + * off() must be called multiple times to remove each instance. + * @returns this ChatCompletionStream, so that calls can be chained + */ + off(event: Event, listener: ListenerForEvent): this { + const listeners = this.#listeners[event]; + if (!listeners) return this; + const index = listeners.findIndex((l) => l.listener === listener); + if (index >= 0) listeners.splice(index, 1); + return this; + } + + /** + * Adds a one-time listener function for the event. The next time the event is triggered, + * this listener is removed and then invoked. + * @returns this ChatCompletionStream, so that calls can be chained + */ + once(event: Event, listener: ListenerForEvent): this { + const listeners: ListenersForEvent = + this.#listeners[event] || (this.#listeners[event] = []); + listeners.push({ listener, once: true }); + return this; + } + + /** + * This is similar to `.once()`, but returns a Promise that resolves the next time + * the event is triggered, instead of calling a listener callback. + * @returns a Promise that resolves the next time given event is triggered, + * or rejects if an error is emitted. (If you request the 'error' event, + * returns a promise that resolves with the error). + * + * Example: + * + * const message = await stream.emitted('message') // rejects if the stream errors + */ + emitted( + event: Event, + ): Promise< + EventParameters extends [infer Param] ? Param + : EventParameters extends [] ? void + : EventParameters + > { + return new Promise((resolve, reject) => { + this.#catchingPromiseCreated = true; + if (event !== 'error') this.once('error', reject); + this.once(event, resolve as any); + }); + } + + async done(): Promise { + this.#catchingPromiseCreated = true; + await this.#endPromise; + } + + #handleError = (error: unknown) => { + this.#errored = true; + if (error instanceof Error && error.name === 'AbortError') { + error = new APIUserAbortError(); + } + if (error instanceof APIUserAbortError) { + this.#aborted = true; + return this._emit('abort', error); + } + if (error instanceof OpenAIError) { + return this._emit('error', error); + } + if (error instanceof Error) { + const openAIError: OpenAIError = new OpenAIError(error.message); + // @ts-ignore + openAIError.cause = error; + return this._emit('error', openAIError); + } + return this._emit('error', new OpenAIError(String(error))); + }; + + protected _emit(event: Event, ...args: EventParameters) { + // make sure we don't emit any events after end + if (this.#ended) { + return; + } + + if (event === 'end') { + this.#ended = true; + this.#resolveEndPromise(); + } + + const listeners: ListenersForEvent | undefined = this.#listeners[event]; + if (listeners) { + this.#listeners[event] = listeners.filter((l) => !l.once) as any; + listeners.forEach(({ listener }: any) => listener(...args)); + } + + if (event === 'abort') { + const error = args[0] as APIUserAbortError; + if (!this.#catchingPromiseCreated && !listeners?.length) { + Promise.reject(error); + } + this.#rejectConnectedPromise(error); + this.#rejectEndPromise(error); + this._emit('end'); + return; + } + + if (event === 'error') { + // NOTE: _emit('error', error) should only be called from #handleError(). + + const error = args[0] as OpenAIError; + if (!this.#catchingPromiseCreated && !listeners?.length) { + // Trigger an unhandled rejection if the user hasn't registered any error handlers. + // If you are seeing stack traces here, make sure to handle errors via either: + // - runner.on('error', () => ...) + // - await runner.done() + // - await runner.finalChatCompletion() + // - etc. + Promise.reject(error); + } + this.#rejectConnectedPromise(error); + this.#rejectEndPromise(error); + this._emit('end'); + } + } + + protected async _threadAssistantStream( + body: ThreadCreateAndRunParamsBase, + thread: Threads, + options?: Core.RequestOptions, + ): Promise { + return await this._createThreadAssistantStream(thread, body, options); + } + + protected async _runAssistantStream( + threadId: string, + runs: Runs, + params: RunCreateParamsBase, + options?: Core.RequestOptions, + ): Promise { + return await this._createAssistantStream(runs, threadId, params, options); + } + + protected async _runToolAssistantStream( + threadId: string, + runId: string, + runs: Runs, + params: RunSubmitToolOutputsParamsBase, + options?: Core.RequestOptions, + ): Promise { + return await this._createToolAssistantStream(runs, threadId, runId, params, options); + } + + protected async _createThreadAssistantStream( + thread: Threads, + body: ThreadCreateAndRunParamsBase, + options?: Core.RequestOptions, + ): Promise { + const signal = options?.signal; + if (signal) { + if (signal.aborted) this.controller.abort(); + signal.addEventListener('abort', () => this.controller.abort()); + } + // this.#validateParams(params); + + const runResult = await thread.createAndRun( + { ...body, stream: false }, + { ...options, signal: this.controller.signal }, + ); + this._connected(); + return this._addRun(runResult as Run); + } + + protected async _createToolAssistantStream( + run: Runs, + threadId: string, + runId: string, + params: RunSubmitToolOutputsParamsBase, + options?: Core.RequestOptions, + ): Promise { + const signal = options?.signal; + if (signal) { + if (signal.aborted) this.controller.abort(); + signal.addEventListener('abort', () => this.controller.abort()); + } + + const runResult = await run.submitToolOutputs( + threadId, + runId, + { ...params, stream: false }, + { ...options, signal: this.controller.signal }, + ); + this._connected(); + return this._addRun(runResult as Run); + } + + protected async _createAssistantStream( + run: Runs, + threadId: string, + params: RunCreateParamsBase, + options?: Core.RequestOptions, + ): Promise { + const signal = options?.signal; + if (signal) { + if (signal.aborted) this.controller.abort(); + signal.addEventListener('abort', () => this.controller.abort()); + } + // this.#validateParams(params); + + const runResult = await run.create( + threadId, + { ...params, stream: false }, + { ...options, signal: this.controller.signal }, + ); + this._connected(); + return this._addRun(runResult as Run); + } +} + +type CustomEvents = { + [k in Event]: k extends keyof AbstractAssistantRunnerEvents ? AbstractAssistantRunnerEvents[k] + : (...args: any[]) => void; +}; + +type ListenerForEvent, Event extends keyof Events> = Event extends ( + keyof AbstractAssistantRunnerEvents +) ? + AbstractAssistantRunnerEvents[Event] +: Events[Event]; + +type ListenersForEvent, Event extends keyof Events> = Array<{ + listener: ListenerForEvent; + once?: boolean; +}>; +type EventParameters, Event extends keyof Events> = Parameters< + ListenerForEvent +>; + +export interface AbstractAssistantRunnerEvents { + connect: () => void; + run: (run: Run) => void; + error: (error: OpenAIError) => void; + abort: (error: APIUserAbortError) => void; + end: () => void; +} diff --git a/backend/node_modules/openai/src/lib/AbstractChatCompletionRunner.ts b/backend/node_modules/openai/src/lib/AbstractChatCompletionRunner.ts new file mode 100644 index 0000000000000000000000000000000000000000..67a75b8554e2160a978d7aef7c54585a7c442a1d --- /dev/null +++ b/backend/node_modules/openai/src/lib/AbstractChatCompletionRunner.ts @@ -0,0 +1,682 @@ +import * as Core from "../core"; +import { type CompletionUsage } from "../resources/completions"; +import { + type Completions, + type ChatCompletion, + type ChatCompletionMessage, + type ChatCompletionMessageParam, + type ChatCompletionCreateParams, + type ChatCompletionTool, +} from "../resources/chat/completions"; +import { APIUserAbortError, OpenAIError } from "../error"; +import { + type RunnableFunction, + isRunnableFunctionWithParse, + type BaseFunctionsArgs, +} from './RunnableFunction'; +import { ChatCompletionFunctionRunnerParams, ChatCompletionToolRunnerParams } from './ChatCompletionRunner'; +import { + ChatCompletionStreamingFunctionRunnerParams, + ChatCompletionStreamingToolRunnerParams, +} from './ChatCompletionStreamingRunner'; +import { isAssistantMessage, isFunctionMessage, isToolMessage } from './chatCompletionUtils'; + +const DEFAULT_MAX_CHAT_COMPLETIONS = 10; +export interface RunnerOptions extends Core.RequestOptions { + /** How many requests to make before canceling. Default 10. */ + maxChatCompletions?: number; +} + +export abstract class AbstractChatCompletionRunner< + Events extends CustomEvents = AbstractChatCompletionRunnerEvents, +> { + controller: AbortController = new AbortController(); + + #connectedPromise: Promise; + #resolveConnectedPromise: () => void = () => {}; + #rejectConnectedPromise: (error: OpenAIError) => void = () => {}; + + #endPromise: Promise; + #resolveEndPromise: () => void = () => {}; + #rejectEndPromise: (error: OpenAIError) => void = () => {}; + + #listeners: { [Event in keyof Events]?: ListenersForEvent } = {}; + + protected _chatCompletions: ChatCompletion[] = []; + messages: ChatCompletionMessageParam[] = []; + + #ended = false; + #errored = false; + #aborted = false; + #catchingPromiseCreated = false; + + constructor() { + this.#connectedPromise = new Promise((resolve, reject) => { + this.#resolveConnectedPromise = resolve; + this.#rejectConnectedPromise = reject; + }); + + this.#endPromise = new Promise((resolve, reject) => { + this.#resolveEndPromise = resolve; + this.#rejectEndPromise = reject; + }); + + // Don't let these promises cause unhandled rejection errors. + // we will manually cause an unhandled rejection error later + // if the user hasn't registered any error listener or called + // any promise-returning method. + this.#connectedPromise.catch(() => {}); + this.#endPromise.catch(() => {}); + } + + protected _run(executor: () => Promise) { + // Unfortunately if we call `executor()` immediately we get runtime errors about + // references to `this` before the `super()` constructor call returns. + setTimeout(() => { + executor().then(() => { + this._emitFinal(); + this._emit('end'); + }, this.#handleError); + }, 0); + } + + protected _addChatCompletion(chatCompletion: ChatCompletion): ChatCompletion { + this._chatCompletions.push(chatCompletion); + this._emit('chatCompletion', chatCompletion); + const message = chatCompletion.choices[0]?.message; + if (message) this._addMessage(message as ChatCompletionMessageParam); + return chatCompletion; + } + + protected _addMessage(message: ChatCompletionMessageParam, emit = true) { + if (!('content' in message)) message.content = null; + + this.messages.push(message); + + if (emit) { + this._emit('message', message); + if ((isFunctionMessage(message) || isToolMessage(message)) && message.content) { + // Note, this assumes that {role: 'tool', content: …} is always the result of a call of tool of type=function. + this._emit('functionCallResult', message.content as string); + } else if (isAssistantMessage(message) && message.function_call) { + this._emit('functionCall', message.function_call); + } else if (isAssistantMessage(message) && message.tool_calls) { + for (const tool_call of message.tool_calls) { + if (tool_call.type === 'function') { + this._emit('functionCall', tool_call.function); + } + } + } + } + } + + protected _connected() { + if (this.ended) return; + this.#resolveConnectedPromise(); + this._emit('connect'); + } + + get ended(): boolean { + return this.#ended; + } + + get errored(): boolean { + return this.#errored; + } + + get aborted(): boolean { + return this.#aborted; + } + + abort() { + this.controller.abort(); + } + + /** + * Adds the listener function to the end of the listeners array for the event. + * No checks are made to see if the listener has already been added. Multiple calls passing + * the same combination of event and listener will result in the listener being added, and + * called, multiple times. + * @returns this ChatCompletionStream, so that calls can be chained + */ + on(event: Event, listener: ListenerForEvent): this { + const listeners: ListenersForEvent = + this.#listeners[event] || (this.#listeners[event] = []); + listeners.push({ listener }); + return this; + } + + /** + * Removes the specified listener from the listener array for the event. + * off() will remove, at most, one instance of a listener from the listener array. If any single + * listener has been added multiple times to the listener array for the specified event, then + * off() must be called multiple times to remove each instance. + * @returns this ChatCompletionStream, so that calls can be chained + */ + off(event: Event, listener: ListenerForEvent): this { + const listeners = this.#listeners[event]; + if (!listeners) return this; + const index = listeners.findIndex((l) => l.listener === listener); + if (index >= 0) listeners.splice(index, 1); + return this; + } + + /** + * Adds a one-time listener function for the event. The next time the event is triggered, + * this listener is removed and then invoked. + * @returns this ChatCompletionStream, so that calls can be chained + */ + once(event: Event, listener: ListenerForEvent): this { + const listeners: ListenersForEvent = + this.#listeners[event] || (this.#listeners[event] = []); + listeners.push({ listener, once: true }); + return this; + } + + /** + * This is similar to `.once()`, but returns a Promise that resolves the next time + * the event is triggered, instead of calling a listener callback. + * @returns a Promise that resolves the next time given event is triggered, + * or rejects if an error is emitted. (If you request the 'error' event, + * returns a promise that resolves with the error). + * + * Example: + * + * const message = await stream.emitted('message') // rejects if the stream errors + */ + emitted( + event: Event, + ): Promise< + EventParameters extends [infer Param] ? Param + : EventParameters extends [] ? void + : EventParameters + > { + return new Promise((resolve, reject) => { + this.#catchingPromiseCreated = true; + if (event !== 'error') this.once('error', reject); + this.once(event, resolve as any); + }); + } + + async done(): Promise { + this.#catchingPromiseCreated = true; + await this.#endPromise; + } + + /** + * @returns a promise that resolves with the final ChatCompletion, or rejects + * if an error occurred or the stream ended prematurely without producing a ChatCompletion. + */ + async finalChatCompletion(): Promise { + await this.done(); + const completion = this._chatCompletions[this._chatCompletions.length - 1]; + if (!completion) throw new OpenAIError('stream ended without producing a ChatCompletion'); + return completion; + } + + #getFinalContent(): string | null { + return this.#getFinalMessage().content ?? null; + } + + /** + * @returns a promise that resolves with the content of the final ChatCompletionMessage, or rejects + * if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage. + */ + async finalContent(): Promise { + await this.done(); + return this.#getFinalContent(); + } + + #getFinalMessage(): ChatCompletionMessage { + let i = this.messages.length; + while (i-- > 0) { + const message = this.messages[i]; + if (isAssistantMessage(message)) { + return { ...message, content: message.content ?? null }; + } + } + throw new OpenAIError('stream ended without producing a ChatCompletionMessage with role=assistant'); + } + + /** + * @returns a promise that resolves with the the final assistant ChatCompletionMessage response, + * or rejects if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage. + */ + async finalMessage(): Promise { + await this.done(); + return this.#getFinalMessage(); + } + + #getFinalFunctionCall(): ChatCompletionMessage.FunctionCall | undefined { + for (let i = this.messages.length - 1; i >= 0; i--) { + const message = this.messages[i]; + if (isAssistantMessage(message) && message?.function_call) { + return message.function_call; + } + if (isAssistantMessage(message) && message?.tool_calls?.length) { + return message.tool_calls.at(-1)?.function; + } + } + + return; + } + + /** + * @returns a promise that resolves with the content of the final FunctionCall, or rejects + * if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage. + */ + async finalFunctionCall(): Promise { + await this.done(); + return this.#getFinalFunctionCall(); + } + + #getFinalFunctionCallResult(): string | undefined { + for (let i = this.messages.length - 1; i >= 0; i--) { + const message = this.messages[i]; + if (isFunctionMessage(message) && message.content != null) { + return message.content; + } + if ( + isToolMessage(message) && + message.content != null && + this.messages.some( + (x) => + x.role === 'assistant' && + x.tool_calls?.some((y) => y.type === 'function' && y.id === message.tool_call_id), + ) + ) { + return message.content; + } + } + + return; + } + + async finalFunctionCallResult(): Promise { + await this.done(); + return this.#getFinalFunctionCallResult(); + } + + #calculateTotalUsage(): CompletionUsage { + const total: CompletionUsage = { + completion_tokens: 0, + prompt_tokens: 0, + total_tokens: 0, + }; + for (const { usage } of this._chatCompletions) { + if (usage) { + total.completion_tokens += usage.completion_tokens; + total.prompt_tokens += usage.prompt_tokens; + total.total_tokens += usage.total_tokens; + } + } + return total; + } + + async totalUsage(): Promise { + await this.done(); + return this.#calculateTotalUsage(); + } + + allChatCompletions(): ChatCompletion[] { + return [...this._chatCompletions]; + } + + #handleError = (error: unknown) => { + this.#errored = true; + if (error instanceof Error && error.name === 'AbortError') { + error = new APIUserAbortError(); + } + if (error instanceof APIUserAbortError) { + this.#aborted = true; + return this._emit('abort', error); + } + if (error instanceof OpenAIError) { + return this._emit('error', error); + } + if (error instanceof Error) { + const openAIError: OpenAIError = new OpenAIError(error.message); + // @ts-ignore + openAIError.cause = error; + return this._emit('error', openAIError); + } + return this._emit('error', new OpenAIError(String(error))); + }; + + protected _emit(event: Event, ...args: EventParameters) { + // make sure we don't emit any events after end + if (this.#ended) { + return; + } + + if (event === 'end') { + this.#ended = true; + this.#resolveEndPromise(); + } + + const listeners: ListenersForEvent | undefined = this.#listeners[event]; + if (listeners) { + this.#listeners[event] = listeners.filter((l) => !l.once) as any; + listeners.forEach(({ listener }: any) => listener(...args)); + } + + if (event === 'abort') { + const error = args[0] as APIUserAbortError; + if (!this.#catchingPromiseCreated && !listeners?.length) { + Promise.reject(error); + } + this.#rejectConnectedPromise(error); + this.#rejectEndPromise(error); + this._emit('end'); + return; + } + + if (event === 'error') { + // NOTE: _emit('error', error) should only be called from #handleError(). + + const error = args[0] as OpenAIError; + if (!this.#catchingPromiseCreated && !listeners?.length) { + // Trigger an unhandled rejection if the user hasn't registered any error handlers. + // If you are seeing stack traces here, make sure to handle errors via either: + // - runner.on('error', () => ...) + // - await runner.done() + // - await runner.finalChatCompletion() + // - etc. + Promise.reject(error); + } + this.#rejectConnectedPromise(error); + this.#rejectEndPromise(error); + this._emit('end'); + } + } + + protected _emitFinal() { + const completion = this._chatCompletions[this._chatCompletions.length - 1]; + if (completion) this._emit('finalChatCompletion', completion); + const finalMessage = this.#getFinalMessage(); + if (finalMessage) this._emit('finalMessage', finalMessage); + const finalContent = this.#getFinalContent(); + if (finalContent) this._emit('finalContent', finalContent); + + const finalFunctionCall = this.#getFinalFunctionCall(); + if (finalFunctionCall) this._emit('finalFunctionCall', finalFunctionCall); + + const finalFunctionCallResult = this.#getFinalFunctionCallResult(); + if (finalFunctionCallResult != null) this._emit('finalFunctionCallResult', finalFunctionCallResult); + + if (this._chatCompletions.some((c) => c.usage)) { + this._emit('totalUsage', this.#calculateTotalUsage()); + } + } + + #validateParams(params: ChatCompletionCreateParams): void { + if (params.n != null && params.n > 1) { + throw new OpenAIError( + 'ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.', + ); + } + } + + protected async _createChatCompletion( + completions: Completions, + params: ChatCompletionCreateParams, + options?: Core.RequestOptions, + ): Promise { + const signal = options?.signal; + if (signal) { + if (signal.aborted) this.controller.abort(); + signal.addEventListener('abort', () => this.controller.abort()); + } + this.#validateParams(params); + + const chatCompletion = await completions.create( + { ...params, stream: false }, + { ...options, signal: this.controller.signal }, + ); + this._connected(); + return this._addChatCompletion(chatCompletion); + } + + protected async _runChatCompletion( + completions: Completions, + params: ChatCompletionCreateParams, + options?: Core.RequestOptions, + ): Promise { + for (const message of params.messages) { + this._addMessage(message, false); + } + return await this._createChatCompletion(completions, params, options); + } + + protected async _runFunctions( + completions: Completions, + params: + | ChatCompletionFunctionRunnerParams + | ChatCompletionStreamingFunctionRunnerParams, + options?: RunnerOptions, + ) { + const role = 'function' as const; + const { function_call = 'auto', stream, ...restParams } = params; + const singleFunctionToCall = typeof function_call !== 'string' && function_call?.name; + const { maxChatCompletions = DEFAULT_MAX_CHAT_COMPLETIONS } = options || {}; + + const functionsByName: Record> = {}; + for (const f of params.functions) { + functionsByName[f.name || f.function.name] = f; + } + + const functions: ChatCompletionCreateParams.Function[] = params.functions.map( + (f): ChatCompletionCreateParams.Function => ({ + name: f.name || f.function.name, + parameters: f.parameters as Record, + description: f.description, + }), + ); + + for (const message of params.messages) { + this._addMessage(message, false); + } + + for (let i = 0; i < maxChatCompletions; ++i) { + const chatCompletion: ChatCompletion = await this._createChatCompletion( + completions, + { + ...restParams, + function_call, + functions, + messages: [...this.messages], + }, + options, + ); + const message = chatCompletion.choices[0]?.message; + if (!message) { + throw new OpenAIError(`missing message in ChatCompletion response`); + } + if (!message.function_call) return; + const { name, arguments: args } = message.function_call; + const fn = functionsByName[name]; + if (!fn) { + const content = `Invalid function_call: ${JSON.stringify(name)}. Available options are: ${functions + .map((f) => JSON.stringify(f.name)) + .join(', ')}. Please try again`; + + this._addMessage({ role, name, content }); + continue; + } else if (singleFunctionToCall && singleFunctionToCall !== name) { + const content = `Invalid function_call: ${JSON.stringify(name)}. ${JSON.stringify( + singleFunctionToCall, + )} requested. Please try again`; + + this._addMessage({ role, name, content }); + continue; + } + + let parsed; + try { + parsed = isRunnableFunctionWithParse(fn) ? await fn.parse(args) : args; + } catch (error) { + this._addMessage({ + role, + name, + content: error instanceof Error ? error.message : String(error), + }); + continue; + } + + // @ts-expect-error it can't rule out `never` type. + const rawContent = await fn.function(parsed, this); + const content = this.#stringifyFunctionCallResult(rawContent); + + this._addMessage({ role, name, content }); + + if (singleFunctionToCall) return; + } + } + + protected async _runTools( + completions: Completions, + params: + | ChatCompletionToolRunnerParams + | ChatCompletionStreamingToolRunnerParams, + options?: RunnerOptions, + ) { + const role = 'tool' as const; + const { tool_choice = 'auto', stream, ...restParams } = params; + const singleFunctionToCall = typeof tool_choice !== 'string' && tool_choice?.function?.name; + const { maxChatCompletions = DEFAULT_MAX_CHAT_COMPLETIONS } = options || {}; + + const functionsByName: Record> = {}; + for (const f of params.tools) { + if (f.type === 'function') { + functionsByName[f.function.name || f.function.function.name] = f.function; + } + } + + const tools: ChatCompletionTool[] = + 'tools' in params ? + params.tools.map((t) => + t.type === 'function' ? + { + type: 'function', + function: { + name: t.function.name || t.function.function.name, + parameters: t.function.parameters as Record, + description: t.function.description, + }, + } + : (t as unknown as ChatCompletionTool), + ) + : (undefined as any); + + for (const message of params.messages) { + this._addMessage(message, false); + } + + for (let i = 0; i < maxChatCompletions; ++i) { + const chatCompletion: ChatCompletion = await this._createChatCompletion( + completions, + { + ...restParams, + tool_choice, + tools, + messages: [...this.messages], + }, + options, + ); + const message = chatCompletion.choices[0]?.message; + if (!message) { + throw new OpenAIError(`missing message in ChatCompletion response`); + } + if (!message.tool_calls) { + return; + } + + for (const tool_call of message.tool_calls) { + if (tool_call.type !== 'function') continue; + const tool_call_id = tool_call.id; + const { name, arguments: args } = tool_call.function; + const fn = functionsByName[name]; + + if (!fn) { + const content = `Invalid tool_call: ${JSON.stringify(name)}. Available options are: ${tools + .map((f) => JSON.stringify(f.function.name)) + .join(', ')}. Please try again`; + + this._addMessage({ role, tool_call_id, content }); + continue; + } else if (singleFunctionToCall && singleFunctionToCall !== name) { + const content = `Invalid tool_call: ${JSON.stringify(name)}. ${JSON.stringify( + singleFunctionToCall, + )} requested. Please try again`; + + this._addMessage({ role, tool_call_id, content }); + continue; + } + + let parsed; + try { + parsed = isRunnableFunctionWithParse(fn) ? await fn.parse(args) : args; + } catch (error) { + const content = error instanceof Error ? error.message : String(error); + this._addMessage({ role, tool_call_id, content }); + continue; + } + + // @ts-expect-error it can't rule out `never` type. + const rawContent = await fn.function(parsed, this); + const content = this.#stringifyFunctionCallResult(rawContent); + this._addMessage({ role, tool_call_id, content }); + + if (singleFunctionToCall) { + return; + } + } + } + + return; + } + + #stringifyFunctionCallResult(rawContent: unknown): string { + return ( + typeof rawContent === 'string' ? rawContent + : rawContent === undefined ? 'undefined' + : JSON.stringify(rawContent) + ); + } +} + +type CustomEvents = { + [k in Event]: k extends keyof AbstractChatCompletionRunnerEvents ? AbstractChatCompletionRunnerEvents[k] + : (...args: any[]) => void; +}; + +type ListenerForEvent, Event extends keyof Events> = Event extends ( + keyof AbstractChatCompletionRunnerEvents +) ? + AbstractChatCompletionRunnerEvents[Event] +: Events[Event]; + +type ListenersForEvent, Event extends keyof Events> = Array<{ + listener: ListenerForEvent; + once?: boolean; +}>; +type EventParameters, Event extends keyof Events> = Parameters< + ListenerForEvent +>; + +export interface AbstractChatCompletionRunnerEvents { + connect: () => void; + functionCall: (functionCall: ChatCompletionMessage.FunctionCall) => void; + message: (message: ChatCompletionMessageParam) => void; + chatCompletion: (completion: ChatCompletion) => void; + finalContent: (contentSnapshot: string) => void; + finalMessage: (message: ChatCompletionMessageParam) => void; + finalChatCompletion: (completion: ChatCompletion) => void; + finalFunctionCall: (functionCall: ChatCompletionMessage.FunctionCall) => void; + functionCallResult: (content: string) => void; + finalFunctionCallResult: (content: string) => void; + error: (error: OpenAIError) => void; + abort: (error: APIUserAbortError) => void; + end: () => void; + totalUsage: (usage: CompletionUsage) => void; +} diff --git a/backend/node_modules/openai/src/lib/AssistantStream.ts b/backend/node_modules/openai/src/lib/AssistantStream.ts new file mode 100644 index 0000000000000000000000000000000000000000..74d9ce814c4731aa92f47c6c0754b871f107546e --- /dev/null +++ b/backend/node_modules/openai/src/lib/AssistantStream.ts @@ -0,0 +1,724 @@ +import { + TextContentBlock, + ImageFileContentBlock, + Message, + MessageContentDelta, + Text, + ImageFile, + TextDelta, + Messages, +} from "../resources/beta/threads/messages/messages"; +import * as Core from "../core"; +import { RequestOptions } from "../core"; +import { + Run, + RunCreateParamsBase, + RunCreateParamsStreaming, + Runs, + RunSubmitToolOutputsParamsBase, + RunSubmitToolOutputsParamsStreaming, +} from "../resources/beta/threads/runs/runs"; +import { + AbstractAssistantRunnerEvents, + AbstractAssistantStreamRunner, +} from './AbstractAssistantStreamRunner'; +import { type ReadableStream } from "../_shims/index"; +import { Stream } from "../streaming"; +import { APIUserAbortError, OpenAIError } from "../error"; +import { + AssistantStreamEvent, + MessageStreamEvent, + RunStepStreamEvent, + RunStreamEvent, +} from "../resources/beta/assistants/assistants"; +import { RunStep, RunStepDelta, ToolCall, ToolCallDelta } from "../resources/beta/threads/runs/steps"; +import { ThreadCreateAndRunParamsBase, Threads } from "../resources/beta/threads/threads"; +import MessageDelta = Messages.MessageDelta; + +export interface AssistantStreamEvents extends AbstractAssistantRunnerEvents { + //New event structure + messageCreated: (message: Message) => void; + messageDelta: (message: MessageDelta, snapshot: Message) => void; + messageDone: (message: Message) => void; + + runStepCreated: (runStep: RunStep) => void; + runStepDelta: (delta: RunStepDelta, snapshot: Runs.RunStep) => void; + runStepDone: (runStep: Runs.RunStep, snapshot: Runs.RunStep) => void; + + toolCallCreated: (toolCall: ToolCall) => void; + toolCallDelta: (delta: ToolCallDelta, snapshot: ToolCall) => void; + toolCallDone: (toolCall: ToolCall) => void; + + textCreated: (content: Text) => void; + textDelta: (delta: TextDelta, snapshot: Text) => void; + textDone: (content: Text, snapshot: Message) => void; + + //No created or delta as this is not streamed + imageFileDone: (content: ImageFile, snapshot: Message) => void; + + end: () => void; + + event: (event: AssistantStreamEvent) => void; +} + +export type ThreadCreateAndRunParamsBaseStream = Omit & { + stream?: true; +}; + +export type RunCreateParamsBaseStream = Omit & { + stream?: true; +}; + +export type RunSubmitToolOutputsParamsStream = Omit & { + stream?: true; +}; + +export class AssistantStream + extends AbstractAssistantStreamRunner + implements AsyncIterable +{ + //Track all events in a single list for reference + #events: AssistantStreamEvent[] = []; + + //Used to accumulate deltas + //We are accumulating many types so the value here is not strict + #runStepSnapshots: { [id: string]: Runs.RunStep } = {}; + #messageSnapshots: { [id: string]: Message } = {}; + #messageSnapshot: Message | undefined; + #finalRun: Run | undefined; + #currentContentIndex: number | undefined; + #currentContent: TextContentBlock | ImageFileContentBlock | undefined; + #currentToolCallIndex: number | undefined; + #currentToolCall: ToolCall | undefined; + + //For current snapshot methods + #currentEvent: AssistantStreamEvent | undefined; + #currentRunSnapshot: Run | undefined; + #currentRunStepSnapshot: Runs.RunStep | undefined; + + [Symbol.asyncIterator](): AsyncIterator { + const pushQueue: AssistantStreamEvent[] = []; + const readQueue: { + resolve: (chunk: AssistantStreamEvent | undefined) => void; + reject: (err: unknown) => void; + }[] = []; + let done = false; + + //Catch all for passing along all events + this.on('event', (event) => { + const reader = readQueue.shift(); + if (reader) { + reader.resolve(event); + } else { + pushQueue.push(event); + } + }); + + this.on('end', () => { + done = true; + for (const reader of readQueue) { + reader.resolve(undefined); + } + readQueue.length = 0; + }); + + this.on('abort', (err) => { + done = true; + for (const reader of readQueue) { + reader.reject(err); + } + readQueue.length = 0; + }); + + this.on('error', (err) => { + done = true; + for (const reader of readQueue) { + reader.reject(err); + } + readQueue.length = 0; + }); + + return { + next: async (): Promise> => { + if (!pushQueue.length) { + if (done) { + return { value: undefined, done: true }; + } + return new Promise((resolve, reject) => + readQueue.push({ resolve, reject }), + ).then((chunk) => (chunk ? { value: chunk, done: false } : { value: undefined, done: true })); + } + const chunk = pushQueue.shift()!; + return { value: chunk, done: false }; + }, + return: async () => { + this.abort(); + return { value: undefined, done: true }; + }, + }; + } + + static fromReadableStream(stream: ReadableStream): AssistantStream { + const runner = new AssistantStream(); + runner._run(() => runner._fromReadableStream(stream)); + return runner; + } + + protected async _fromReadableStream( + readableStream: ReadableStream, + options?: Core.RequestOptions, + ): Promise { + const signal = options?.signal; + if (signal) { + if (signal.aborted) this.controller.abort(); + signal.addEventListener('abort', () => this.controller.abort()); + } + this._connected(); + const stream = Stream.fromReadableStream(readableStream, this.controller); + for await (const event of stream) { + this.#addEvent(event); + } + if (stream.controller.signal?.aborted) { + throw new APIUserAbortError(); + } + return this._addRun(this.#endRequest()); + } + + toReadableStream(): ReadableStream { + const stream = new Stream(this[Symbol.asyncIterator].bind(this), this.controller); + return stream.toReadableStream(); + } + + static createToolAssistantStream( + threadId: string, + runId: string, + runs: Runs, + body: RunSubmitToolOutputsParamsStream, + options: RequestOptions | undefined, + ) { + const runner = new AssistantStream(); + runner._run(() => + runner._runToolAssistantStream(threadId, runId, runs, body, { + ...options, + headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' }, + }), + ); + return runner; + } + + protected override async _createToolAssistantStream( + run: Runs, + threadId: string, + runId: string, + params: RunSubmitToolOutputsParamsStream, + options?: Core.RequestOptions, + ): Promise { + const signal = options?.signal; + if (signal) { + if (signal.aborted) this.controller.abort(); + signal.addEventListener('abort', () => this.controller.abort()); + } + + const body: RunSubmitToolOutputsParamsStreaming = { ...params, stream: true }; + const stream = await run.submitToolOutputs(threadId, runId, body, { + ...options, + signal: this.controller.signal, + }); + + this._connected(); + + for await (const event of stream) { + this.#addEvent(event); + } + if (stream.controller.signal?.aborted) { + throw new APIUserAbortError(); + } + + return this._addRun(this.#endRequest()); + } + + static createThreadAssistantStream( + body: ThreadCreateAndRunParamsBaseStream, + thread: Threads, + options?: RequestOptions, + ) { + const runner = new AssistantStream(); + runner._run(() => + runner._threadAssistantStream(body, thread, { + ...options, + headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' }, + }), + ); + return runner; + } + + static createAssistantStream( + threadId: string, + runs: Runs, + params: RunCreateParamsBaseStream, + options?: RequestOptions, + ) { + const runner = new AssistantStream(); + runner._run(() => + runner._runAssistantStream(threadId, runs, params, { + ...options, + headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' }, + }), + ); + return runner; + } + + currentEvent(): AssistantStreamEvent | undefined { + return this.#currentEvent; + } + + currentRun(): Run | undefined { + return this.#currentRunSnapshot; + } + + currentMessageSnapshot(): Message | undefined { + return this.#messageSnapshot; + } + + currentRunStepSnapshot(): Runs.RunStep | undefined { + return this.#currentRunStepSnapshot; + } + + async finalRunSteps(): Promise { + await this.done(); + + return Object.values(this.#runStepSnapshots); + } + + async finalMessages(): Promise { + await this.done(); + + return Object.values(this.#messageSnapshots); + } + + async finalRun(): Promise { + await this.done(); + if (!this.#finalRun) throw Error('Final run was not received.'); + + return this.#finalRun; + } + + protected override async _createThreadAssistantStream( + thread: Threads, + params: ThreadCreateAndRunParamsBase, + options?: Core.RequestOptions, + ): Promise { + const signal = options?.signal; + if (signal) { + if (signal.aborted) this.controller.abort(); + signal.addEventListener('abort', () => this.controller.abort()); + } + + const body: RunCreateParamsStreaming = { ...params, stream: true }; + const stream = await thread.createAndRun(body, { ...options, signal: this.controller.signal }); + + this._connected(); + + for await (const event of stream) { + this.#addEvent(event); + } + if (stream.controller.signal?.aborted) { + throw new APIUserAbortError(); + } + + return this._addRun(this.#endRequest()); + } + + protected override async _createAssistantStream( + run: Runs, + threadId: string, + params: RunCreateParamsBase, + options?: Core.RequestOptions, + ): Promise { + const signal = options?.signal; + if (signal) { + if (signal.aborted) this.controller.abort(); + signal.addEventListener('abort', () => this.controller.abort()); + } + + const body: RunCreateParamsStreaming = { ...params, stream: true }; + const stream = await run.create(threadId, body, { ...options, signal: this.controller.signal }); + + this._connected(); + + for await (const event of stream) { + this.#addEvent(event); + } + if (stream.controller.signal?.aborted) { + throw new APIUserAbortError(); + } + + return this._addRun(this.#endRequest()); + } + + #addEvent(event: AssistantStreamEvent) { + if (this.ended) return; + + this.#currentEvent = event; + + this.#handleEvent(event); + + switch (event.event) { + case 'thread.created': + //No action on this event. + break; + + case 'thread.run.created': + case 'thread.run.queued': + case 'thread.run.in_progress': + case 'thread.run.requires_action': + case 'thread.run.completed': + case 'thread.run.failed': + case 'thread.run.cancelling': + case 'thread.run.cancelled': + case 'thread.run.expired': + this.#handleRun(event); + break; + + case 'thread.run.step.created': + case 'thread.run.step.in_progress': + case 'thread.run.step.delta': + case 'thread.run.step.completed': + case 'thread.run.step.failed': + case 'thread.run.step.cancelled': + case 'thread.run.step.expired': + this.#handleRunStep(event); + break; + + case 'thread.message.created': + case 'thread.message.in_progress': + case 'thread.message.delta': + case 'thread.message.completed': + case 'thread.message.incomplete': + this.#handleMessage(event); + break; + + case 'error': + //This is included for completeness, but errors are processed in the SSE event processing so this should not occur + throw new Error( + 'Encountered an error event in event processing - errors should be processed earlier', + ); + } + } + + #endRequest(): Run { + if (this.ended) { + throw new OpenAIError(`stream has ended, this shouldn't happen`); + } + + if (!this.#finalRun) throw Error('Final run has not been received'); + + return this.#finalRun; + } + + #handleMessage(event: MessageStreamEvent) { + const [accumulatedMessage, newContent] = this.#accumulateMessage(event, this.#messageSnapshot); + this.#messageSnapshot = accumulatedMessage; + this.#messageSnapshots[accumulatedMessage.id] = accumulatedMessage; + + for (const content of newContent) { + const snapshotContent = accumulatedMessage.content[content.index]; + if (snapshotContent?.type == 'text') { + this._emit('textCreated', snapshotContent.text); + } + } + + switch (event.event) { + case 'thread.message.created': + this._emit('messageCreated', event.data); + break; + + case 'thread.message.in_progress': + break; + + case 'thread.message.delta': + this._emit('messageDelta', event.data.delta, accumulatedMessage); + + if (event.data.delta.content) { + for (const content of event.data.delta.content) { + //If it is text delta, emit a text delta event + if (content.type == 'text' && content.text) { + let textDelta = content.text; + let snapshot = accumulatedMessage.content[content.index]; + if (snapshot && snapshot.type == 'text') { + this._emit('textDelta', textDelta, snapshot.text); + } else { + throw Error('The snapshot associated with this text delta is not text or missing'); + } + } + + if (content.index != this.#currentContentIndex) { + //See if we have in progress content + if (this.#currentContent) { + switch (this.#currentContent.type) { + case 'text': + this._emit('textDone', this.#currentContent.text, this.#messageSnapshot); + break; + case 'image_file': + this._emit('imageFileDone', this.#currentContent.image_file, this.#messageSnapshot); + break; + } + } + + this.#currentContentIndex = content.index; + } + + this.#currentContent = accumulatedMessage.content[content.index]; + } + } + + break; + + case 'thread.message.completed': + case 'thread.message.incomplete': + //We emit the latest content we were working on on completion (including incomplete) + if (this.#currentContentIndex !== undefined) { + const currentContent = event.data.content[this.#currentContentIndex]; + if (currentContent) { + switch (currentContent.type) { + case 'image_file': + this._emit('imageFileDone', currentContent.image_file, this.#messageSnapshot); + break; + case 'text': + this._emit('textDone', currentContent.text, this.#messageSnapshot); + break; + } + } + } + + if (this.#messageSnapshot) { + this._emit('messageDone', event.data); + } + + this.#messageSnapshot = undefined; + } + } + + #handleRunStep(event: RunStepStreamEvent) { + const accumulatedRunStep = this.#accumulateRunStep(event); + this.#currentRunStepSnapshot = accumulatedRunStep; + + switch (event.event) { + case 'thread.run.step.created': + this._emit('runStepCreated', event.data); + break; + case 'thread.run.step.delta': + const delta = event.data.delta; + if ( + delta.step_details && + delta.step_details.type == 'tool_calls' && + delta.step_details.tool_calls && + accumulatedRunStep.step_details.type == 'tool_calls' + ) { + for (const toolCall of delta.step_details.tool_calls) { + if (toolCall.index == this.#currentToolCallIndex) { + this._emit( + 'toolCallDelta', + toolCall, + accumulatedRunStep.step_details.tool_calls[toolCall.index] as ToolCall, + ); + } else { + if (this.#currentToolCall) { + this._emit('toolCallDone', this.#currentToolCall); + } + + this.#currentToolCallIndex = toolCall.index; + this.#currentToolCall = accumulatedRunStep.step_details.tool_calls[toolCall.index]; + if (this.#currentToolCall) this._emit('toolCallCreated', this.#currentToolCall); + } + } + } + + this._emit('runStepDelta', event.data.delta, accumulatedRunStep); + break; + case 'thread.run.step.completed': + case 'thread.run.step.failed': + case 'thread.run.step.cancelled': + case 'thread.run.step.expired': + this.#currentRunStepSnapshot = undefined; + const details = event.data.step_details; + if (details.type == 'tool_calls') { + if (this.#currentToolCall) { + this._emit('toolCallDone', this.#currentToolCall as ToolCall); + this.#currentToolCall = undefined; + } + } + this._emit('runStepDone', event.data, accumulatedRunStep); + break; + case 'thread.run.step.in_progress': + break; + } + } + + #handleEvent(event: AssistantStreamEvent) { + this.#events.push(event); + this._emit('event', event); + } + + #accumulateRunStep(event: RunStepStreamEvent): Runs.RunStep { + switch (event.event) { + case 'thread.run.step.created': + this.#runStepSnapshots[event.data.id] = event.data; + return event.data; + + case 'thread.run.step.delta': + let snapshot = this.#runStepSnapshots[event.data.id] as Runs.RunStep; + if (!snapshot) { + throw Error('Received a RunStepDelta before creation of a snapshot'); + } + + let data = event.data; + + if (data.delta) { + const accumulated = AssistantStream.accumulateDelta(snapshot, data.delta) as Runs.RunStep; + this.#runStepSnapshots[event.data.id] = accumulated; + } + + return this.#runStepSnapshots[event.data.id] as Runs.RunStep; + + case 'thread.run.step.completed': + case 'thread.run.step.failed': + case 'thread.run.step.cancelled': + case 'thread.run.step.expired': + case 'thread.run.step.in_progress': + this.#runStepSnapshots[event.data.id] = event.data; + break; + } + + if (this.#runStepSnapshots[event.data.id]) return this.#runStepSnapshots[event.data.id] as Runs.RunStep; + throw new Error('No snapshot available'); + } + + #accumulateMessage( + event: AssistantStreamEvent, + snapshot: Message | undefined, + ): [Message, MessageContentDelta[]] { + let newContent: MessageContentDelta[] = []; + + switch (event.event) { + case 'thread.message.created': + //On creation the snapshot is just the initial message + return [event.data, newContent]; + + case 'thread.message.delta': + if (!snapshot) { + throw Error( + 'Received a delta with no existing snapshot (there should be one from message creation)', + ); + } + + let data = event.data; + + //If this delta does not have content, nothing to process + if (data.delta.content) { + for (const contentElement of data.delta.content) { + if (contentElement.index in snapshot.content) { + let currentContent = snapshot.content[contentElement.index]; + snapshot.content[contentElement.index] = this.#accumulateContent( + contentElement, + currentContent, + ); + } else { + snapshot.content[contentElement.index] = contentElement as + | TextContentBlock + | ImageFileContentBlock; + //This is a new element + newContent.push(contentElement); + } + } + } + + return [snapshot, newContent]; + + case 'thread.message.in_progress': + case 'thread.message.completed': + case 'thread.message.incomplete': + //No changes on other thread events + if (snapshot) { + return [snapshot, newContent]; + } else { + throw Error('Received thread message event with no existing snapshot'); + } + } + throw Error('Tried to accumulate a non-message event'); + } + + #accumulateContent( + contentElement: MessageContentDelta, + currentContent: TextContentBlock | ImageFileContentBlock | undefined, + ): TextContentBlock | ImageFileContentBlock { + return AssistantStream.accumulateDelta(currentContent as unknown as Record, contentElement) as + | TextContentBlock + | ImageFileContentBlock; + } + + static accumulateDelta(acc: Record, delta: Record): Record { + for (const [key, deltaValue] of Object.entries(delta)) { + if (!acc.hasOwnProperty(key)) { + acc[key] = deltaValue; + continue; + } + + let accValue = acc[key]; + if (accValue === null || accValue === undefined) { + acc[key] = deltaValue; + continue; + } + + // We don't accumulate these special properties + if (key === 'index' || key === 'type') { + acc[key] = deltaValue; + continue; + } + + // Type-specific accumulation logic + if (typeof accValue === 'string' && typeof deltaValue === 'string') { + accValue += deltaValue; + } else if (typeof accValue === 'number' && typeof deltaValue === 'number') { + accValue += deltaValue; + } else if (Core.isObj(accValue) && Core.isObj(deltaValue)) { + accValue = this.accumulateDelta(accValue as Record, deltaValue as Record); + } else if (Array.isArray(accValue) && Array.isArray(deltaValue)) { + if (accValue.every((x) => typeof x === 'string' || typeof x === 'number')) { + accValue.push(...deltaValue); // Use spread syntax for efficient addition + continue; + } + } else { + throw Error(`Unhandled record type: ${key}, deltaValue: ${deltaValue}, accValue: ${accValue}`); + } + acc[key] = accValue; + } + + return acc; + } + + #handleRun(event: RunStreamEvent) { + this.#currentRunSnapshot = event.data; + switch (event.event) { + case 'thread.run.created': + break; + case 'thread.run.queued': + break; + case 'thread.run.in_progress': + break; + case 'thread.run.requires_action': + case 'thread.run.cancelled': + case 'thread.run.failed': + case 'thread.run.completed': + case 'thread.run.expired': + this.#finalRun = event.data; + if (this.#currentToolCall) { + this._emit('toolCallDone', this.#currentToolCall); + this.#currentToolCall = undefined; + } + break; + case 'thread.run.cancelling': + break; + } + } +} diff --git a/backend/node_modules/openai/src/lib/ChatCompletionRunFunctions.test.ts b/backend/node_modules/openai/src/lib/ChatCompletionRunFunctions.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..7d45db3e64c2c8dfd01169b1e16a266e7950f139 --- /dev/null +++ b/backend/node_modules/openai/src/lib/ChatCompletionRunFunctions.test.ts @@ -0,0 +1,2328 @@ +import OpenAI from 'openai'; +import { OpenAIError, APIConnectionError } from "../error"; +import { PassThrough } from 'stream'; +import { + ParsingToolFunction, + type ChatCompletionRunner, + type ChatCompletionFunctionRunnerParams, + ChatCompletionStreamingRunner, + type ChatCompletionStreamingFunctionRunnerParams, +} from "../resources/beta/chat/completions"; +import type { ChatCompletionMessageParam } from "../resources/chat/completions"; + +import { type RequestInfo, type RequestInit } from "../_shims/index"; +import { Response } from 'node-fetch'; +import { isAssistantMessage } from './chatCompletionUtils'; + +type Fetch = (req: string | RequestInfo, init?: RequestInit) => Promise; + +/** + * Creates a mock `fetch` function and a `handleRequest` function for intercepting `fetch` calls. + * + * You call `handleRequest` with a callback function that handles the next `fetch` call. + * It returns a Promise that: + * - waits for the next call to `fetch` + * - calls the callback with the `fetch` arguments + * - resolves `fetch` with the callback output + */ +function mockFetch(): { fetch: Fetch; handleRequest: (handle: Fetch) => Promise } { + const fetchQueue: ((handler: typeof fetch) => void)[] = []; + const handlerQueue: Promise[] = []; + + const enqueueHandler = () => { + handlerQueue.push( + new Promise((resolve) => { + fetchQueue.push((handle: typeof fetch) => { + enqueueHandler(); + resolve(handle); + }); + }), + ); + }; + enqueueHandler(); + + async function fetch(req: string | RequestInfo, init?: RequestInit): Promise { + const handler = await handlerQueue.shift(); + if (!handler) throw new Error('expected handler to be defined'); + const signal = init?.signal; + if (!signal) return await handler(req, init); + return await Promise.race([ + handler(req, init), + new Promise((resolve, reject) => { + if (signal.aborted) { + // @ts-ignore does exist in Node + reject(new DOMException('The user aborted a request.', 'AbortError')); + return; + } + signal.addEventListener('abort', (e) => { + // @ts-ignore does exist in Node + reject(new DOMException('The user aborted a request.', 'AbortError')); + }); + }), + ]); + } + + function handleRequest(handle: typeof fetch): Promise { + return new Promise((resolve, reject) => { + fetchQueue.shift()?.(async (req, init) => { + try { + return await handle(req, init); + } catch (err) { + reject(err); + return err as any; + } finally { + resolve(); + } + }); + }); + } + + return { fetch, handleRequest }; +} + +// mockChatCompletionFetch is like mockFetch, but with better a more convenient handleRequest to mock +// chat completion request/responses. +function mockChatCompletionFetch() { + const { fetch, handleRequest: handleRawRequest } = mockFetch(); + + function handleRequest( + handler: (body: ChatCompletionFunctionRunnerParams) => Promise, + ): Promise { + return handleRawRequest(async (req, init) => { + const rawBody = init?.body; + if (typeof rawBody !== 'string') throw new Error(`expected init.body to be a string`); + const body: ChatCompletionFunctionRunnerParams = JSON.parse(rawBody); + return new Response(JSON.stringify(await handler(body)), { + headers: { 'Content-Type': 'application/json' }, + }); + }); + } + return { fetch, handleRequest }; +} + +// mockStreamingChatCompletionFetch is like mockFetch, but with better a more convenient handleRequest to mock +// streaming chat completion request/responses. +function mockStreamingChatCompletionFetch() { + const { fetch, handleRequest: handleRawRequest } = mockFetch(); + + function handleRequest( + handler: ( + body: ChatCompletionStreamingFunctionRunnerParams, + ) => AsyncIterable, + ): Promise { + return handleRawRequest(async (req, init) => { + const rawBody = init?.body; + if (typeof rawBody !== 'string') throw new Error(`expected init.body to be a string`); + const body: ChatCompletionStreamingFunctionRunnerParams = JSON.parse(rawBody); + const stream = new PassThrough(); + (async () => { + for await (const chunk of handler(body)) { + stream.write(`data: ${JSON.stringify(chunk)}\n\n`); + } + stream.end(`data: [DONE]\n\n`); + })(); + return new Response(stream, { + headers: { + 'Content-Type': 'text/event-stream', + 'Transfer-Encoding': 'chunked', + }, + }); + }); + } + return { fetch, handleRequest }; +} + +// contentChoiceDeltas returns an async iterator which mocks a delta stream of a by splitting the +// argument into chunks separated by whitespace. +function* contentChoiceDeltas( + content: string, + { + index = 0, + role = 'assistant', + }: { index?: number; role?: NonNullable } = {}, +): Iterable { + const deltas = content.split(/\s+/g); + for (let i = 0; i < deltas.length; i++) { + yield { + index, + finish_reason: i === deltas.length - 1 ? 'stop' : null, + logprobs: null, + delta: { + role, + content: deltas[i] ? `${deltas[i]}${i === deltas.length - 1 ? '' : ' '}` : null, + }, + }; + } +} + +// functionCallDeltas returns an async iterator which mocks a delta stream of a functionCall by splitting +// the argument into chunks separated by whitespace. +function* functionCallDeltas( + args: string, + { + index = 0, + id = '123', + name, + role = 'assistant', + }: { + name: string; + id?: string; + index?: number; + role?: NonNullable; + }, +): Iterable { + const deltas = args.split(/\s+/g); + for (let i = 0; i < deltas.length; i++) { + yield { + index, + finish_reason: i === deltas.length - 1 ? 'function_call' : null, + delta: { + role, + tool_calls: [ + { + type: 'function', + index: 0, + id, + function: { + arguments: `${deltas[i] || ''}${i === deltas.length - 1 ? '' : ' '}`, + ...(i === deltas.length - 1 ? { name } : null), + }, + }, + ], + }, + }; + } +} + +class RunnerListener { + readonly contents: string[] = []; + readonly messages: ChatCompletionMessageParam[] = []; + readonly chatCompletions: OpenAI.Chat.ChatCompletion[] = []; + readonly functionCalls: OpenAI.Chat.ChatCompletionMessage.FunctionCall[] = []; + readonly functionCallResults: string[] = []; + finalContent: string | null = null; + finalMessage: ChatCompletionMessageParam | undefined; + finalChatCompletion: OpenAI.Chat.ChatCompletion | undefined; + finalFunctionCall: OpenAI.Chat.ChatCompletionMessage.FunctionCall | undefined; + finalFunctionCallResult: string | undefined; + totalUsage: OpenAI.CompletionUsage | undefined; + error: OpenAIError | undefined; + gotConnect = false; + gotAbort = false; + gotEnd = false; + + onceMessageCallCount = 0; + + constructor(public runner: ChatCompletionRunner) { + runner + .on('connect', () => (this.gotConnect = true)) + .on('content', (content) => this.contents.push(content)) + .on('message', (message) => this.messages.push(message)) + .on('chatCompletion', (completion) => this.chatCompletions.push(completion)) + .on('functionCall', (functionCall) => this.functionCalls.push(functionCall)) + .on('functionCallResult', (result) => this.functionCallResults.push(result)) + .on('finalContent', (content) => (this.finalContent = content)) + .on('finalMessage', (message) => (this.finalMessage = message)) + .on('finalChatCompletion', (completion) => (this.finalChatCompletion = completion)) + .on('finalFunctionCall', (functionCall) => (this.finalFunctionCall = functionCall)) + .on('finalFunctionCallResult', (result) => (this.finalFunctionCallResult = result)) + .on('totalUsage', (usage) => (this.totalUsage = usage)) + .on('error', (error) => (this.error = error)) + .on('abort', (error) => ((this.error = error), (this.gotAbort = true))) + .on('end', () => (this.gotEnd = true)) + .once('message', () => this.onceMessageCallCount++); + } + + async sanityCheck({ error }: { error?: string } = {}) { + expect(this.onceMessageCallCount).toBeLessThanOrEqual(1); + expect(this.gotAbort).toEqual(this.runner.aborted); + if (this.runner.aborted) expect(this.runner.errored).toBe(true); + if (error) { + expect(this.error?.message).toEqual(error); + expect(this.runner.errored).toBe(true); + await expect(this.runner.finalChatCompletion()).rejects.toThrow(error); + await expect(this.runner.finalMessage()).rejects.toThrow(error); + await expect(this.runner.finalContent()).rejects.toThrow(error); + await expect(this.runner.finalFunctionCall()).rejects.toThrow(error); + await expect(this.runner.finalFunctionCallResult()).rejects.toThrow(error); + await expect(this.runner.totalUsage()).rejects.toThrow(error); + await expect(this.runner.done()).rejects.toThrow(error); + } else { + expect(this.error).toBeUndefined(); + expect(this.runner.errored).toBe(false); + } + + if (!this.gotConnect) { + expect(this.contents).toEqual([]); + expect(this.messages).toEqual([]); + expect(this.chatCompletions).toEqual([]); + expect(this.functionCalls).toEqual([]); + expect(this.functionCallResults).toEqual([]); + expect(this.finalContent).toBeUndefined(); + expect(this.finalMessage).toBeUndefined(); + expect(this.finalChatCompletion).toBeUndefined(); + expect(this.finalFunctionCall).toBeUndefined(); + expect(this.finalFunctionCallResult).toBeUndefined(); + expect(this.totalUsage).toBeUndefined(); + expect(this.gotEnd).toBe(true); + return; + } + + if (error) return; + + const expectedContents = this.messages + .filter(isAssistantMessage) + .map((m) => m.content as string) + .filter(Boolean); + expect(this.contents).toEqual(expectedContents); + expect(this.finalMessage).toEqual([...this.messages].reverse().find((x) => x.role === 'assistant')); + expect(await this.runner.finalMessage()).toEqual(this.finalMessage); + expect(this.finalContent).toEqual(expectedContents[expectedContents.length - 1] ?? null); + expect(await this.runner.finalContent()).toEqual(this.finalContent); + expect(this.finalChatCompletion).toEqual(this.chatCompletions[this.chatCompletions.length - 1]); + expect(await this.runner.finalChatCompletion()).toEqual(this.finalChatCompletion); + expect(this.finalFunctionCall).toEqual(this.functionCalls[this.functionCalls.length - 1]); + expect(await this.runner.finalFunctionCall()).toEqual(this.finalFunctionCall); + expect(this.finalFunctionCallResult).toEqual( + this.functionCallResults[this.functionCallResults.length - 1], + ); + expect(await this.runner.finalFunctionCallResult()).toEqual(this.finalFunctionCallResult); + expect(this.chatCompletions).toEqual(this.runner.allChatCompletions()); + expect(this.messages).toEqual(this.runner.messages.slice(-this.messages.length)); + if (this.chatCompletions.some((c) => c.usage)) { + const totalUsage: OpenAI.CompletionUsage = { + completion_tokens: 0, + prompt_tokens: 0, + total_tokens: 0, + }; + for (const { usage } of this.chatCompletions) { + if (usage) { + totalUsage.completion_tokens += usage.completion_tokens; + totalUsage.prompt_tokens += usage.prompt_tokens; + totalUsage.total_tokens += usage.total_tokens; + } + } + expect(this.totalUsage).toEqual(totalUsage); + expect(await this.runner.totalUsage()).toEqual(totalUsage); + } + + expect(this.gotEnd).toBe(true); + } +} + +class StreamingRunnerListener { + readonly eventChunks: OpenAI.Chat.ChatCompletionChunk[] = []; + readonly eventContents: [string, string][] = []; + readonly eventMessages: ChatCompletionMessageParam[] = []; + readonly eventChatCompletions: OpenAI.Chat.ChatCompletion[] = []; + readonly eventFunctionCalls: OpenAI.Chat.ChatCompletionMessage.FunctionCall[] = []; + readonly eventFunctionCallResults: string[] = []; + + finalContent: string | null = null; + finalMessage: ChatCompletionMessageParam | undefined; + finalChatCompletion: OpenAI.Chat.ChatCompletion | undefined; + finalFunctionCall: OpenAI.Chat.ChatCompletionMessage.FunctionCall | undefined; + finalFunctionCallResult: string | undefined; + error: OpenAIError | undefined; + gotConnect = false; + gotEnd = false; + + constructor(public runner: ChatCompletionStreamingRunner) { + runner + .on('connect', () => (this.gotConnect = true)) + .on('chunk', (chunk) => this.eventChunks.push(chunk)) + .on('content', (delta, snapshot) => this.eventContents.push([delta, snapshot])) + .on('message', (message) => this.eventMessages.push(message)) + .on('chatCompletion', (completion) => this.eventChatCompletions.push(completion)) + .on('functionCall', (functionCall) => this.eventFunctionCalls.push(functionCall)) + .on('functionCallResult', (result) => this.eventFunctionCallResults.push(result)) + .on('finalContent', (content) => (this.finalContent = content)) + .on('finalMessage', (message) => (this.finalMessage = message)) + .on('finalChatCompletion', (completion) => (this.finalChatCompletion = completion)) + .on('finalFunctionCall', (functionCall) => (this.finalFunctionCall = functionCall)) + .on('finalFunctionCallResult', (result) => (this.finalFunctionCallResult = result)) + .on('error', (error) => (this.error = error)) + .on('abort', (abort) => (this.error = abort)) + .on('end', () => (this.gotEnd = true)); + } + + async sanityCheck({ error }: { error?: string } = {}) { + if (error) { + expect(this.error?.message).toEqual(error); + expect(this.runner.errored).toBe(true); + await expect(this.runner.finalChatCompletion()).rejects.toThrow(error); + await expect(this.runner.finalMessage()).rejects.toThrow(error); + await expect(this.runner.finalContent()).rejects.toThrow(error); + await expect(this.runner.finalFunctionCall()).rejects.toThrow(error); + await expect(this.runner.finalFunctionCallResult()).rejects.toThrow(error); + await expect(this.runner.done()).rejects.toThrow(error); + } else { + expect(this.error).toBeUndefined(); + expect(this.runner.errored).toBe(false); + } + + if (!this.gotConnect) { + expect(this.eventContents).toEqual([]); + expect(this.eventMessages).toEqual([]); + expect(this.eventChatCompletions).toEqual([]); + expect(this.eventFunctionCalls).toEqual([]); + expect(this.eventFunctionCallResults).toEqual([]); + expect(this.finalContent).toBeUndefined(); + expect(this.finalMessage).toBeUndefined(); + expect(this.finalChatCompletion).toBeUndefined(); + expect(this.finalFunctionCall).toBeUndefined(); + expect(this.finalFunctionCallResult).toBeUndefined(); + expect(this.gotEnd).toBe(true); + return; + } + + if (error) return; + + if (this.eventContents.length) expect(this.eventChunks.length).toBeGreaterThan(0); + expect(this.finalMessage).toEqual([...this.eventMessages].reverse().find((x) => x.role === 'assistant')); + expect(await this.runner.finalMessage()).toEqual(this.finalMessage); + expect(this.finalContent).toEqual(this.eventContents[this.eventContents.length - 1]?.[1] ?? null); + expect(await this.runner.finalContent()).toEqual(this.finalContent); + expect(this.finalChatCompletion).toEqual(this.eventChatCompletions[this.eventChatCompletions.length - 1]); + expect(await this.runner.finalChatCompletion()).toEqual(this.finalChatCompletion); + expect(this.finalFunctionCall).toEqual(this.eventFunctionCalls[this.eventFunctionCalls.length - 1]); + expect(await this.runner.finalFunctionCall()).toEqual(this.finalFunctionCall); + expect(this.finalFunctionCallResult).toEqual( + this.eventFunctionCallResults[this.eventFunctionCallResults.length - 1], + ); + expect(await this.runner.finalFunctionCallResult()).toEqual(this.finalFunctionCallResult); + expect(this.eventChatCompletions).toEqual(this.runner.allChatCompletions()); + expect(this.eventMessages).toEqual(this.runner.messages.slice(-this.eventMessages.length)); + if (error) { + expect(this.error?.message).toEqual(error); + expect(this.runner.errored).toBe(true); + } else { + expect(this.error).toBeUndefined(); + expect(this.runner.errored).toBe(false); + } + expect(this.gotEnd).toBe(true); + } +} + +function _typeTests() { + const openai = new OpenAI(); + + openai.beta.chat.completions.runTools({ + messages: [ + { role: 'user', content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}' }, + ], + model: 'gpt-3.5-turbo', + tools: [ + { + type: 'function', + function: { + name: 'numProperties', + function: (obj: object) => String(Object.keys(obj).length), + parameters: { type: 'object' }, + parse: (str: string): object => { + const result = JSON.parse(str); + if (!(result instanceof Object) || Array.isArray(result)) { + throw new Error('must be an object'); + } + return result; + }, + description: 'gets the number of properties on an object', + }, + }, + { + type: 'function', + function: { + function: (str: string) => String(str.length), + parameters: { type: 'string' }, + description: 'gets the length of a string', + }, + }, + { + type: 'function', + // @ts-expect-error function must accept string if parse is omitted + function: { + function: (obj: object) => String(Object.keys(obj).length), + parameters: { type: 'object' }, + description: 'gets the number of properties on an object', + }, + }, + ], + }); + openai.beta.chat.completions.runTools({ + messages: [ + { role: 'user', content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}' }, + ], + model: 'gpt-3.5-turbo', + tools: [ + new ParsingToolFunction({ + name: 'numProperties', + // @ts-expect-error parse and function don't match + parse: (str: string) => str, + function: (obj: object) => String(Object.keys(obj).length), + parameters: { type: 'object' }, + description: 'gets the number of properties on an object', + }), + ], + }); + openai.beta.chat.completions.runTools({ + messages: [ + { role: 'user', content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}' }, + ], + model: 'gpt-3.5-turbo', + tools: [ + new ParsingToolFunction({ + name: 'numProperties', + parse: (str: string): object => { + const result = JSON.parse(str); + if (!(result instanceof Object) || Array.isArray(result)) { + throw new Error('must be an object'); + } + return result; + }, + function: (obj: object) => String(Object.keys(obj).length), + parameters: { type: 'object' }, + description: 'gets the number of properties on an object', + }), + new ParsingToolFunction({ + name: 'keys', + parse: (str: string): object => { + const result = JSON.parse(str); + if (!(result instanceof Object)) { + throw new Error('must be an Object'); + } + return result; + }, + function: (obj: object) => Object.keys(obj).join(', '), + parameters: { type: 'object' }, + description: 'gets the number of properties on an object', + }), + new ParsingToolFunction({ + name: 'len2', + // @ts-expect-error parse and function don't match + parse: (str: string) => str, + function: (obj: object) => String(Object.keys(obj).length), + parameters: { type: 'object' }, + description: 'gets the number of properties on an object', + }), + ], + }); + openai.beta.chat.completions.runTools({ + messages: [ + { role: 'user', content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}' }, + ], + model: 'gpt-3.5-turbo', + // @ts-ignore error occurs here in TS 4 + tools: [ + { + type: 'function', + function: { + name: 'numProperties', + parse: (str: string): object => { + const result = JSON.parse(str); + if (!(result instanceof Object) || Array.isArray(result)) { + throw new Error('must be an object'); + } + return result; + }, + function: (obj: object) => String(Object.keys(obj).length), + parameters: { type: 'object' }, + description: 'gets the number of properties on an object', + }, + }, + { + type: 'function', + function: { + name: 'keys', + parse: (str: string): object => { + const result = JSON.parse(str); + if (!(result instanceof Object)) { + throw new Error('must be an Object'); + } + return result; + }, + function: (obj: object) => Object.keys(obj).join(', '), + parameters: { type: 'object' }, + description: 'gets the number of properties on an object', + }, + }, + { + type: 'function', + function: { + name: 'len2', + parse: (str: string) => str, + // @ts-ignore error occurs here in TS 5 + // function input doesn't match parse output + function: (obj: object) => String(Object.keys(obj).length), + parameters: { type: 'object' }, + description: 'gets the number of properties on an object', + }, + }, + ] as const, + }); +} + +describe('resource completions', () => { + describe('runTools with stream: false', () => { + test('successful flow', async () => { + const { fetch, handleRequest } = mockChatCompletionFetch(); + + const openai = new OpenAI({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + + const runner = openai.beta.chat.completions.runTools({ + messages: [{ role: 'user', content: 'tell me what the weather is like' }], + model: 'gpt-3.5-turbo', + tools: [ + { + type: 'function', + function: { + function: function getWeather() { + return `it's raining`; + }, + parameters: {}, + description: 'gets the weather', + }, + }, + ], + }); + const listener = new RunnerListener(runner); + + await handleRequest(async (request) => { + expect(request.messages).toEqual([{ role: 'user', content: 'tell me what the weather is like' }]); + return { + id: '1', + choices: [ + { + index: 0, + finish_reason: 'function_call', + logprobs: null, + message: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion', + }; + }); + + await handleRequest(async (request) => { + expect(request.messages).toEqual([ + { role: 'user', content: 'tell me what the weather is like' }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + { + role: 'tool', + content: `it's raining`, + tool_call_id: '123', + }, + ]); + + return { + id: '2', + choices: [ + { + index: 0, + finish_reason: 'stop', + logprobs: null, + message: { + role: 'assistant', + content: `it's raining`, + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion', + }; + }); + + await runner.done(); + + expect(listener.messages).toEqual([ + { role: 'user', content: 'tell me what the weather is like' }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + { role: 'tool', content: `it's raining`, tool_call_id: '123' }, + { role: 'assistant', content: "it's raining" }, + ]); + expect(listener.functionCallResults).toEqual([`it's raining`]); + await listener.sanityCheck(); + }); + test('flow with abort', async () => { + const { fetch, handleRequest } = mockChatCompletionFetch(); + + const openai = new OpenAI({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + + const controller = new AbortController(); + const runner = openai.beta.chat.completions.runTools( + { + messages: [{ role: 'user', content: 'tell me what the weather is like' }], + model: 'gpt-3.5-turbo', + tools: [ + { + type: 'function', + function: { + function: function getWeather() { + return `it's raining`; + }, + parameters: {}, + description: 'gets the weather', + }, + }, + ], + }, + { signal: controller.signal }, + ); + const listener = new RunnerListener(runner); + + await handleRequest(async (request) => { + expect(request.messages).toEqual([{ role: 'user', content: 'tell me what the weather is like' }]); + return { + id: '1', + choices: [ + { + index: 0, + finish_reason: 'function_call', + logprobs: null, + message: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion', + }; + }); + + controller.abort(); + + await runner.done().catch(() => {}); + + expect(listener.messages).toEqual([ + { role: 'user', content: 'tell me what the weather is like' }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + { role: 'tool', content: `it's raining`, tool_call_id: '123' }, + ]); + expect(listener.functionCallResults).toEqual([`it's raining`]); + await listener.sanityCheck({ error: 'Request was aborted.' }); + expect(runner.aborted).toBe(true); + }); + test('successful flow with parse', async () => { + const { fetch, handleRequest } = mockChatCompletionFetch(); + + const openai = new OpenAI({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + + const runner = openai.beta.chat.completions.runTools({ + messages: [ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + ], + model: 'gpt-3.5-turbo', + tools: [ + new ParsingToolFunction({ + name: 'numProperties', + function: (obj: object) => String(Object.keys(obj).length), + parameters: { type: 'object' }, + parse: (str: string): object => { + const result = JSON.parse(str); + if (!(result instanceof Object) || Array.isArray(result)) { + throw new Error('must be an object'); + } + return result; + }, + description: 'gets the number of properties on an object', + }), + ], + }); + const listener = new RunnerListener(runner); + + await handleRequest(async (request) => { + expect(request.messages).toEqual([ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + ]); + return { + id: '1', + choices: [ + { + index: 0, + finish_reason: 'function_call', + logprobs: null, + message: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '{"a": 1, "b": 2, "c": 3}', + name: 'numProperties', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion', + usage: { + completion_tokens: 5, + prompt_tokens: 20, + total_tokens: 25, + }, + }; + }); + + await handleRequest(async (request) => { + expect(request.messages).toEqual([ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '{"a": 1, "b": 2, "c": 3}', + name: 'numProperties', + }, + }, + ], + }, + { + role: 'tool', + content: '3', + tool_call_id: '123', + }, + ]); + return { + id: '2', + choices: [ + { + index: 0, + finish_reason: 'stop', + logprobs: null, + message: { + role: 'assistant', + content: `there are 3 properties in {"a": 1, "b": 2, "c": 3}`, + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion', + usage: { + completion_tokens: 10, + prompt_tokens: 25, + total_tokens: 35, + }, + }; + }); + + await runner.done(); + + expect(listener.messages).toEqual([ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { name: 'numProperties', arguments: '{"a": 1, "b": 2, "c": 3}' }, + }, + ], + }, + { role: 'tool', content: '3', tool_call_id: '123' }, + { role: 'assistant', content: 'there are 3 properties in {"a": 1, "b": 2, "c": 3}' }, + ]); + expect(listener.functionCallResults).toEqual(['3']); + await listener.sanityCheck(); + }); + test('flow with parse error', async () => { + const { fetch, handleRequest } = mockChatCompletionFetch(); + + const openai = new OpenAI({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + + const runner = openai.beta.chat.completions.runTools({ + messages: [ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + ], + model: 'gpt-3.5-turbo', + tools: [ + new ParsingToolFunction({ + name: 'numProperties', + function: (obj: object) => String(Object.keys(obj).length), + parameters: { type: 'object' }, + parse: (str: string): object => { + const result = JSON.parse(str); + if (!(result instanceof Object) || Array.isArray(result)) { + throw new Error('must be an object'); + } + return result; + }, + description: 'gets the number of properties on an object', + }), + ], + }); + const listener = new RunnerListener(runner); + + await Promise.all([ + handleRequest(async (request) => { + expect(request.messages).toEqual([ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + ]); + return { + id: '1', + choices: [ + { + index: 0, + finish_reason: 'function_call', + logprobs: null, + message: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '[{"a": 1, "b": 2, "c": 3}]', + name: 'numProperties', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion', + }; + }), + handleRequest(async (request) => { + expect(request.messages).toEqual([ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '[{"a": 1, "b": 2, "c": 3}]', + name: 'numProperties', + }, + }, + ], + }, + { + role: 'tool', + content: `must be an object`, + tool_call_id: '123', + }, + ]); + return { + id: '2', + choices: [ + { + index: 0, + finish_reason: 'function_call', + logprobs: null, + message: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '1234', + function: { + arguments: '{"a": 1, "b": 2, "c": 3}', + name: 'numProperties', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion', + }; + }), + handleRequest(async (request) => { + expect(request.messages).toEqual([ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '[{"a": 1, "b": 2, "c": 3}]', + name: 'numProperties', + }, + }, + ], + }, + { + role: 'tool', + content: `must be an object`, + tool_call_id: '123', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '1234', + function: { + arguments: '{"a": 1, "b": 2, "c": 3}', + name: 'numProperties', + }, + }, + ], + }, + { + role: 'tool', + content: '3', + tool_call_id: '1234', + }, + ]); + return { + id: '3', + choices: [ + { + index: 0, + finish_reason: 'stop', + logprobs: null, + message: { + role: 'assistant', + content: `there are 3 properties in {"a": 1, "b": 2, "c": 3}`, + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion', + }; + }), + runner.done(), + ]); + + expect(listener.messages).toEqual([ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { name: 'numProperties', arguments: '[{"a": 1, "b": 2, "c": 3}]' }, + }, + ], + }, + { role: 'tool', content: `must be an object`, tool_call_id: '123' }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '1234', + function: { name: 'numProperties', arguments: '{"a": 1, "b": 2, "c": 3}' }, + }, + ], + }, + { role: 'tool', content: '3', tool_call_id: '1234' }, + { role: 'assistant', content: 'there are 3 properties in {"a": 1, "b": 2, "c": 3}' }, + ]); + expect(listener.functionCallResults).toEqual([`must be an object`, '3']); + await listener.sanityCheck(); + }); + test('single function call', async () => { + const { fetch, handleRequest } = mockChatCompletionFetch(); + + const openai = new OpenAI({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + + const runner = openai.beta.chat.completions.runTools({ + messages: [{ role: 'user', content: 'tell me what the weather is like' }], + model: 'gpt-3.5-turbo', + tool_choice: { + type: 'function', + function: { + name: 'getWeather', + }, + }, + tools: [ + { + type: 'function', + function: { + function: function getWeather() { + return `it's raining`; + }, + parameters: {}, + description: 'gets the weather', + }, + }, + ], + }); + const listener = new RunnerListener(runner); + + await Promise.all([ + handleRequest(async (request) => { + expect(request.messages).toEqual([{ role: 'user', content: 'tell me what the weather is like' }]); + return { + id: '1', + choices: [ + { + index: 0, + finish_reason: 'function_call', + logprobs: null, + message: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion', + }; + }), + runner.done(), + ]); + + expect(listener.messages).toEqual([ + { role: 'user', content: 'tell me what the weather is like' }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + { role: 'tool', content: `it's raining`, tool_call_id: '123' }, + ]); + expect(listener.functionCallResults).toEqual([`it's raining`]); + await listener.sanityCheck(); + }); + test('wrong function name', async () => { + const { fetch, handleRequest } = mockChatCompletionFetch(); + + const openai = new OpenAI({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + + const runner = openai.beta.chat.completions.runTools({ + messages: [{ role: 'user', content: 'tell me what the weather is like' }], + model: 'gpt-3.5-turbo', + tools: [ + { + type: 'function', + function: { + function: function getWeather() { + return `it's raining`; + }, + parameters: {}, + description: 'gets the weather', + }, + }, + ], + }); + const listener = new RunnerListener(runner); + + await Promise.all([ + handleRequest(async (request) => { + expect(request.messages).toEqual([{ role: 'user', content: 'tell me what the weather is like' }]); + return { + id: '1', + choices: [ + { + index: 0, + finish_reason: 'function_call', + logprobs: null, + message: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'get_weather', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion', + }; + }), + handleRequest(async (request) => { + expect(request.messages).toEqual([ + { role: 'user', content: 'tell me what the weather is like' }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'get_weather', + }, + }, + ], + }, + { + role: 'tool', + content: `Invalid tool_call: "get_weather". Available options are: "getWeather". Please try again`, + tool_call_id: '123', + }, + ]); + return { + id: '2', + choices: [ + { + index: 0, + finish_reason: 'function_call', + logprobs: null, + message: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '1234', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion', + }; + }), + handleRequest(async (request) => { + expect(request.messages).toEqual([ + { role: 'user', content: 'tell me what the weather is like' }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'get_weather', + }, + }, + ], + }, + { + role: 'tool', + content: `Invalid tool_call: "get_weather". Available options are: "getWeather". Please try again`, + tool_call_id: '123', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '1234', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + { + role: 'tool', + content: `it's raining`, + tool_call_id: '1234', + }, + ]); + return { + id: '3', + choices: [ + { + index: 0, + finish_reason: 'stop', + logprobs: null, + message: { + role: 'assistant', + content: `it's raining`, + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion', + }; + }), + runner.done(), + ]); + + expect(listener.messages).toEqual([ + { role: 'user', content: 'tell me what the weather is like' }, + { + role: 'assistant', + content: null, + tool_calls: [{ type: 'function', id: '123', function: { name: 'get_weather', arguments: '' } }], + }, + { + role: 'tool', + content: `Invalid tool_call: "get_weather". Available options are: "getWeather". Please try again`, + tool_call_id: '123', + }, + { + role: 'assistant', + content: null, + tool_calls: [{ type: 'function', id: '1234', function: { name: 'getWeather', arguments: '' } }], + }, + { role: 'tool', content: `it's raining`, tool_call_id: '1234' }, + { role: 'assistant', content: "it's raining" }, + ]); + expect(listener.functionCallResults).toEqual([ + `Invalid tool_call: "get_weather". Available options are: "getWeather". Please try again`, + `it's raining`, + ]); + await listener.sanityCheck(); + }); + }); + + describe('runTools with stream: true', () => { + test('successful flow', async () => { + const { fetch, handleRequest } = mockStreamingChatCompletionFetch(); + + const openai = new OpenAI({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + + const runner = openai.beta.chat.completions.runTools({ + stream: true, + messages: [{ role: 'user', content: 'tell me what the weather is like' }], + model: 'gpt-3.5-turbo', + tools: [ + { + type: 'function', + function: { + function: function getWeather() { + return `it's raining`; + }, + parameters: {}, + description: 'gets the weather', + }, + }, + ], + }); + const listener = new StreamingRunnerListener(runner); + + await Promise.all([ + handleRequest(async function* (request): AsyncIterable { + expect(request.messages).toEqual([{ role: 'user', content: 'tell me what the weather is like' }]); + yield { + id: '1', + choices: [ + { + index: 0, + finish_reason: 'function_call', + logprobs: null, + delta: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + index: 0, + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + }), + handleRequest(async function* (request): AsyncIterable { + expect(request.messages).toEqual([ + { role: 'user', content: 'tell me what the weather is like' }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + { + role: 'tool', + content: `it's raining`, + tool_call_id: '123', + }, + ]); + for (const choice of contentChoiceDeltas(`it's raining`)) { + yield { + id: '2', + choices: [choice], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + } + }), + runner.done(), + ]); + + expect(listener.eventMessages).toEqual([ + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + { role: 'tool', content: `it's raining`, tool_call_id: '123' }, + { role: 'assistant', content: "it's raining" }, + ]); + expect(listener.eventFunctionCallResults).toEqual([`it's raining`]); + await listener.sanityCheck(); + }); + test('flow with abort', async () => { + const { fetch, handleRequest } = mockStreamingChatCompletionFetch(); + + const openai = new OpenAI({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + + const controller = new AbortController(); + const runner = openai.beta.chat.completions.runTools( + { + stream: true, + messages: [{ role: 'user', content: 'tell me what the weather is like' }], + model: 'gpt-3.5-turbo', + tools: [ + { + type: 'function', + function: { + function: function getWeather() { + return `it's raining`; + }, + parameters: {}, + description: 'gets the weather', + }, + }, + ], + }, + { signal: controller.signal }, + ); + runner.on('functionCallResult', () => controller.abort()); + const listener = new StreamingRunnerListener(runner); + + await handleRequest(async function* (request): AsyncIterable { + expect(request.messages).toEqual([{ role: 'user', content: 'tell me what the weather is like' }]); + yield { + id: '1', + choices: [ + { + index: 0, + finish_reason: 'function_call', + delta: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + index: 0, + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + }); + + await runner.done().catch(() => {}); + + expect(listener.eventMessages).toEqual([ + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + { role: 'tool', content: `it's raining`, tool_call_id: '123' }, + ]); + expect(listener.eventFunctionCallResults).toEqual([`it's raining`]); + await listener.sanityCheck({ error: 'Request was aborted.' }); + expect(runner.aborted).toBe(true); + }); + test('successful flow with parse', async () => { + const { fetch, handleRequest } = mockStreamingChatCompletionFetch(); + + const openai = new OpenAI({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + + const runner = openai.beta.chat.completions.runTools({ + stream: true, + messages: [ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + ], + model: 'gpt-3.5-turbo', + tools: [ + new ParsingToolFunction({ + name: 'numProperties', + function: (obj: object) => String(Object.keys(obj).length), + parameters: { type: 'object' }, + parse: (str: string): object => { + const result = JSON.parse(str); + if (!(result instanceof Object) || Array.isArray(result)) { + throw new Error('must be an object'); + } + return result; + }, + description: 'gets the number of properties on an object', + }), + ], + }); + const listener = new StreamingRunnerListener(runner); + + await Promise.all([ + handleRequest(async function* (request): AsyncIterable { + expect(request.messages).toEqual([ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + ]); + yield { + id: '1', + choices: [ + { + index: 0, + finish_reason: 'function_call', + delta: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + index: 0, + function: { + arguments: '{"a": 1, "b": 2, "c": 3}', + name: 'numProperties', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + }), + handleRequest(async function* (request): AsyncIterable { + expect(request.messages).toEqual([ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '{"a": 1, "b": 2, "c": 3}', + name: 'numProperties', + }, + }, + ], + }, + { + role: 'tool', + content: '3', + tool_call_id: '123', + }, + ]); + for (const choice of contentChoiceDeltas(`there are 3 properties in {"a": 1, "b": 2, "c": 3}`)) { + yield { + id: '2', + choices: [choice], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + } + }), + runner.done(), + ]); + + expect(listener.eventMessages).toEqual([ + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { name: 'numProperties', arguments: '{"a": 1, "b": 2, "c": 3}' }, + }, + ], + }, + { role: 'tool', content: '3', tool_call_id: '123' }, + { role: 'assistant', content: 'there are 3 properties in {"a": 1, "b": 2, "c": 3}' }, + ]); + expect(listener.eventFunctionCallResults).toEqual(['3']); + await listener.sanityCheck(); + }); + test('flow with parse error', async () => { + const { fetch, handleRequest } = mockStreamingChatCompletionFetch(); + + const openai = new OpenAI({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + + const runner = openai.beta.chat.completions.runTools({ + stream: true, + messages: [ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + ], + model: 'gpt-3.5-turbo', + tools: [ + new ParsingToolFunction({ + name: 'numProperties', + function: (obj: object) => String(Object.keys(obj).length), + parameters: { type: 'object' }, + parse: (str: string): object => { + const result = JSON.parse(str); + if (!(result instanceof Object) || Array.isArray(result)) { + throw new Error('must be an object'); + } + return result; + }, + description: 'gets the number of properties on an object', + }), + ], + }); + const listener = new StreamingRunnerListener(runner); + + await Promise.all([ + handleRequest(async function* (request): AsyncIterable { + expect(request.messages).toEqual([ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + ]); + for (const choice of functionCallDeltas('[{"a": 1, "b": 2, "c": 3}]', { + name: 'numProperties', + id: '123', + })) { + yield { + id: '1', + choices: [choice], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + } + }), + handleRequest(async function* (request): AsyncIterable { + expect(request.messages).toEqual([ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '[{"a": 1, "b": 2, "c": 3}]', + name: 'numProperties', + }, + }, + ], + }, + { + role: 'tool', + content: `must be an object`, + tool_call_id: '123', + }, + ]); + for (const choice of functionCallDeltas('{"a": 1, "b": 2, "c": 3}', { + name: 'numProperties', + id: '1234', + })) { + yield { + id: '2', + choices: [choice], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + } + }), + handleRequest(async function* (request): AsyncIterable { + expect(request.messages).toEqual([ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '[{"a": 1, "b": 2, "c": 3}]', + name: 'numProperties', + }, + }, + ], + }, + { + role: 'tool', + content: `must be an object`, + tool_call_id: '123', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '1234', + function: { + arguments: '{"a": 1, "b": 2, "c": 3}', + name: 'numProperties', + }, + }, + ], + }, + { + role: 'tool', + content: '3', + tool_call_id: '1234', + }, + ]); + for (const choice of contentChoiceDeltas(`there are 3 properties in {"a": 1, "b": 2, "c": 3}`)) { + yield { + id: '3', + choices: [choice], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + } + }), + runner.done(), + ]); + + expect(listener.eventMessages).toEqual([ + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { name: 'numProperties', arguments: '[{"a": 1, "b": 2, "c": 3}]' }, + }, + ], + }, + { role: 'tool', content: `must be an object`, tool_call_id: '123' }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '1234', + function: { name: 'numProperties', arguments: '{"a": 1, "b": 2, "c": 3}' }, + }, + ], + }, + { role: 'tool', content: '3', tool_call_id: '1234' }, + { role: 'assistant', content: 'there are 3 properties in {"a": 1, "b": 2, "c": 3}' }, + ]); + expect(listener.eventFunctionCallResults).toEqual([`must be an object`, '3']); + await listener.sanityCheck(); + }); + test('single function call', async () => { + const { fetch, handleRequest } = mockStreamingChatCompletionFetch(); + + const openai = new OpenAI({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + + const runner = openai.beta.chat.completions.runTools({ + stream: true, + messages: [{ role: 'user', content: 'tell me what the weather is like' }], + model: 'gpt-3.5-turbo', + tool_choice: { + type: 'function', + function: { + name: 'getWeather', + }, + }, + tools: [ + { + type: 'function', + function: { + function: function getWeather() { + return `it's raining`; + }, + parameters: {}, + description: 'gets the weather', + }, + }, + ], + }); + const listener = new StreamingRunnerListener(runner); + + await Promise.all([ + handleRequest(async function* (request): AsyncIterable { + expect(request.messages).toEqual([{ role: 'user', content: 'tell me what the weather is like' }]); + yield { + id: '1', + choices: [ + { + index: 0, + finish_reason: 'function_call', + delta: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + index: 0, + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + }), + runner.done(), + ]); + + expect(listener.eventMessages).toEqual([ + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + { role: 'tool', tool_call_id: '123', content: `it's raining` }, + ]); + expect(listener.eventFunctionCallResults).toEqual([`it's raining`]); + await listener.sanityCheck(); + }); + test('wrong function name', async () => { + const { fetch, handleRequest } = mockStreamingChatCompletionFetch(); + + const openai = new OpenAI({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + + const runner = openai.beta.chat.completions.runTools({ + stream: true, + messages: [{ role: 'user', content: 'tell me what the weather is like' }], + model: 'gpt-3.5-turbo', + tools: [ + { + type: 'function', + function: { + function: function getWeather() { + return `it's raining`; + }, + parameters: {}, + description: 'gets the weather', + }, + }, + ], + }); + const listener = new StreamingRunnerListener(runner); + + await Promise.all([ + handleRequest(async function* (request): AsyncIterable { + expect(request.messages).toEqual([{ role: 'user', content: 'tell me what the weather is like' }]); + yield { + id: '1', + choices: [ + { + index: 0, + finish_reason: 'function_call', + delta: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + index: 0, + id: '123', + function: { + arguments: '', + name: 'get_weather', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + }), + handleRequest(async function* (request): AsyncIterable { + expect(request.messages).toEqual([ + { role: 'user', content: 'tell me what the weather is like' }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'get_weather', + }, + }, + ], + }, + { + role: 'tool', + content: `Invalid tool_call: "get_weather". Available options are: "getWeather". Please try again`, + tool_call_id: '123', + }, + ]); + yield { + id: '2', + choices: [ + { + index: 0, + finish_reason: 'function_call', + logprobs: null, + delta: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + index: 0, + id: '1234', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + }), + handleRequest(async function* (request): AsyncIterable { + expect(request.messages).toEqual([ + { role: 'user', content: 'tell me what the weather is like' }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'get_weather', + }, + }, + ], + }, + { + role: 'tool', + content: `Invalid tool_call: "get_weather". Available options are: "getWeather". Please try again`, + tool_call_id: '123', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '1234', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + { + role: 'tool', + content: `it's raining`, + tool_call_id: '1234', + }, + ]); + for (const choice of contentChoiceDeltas(`it's raining`)) { + yield { + id: '3', + choices: [choice], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + } + }), + runner.done(), + ]); + + expect(listener.eventMessages).toEqual([ + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'get_weather', + }, + }, + ], + }, + { + role: 'tool', + content: `Invalid tool_call: "get_weather". Available options are: "getWeather". Please try again`, + tool_call_id: '123', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '1234', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + { role: 'tool', content: `it's raining`, tool_call_id: '1234' }, + { role: 'assistant', content: "it's raining" }, + ]); + expect(listener.eventFunctionCallResults).toEqual([ + `Invalid tool_call: "get_weather". Available options are: "getWeather". Please try again`, + `it's raining`, + ]); + await listener.sanityCheck(); + }); + }); + + describe('stream', () => { + test('successful flow', async () => { + const { fetch, handleRequest } = mockStreamingChatCompletionFetch(); + + const openai = new OpenAI({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + + const runner = openai.beta.chat.completions.stream({ + stream: true, + messages: [{ role: 'user', content: 'tell me what the weather is like' }], + model: 'gpt-3.5-turbo', + }); + + const listener = new StreamingRunnerListener(runner); + + await Promise.all([ + handleRequest(async function* (request): AsyncIterable { + expect(request.messages).toEqual([{ role: 'user', content: 'tell me what the weather is like' }]); + for (const choice of contentChoiceDeltas(`The weather is great today!`)) { + yield { + id: '1', + choices: [choice], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + } + }), + runner.done(), + ]); + + expect(listener.finalMessage).toEqual({ role: 'assistant', content: 'The weather is great today!' }); + await listener.sanityCheck(); + }); + test('toReadableStream and fromReadableStream', async () => { + const { fetch, handleRequest } = mockStreamingChatCompletionFetch(); + + const openai = new OpenAI({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + + const runner = openai.beta.chat.completions.stream({ + stream: true, + messages: [{ role: 'user', content: 'tell me what the weather is like' }], + model: 'gpt-3.5-turbo', + }); + + const proxied = ChatCompletionStreamingRunner.fromReadableStream(runner.toReadableStream()); + const listener = new StreamingRunnerListener(proxied); + + await Promise.all([ + handleRequest(async function* (request): AsyncIterable { + expect(request.messages).toEqual([{ role: 'user', content: 'tell me what the weather is like' }]); + for (const choice of contentChoiceDeltas(`The weather is great today!`)) { + yield { + id: '1', + choices: [choice], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + } + }), + proxied.done(), + ]); + + expect(listener.finalMessage).toEqual({ role: 'assistant', content: 'The weather is great today!' }); + await listener.sanityCheck(); + }); + test('handles network errors', async () => { + const { fetch, handleRequest } = mockFetch(); + + const openai = new OpenAI({ apiKey: '...', fetch }); + + const stream = openai.beta.chat.completions.stream( + { + max_tokens: 1024, + model: 'gpt-3.5-turbo', + messages: [{ role: 'user', content: 'Say hello there!' }], + }, + { maxRetries: 0 }, + ); + + handleRequest(async () => { + throw new Error('mock request error'); + }).catch(() => {}); + + async function runStream() { + await stream.done(); + } + + await expect(runStream).rejects.toThrow(APIConnectionError); + }); + test('handles network errors on async iterator', async () => { + const { fetch, handleRequest } = mockFetch(); + + const openai = new OpenAI({ apiKey: '...', fetch }); + + const stream = openai.beta.chat.completions.stream( + { + max_tokens: 1024, + model: 'gpt-3.5-turbo', + messages: [{ role: 'user', content: 'Say hello there!' }], + }, + { maxRetries: 0 }, + ); + + handleRequest(async () => { + throw new Error('mock request error'); + }).catch(() => {}); + + async function runStream() { + for await (const _event of stream) { + continue; + } + } + + await expect(runStream).rejects.toThrow(APIConnectionError); + }); + }); +}); diff --git a/backend/node_modules/openai/src/lib/ChatCompletionRunner.ts b/backend/node_modules/openai/src/lib/ChatCompletionRunner.ts new file mode 100644 index 0000000000000000000000000000000000000000..cf5f19765c86d5c261776b5cd60e0d2a522b7022 --- /dev/null +++ b/backend/node_modules/openai/src/lib/ChatCompletionRunner.ts @@ -0,0 +1,68 @@ +import { + type Completions, + type ChatCompletionMessageParam, + type ChatCompletionCreateParamsNonStreaming, +} from "../resources/chat/completions"; +import { type RunnableFunctions, type BaseFunctionsArgs, RunnableTools } from './RunnableFunction'; +import { + AbstractChatCompletionRunner, + AbstractChatCompletionRunnerEvents, + RunnerOptions, +} from './AbstractChatCompletionRunner'; +import { isAssistantMessage } from './chatCompletionUtils'; + +export interface ChatCompletionRunnerEvents extends AbstractChatCompletionRunnerEvents { + content: (content: string) => void; +} + +export type ChatCompletionFunctionRunnerParams = Omit< + ChatCompletionCreateParamsNonStreaming, + 'functions' +> & { + functions: RunnableFunctions; +}; + +export type ChatCompletionToolRunnerParams = Omit< + ChatCompletionCreateParamsNonStreaming, + 'tools' +> & { + tools: RunnableTools; +}; + +export class ChatCompletionRunner extends AbstractChatCompletionRunner { + /** @deprecated - please use `runTools` instead. */ + static runFunctions( + completions: Completions, + params: ChatCompletionFunctionRunnerParams, + options?: RunnerOptions, + ): ChatCompletionRunner { + const runner = new ChatCompletionRunner(); + const opts = { + ...options, + headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'runFunctions' }, + }; + runner._run(() => runner._runFunctions(completions, params, opts)); + return runner; + } + + static runTools( + completions: Completions, + params: ChatCompletionToolRunnerParams, + options?: RunnerOptions, + ): ChatCompletionRunner { + const runner = new ChatCompletionRunner(); + const opts = { + ...options, + headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'runTools' }, + }; + runner._run(() => runner._runTools(completions, params, opts)); + return runner; + } + + override _addMessage(message: ChatCompletionMessageParam) { + super._addMessage(message); + if (isAssistantMessage(message) && message.content) { + this._emit('content', message.content as string); + } + } +} diff --git a/backend/node_modules/openai/src/lib/ChatCompletionStream.ts b/backend/node_modules/openai/src/lib/ChatCompletionStream.ts new file mode 100644 index 0000000000000000000000000000000000000000..6e0d3cff1e784c35f807be19bbac1eaa50fe8093 --- /dev/null +++ b/backend/node_modules/openai/src/lib/ChatCompletionStream.ts @@ -0,0 +1,494 @@ +import * as Core from "../core"; +import { OpenAIError, APIUserAbortError } from "../error"; +import { + Completions, + type ChatCompletion, + type ChatCompletionChunk, + type ChatCompletionCreateParams, + type ChatCompletionCreateParamsBase, +} from "../resources/chat/completions"; +import { + AbstractChatCompletionRunner, + type AbstractChatCompletionRunnerEvents, +} from './AbstractChatCompletionRunner'; +import { type ReadableStream } from "../_shims/index"; +import { Stream } from "../streaming"; + +export interface ChatCompletionStreamEvents extends AbstractChatCompletionRunnerEvents { + content: (contentDelta: string, contentSnapshot: string) => void; + chunk: (chunk: ChatCompletionChunk, snapshot: ChatCompletionSnapshot) => void; +} + +export type ChatCompletionStreamParams = Omit & { + stream?: true; +}; + +export class ChatCompletionStream + extends AbstractChatCompletionRunner + implements AsyncIterable +{ + #currentChatCompletionSnapshot: ChatCompletionSnapshot | undefined; + + get currentChatCompletionSnapshot(): ChatCompletionSnapshot | undefined { + return this.#currentChatCompletionSnapshot; + } + + /** + * Intended for use on the frontend, consuming a stream produced with + * `.toReadableStream()` on the backend. + * + * Note that messages sent to the model do not appear in `.on('message')` + * in this context. + */ + static fromReadableStream(stream: ReadableStream): ChatCompletionStream { + const runner = new ChatCompletionStream(); + runner._run(() => runner._fromReadableStream(stream)); + return runner; + } + + static createChatCompletion( + completions: Completions, + params: ChatCompletionStreamParams, + options?: Core.RequestOptions, + ): ChatCompletionStream { + const runner = new ChatCompletionStream(); + runner._run(() => + runner._runChatCompletion( + completions, + { ...params, stream: true }, + { ...options, headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' } }, + ), + ); + return runner; + } + + #beginRequest() { + if (this.ended) return; + this.#currentChatCompletionSnapshot = undefined; + } + #addChunk(chunk: ChatCompletionChunk) { + if (this.ended) return; + const completion = this.#accumulateChatCompletion(chunk); + this._emit('chunk', chunk, completion); + const delta = chunk.choices[0]?.delta?.content; + const snapshot = completion.choices[0]?.message; + if (delta != null && snapshot?.role === 'assistant' && snapshot?.content) { + this._emit('content', delta, snapshot.content); + } + } + #endRequest(): ChatCompletion { + if (this.ended) { + throw new OpenAIError(`stream has ended, this shouldn't happen`); + } + const snapshot = this.#currentChatCompletionSnapshot; + if (!snapshot) { + throw new OpenAIError(`request ended without sending any chunks`); + } + this.#currentChatCompletionSnapshot = undefined; + return finalizeChatCompletion(snapshot); + } + + protected override async _createChatCompletion( + completions: Completions, + params: ChatCompletionCreateParams, + options?: Core.RequestOptions, + ): Promise { + const signal = options?.signal; + if (signal) { + if (signal.aborted) this.controller.abort(); + signal.addEventListener('abort', () => this.controller.abort()); + } + this.#beginRequest(); + const stream = await completions.create( + { ...params, stream: true }, + { ...options, signal: this.controller.signal }, + ); + this._connected(); + for await (const chunk of stream) { + this.#addChunk(chunk); + } + if (stream.controller.signal?.aborted) { + throw new APIUserAbortError(); + } + return this._addChatCompletion(this.#endRequest()); + } + + protected async _fromReadableStream( + readableStream: ReadableStream, + options?: Core.RequestOptions, + ): Promise { + const signal = options?.signal; + if (signal) { + if (signal.aborted) this.controller.abort(); + signal.addEventListener('abort', () => this.controller.abort()); + } + this.#beginRequest(); + this._connected(); + const stream = Stream.fromReadableStream(readableStream, this.controller); + let chatId; + for await (const chunk of stream) { + if (chatId && chatId !== chunk.id) { + // A new request has been made. + this._addChatCompletion(this.#endRequest()); + } + + this.#addChunk(chunk); + chatId = chunk.id; + } + if (stream.controller.signal?.aborted) { + throw new APIUserAbortError(); + } + return this._addChatCompletion(this.#endRequest()); + } + + #accumulateChatCompletion(chunk: ChatCompletionChunk): ChatCompletionSnapshot { + let snapshot = this.#currentChatCompletionSnapshot; + const { choices, ...rest } = chunk; + if (!snapshot) { + snapshot = this.#currentChatCompletionSnapshot = { + ...rest, + choices: [], + }; + } else { + Object.assign(snapshot, rest); + } + + for (const { delta, finish_reason, index, logprobs = null, ...other } of chunk.choices) { + let choice = snapshot.choices[index]; + if (!choice) { + choice = snapshot.choices[index] = { finish_reason, index, message: {}, logprobs, ...other }; + } + + if (logprobs) { + if (!choice.logprobs) { + choice.logprobs = Object.assign({}, logprobs); + } else { + const { content, ...rest } = logprobs; + Object.assign(choice.logprobs, rest); + if (content) { + choice.logprobs.content ??= []; + choice.logprobs.content.push(...content); + } + } + } + + if (finish_reason) choice.finish_reason = finish_reason; + Object.assign(choice, other); + + if (!delta) continue; // Shouldn't happen; just in case. + const { content, function_call, role, tool_calls, ...rest } = delta; + Object.assign(choice.message, rest); + + if (content) choice.message.content = (choice.message.content || '') + content; + if (role) choice.message.role = role; + if (function_call) { + if (!choice.message.function_call) { + choice.message.function_call = function_call; + } else { + if (function_call.name) choice.message.function_call.name = function_call.name; + if (function_call.arguments) { + choice.message.function_call.arguments ??= ''; + choice.message.function_call.arguments += function_call.arguments; + } + } + } + if (tool_calls) { + if (!choice.message.tool_calls) choice.message.tool_calls = []; + for (const { index, id, type, function: fn, ...rest } of tool_calls) { + const tool_call = (choice.message.tool_calls[index] ??= {}); + Object.assign(tool_call, rest); + if (id) tool_call.id = id; + if (type) tool_call.type = type; + if (fn) tool_call.function ??= { arguments: '' }; + if (fn?.name) tool_call.function!.name = fn.name; + if (fn?.arguments) tool_call.function!.arguments += fn.arguments; + } + } + } + return snapshot; + } + + [Symbol.asyncIterator](): AsyncIterator { + const pushQueue: ChatCompletionChunk[] = []; + const readQueue: { + resolve: (chunk: ChatCompletionChunk | undefined) => void; + reject: (err: unknown) => void; + }[] = []; + let done = false; + + this.on('chunk', (chunk) => { + const reader = readQueue.shift(); + if (reader) { + reader.resolve(chunk); + } else { + pushQueue.push(chunk); + } + }); + + this.on('end', () => { + done = true; + for (const reader of readQueue) { + reader.resolve(undefined); + } + readQueue.length = 0; + }); + + this.on('abort', (err) => { + done = true; + for (const reader of readQueue) { + reader.reject(err); + } + readQueue.length = 0; + }); + + this.on('error', (err) => { + done = true; + for (const reader of readQueue) { + reader.reject(err); + } + readQueue.length = 0; + }); + + return { + next: async (): Promise> => { + if (!pushQueue.length) { + if (done) { + return { value: undefined, done: true }; + } + return new Promise((resolve, reject) => + readQueue.push({ resolve, reject }), + ).then((chunk) => (chunk ? { value: chunk, done: false } : { value: undefined, done: true })); + } + const chunk = pushQueue.shift()!; + return { value: chunk, done: false }; + }, + return: async () => { + this.abort(); + return { value: undefined, done: true }; + }, + }; + } + + toReadableStream(): ReadableStream { + const stream = new Stream(this[Symbol.asyncIterator].bind(this), this.controller); + return stream.toReadableStream(); + } +} + +function finalizeChatCompletion(snapshot: ChatCompletionSnapshot): ChatCompletion { + const { id, choices, created, model, system_fingerprint, ...rest } = snapshot; + return { + ...rest, + id, + choices: choices.map( + ({ message, finish_reason, index, logprobs, ...choiceRest }): ChatCompletion.Choice => { + if (!finish_reason) throw new OpenAIError(`missing finish_reason for choice ${index}`); + const { content = null, function_call, tool_calls, ...messageRest } = message; + const role = message.role as 'assistant'; // this is what we expect; in theory it could be different which would make our types a slight lie but would be fine. + if (!role) throw new OpenAIError(`missing role for choice ${index}`); + if (function_call) { + const { arguments: args, name } = function_call; + if (args == null) throw new OpenAIError(`missing function_call.arguments for choice ${index}`); + if (!name) throw new OpenAIError(`missing function_call.name for choice ${index}`); + return { + ...choiceRest, + message: { content, function_call: { arguments: args, name }, role }, + finish_reason, + index, + logprobs, + }; + } + if (tool_calls) { + return { + ...choiceRest, + index, + finish_reason, + logprobs, + message: { + ...messageRest, + role, + content, + tool_calls: tool_calls.map((tool_call, i) => { + const { function: fn, type, id, ...toolRest } = tool_call; + const { arguments: args, name, ...fnRest } = fn || {}; + if (id == null) + throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].id\n${str(snapshot)}`); + if (type == null) + throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].type\n${str(snapshot)}`); + if (name == null) + throw new OpenAIError( + `missing choices[${index}].tool_calls[${i}].function.name\n${str(snapshot)}`, + ); + if (args == null) + throw new OpenAIError( + `missing choices[${index}].tool_calls[${i}].function.arguments\n${str(snapshot)}`, + ); + + return { ...toolRest, id, type, function: { ...fnRest, name, arguments: args } }; + }), + }, + }; + } + return { + ...choiceRest, + message: { ...messageRest, content, role }, + finish_reason, + index, + logprobs, + }; + }, + ), + created, + model, + object: 'chat.completion', + ...(system_fingerprint ? { system_fingerprint } : {}), + }; +} + +function str(x: unknown) { + return JSON.stringify(x); +} + +/** + * Represents a streamed chunk of a chat completion response returned by model, + * based on the provided input. + */ +export interface ChatCompletionSnapshot { + /** + * A unique identifier for the chat completion. + */ + id: string; + + /** + * A list of chat completion choices. Can be more than one if `n` is greater + * than 1. + */ + choices: Array; + + /** + * The Unix timestamp (in seconds) of when the chat completion was created. + */ + created: number; + + /** + * The model to generate the completion. + */ + model: string; + + // Note we do not include an "object" type on the snapshot, + // because the object is not a valid "chat.completion" until finalized. + // object: 'chat.completion'; + + /** + * This fingerprint represents the backend configuration that the model runs with. + * + * Can be used in conjunction with the `seed` request parameter to understand when + * backend changes have been made that might impact determinism. + */ + system_fingerprint?: string; +} + +export namespace ChatCompletionSnapshot { + export interface Choice { + /** + * A chat completion delta generated by streamed model responses. + */ + message: Choice.Message; + + /** + * The reason the model stopped generating tokens. This will be `stop` if the model + * hit a natural stop point or a provided stop sequence, `length` if the maximum + * number of tokens specified in the request was reached, `content_filter` if + * content was omitted due to a flag from our content filters, or `function_call` + * if the model called a function. + */ + finish_reason: ChatCompletion.Choice['finish_reason'] | null; + + /** + * Log probability information for the choice. + */ + logprobs: ChatCompletion.Choice.Logprobs | null; + + /** + * The index of the choice in the list of choices. + */ + index: number; + } + + export namespace Choice { + /** + * A chat completion delta generated by streamed model responses. + */ + export interface Message { + /** + * The contents of the chunk message. + */ + content?: string | null; + + /** + * The name and arguments of a function that should be called, as generated by the + * model. + */ + function_call?: Message.FunctionCall; + + tool_calls?: Array; + + /** + * The role of the author of this message. + */ + role?: 'system' | 'user' | 'assistant' | 'function' | 'tool'; + } + + export namespace Message { + export interface ToolCall { + /** + * The ID of the tool call. + */ + id?: string; + + function?: ToolCall.Function; + + /** + * The type of the tool. + */ + type?: 'function'; + } + + export namespace ToolCall { + export interface Function { + /** + * The arguments to call the function with, as generated by the model in JSON + * format. Note that the model does not always generate valid JSON, and may + * hallucinate parameters not defined by your function schema. Validate the + * arguments in your code before calling your function. + */ + arguments?: string; + + /** + * The name of the function to call. + */ + name?: string; + } + } + + /** + * The name and arguments of a function that should be called, as generated by the + * model. + */ + export interface FunctionCall { + /** + * The arguments to call the function with, as generated by the model in JSON + * format. Note that the model does not always generate valid JSON, and may + * hallucinate parameters not defined by your function schema. Validate the + * arguments in your code before calling your function. + */ + arguments?: string; + + /** + * The name of the function to call. + */ + name?: string; + } + } + } +} diff --git a/backend/node_modules/openai/src/lib/ChatCompletionStreamingRunner.ts b/backend/node_modules/openai/src/lib/ChatCompletionStreamingRunner.ts new file mode 100644 index 0000000000000000000000000000000000000000..1a3910ba0f8c2b1469c1cf789c9e0c108cfb2f22 --- /dev/null +++ b/backend/node_modules/openai/src/lib/ChatCompletionStreamingRunner.ts @@ -0,0 +1,68 @@ +import { + Completions, + type ChatCompletionChunk, + type ChatCompletionCreateParamsStreaming, +} from "../resources/chat/completions"; +import { RunnerOptions, type AbstractChatCompletionRunnerEvents } from './AbstractChatCompletionRunner'; +import { type ReadableStream } from "../_shims/index"; +import { RunnableTools, type BaseFunctionsArgs, type RunnableFunctions } from './RunnableFunction'; +import { ChatCompletionSnapshot, ChatCompletionStream } from './ChatCompletionStream'; + +export interface ChatCompletionStreamEvents extends AbstractChatCompletionRunnerEvents { + content: (contentDelta: string, contentSnapshot: string) => void; + chunk: (chunk: ChatCompletionChunk, snapshot: ChatCompletionSnapshot) => void; +} + +export type ChatCompletionStreamingFunctionRunnerParams = Omit< + ChatCompletionCreateParamsStreaming, + 'functions' +> & { + functions: RunnableFunctions; +}; + +export type ChatCompletionStreamingToolRunnerParams = Omit< + ChatCompletionCreateParamsStreaming, + 'tools' +> & { + tools: RunnableTools; +}; + +export class ChatCompletionStreamingRunner + extends ChatCompletionStream + implements AsyncIterable +{ + static override fromReadableStream(stream: ReadableStream): ChatCompletionStreamingRunner { + const runner = new ChatCompletionStreamingRunner(); + runner._run(() => runner._fromReadableStream(stream)); + return runner; + } + + /** @deprecated - please use `runTools` instead. */ + static runFunctions( + completions: Completions, + params: ChatCompletionStreamingFunctionRunnerParams, + options?: RunnerOptions, + ): ChatCompletionStreamingRunner { + const runner = new ChatCompletionStreamingRunner(); + const opts = { + ...options, + headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'runFunctions' }, + }; + runner._run(() => runner._runFunctions(completions, params, opts)); + return runner; + } + + static runTools( + completions: Completions, + params: ChatCompletionStreamingToolRunnerParams, + options?: RunnerOptions, + ): ChatCompletionStreamingRunner { + const runner = new ChatCompletionStreamingRunner(); + const opts = { + ...options, + headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'runTools' }, + }; + runner._run(() => runner._runTools(completions, params, opts)); + return runner; + } +} diff --git a/backend/node_modules/openai/src/lib/RunnableFunction.ts b/backend/node_modules/openai/src/lib/RunnableFunction.ts new file mode 100644 index 0000000000000000000000000000000000000000..96ca06c86cf03338c0068e81ffd1232b9e3e6981 --- /dev/null +++ b/backend/node_modules/openai/src/lib/RunnableFunction.ts @@ -0,0 +1,134 @@ +import { type ChatCompletionRunner } from './ChatCompletionRunner'; +import { type ChatCompletionStreamingRunner } from './ChatCompletionStreamingRunner'; +import { JSONSchema } from './jsonschema'; + +type PromiseOrValue = T | Promise; + +export type RunnableFunctionWithParse = { + /** + * @param args the return value from `parse`. + * @param runner the runner evaluating this callback. + * @returns a string to send back to OpenAI. + */ + function: ( + args: Args, + runner: ChatCompletionRunner | ChatCompletionStreamingRunner, + ) => PromiseOrValue; + /** + * @param input the raw args from the OpenAI function call. + * @returns the parsed arguments to pass to `function` + */ + parse: (input: string) => PromiseOrValue; + /** + * The parameters the function accepts, describes as a JSON Schema object. + */ + parameters: JSONSchema; + /** + * A description of what the function does, used by the model to choose when and how to call the function. + */ + description: string; + /** + * The name of the function to be called. Will default to function.name if omitted. + */ + name?: string | undefined; +}; + +export type RunnableFunctionWithoutParse = { + /** + * @param args the raw args from the OpenAI function call. + * @returns a string to send back to OpenAI + */ + function: ( + args: string, + runner: ChatCompletionRunner | ChatCompletionStreamingRunner, + ) => PromiseOrValue; + /** + * The parameters the function accepts, describes as a JSON Schema object. + */ + parameters: JSONSchema; + /** + * A description of what the function does, used by the model to choose when and how to call the function. + */ + description: string; + /** + * The name of the function to be called. Will default to function.name if omitted. + */ + name?: string | undefined; +}; + +export type RunnableFunction = + Args extends string ? RunnableFunctionWithoutParse + : Args extends object ? RunnableFunctionWithParse + : never; + +export type RunnableToolFunction = + Args extends string ? RunnableToolFunctionWithoutParse + : Args extends object ? RunnableToolFunctionWithParse + : never; + +export type RunnableToolFunctionWithoutParse = { + type: 'function'; + function: RunnableFunctionWithoutParse; +}; +export type RunnableToolFunctionWithParse = { + type: 'function'; + function: RunnableFunctionWithParse; +}; + +export function isRunnableFunctionWithParse( + fn: any, +): fn is RunnableFunctionWithParse { + return typeof (fn as any).parse === 'function'; +} + +export type BaseFunctionsArgs = readonly (object | string)[]; + +export type RunnableFunctions = + [any[]] extends [FunctionsArgs] ? readonly RunnableFunction[] + : { + [Index in keyof FunctionsArgs]: Index extends number ? RunnableFunction + : FunctionsArgs[Index]; + }; + +export type RunnableTools = + [any[]] extends [FunctionsArgs] ? readonly RunnableToolFunction[] + : { + [Index in keyof FunctionsArgs]: Index extends number ? RunnableToolFunction + : FunctionsArgs[Index]; + }; + +/** + * This is helper class for passing a `function` and `parse` where the `function` + * argument type matches the `parse` return type. + * + * @deprecated - please use ParsingToolFunction instead. + */ +export class ParsingFunction { + function: RunnableFunctionWithParse['function']; + parse: RunnableFunctionWithParse['parse']; + parameters: RunnableFunctionWithParse['parameters']; + description: RunnableFunctionWithParse['description']; + name?: RunnableFunctionWithParse['name']; + + constructor(input: RunnableFunctionWithParse) { + this.function = input.function; + this.parse = input.parse; + this.parameters = input.parameters; + this.description = input.description; + this.name = input.name; + } +} + +/** + * This is helper class for passing a `function` and `parse` where the `function` + * argument type matches the `parse` return type. + */ +export class ParsingToolFunction { + type: 'function'; + function: RunnableFunctionWithParse; + + constructor(input: RunnableFunctionWithParse) { + this.type = 'function'; + this.function = input; + } +} diff --git a/backend/node_modules/openai/src/lib/chatCompletionUtils.ts b/backend/node_modules/openai/src/lib/chatCompletionUtils.ts new file mode 100644 index 0000000000000000000000000000000000000000..3f200affb1714d333dafa1dcf46dbcc8bf7edace --- /dev/null +++ b/backend/node_modules/openai/src/lib/chatCompletionUtils.ts @@ -0,0 +1,28 @@ +import { + type ChatCompletionAssistantMessageParam, + type ChatCompletionFunctionMessageParam, + type ChatCompletionMessageParam, + type ChatCompletionToolMessageParam, +} from "../resources"; + +export const isAssistantMessage = ( + message: ChatCompletionMessageParam | null | undefined, +): message is ChatCompletionAssistantMessageParam => { + return message?.role === 'assistant'; +}; + +export const isFunctionMessage = ( + message: ChatCompletionMessageParam | null | undefined, +): message is ChatCompletionFunctionMessageParam => { + return message?.role === 'function'; +}; + +export const isToolMessage = ( + message: ChatCompletionMessageParam | null | undefined, +): message is ChatCompletionToolMessageParam => { + return message?.role === 'tool'; +}; + +export function isPresent(obj: T | null | undefined): obj is T { + return obj != null; +} diff --git a/backend/node_modules/openai/src/lib/jsonschema.ts b/backend/node_modules/openai/src/lib/jsonschema.ts new file mode 100644 index 0000000000000000000000000000000000000000..6362777054006210c27a9deaecb198b670caab50 --- /dev/null +++ b/backend/node_modules/openai/src/lib/jsonschema.ts @@ -0,0 +1,148 @@ +// File mostly copied from @types/json-schema, but stripped down a bit for brevity +// https://github.com/DefinitelyTyped/DefinitelyTyped/blob/817274f3280152ba2929a6067c93df8b34c4c9aa/types/json-schema/index.d.ts +// +// ================================================================================================== +// JSON Schema Draft 07 +// ================================================================================================== +// https://tools.ietf.org/html/draft-handrews-json-schema-validation-01 +// -------------------------------------------------------------------------------------------------- + +/** + * Primitive type + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.1.1 + */ +export type JSONSchemaTypeName = + | ({} & string) + | 'string' + | 'number' + | 'integer' + | 'boolean' + | 'object' + | 'array' + | 'null'; + +/** + * Primitive type + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.1.1 + */ +export type JSONSchemaType = + | string // + | number + | boolean + | JSONSchemaObject + | JSONSchemaArray + | null; + +// Workaround for infinite type recursion +export interface JSONSchemaObject { + [key: string]: JSONSchemaType; +} + +// Workaround for infinite type recursion +// https://github.com/Microsoft/TypeScript/issues/3496#issuecomment-128553540 +export interface JSONSchemaArray extends Array {} + +/** + * Meta schema + * + * Recommended values: + * - 'http://json-schema.org/schema#' + * - 'http://json-schema.org/hyper-schema#' + * - 'http://json-schema.org/draft-07/schema#' + * - 'http://json-schema.org/draft-07/hyper-schema#' + * + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-5 + */ +export type JSONSchemaVersion = string; + +/** + * JSON Schema v7 + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01 + */ +export type JSONSchemaDefinition = JSONSchema | boolean; +export interface JSONSchema { + $id?: string | undefined; + $comment?: string | undefined; + + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.1 + */ + type?: JSONSchemaTypeName | JSONSchemaTypeName[] | undefined; + enum?: JSONSchemaType[] | undefined; + const?: JSONSchemaType | undefined; + + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.2 + */ + multipleOf?: number | undefined; + maximum?: number | undefined; + exclusiveMaximum?: number | undefined; + minimum?: number | undefined; + exclusiveMinimum?: number | undefined; + + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.3 + */ + maxLength?: number | undefined; + minLength?: number | undefined; + pattern?: string | undefined; + + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.4 + */ + items?: JSONSchemaDefinition | JSONSchemaDefinition[] | undefined; + additionalItems?: JSONSchemaDefinition | undefined; + maxItems?: number | undefined; + minItems?: number | undefined; + uniqueItems?: boolean | undefined; + contains?: JSONSchemaDefinition | undefined; + + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.5 + */ + maxProperties?: number | undefined; + minProperties?: number | undefined; + required?: string[] | undefined; + properties?: + | { + [key: string]: JSONSchemaDefinition; + } + | undefined; + patternProperties?: + | { + [key: string]: JSONSchemaDefinition; + } + | undefined; + additionalProperties?: JSONSchemaDefinition | undefined; + propertyNames?: JSONSchemaDefinition | undefined; + + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.6 + */ + if?: JSONSchemaDefinition | undefined; + then?: JSONSchemaDefinition | undefined; + else?: JSONSchemaDefinition | undefined; + + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.7 + */ + allOf?: JSONSchemaDefinition[] | undefined; + anyOf?: JSONSchemaDefinition[] | undefined; + oneOf?: JSONSchemaDefinition[] | undefined; + not?: JSONSchemaDefinition | undefined; + + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-7 + */ + format?: string | undefined; + + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-10 + */ + title?: string | undefined; + description?: string | undefined; + default?: JSONSchemaType | undefined; + readOnly?: boolean | undefined; + writeOnly?: boolean | undefined; + examples?: JSONSchemaType | undefined; +} diff --git a/backend/node_modules/openai/src/pagination.ts b/backend/node_modules/openai/src/pagination.ts new file mode 100644 index 0000000000000000000000000000000000000000..63644e333860b19694a36f352862530d188472d0 --- /dev/null +++ b/backend/node_modules/openai/src/pagination.ts @@ -0,0 +1,98 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { AbstractPage, Response, APIClient, FinalRequestOptions, PageInfo } from './core'; + +export interface PageResponse { + data: Array; + + object: string; +} + +/** + * Note: no pagination actually occurs yet, this is for forwards-compatibility. + */ +export class Page extends AbstractPage implements PageResponse { + data: Array; + + object: string; + + constructor(client: APIClient, response: Response, body: PageResponse, options: FinalRequestOptions) { + super(client, response, body, options); + + this.data = body.data || []; + this.object = body.object; + } + + getPaginatedItems(): Item[] { + return this.data ?? []; + } + + // @deprecated Please use `nextPageInfo()` instead + /** + * This page represents a response that isn't actually paginated at the API level + * so there will never be any next page params. + */ + nextPageParams(): null { + return null; + } + + nextPageInfo(): null { + return null; + } +} + +export interface CursorPageResponse { + data: Array; +} + +export interface CursorPageParams { + after?: string; + + limit?: number; +} + +export class CursorPage + extends AbstractPage + implements CursorPageResponse +{ + data: Array; + + constructor( + client: APIClient, + response: Response, + body: CursorPageResponse, + options: FinalRequestOptions, + ) { + super(client, response, body, options); + + this.data = body.data || []; + } + + getPaginatedItems(): Item[] { + return this.data ?? []; + } + + // @deprecated Please use `nextPageInfo()` instead + nextPageParams(): Partial | null { + const info = this.nextPageInfo(); + if (!info) return null; + if ('params' in info) return info.params; + const params = Object.fromEntries(info.url.searchParams); + if (!Object.keys(params).length) return null; + return params; + } + + nextPageInfo(): PageInfo | null { + const data = this.getPaginatedItems(); + if (!data.length) { + return null; + } + + const id = data[data.length - 1]?.id; + if (!id) { + return null; + } + + return { params: { after: id } }; + } +} diff --git a/backend/node_modules/openai/src/resource.ts b/backend/node_modules/openai/src/resource.ts new file mode 100644 index 0000000000000000000000000000000000000000..87847c87968618fad6ca6587b0f2898fe9738a00 --- /dev/null +++ b/backend/node_modules/openai/src/resource.ts @@ -0,0 +1,11 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import type { OpenAI } from './index'; + +export class APIResource { + protected _client: OpenAI; + + constructor(client: OpenAI) { + this._client = client; + } +} diff --git a/backend/node_modules/openai/src/resources/audio/audio.ts b/backend/node_modules/openai/src/resources/audio/audio.ts new file mode 100644 index 0000000000000000000000000000000000000000..6621f884bce0baeaad12ad6fb9084129c7e7ab6e --- /dev/null +++ b/backend/node_modules/openai/src/resources/audio/audio.ts @@ -0,0 +1,23 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { APIResource } from "../../resource"; +import * as SpeechAPI from "./speech"; +import * as TranscriptionsAPI from "./transcriptions"; +import * as TranslationsAPI from "./translations"; + +export class Audio extends APIResource { + transcriptions: TranscriptionsAPI.Transcriptions = new TranscriptionsAPI.Transcriptions(this._client); + translations: TranslationsAPI.Translations = new TranslationsAPI.Translations(this._client); + speech: SpeechAPI.Speech = new SpeechAPI.Speech(this._client); +} + +export namespace Audio { + export import Transcriptions = TranscriptionsAPI.Transcriptions; + export import Transcription = TranscriptionsAPI.Transcription; + export import TranscriptionCreateParams = TranscriptionsAPI.TranscriptionCreateParams; + export import Translations = TranslationsAPI.Translations; + export import Translation = TranslationsAPI.Translation; + export import TranslationCreateParams = TranslationsAPI.TranslationCreateParams; + export import Speech = SpeechAPI.Speech; + export import SpeechCreateParams = SpeechAPI.SpeechCreateParams; +} diff --git a/backend/node_modules/openai/src/resources/audio/index.ts b/backend/node_modules/openai/src/resources/audio/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..31732a26705022e8dacb196baa3d86532a01a866 --- /dev/null +++ b/backend/node_modules/openai/src/resources/audio/index.ts @@ -0,0 +1,6 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export { Audio } from './audio'; +export { SpeechCreateParams, Speech } from './speech'; +export { Transcription, TranscriptionCreateParams, Transcriptions } from './transcriptions'; +export { Translation, TranslationCreateParams, Translations } from './translations'; diff --git a/backend/node_modules/openai/src/resources/audio/speech.ts b/backend/node_modules/openai/src/resources/audio/speech.ts new file mode 100644 index 0000000000000000000000000000000000000000..87b6582ba65d60d4620289e623ec42278f4dfa7f --- /dev/null +++ b/backend/node_modules/openai/src/resources/audio/speech.ts @@ -0,0 +1,52 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import * as Core from "../../core"; +import { APIResource } from "../../resource"; +import { type Response } from "../../_shims/index"; +import * as SpeechAPI from "./speech"; + +export class Speech extends APIResource { + /** + * Generates audio from the input text. + */ + create(body: SpeechCreateParams, options?: Core.RequestOptions): Core.APIPromise { + return this._client.post('/audio/speech', { body, ...options, __binaryResponse: true }); + } +} + +export interface SpeechCreateParams { + /** + * The text to generate audio for. The maximum length is 4096 characters. + */ + input: string; + + /** + * One of the available [TTS models](https://platform.openai.com/docs/models/tts): + * `tts-1` or `tts-1-hd` + */ + model: (string & {}) | 'tts-1' | 'tts-1-hd'; + + /** + * The voice to use when generating the audio. Supported voices are `alloy`, + * `echo`, `fable`, `onyx`, `nova`, and `shimmer`. Previews of the voices are + * available in the + * [Text to speech guide](https://platform.openai.com/docs/guides/text-to-speech/voice-options). + */ + voice: 'alloy' | 'echo' | 'fable' | 'onyx' | 'nova' | 'shimmer'; + + /** + * The format to audio in. Supported formats are `mp3`, `opus`, `aac`, `flac`, + * `wav`, and `pcm`. + */ + response_format?: 'mp3' | 'opus' | 'aac' | 'flac' | 'wav' | 'pcm'; + + /** + * The speed of the generated audio. Select a value from `0.25` to `4.0`. `1.0` is + * the default. + */ + speed?: number; +} + +export namespace Speech { + export import SpeechCreateParams = SpeechAPI.SpeechCreateParams; +} diff --git a/backend/node_modules/openai/src/resources/audio/transcriptions.ts b/backend/node_modules/openai/src/resources/audio/transcriptions.ts new file mode 100644 index 0000000000000000000000000000000000000000..4a939db341b0c1a3f6f8d0cc2fa8c59c5043972c --- /dev/null +++ b/backend/node_modules/openai/src/resources/audio/transcriptions.ts @@ -0,0 +1,84 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import * as Core from "../../core"; +import { APIResource } from "../../resource"; +import * as TranscriptionsAPI from "./transcriptions"; +import { type Uploadable, multipartFormRequestOptions } from "../../core"; + +export class Transcriptions extends APIResource { + /** + * Transcribes audio into the input language. + */ + create(body: TranscriptionCreateParams, options?: Core.RequestOptions): Core.APIPromise { + return this._client.post('/audio/transcriptions', multipartFormRequestOptions({ body, ...options })); + } +} + +/** + * Represents a transcription response returned by model, based on the provided + * input. + */ +export interface Transcription { + /** + * The transcribed text. + */ + text: string; +} + +export interface TranscriptionCreateParams { + /** + * The audio file object (not file name) to transcribe, in one of these formats: + * flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm. + */ + file: Uploadable; + + /** + * ID of the model to use. Only `whisper-1` (which is powered by our open source + * Whisper V2 model) is currently available. + */ + model: (string & {}) | 'whisper-1'; + + /** + * The language of the input audio. Supplying the input language in + * [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) format will + * improve accuracy and latency. + */ + language?: string; + + /** + * An optional text to guide the model's style or continue a previous audio + * segment. The + * [prompt](https://platform.openai.com/docs/guides/speech-to-text/prompting) + * should match the audio language. + */ + prompt?: string; + + /** + * The format of the transcript output, in one of these options: `json`, `text`, + * `srt`, `verbose_json`, or `vtt`. + */ + response_format?: 'json' | 'text' | 'srt' | 'verbose_json' | 'vtt'; + + /** + * The sampling temperature, between 0 and 1. Higher values like 0.8 will make the + * output more random, while lower values like 0.2 will make it more focused and + * deterministic. If set to 0, the model will use + * [log probability](https://en.wikipedia.org/wiki/Log_probability) to + * automatically increase the temperature until certain thresholds are hit. + */ + temperature?: number; + + /** + * The timestamp granularities to populate for this transcription. + * `response_format` must be set `verbose_json` to use timestamp granularities. + * Either or both of these options are supported: `word`, or `segment`. Note: There + * is no additional latency for segment timestamps, but generating word timestamps + * incurs additional latency. + */ + timestamp_granularities?: Array<'word' | 'segment'>; +} + +export namespace Transcriptions { + export import Transcription = TranscriptionsAPI.Transcription; + export import TranscriptionCreateParams = TranscriptionsAPI.TranscriptionCreateParams; +} diff --git a/backend/node_modules/openai/src/resources/audio/translations.ts b/backend/node_modules/openai/src/resources/audio/translations.ts new file mode 100644 index 0000000000000000000000000000000000000000..53eee913028ce391e0247cbbdcd6533c33d388e8 --- /dev/null +++ b/backend/node_modules/openai/src/resources/audio/translations.ts @@ -0,0 +1,61 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import * as Core from "../../core"; +import { APIResource } from "../../resource"; +import * as TranslationsAPI from "./translations"; +import { type Uploadable, multipartFormRequestOptions } from "../../core"; + +export class Translations extends APIResource { + /** + * Translates audio into English. + */ + create(body: TranslationCreateParams, options?: Core.RequestOptions): Core.APIPromise { + return this._client.post('/audio/translations', multipartFormRequestOptions({ body, ...options })); + } +} + +export interface Translation { + text: string; +} + +export interface TranslationCreateParams { + /** + * The audio file object (not file name) translate, in one of these formats: flac, + * mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm. + */ + file: Uploadable; + + /** + * ID of the model to use. Only `whisper-1` (which is powered by our open source + * Whisper V2 model) is currently available. + */ + model: (string & {}) | 'whisper-1'; + + /** + * An optional text to guide the model's style or continue a previous audio + * segment. The + * [prompt](https://platform.openai.com/docs/guides/speech-to-text/prompting) + * should be in English. + */ + prompt?: string; + + /** + * The format of the transcript output, in one of these options: `json`, `text`, + * `srt`, `verbose_json`, or `vtt`. + */ + response_format?: string; + + /** + * The sampling temperature, between 0 and 1. Higher values like 0.8 will make the + * output more random, while lower values like 0.2 will make it more focused and + * deterministic. If set to 0, the model will use + * [log probability](https://en.wikipedia.org/wiki/Log_probability) to + * automatically increase the temperature until certain thresholds are hit. + */ + temperature?: number; +} + +export namespace Translations { + export import Translation = TranslationsAPI.Translation; + export import TranslationCreateParams = TranslationsAPI.TranslationCreateParams; +} diff --git a/backend/node_modules/openai/src/resources/batches.ts b/backend/node_modules/openai/src/resources/batches.ts new file mode 100644 index 0000000000000000000000000000000000000000..e7d662172ddfb5264baa880da095fd1c1c27ad87 --- /dev/null +++ b/backend/node_modules/openai/src/resources/batches.ts @@ -0,0 +1,225 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import * as Core from "../core"; +import { APIResource } from "../resource"; +import * as BatchesAPI from "./batches"; + +export class Batches extends APIResource { + /** + * Creates and executes a batch from an uploaded file of requests + */ + create(body: BatchCreateParams, options?: Core.RequestOptions): Core.APIPromise { + return this._client.post('/batches', { body, ...options }); + } + + /** + * Retrieves a batch. + */ + retrieve(batchId: string, options?: Core.RequestOptions): Core.APIPromise { + return this._client.get(`/batches/${batchId}`, options); + } + + /** + * Cancels an in-progress batch. + */ + cancel(batchId: string, options?: Core.RequestOptions): Core.APIPromise { + return this._client.post(`/batches/${batchId}/cancel`, options); + } +} + +export interface Batch { + id: string; + + /** + * The time frame within which the batch should be processed. + */ + completion_window: string; + + /** + * The Unix timestamp (in seconds) for when the batch was created. + */ + created_at: string; + + /** + * The OpenAI API endpoint used by the batch. + */ + endpoint: string; + + /** + * The ID of the input file for the batch. + */ + input_file_id: string; + + /** + * The object type, which is always `batch`. + */ + object: 'batch'; + + /** + * The current status of the batch. + */ + status: + | 'validating' + | 'failed' + | 'in_progress' + | 'finalizing' + | 'completed' + | 'expired' + | 'cancelling' + | 'cancelled'; + + /** + * The Unix timestamp (in seconds) for when the batch was cancelled. + */ + cancelled_at?: string; + + /** + * The Unix timestamp (in seconds) for when the batch started cancelling. + */ + cancelling_at?: string; + + /** + * The Unix timestamp (in seconds) for when the batch was completed. + */ + completed_at?: string; + + /** + * The ID of the file containing the outputs of requests with errors. + */ + error_file_id?: string; + + errors?: Batch.Errors; + + /** + * The Unix timestamp (in seconds) for when the batch expired. + */ + expired_at?: string; + + /** + * The Unix timestamp (in seconds) for when the batch will expire. + */ + expires_at?: string; + + /** + * The Unix timestamp (in seconds) for when the batch failed. + */ + failed_at?: string; + + /** + * The Unix timestamp (in seconds) for when the batch started finalizing. + */ + finalizing_at?: string; + + /** + * The Unix timestamp (in seconds) for when the batch started processing. + */ + in_progress_at?: string; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata?: unknown | null; + + /** + * The ID of the file containing the outputs of successfully executed requests. + */ + output_file_id?: string; + + /** + * The request counts for different statuses within the batch. + */ + request_counts?: BatchRequestCounts; +} + +export namespace Batch { + export interface Errors { + data?: Array; + + /** + * The object type, which is always `list`. + */ + object?: string; + } +} + +export interface BatchError { + /** + * An error code identifying the error type. + */ + code?: string; + + /** + * The line number of the input file where the error occurred, if applicable. + */ + line?: number | null; + + /** + * A human-readable message providing more details about the error. + */ + message?: string; + + /** + * The name of the parameter that caused the error, if applicable. + */ + param?: string | null; +} + +/** + * The request counts for different statuses within the batch. + */ +export interface BatchRequestCounts { + /** + * Number of requests that have been completed successfully. + */ + completed: number; + + /** + * Number of requests that have failed. + */ + failed: number; + + /** + * Total number of requests in the batch. + */ + total: number; +} + +export interface BatchCreateParams { + /** + * The time frame within which the batch should be processed. Currently only `24h` + * is supported. + */ + completion_window: '24h'; + + /** + * The endpoint to be used for all requests in the batch. Currently only + * `/v1/chat/completions` is supported. + */ + endpoint: '/v1/chat/completions'; + + /** + * The ID of an uploaded file that contains requests for the new batch. + * + * See [upload file](https://platform.openai.com/docs/api-reference/files/create) + * for how to upload a file. + * + * Your input file must be formatted as a JSONL file, and must be uploaded with the + * purpose `batch`. + */ + input_file_id: string; + + /** + * Optional custom metadata for the batch. + */ + metadata?: Record | null; +} + +export namespace Batches { + export import Batch = BatchesAPI.Batch; + export import BatchError = BatchesAPI.BatchError; + export import BatchRequestCounts = BatchesAPI.BatchRequestCounts; + export import BatchCreateParams = BatchesAPI.BatchCreateParams; +} diff --git a/backend/node_modules/openai/src/resources/beta/assistants/assistants.ts b/backend/node_modules/openai/src/resources/beta/assistants/assistants.ts new file mode 100644 index 0000000000000000000000000000000000000000..cf2d924ba90125d3f261e7b71da99fc409ab92a9 --- /dev/null +++ b/backend/node_modules/openai/src/resources/beta/assistants/assistants.ts @@ -0,0 +1,1080 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import * as Core from "../../../core"; +import { APIResource } from "../../../resource"; +import { isRequestOptions } from "../../../core"; +import * as AssistantsAPI from "./assistants"; +import * as Shared from "../../shared"; +import * as FilesAPI from "./files"; +import * as ThreadsAPI from "../threads/threads"; +import * as MessagesAPI from "../threads/messages/messages"; +import * as RunsAPI from "../threads/runs/runs"; +import * as StepsAPI from "../threads/runs/steps"; +import { CursorPage, type CursorPageParams } from "../../../pagination"; + +export class Assistants extends APIResource { + files: FilesAPI.Files = new FilesAPI.Files(this._client); + + /** + * Create an assistant with a model and instructions. + */ + create(body: AssistantCreateParams, options?: Core.RequestOptions): Core.APIPromise { + return this._client.post('/assistants', { + body, + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } + + /** + * Retrieves an assistant. + */ + retrieve(assistantId: string, options?: Core.RequestOptions): Core.APIPromise { + return this._client.get(`/assistants/${assistantId}`, { + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } + + /** + * Modifies an assistant. + */ + update( + assistantId: string, + body: AssistantUpdateParams, + options?: Core.RequestOptions, + ): Core.APIPromise { + return this._client.post(`/assistants/${assistantId}`, { + body, + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } + + /** + * Returns a list of assistants. + */ + list( + query?: AssistantListParams, + options?: Core.RequestOptions, + ): Core.PagePromise; + list(options?: Core.RequestOptions): Core.PagePromise; + list( + query: AssistantListParams | Core.RequestOptions = {}, + options?: Core.RequestOptions, + ): Core.PagePromise { + if (isRequestOptions(query)) { + return this.list({}, query); + } + return this._client.getAPIList('/assistants', AssistantsPage, { + query, + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } + + /** + * Delete an assistant. + */ + del(assistantId: string, options?: Core.RequestOptions): Core.APIPromise { + return this._client.delete(`/assistants/${assistantId}`, { + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } +} + +export class AssistantsPage extends CursorPage {} + +/** + * Represents an `assistant` that can call the model and use tools. + */ +export interface Assistant { + /** + * The identifier, which can be referenced in API endpoints. + */ + id: string; + + /** + * The Unix timestamp (in seconds) for when the assistant was created. + */ + created_at: number; + + /** + * The description of the assistant. The maximum length is 512 characters. + */ + description: string | null; + + /** + * A list of [file](https://platform.openai.com/docs/api-reference/files) IDs + * attached to this assistant. There can be a maximum of 20 files attached to the + * assistant. Files are ordered by their creation date in ascending order. + */ + file_ids: Array; + + /** + * The system instructions that the assistant uses. The maximum length is 256,000 + * characters. + */ + instructions: string | null; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata: unknown | null; + + /** + * ID of the model to use. You can use the + * [List models](https://platform.openai.com/docs/api-reference/models/list) API to + * see all of your available models, or see our + * [Model overview](https://platform.openai.com/docs/models/overview) for + * descriptions of them. + */ + model: string; + + /** + * The name of the assistant. The maximum length is 256 characters. + */ + name: string | null; + + /** + * The object type, which is always `assistant`. + */ + object: 'assistant'; + + /** + * A list of tool enabled on the assistant. There can be a maximum of 128 tools per + * assistant. Tools can be of types `code_interpreter`, `retrieval`, or `function`. + */ + tools: Array; +} + +export interface AssistantDeleted { + id: string; + + deleted: boolean; + + object: 'assistant.deleted'; +} + +/** + * Represents an event emitted when streaming a Run. + * + * Each event in a server-sent events stream has an `event` and `data` property: + * + * ``` + * event: thread.created + * data: {"id": "thread_123", "object": "thread", ...} + * ``` + * + * We emit events whenever a new object is created, transitions to a new state, or + * is being streamed in parts (deltas). For example, we emit `thread.run.created` + * when a new run is created, `thread.run.completed` when a run completes, and so + * on. When an Assistant chooses to create a message during a run, we emit a + * `thread.message.created event`, a `thread.message.in_progress` event, many + * `thread.message.delta` events, and finally a `thread.message.completed` event. + * + * We may add additional events over time, so we recommend handling unknown events + * gracefully in your code. See the + * [Assistants API quickstart](https://platform.openai.com/docs/assistants/overview) + * to learn how to integrate the Assistants API with streaming. + */ +export type AssistantStreamEvent = + | AssistantStreamEvent.ThreadCreated + | AssistantStreamEvent.ThreadRunCreated + | AssistantStreamEvent.ThreadRunQueued + | AssistantStreamEvent.ThreadRunInProgress + | AssistantStreamEvent.ThreadRunRequiresAction + | AssistantStreamEvent.ThreadRunCompleted + | AssistantStreamEvent.ThreadRunFailed + | AssistantStreamEvent.ThreadRunCancelling + | AssistantStreamEvent.ThreadRunCancelled + | AssistantStreamEvent.ThreadRunExpired + | AssistantStreamEvent.ThreadRunStepCreated + | AssistantStreamEvent.ThreadRunStepInProgress + | AssistantStreamEvent.ThreadRunStepDelta + | AssistantStreamEvent.ThreadRunStepCompleted + | AssistantStreamEvent.ThreadRunStepFailed + | AssistantStreamEvent.ThreadRunStepCancelled + | AssistantStreamEvent.ThreadRunStepExpired + | AssistantStreamEvent.ThreadMessageCreated + | AssistantStreamEvent.ThreadMessageInProgress + | AssistantStreamEvent.ThreadMessageDelta + | AssistantStreamEvent.ThreadMessageCompleted + | AssistantStreamEvent.ThreadMessageIncomplete + | AssistantStreamEvent.ErrorEvent; + +export namespace AssistantStreamEvent { + /** + * Occurs when a new + * [thread](https://platform.openai.com/docs/api-reference/threads/object) is + * created. + */ + export interface ThreadCreated { + /** + * Represents a thread that contains + * [messages](https://platform.openai.com/docs/api-reference/messages). + */ + data: ThreadsAPI.Thread; + + event: 'thread.created'; + } + + /** + * Occurs when a new + * [run](https://platform.openai.com/docs/api-reference/runs/object) is created. + */ + export interface ThreadRunCreated { + /** + * Represents an execution run on a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: RunsAPI.Run; + + event: 'thread.run.created'; + } + + /** + * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) + * moves to a `queued` status. + */ + export interface ThreadRunQueued { + /** + * Represents an execution run on a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: RunsAPI.Run; + + event: 'thread.run.queued'; + } + + /** + * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) + * moves to an `in_progress` status. + */ + export interface ThreadRunInProgress { + /** + * Represents an execution run on a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: RunsAPI.Run; + + event: 'thread.run.in_progress'; + } + + /** + * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) + * moves to a `requires_action` status. + */ + export interface ThreadRunRequiresAction { + /** + * Represents an execution run on a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: RunsAPI.Run; + + event: 'thread.run.requires_action'; + } + + /** + * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) + * is completed. + */ + export interface ThreadRunCompleted { + /** + * Represents an execution run on a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: RunsAPI.Run; + + event: 'thread.run.completed'; + } + + /** + * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) + * fails. + */ + export interface ThreadRunFailed { + /** + * Represents an execution run on a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: RunsAPI.Run; + + event: 'thread.run.failed'; + } + + /** + * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) + * moves to a `cancelling` status. + */ + export interface ThreadRunCancelling { + /** + * Represents an execution run on a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: RunsAPI.Run; + + event: 'thread.run.cancelling'; + } + + /** + * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) + * is cancelled. + */ + export interface ThreadRunCancelled { + /** + * Represents an execution run on a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: RunsAPI.Run; + + event: 'thread.run.cancelled'; + } + + /** + * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) + * expires. + */ + export interface ThreadRunExpired { + /** + * Represents an execution run on a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: RunsAPI.Run; + + event: 'thread.run.expired'; + } + + /** + * Occurs when a + * [run step](https://platform.openai.com/docs/api-reference/runs/step-object) is + * created. + */ + export interface ThreadRunStepCreated { + /** + * Represents a step in execution of a run. + */ + data: StepsAPI.RunStep; + + event: 'thread.run.step.created'; + } + + /** + * Occurs when a + * [run step](https://platform.openai.com/docs/api-reference/runs/step-object) + * moves to an `in_progress` state. + */ + export interface ThreadRunStepInProgress { + /** + * Represents a step in execution of a run. + */ + data: StepsAPI.RunStep; + + event: 'thread.run.step.in_progress'; + } + + /** + * Occurs when parts of a + * [run step](https://platform.openai.com/docs/api-reference/runs/step-object) are + * being streamed. + */ + export interface ThreadRunStepDelta { + /** + * Represents a run step delta i.e. any changed fields on a run step during + * streaming. + */ + data: StepsAPI.RunStepDeltaEvent; + + event: 'thread.run.step.delta'; + } + + /** + * Occurs when a + * [run step](https://platform.openai.com/docs/api-reference/runs/step-object) is + * completed. + */ + export interface ThreadRunStepCompleted { + /** + * Represents a step in execution of a run. + */ + data: StepsAPI.RunStep; + + event: 'thread.run.step.completed'; + } + + /** + * Occurs when a + * [run step](https://platform.openai.com/docs/api-reference/runs/step-object) + * fails. + */ + export interface ThreadRunStepFailed { + /** + * Represents a step in execution of a run. + */ + data: StepsAPI.RunStep; + + event: 'thread.run.step.failed'; + } + + /** + * Occurs when a + * [run step](https://platform.openai.com/docs/api-reference/runs/step-object) is + * cancelled. + */ + export interface ThreadRunStepCancelled { + /** + * Represents a step in execution of a run. + */ + data: StepsAPI.RunStep; + + event: 'thread.run.step.cancelled'; + } + + /** + * Occurs when a + * [run step](https://platform.openai.com/docs/api-reference/runs/step-object) + * expires. + */ + export interface ThreadRunStepExpired { + /** + * Represents a step in execution of a run. + */ + data: StepsAPI.RunStep; + + event: 'thread.run.step.expired'; + } + + /** + * Occurs when a + * [message](https://platform.openai.com/docs/api-reference/messages/object) is + * created. + */ + export interface ThreadMessageCreated { + /** + * Represents a message within a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: MessagesAPI.Message; + + event: 'thread.message.created'; + } + + /** + * Occurs when a + * [message](https://platform.openai.com/docs/api-reference/messages/object) moves + * to an `in_progress` state. + */ + export interface ThreadMessageInProgress { + /** + * Represents a message within a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: MessagesAPI.Message; + + event: 'thread.message.in_progress'; + } + + /** + * Occurs when parts of a + * [Message](https://platform.openai.com/docs/api-reference/messages/object) are + * being streamed. + */ + export interface ThreadMessageDelta { + /** + * Represents a message delta i.e. any changed fields on a message during + * streaming. + */ + data: MessagesAPI.MessageDeltaEvent; + + event: 'thread.message.delta'; + } + + /** + * Occurs when a + * [message](https://platform.openai.com/docs/api-reference/messages/object) is + * completed. + */ + export interface ThreadMessageCompleted { + /** + * Represents a message within a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: MessagesAPI.Message; + + event: 'thread.message.completed'; + } + + /** + * Occurs when a + * [message](https://platform.openai.com/docs/api-reference/messages/object) ends + * before it is completed. + */ + export interface ThreadMessageIncomplete { + /** + * Represents a message within a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: MessagesAPI.Message; + + event: 'thread.message.incomplete'; + } + + /** + * Occurs when an + * [error](https://platform.openai.com/docs/guides/error-codes/api-errors) occurs. + * This can happen due to an internal server error or a timeout. + */ + export interface ErrorEvent { + data: Shared.ErrorObject; + + event: 'error'; + } +} + +export type AssistantTool = CodeInterpreterTool | RetrievalTool | FunctionTool; + +export interface CodeInterpreterTool { + /** + * The type of tool being defined: `code_interpreter` + */ + type: 'code_interpreter'; +} + +export interface FunctionTool { + function: Shared.FunctionDefinition; + + /** + * The type of tool being defined: `function` + */ + type: 'function'; +} + +/** + * Occurs when a + * [message](https://platform.openai.com/docs/api-reference/messages/object) is + * created. + */ +export type MessageStreamEvent = + | MessageStreamEvent.ThreadMessageCreated + | MessageStreamEvent.ThreadMessageInProgress + | MessageStreamEvent.ThreadMessageDelta + | MessageStreamEvent.ThreadMessageCompleted + | MessageStreamEvent.ThreadMessageIncomplete; + +export namespace MessageStreamEvent { + /** + * Occurs when a + * [message](https://platform.openai.com/docs/api-reference/messages/object) is + * created. + */ + export interface ThreadMessageCreated { + /** + * Represents a message within a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: MessagesAPI.Message; + + event: 'thread.message.created'; + } + + /** + * Occurs when a + * [message](https://platform.openai.com/docs/api-reference/messages/object) moves + * to an `in_progress` state. + */ + export interface ThreadMessageInProgress { + /** + * Represents a message within a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: MessagesAPI.Message; + + event: 'thread.message.in_progress'; + } + + /** + * Occurs when parts of a + * [Message](https://platform.openai.com/docs/api-reference/messages/object) are + * being streamed. + */ + export interface ThreadMessageDelta { + /** + * Represents a message delta i.e. any changed fields on a message during + * streaming. + */ + data: MessagesAPI.MessageDeltaEvent; + + event: 'thread.message.delta'; + } + + /** + * Occurs when a + * [message](https://platform.openai.com/docs/api-reference/messages/object) is + * completed. + */ + export interface ThreadMessageCompleted { + /** + * Represents a message within a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: MessagesAPI.Message; + + event: 'thread.message.completed'; + } + + /** + * Occurs when a + * [message](https://platform.openai.com/docs/api-reference/messages/object) ends + * before it is completed. + */ + export interface ThreadMessageIncomplete { + /** + * Represents a message within a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: MessagesAPI.Message; + + event: 'thread.message.incomplete'; + } +} + +export interface RetrievalTool { + /** + * The type of tool being defined: `retrieval` + */ + type: 'retrieval'; +} + +/** + * Occurs when a + * [run step](https://platform.openai.com/docs/api-reference/runs/step-object) is + * created. + */ +export type RunStepStreamEvent = + | RunStepStreamEvent.ThreadRunStepCreated + | RunStepStreamEvent.ThreadRunStepInProgress + | RunStepStreamEvent.ThreadRunStepDelta + | RunStepStreamEvent.ThreadRunStepCompleted + | RunStepStreamEvent.ThreadRunStepFailed + | RunStepStreamEvent.ThreadRunStepCancelled + | RunStepStreamEvent.ThreadRunStepExpired; + +export namespace RunStepStreamEvent { + /** + * Occurs when a + * [run step](https://platform.openai.com/docs/api-reference/runs/step-object) is + * created. + */ + export interface ThreadRunStepCreated { + /** + * Represents a step in execution of a run. + */ + data: StepsAPI.RunStep; + + event: 'thread.run.step.created'; + } + + /** + * Occurs when a + * [run step](https://platform.openai.com/docs/api-reference/runs/step-object) + * moves to an `in_progress` state. + */ + export interface ThreadRunStepInProgress { + /** + * Represents a step in execution of a run. + */ + data: StepsAPI.RunStep; + + event: 'thread.run.step.in_progress'; + } + + /** + * Occurs when parts of a + * [run step](https://platform.openai.com/docs/api-reference/runs/step-object) are + * being streamed. + */ + export interface ThreadRunStepDelta { + /** + * Represents a run step delta i.e. any changed fields on a run step during + * streaming. + */ + data: StepsAPI.RunStepDeltaEvent; + + event: 'thread.run.step.delta'; + } + + /** + * Occurs when a + * [run step](https://platform.openai.com/docs/api-reference/runs/step-object) is + * completed. + */ + export interface ThreadRunStepCompleted { + /** + * Represents a step in execution of a run. + */ + data: StepsAPI.RunStep; + + event: 'thread.run.step.completed'; + } + + /** + * Occurs when a + * [run step](https://platform.openai.com/docs/api-reference/runs/step-object) + * fails. + */ + export interface ThreadRunStepFailed { + /** + * Represents a step in execution of a run. + */ + data: StepsAPI.RunStep; + + event: 'thread.run.step.failed'; + } + + /** + * Occurs when a + * [run step](https://platform.openai.com/docs/api-reference/runs/step-object) is + * cancelled. + */ + export interface ThreadRunStepCancelled { + /** + * Represents a step in execution of a run. + */ + data: StepsAPI.RunStep; + + event: 'thread.run.step.cancelled'; + } + + /** + * Occurs when a + * [run step](https://platform.openai.com/docs/api-reference/runs/step-object) + * expires. + */ + export interface ThreadRunStepExpired { + /** + * Represents a step in execution of a run. + */ + data: StepsAPI.RunStep; + + event: 'thread.run.step.expired'; + } +} + +/** + * Occurs when a new + * [run](https://platform.openai.com/docs/api-reference/runs/object) is created. + */ +export type RunStreamEvent = + | RunStreamEvent.ThreadRunCreated + | RunStreamEvent.ThreadRunQueued + | RunStreamEvent.ThreadRunInProgress + | RunStreamEvent.ThreadRunRequiresAction + | RunStreamEvent.ThreadRunCompleted + | RunStreamEvent.ThreadRunFailed + | RunStreamEvent.ThreadRunCancelling + | RunStreamEvent.ThreadRunCancelled + | RunStreamEvent.ThreadRunExpired; + +export namespace RunStreamEvent { + /** + * Occurs when a new + * [run](https://platform.openai.com/docs/api-reference/runs/object) is created. + */ + export interface ThreadRunCreated { + /** + * Represents an execution run on a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: RunsAPI.Run; + + event: 'thread.run.created'; + } + + /** + * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) + * moves to a `queued` status. + */ + export interface ThreadRunQueued { + /** + * Represents an execution run on a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: RunsAPI.Run; + + event: 'thread.run.queued'; + } + + /** + * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) + * moves to an `in_progress` status. + */ + export interface ThreadRunInProgress { + /** + * Represents an execution run on a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: RunsAPI.Run; + + event: 'thread.run.in_progress'; + } + + /** + * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) + * moves to a `requires_action` status. + */ + export interface ThreadRunRequiresAction { + /** + * Represents an execution run on a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: RunsAPI.Run; + + event: 'thread.run.requires_action'; + } + + /** + * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) + * is completed. + */ + export interface ThreadRunCompleted { + /** + * Represents an execution run on a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: RunsAPI.Run; + + event: 'thread.run.completed'; + } + + /** + * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) + * fails. + */ + export interface ThreadRunFailed { + /** + * Represents an execution run on a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: RunsAPI.Run; + + event: 'thread.run.failed'; + } + + /** + * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) + * moves to a `cancelling` status. + */ + export interface ThreadRunCancelling { + /** + * Represents an execution run on a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: RunsAPI.Run; + + event: 'thread.run.cancelling'; + } + + /** + * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) + * is cancelled. + */ + export interface ThreadRunCancelled { + /** + * Represents an execution run on a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: RunsAPI.Run; + + event: 'thread.run.cancelled'; + } + + /** + * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) + * expires. + */ + export interface ThreadRunExpired { + /** + * Represents an execution run on a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: RunsAPI.Run; + + event: 'thread.run.expired'; + } +} + +/** + * Occurs when a new + * [thread](https://platform.openai.com/docs/api-reference/threads/object) is + * created. + */ +export interface ThreadStreamEvent { + /** + * Represents a thread that contains + * [messages](https://platform.openai.com/docs/api-reference/messages). + */ + data: ThreadsAPI.Thread; + + event: 'thread.created'; +} + +export interface AssistantCreateParams { + /** + * ID of the model to use. You can use the + * [List models](https://platform.openai.com/docs/api-reference/models/list) API to + * see all of your available models, or see our + * [Model overview](https://platform.openai.com/docs/models/overview) for + * descriptions of them. + */ + model: + | (string & {}) + | 'gpt-4-turbo' + | 'gpt-4-turbo-2024-04-09' + | 'gpt-4-0125-preview' + | 'gpt-4-turbo-preview' + | 'gpt-4-1106-preview' + | 'gpt-4-vision-preview' + | 'gpt-4' + | 'gpt-4-0314' + | 'gpt-4-0613' + | 'gpt-4-32k' + | 'gpt-4-32k-0314' + | 'gpt-4-32k-0613' + | 'gpt-3.5-turbo' + | 'gpt-3.5-turbo-16k' + | 'gpt-3.5-turbo-0613' + | 'gpt-3.5-turbo-1106' + | 'gpt-3.5-turbo-0125' + | 'gpt-3.5-turbo-16k-0613'; + + /** + * The description of the assistant. The maximum length is 512 characters. + */ + description?: string | null; + + /** + * A list of [file](https://platform.openai.com/docs/api-reference/files) IDs + * attached to this assistant. There can be a maximum of 20 files attached to the + * assistant. Files are ordered by their creation date in ascending order. + */ + file_ids?: Array; + + /** + * The system instructions that the assistant uses. The maximum length is 256,000 + * characters. + */ + instructions?: string | null; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata?: unknown | null; + + /** + * The name of the assistant. The maximum length is 256 characters. + */ + name?: string | null; + + /** + * A list of tool enabled on the assistant. There can be a maximum of 128 tools per + * assistant. Tools can be of types `code_interpreter`, `retrieval`, or `function`. + */ + tools?: Array; +} + +export interface AssistantUpdateParams { + /** + * The description of the assistant. The maximum length is 512 characters. + */ + description?: string | null; + + /** + * A list of [File](https://platform.openai.com/docs/api-reference/files) IDs + * attached to this assistant. There can be a maximum of 20 files attached to the + * assistant. Files are ordered by their creation date in ascending order. If a + * file was previously attached to the list but does not show up in the list, it + * will be deleted from the assistant. + */ + file_ids?: Array; + + /** + * The system instructions that the assistant uses. The maximum length is 256,000 + * characters. + */ + instructions?: string | null; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata?: unknown | null; + + /** + * ID of the model to use. You can use the + * [List models](https://platform.openai.com/docs/api-reference/models/list) API to + * see all of your available models, or see our + * [Model overview](https://platform.openai.com/docs/models/overview) for + * descriptions of them. + */ + model?: string; + + /** + * The name of the assistant. The maximum length is 256 characters. + */ + name?: string | null; + + /** + * A list of tool enabled on the assistant. There can be a maximum of 128 tools per + * assistant. Tools can be of types `code_interpreter`, `retrieval`, or `function`. + */ + tools?: Array; +} + +export interface AssistantListParams extends CursorPageParams { + /** + * A cursor for use in pagination. `before` is an object ID that defines your place + * in the list. For instance, if you make a list request and receive 100 objects, + * ending with obj_foo, your subsequent call can include before=obj_foo in order to + * fetch the previous page of the list. + */ + before?: string; + + /** + * Sort order by the `created_at` timestamp of the objects. `asc` for ascending + * order and `desc` for descending order. + */ + order?: 'asc' | 'desc'; +} + +export namespace Assistants { + export import Assistant = AssistantsAPI.Assistant; + export import AssistantDeleted = AssistantsAPI.AssistantDeleted; + export import AssistantStreamEvent = AssistantsAPI.AssistantStreamEvent; + export import AssistantTool = AssistantsAPI.AssistantTool; + export import CodeInterpreterTool = AssistantsAPI.CodeInterpreterTool; + export import FunctionTool = AssistantsAPI.FunctionTool; + export import MessageStreamEvent = AssistantsAPI.MessageStreamEvent; + export import RetrievalTool = AssistantsAPI.RetrievalTool; + export import RunStepStreamEvent = AssistantsAPI.RunStepStreamEvent; + export import RunStreamEvent = AssistantsAPI.RunStreamEvent; + export import ThreadStreamEvent = AssistantsAPI.ThreadStreamEvent; + export import AssistantsPage = AssistantsAPI.AssistantsPage; + export import AssistantCreateParams = AssistantsAPI.AssistantCreateParams; + export import AssistantUpdateParams = AssistantsAPI.AssistantUpdateParams; + export import AssistantListParams = AssistantsAPI.AssistantListParams; + export import Files = FilesAPI.Files; + export import AssistantFile = FilesAPI.AssistantFile; + export import FileDeleteResponse = FilesAPI.FileDeleteResponse; + export import AssistantFilesPage = FilesAPI.AssistantFilesPage; + export import FileCreateParams = FilesAPI.FileCreateParams; + export import FileListParams = FilesAPI.FileListParams; +} diff --git a/backend/node_modules/openai/src/resources/beta/assistants/files.ts b/backend/node_modules/openai/src/resources/beta/assistants/files.ts new file mode 100644 index 0000000000000000000000000000000000000000..6838aaf3fba207ee38b5b4cf20f121ceae412b04 --- /dev/null +++ b/backend/node_modules/openai/src/resources/beta/assistants/files.ts @@ -0,0 +1,154 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import * as Core from "../../../core"; +import { APIResource } from "../../../resource"; +import { isRequestOptions } from "../../../core"; +import * as FilesAPI from "./files"; +import { CursorPage, type CursorPageParams } from "../../../pagination"; + +export class Files extends APIResource { + /** + * Create an assistant file by attaching a + * [File](https://platform.openai.com/docs/api-reference/files) to an + * [assistant](https://platform.openai.com/docs/api-reference/assistants). + */ + create( + assistantId: string, + body: FileCreateParams, + options?: Core.RequestOptions, + ): Core.APIPromise { + return this._client.post(`/assistants/${assistantId}/files`, { + body, + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } + + /** + * Retrieves an AssistantFile. + */ + retrieve( + assistantId: string, + fileId: string, + options?: Core.RequestOptions, + ): Core.APIPromise { + return this._client.get(`/assistants/${assistantId}/files/${fileId}`, { + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } + + /** + * Returns a list of assistant files. + */ + list( + assistantId: string, + query?: FileListParams, + options?: Core.RequestOptions, + ): Core.PagePromise; + list( + assistantId: string, + options?: Core.RequestOptions, + ): Core.PagePromise; + list( + assistantId: string, + query: FileListParams | Core.RequestOptions = {}, + options?: Core.RequestOptions, + ): Core.PagePromise { + if (isRequestOptions(query)) { + return this.list(assistantId, {}, query); + } + return this._client.getAPIList(`/assistants/${assistantId}/files`, AssistantFilesPage, { + query, + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } + + /** + * Delete an assistant file. + */ + del( + assistantId: string, + fileId: string, + options?: Core.RequestOptions, + ): Core.APIPromise { + return this._client.delete(`/assistants/${assistantId}/files/${fileId}`, { + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } +} + +export class AssistantFilesPage extends CursorPage {} + +/** + * A list of [Files](https://platform.openai.com/docs/api-reference/files) attached + * to an `assistant`. + */ +export interface AssistantFile { + /** + * The identifier, which can be referenced in API endpoints. + */ + id: string; + + /** + * The assistant ID that the file is attached to. + */ + assistant_id: string; + + /** + * The Unix timestamp (in seconds) for when the assistant file was created. + */ + created_at: number; + + /** + * The object type, which is always `assistant.file`. + */ + object: 'assistant.file'; +} + +/** + * Deletes the association between the assistant and the file, but does not delete + * the [File](https://platform.openai.com/docs/api-reference/files) object itself. + */ +export interface FileDeleteResponse { + id: string; + + deleted: boolean; + + object: 'assistant.file.deleted'; +} + +export interface FileCreateParams { + /** + * A [File](https://platform.openai.com/docs/api-reference/files) ID (with + * `purpose="assistants"`) that the assistant should use. Useful for tools like + * `retrieval` and `code_interpreter` that can access files. + */ + file_id: string; +} + +export interface FileListParams extends CursorPageParams { + /** + * A cursor for use in pagination. `before` is an object ID that defines your place + * in the list. For instance, if you make a list request and receive 100 objects, + * ending with obj_foo, your subsequent call can include before=obj_foo in order to + * fetch the previous page of the list. + */ + before?: string; + + /** + * Sort order by the `created_at` timestamp of the objects. `asc` for ascending + * order and `desc` for descending order. + */ + order?: 'asc' | 'desc'; +} + +export namespace Files { + export import AssistantFile = FilesAPI.AssistantFile; + export import FileDeleteResponse = FilesAPI.FileDeleteResponse; + export import AssistantFilesPage = FilesAPI.AssistantFilesPage; + export import FileCreateParams = FilesAPI.FileCreateParams; + export import FileListParams = FilesAPI.FileListParams; +} diff --git a/backend/node_modules/openai/src/resources/beta/assistants/index.ts b/backend/node_modules/openai/src/resources/beta/assistants/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..c191d338b30109084bad834243e2dbbfffdaf264 --- /dev/null +++ b/backend/node_modules/openai/src/resources/beta/assistants/index.ts @@ -0,0 +1,28 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export { + Assistant, + AssistantDeleted, + AssistantStreamEvent, + AssistantTool, + CodeInterpreterTool, + FunctionTool, + MessageStreamEvent, + RetrievalTool, + RunStepStreamEvent, + RunStreamEvent, + ThreadStreamEvent, + AssistantCreateParams, + AssistantUpdateParams, + AssistantListParams, + AssistantsPage, + Assistants, +} from './assistants'; +export { + AssistantFile, + FileDeleteResponse, + FileCreateParams, + FileListParams, + AssistantFilesPage, + Files, +} from './files'; diff --git a/backend/node_modules/openai/src/resources/beta/beta.ts b/backend/node_modules/openai/src/resources/beta/beta.ts new file mode 100644 index 0000000000000000000000000000000000000000..80c5764a33702058edbed0dd3ad0bc54205bee78 --- /dev/null +++ b/backend/node_modules/openai/src/resources/beta/beta.ts @@ -0,0 +1,47 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { APIResource } from "../../resource"; +import * as AssistantsAPI from "./assistants/assistants"; +import * as ChatAPI from "./chat/chat"; +import * as ThreadsAPI from "./threads/threads"; + +export class Beta extends APIResource { + chat: ChatAPI.Chat = new ChatAPI.Chat(this._client); + assistants: AssistantsAPI.Assistants = new AssistantsAPI.Assistants(this._client); + threads: ThreadsAPI.Threads = new ThreadsAPI.Threads(this._client); +} + +export namespace Beta { + export import Chat = ChatAPI.Chat; + export import Assistants = AssistantsAPI.Assistants; + export import Assistant = AssistantsAPI.Assistant; + export import AssistantDeleted = AssistantsAPI.AssistantDeleted; + export import AssistantStreamEvent = AssistantsAPI.AssistantStreamEvent; + export import AssistantTool = AssistantsAPI.AssistantTool; + export import CodeInterpreterTool = AssistantsAPI.CodeInterpreterTool; + export import FunctionTool = AssistantsAPI.FunctionTool; + export import MessageStreamEvent = AssistantsAPI.MessageStreamEvent; + export import RetrievalTool = AssistantsAPI.RetrievalTool; + export import RunStepStreamEvent = AssistantsAPI.RunStepStreamEvent; + export import RunStreamEvent = AssistantsAPI.RunStreamEvent; + export import ThreadStreamEvent = AssistantsAPI.ThreadStreamEvent; + export import AssistantsPage = AssistantsAPI.AssistantsPage; + export import AssistantCreateParams = AssistantsAPI.AssistantCreateParams; + export import AssistantUpdateParams = AssistantsAPI.AssistantUpdateParams; + export import AssistantListParams = AssistantsAPI.AssistantListParams; + export import Threads = ThreadsAPI.Threads; + export import AssistantResponseFormat = ThreadsAPI.AssistantResponseFormat; + export import AssistantResponseFormatOption = ThreadsAPI.AssistantResponseFormatOption; + export import AssistantToolChoice = ThreadsAPI.AssistantToolChoice; + export import AssistantToolChoiceFunction = ThreadsAPI.AssistantToolChoiceFunction; + export import AssistantToolChoiceOption = ThreadsAPI.AssistantToolChoiceOption; + export import Thread = ThreadsAPI.Thread; + export import ThreadDeleted = ThreadsAPI.ThreadDeleted; + export import ThreadCreateParams = ThreadsAPI.ThreadCreateParams; + export import ThreadUpdateParams = ThreadsAPI.ThreadUpdateParams; + export import ThreadCreateAndRunParams = ThreadsAPI.ThreadCreateAndRunParams; + export import ThreadCreateAndRunParamsNonStreaming = ThreadsAPI.ThreadCreateAndRunParamsNonStreaming; + export import ThreadCreateAndRunParamsStreaming = ThreadsAPI.ThreadCreateAndRunParamsStreaming; + export import ThreadCreateAndRunPollParams = ThreadsAPI.ThreadCreateAndRunPollParams; + export import ThreadCreateAndRunStreamParams = ThreadsAPI.ThreadCreateAndRunStreamParams; +} diff --git a/backend/node_modules/openai/src/resources/beta/chat/chat.ts b/backend/node_modules/openai/src/resources/beta/chat/chat.ts new file mode 100644 index 0000000000000000000000000000000000000000..991393880823ec2ad74ecf461151d74468a62a07 --- /dev/null +++ b/backend/node_modules/openai/src/resources/beta/chat/chat.ts @@ -0,0 +1,12 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { APIResource } from "../../../resource"; +import * as CompletionsAPI from "./completions"; + +export class Chat extends APIResource { + completions: CompletionsAPI.Completions = new CompletionsAPI.Completions(this._client); +} + +export namespace Chat { + export import Completions = CompletionsAPI.Completions; +} diff --git a/backend/node_modules/openai/src/resources/beta/chat/completions.ts b/backend/node_modules/openai/src/resources/beta/chat/completions.ts new file mode 100644 index 0000000000000000000000000000000000000000..8523c3b5704443b3fced5d04c21b828fd5b5f77f --- /dev/null +++ b/backend/node_modules/openai/src/resources/beta/chat/completions.ts @@ -0,0 +1,106 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import * as Core from "../../../core"; +import { APIResource } from "../../../resource"; +import { ChatCompletionRunner, ChatCompletionFunctionRunnerParams } from "../../../lib/ChatCompletionRunner"; +export { ChatCompletionRunner, ChatCompletionFunctionRunnerParams } from "../../../lib/ChatCompletionRunner"; +import { + ChatCompletionStreamingRunner, + ChatCompletionStreamingFunctionRunnerParams, +} from "../../../lib/ChatCompletionStreamingRunner"; +export { + ChatCompletionStreamingRunner, + ChatCompletionStreamingFunctionRunnerParams, +} from "../../../lib/ChatCompletionStreamingRunner"; +import { BaseFunctionsArgs } from "../../../lib/RunnableFunction"; +export { + RunnableFunction, + RunnableFunctions, + RunnableFunctionWithParse, + RunnableFunctionWithoutParse, + ParsingFunction, + ParsingToolFunction, +} from "../../../lib/RunnableFunction"; +import { ChatCompletionToolRunnerParams } from "../../../lib/ChatCompletionRunner"; +export { ChatCompletionToolRunnerParams } from "../../../lib/ChatCompletionRunner"; +import { ChatCompletionStreamingToolRunnerParams } from "../../../lib/ChatCompletionStreamingRunner"; +export { ChatCompletionStreamingToolRunnerParams } from "../../../lib/ChatCompletionStreamingRunner"; +import { ChatCompletionStream, type ChatCompletionStreamParams } from "../../../lib/ChatCompletionStream"; +export { ChatCompletionStream, type ChatCompletionStreamParams } from "../../../lib/ChatCompletionStream"; + +export class Completions extends APIResource { + /** + * @deprecated - use `runTools` instead. + */ + runFunctions( + body: ChatCompletionFunctionRunnerParams, + options?: Core.RequestOptions, + ): ChatCompletionRunner; + runFunctions( + body: ChatCompletionStreamingFunctionRunnerParams, + options?: Core.RequestOptions, + ): ChatCompletionStreamingRunner; + runFunctions( + body: + | ChatCompletionFunctionRunnerParams + | ChatCompletionStreamingFunctionRunnerParams, + options?: Core.RequestOptions, + ): ChatCompletionRunner | ChatCompletionStreamingRunner { + if (body.stream) { + return ChatCompletionStreamingRunner.runFunctions( + this._client.chat.completions, + body as ChatCompletionStreamingFunctionRunnerParams, + options, + ); + } + return ChatCompletionRunner.runFunctions( + this._client.chat.completions, + body as ChatCompletionFunctionRunnerParams, + options, + ); + } + + /** + * A convenience helper for using tool calls with the /chat/completions endpoint + * which automatically calls the JavaScript functions you provide and sends their + * results back to the /chat/completions endpoint, looping as long as the model + * requests function calls. + * + * For more details and examples, see + * [the docs](https://github.com/openai/openai-node#automated-function-calls) + */ + runTools( + body: ChatCompletionToolRunnerParams, + options?: Core.RequestOptions, + ): ChatCompletionRunner; + runTools( + body: ChatCompletionStreamingToolRunnerParams, + options?: Core.RequestOptions, + ): ChatCompletionStreamingRunner; + runTools( + body: + | ChatCompletionToolRunnerParams + | ChatCompletionStreamingToolRunnerParams, + options?: Core.RequestOptions, + ): ChatCompletionRunner | ChatCompletionStreamingRunner { + if (body.stream) { + return ChatCompletionStreamingRunner.runTools( + this._client.chat.completions, + body as ChatCompletionStreamingToolRunnerParams, + options, + ); + } + return ChatCompletionRunner.runTools( + this._client.chat.completions, + body as ChatCompletionToolRunnerParams, + options, + ); + } + + /** + * Creates a chat completion stream + */ + stream(body: ChatCompletionStreamParams, options?: Core.RequestOptions): ChatCompletionStream { + return ChatCompletionStream.createChatCompletion(this._client.chat.completions, body, options); + } +} diff --git a/backend/node_modules/openai/src/resources/beta/chat/index.ts b/backend/node_modules/openai/src/resources/beta/chat/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..23b1b8ff3fb43b117ec37c029c0ca2cdf35f10cc --- /dev/null +++ b/backend/node_modules/openai/src/resources/beta/chat/index.ts @@ -0,0 +1,4 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export { Chat } from './chat'; +export { Completions } from './completions'; diff --git a/backend/node_modules/openai/src/resources/beta/index.ts b/backend/node_modules/openai/src/resources/beta/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..54407edb30116b80f211e94d3834522dc9be7f94 --- /dev/null +++ b/backend/node_modules/openai/src/resources/beta/index.ts @@ -0,0 +1,39 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export { + Assistant, + AssistantDeleted, + AssistantStreamEvent, + AssistantTool, + CodeInterpreterTool, + FunctionTool, + MessageStreamEvent, + RetrievalTool, + RunStepStreamEvent, + RunStreamEvent, + ThreadStreamEvent, + AssistantCreateParams, + AssistantUpdateParams, + AssistantListParams, + AssistantsPage, + Assistants, +} from './assistants/index'; +export { + AssistantResponseFormat, + AssistantResponseFormatOption, + AssistantToolChoice, + AssistantToolChoiceFunction, + AssistantToolChoiceOption, + Thread, + ThreadDeleted, + ThreadCreateParams, + ThreadUpdateParams, + ThreadCreateAndRunParams, + ThreadCreateAndRunParamsNonStreaming, + ThreadCreateAndRunParamsStreaming, + ThreadCreateAndRunPollParams, + ThreadCreateAndRunStreamParams, + Threads, +} from './threads/index'; +export { Beta } from './beta'; +export { Chat } from './chat/index'; diff --git a/backend/node_modules/openai/src/resources/beta/threads/index.ts b/backend/node_modules/openai/src/resources/beta/threads/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..5f41766a92220740cd3459f4923565bc8dbfaf11 --- /dev/null +++ b/backend/node_modules/openai/src/resources/beta/threads/index.ts @@ -0,0 +1,66 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export { + Annotation, + AnnotationDelta, + FileCitationAnnotation, + FileCitationDeltaAnnotation, + FilePathAnnotation, + FilePathDeltaAnnotation, + ImageFile, + ImageFileContentBlock, + ImageFileDelta, + ImageFileDeltaBlock, + Message, + MessageContent, + MessageContentDelta, + MessageDeleted, + MessageDelta, + MessageDeltaEvent, + Text, + TextContentBlock, + TextDelta, + TextDeltaBlock, + MessageCreateParams, + MessageUpdateParams, + MessageListParams, + MessagesPage, + Messages, +} from './messages/index'; +export { + AssistantResponseFormat, + AssistantResponseFormatOption, + AssistantToolChoice, + AssistantToolChoiceFunction, + AssistantToolChoiceOption, + Thread, + ThreadDeleted, + ThreadCreateParams, + ThreadUpdateParams, + ThreadCreateAndRunParams, + ThreadCreateAndRunParamsNonStreaming, + ThreadCreateAndRunParamsStreaming, + ThreadCreateAndRunPollParams, + ThreadCreateAndRunStreamParams, + Threads, +} from './threads'; +export { + RequiredActionFunctionToolCall, + Run, + RunStatus, + RunCreateParams, + RunCreateParamsNonStreaming, + RunCreateParamsStreaming, + RunUpdateParams, + RunListParams, + RunCreateAndPollParams, + RunCreateAndStreamParams, + RunStreamParams, + RunSubmitToolOutputsParams, + RunSubmitToolOutputsParamsNonStreaming, + RunSubmitToolOutputsParamsStreaming, + RunSubmitToolOutputsAndPollParams, + RunSubmitToolOutputsStreamParams, + RunsPage, + Runs, +} from './runs/index'; diff --git a/backend/node_modules/openai/src/resources/beta/threads/messages/files.ts b/backend/node_modules/openai/src/resources/beta/threads/messages/files.ts new file mode 100644 index 0000000000000000000000000000000000000000..87fe1164e9bd96a5024daeec9f5d81de20690b06 --- /dev/null +++ b/backend/node_modules/openai/src/resources/beta/threads/messages/files.ts @@ -0,0 +1,105 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import * as Core from "../../../../core"; +import { APIResource } from "../../../../resource"; +import { isRequestOptions } from "../../../../core"; +import * as FilesAPI from "./files"; +import { CursorPage, type CursorPageParams } from "../../../../pagination"; + +export class Files extends APIResource { + /** + * Retrieves a message file. + */ + retrieve( + threadId: string, + messageId: string, + fileId: string, + options?: Core.RequestOptions, + ): Core.APIPromise { + return this._client.get(`/threads/${threadId}/messages/${messageId}/files/${fileId}`, { + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } + + /** + * Returns a list of message files. + */ + list( + threadId: string, + messageId: string, + query?: FileListParams, + options?: Core.RequestOptions, + ): Core.PagePromise; + list( + threadId: string, + messageId: string, + options?: Core.RequestOptions, + ): Core.PagePromise; + list( + threadId: string, + messageId: string, + query: FileListParams | Core.RequestOptions = {}, + options?: Core.RequestOptions, + ): Core.PagePromise { + if (isRequestOptions(query)) { + return this.list(threadId, messageId, {}, query); + } + return this._client.getAPIList(`/threads/${threadId}/messages/${messageId}/files`, MessageFilesPage, { + query, + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } +} + +export class MessageFilesPage extends CursorPage {} + +/** + * A list of files attached to a `message`. + */ +export interface MessageFile { + /** + * The identifier, which can be referenced in API endpoints. + */ + id: string; + + /** + * The Unix timestamp (in seconds) for when the message file was created. + */ + created_at: number; + + /** + * The ID of the [message](https://platform.openai.com/docs/api-reference/messages) + * that the [File](https://platform.openai.com/docs/api-reference/files) is + * attached to. + */ + message_id: string; + + /** + * The object type, which is always `thread.message.file`. + */ + object: 'thread.message.file'; +} + +export interface FileListParams extends CursorPageParams { + /** + * A cursor for use in pagination. `before` is an object ID that defines your place + * in the list. For instance, if you make a list request and receive 100 objects, + * ending with obj_foo, your subsequent call can include before=obj_foo in order to + * fetch the previous page of the list. + */ + before?: string; + + /** + * Sort order by the `created_at` timestamp of the objects. `asc` for ascending + * order and `desc` for descending order. + */ + order?: 'asc' | 'desc'; +} + +export namespace Files { + export import MessageFile = FilesAPI.MessageFile; + export import MessageFilesPage = FilesAPI.MessageFilesPage; + export import FileListParams = FilesAPI.FileListParams; +} diff --git a/backend/node_modules/openai/src/resources/beta/threads/messages/index.ts b/backend/node_modules/openai/src/resources/beta/threads/messages/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..ef446d012353c9d08fc9b58a1b828ffbd07660dd --- /dev/null +++ b/backend/node_modules/openai/src/resources/beta/threads/messages/index.ts @@ -0,0 +1,30 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export { + Annotation, + AnnotationDelta, + FileCitationAnnotation, + FileCitationDeltaAnnotation, + FilePathAnnotation, + FilePathDeltaAnnotation, + ImageFile, + ImageFileContentBlock, + ImageFileDelta, + ImageFileDeltaBlock, + Message, + MessageContent, + MessageContentDelta, + MessageDeleted, + MessageDelta, + MessageDeltaEvent, + Text, + TextContentBlock, + TextDelta, + TextDeltaBlock, + MessageCreateParams, + MessageUpdateParams, + MessageListParams, + MessagesPage, + Messages, +} from './messages'; +export { MessageFile, FileListParams, MessageFilesPage, Files } from './files'; diff --git a/backend/node_modules/openai/src/resources/beta/threads/messages/messages.ts b/backend/node_modules/openai/src/resources/beta/threads/messages/messages.ts new file mode 100644 index 0000000000000000000000000000000000000000..619b2c5bcbc83e17c5823f57d8ad5e0034f87c57 --- /dev/null +++ b/backend/node_modules/openai/src/resources/beta/threads/messages/messages.ts @@ -0,0 +1,590 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import * as Core from "../../../../core"; +import { APIResource } from "../../../../resource"; +import { isRequestOptions } from "../../../../core"; +import * as MessagesAPI from "./messages"; +import * as FilesAPI from "./files"; +import { CursorPage, type CursorPageParams } from "../../../../pagination"; + +export class Messages extends APIResource { + files: FilesAPI.Files = new FilesAPI.Files(this._client); + + /** + * Create a message. + */ + create( + threadId: string, + body: MessageCreateParams, + options?: Core.RequestOptions, + ): Core.APIPromise { + return this._client.post(`/threads/${threadId}/messages`, { + body, + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } + + /** + * Retrieve a message. + */ + retrieve(threadId: string, messageId: string, options?: Core.RequestOptions): Core.APIPromise { + return this._client.get(`/threads/${threadId}/messages/${messageId}`, { + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } + + /** + * Modifies a message. + */ + update( + threadId: string, + messageId: string, + body: MessageUpdateParams, + options?: Core.RequestOptions, + ): Core.APIPromise { + return this._client.post(`/threads/${threadId}/messages/${messageId}`, { + body, + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } + + /** + * Returns a list of messages for a given thread. + */ + list( + threadId: string, + query?: MessageListParams, + options?: Core.RequestOptions, + ): Core.PagePromise; + list(threadId: string, options?: Core.RequestOptions): Core.PagePromise; + list( + threadId: string, + query: MessageListParams | Core.RequestOptions = {}, + options?: Core.RequestOptions, + ): Core.PagePromise { + if (isRequestOptions(query)) { + return this.list(threadId, {}, query); + } + return this._client.getAPIList(`/threads/${threadId}/messages`, MessagesPage, { + query, + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } +} + +export class MessagesPage extends CursorPage {} + +/** + * A citation within the message that points to a specific quote from a specific + * File associated with the assistant or the message. Generated when the assistant + * uses the "retrieval" tool to search files. + */ +export type Annotation = FileCitationAnnotation | FilePathAnnotation; + +/** + * A citation within the message that points to a specific quote from a specific + * File associated with the assistant or the message. Generated when the assistant + * uses the "retrieval" tool to search files. + */ +export type AnnotationDelta = FileCitationDeltaAnnotation | FilePathDeltaAnnotation; + +/** + * A citation within the message that points to a specific quote from a specific + * File associated with the assistant or the message. Generated when the assistant + * uses the "retrieval" tool to search files. + */ +export interface FileCitationAnnotation { + end_index: number; + + file_citation: FileCitationAnnotation.FileCitation; + + start_index: number; + + /** + * The text in the message content that needs to be replaced. + */ + text: string; + + /** + * Always `file_citation`. + */ + type: 'file_citation'; +} + +export namespace FileCitationAnnotation { + export interface FileCitation { + /** + * The ID of the specific File the citation is from. + */ + file_id: string; + + /** + * The specific quote in the file. + */ + quote: string; + } +} + +/** + * A citation within the message that points to a specific quote from a specific + * File associated with the assistant or the message. Generated when the assistant + * uses the "retrieval" tool to search files. + */ +export interface FileCitationDeltaAnnotation { + /** + * The index of the annotation in the text content part. + */ + index: number; + + /** + * Always `file_citation`. + */ + type: 'file_citation'; + + end_index?: number; + + file_citation?: FileCitationDeltaAnnotation.FileCitation; + + start_index?: number; + + /** + * The text in the message content that needs to be replaced. + */ + text?: string; +} + +export namespace FileCitationDeltaAnnotation { + export interface FileCitation { + /** + * The ID of the specific File the citation is from. + */ + file_id?: string; + + /** + * The specific quote in the file. + */ + quote?: string; + } +} + +/** + * A URL for the file that's generated when the assistant used the + * `code_interpreter` tool to generate a file. + */ +export interface FilePathAnnotation { + end_index: number; + + file_path: FilePathAnnotation.FilePath; + + start_index: number; + + /** + * The text in the message content that needs to be replaced. + */ + text: string; + + /** + * Always `file_path`. + */ + type: 'file_path'; +} + +export namespace FilePathAnnotation { + export interface FilePath { + /** + * The ID of the file that was generated. + */ + file_id: string; + } +} + +/** + * A URL for the file that's generated when the assistant used the + * `code_interpreter` tool to generate a file. + */ +export interface FilePathDeltaAnnotation { + /** + * The index of the annotation in the text content part. + */ + index: number; + + /** + * Always `file_path`. + */ + type: 'file_path'; + + end_index?: number; + + file_path?: FilePathDeltaAnnotation.FilePath; + + start_index?: number; + + /** + * The text in the message content that needs to be replaced. + */ + text?: string; +} + +export namespace FilePathDeltaAnnotation { + export interface FilePath { + /** + * The ID of the file that was generated. + */ + file_id?: string; + } +} + +export interface ImageFile { + /** + * The [File](https://platform.openai.com/docs/api-reference/files) ID of the image + * in the message content. + */ + file_id: string; +} + +/** + * References an image [File](https://platform.openai.com/docs/api-reference/files) + * in the content of a message. + */ +export interface ImageFileContentBlock { + image_file: ImageFile; + + /** + * Always `image_file`. + */ + type: 'image_file'; +} + +export interface ImageFileDelta { + /** + * The [File](https://platform.openai.com/docs/api-reference/files) ID of the image + * in the message content. + */ + file_id?: string; +} + +/** + * References an image [File](https://platform.openai.com/docs/api-reference/files) + * in the content of a message. + */ +export interface ImageFileDeltaBlock { + /** + * The index of the content part in the message. + */ + index: number; + + /** + * Always `image_file`. + */ + type: 'image_file'; + + image_file?: ImageFileDelta; +} + +/** + * Represents a message within a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ +export interface Message { + /** + * The identifier, which can be referenced in API endpoints. + */ + id: string; + + /** + * If applicable, the ID of the + * [assistant](https://platform.openai.com/docs/api-reference/assistants) that + * authored this message. + */ + assistant_id: string | null; + + /** + * The Unix timestamp (in seconds) for when the message was completed. + */ + completed_at: number | null; + + /** + * The content of the message in array of text and/or images. + */ + content: Array; + + /** + * The Unix timestamp (in seconds) for when the message was created. + */ + created_at: number; + + /** + * A list of [file](https://platform.openai.com/docs/api-reference/files) IDs that + * the assistant should use. Useful for tools like retrieval and code_interpreter + * that can access files. A maximum of 10 files can be attached to a message. + */ + file_ids: Array; + + /** + * The Unix timestamp (in seconds) for when the message was marked as incomplete. + */ + incomplete_at: number | null; + + /** + * On an incomplete message, details about why the message is incomplete. + */ + incomplete_details: Message.IncompleteDetails | null; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata: unknown | null; + + /** + * The object type, which is always `thread.message`. + */ + object: 'thread.message'; + + /** + * The entity that produced the message. One of `user` or `assistant`. + */ + role: 'user' | 'assistant'; + + /** + * The ID of the [run](https://platform.openai.com/docs/api-reference/runs) + * associated with the creation of this message. Value is `null` when messages are + * created manually using the create message or create thread endpoints. + */ + run_id: string | null; + + /** + * The status of the message, which can be either `in_progress`, `incomplete`, or + * `completed`. + */ + status: 'in_progress' | 'incomplete' | 'completed'; + + /** + * The [thread](https://platform.openai.com/docs/api-reference/threads) ID that + * this message belongs to. + */ + thread_id: string; +} + +export namespace Message { + /** + * On an incomplete message, details about why the message is incomplete. + */ + export interface IncompleteDetails { + /** + * The reason the message is incomplete. + */ + reason: 'content_filter' | 'max_tokens' | 'run_cancelled' | 'run_expired' | 'run_failed'; + } +} + +/** + * References an image [File](https://platform.openai.com/docs/api-reference/files) + * in the content of a message. + */ +export type MessageContent = ImageFileContentBlock | TextContentBlock; + +/** + * References an image [File](https://platform.openai.com/docs/api-reference/files) + * in the content of a message. + */ +export type MessageContentDelta = ImageFileDeltaBlock | TextDeltaBlock; + +export interface MessageDeleted { + id: string; + + deleted: boolean; + + object: 'thread.message.deleted'; +} + +/** + * The delta containing the fields that have changed on the Message. + */ +export interface MessageDelta { + /** + * The content of the message in array of text and/or images. + */ + content?: Array; + + /** + * A list of [file](https://platform.openai.com/docs/api-reference/files) IDs that + * the assistant should use. Useful for tools like retrieval and code_interpreter + * that can access files. A maximum of 10 files can be attached to a message. + */ + file_ids?: Array; + + /** + * The entity that produced the message. One of `user` or `assistant`. + */ + role?: 'user' | 'assistant'; +} + +/** + * Represents a message delta i.e. any changed fields on a message during + * streaming. + */ +export interface MessageDeltaEvent { + /** + * The identifier of the message, which can be referenced in API endpoints. + */ + id: string; + + /** + * The delta containing the fields that have changed on the Message. + */ + delta: MessageDelta; + + /** + * The object type, which is always `thread.message.delta`. + */ + object: 'thread.message.delta'; +} + +export interface Text { + annotations: Array; + + /** + * The data that makes up the text. + */ + value: string; +} + +/** + * The text content that is part of a message. + */ +export interface TextContentBlock { + text: Text; + + /** + * Always `text`. + */ + type: 'text'; +} + +export interface TextDelta { + annotations?: Array; + + /** + * The data that makes up the text. + */ + value?: string; +} + +/** + * The text content that is part of a message. + */ +export interface TextDeltaBlock { + /** + * The index of the content part in the message. + */ + index: number; + + /** + * Always `text`. + */ + type: 'text'; + + text?: TextDelta; +} + +export interface MessageCreateParams { + /** + * The content of the message. + */ + content: string; + + /** + * The role of the entity that is creating the message. Allowed values include: + * + * - `user`: Indicates the message is sent by an actual user and should be used in + * most cases to represent user-generated messages. + * - `assistant`: Indicates the message is generated by the assistant. Use this + * value to insert messages from the assistant into the conversation. + */ + role: 'user' | 'assistant'; + + /** + * A list of [File](https://platform.openai.com/docs/api-reference/files) IDs that + * the message should use. There can be a maximum of 10 files attached to a + * message. Useful for tools like `retrieval` and `code_interpreter` that can + * access and use files. + */ + file_ids?: Array; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata?: unknown | null; +} + +export interface MessageUpdateParams { + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata?: unknown | null; +} + +export interface MessageListParams extends CursorPageParams { + /** + * A cursor for use in pagination. `before` is an object ID that defines your place + * in the list. For instance, if you make a list request and receive 100 objects, + * ending with obj_foo, your subsequent call can include before=obj_foo in order to + * fetch the previous page of the list. + */ + before?: string; + + /** + * Sort order by the `created_at` timestamp of the objects. `asc` for ascending + * order and `desc` for descending order. + */ + order?: 'asc' | 'desc'; + + /** + * Filter messages by the run ID that generated them. + */ + run_id?: string; +} + +export namespace Messages { + export import Annotation = MessagesAPI.Annotation; + export import AnnotationDelta = MessagesAPI.AnnotationDelta; + export import FileCitationAnnotation = MessagesAPI.FileCitationAnnotation; + export import FileCitationDeltaAnnotation = MessagesAPI.FileCitationDeltaAnnotation; + export import FilePathAnnotation = MessagesAPI.FilePathAnnotation; + export import FilePathDeltaAnnotation = MessagesAPI.FilePathDeltaAnnotation; + export import ImageFile = MessagesAPI.ImageFile; + export import ImageFileContentBlock = MessagesAPI.ImageFileContentBlock; + export import ImageFileDelta = MessagesAPI.ImageFileDelta; + export import ImageFileDeltaBlock = MessagesAPI.ImageFileDeltaBlock; + export import Message = MessagesAPI.Message; + export import MessageContent = MessagesAPI.MessageContent; + export import MessageContentDelta = MessagesAPI.MessageContentDelta; + export import MessageDeleted = MessagesAPI.MessageDeleted; + export import MessageDelta = MessagesAPI.MessageDelta; + export import MessageDeltaEvent = MessagesAPI.MessageDeltaEvent; + export import Text = MessagesAPI.Text; + export import TextContentBlock = MessagesAPI.TextContentBlock; + export import TextDelta = MessagesAPI.TextDelta; + export import TextDeltaBlock = MessagesAPI.TextDeltaBlock; + export import MessagesPage = MessagesAPI.MessagesPage; + export import MessageCreateParams = MessagesAPI.MessageCreateParams; + export import MessageUpdateParams = MessagesAPI.MessageUpdateParams; + export import MessageListParams = MessagesAPI.MessageListParams; + export import Files = FilesAPI.Files; + export import MessageFile = FilesAPI.MessageFile; + export import MessageFilesPage = FilesAPI.MessageFilesPage; + export import FileListParams = FilesAPI.FileListParams; +} diff --git a/backend/node_modules/openai/src/resources/beta/threads/runs/index.ts b/backend/node_modules/openai/src/resources/beta/threads/runs/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..c9b2d1ef5616fe17a88d89333b19a679d3256927 --- /dev/null +++ b/backend/node_modules/openai/src/resources/beta/threads/runs/index.ts @@ -0,0 +1,44 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export { + CodeInterpreterLogs, + CodeInterpreterOutputImage, + CodeInterpreterToolCall, + CodeInterpreterToolCallDelta, + FunctionToolCall, + FunctionToolCallDelta, + MessageCreationStepDetails, + RetrievalToolCall, + RetrievalToolCallDelta, + RunStep, + RunStepDelta, + RunStepDeltaEvent, + RunStepDeltaMessageDelta, + ToolCall, + ToolCallDelta, + ToolCallDeltaObject, + ToolCallsStepDetails, + StepListParams, + RunStepsPage, + Steps, +} from './steps'; +export { + RequiredActionFunctionToolCall, + Run, + RunStatus, + RunCreateParams, + RunCreateParamsNonStreaming, + RunCreateParamsStreaming, + RunUpdateParams, + RunListParams, + RunCreateAndPollParams, + RunCreateAndStreamParams, + RunStreamParams, + RunSubmitToolOutputsParams, + RunSubmitToolOutputsParamsNonStreaming, + RunSubmitToolOutputsParamsStreaming, + RunSubmitToolOutputsAndPollParams, + RunSubmitToolOutputsStreamParams, + RunsPage, + Runs, +} from './runs'; diff --git a/backend/node_modules/openai/src/resources/beta/threads/runs/runs.ts b/backend/node_modules/openai/src/resources/beta/threads/runs/runs.ts new file mode 100644 index 0000000000000000000000000000000000000000..d7a0d262dc0bdddf884497111c3cb700b811224f --- /dev/null +++ b/backend/node_modules/openai/src/resources/beta/threads/runs/runs.ts @@ -0,0 +1,1488 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import * as Core from "../../../../core"; +import { APIPromise } from "../../../../core"; +import { APIResource } from "../../../../resource"; +import { isRequestOptions } from "../../../../core"; +import { AssistantStream, RunCreateParamsBaseStream } from "../../../../lib/AssistantStream"; +import { sleep } from "../../../../core"; +import { RunSubmitToolOutputsParamsStream } from "../../../../lib/AssistantStream"; +import * as RunsAPI from "./runs"; +import * as AssistantsAPI from "../../assistants/assistants"; +import * as ThreadsAPI from "../threads"; +import * as StepsAPI from "./steps"; +import { CursorPage, type CursorPageParams } from "../../../../pagination"; +import { Stream } from "../../../../streaming"; + +export class Runs extends APIResource { + steps: StepsAPI.Steps = new StepsAPI.Steps(this._client); + + /** + * Create a run. + */ + create(threadId: string, body: RunCreateParamsNonStreaming, options?: Core.RequestOptions): APIPromise; + create( + threadId: string, + body: RunCreateParamsStreaming, + options?: Core.RequestOptions, + ): APIPromise>; + create( + threadId: string, + body: RunCreateParamsBase, + options?: Core.RequestOptions, + ): APIPromise | Run>; + create( + threadId: string, + body: RunCreateParams, + options?: Core.RequestOptions, + ): APIPromise | APIPromise> { + return this._client.post(`/threads/${threadId}/runs`, { + body, + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + stream: body.stream ?? false, + }) as APIPromise | APIPromise>; + } + + /** + * Retrieves a run. + */ + retrieve(threadId: string, runId: string, options?: Core.RequestOptions): Core.APIPromise { + return this._client.get(`/threads/${threadId}/runs/${runId}`, { + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } + + /** + * Modifies a run. + */ + update( + threadId: string, + runId: string, + body: RunUpdateParams, + options?: Core.RequestOptions, + ): Core.APIPromise { + return this._client.post(`/threads/${threadId}/runs/${runId}`, { + body, + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } + + /** + * Returns a list of runs belonging to a thread. + */ + list( + threadId: string, + query?: RunListParams, + options?: Core.RequestOptions, + ): Core.PagePromise; + list(threadId: string, options?: Core.RequestOptions): Core.PagePromise; + list( + threadId: string, + query: RunListParams | Core.RequestOptions = {}, + options?: Core.RequestOptions, + ): Core.PagePromise { + if (isRequestOptions(query)) { + return this.list(threadId, {}, query); + } + return this._client.getAPIList(`/threads/${threadId}/runs`, RunsPage, { + query, + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } + + /** + * Cancels a run that is `in_progress`. + */ + cancel(threadId: string, runId: string, options?: Core.RequestOptions): Core.APIPromise { + return this._client.post(`/threads/${threadId}/runs/${runId}/cancel`, { + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } + + /** + * A helper to create a run an poll for a terminal state. More information on Run + * lifecycles can be found here: + * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps + */ + async createAndPoll( + threadId: string, + body: RunCreateParamsNonStreaming, + options?: Core.RequestOptions & { pollIntervalMs?: number }, + ): Promise { + const run = await this.create(threadId, body, options); + return await this.poll(threadId, run.id, options); + } + + /** + * Create a Run stream + * + * @deprecated use `stream` instead + */ + createAndStream( + threadId: string, + body: RunCreateParamsBaseStream, + options?: Core.RequestOptions, + ): AssistantStream { + return AssistantStream.createAssistantStream(threadId, this._client.beta.threads.runs, body, options); + } + + /** + * A helper to poll a run status until it reaches a terminal state. More + * information on Run lifecycles can be found here: + * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps + */ + async poll( + threadId: string, + runId: string, + options?: Core.RequestOptions & { pollIntervalMs?: number }, + ): Promise { + const headers: { [key: string]: string } = { ...options?.headers, 'X-Stainless-Poll-Helper': 'true' }; + + if (options?.pollIntervalMs) { + headers['X-Stainless-Custom-Poll-Interval'] = options.pollIntervalMs.toString(); + } + + while (true) { + const { data: run, response } = await this.retrieve(threadId, runId, { + ...options, + headers: { ...options?.headers, ...headers }, + }).withResponse(); + + switch (run.status) { + //If we are in any sort of intermediate state we poll + case 'queued': + case 'in_progress': + case 'cancelling': + let sleepInterval = 5000; + + if (options?.pollIntervalMs) { + sleepInterval = options.pollIntervalMs; + } else { + const headerInterval = response.headers.get('openai-poll-after-ms'); + if (headerInterval) { + const headerIntervalMs = parseInt(headerInterval); + if (!isNaN(headerIntervalMs)) { + sleepInterval = headerIntervalMs; + } + } + } + await sleep(sleepInterval); + break; + //We return the run in any terminal state. + case 'requires_action': + case 'cancelled': + case 'completed': + case 'failed': + case 'expired': + return run; + } + } + } + + /** + * Create a Run stream + */ + stream(threadId: string, body: RunCreateParamsBaseStream, options?: Core.RequestOptions): AssistantStream { + return AssistantStream.createAssistantStream(threadId, this._client.beta.threads.runs, body, options); + } + + /** + * When a run has the `status: "requires_action"` and `required_action.type` is + * `submit_tool_outputs`, this endpoint can be used to submit the outputs from the + * tool calls once they're all completed. All outputs must be submitted in a single + * request. + */ + submitToolOutputs( + threadId: string, + runId: string, + body: RunSubmitToolOutputsParamsNonStreaming, + options?: Core.RequestOptions, + ): APIPromise; + submitToolOutputs( + threadId: string, + runId: string, + body: RunSubmitToolOutputsParamsStreaming, + options?: Core.RequestOptions, + ): APIPromise>; + submitToolOutputs( + threadId: string, + runId: string, + body: RunSubmitToolOutputsParamsBase, + options?: Core.RequestOptions, + ): APIPromise | Run>; + submitToolOutputs( + threadId: string, + runId: string, + body: RunSubmitToolOutputsParams, + options?: Core.RequestOptions, + ): APIPromise | APIPromise> { + return this._client.post(`/threads/${threadId}/runs/${runId}/submit_tool_outputs`, { + body, + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + stream: body.stream ?? false, + }) as APIPromise | APIPromise>; + } + + /** + * A helper to submit a tool output to a run and poll for a terminal run state. + * More information on Run lifecycles can be found here: + * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps + */ + async submitToolOutputsAndPoll( + threadId: string, + runId: string, + body: RunSubmitToolOutputsParamsNonStreaming, + options?: Core.RequestOptions & { pollIntervalMs?: number }, + ): Promise { + const run = await this.submitToolOutputs(threadId, runId, body, options); + return await this.poll(threadId, run.id, options); + } + + /** + * Submit the tool outputs from a previous run and stream the run to a terminal + * state. More information on Run lifecycles can be found here: + * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps + */ + submitToolOutputsStream( + threadId: string, + runId: string, + body: RunSubmitToolOutputsParamsStream, + options?: Core.RequestOptions, + ): AssistantStream { + return AssistantStream.createToolAssistantStream( + threadId, + runId, + this._client.beta.threads.runs, + body, + options, + ); + } +} + +export class RunsPage extends CursorPage {} + +/** + * Tool call objects + */ +export interface RequiredActionFunctionToolCall { + /** + * The ID of the tool call. This ID must be referenced when you submit the tool + * outputs in using the + * [Submit tool outputs to run](https://platform.openai.com/docs/api-reference/runs/submitToolOutputs) + * endpoint. + */ + id: string; + + /** + * The function definition. + */ + function: RequiredActionFunctionToolCall.Function; + + /** + * The type of tool call the output is required for. For now, this is always + * `function`. + */ + type: 'function'; +} + +export namespace RequiredActionFunctionToolCall { + /** + * The function definition. + */ + export interface Function { + /** + * The arguments that the model expects you to pass to the function. + */ + arguments: string; + + /** + * The name of the function. + */ + name: string; + } +} + +/** + * Represents an execution run on a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ +export interface Run { + /** + * The identifier, which can be referenced in API endpoints. + */ + id: string; + + /** + * The ID of the + * [assistant](https://platform.openai.com/docs/api-reference/assistants) used for + * execution of this run. + */ + assistant_id: string; + + /** + * The Unix timestamp (in seconds) for when the run was cancelled. + */ + cancelled_at: number | null; + + /** + * The Unix timestamp (in seconds) for when the run was completed. + */ + completed_at: number | null; + + /** + * The Unix timestamp (in seconds) for when the run was created. + */ + created_at: number; + + /** + * The Unix timestamp (in seconds) for when the run will expire. + */ + expires_at: number | null; + + /** + * The Unix timestamp (in seconds) for when the run failed. + */ + failed_at: number | null; + + /** + * The list of [File](https://platform.openai.com/docs/api-reference/files) IDs the + * [assistant](https://platform.openai.com/docs/api-reference/assistants) used for + * this run. + */ + file_ids: Array; + + /** + * Details on why the run is incomplete. Will be `null` if the run is not + * incomplete. + */ + incomplete_details: Run.IncompleteDetails | null; + + /** + * The instructions that the + * [assistant](https://platform.openai.com/docs/api-reference/assistants) used for + * this run. + */ + instructions: string; + + /** + * The last error associated with this run. Will be `null` if there are no errors. + */ + last_error: Run.LastError | null; + + /** + * The maximum number of completion tokens specified to have been used over the + * course of the run. + */ + max_completion_tokens: number | null; + + /** + * The maximum number of prompt tokens specified to have been used over the course + * of the run. + */ + max_prompt_tokens: number | null; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata: unknown | null; + + /** + * The model that the + * [assistant](https://platform.openai.com/docs/api-reference/assistants) used for + * this run. + */ + model: string; + + /** + * The object type, which is always `thread.run`. + */ + object: 'thread.run'; + + /** + * Details on the action required to continue the run. Will be `null` if no action + * is required. + */ + required_action: Run.RequiredAction | null; + + /** + * Specifies the format that the model must output. Compatible with + * [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and + * all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + * + * Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + * message the model generates is valid JSON. + * + * **Important:** when using JSON mode, you **must** also instruct the model to + * produce JSON yourself via a system or user message. Without this, the model may + * generate an unending stream of whitespace until the generation reaches the token + * limit, resulting in a long-running and seemingly "stuck" request. Also note that + * the message content may be partially cut off if `finish_reason="length"`, which + * indicates the generation exceeded `max_tokens` or the conversation exceeded the + * max context length. + */ + response_format: ThreadsAPI.AssistantResponseFormatOption | null; + + /** + * The Unix timestamp (in seconds) for when the run was started. + */ + started_at: number | null; + + /** + * The status of the run, which can be either `queued`, `in_progress`, + * `requires_action`, `cancelling`, `cancelled`, `failed`, `completed`, or + * `expired`. + */ + status: RunStatus; + + /** + * The ID of the [thread](https://platform.openai.com/docs/api-reference/threads) + * that was executed on as a part of this run. + */ + thread_id: string; + + /** + * Controls which (if any) tool is called by the model. `none` means the model will + * not call any tools and instead generates a message. `auto` is the default value + * and means the model can pick between generating a message or calling a tool. + * Specifying a particular tool like `{"type": "TOOL_TYPE"}` or + * `{"type": "function", "function": {"name": "my_function"}}` forces the model to + * call that tool. + */ + tool_choice: ThreadsAPI.AssistantToolChoiceOption | null; + + /** + * The list of tools that the + * [assistant](https://platform.openai.com/docs/api-reference/assistants) used for + * this run. + */ + tools: Array; + + truncation_strategy: Run.TruncationStrategy | null; + + /** + * Usage statistics related to the run. This value will be `null` if the run is not + * in a terminal state (i.e. `in_progress`, `queued`, etc.). + */ + usage: Run.Usage | null; + + /** + * The sampling temperature used for this run. If not set, defaults to 1. + */ + temperature?: number | null; +} + +export namespace Run { + /** + * Details on why the run is incomplete. Will be `null` if the run is not + * incomplete. + */ + export interface IncompleteDetails { + /** + * The reason why the run is incomplete. This will point to which specific token + * limit was reached over the course of the run. + */ + reason?: 'max_completion_tokens' | 'max_prompt_tokens'; + } + + /** + * The last error associated with this run. Will be `null` if there are no errors. + */ + export interface LastError { + /** + * One of `server_error`, `rate_limit_exceeded`, or `invalid_prompt`. + */ + code: 'server_error' | 'rate_limit_exceeded' | 'invalid_prompt'; + + /** + * A human-readable description of the error. + */ + message: string; + } + + /** + * Details on the action required to continue the run. Will be `null` if no action + * is required. + */ + export interface RequiredAction { + /** + * Details on the tool outputs needed for this run to continue. + */ + submit_tool_outputs: RequiredAction.SubmitToolOutputs; + + /** + * For now, this is always `submit_tool_outputs`. + */ + type: 'submit_tool_outputs'; + } + + export namespace RequiredAction { + /** + * Details on the tool outputs needed for this run to continue. + */ + export interface SubmitToolOutputs { + /** + * A list of the relevant tool calls. + */ + tool_calls: Array; + } + } + + export interface TruncationStrategy { + /** + * The truncation strategy to use for the thread. The default is `auto`. If set to + * `last_messages`, the thread will be truncated to the n most recent messages in + * the thread. When set to `auto`, messages in the middle of the thread will be + * dropped to fit the context length of the model, `max_prompt_tokens`. + */ + type: 'auto' | 'last_messages'; + + /** + * The number of most recent messages from the thread when constructing the context + * for the run. + */ + last_messages?: number | null; + } + + /** + * Usage statistics related to the run. This value will be `null` if the run is not + * in a terminal state (i.e. `in_progress`, `queued`, etc.). + */ + export interface Usage { + /** + * Number of completion tokens used over the course of the run. + */ + completion_tokens: number; + + /** + * Number of prompt tokens used over the course of the run. + */ + prompt_tokens: number; + + /** + * Total number of tokens used (prompt + completion). + */ + total_tokens: number; + } +} + +/** + * The status of the run, which can be either `queued`, `in_progress`, + * `requires_action`, `cancelling`, `cancelled`, `failed`, `completed`, or + * `expired`. + */ +export type RunStatus = + | 'queued' + | 'in_progress' + | 'requires_action' + | 'cancelling' + | 'cancelled' + | 'failed' + | 'completed' + | 'expired'; + +export type RunCreateParams = RunCreateParamsNonStreaming | RunCreateParamsStreaming; + +export interface RunCreateParamsBase { + /** + * The ID of the + * [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to + * execute this run. + */ + assistant_id: string; + + /** + * Appends additional instructions at the end of the instructions for the run. This + * is useful for modifying the behavior on a per-run basis without overriding other + * instructions. + */ + additional_instructions?: string | null; + + /** + * Adds additional messages to the thread before creating the run. + */ + additional_messages?: Array | null; + + /** + * Overrides the + * [instructions](https://platform.openai.com/docs/api-reference/assistants/createAssistant) + * of the assistant. This is useful for modifying the behavior on a per-run basis. + */ + instructions?: string | null; + + /** + * The maximum number of completion tokens that may be used over the course of the + * run. The run will make a best effort to use only the number of completion tokens + * specified, across multiple turns of the run. If the run exceeds the number of + * completion tokens specified, the run will end with status `complete`. See + * `incomplete_details` for more info. + */ + max_completion_tokens?: number | null; + + /** + * The maximum number of prompt tokens that may be used over the course of the run. + * The run will make a best effort to use only the number of prompt tokens + * specified, across multiple turns of the run. If the run exceeds the number of + * prompt tokens specified, the run will end with status `complete`. See + * `incomplete_details` for more info. + */ + max_prompt_tokens?: number | null; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata?: unknown | null; + + /** + * The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to + * be used to execute this run. If a value is provided here, it will override the + * model associated with the assistant. If not, the model associated with the + * assistant will be used. + */ + model?: + | (string & {}) + | 'gpt-4-turbo' + | 'gpt-4-turbo-2024-04-09' + | 'gpt-4-0125-preview' + | 'gpt-4-turbo-preview' + | 'gpt-4-1106-preview' + | 'gpt-4-vision-preview' + | 'gpt-4' + | 'gpt-4-0314' + | 'gpt-4-0613' + | 'gpt-4-32k' + | 'gpt-4-32k-0314' + | 'gpt-4-32k-0613' + | 'gpt-3.5-turbo' + | 'gpt-3.5-turbo-16k' + | 'gpt-3.5-turbo-0613' + | 'gpt-3.5-turbo-1106' + | 'gpt-3.5-turbo-0125' + | 'gpt-3.5-turbo-16k-0613' + | null; + + /** + * Specifies the format that the model must output. Compatible with + * [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and + * all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + * + * Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + * message the model generates is valid JSON. + * + * **Important:** when using JSON mode, you **must** also instruct the model to + * produce JSON yourself via a system or user message. Without this, the model may + * generate an unending stream of whitespace until the generation reaches the token + * limit, resulting in a long-running and seemingly "stuck" request. Also note that + * the message content may be partially cut off if `finish_reason="length"`, which + * indicates the generation exceeded `max_tokens` or the conversation exceeded the + * max context length. + */ + response_format?: ThreadsAPI.AssistantResponseFormatOption | null; + + /** + * If `true`, returns a stream of events that happen during the Run as server-sent + * events, terminating when the Run enters a terminal state with a `data: [DONE]` + * message. + */ + stream?: boolean | null; + + /** + * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + * make the output more random, while lower values like 0.2 will make it more + * focused and deterministic. + */ + temperature?: number | null; + + /** + * Controls which (if any) tool is called by the model. `none` means the model will + * not call any tools and instead generates a message. `auto` is the default value + * and means the model can pick between generating a message or calling a tool. + * Specifying a particular tool like `{"type": "TOOL_TYPE"}` or + * `{"type": "function", "function": {"name": "my_function"}}` forces the model to + * call that tool. + */ + tool_choice?: ThreadsAPI.AssistantToolChoiceOption | null; + + /** + * Override the tools the assistant can use for this run. This is useful for + * modifying the behavior on a per-run basis. + */ + tools?: Array | null; + + truncation_strategy?: RunCreateParams.TruncationStrategy | null; +} + +export namespace RunCreateParams { + export interface AdditionalMessage { + /** + * The content of the message. + */ + content: string; + + /** + * The role of the entity that is creating the message. Allowed values include: + * + * - `user`: Indicates the message is sent by an actual user and should be used in + * most cases to represent user-generated messages. + * - `assistant`: Indicates the message is generated by the assistant. Use this + * value to insert messages from the assistant into the conversation. + */ + role: 'user' | 'assistant'; + + /** + * A list of [File](https://platform.openai.com/docs/api-reference/files) IDs that + * the message should use. There can be a maximum of 10 files attached to a + * message. Useful for tools like `retrieval` and `code_interpreter` that can + * access and use files. + */ + file_ids?: Array; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata?: unknown | null; + } + + export interface TruncationStrategy { + /** + * The truncation strategy to use for the thread. The default is `auto`. If set to + * `last_messages`, the thread will be truncated to the n most recent messages in + * the thread. When set to `auto`, messages in the middle of the thread will be + * dropped to fit the context length of the model, `max_prompt_tokens`. + */ + type: 'auto' | 'last_messages'; + + /** + * The number of most recent messages from the thread when constructing the context + * for the run. + */ + last_messages?: number | null; + } + + export type RunCreateParamsNonStreaming = RunsAPI.RunCreateParamsNonStreaming; + export type RunCreateParamsStreaming = RunsAPI.RunCreateParamsStreaming; +} + +export interface RunCreateParamsNonStreaming extends RunCreateParamsBase { + /** + * If `true`, returns a stream of events that happen during the Run as server-sent + * events, terminating when the Run enters a terminal state with a `data: [DONE]` + * message. + */ + stream?: false | null; +} + +export interface RunCreateParamsStreaming extends RunCreateParamsBase { + /** + * If `true`, returns a stream of events that happen during the Run as server-sent + * events, terminating when the Run enters a terminal state with a `data: [DONE]` + * message. + */ + stream: true; +} + +export interface RunUpdateParams { + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata?: unknown | null; +} + +export interface RunListParams extends CursorPageParams { + /** + * A cursor for use in pagination. `before` is an object ID that defines your place + * in the list. For instance, if you make a list request and receive 100 objects, + * ending with obj_foo, your subsequent call can include before=obj_foo in order to + * fetch the previous page of the list. + */ + before?: string; + + /** + * Sort order by the `created_at` timestamp of the objects. `asc` for ascending + * order and `desc` for descending order. + */ + order?: 'asc' | 'desc'; +} + +export interface RunCreateAndPollParams { + /** + * The ID of the + * [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to + * execute this run. + */ + assistant_id: string; + + /** + * Appends additional instructions at the end of the instructions for the run. This + * is useful for modifying the behavior on a per-run basis without overriding other + * instructions. + */ + additional_instructions?: string | null; + + /** + * Adds additional messages to the thread before creating the run. + */ + additional_messages?: Array | null; + + /** + * Overrides the + * [instructions](https://platform.openai.com/docs/api-reference/assistants/createAssistant) + * of the assistant. This is useful for modifying the behavior on a per-run basis. + */ + instructions?: string | null; + + /** + * The maximum number of completion tokens that may be used over the course of the + * run. The run will make a best effort to use only the number of completion tokens + * specified, across multiple turns of the run. If the run exceeds the number of + * completion tokens specified, the run will end with status `complete`. See + * `incomplete_details` for more info. + */ + max_completion_tokens?: number | null; + + /** + * The maximum number of prompt tokens that may be used over the course of the run. + * The run will make a best effort to use only the number of prompt tokens + * specified, across multiple turns of the run. If the run exceeds the number of + * prompt tokens specified, the run will end with status `complete`. See + * `incomplete_details` for more info. + */ + max_prompt_tokens?: number | null; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata?: unknown | null; + + /** + * The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to + * be used to execute this run. If a value is provided here, it will override the + * model associated with the assistant. If not, the model associated with the + * assistant will be used. + */ + model?: + | (string & {}) + | 'gpt-4-turbo' + | 'gpt-4-turbo-2024-04-09' + | 'gpt-4-0125-preview' + | 'gpt-4-turbo-preview' + | 'gpt-4-1106-preview' + | 'gpt-4-vision-preview' + | 'gpt-4' + | 'gpt-4-0314' + | 'gpt-4-0613' + | 'gpt-4-32k' + | 'gpt-4-32k-0314' + | 'gpt-4-32k-0613' + | 'gpt-3.5-turbo' + | 'gpt-3.5-turbo-16k' + | 'gpt-3.5-turbo-0613' + | 'gpt-3.5-turbo-1106' + | 'gpt-3.5-turbo-0125' + | 'gpt-3.5-turbo-16k-0613' + | null; + + /** + * Specifies the format that the model must output. Compatible with + * [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and + * all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + * + * Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + * message the model generates is valid JSON. + * + * **Important:** when using JSON mode, you **must** also instruct the model to + * produce JSON yourself via a system or user message. Without this, the model may + * generate an unending stream of whitespace until the generation reaches the token + * limit, resulting in a long-running and seemingly "stuck" request. Also note that + * the message content may be partially cut off if `finish_reason="length"`, which + * indicates the generation exceeded `max_tokens` or the conversation exceeded the + * max context length. + */ + response_format?: ThreadsAPI.AssistantResponseFormatOption | null; + + /** + * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + * make the output more random, while lower values like 0.2 will make it more + * focused and deterministic. + */ + temperature?: number | null; + + /** + * Controls which (if any) tool is called by the model. `none` means the model will + * not call any tools and instead generates a message. `auto` is the default value + * and means the model can pick between generating a message or calling a tool. + * Specifying a particular tool like `{"type": "TOOL_TYPE"}` or + * `{"type": "function", "function": {"name": "my_function"}}` forces the model to + * call that tool. + */ + tool_choice?: ThreadsAPI.AssistantToolChoiceOption | null; + + /** + * Override the tools the assistant can use for this run. This is useful for + * modifying the behavior on a per-run basis. + */ + tools?: Array | null; + + truncation_strategy?: RunCreateAndPollParams.TruncationStrategy | null; +} + +export namespace RunCreateAndPollParams { + export interface AdditionalMessage { + /** + * The content of the message. + */ + content: string; + + /** + * The role of the entity that is creating the message. Allowed values include: + * + * - `user`: Indicates the message is sent by an actual user and should be used in + * most cases to represent user-generated messages. + * - `assistant`: Indicates the message is generated by the assistant. Use this + * value to insert messages from the assistant into the conversation. + */ + role: 'user' | 'assistant'; + + /** + * A list of [File](https://platform.openai.com/docs/api-reference/files) IDs that + * the message should use. There can be a maximum of 10 files attached to a + * message. Useful for tools like `retrieval` and `code_interpreter` that can + * access and use files. + */ + file_ids?: Array; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata?: unknown | null; + } + + export interface TruncationStrategy { + /** + * The truncation strategy to use for the thread. The default is `auto`. If set to + * `last_messages`, the thread will be truncated to the n most recent messages in + * the thread. When set to `auto`, messages in the middle of the thread will be + * dropped to fit the context length of the model, `max_prompt_tokens`. + */ + type: 'auto' | 'last_messages'; + + /** + * The number of most recent messages from the thread when constructing the context + * for the run. + */ + last_messages?: number | null; + } +} + +export interface RunCreateAndStreamParams { + /** + * The ID of the + * [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to + * execute this run. + */ + assistant_id: string; + + /** + * Appends additional instructions at the end of the instructions for the run. This + * is useful for modifying the behavior on a per-run basis without overriding other + * instructions. + */ + additional_instructions?: string | null; + + /** + * Adds additional messages to the thread before creating the run. + */ + additional_messages?: Array | null; + + /** + * Overrides the + * [instructions](https://platform.openai.com/docs/api-reference/assistants/createAssistant) + * of the assistant. This is useful for modifying the behavior on a per-run basis. + */ + instructions?: string | null; + + /** + * The maximum number of completion tokens that may be used over the course of the + * run. The run will make a best effort to use only the number of completion tokens + * specified, across multiple turns of the run. If the run exceeds the number of + * completion tokens specified, the run will end with status `complete`. See + * `incomplete_details` for more info. + */ + max_completion_tokens?: number | null; + + /** + * The maximum number of prompt tokens that may be used over the course of the run. + * The run will make a best effort to use only the number of prompt tokens + * specified, across multiple turns of the run. If the run exceeds the number of + * prompt tokens specified, the run will end with status `complete`. See + * `incomplete_details` for more info. + */ + max_prompt_tokens?: number | null; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata?: unknown | null; + + /** + * The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to + * be used to execute this run. If a value is provided here, it will override the + * model associated with the assistant. If not, the model associated with the + * assistant will be used. + */ + model?: + | (string & {}) + | 'gpt-4-turbo' + | 'gpt-4-turbo-2024-04-09' + | 'gpt-4-0125-preview' + | 'gpt-4-turbo-preview' + | 'gpt-4-1106-preview' + | 'gpt-4-vision-preview' + | 'gpt-4' + | 'gpt-4-0314' + | 'gpt-4-0613' + | 'gpt-4-32k' + | 'gpt-4-32k-0314' + | 'gpt-4-32k-0613' + | 'gpt-3.5-turbo' + | 'gpt-3.5-turbo-16k' + | 'gpt-3.5-turbo-0613' + | 'gpt-3.5-turbo-1106' + | 'gpt-3.5-turbo-0125' + | 'gpt-3.5-turbo-16k-0613' + | null; + + /** + * Specifies the format that the model must output. Compatible with + * [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and + * all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + * + * Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + * message the model generates is valid JSON. + * + * **Important:** when using JSON mode, you **must** also instruct the model to + * produce JSON yourself via a system or user message. Without this, the model may + * generate an unending stream of whitespace until the generation reaches the token + * limit, resulting in a long-running and seemingly "stuck" request. Also note that + * the message content may be partially cut off if `finish_reason="length"`, which + * indicates the generation exceeded `max_tokens` or the conversation exceeded the + * max context length. + */ + response_format?: ThreadsAPI.AssistantResponseFormatOption | null; + + /** + * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + * make the output more random, while lower values like 0.2 will make it more + * focused and deterministic. + */ + temperature?: number | null; + + /** + * Controls which (if any) tool is called by the model. `none` means the model will + * not call any tools and instead generates a message. `auto` is the default value + * and means the model can pick between generating a message or calling a tool. + * Specifying a particular tool like `{"type": "TOOL_TYPE"}` or + * `{"type": "function", "function": {"name": "my_function"}}` forces the model to + * call that tool. + */ + tool_choice?: ThreadsAPI.AssistantToolChoiceOption | null; + + /** + * Override the tools the assistant can use for this run. This is useful for + * modifying the behavior on a per-run basis. + */ + tools?: Array | null; + + truncation_strategy?: RunCreateAndStreamParams.TruncationStrategy | null; +} + +export namespace RunCreateAndStreamParams { + export interface AdditionalMessage { + /** + * The content of the message. + */ + content: string; + + /** + * The role of the entity that is creating the message. Allowed values include: + * + * - `user`: Indicates the message is sent by an actual user and should be used in + * most cases to represent user-generated messages. + * - `assistant`: Indicates the message is generated by the assistant. Use this + * value to insert messages from the assistant into the conversation. + */ + role: 'user' | 'assistant'; + + /** + * A list of [File](https://platform.openai.com/docs/api-reference/files) IDs that + * the message should use. There can be a maximum of 10 files attached to a + * message. Useful for tools like `retrieval` and `code_interpreter` that can + * access and use files. + */ + file_ids?: Array; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata?: unknown | null; + } + + export interface TruncationStrategy { + /** + * The truncation strategy to use for the thread. The default is `auto`. If set to + * `last_messages`, the thread will be truncated to the n most recent messages in + * the thread. When set to `auto`, messages in the middle of the thread will be + * dropped to fit the context length of the model, `max_prompt_tokens`. + */ + type: 'auto' | 'last_messages'; + + /** + * The number of most recent messages from the thread when constructing the context + * for the run. + */ + last_messages?: number | null; + } +} + +export interface RunStreamParams { + /** + * The ID of the + * [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to + * execute this run. + */ + assistant_id: string; + + /** + * Appends additional instructions at the end of the instructions for the run. This + * is useful for modifying the behavior on a per-run basis without overriding other + * instructions. + */ + additional_instructions?: string | null; + + /** + * Adds additional messages to the thread before creating the run. + */ + additional_messages?: Array | null; + + /** + * Overrides the + * [instructions](https://platform.openai.com/docs/api-reference/assistants/createAssistant) + * of the assistant. This is useful for modifying the behavior on a per-run basis. + */ + instructions?: string | null; + + /** + * The maximum number of completion tokens that may be used over the course of the + * run. The run will make a best effort to use only the number of completion tokens + * specified, across multiple turns of the run. If the run exceeds the number of + * completion tokens specified, the run will end with status `complete`. See + * `incomplete_details` for more info. + */ + max_completion_tokens?: number | null; + + /** + * The maximum number of prompt tokens that may be used over the course of the run. + * The run will make a best effort to use only the number of prompt tokens + * specified, across multiple turns of the run. If the run exceeds the number of + * prompt tokens specified, the run will end with status `complete`. See + * `incomplete_details` for more info. + */ + max_prompt_tokens?: number | null; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata?: unknown | null; + + /** + * The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to + * be used to execute this run. If a value is provided here, it will override the + * model associated with the assistant. If not, the model associated with the + * assistant will be used. + */ + model?: + | (string & {}) + | 'gpt-4-turbo' + | 'gpt-4-turbo-2024-04-09' + | 'gpt-4-0125-preview' + | 'gpt-4-turbo-preview' + | 'gpt-4-1106-preview' + | 'gpt-4-vision-preview' + | 'gpt-4' + | 'gpt-4-0314' + | 'gpt-4-0613' + | 'gpt-4-32k' + | 'gpt-4-32k-0314' + | 'gpt-4-32k-0613' + | 'gpt-3.5-turbo' + | 'gpt-3.5-turbo-16k' + | 'gpt-3.5-turbo-0613' + | 'gpt-3.5-turbo-1106' + | 'gpt-3.5-turbo-0125' + | 'gpt-3.5-turbo-16k-0613' + | null; + + /** + * Specifies the format that the model must output. Compatible with + * [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and + * all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + * + * Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + * message the model generates is valid JSON. + * + * **Important:** when using JSON mode, you **must** also instruct the model to + * produce JSON yourself via a system or user message. Without this, the model may + * generate an unending stream of whitespace until the generation reaches the token + * limit, resulting in a long-running and seemingly "stuck" request. Also note that + * the message content may be partially cut off if `finish_reason="length"`, which + * indicates the generation exceeded `max_tokens` or the conversation exceeded the + * max context length. + */ + response_format?: ThreadsAPI.AssistantResponseFormatOption | null; + + /** + * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + * make the output more random, while lower values like 0.2 will make it more + * focused and deterministic. + */ + temperature?: number | null; + + /** + * Controls which (if any) tool is called by the model. `none` means the model will + * not call any tools and instead generates a message. `auto` is the default value + * and means the model can pick between generating a message or calling a tool. + * Specifying a particular tool like `{"type": "TOOL_TYPE"}` or + * `{"type": "function", "function": {"name": "my_function"}}` forces the model to + * call that tool. + */ + tool_choice?: ThreadsAPI.AssistantToolChoiceOption | null; + + /** + * Override the tools the assistant can use for this run. This is useful for + * modifying the behavior on a per-run basis. + */ + tools?: Array | null; + + truncation_strategy?: RunStreamParams.TruncationStrategy | null; +} + +export namespace RunStreamParams { + export interface AdditionalMessage { + /** + * The content of the message. + */ + content: string; + + /** + * The role of the entity that is creating the message. Allowed values include: + * + * - `user`: Indicates the message is sent by an actual user and should be used in + * most cases to represent user-generated messages. + * - `assistant`: Indicates the message is generated by the assistant. Use this + * value to insert messages from the assistant into the conversation. + */ + role: 'user' | 'assistant'; + + /** + * A list of [File](https://platform.openai.com/docs/api-reference/files) IDs that + * the message should use. There can be a maximum of 10 files attached to a + * message. Useful for tools like `retrieval` and `code_interpreter` that can + * access and use files. + */ + file_ids?: Array; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata?: unknown | null; + } + + export interface TruncationStrategy { + /** + * The truncation strategy to use for the thread. The default is `auto`. If set to + * `last_messages`, the thread will be truncated to the n most recent messages in + * the thread. When set to `auto`, messages in the middle of the thread will be + * dropped to fit the context length of the model, `max_prompt_tokens`. + */ + type: 'auto' | 'last_messages'; + + /** + * The number of most recent messages from the thread when constructing the context + * for the run. + */ + last_messages?: number | null; + } +} + +export type RunSubmitToolOutputsParams = + | RunSubmitToolOutputsParamsNonStreaming + | RunSubmitToolOutputsParamsStreaming; + +export interface RunSubmitToolOutputsParamsBase { + /** + * A list of tools for which the outputs are being submitted. + */ + tool_outputs: Array; + + /** + * If `true`, returns a stream of events that happen during the Run as server-sent + * events, terminating when the Run enters a terminal state with a `data: [DONE]` + * message. + */ + stream?: boolean | null; +} + +export namespace RunSubmitToolOutputsParams { + export interface ToolOutput { + /** + * The output of the tool call to be submitted to continue the run. + */ + output?: string; + + /** + * The ID of the tool call in the `required_action` object within the run object + * the output is being submitted for. + */ + tool_call_id?: string; + } + + export type RunSubmitToolOutputsParamsNonStreaming = RunsAPI.RunSubmitToolOutputsParamsNonStreaming; + export type RunSubmitToolOutputsParamsStreaming = RunsAPI.RunSubmitToolOutputsParamsStreaming; +} + +export interface RunSubmitToolOutputsParamsNonStreaming extends RunSubmitToolOutputsParamsBase { + /** + * If `true`, returns a stream of events that happen during the Run as server-sent + * events, terminating when the Run enters a terminal state with a `data: [DONE]` + * message. + */ + stream?: false | null; +} + +export interface RunSubmitToolOutputsParamsStreaming extends RunSubmitToolOutputsParamsBase { + /** + * If `true`, returns a stream of events that happen during the Run as server-sent + * events, terminating when the Run enters a terminal state with a `data: [DONE]` + * message. + */ + stream: true; +} + +export interface RunSubmitToolOutputsAndPollParams { + /** + * A list of tools for which the outputs are being submitted. + */ + tool_outputs: Array; +} + +export namespace RunSubmitToolOutputsAndPollParams { + export interface ToolOutput { + /** + * The output of the tool call to be submitted to continue the run. + */ + output?: string; + + /** + * The ID of the tool call in the `required_action` object within the run object + * the output is being submitted for. + */ + tool_call_id?: string; + } +} + +export interface RunSubmitToolOutputsStreamParams { + /** + * A list of tools for which the outputs are being submitted. + */ + tool_outputs: Array; +} + +export namespace RunSubmitToolOutputsStreamParams { + export interface ToolOutput { + /** + * The output of the tool call to be submitted to continue the run. + */ + output?: string; + + /** + * The ID of the tool call in the `required_action` object within the run object + * the output is being submitted for. + */ + tool_call_id?: string; + } +} + +export namespace Runs { + export import RequiredActionFunctionToolCall = RunsAPI.RequiredActionFunctionToolCall; + export import Run = RunsAPI.Run; + export import RunStatus = RunsAPI.RunStatus; + export import RunsPage = RunsAPI.RunsPage; + export import RunCreateParams = RunsAPI.RunCreateParams; + export import RunCreateParamsNonStreaming = RunsAPI.RunCreateParamsNonStreaming; + export import RunCreateParamsStreaming = RunsAPI.RunCreateParamsStreaming; + export import RunUpdateParams = RunsAPI.RunUpdateParams; + export import RunListParams = RunsAPI.RunListParams; + export import RunCreateAndPollParams = RunsAPI.RunCreateAndPollParams; + export import RunCreateAndStreamParams = RunsAPI.RunCreateAndStreamParams; + export import RunStreamParams = RunsAPI.RunStreamParams; + export import RunSubmitToolOutputsParams = RunsAPI.RunSubmitToolOutputsParams; + export import RunSubmitToolOutputsParamsNonStreaming = RunsAPI.RunSubmitToolOutputsParamsNonStreaming; + export import RunSubmitToolOutputsParamsStreaming = RunsAPI.RunSubmitToolOutputsParamsStreaming; + export import RunSubmitToolOutputsAndPollParams = RunsAPI.RunSubmitToolOutputsAndPollParams; + export import RunSubmitToolOutputsStreamParams = RunsAPI.RunSubmitToolOutputsStreamParams; + export import Steps = StepsAPI.Steps; + export import CodeInterpreterLogs = StepsAPI.CodeInterpreterLogs; + export import CodeInterpreterOutputImage = StepsAPI.CodeInterpreterOutputImage; + export import CodeInterpreterToolCall = StepsAPI.CodeInterpreterToolCall; + export import CodeInterpreterToolCallDelta = StepsAPI.CodeInterpreterToolCallDelta; + export import FunctionToolCall = StepsAPI.FunctionToolCall; + export import FunctionToolCallDelta = StepsAPI.FunctionToolCallDelta; + export import MessageCreationStepDetails = StepsAPI.MessageCreationStepDetails; + export import RetrievalToolCall = StepsAPI.RetrievalToolCall; + export import RetrievalToolCallDelta = StepsAPI.RetrievalToolCallDelta; + export import RunStep = StepsAPI.RunStep; + export import RunStepDelta = StepsAPI.RunStepDelta; + export import RunStepDeltaEvent = StepsAPI.RunStepDeltaEvent; + export import RunStepDeltaMessageDelta = StepsAPI.RunStepDeltaMessageDelta; + export import ToolCall = StepsAPI.ToolCall; + export import ToolCallDelta = StepsAPI.ToolCallDelta; + export import ToolCallDeltaObject = StepsAPI.ToolCallDeltaObject; + export import ToolCallsStepDetails = StepsAPI.ToolCallsStepDetails; + export import RunStepsPage = StepsAPI.RunStepsPage; + export import StepListParams = StepsAPI.StepListParams; +} diff --git a/backend/node_modules/openai/src/resources/beta/threads/runs/steps.ts b/backend/node_modules/openai/src/resources/beta/threads/runs/steps.ts new file mode 100644 index 0000000000000000000000000000000000000000..7b26ea7798be91e2eb50746e62c593cd2645e477 --- /dev/null +++ b/backend/node_modules/openai/src/resources/beta/threads/runs/steps.ts @@ -0,0 +1,641 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import * as Core from "../../../../core"; +import { APIResource } from "../../../../resource"; +import { isRequestOptions } from "../../../../core"; +import * as StepsAPI from "./steps"; +import { CursorPage, type CursorPageParams } from "../../../../pagination"; + +export class Steps extends APIResource { + /** + * Retrieves a run step. + */ + retrieve( + threadId: string, + runId: string, + stepId: string, + options?: Core.RequestOptions, + ): Core.APIPromise { + return this._client.get(`/threads/${threadId}/runs/${runId}/steps/${stepId}`, { + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } + + /** + * Returns a list of run steps belonging to a run. + */ + list( + threadId: string, + runId: string, + query?: StepListParams, + options?: Core.RequestOptions, + ): Core.PagePromise; + list( + threadId: string, + runId: string, + options?: Core.RequestOptions, + ): Core.PagePromise; + list( + threadId: string, + runId: string, + query: StepListParams | Core.RequestOptions = {}, + options?: Core.RequestOptions, + ): Core.PagePromise { + if (isRequestOptions(query)) { + return this.list(threadId, runId, {}, query); + } + return this._client.getAPIList(`/threads/${threadId}/runs/${runId}/steps`, RunStepsPage, { + query, + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } +} + +export class RunStepsPage extends CursorPage {} + +/** + * Text output from the Code Interpreter tool call as part of a run step. + */ +export interface CodeInterpreterLogs { + /** + * The index of the output in the outputs array. + */ + index: number; + + /** + * Always `logs`. + */ + type: 'logs'; + + /** + * The text output from the Code Interpreter tool call. + */ + logs?: string; +} + +export interface CodeInterpreterOutputImage { + /** + * The index of the output in the outputs array. + */ + index: number; + + /** + * Always `image`. + */ + type: 'image'; + + image?: CodeInterpreterOutputImage.Image; +} + +export namespace CodeInterpreterOutputImage { + export interface Image { + /** + * The [file](https://platform.openai.com/docs/api-reference/files) ID of the + * image. + */ + file_id?: string; + } +} + +/** + * Details of the Code Interpreter tool call the run step was involved in. + */ +export interface CodeInterpreterToolCall { + /** + * The ID of the tool call. + */ + id: string; + + /** + * The Code Interpreter tool call definition. + */ + code_interpreter: CodeInterpreterToolCall.CodeInterpreter; + + /** + * The type of tool call. This is always going to be `code_interpreter` for this + * type of tool call. + */ + type: 'code_interpreter'; +} + +export namespace CodeInterpreterToolCall { + /** + * The Code Interpreter tool call definition. + */ + export interface CodeInterpreter { + /** + * The input to the Code Interpreter tool call. + */ + input: string; + + /** + * The outputs from the Code Interpreter tool call. Code Interpreter can output one + * or more items, including text (`logs`) or images (`image`). Each of these are + * represented by a different object type. + */ + outputs: Array; + } + + export namespace CodeInterpreter { + /** + * Text output from the Code Interpreter tool call as part of a run step. + */ + export interface Logs { + /** + * The text output from the Code Interpreter tool call. + */ + logs: string; + + /** + * Always `logs`. + */ + type: 'logs'; + } + + export interface Image { + image: Image.Image; + + /** + * Always `image`. + */ + type: 'image'; + } + + export namespace Image { + export interface Image { + /** + * The [file](https://platform.openai.com/docs/api-reference/files) ID of the + * image. + */ + file_id: string; + } + } + } +} + +/** + * Details of the Code Interpreter tool call the run step was involved in. + */ +export interface CodeInterpreterToolCallDelta { + /** + * The index of the tool call in the tool calls array. + */ + index: number; + + /** + * The type of tool call. This is always going to be `code_interpreter` for this + * type of tool call. + */ + type: 'code_interpreter'; + + /** + * The ID of the tool call. + */ + id?: string; + + /** + * The Code Interpreter tool call definition. + */ + code_interpreter?: CodeInterpreterToolCallDelta.CodeInterpreter; +} + +export namespace CodeInterpreterToolCallDelta { + /** + * The Code Interpreter tool call definition. + */ + export interface CodeInterpreter { + /** + * The input to the Code Interpreter tool call. + */ + input?: string; + + /** + * The outputs from the Code Interpreter tool call. Code Interpreter can output one + * or more items, including text (`logs`) or images (`image`). Each of these are + * represented by a different object type. + */ + outputs?: Array; + } +} + +export interface FunctionToolCall { + /** + * The ID of the tool call object. + */ + id: string; + + /** + * The definition of the function that was called. + */ + function: FunctionToolCall.Function; + + /** + * The type of tool call. This is always going to be `function` for this type of + * tool call. + */ + type: 'function'; +} + +export namespace FunctionToolCall { + /** + * The definition of the function that was called. + */ + export interface Function { + /** + * The arguments passed to the function. + */ + arguments: string; + + /** + * The name of the function. + */ + name: string; + + /** + * The output of the function. This will be `null` if the outputs have not been + * [submitted](https://platform.openai.com/docs/api-reference/runs/submitToolOutputs) + * yet. + */ + output: string | null; + } +} + +export interface FunctionToolCallDelta { + /** + * The index of the tool call in the tool calls array. + */ + index: number; + + /** + * The type of tool call. This is always going to be `function` for this type of + * tool call. + */ + type: 'function'; + + /** + * The ID of the tool call object. + */ + id?: string; + + /** + * The definition of the function that was called. + */ + function?: FunctionToolCallDelta.Function; +} + +export namespace FunctionToolCallDelta { + /** + * The definition of the function that was called. + */ + export interface Function { + /** + * The arguments passed to the function. + */ + arguments?: string; + + /** + * The name of the function. + */ + name?: string; + + /** + * The output of the function. This will be `null` if the outputs have not been + * [submitted](https://platform.openai.com/docs/api-reference/runs/submitToolOutputs) + * yet. + */ + output?: string | null; + } +} + +/** + * Details of the message creation by the run step. + */ +export interface MessageCreationStepDetails { + message_creation: MessageCreationStepDetails.MessageCreation; + + /** + * Always `message_creation`. + */ + type: 'message_creation'; +} + +export namespace MessageCreationStepDetails { + export interface MessageCreation { + /** + * The ID of the message that was created by this run step. + */ + message_id: string; + } +} + +export interface RetrievalToolCall { + /** + * The ID of the tool call object. + */ + id: string; + + /** + * For now, this is always going to be an empty object. + */ + retrieval: unknown; + + /** + * The type of tool call. This is always going to be `retrieval` for this type of + * tool call. + */ + type: 'retrieval'; +} + +export interface RetrievalToolCallDelta { + /** + * The index of the tool call in the tool calls array. + */ + index: number; + + /** + * The type of tool call. This is always going to be `retrieval` for this type of + * tool call. + */ + type: 'retrieval'; + + /** + * The ID of the tool call object. + */ + id?: string; + + /** + * For now, this is always going to be an empty object. + */ + retrieval?: unknown; +} + +/** + * Represents a step in execution of a run. + */ +export interface RunStep { + /** + * The identifier of the run step, which can be referenced in API endpoints. + */ + id: string; + + /** + * The ID of the + * [assistant](https://platform.openai.com/docs/api-reference/assistants) + * associated with the run step. + */ + assistant_id: string; + + /** + * The Unix timestamp (in seconds) for when the run step was cancelled. + */ + cancelled_at: number | null; + + /** + * The Unix timestamp (in seconds) for when the run step completed. + */ + completed_at: number | null; + + /** + * The Unix timestamp (in seconds) for when the run step was created. + */ + created_at: number; + + /** + * The Unix timestamp (in seconds) for when the run step expired. A step is + * considered expired if the parent run is expired. + */ + expired_at: number | null; + + /** + * The Unix timestamp (in seconds) for when the run step failed. + */ + failed_at: number | null; + + /** + * The last error associated with this run step. Will be `null` if there are no + * errors. + */ + last_error: RunStep.LastError | null; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata: unknown | null; + + /** + * The object type, which is always `thread.run.step`. + */ + object: 'thread.run.step'; + + /** + * The ID of the [run](https://platform.openai.com/docs/api-reference/runs) that + * this run step is a part of. + */ + run_id: string; + + /** + * The status of the run step, which can be either `in_progress`, `cancelled`, + * `failed`, `completed`, or `expired`. + */ + status: 'in_progress' | 'cancelled' | 'failed' | 'completed' | 'expired'; + + /** + * The details of the run step. + */ + step_details: MessageCreationStepDetails | ToolCallsStepDetails; + + /** + * The ID of the [thread](https://platform.openai.com/docs/api-reference/threads) + * that was run. + */ + thread_id: string; + + /** + * The type of run step, which can be either `message_creation` or `tool_calls`. + */ + type: 'message_creation' | 'tool_calls'; + + /** + * Usage statistics related to the run step. This value will be `null` while the + * run step's status is `in_progress`. + */ + usage: RunStep.Usage | null; +} + +export namespace RunStep { + /** + * The last error associated with this run step. Will be `null` if there are no + * errors. + */ + export interface LastError { + /** + * One of `server_error` or `rate_limit_exceeded`. + */ + code: 'server_error' | 'rate_limit_exceeded'; + + /** + * A human-readable description of the error. + */ + message: string; + } + + /** + * Usage statistics related to the run step. This value will be `null` while the + * run step's status is `in_progress`. + */ + export interface Usage { + /** + * Number of completion tokens used over the course of the run step. + */ + completion_tokens: number; + + /** + * Number of prompt tokens used over the course of the run step. + */ + prompt_tokens: number; + + /** + * Total number of tokens used (prompt + completion). + */ + total_tokens: number; + } +} + +/** + * The delta containing the fields that have changed on the run step. + */ +export interface RunStepDelta { + /** + * The details of the run step. + */ + step_details?: RunStepDeltaMessageDelta | ToolCallDeltaObject; +} + +/** + * Represents a run step delta i.e. any changed fields on a run step during + * streaming. + */ +export interface RunStepDeltaEvent { + /** + * The identifier of the run step, which can be referenced in API endpoints. + */ + id: string; + + /** + * The delta containing the fields that have changed on the run step. + */ + delta: RunStepDelta; + + /** + * The object type, which is always `thread.run.step.delta`. + */ + object: 'thread.run.step.delta'; +} + +/** + * Details of the message creation by the run step. + */ +export interface RunStepDeltaMessageDelta { + /** + * Always `message_creation`. + */ + type: 'message_creation'; + + message_creation?: RunStepDeltaMessageDelta.MessageCreation; +} + +export namespace RunStepDeltaMessageDelta { + export interface MessageCreation { + /** + * The ID of the message that was created by this run step. + */ + message_id?: string; + } +} + +/** + * Details of the Code Interpreter tool call the run step was involved in. + */ +export type ToolCall = CodeInterpreterToolCall | RetrievalToolCall | FunctionToolCall; + +/** + * Details of the Code Interpreter tool call the run step was involved in. + */ +export type ToolCallDelta = CodeInterpreterToolCallDelta | RetrievalToolCallDelta | FunctionToolCallDelta; + +/** + * Details of the tool call. + */ +export interface ToolCallDeltaObject { + /** + * Always `tool_calls`. + */ + type: 'tool_calls'; + + /** + * An array of tool calls the run step was involved in. These can be associated + * with one of three types of tools: `code_interpreter`, `retrieval`, or + * `function`. + */ + tool_calls?: Array; +} + +/** + * Details of the tool call. + */ +export interface ToolCallsStepDetails { + /** + * An array of tool calls the run step was involved in. These can be associated + * with one of three types of tools: `code_interpreter`, `retrieval`, or + * `function`. + */ + tool_calls: Array; + + /** + * Always `tool_calls`. + */ + type: 'tool_calls'; +} + +export interface StepListParams extends CursorPageParams { + /** + * A cursor for use in pagination. `before` is an object ID that defines your place + * in the list. For instance, if you make a list request and receive 100 objects, + * ending with obj_foo, your subsequent call can include before=obj_foo in order to + * fetch the previous page of the list. + */ + before?: string; + + /** + * Sort order by the `created_at` timestamp of the objects. `asc` for ascending + * order and `desc` for descending order. + */ + order?: 'asc' | 'desc'; +} + +export namespace Steps { + export import CodeInterpreterLogs = StepsAPI.CodeInterpreterLogs; + export import CodeInterpreterOutputImage = StepsAPI.CodeInterpreterOutputImage; + export import CodeInterpreterToolCall = StepsAPI.CodeInterpreterToolCall; + export import CodeInterpreterToolCallDelta = StepsAPI.CodeInterpreterToolCallDelta; + export import FunctionToolCall = StepsAPI.FunctionToolCall; + export import FunctionToolCallDelta = StepsAPI.FunctionToolCallDelta; + export import MessageCreationStepDetails = StepsAPI.MessageCreationStepDetails; + export import RetrievalToolCall = StepsAPI.RetrievalToolCall; + export import RetrievalToolCallDelta = StepsAPI.RetrievalToolCallDelta; + export import RunStep = StepsAPI.RunStep; + export import RunStepDelta = StepsAPI.RunStepDelta; + export import RunStepDeltaEvent = StepsAPI.RunStepDeltaEvent; + export import RunStepDeltaMessageDelta = StepsAPI.RunStepDeltaMessageDelta; + export import ToolCall = StepsAPI.ToolCall; + export import ToolCallDelta = StepsAPI.ToolCallDelta; + export import ToolCallDeltaObject = StepsAPI.ToolCallDeltaObject; + export import ToolCallsStepDetails = StepsAPI.ToolCallsStepDetails; + export import RunStepsPage = StepsAPI.RunStepsPage; + export import StepListParams = StepsAPI.StepListParams; +} diff --git a/backend/node_modules/openai/src/resources/beta/threads/threads.ts b/backend/node_modules/openai/src/resources/beta/threads/threads.ts new file mode 100644 index 0000000000000000000000000000000000000000..f7e58e100997c73281d3a601823c2bbd9acb4cdd --- /dev/null +++ b/backend/node_modules/openai/src/resources/beta/threads/threads.ts @@ -0,0 +1,940 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import * as Core from "../../../core"; +import { APIPromise } from "../../../core"; +import { APIResource } from "../../../resource"; +import { isRequestOptions } from "../../../core"; +import { AssistantStream, ThreadCreateAndRunParamsBaseStream } from "../../../lib/AssistantStream"; +import * as ThreadsAPI from "./threads"; +import * as AssistantsAPI from "../assistants/assistants"; +import * as MessagesAPI from "./messages/messages"; +import * as RunsAPI from "./runs/runs"; +import { Stream } from "../../../streaming"; + +export class Threads extends APIResource { + runs: RunsAPI.Runs = new RunsAPI.Runs(this._client); + messages: MessagesAPI.Messages = new MessagesAPI.Messages(this._client); + + /** + * Create a thread. + */ + create(body?: ThreadCreateParams, options?: Core.RequestOptions): Core.APIPromise; + create(options?: Core.RequestOptions): Core.APIPromise; + create( + body: ThreadCreateParams | Core.RequestOptions = {}, + options?: Core.RequestOptions, + ): Core.APIPromise { + if (isRequestOptions(body)) { + return this.create({}, body); + } + return this._client.post('/threads', { + body, + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } + + /** + * Retrieves a thread. + */ + retrieve(threadId: string, options?: Core.RequestOptions): Core.APIPromise { + return this._client.get(`/threads/${threadId}`, { + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } + + /** + * Modifies a thread. + */ + update(threadId: string, body: ThreadUpdateParams, options?: Core.RequestOptions): Core.APIPromise { + return this._client.post(`/threads/${threadId}`, { + body, + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } + + /** + * Delete a thread. + */ + del(threadId: string, options?: Core.RequestOptions): Core.APIPromise { + return this._client.delete(`/threads/${threadId}`, { + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + }); + } + + /** + * Create a thread and run it in one request. + */ + createAndRun( + body: ThreadCreateAndRunParamsNonStreaming, + options?: Core.RequestOptions, + ): APIPromise; + createAndRun( + body: ThreadCreateAndRunParamsStreaming, + options?: Core.RequestOptions, + ): APIPromise>; + createAndRun( + body: ThreadCreateAndRunParamsBase, + options?: Core.RequestOptions, + ): APIPromise | RunsAPI.Run>; + createAndRun( + body: ThreadCreateAndRunParams, + options?: Core.RequestOptions, + ): APIPromise | APIPromise> { + return this._client.post('/threads/runs', { + body, + ...options, + headers: { 'OpenAI-Beta': 'assistants=v1', ...options?.headers }, + stream: body.stream ?? false, + }) as APIPromise | APIPromise>; + } + + /** + * A helper to create a thread, start a run and then poll for a terminal state. + * More information on Run lifecycles can be found here: + * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps + */ + async createAndRunPoll( + body: ThreadCreateAndRunParamsNonStreaming, + options?: Core.RequestOptions & { pollIntervalMs?: number }, + ): Promise { + const run = await this.createAndRun(body, options); + return await this.runs.poll(run.thread_id, run.id, options); + } + + /** + * Create a thread and stream the run back + */ + createAndRunStream( + body: ThreadCreateAndRunParamsBaseStream, + options?: Core.RequestOptions, + ): AssistantStream { + return AssistantStream.createThreadAssistantStream(body, this._client.beta.threads, options); + } +} + +/** + * An object describing the expected output of the model. If `json_object` only + * `function` type `tools` are allowed to be passed to the Run. If `text` the model + * can return text or any value needed. + */ +export interface AssistantResponseFormat { + /** + * Must be one of `text` or `json_object`. + */ + type?: 'text' | 'json_object'; +} + +/** + * Specifies the format that the model must output. Compatible with + * [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and + * all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + * + * Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + * message the model generates is valid JSON. + * + * **Important:** when using JSON mode, you **must** also instruct the model to + * produce JSON yourself via a system or user message. Without this, the model may + * generate an unending stream of whitespace until the generation reaches the token + * limit, resulting in a long-running and seemingly "stuck" request. Also note that + * the message content may be partially cut off if `finish_reason="length"`, which + * indicates the generation exceeded `max_tokens` or the conversation exceeded the + * max context length. + */ +export type AssistantResponseFormatOption = 'none' | 'auto' | AssistantResponseFormat; + +/** + * Specifies a tool the model should use. Use to force the model to call a specific + * tool. + */ +export interface AssistantToolChoice { + /** + * The type of the tool. If type is `function`, the function name must be set + */ + type: 'function' | 'code_interpreter' | 'retrieval'; + + function?: AssistantToolChoiceFunction; +} + +export interface AssistantToolChoiceFunction { + /** + * The name of the function to call. + */ + name: string; +} + +/** + * Controls which (if any) tool is called by the model. `none` means the model will + * not call any tools and instead generates a message. `auto` is the default value + * and means the model can pick between generating a message or calling a tool. + * Specifying a particular tool like `{"type": "TOOL_TYPE"}` or + * `{"type": "function", "function": {"name": "my_function"}}` forces the model to + * call that tool. + */ +export type AssistantToolChoiceOption = 'none' | 'auto' | AssistantToolChoice; + +/** + * Represents a thread that contains + * [messages](https://platform.openai.com/docs/api-reference/messages). + */ +export interface Thread { + /** + * The identifier, which can be referenced in API endpoints. + */ + id: string; + + /** + * The Unix timestamp (in seconds) for when the thread was created. + */ + created_at: number; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata: unknown | null; + + /** + * The object type, which is always `thread`. + */ + object: 'thread'; +} + +export interface ThreadDeleted { + id: string; + + deleted: boolean; + + object: 'thread.deleted'; +} + +export interface ThreadCreateParams { + /** + * A list of [messages](https://platform.openai.com/docs/api-reference/messages) to + * start the thread with. + */ + messages?: Array; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata?: unknown | null; +} + +export namespace ThreadCreateParams { + export interface Message { + /** + * The content of the message. + */ + content: string; + + /** + * The role of the entity that is creating the message. Allowed values include: + * + * - `user`: Indicates the message is sent by an actual user and should be used in + * most cases to represent user-generated messages. + * - `assistant`: Indicates the message is generated by the assistant. Use this + * value to insert messages from the assistant into the conversation. + */ + role: 'user' | 'assistant'; + + /** + * A list of [File](https://platform.openai.com/docs/api-reference/files) IDs that + * the message should use. There can be a maximum of 10 files attached to a + * message. Useful for tools like `retrieval` and `code_interpreter` that can + * access and use files. + */ + file_ids?: Array; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata?: unknown | null; + } +} + +export interface ThreadUpdateParams { + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata?: unknown | null; +} + +export type ThreadCreateAndRunParams = + | ThreadCreateAndRunParamsNonStreaming + | ThreadCreateAndRunParamsStreaming; + +export interface ThreadCreateAndRunParamsBase { + /** + * The ID of the + * [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to + * execute this run. + */ + assistant_id: string; + + /** + * Override the default system message of the assistant. This is useful for + * modifying the behavior on a per-run basis. + */ + instructions?: string | null; + + /** + * The maximum number of completion tokens that may be used over the course of the + * run. The run will make a best effort to use only the number of completion tokens + * specified, across multiple turns of the run. If the run exceeds the number of + * completion tokens specified, the run will end with status `complete`. See + * `incomplete_details` for more info. + */ + max_completion_tokens?: number | null; + + /** + * The maximum number of prompt tokens that may be used over the course of the run. + * The run will make a best effort to use only the number of prompt tokens + * specified, across multiple turns of the run. If the run exceeds the number of + * prompt tokens specified, the run will end with status `complete`. See + * `incomplete_details` for more info. + */ + max_prompt_tokens?: number | null; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata?: unknown | null; + + /** + * The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to + * be used to execute this run. If a value is provided here, it will override the + * model associated with the assistant. If not, the model associated with the + * assistant will be used. + */ + model?: + | (string & {}) + | 'gpt-4-turbo' + | 'gpt-4-turbo-2024-04-09' + | 'gpt-4-0125-preview' + | 'gpt-4-turbo-preview' + | 'gpt-4-1106-preview' + | 'gpt-4-vision-preview' + | 'gpt-4' + | 'gpt-4-0314' + | 'gpt-4-0613' + | 'gpt-4-32k' + | 'gpt-4-32k-0314' + | 'gpt-4-32k-0613' + | 'gpt-3.5-turbo' + | 'gpt-3.5-turbo-16k' + | 'gpt-3.5-turbo-0613' + | 'gpt-3.5-turbo-1106' + | 'gpt-3.5-turbo-0125' + | 'gpt-3.5-turbo-16k-0613' + | null; + + /** + * Specifies the format that the model must output. Compatible with + * [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and + * all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + * + * Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + * message the model generates is valid JSON. + * + * **Important:** when using JSON mode, you **must** also instruct the model to + * produce JSON yourself via a system or user message. Without this, the model may + * generate an unending stream of whitespace until the generation reaches the token + * limit, resulting in a long-running and seemingly "stuck" request. Also note that + * the message content may be partially cut off if `finish_reason="length"`, which + * indicates the generation exceeded `max_tokens` or the conversation exceeded the + * max context length. + */ + response_format?: AssistantResponseFormatOption | null; + + /** + * If `true`, returns a stream of events that happen during the Run as server-sent + * events, terminating when the Run enters a terminal state with a `data: [DONE]` + * message. + */ + stream?: boolean | null; + + /** + * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + * make the output more random, while lower values like 0.2 will make it more + * focused and deterministic. + */ + temperature?: number | null; + + /** + * If no thread is provided, an empty thread will be created. + */ + thread?: ThreadCreateAndRunParams.Thread; + + /** + * Controls which (if any) tool is called by the model. `none` means the model will + * not call any tools and instead generates a message. `auto` is the default value + * and means the model can pick between generating a message or calling a tool. + * Specifying a particular tool like `{"type": "TOOL_TYPE"}` or + * `{"type": "function", "function": {"name": "my_function"}}` forces the model to + * call that tool. + */ + tool_choice?: AssistantToolChoiceOption | null; + + /** + * Override the tools the assistant can use for this run. This is useful for + * modifying the behavior on a per-run basis. + */ + tools?: Array< + AssistantsAPI.CodeInterpreterTool | AssistantsAPI.RetrievalTool | AssistantsAPI.FunctionTool + > | null; + + truncation_strategy?: ThreadCreateAndRunParams.TruncationStrategy | null; +} + +export namespace ThreadCreateAndRunParams { + /** + * If no thread is provided, an empty thread will be created. + */ + export interface Thread { + /** + * A list of [messages](https://platform.openai.com/docs/api-reference/messages) to + * start the thread with. + */ + messages?: Array; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata?: unknown | null; + } + + export namespace Thread { + export interface Message { + /** + * The content of the message. + */ + content: string; + + /** + * The role of the entity that is creating the message. Allowed values include: + * + * - `user`: Indicates the message is sent by an actual user and should be used in + * most cases to represent user-generated messages. + * - `assistant`: Indicates the message is generated by the assistant. Use this + * value to insert messages from the assistant into the conversation. + */ + role: 'user' | 'assistant'; + + /** + * A list of [File](https://platform.openai.com/docs/api-reference/files) IDs that + * the message should use. There can be a maximum of 10 files attached to a + * message. Useful for tools like `retrieval` and `code_interpreter` that can + * access and use files. + */ + file_ids?: Array; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata?: unknown | null; + } + } + + export interface TruncationStrategy { + /** + * The truncation strategy to use for the thread. The default is `auto`. If set to + * `last_messages`, the thread will be truncated to the n most recent messages in + * the thread. When set to `auto`, messages in the middle of the thread will be + * dropped to fit the context length of the model, `max_prompt_tokens`. + */ + type: 'auto' | 'last_messages'; + + /** + * The number of most recent messages from the thread when constructing the context + * for the run. + */ + last_messages?: number | null; + } + + export type ThreadCreateAndRunParamsNonStreaming = ThreadsAPI.ThreadCreateAndRunParamsNonStreaming; + export type ThreadCreateAndRunParamsStreaming = ThreadsAPI.ThreadCreateAndRunParamsStreaming; +} + +export interface ThreadCreateAndRunParamsNonStreaming extends ThreadCreateAndRunParamsBase { + /** + * If `true`, returns a stream of events that happen during the Run as server-sent + * events, terminating when the Run enters a terminal state with a `data: [DONE]` + * message. + */ + stream?: false | null; +} + +export interface ThreadCreateAndRunParamsStreaming extends ThreadCreateAndRunParamsBase { + /** + * If `true`, returns a stream of events that happen during the Run as server-sent + * events, terminating when the Run enters a terminal state with a `data: [DONE]` + * message. + */ + stream: true; +} + +export interface ThreadCreateAndRunPollParams { + /** + * The ID of the + * [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to + * execute this run. + */ + assistant_id: string; + + /** + * Override the default system message of the assistant. This is useful for + * modifying the behavior on a per-run basis. + */ + instructions?: string | null; + + /** + * The maximum number of completion tokens that may be used over the course of the + * run. The run will make a best effort to use only the number of completion tokens + * specified, across multiple turns of the run. If the run exceeds the number of + * completion tokens specified, the run will end with status `complete`. See + * `incomplete_details` for more info. + */ + max_completion_tokens?: number | null; + + /** + * The maximum number of prompt tokens that may be used over the course of the run. + * The run will make a best effort to use only the number of prompt tokens + * specified, across multiple turns of the run. If the run exceeds the number of + * prompt tokens specified, the run will end with status `complete`. See + * `incomplete_details` for more info. + */ + max_prompt_tokens?: number | null; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata?: unknown | null; + + /** + * The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to + * be used to execute this run. If a value is provided here, it will override the + * model associated with the assistant. If not, the model associated with the + * assistant will be used. + */ + model?: + | (string & {}) + | 'gpt-4-turbo' + | 'gpt-4-turbo-2024-04-09' + | 'gpt-4-0125-preview' + | 'gpt-4-turbo-preview' + | 'gpt-4-1106-preview' + | 'gpt-4-vision-preview' + | 'gpt-4' + | 'gpt-4-0314' + | 'gpt-4-0613' + | 'gpt-4-32k' + | 'gpt-4-32k-0314' + | 'gpt-4-32k-0613' + | 'gpt-3.5-turbo' + | 'gpt-3.5-turbo-16k' + | 'gpt-3.5-turbo-0613' + | 'gpt-3.5-turbo-1106' + | 'gpt-3.5-turbo-0125' + | 'gpt-3.5-turbo-16k-0613' + | null; + + /** + * Specifies the format that the model must output. Compatible with + * [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and + * all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + * + * Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + * message the model generates is valid JSON. + * + * **Important:** when using JSON mode, you **must** also instruct the model to + * produce JSON yourself via a system or user message. Without this, the model may + * generate an unending stream of whitespace until the generation reaches the token + * limit, resulting in a long-running and seemingly "stuck" request. Also note that + * the message content may be partially cut off if `finish_reason="length"`, which + * indicates the generation exceeded `max_tokens` or the conversation exceeded the + * max context length. + */ + response_format?: AssistantResponseFormatOption | null; + + /** + * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + * make the output more random, while lower values like 0.2 will make it more + * focused and deterministic. + */ + temperature?: number | null; + + /** + * If no thread is provided, an empty thread will be created. + */ + thread?: ThreadCreateAndRunPollParams.Thread; + + /** + * Controls which (if any) tool is called by the model. `none` means the model will + * not call any tools and instead generates a message. `auto` is the default value + * and means the model can pick between generating a message or calling a tool. + * Specifying a particular tool like `{"type": "TOOL_TYPE"}` or + * `{"type": "function", "function": {"name": "my_function"}}` forces the model to + * call that tool. + */ + tool_choice?: AssistantToolChoiceOption | null; + + /** + * Override the tools the assistant can use for this run. This is useful for + * modifying the behavior on a per-run basis. + */ + tools?: Array< + AssistantsAPI.CodeInterpreterTool | AssistantsAPI.RetrievalTool | AssistantsAPI.FunctionTool + > | null; + + truncation_strategy?: ThreadCreateAndRunPollParams.TruncationStrategy | null; +} + +export namespace ThreadCreateAndRunPollParams { + /** + * If no thread is provided, an empty thread will be created. + */ + export interface Thread { + /** + * A list of [messages](https://platform.openai.com/docs/api-reference/messages) to + * start the thread with. + */ + messages?: Array; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata?: unknown | null; + } + + export namespace Thread { + export interface Message { + /** + * The content of the message. + */ + content: string; + + /** + * The role of the entity that is creating the message. Allowed values include: + * + * - `user`: Indicates the message is sent by an actual user and should be used in + * most cases to represent user-generated messages. + * - `assistant`: Indicates the message is generated by the assistant. Use this + * value to insert messages from the assistant into the conversation. + */ + role: 'user' | 'assistant'; + + /** + * A list of [File](https://platform.openai.com/docs/api-reference/files) IDs that + * the message should use. There can be a maximum of 10 files attached to a + * message. Useful for tools like `retrieval` and `code_interpreter` that can + * access and use files. + */ + file_ids?: Array; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata?: unknown | null; + } + } + + export interface TruncationStrategy { + /** + * The truncation strategy to use for the thread. The default is `auto`. If set to + * `last_messages`, the thread will be truncated to the n most recent messages in + * the thread. When set to `auto`, messages in the middle of the thread will be + * dropped to fit the context length of the model, `max_prompt_tokens`. + */ + type: 'auto' | 'last_messages'; + + /** + * The number of most recent messages from the thread when constructing the context + * for the run. + */ + last_messages?: number | null; + } +} + +export interface ThreadCreateAndRunStreamParams { + /** + * The ID of the + * [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to + * execute this run. + */ + assistant_id: string; + + /** + * Override the default system message of the assistant. This is useful for + * modifying the behavior on a per-run basis. + */ + instructions?: string | null; + + /** + * The maximum number of completion tokens that may be used over the course of the + * run. The run will make a best effort to use only the number of completion tokens + * specified, across multiple turns of the run. If the run exceeds the number of + * completion tokens specified, the run will end with status `complete`. See + * `incomplete_details` for more info. + */ + max_completion_tokens?: number | null; + + /** + * The maximum number of prompt tokens that may be used over the course of the run. + * The run will make a best effort to use only the number of prompt tokens + * specified, across multiple turns of the run. If the run exceeds the number of + * prompt tokens specified, the run will end with status `complete`. See + * `incomplete_details` for more info. + */ + max_prompt_tokens?: number | null; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata?: unknown | null; + + /** + * The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to + * be used to execute this run. If a value is provided here, it will override the + * model associated with the assistant. If not, the model associated with the + * assistant will be used. + */ + model?: + | (string & {}) + | 'gpt-4-turbo' + | 'gpt-4-turbo-2024-04-09' + | 'gpt-4-0125-preview' + | 'gpt-4-turbo-preview' + | 'gpt-4-1106-preview' + | 'gpt-4-vision-preview' + | 'gpt-4' + | 'gpt-4-0314' + | 'gpt-4-0613' + | 'gpt-4-32k' + | 'gpt-4-32k-0314' + | 'gpt-4-32k-0613' + | 'gpt-3.5-turbo' + | 'gpt-3.5-turbo-16k' + | 'gpt-3.5-turbo-0613' + | 'gpt-3.5-turbo-1106' + | 'gpt-3.5-turbo-0125' + | 'gpt-3.5-turbo-16k-0613' + | null; + + /** + * Specifies the format that the model must output. Compatible with + * [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and + * all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + * + * Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + * message the model generates is valid JSON. + * + * **Important:** when using JSON mode, you **must** also instruct the model to + * produce JSON yourself via a system or user message. Without this, the model may + * generate an unending stream of whitespace until the generation reaches the token + * limit, resulting in a long-running and seemingly "stuck" request. Also note that + * the message content may be partially cut off if `finish_reason="length"`, which + * indicates the generation exceeded `max_tokens` or the conversation exceeded the + * max context length. + */ + response_format?: AssistantResponseFormatOption | null; + + /** + * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + * make the output more random, while lower values like 0.2 will make it more + * focused and deterministic. + */ + temperature?: number | null; + + /** + * If no thread is provided, an empty thread will be created. + */ + thread?: ThreadCreateAndRunStreamParams.Thread; + + /** + * Controls which (if any) tool is called by the model. `none` means the model will + * not call any tools and instead generates a message. `auto` is the default value + * and means the model can pick between generating a message or calling a tool. + * Specifying a particular tool like `{"type": "TOOL_TYPE"}` or + * `{"type": "function", "function": {"name": "my_function"}}` forces the model to + * call that tool. + */ + tool_choice?: AssistantToolChoiceOption | null; + + /** + * Override the tools the assistant can use for this run. This is useful for + * modifying the behavior on a per-run basis. + */ + tools?: Array< + AssistantsAPI.CodeInterpreterTool | AssistantsAPI.RetrievalTool | AssistantsAPI.FunctionTool + > | null; + + truncation_strategy?: ThreadCreateAndRunStreamParams.TruncationStrategy | null; +} + +export namespace ThreadCreateAndRunStreamParams { + /** + * If no thread is provided, an empty thread will be created. + */ + export interface Thread { + /** + * A list of [messages](https://platform.openai.com/docs/api-reference/messages) to + * start the thread with. + */ + messages?: Array; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata?: unknown | null; + } + + export namespace Thread { + export interface Message { + /** + * The content of the message. + */ + content: string; + + /** + * The role of the entity that is creating the message. Allowed values include: + * + * - `user`: Indicates the message is sent by an actual user and should be used in + * most cases to represent user-generated messages. + * - `assistant`: Indicates the message is generated by the assistant. Use this + * value to insert messages from the assistant into the conversation. + */ + role: 'user' | 'assistant'; + + /** + * A list of [File](https://platform.openai.com/docs/api-reference/files) IDs that + * the message should use. There can be a maximum of 10 files attached to a + * message. Useful for tools like `retrieval` and `code_interpreter` that can + * access and use files. + */ + file_ids?: Array; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata?: unknown | null; + } + } + + export interface TruncationStrategy { + /** + * The truncation strategy to use for the thread. The default is `auto`. If set to + * `last_messages`, the thread will be truncated to the n most recent messages in + * the thread. When set to `auto`, messages in the middle of the thread will be + * dropped to fit the context length of the model, `max_prompt_tokens`. + */ + type: 'auto' | 'last_messages'; + + /** + * The number of most recent messages from the thread when constructing the context + * for the run. + */ + last_messages?: number | null; + } +} + +export namespace Threads { + export import AssistantResponseFormat = ThreadsAPI.AssistantResponseFormat; + export import AssistantResponseFormatOption = ThreadsAPI.AssistantResponseFormatOption; + export import AssistantToolChoice = ThreadsAPI.AssistantToolChoice; + export import AssistantToolChoiceFunction = ThreadsAPI.AssistantToolChoiceFunction; + export import AssistantToolChoiceOption = ThreadsAPI.AssistantToolChoiceOption; + export import Thread = ThreadsAPI.Thread; + export import ThreadDeleted = ThreadsAPI.ThreadDeleted; + export import ThreadCreateParams = ThreadsAPI.ThreadCreateParams; + export import ThreadUpdateParams = ThreadsAPI.ThreadUpdateParams; + export import ThreadCreateAndRunParams = ThreadsAPI.ThreadCreateAndRunParams; + export import ThreadCreateAndRunParamsNonStreaming = ThreadsAPI.ThreadCreateAndRunParamsNonStreaming; + export import ThreadCreateAndRunParamsStreaming = ThreadsAPI.ThreadCreateAndRunParamsStreaming; + export import ThreadCreateAndRunPollParams = ThreadsAPI.ThreadCreateAndRunPollParams; + export import ThreadCreateAndRunStreamParams = ThreadsAPI.ThreadCreateAndRunStreamParams; + export import Runs = RunsAPI.Runs; + export import RequiredActionFunctionToolCall = RunsAPI.RequiredActionFunctionToolCall; + export import Run = RunsAPI.Run; + export import RunStatus = RunsAPI.RunStatus; + export import RunsPage = RunsAPI.RunsPage; + export import RunCreateParams = RunsAPI.RunCreateParams; + export import RunCreateParamsNonStreaming = RunsAPI.RunCreateParamsNonStreaming; + export import RunCreateParamsStreaming = RunsAPI.RunCreateParamsStreaming; + export import RunUpdateParams = RunsAPI.RunUpdateParams; + export import RunListParams = RunsAPI.RunListParams; + export import RunCreateAndPollParams = RunsAPI.RunCreateAndPollParams; + export import RunCreateAndStreamParams = RunsAPI.RunCreateAndStreamParams; + export import RunStreamParams = RunsAPI.RunStreamParams; + export import RunSubmitToolOutputsParams = RunsAPI.RunSubmitToolOutputsParams; + export import RunSubmitToolOutputsParamsNonStreaming = RunsAPI.RunSubmitToolOutputsParamsNonStreaming; + export import RunSubmitToolOutputsParamsStreaming = RunsAPI.RunSubmitToolOutputsParamsStreaming; + export import RunSubmitToolOutputsAndPollParams = RunsAPI.RunSubmitToolOutputsAndPollParams; + export import RunSubmitToolOutputsStreamParams = RunsAPI.RunSubmitToolOutputsStreamParams; + export import Messages = MessagesAPI.Messages; + export import Annotation = MessagesAPI.Annotation; + export import AnnotationDelta = MessagesAPI.AnnotationDelta; + export import FileCitationAnnotation = MessagesAPI.FileCitationAnnotation; + export import FileCitationDeltaAnnotation = MessagesAPI.FileCitationDeltaAnnotation; + export import FilePathAnnotation = MessagesAPI.FilePathAnnotation; + export import FilePathDeltaAnnotation = MessagesAPI.FilePathDeltaAnnotation; + export import ImageFile = MessagesAPI.ImageFile; + export import ImageFileContentBlock = MessagesAPI.ImageFileContentBlock; + export import ImageFileDelta = MessagesAPI.ImageFileDelta; + export import ImageFileDeltaBlock = MessagesAPI.ImageFileDeltaBlock; + export import Message = MessagesAPI.Message; + export import MessageContent = MessagesAPI.MessageContent; + export import MessageContentDelta = MessagesAPI.MessageContentDelta; + export import MessageDeleted = MessagesAPI.MessageDeleted; + export import MessageDelta = MessagesAPI.MessageDelta; + export import MessageDeltaEvent = MessagesAPI.MessageDeltaEvent; + export import Text = MessagesAPI.Text; + export import TextContentBlock = MessagesAPI.TextContentBlock; + export import TextDelta = MessagesAPI.TextDelta; + export import TextDeltaBlock = MessagesAPI.TextDeltaBlock; + export import MessagesPage = MessagesAPI.MessagesPage; + export import MessageCreateParams = MessagesAPI.MessageCreateParams; + export import MessageUpdateParams = MessagesAPI.MessageUpdateParams; + export import MessageListParams = MessagesAPI.MessageListParams; +} diff --git a/backend/node_modules/openai/src/resources/chat/chat.ts b/backend/node_modules/openai/src/resources/chat/chat.ts new file mode 100644 index 0000000000000000000000000000000000000000..9df92789133b72f140c2f3edcfeb4f24f5ea934b --- /dev/null +++ b/backend/node_modules/openai/src/resources/chat/chat.ts @@ -0,0 +1,41 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { APIResource } from "../../resource"; +import * as CompletionsAPI from "./completions"; + +export class Chat extends APIResource { + completions: CompletionsAPI.Completions = new CompletionsAPI.Completions(this._client); +} + +export namespace Chat { + export import Completions = CompletionsAPI.Completions; + export import ChatCompletion = CompletionsAPI.ChatCompletion; + export import ChatCompletionAssistantMessageParam = CompletionsAPI.ChatCompletionAssistantMessageParam; + export import ChatCompletionChunk = CompletionsAPI.ChatCompletionChunk; + export import ChatCompletionContentPart = CompletionsAPI.ChatCompletionContentPart; + export import ChatCompletionContentPartImage = CompletionsAPI.ChatCompletionContentPartImage; + export import ChatCompletionContentPartText = CompletionsAPI.ChatCompletionContentPartText; + export import ChatCompletionFunctionCallOption = CompletionsAPI.ChatCompletionFunctionCallOption; + export import ChatCompletionFunctionMessageParam = CompletionsAPI.ChatCompletionFunctionMessageParam; + export import ChatCompletionMessage = CompletionsAPI.ChatCompletionMessage; + export import ChatCompletionMessageParam = CompletionsAPI.ChatCompletionMessageParam; + export import ChatCompletionMessageToolCall = CompletionsAPI.ChatCompletionMessageToolCall; + export import ChatCompletionNamedToolChoice = CompletionsAPI.ChatCompletionNamedToolChoice; + export import ChatCompletionRole = CompletionsAPI.ChatCompletionRole; + export import ChatCompletionSystemMessageParam = CompletionsAPI.ChatCompletionSystemMessageParam; + export import ChatCompletionTokenLogprob = CompletionsAPI.ChatCompletionTokenLogprob; + export import ChatCompletionTool = CompletionsAPI.ChatCompletionTool; + export import ChatCompletionToolChoiceOption = CompletionsAPI.ChatCompletionToolChoiceOption; + export import ChatCompletionToolMessageParam = CompletionsAPI.ChatCompletionToolMessageParam; + export import ChatCompletionUserMessageParam = CompletionsAPI.ChatCompletionUserMessageParam; + /** + * @deprecated ChatCompletionMessageParam should be used instead + */ + export import CreateChatCompletionRequestMessage = CompletionsAPI.CreateChatCompletionRequestMessage; + export import ChatCompletionCreateParams = CompletionsAPI.ChatCompletionCreateParams; + export import CompletionCreateParams = CompletionsAPI.CompletionCreateParams; + export import ChatCompletionCreateParamsNonStreaming = CompletionsAPI.ChatCompletionCreateParamsNonStreaming; + export import CompletionCreateParamsNonStreaming = CompletionsAPI.CompletionCreateParamsNonStreaming; + export import ChatCompletionCreateParamsStreaming = CompletionsAPI.ChatCompletionCreateParamsStreaming; + export import CompletionCreateParamsStreaming = CompletionsAPI.CompletionCreateParamsStreaming; +} diff --git a/backend/node_modules/openai/src/resources/chat/completions.ts b/backend/node_modules/openai/src/resources/chat/completions.ts new file mode 100644 index 0000000000000000000000000000000000000000..e9866308499f389fcb3c6ee65b584e8b0fc5de31 --- /dev/null +++ b/backend/node_modules/openai/src/resources/chat/completions.ts @@ -0,0 +1,987 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import * as Core from "../../core"; +import { APIPromise } from "../../core"; +import { APIResource } from "../../resource"; +import * as ChatCompletionsAPI from "./completions"; +import * as CompletionsAPI from "../completions"; +import * as Shared from "../shared"; +import { Stream } from "../../streaming"; + +export class Completions extends APIResource { + /** + * Creates a model response for the given chat conversation. + */ + create( + body: ChatCompletionCreateParamsNonStreaming, + options?: Core.RequestOptions, + ): APIPromise; + create( + body: ChatCompletionCreateParamsStreaming, + options?: Core.RequestOptions, + ): APIPromise>; + create( + body: ChatCompletionCreateParamsBase, + options?: Core.RequestOptions, + ): APIPromise | ChatCompletion>; + create( + body: ChatCompletionCreateParams, + options?: Core.RequestOptions, + ): APIPromise | APIPromise> { + return this._client.post('/chat/completions', { body, ...options, stream: body.stream ?? false }) as + | APIPromise + | APIPromise>; + } +} + +/** + * Represents a chat completion response returned by model, based on the provided + * input. + */ +export interface ChatCompletion { + /** + * A unique identifier for the chat completion. + */ + id: string; + + /** + * A list of chat completion choices. Can be more than one if `n` is greater + * than 1. + */ + choices: Array; + + /** + * The Unix timestamp (in seconds) of when the chat completion was created. + */ + created: number; + + /** + * The model used for the chat completion. + */ + model: string; + + /** + * The object type, which is always `chat.completion`. + */ + object: 'chat.completion'; + + /** + * This fingerprint represents the backend configuration that the model runs with. + * + * Can be used in conjunction with the `seed` request parameter to understand when + * backend changes have been made that might impact determinism. + */ + system_fingerprint?: string; + + /** + * Usage statistics for the completion request. + */ + usage?: CompletionsAPI.CompletionUsage; +} + +export namespace ChatCompletion { + export interface Choice { + /** + * The reason the model stopped generating tokens. This will be `stop` if the model + * hit a natural stop point or a provided stop sequence, `length` if the maximum + * number of tokens specified in the request was reached, `content_filter` if + * content was omitted due to a flag from our content filters, `tool_calls` if the + * model called a tool, or `function_call` (deprecated) if the model called a + * function. + */ + finish_reason: 'stop' | 'length' | 'tool_calls' | 'content_filter' | 'function_call'; + + /** + * The index of the choice in the list of choices. + */ + index: number; + + /** + * Log probability information for the choice. + */ + logprobs: Choice.Logprobs | null; + + /** + * A chat completion message generated by the model. + */ + message: ChatCompletionsAPI.ChatCompletionMessage; + } + + export namespace Choice { + /** + * Log probability information for the choice. + */ + export interface Logprobs { + /** + * A list of message content tokens with log probability information. + */ + content: Array | null; + } + } +} + +export interface ChatCompletionAssistantMessageParam { + /** + * The role of the messages author, in this case `assistant`. + */ + role: 'assistant'; + + /** + * The contents of the assistant message. Required unless `tool_calls` or + * `function_call` is specified. + */ + content?: string | null; + + /** + * @deprecated: Deprecated and replaced by `tool_calls`. The name and arguments of + * a function that should be called, as generated by the model. + */ + function_call?: ChatCompletionAssistantMessageParam.FunctionCall; + + /** + * An optional name for the participant. Provides the model information to + * differentiate between participants of the same role. + */ + name?: string; + + /** + * The tool calls generated by the model, such as function calls. + */ + tool_calls?: Array; +} + +export namespace ChatCompletionAssistantMessageParam { + /** + * @deprecated: Deprecated and replaced by `tool_calls`. The name and arguments of + * a function that should be called, as generated by the model. + */ + export interface FunctionCall { + /** + * The arguments to call the function with, as generated by the model in JSON + * format. Note that the model does not always generate valid JSON, and may + * hallucinate parameters not defined by your function schema. Validate the + * arguments in your code before calling your function. + */ + arguments: string; + + /** + * The name of the function to call. + */ + name: string; + } +} + +/** + * Represents a streamed chunk of a chat completion response returned by model, + * based on the provided input. + */ +export interface ChatCompletionChunk { + /** + * A unique identifier for the chat completion. Each chunk has the same ID. + */ + id: string; + + /** + * A list of chat completion choices. Can be more than one if `n` is greater + * than 1. + */ + choices: Array; + + /** + * The Unix timestamp (in seconds) of when the chat completion was created. Each + * chunk has the same timestamp. + */ + created: number; + + /** + * The model to generate the completion. + */ + model: string; + + /** + * The object type, which is always `chat.completion.chunk`. + */ + object: 'chat.completion.chunk'; + + /** + * This fingerprint represents the backend configuration that the model runs with. + * Can be used in conjunction with the `seed` request parameter to understand when + * backend changes have been made that might impact determinism. + */ + system_fingerprint?: string; +} + +export namespace ChatCompletionChunk { + export interface Choice { + /** + * A chat completion delta generated by streamed model responses. + */ + delta: Choice.Delta; + + /** + * The reason the model stopped generating tokens. This will be `stop` if the model + * hit a natural stop point or a provided stop sequence, `length` if the maximum + * number of tokens specified in the request was reached, `content_filter` if + * content was omitted due to a flag from our content filters, `tool_calls` if the + * model called a tool, or `function_call` (deprecated) if the model called a + * function. + */ + finish_reason: 'stop' | 'length' | 'tool_calls' | 'content_filter' | 'function_call' | null; + + /** + * The index of the choice in the list of choices. + */ + index: number; + + /** + * Log probability information for the choice. + */ + logprobs?: Choice.Logprobs | null; + } + + export namespace Choice { + /** + * A chat completion delta generated by streamed model responses. + */ + export interface Delta { + /** + * The contents of the chunk message. + */ + content?: string | null; + + /** + * @deprecated: Deprecated and replaced by `tool_calls`. The name and arguments of + * a function that should be called, as generated by the model. + */ + function_call?: Delta.FunctionCall; + + /** + * The role of the author of this message. + */ + role?: 'system' | 'user' | 'assistant' | 'tool'; + + tool_calls?: Array; + } + + export namespace Delta { + /** + * @deprecated: Deprecated and replaced by `tool_calls`. The name and arguments of + * a function that should be called, as generated by the model. + */ + export interface FunctionCall { + /** + * The arguments to call the function with, as generated by the model in JSON + * format. Note that the model does not always generate valid JSON, and may + * hallucinate parameters not defined by your function schema. Validate the + * arguments in your code before calling your function. + */ + arguments?: string; + + /** + * The name of the function to call. + */ + name?: string; + } + + export interface ToolCall { + index: number; + + /** + * The ID of the tool call. + */ + id?: string; + + function?: ToolCall.Function; + + /** + * The type of the tool. Currently, only `function` is supported. + */ + type?: 'function'; + } + + export namespace ToolCall { + export interface Function { + /** + * The arguments to call the function with, as generated by the model in JSON + * format. Note that the model does not always generate valid JSON, and may + * hallucinate parameters not defined by your function schema. Validate the + * arguments in your code before calling your function. + */ + arguments?: string; + + /** + * The name of the function to call. + */ + name?: string; + } + } + } + + /** + * Log probability information for the choice. + */ + export interface Logprobs { + /** + * A list of message content tokens with log probability information. + */ + content: Array | null; + } + } +} + +export type ChatCompletionContentPart = ChatCompletionContentPartText | ChatCompletionContentPartImage; + +export interface ChatCompletionContentPartImage { + image_url: ChatCompletionContentPartImage.ImageURL; + + /** + * The type of the content part. + */ + type: 'image_url'; +} + +export namespace ChatCompletionContentPartImage { + export interface ImageURL { + /** + * Either a URL of the image or the base64 encoded image data. + */ + url: string; + + /** + * Specifies the detail level of the image. Learn more in the + * [Vision guide](https://platform.openai.com/docs/guides/vision/low-or-high-fidelity-image-understanding). + */ + detail?: 'auto' | 'low' | 'high'; + } +} + +export interface ChatCompletionContentPartText { + /** + * The text content. + */ + text: string; + + /** + * The type of the content part. + */ + type: 'text'; +} + +/** + * Specifying a particular function via `{"name": "my_function"}` forces the model + * to call that function. + */ +export interface ChatCompletionFunctionCallOption { + /** + * The name of the function to call. + */ + name: string; +} + +/** + * @deprecated + */ +export interface ChatCompletionFunctionMessageParam { + /** + * The contents of the function message. + */ + content: string | null; + + /** + * The name of the function to call. + */ + name: string; + + /** + * The role of the messages author, in this case `function`. + */ + role: 'function'; +} + +/** + * A chat completion message generated by the model. + */ +export interface ChatCompletionMessage { + /** + * The contents of the message. + */ + content: string | null; + + /** + * The role of the author of this message. + */ + role: 'assistant'; + + /** + * @deprecated: Deprecated and replaced by `tool_calls`. The name and arguments of + * a function that should be called, as generated by the model. + */ + function_call?: ChatCompletionMessage.FunctionCall; + + /** + * The tool calls generated by the model, such as function calls. + */ + tool_calls?: Array; +} + +export namespace ChatCompletionMessage { + /** + * @deprecated: Deprecated and replaced by `tool_calls`. The name and arguments of + * a function that should be called, as generated by the model. + */ + export interface FunctionCall { + /** + * The arguments to call the function with, as generated by the model in JSON + * format. Note that the model does not always generate valid JSON, and may + * hallucinate parameters not defined by your function schema. Validate the + * arguments in your code before calling your function. + */ + arguments: string; + + /** + * The name of the function to call. + */ + name: string; + } +} + +export type ChatCompletionMessageParam = + | ChatCompletionSystemMessageParam + | ChatCompletionUserMessageParam + | ChatCompletionAssistantMessageParam + | ChatCompletionToolMessageParam + | ChatCompletionFunctionMessageParam; + +export interface ChatCompletionMessageToolCall { + /** + * The ID of the tool call. + */ + id: string; + + /** + * The function that the model called. + */ + function: ChatCompletionMessageToolCall.Function; + + /** + * The type of the tool. Currently, only `function` is supported. + */ + type: 'function'; +} + +export namespace ChatCompletionMessageToolCall { + /** + * The function that the model called. + */ + export interface Function { + /** + * The arguments to call the function with, as generated by the model in JSON + * format. Note that the model does not always generate valid JSON, and may + * hallucinate parameters not defined by your function schema. Validate the + * arguments in your code before calling your function. + */ + arguments: string; + + /** + * The name of the function to call. + */ + name: string; + } +} + +/** + * Specifies a tool the model should use. Use to force the model to call a specific + * function. + */ +export interface ChatCompletionNamedToolChoice { + function: ChatCompletionNamedToolChoice.Function; + + /** + * The type of the tool. Currently, only `function` is supported. + */ + type: 'function'; +} + +export namespace ChatCompletionNamedToolChoice { + export interface Function { + /** + * The name of the function to call. + */ + name: string; + } +} + +/** + * The role of the author of a message + */ +export type ChatCompletionRole = 'system' | 'user' | 'assistant' | 'tool' | 'function'; + +export interface ChatCompletionSystemMessageParam { + /** + * The contents of the system message. + */ + content: string; + + /** + * The role of the messages author, in this case `system`. + */ + role: 'system'; + + /** + * An optional name for the participant. Provides the model information to + * differentiate between participants of the same role. + */ + name?: string; +} + +export interface ChatCompletionTokenLogprob { + /** + * The token. + */ + token: string; + + /** + * A list of integers representing the UTF-8 bytes representation of the token. + * Useful in instances where characters are represented by multiple tokens and + * their byte representations must be combined to generate the correct text + * representation. Can be `null` if there is no bytes representation for the token. + */ + bytes: Array | null; + + /** + * The log probability of this token, if it is within the top 20 most likely + * tokens. Otherwise, the value `-9999.0` is used to signify that the token is very + * unlikely. + */ + logprob: number; + + /** + * List of the most likely tokens and their log probability, at this token + * position. In rare cases, there may be fewer than the number of requested + * `top_logprobs` returned. + */ + top_logprobs: Array; +} + +export namespace ChatCompletionTokenLogprob { + export interface TopLogprob { + /** + * The token. + */ + token: string; + + /** + * A list of integers representing the UTF-8 bytes representation of the token. + * Useful in instances where characters are represented by multiple tokens and + * their byte representations must be combined to generate the correct text + * representation. Can be `null` if there is no bytes representation for the token. + */ + bytes: Array | null; + + /** + * The log probability of this token, if it is within the top 20 most likely + * tokens. Otherwise, the value `-9999.0` is used to signify that the token is very + * unlikely. + */ + logprob: number; + } +} + +export interface ChatCompletionTool { + function: Shared.FunctionDefinition; + + /** + * The type of the tool. Currently, only `function` is supported. + */ + type: 'function'; +} + +/** + * Controls which (if any) function is called by the model. `none` means the model + * will not call a function and instead generates a message. `auto` means the model + * can pick between generating a message or calling a function. Specifying a + * particular function via + * `{"type": "function", "function": {"name": "my_function"}}` forces the model to + * call that function. + * + * `none` is the default when no functions are present. `auto` is the default if + * functions are present. + */ +export type ChatCompletionToolChoiceOption = 'none' | 'auto' | ChatCompletionNamedToolChoice; + +export interface ChatCompletionToolMessageParam { + /** + * The contents of the tool message. + */ + content: string; + + /** + * The role of the messages author, in this case `tool`. + */ + role: 'tool'; + + /** + * Tool call that this message is responding to. + */ + tool_call_id: string; +} + +export interface ChatCompletionUserMessageParam { + /** + * The contents of the user message. + */ + content: string | Array; + + /** + * The role of the messages author, in this case `user`. + */ + role: 'user'; + + /** + * An optional name for the participant. Provides the model information to + * differentiate between participants of the same role. + */ + name?: string; +} + +/** + * @deprecated ChatCompletionMessageParam should be used instead + */ +export type CreateChatCompletionRequestMessage = ChatCompletionMessageParam; + +export type ChatCompletionCreateParams = + | ChatCompletionCreateParamsNonStreaming + | ChatCompletionCreateParamsStreaming; + +export interface ChatCompletionCreateParamsBase { + /** + * A list of messages comprising the conversation so far. + * [Example Python code](https://cookbook.openai.com/examples/how_to_format_inputs_to_chatgpt_models). + */ + messages: Array; + + /** + * ID of the model to use. See the + * [model endpoint compatibility](https://platform.openai.com/docs/models/model-endpoint-compatibility) + * table for details on which models work with the Chat API. + */ + model: + | (string & {}) + | 'gpt-4-turbo' + | 'gpt-4-turbo-2024-04-09' + | 'gpt-4-0125-preview' + | 'gpt-4-turbo-preview' + | 'gpt-4-1106-preview' + | 'gpt-4-vision-preview' + | 'gpt-4' + | 'gpt-4-0314' + | 'gpt-4-0613' + | 'gpt-4-32k' + | 'gpt-4-32k-0314' + | 'gpt-4-32k-0613' + | 'gpt-3.5-turbo' + | 'gpt-3.5-turbo-16k' + | 'gpt-3.5-turbo-0301' + | 'gpt-3.5-turbo-0613' + | 'gpt-3.5-turbo-1106' + | 'gpt-3.5-turbo-0125' + | 'gpt-3.5-turbo-16k-0613'; + + /** + * Number between -2.0 and 2.0. Positive values penalize new tokens based on their + * existing frequency in the text so far, decreasing the model's likelihood to + * repeat the same line verbatim. + * + * [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) + */ + frequency_penalty?: number | null; + + /** + * Deprecated in favor of `tool_choice`. + * + * Controls which (if any) function is called by the model. `none` means the model + * will not call a function and instead generates a message. `auto` means the model + * can pick between generating a message or calling a function. Specifying a + * particular function via `{"name": "my_function"}` forces the model to call that + * function. + * + * `none` is the default when no functions are present. `auto` is the default if + * functions are present. + */ + function_call?: 'none' | 'auto' | ChatCompletionFunctionCallOption; + + /** + * Deprecated in favor of `tools`. + * + * A list of functions the model may generate JSON inputs for. + */ + functions?: Array; + + /** + * Modify the likelihood of specified tokens appearing in the completion. + * + * Accepts a JSON object that maps tokens (specified by their token ID in the + * tokenizer) to an associated bias value from -100 to 100. Mathematically, the + * bias is added to the logits generated by the model prior to sampling. The exact + * effect will vary per model, but values between -1 and 1 should decrease or + * increase likelihood of selection; values like -100 or 100 should result in a ban + * or exclusive selection of the relevant token. + */ + logit_bias?: Record | null; + + /** + * Whether to return log probabilities of the output tokens or not. If true, + * returns the log probabilities of each output token returned in the `content` of + * `message`. + */ + logprobs?: boolean | null; + + /** + * The maximum number of [tokens](/tokenizer) that can be generated in the chat + * completion. + * + * The total length of input tokens and generated tokens is limited by the model's + * context length. + * [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) + * for counting tokens. + */ + max_tokens?: number | null; + + /** + * How many chat completion choices to generate for each input message. Note that + * you will be charged based on the number of generated tokens across all of the + * choices. Keep `n` as `1` to minimize costs. + */ + n?: number | null; + + /** + * Number between -2.0 and 2.0. Positive values penalize new tokens based on + * whether they appear in the text so far, increasing the model's likelihood to + * talk about new topics. + * + * [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) + */ + presence_penalty?: number | null; + + /** + * An object specifying the format that the model must output. Compatible with + * [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and + * all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + * + * Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + * message the model generates is valid JSON. + * + * **Important:** when using JSON mode, you **must** also instruct the model to + * produce JSON yourself via a system or user message. Without this, the model may + * generate an unending stream of whitespace until the generation reaches the token + * limit, resulting in a long-running and seemingly "stuck" request. Also note that + * the message content may be partially cut off if `finish_reason="length"`, which + * indicates the generation exceeded `max_tokens` or the conversation exceeded the + * max context length. + */ + response_format?: ChatCompletionCreateParams.ResponseFormat; + + /** + * This feature is in Beta. If specified, our system will make a best effort to + * sample deterministically, such that repeated requests with the same `seed` and + * parameters should return the same result. Determinism is not guaranteed, and you + * should refer to the `system_fingerprint` response parameter to monitor changes + * in the backend. + */ + seed?: number | null; + + /** + * Up to 4 sequences where the API will stop generating further tokens. + */ + stop?: string | null | Array; + + /** + * If set, partial message deltas will be sent, like in ChatGPT. Tokens will be + * sent as data-only + * [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) + * as they become available, with the stream terminated by a `data: [DONE]` + * message. + * [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions). + */ + stream?: boolean | null; + + /** + * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + * make the output more random, while lower values like 0.2 will make it more + * focused and deterministic. + * + * We generally recommend altering this or `top_p` but not both. + */ + temperature?: number | null; + + /** + * Controls which (if any) function is called by the model. `none` means the model + * will not call a function and instead generates a message. `auto` means the model + * can pick between generating a message or calling a function. Specifying a + * particular function via + * `{"type": "function", "function": {"name": "my_function"}}` forces the model to + * call that function. + * + * `none` is the default when no functions are present. `auto` is the default if + * functions are present. + */ + tool_choice?: ChatCompletionToolChoiceOption; + + /** + * A list of tools the model may call. Currently, only functions are supported as a + * tool. Use this to provide a list of functions the model may generate JSON inputs + * for. A max of 128 functions are supported. + */ + tools?: Array; + + /** + * An integer between 0 and 20 specifying the number of most likely tokens to + * return at each token position, each with an associated log probability. + * `logprobs` must be set to `true` if this parameter is used. + */ + top_logprobs?: number | null; + + /** + * An alternative to sampling with temperature, called nucleus sampling, where the + * model considers the results of the tokens with top_p probability mass. So 0.1 + * means only the tokens comprising the top 10% probability mass are considered. + * + * We generally recommend altering this or `temperature` but not both. + */ + top_p?: number | null; + + /** + * A unique identifier representing your end-user, which can help OpenAI to monitor + * and detect abuse. + * [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + */ + user?: string; +} + +export namespace ChatCompletionCreateParams { + /** + * @deprecated + */ + export interface Function { + /** + * The name of the function to be called. Must be a-z, A-Z, 0-9, or contain + * underscores and dashes, with a maximum length of 64. + */ + name: string; + + /** + * A description of what the function does, used by the model to choose when and + * how to call the function. + */ + description?: string; + + /** + * The parameters the functions accepts, described as a JSON Schema object. See the + * [guide](https://platform.openai.com/docs/guides/text-generation/function-calling) + * for examples, and the + * [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for + * documentation about the format. + * + * Omitting `parameters` defines a function with an empty parameter list. + */ + parameters?: Shared.FunctionParameters; + } + + /** + * An object specifying the format that the model must output. Compatible with + * [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and + * all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + * + * Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + * message the model generates is valid JSON. + * + * **Important:** when using JSON mode, you **must** also instruct the model to + * produce JSON yourself via a system or user message. Without this, the model may + * generate an unending stream of whitespace until the generation reaches the token + * limit, resulting in a long-running and seemingly "stuck" request. Also note that + * the message content may be partially cut off if `finish_reason="length"`, which + * indicates the generation exceeded `max_tokens` or the conversation exceeded the + * max context length. + */ + export interface ResponseFormat { + /** + * Must be one of `text` or `json_object`. + */ + type?: 'text' | 'json_object'; + } + + export type ChatCompletionCreateParamsNonStreaming = + ChatCompletionsAPI.ChatCompletionCreateParamsNonStreaming; + export type ChatCompletionCreateParamsStreaming = ChatCompletionsAPI.ChatCompletionCreateParamsStreaming; +} + +/** + * @deprecated Use ChatCompletionCreateParams instead + */ +export type CompletionCreateParams = ChatCompletionCreateParams; + +export interface ChatCompletionCreateParamsNonStreaming extends ChatCompletionCreateParamsBase { + /** + * If set, partial message deltas will be sent, like in ChatGPT. Tokens will be + * sent as data-only + * [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) + * as they become available, with the stream terminated by a `data: [DONE]` + * message. + * [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions). + */ + stream?: false | null; +} + +/** + * @deprecated Use ChatCompletionCreateParamsNonStreaming instead + */ +export type CompletionCreateParamsNonStreaming = ChatCompletionCreateParamsNonStreaming; + +export interface ChatCompletionCreateParamsStreaming extends ChatCompletionCreateParamsBase { + /** + * If set, partial message deltas will be sent, like in ChatGPT. Tokens will be + * sent as data-only + * [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) + * as they become available, with the stream terminated by a `data: [DONE]` + * message. + * [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions). + */ + stream: true; +} + +/** + * @deprecated Use ChatCompletionCreateParamsStreaming instead + */ +export type CompletionCreateParamsStreaming = ChatCompletionCreateParamsStreaming; + +export namespace Completions { + export import ChatCompletion = ChatCompletionsAPI.ChatCompletion; + export import ChatCompletionAssistantMessageParam = ChatCompletionsAPI.ChatCompletionAssistantMessageParam; + export import ChatCompletionChunk = ChatCompletionsAPI.ChatCompletionChunk; + export import ChatCompletionContentPart = ChatCompletionsAPI.ChatCompletionContentPart; + export import ChatCompletionContentPartImage = ChatCompletionsAPI.ChatCompletionContentPartImage; + export import ChatCompletionContentPartText = ChatCompletionsAPI.ChatCompletionContentPartText; + export import ChatCompletionFunctionCallOption = ChatCompletionsAPI.ChatCompletionFunctionCallOption; + export import ChatCompletionFunctionMessageParam = ChatCompletionsAPI.ChatCompletionFunctionMessageParam; + export import ChatCompletionMessage = ChatCompletionsAPI.ChatCompletionMessage; + export import ChatCompletionMessageParam = ChatCompletionsAPI.ChatCompletionMessageParam; + export import ChatCompletionMessageToolCall = ChatCompletionsAPI.ChatCompletionMessageToolCall; + export import ChatCompletionNamedToolChoice = ChatCompletionsAPI.ChatCompletionNamedToolChoice; + export import ChatCompletionRole = ChatCompletionsAPI.ChatCompletionRole; + export import ChatCompletionSystemMessageParam = ChatCompletionsAPI.ChatCompletionSystemMessageParam; + export import ChatCompletionTokenLogprob = ChatCompletionsAPI.ChatCompletionTokenLogprob; + export import ChatCompletionTool = ChatCompletionsAPI.ChatCompletionTool; + export import ChatCompletionToolChoiceOption = ChatCompletionsAPI.ChatCompletionToolChoiceOption; + export import ChatCompletionToolMessageParam = ChatCompletionsAPI.ChatCompletionToolMessageParam; + export import ChatCompletionUserMessageParam = ChatCompletionsAPI.ChatCompletionUserMessageParam; + /** + * @deprecated ChatCompletionMessageParam should be used instead + */ + export import CreateChatCompletionRequestMessage = ChatCompletionsAPI.CreateChatCompletionRequestMessage; + export import ChatCompletionCreateParams = ChatCompletionsAPI.ChatCompletionCreateParams; + export import CompletionCreateParams = ChatCompletionsAPI.CompletionCreateParams; + export import ChatCompletionCreateParamsNonStreaming = ChatCompletionsAPI.ChatCompletionCreateParamsNonStreaming; + export import CompletionCreateParamsNonStreaming = ChatCompletionsAPI.CompletionCreateParamsNonStreaming; + export import ChatCompletionCreateParamsStreaming = ChatCompletionsAPI.ChatCompletionCreateParamsStreaming; + export import CompletionCreateParamsStreaming = ChatCompletionsAPI.CompletionCreateParamsStreaming; +} diff --git a/backend/node_modules/openai/src/resources/chat/index.ts b/backend/node_modules/openai/src/resources/chat/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..78a7516edd0275fd547682157a48ae40cebe9a3a --- /dev/null +++ b/backend/node_modules/openai/src/resources/chat/index.ts @@ -0,0 +1,32 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export { Chat } from './chat'; +export { + ChatCompletion, + ChatCompletionAssistantMessageParam, + ChatCompletionChunk, + ChatCompletionContentPart, + ChatCompletionContentPartImage, + ChatCompletionContentPartText, + ChatCompletionFunctionCallOption, + ChatCompletionFunctionMessageParam, + ChatCompletionMessage, + ChatCompletionMessageParam, + ChatCompletionMessageToolCall, + ChatCompletionNamedToolChoice, + ChatCompletionRole, + ChatCompletionSystemMessageParam, + ChatCompletionTokenLogprob, + ChatCompletionTool, + ChatCompletionToolChoiceOption, + ChatCompletionToolMessageParam, + ChatCompletionUserMessageParam, + CreateChatCompletionRequestMessage, + ChatCompletionCreateParams, + CompletionCreateParams, + ChatCompletionCreateParamsNonStreaming, + CompletionCreateParamsNonStreaming, + ChatCompletionCreateParamsStreaming, + CompletionCreateParamsStreaming, + Completions, +} from './completions'; diff --git a/backend/node_modules/openai/src/resources/completions.ts b/backend/node_modules/openai/src/resources/completions.ts new file mode 100644 index 0000000000000000000000000000000000000000..737e01282e1fe3cbd3190aead9ef0de7e9879cb8 --- /dev/null +++ b/backend/node_modules/openai/src/resources/completions.ts @@ -0,0 +1,323 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import * as Core from "../core"; +import { APIPromise } from "../core"; +import { APIResource } from "../resource"; +import * as CompletionsAPI from "./completions"; +import { Stream } from "../streaming"; + +export class Completions extends APIResource { + /** + * Creates a completion for the provided prompt and parameters. + */ + create(body: CompletionCreateParamsNonStreaming, options?: Core.RequestOptions): APIPromise; + create( + body: CompletionCreateParamsStreaming, + options?: Core.RequestOptions, + ): APIPromise>; + create( + body: CompletionCreateParamsBase, + options?: Core.RequestOptions, + ): APIPromise | Completion>; + create( + body: CompletionCreateParams, + options?: Core.RequestOptions, + ): APIPromise | APIPromise> { + return this._client.post('/completions', { body, ...options, stream: body.stream ?? false }) as + | APIPromise + | APIPromise>; + } +} + +/** + * Represents a completion response from the API. Note: both the streamed and + * non-streamed response objects share the same shape (unlike the chat endpoint). + */ +export interface Completion { + /** + * A unique identifier for the completion. + */ + id: string; + + /** + * The list of completion choices the model generated for the input prompt. + */ + choices: Array; + + /** + * The Unix timestamp (in seconds) of when the completion was created. + */ + created: number; + + /** + * The model used for completion. + */ + model: string; + + /** + * The object type, which is always "text_completion" + */ + object: 'text_completion'; + + /** + * This fingerprint represents the backend configuration that the model runs with. + * + * Can be used in conjunction with the `seed` request parameter to understand when + * backend changes have been made that might impact determinism. + */ + system_fingerprint?: string; + + /** + * Usage statistics for the completion request. + */ + usage?: CompletionUsage; +} + +export interface CompletionChoice { + /** + * The reason the model stopped generating tokens. This will be `stop` if the model + * hit a natural stop point or a provided stop sequence, `length` if the maximum + * number of tokens specified in the request was reached, or `content_filter` if + * content was omitted due to a flag from our content filters. + */ + finish_reason: 'stop' | 'length' | 'content_filter'; + + index: number; + + logprobs: CompletionChoice.Logprobs | null; + + text: string; +} + +export namespace CompletionChoice { + export interface Logprobs { + text_offset?: Array; + + token_logprobs?: Array; + + tokens?: Array; + + top_logprobs?: Array>; + } +} + +/** + * Usage statistics for the completion request. + */ +export interface CompletionUsage { + /** + * Number of tokens in the generated completion. + */ + completion_tokens: number; + + /** + * Number of tokens in the prompt. + */ + prompt_tokens: number; + + /** + * Total number of tokens used in the request (prompt + completion). + */ + total_tokens: number; +} + +export type CompletionCreateParams = CompletionCreateParamsNonStreaming | CompletionCreateParamsStreaming; + +export interface CompletionCreateParamsBase { + /** + * ID of the model to use. You can use the + * [List models](https://platform.openai.com/docs/api-reference/models/list) API to + * see all of your available models, or see our + * [Model overview](https://platform.openai.com/docs/models/overview) for + * descriptions of them. + */ + model: (string & {}) | 'gpt-3.5-turbo-instruct' | 'davinci-002' | 'babbage-002'; + + /** + * The prompt(s) to generate completions for, encoded as a string, array of + * strings, array of tokens, or array of token arrays. + * + * Note that <|endoftext|> is the document separator that the model sees during + * training, so if a prompt is not specified the model will generate as if from the + * beginning of a new document. + */ + prompt: string | Array | Array | Array> | null; + + /** + * Generates `best_of` completions server-side and returns the "best" (the one with + * the highest log probability per token). Results cannot be streamed. + * + * When used with `n`, `best_of` controls the number of candidate completions and + * `n` specifies how many to return – `best_of` must be greater than `n`. + * + * **Note:** Because this parameter generates many completions, it can quickly + * consume your token quota. Use carefully and ensure that you have reasonable + * settings for `max_tokens` and `stop`. + */ + best_of?: number | null; + + /** + * Echo back the prompt in addition to the completion + */ + echo?: boolean | null; + + /** + * Number between -2.0 and 2.0. Positive values penalize new tokens based on their + * existing frequency in the text so far, decreasing the model's likelihood to + * repeat the same line verbatim. + * + * [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) + */ + frequency_penalty?: number | null; + + /** + * Modify the likelihood of specified tokens appearing in the completion. + * + * Accepts a JSON object that maps tokens (specified by their token ID in the GPT + * tokenizer) to an associated bias value from -100 to 100. You can use this + * [tokenizer tool](/tokenizer?view=bpe) to convert text to token IDs. + * Mathematically, the bias is added to the logits generated by the model prior to + * sampling. The exact effect will vary per model, but values between -1 and 1 + * should decrease or increase likelihood of selection; values like -100 or 100 + * should result in a ban or exclusive selection of the relevant token. + * + * As an example, you can pass `{"50256": -100}` to prevent the <|endoftext|> token + * from being generated. + */ + logit_bias?: Record | null; + + /** + * Include the log probabilities on the `logprobs` most likely output tokens, as + * well the chosen tokens. For example, if `logprobs` is 5, the API will return a + * list of the 5 most likely tokens. The API will always return the `logprob` of + * the sampled token, so there may be up to `logprobs+1` elements in the response. + * + * The maximum value for `logprobs` is 5. + */ + logprobs?: number | null; + + /** + * The maximum number of [tokens](/tokenizer) that can be generated in the + * completion. + * + * The token count of your prompt plus `max_tokens` cannot exceed the model's + * context length. + * [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) + * for counting tokens. + */ + max_tokens?: number | null; + + /** + * How many completions to generate for each prompt. + * + * **Note:** Because this parameter generates many completions, it can quickly + * consume your token quota. Use carefully and ensure that you have reasonable + * settings for `max_tokens` and `stop`. + */ + n?: number | null; + + /** + * Number between -2.0 and 2.0. Positive values penalize new tokens based on + * whether they appear in the text so far, increasing the model's likelihood to + * talk about new topics. + * + * [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) + */ + presence_penalty?: number | null; + + /** + * If specified, our system will make a best effort to sample deterministically, + * such that repeated requests with the same `seed` and parameters should return + * the same result. + * + * Determinism is not guaranteed, and you should refer to the `system_fingerprint` + * response parameter to monitor changes in the backend. + */ + seed?: number | null; + + /** + * Up to 4 sequences where the API will stop generating further tokens. The + * returned text will not contain the stop sequence. + */ + stop?: string | null | Array; + + /** + * Whether to stream back partial progress. If set, tokens will be sent as + * data-only + * [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) + * as they become available, with the stream terminated by a `data: [DONE]` + * message. + * [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions). + */ + stream?: boolean | null; + + /** + * The suffix that comes after a completion of inserted text. + * + * This parameter is only supported for `gpt-3.5-turbo-instruct`. + */ + suffix?: string | null; + + /** + * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + * make the output more random, while lower values like 0.2 will make it more + * focused and deterministic. + * + * We generally recommend altering this or `top_p` but not both. + */ + temperature?: number | null; + + /** + * An alternative to sampling with temperature, called nucleus sampling, where the + * model considers the results of the tokens with top_p probability mass. So 0.1 + * means only the tokens comprising the top 10% probability mass are considered. + * + * We generally recommend altering this or `temperature` but not both. + */ + top_p?: number | null; + + /** + * A unique identifier representing your end-user, which can help OpenAI to monitor + * and detect abuse. + * [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + */ + user?: string; +} + +export namespace CompletionCreateParams { + export type CompletionCreateParamsNonStreaming = CompletionsAPI.CompletionCreateParamsNonStreaming; + export type CompletionCreateParamsStreaming = CompletionsAPI.CompletionCreateParamsStreaming; +} + +export interface CompletionCreateParamsNonStreaming extends CompletionCreateParamsBase { + /** + * Whether to stream back partial progress. If set, tokens will be sent as + * data-only + * [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) + * as they become available, with the stream terminated by a `data: [DONE]` + * message. + * [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions). + */ + stream?: false | null; +} + +export interface CompletionCreateParamsStreaming extends CompletionCreateParamsBase { + /** + * Whether to stream back partial progress. If set, tokens will be sent as + * data-only + * [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) + * as they become available, with the stream terminated by a `data: [DONE]` + * message. + * [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions). + */ + stream: true; +} + +export namespace Completions { + export import Completion = CompletionsAPI.Completion; + export import CompletionChoice = CompletionsAPI.CompletionChoice; + export import CompletionUsage = CompletionsAPI.CompletionUsage; + export import CompletionCreateParams = CompletionsAPI.CompletionCreateParams; + export import CompletionCreateParamsNonStreaming = CompletionsAPI.CompletionCreateParamsNonStreaming; + export import CompletionCreateParamsStreaming = CompletionsAPI.CompletionCreateParamsStreaming; +} diff --git a/backend/node_modules/openai/src/resources/embeddings.ts b/backend/node_modules/openai/src/resources/embeddings.ts new file mode 100644 index 0000000000000000000000000000000000000000..28fb71d52232564d66172e7463b3928f73fdf7ee --- /dev/null +++ b/backend/node_modules/openai/src/resources/embeddings.ts @@ -0,0 +1,125 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import * as Core from "../core"; +import { APIResource } from "../resource"; +import * as EmbeddingsAPI from "./embeddings"; + +export class Embeddings extends APIResource { + /** + * Creates an embedding vector representing the input text. + */ + create( + body: EmbeddingCreateParams, + options?: Core.RequestOptions, + ): Core.APIPromise { + return this._client.post('/embeddings', { body, ...options }); + } +} + +export interface CreateEmbeddingResponse { + /** + * The list of embeddings generated by the model. + */ + data: Array; + + /** + * The name of the model used to generate the embedding. + */ + model: string; + + /** + * The object type, which is always "list". + */ + object: 'list'; + + /** + * The usage information for the request. + */ + usage: CreateEmbeddingResponse.Usage; +} + +export namespace CreateEmbeddingResponse { + /** + * The usage information for the request. + */ + export interface Usage { + /** + * The number of tokens used by the prompt. + */ + prompt_tokens: number; + + /** + * The total number of tokens used by the request. + */ + total_tokens: number; + } +} + +/** + * Represents an embedding vector returned by embedding endpoint. + */ +export interface Embedding { + /** + * The embedding vector, which is a list of floats. The length of vector depends on + * the model as listed in the + * [embedding guide](https://platform.openai.com/docs/guides/embeddings). + */ + embedding: Array; + + /** + * The index of the embedding in the list of embeddings. + */ + index: number; + + /** + * The object type, which is always "embedding". + */ + object: 'embedding'; +} + +export interface EmbeddingCreateParams { + /** + * Input text to embed, encoded as a string or array of tokens. To embed multiple + * inputs in a single request, pass an array of strings or array of token arrays. + * The input must not exceed the max input tokens for the model (8192 tokens for + * `text-embedding-ada-002`), cannot be an empty string, and any array must be 2048 + * dimensions or less. + * [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) + * for counting tokens. + */ + input: string | Array | Array | Array>; + + /** + * ID of the model to use. You can use the + * [List models](https://platform.openai.com/docs/api-reference/models/list) API to + * see all of your available models, or see our + * [Model overview](https://platform.openai.com/docs/models/overview) for + * descriptions of them. + */ + model: (string & {}) | 'text-embedding-ada-002' | 'text-embedding-3-small' | 'text-embedding-3-large'; + + /** + * The number of dimensions the resulting output embeddings should have. Only + * supported in `text-embedding-3` and later models. + */ + dimensions?: number; + + /** + * The format to return the embeddings in. Can be either `float` or + * [`base64`](https://pypi.org/project/pybase64/). + */ + encoding_format?: 'float' | 'base64'; + + /** + * A unique identifier representing your end-user, which can help OpenAI to monitor + * and detect abuse. + * [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + */ + user?: string; +} + +export namespace Embeddings { + export import CreateEmbeddingResponse = EmbeddingsAPI.CreateEmbeddingResponse; + export import Embedding = EmbeddingsAPI.Embedding; + export import EmbeddingCreateParams = EmbeddingsAPI.EmbeddingCreateParams; +} diff --git a/backend/node_modules/openai/src/resources/files.ts b/backend/node_modules/openai/src/resources/files.ts new file mode 100644 index 0000000000000000000000000000000000000000..21d9eb957368af214c2296c05af3334ca2a6dbd1 --- /dev/null +++ b/backend/node_modules/openai/src/resources/files.ts @@ -0,0 +1,202 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import * as Core from "../core"; +import { APIResource } from "../resource"; +import { isRequestOptions } from "../core"; +import { type Response } from "../_shims/index"; +import { sleep } from "../core"; +import { APIConnectionTimeoutError } from "../error"; +import * as FilesAPI from "./files"; +import { type Uploadable, multipartFormRequestOptions } from "../core"; +import { Page } from "../pagination"; + +export class Files extends APIResource { + /** + * Upload a file that can be used across various endpoints. The size of all the + * files uploaded by one organization can be up to 100 GB. + * + * The size of individual files can be a maximum of 512 MB or 2 million tokens for + * Assistants. See the + * [Assistants Tools guide](https://platform.openai.com/docs/assistants/tools) to + * learn more about the types of files supported. The Fine-tuning API only supports + * `.jsonl` files. + * + * Please [contact us](https://help.openai.com/) if you need to increase these + * storage limits. + */ + create(body: FileCreateParams, options?: Core.RequestOptions): Core.APIPromise { + return this._client.post('/files', multipartFormRequestOptions({ body, ...options })); + } + + /** + * Returns information about a specific file. + */ + retrieve(fileId: string, options?: Core.RequestOptions): Core.APIPromise { + return this._client.get(`/files/${fileId}`, options); + } + + /** + * Returns a list of files that belong to the user's organization. + */ + list(query?: FileListParams, options?: Core.RequestOptions): Core.PagePromise; + list(options?: Core.RequestOptions): Core.PagePromise; + list( + query: FileListParams | Core.RequestOptions = {}, + options?: Core.RequestOptions, + ): Core.PagePromise { + if (isRequestOptions(query)) { + return this.list({}, query); + } + return this._client.getAPIList('/files', FileObjectsPage, { query, ...options }); + } + + /** + * Delete a file. + */ + del(fileId: string, options?: Core.RequestOptions): Core.APIPromise { + return this._client.delete(`/files/${fileId}`, options); + } + + /** + * Returns the contents of the specified file. + */ + content(fileId: string, options?: Core.RequestOptions): Core.APIPromise { + return this._client.get(`/files/${fileId}/content`, { ...options, __binaryResponse: true }); + } + + /** + * Returns the contents of the specified file. + * + * @deprecated The `.content()` method should be used instead + */ + retrieveContent(fileId: string, options?: Core.RequestOptions): Core.APIPromise { + return this._client.get(`/files/${fileId}/content`, { + ...options, + headers: { Accept: 'application/json', ...options?.headers }, + }); + } + + /** + * Waits for the given file to be processed, default timeout is 30 mins. + */ + async waitForProcessing( + id: string, + { pollInterval = 5000, maxWait = 30 * 60 * 1000 }: { pollInterval?: number; maxWait?: number } = {}, + ): Promise { + const TERMINAL_STATES = new Set(['processed', 'error', 'deleted']); + + const start = Date.now(); + let file = await this.retrieve(id); + + while (!file.status || !TERMINAL_STATES.has(file.status)) { + await sleep(pollInterval); + + file = await this.retrieve(id); + if (Date.now() - start > maxWait) { + throw new APIConnectionTimeoutError({ + message: `Giving up on waiting for file ${id} to finish processing after ${maxWait} milliseconds.`, + }); + } + } + + return file; + } +} + +/** + * Note: no pagination actually occurs yet, this is for forwards-compatibility. + */ +export class FileObjectsPage extends Page {} + +export type FileContent = string; + +export interface FileDeleted { + id: string; + + deleted: boolean; + + object: 'file'; +} + +/** + * The `File` object represents a document that has been uploaded to OpenAI. + */ +export interface FileObject { + /** + * The file identifier, which can be referenced in the API endpoints. + */ + id: string; + + /** + * The size of the file, in bytes. + */ + bytes: number; + + /** + * The Unix timestamp (in seconds) for when the file was created. + */ + created_at: number; + + /** + * The name of the file. + */ + filename: string; + + /** + * The object type, which is always `file`. + */ + object: 'file'; + + /** + * The intended purpose of the file. Supported values are `fine-tune`, + * `fine-tune-results`, `assistants`, and `assistants_output`. + */ + purpose: 'fine-tune' | 'fine-tune-results' | 'assistants' | 'assistants_output'; + + /** + * @deprecated: Deprecated. The current status of the file, which can be either + * `uploaded`, `processed`, or `error`. + */ + status: 'uploaded' | 'processed' | 'error'; + + /** + * @deprecated: Deprecated. For details on why a fine-tuning training file failed + * validation, see the `error` field on `fine_tuning.job`. + */ + status_details?: string; +} + +export interface FileCreateParams { + /** + * The File object (not file name) to be uploaded. + */ + file: Uploadable; + + /** + * The intended purpose of the uploaded file. + * + * Use "fine-tune" for + * [Fine-tuning](https://platform.openai.com/docs/api-reference/fine-tuning) and + * "assistants" for + * [Assistants](https://platform.openai.com/docs/api-reference/assistants) and + * [Messages](https://platform.openai.com/docs/api-reference/messages). This allows + * us to validate the format of the uploaded file is correct for fine-tuning. + */ + purpose: 'fine-tune' | 'assistants'; +} + +export interface FileListParams { + /** + * Only return files with the given purpose. + */ + purpose?: string; +} + +export namespace Files { + export import FileContent = FilesAPI.FileContent; + export import FileDeleted = FilesAPI.FileDeleted; + export import FileObject = FilesAPI.FileObject; + export import FileObjectsPage = FilesAPI.FileObjectsPage; + export import FileCreateParams = FilesAPI.FileCreateParams; + export import FileListParams = FilesAPI.FileListParams; +} diff --git a/backend/node_modules/openai/src/resources/fine-tuning/fine-tuning.ts b/backend/node_modules/openai/src/resources/fine-tuning/fine-tuning.ts new file mode 100644 index 0000000000000000000000000000000000000000..2936c6e32e6c40c41da5a5cc01169314d61386e0 --- /dev/null +++ b/backend/node_modules/openai/src/resources/fine-tuning/fine-tuning.ts @@ -0,0 +1,22 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { APIResource } from "../../resource"; +import * as JobsAPI from "./jobs/jobs"; + +export class FineTuning extends APIResource { + jobs: JobsAPI.Jobs = new JobsAPI.Jobs(this._client); +} + +export namespace FineTuning { + export import Jobs = JobsAPI.Jobs; + export import FineTuningJob = JobsAPI.FineTuningJob; + export import FineTuningJobEvent = JobsAPI.FineTuningJobEvent; + export import FineTuningJobIntegration = JobsAPI.FineTuningJobIntegration; + export import FineTuningJobWandbIntegration = JobsAPI.FineTuningJobWandbIntegration; + export import FineTuningJobWandbIntegrationObject = JobsAPI.FineTuningJobWandbIntegrationObject; + export import FineTuningJobsPage = JobsAPI.FineTuningJobsPage; + export import FineTuningJobEventsPage = JobsAPI.FineTuningJobEventsPage; + export import JobCreateParams = JobsAPI.JobCreateParams; + export import JobListParams = JobsAPI.JobListParams; + export import JobListEventsParams = JobsAPI.JobListEventsParams; +} diff --git a/backend/node_modules/openai/src/resources/fine-tuning/index.ts b/backend/node_modules/openai/src/resources/fine-tuning/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..1d8739a0a874598e6a806607536a9b5bd9ebc770 --- /dev/null +++ b/backend/node_modules/openai/src/resources/fine-tuning/index.ts @@ -0,0 +1,16 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export { FineTuning } from './fine-tuning'; +export { + FineTuningJob, + FineTuningJobEvent, + FineTuningJobIntegration, + FineTuningJobWandbIntegration, + FineTuningJobWandbIntegrationObject, + JobCreateParams, + JobListParams, + JobListEventsParams, + FineTuningJobsPage, + FineTuningJobEventsPage, + Jobs, +} from './jobs/index'; diff --git a/backend/node_modules/openai/src/resources/fine-tuning/jobs/checkpoints.ts b/backend/node_modules/openai/src/resources/fine-tuning/jobs/checkpoints.ts new file mode 100644 index 0000000000000000000000000000000000000000..9c165199f13c2701e7c3569708e83754c7118339 --- /dev/null +++ b/backend/node_modules/openai/src/resources/fine-tuning/jobs/checkpoints.ts @@ -0,0 +1,108 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import * as Core from "../../../core"; +import { APIResource } from "../../../resource"; +import { isRequestOptions } from "../../../core"; +import * as CheckpointsAPI from "./checkpoints"; +import { CursorPage, type CursorPageParams } from "../../../pagination"; + +export class Checkpoints extends APIResource { + /** + * List checkpoints for a fine-tuning job. + */ + list( + fineTuningJobId: string, + query?: CheckpointListParams, + options?: Core.RequestOptions, + ): Core.PagePromise; + list( + fineTuningJobId: string, + options?: Core.RequestOptions, + ): Core.PagePromise; + list( + fineTuningJobId: string, + query: CheckpointListParams | Core.RequestOptions = {}, + options?: Core.RequestOptions, + ): Core.PagePromise { + if (isRequestOptions(query)) { + return this.list(fineTuningJobId, {}, query); + } + return this._client.getAPIList( + `/fine_tuning/jobs/${fineTuningJobId}/checkpoints`, + FineTuningJobCheckpointsPage, + { query, ...options }, + ); + } +} + +export class FineTuningJobCheckpointsPage extends CursorPage {} + +/** + * The `fine_tuning.job.checkpoint` object represents a model checkpoint for a + * fine-tuning job that is ready to use. + */ +export interface FineTuningJobCheckpoint { + /** + * The checkpoint identifier, which can be referenced in the API endpoints. + */ + id: string; + + /** + * The Unix timestamp (in seconds) for when the checkpoint was created. + */ + created_at: number; + + /** + * The name of the fine-tuned checkpoint model that is created. + */ + fine_tuned_model_checkpoint: string; + + /** + * The name of the fine-tuning job that this checkpoint was created from. + */ + fine_tuning_job_id: string; + + /** + * Metrics at the step number during the fine-tuning job. + */ + metrics: FineTuningJobCheckpoint.Metrics; + + /** + * The object type, which is always "fine_tuning.job.checkpoint". + */ + object: 'fine_tuning.job.checkpoint'; + + /** + * The step number that the checkpoint was created at. + */ + step_number: number; +} + +export namespace FineTuningJobCheckpoint { + /** + * Metrics at the step number during the fine-tuning job. + */ + export interface Metrics { + full_valid_loss?: number; + + full_valid_mean_token_accuracy?: number; + + step?: number; + + train_loss?: number; + + train_mean_token_accuracy?: number; + + valid_loss?: number; + + valid_mean_token_accuracy?: number; + } +} + +export interface CheckpointListParams extends CursorPageParams {} + +export namespace Checkpoints { + export import FineTuningJobCheckpoint = CheckpointsAPI.FineTuningJobCheckpoint; + export import FineTuningJobCheckpointsPage = CheckpointsAPI.FineTuningJobCheckpointsPage; + export import CheckpointListParams = CheckpointsAPI.CheckpointListParams; +} diff --git a/backend/node_modules/openai/src/resources/fine-tuning/jobs/index.ts b/backend/node_modules/openai/src/resources/fine-tuning/jobs/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..275c776e96a743c732e6a77ef400f8e3d960821a --- /dev/null +++ b/backend/node_modules/openai/src/resources/fine-tuning/jobs/index.ts @@ -0,0 +1,21 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export { + FineTuningJob, + FineTuningJobEvent, + FineTuningJobIntegration, + FineTuningJobWandbIntegration, + FineTuningJobWandbIntegrationObject, + JobCreateParams, + JobListParams, + JobListEventsParams, + FineTuningJobsPage, + FineTuningJobEventsPage, + Jobs, +} from './jobs'; +export { + FineTuningJobCheckpoint, + CheckpointListParams, + FineTuningJobCheckpointsPage, + Checkpoints, +} from './checkpoints'; diff --git a/backend/node_modules/openai/src/resources/fine-tuning/jobs/jobs.ts b/backend/node_modules/openai/src/resources/fine-tuning/jobs/jobs.ts new file mode 100644 index 0000000000000000000000000000000000000000..59ada12821f79fcab4cb5588573792b8ce781e0c --- /dev/null +++ b/backend/node_modules/openai/src/resources/fine-tuning/jobs/jobs.ts @@ -0,0 +1,452 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import * as Core from "../../../core"; +import { APIResource } from "../../../resource"; +import { isRequestOptions } from "../../../core"; +import * as JobsAPI from "./jobs"; +import * as CheckpointsAPI from "./checkpoints"; +import { CursorPage, type CursorPageParams } from "../../../pagination"; + +export class Jobs extends APIResource { + checkpoints: CheckpointsAPI.Checkpoints = new CheckpointsAPI.Checkpoints(this._client); + + /** + * Creates a fine-tuning job which begins the process of creating a new model from + * a given dataset. + * + * Response includes details of the enqueued job including job status and the name + * of the fine-tuned models once complete. + * + * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/fine-tuning) + */ + create(body: JobCreateParams, options?: Core.RequestOptions): Core.APIPromise { + return this._client.post('/fine_tuning/jobs', { body, ...options }); + } + + /** + * Get info about a fine-tuning job. + * + * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/fine-tuning) + */ + retrieve(fineTuningJobId: string, options?: Core.RequestOptions): Core.APIPromise { + return this._client.get(`/fine_tuning/jobs/${fineTuningJobId}`, options); + } + + /** + * List your organization's fine-tuning jobs + */ + list( + query?: JobListParams, + options?: Core.RequestOptions, + ): Core.PagePromise; + list(options?: Core.RequestOptions): Core.PagePromise; + list( + query: JobListParams | Core.RequestOptions = {}, + options?: Core.RequestOptions, + ): Core.PagePromise { + if (isRequestOptions(query)) { + return this.list({}, query); + } + return this._client.getAPIList('/fine_tuning/jobs', FineTuningJobsPage, { query, ...options }); + } + + /** + * Immediately cancel a fine-tune job. + */ + cancel(fineTuningJobId: string, options?: Core.RequestOptions): Core.APIPromise { + return this._client.post(`/fine_tuning/jobs/${fineTuningJobId}/cancel`, options); + } + + /** + * Get status updates for a fine-tuning job. + */ + listEvents( + fineTuningJobId: string, + query?: JobListEventsParams, + options?: Core.RequestOptions, + ): Core.PagePromise; + listEvents( + fineTuningJobId: string, + options?: Core.RequestOptions, + ): Core.PagePromise; + listEvents( + fineTuningJobId: string, + query: JobListEventsParams | Core.RequestOptions = {}, + options?: Core.RequestOptions, + ): Core.PagePromise { + if (isRequestOptions(query)) { + return this.listEvents(fineTuningJobId, {}, query); + } + return this._client.getAPIList(`/fine_tuning/jobs/${fineTuningJobId}/events`, FineTuningJobEventsPage, { + query, + ...options, + }); + } +} + +export class FineTuningJobsPage extends CursorPage {} + +export class FineTuningJobEventsPage extends CursorPage {} + +/** + * The `fine_tuning.job` object represents a fine-tuning job that has been created + * through the API. + */ +export interface FineTuningJob { + /** + * The object identifier, which can be referenced in the API endpoints. + */ + id: string; + + /** + * The Unix timestamp (in seconds) for when the fine-tuning job was created. + */ + created_at: number; + + /** + * For fine-tuning jobs that have `failed`, this will contain more information on + * the cause of the failure. + */ + error: FineTuningJob.Error | null; + + /** + * The name of the fine-tuned model that is being created. The value will be null + * if the fine-tuning job is still running. + */ + fine_tuned_model: string | null; + + /** + * The Unix timestamp (in seconds) for when the fine-tuning job was finished. The + * value will be null if the fine-tuning job is still running. + */ + finished_at: number | null; + + /** + * The hyperparameters used for the fine-tuning job. See the + * [fine-tuning guide](https://platform.openai.com/docs/guides/fine-tuning) for + * more details. + */ + hyperparameters: FineTuningJob.Hyperparameters; + + /** + * The base model that is being fine-tuned. + */ + model: string; + + /** + * The object type, which is always "fine_tuning.job". + */ + object: 'fine_tuning.job'; + + /** + * The organization that owns the fine-tuning job. + */ + organization_id: string; + + /** + * The compiled results file ID(s) for the fine-tuning job. You can retrieve the + * results with the + * [Files API](https://platform.openai.com/docs/api-reference/files/retrieve-contents). + */ + result_files: Array; + + /** + * The seed used for the fine-tuning job. + */ + seed: number; + + /** + * The current status of the fine-tuning job, which can be either + * `validating_files`, `queued`, `running`, `succeeded`, `failed`, or `cancelled`. + */ + status: 'validating_files' | 'queued' | 'running' | 'succeeded' | 'failed' | 'cancelled'; + + /** + * The total number of billable tokens processed by this fine-tuning job. The value + * will be null if the fine-tuning job is still running. + */ + trained_tokens: number | null; + + /** + * The file ID used for training. You can retrieve the training data with the + * [Files API](https://platform.openai.com/docs/api-reference/files/retrieve-contents). + */ + training_file: string; + + /** + * The file ID used for validation. You can retrieve the validation results with + * the + * [Files API](https://platform.openai.com/docs/api-reference/files/retrieve-contents). + */ + validation_file: string | null; + + /** + * A list of integrations to enable for this fine-tuning job. + */ + integrations?: Array | null; +} + +export namespace FineTuningJob { + /** + * For fine-tuning jobs that have `failed`, this will contain more information on + * the cause of the failure. + */ + export interface Error { + /** + * A machine-readable error code. + */ + code: string; + + /** + * A human-readable error message. + */ + message: string; + + /** + * The parameter that was invalid, usually `training_file` or `validation_file`. + * This field will be null if the failure was not parameter-specific. + */ + param: string | null; + } + + /** + * The hyperparameters used for the fine-tuning job. See the + * [fine-tuning guide](https://platform.openai.com/docs/guides/fine-tuning) for + * more details. + */ + export interface Hyperparameters { + /** + * The number of epochs to train the model for. An epoch refers to one full cycle + * through the training dataset. "auto" decides the optimal number of epochs based + * on the size of the dataset. If setting the number manually, we support any + * number between 1 and 50 epochs. + */ + n_epochs: 'auto' | number; + } +} + +/** + * Fine-tuning job event object + */ +export interface FineTuningJobEvent { + id: string; + + created_at: number; + + level: 'info' | 'warn' | 'error'; + + message: string; + + object: 'fine_tuning.job.event'; +} + +export type FineTuningJobIntegration = FineTuningJobWandbIntegrationObject; + +/** + * The settings for your integration with Weights and Biases. This payload + * specifies the project that metrics will be sent to. Optionally, you can set an + * explicit display name for your run, add tags to your run, and set a default + * entity (team, username, etc) to be associated with your run. + */ +export interface FineTuningJobWandbIntegration { + /** + * The name of the project that the new run will be created under. + */ + project: string; + + /** + * The entity to use for the run. This allows you to set the team or username of + * the WandB user that you would like associated with the run. If not set, the + * default entity for the registered WandB API key is used. + */ + entity?: string | null; + + /** + * A display name to set for the run. If not set, we will use the Job ID as the + * name. + */ + name?: string | null; + + /** + * A list of tags to be attached to the newly created run. These tags are passed + * through directly to WandB. Some default tags are generated by OpenAI: + * "openai/finetune", "openai/{base-model}", "openai/{ftjob-abcdef}". + */ + tags?: Array; +} + +export interface FineTuningJobWandbIntegrationObject { + /** + * The type of the integration being enabled for the fine-tuning job + */ + type: 'wandb'; + + /** + * The settings for your integration with Weights and Biases. This payload + * specifies the project that metrics will be sent to. Optionally, you can set an + * explicit display name for your run, add tags to your run, and set a default + * entity (team, username, etc) to be associated with your run. + */ + wandb: FineTuningJobWandbIntegration; +} + +export interface JobCreateParams { + /** + * The name of the model to fine-tune. You can select one of the + * [supported models](https://platform.openai.com/docs/guides/fine-tuning/what-models-can-be-fine-tuned). + */ + model: (string & {}) | 'babbage-002' | 'davinci-002' | 'gpt-3.5-turbo'; + + /** + * The ID of an uploaded file that contains training data. + * + * See [upload file](https://platform.openai.com/docs/api-reference/files/upload) + * for how to upload a file. + * + * Your dataset must be formatted as a JSONL file. Additionally, you must upload + * your file with the purpose `fine-tune`. + * + * See the [fine-tuning guide](https://platform.openai.com/docs/guides/fine-tuning) + * for more details. + */ + training_file: string; + + /** + * The hyperparameters used for the fine-tuning job. + */ + hyperparameters?: JobCreateParams.Hyperparameters; + + /** + * A list of integrations to enable for your fine-tuning job. + */ + integrations?: Array | null; + + /** + * The seed controls the reproducibility of the job. Passing in the same seed and + * job parameters should produce the same results, but may differ in rare cases. If + * a seed is not specified, one will be generated for you. + */ + seed?: number | null; + + /** + * A string of up to 18 characters that will be added to your fine-tuned model + * name. + * + * For example, a `suffix` of "custom-model-name" would produce a model name like + * `ft:gpt-3.5-turbo:openai:custom-model-name:7p4lURel`. + */ + suffix?: string | null; + + /** + * The ID of an uploaded file that contains validation data. + * + * If you provide this file, the data is used to generate validation metrics + * periodically during fine-tuning. These metrics can be viewed in the fine-tuning + * results file. The same data should not be present in both train and validation + * files. + * + * Your dataset must be formatted as a JSONL file. You must upload your file with + * the purpose `fine-tune`. + * + * See the [fine-tuning guide](https://platform.openai.com/docs/guides/fine-tuning) + * for more details. + */ + validation_file?: string | null; +} + +export namespace JobCreateParams { + /** + * The hyperparameters used for the fine-tuning job. + */ + export interface Hyperparameters { + /** + * Number of examples in each batch. A larger batch size means that model + * parameters are updated less frequently, but with lower variance. + */ + batch_size?: 'auto' | number; + + /** + * Scaling factor for the learning rate. A smaller learning rate may be useful to + * avoid overfitting. + */ + learning_rate_multiplier?: 'auto' | number; + + /** + * The number of epochs to train the model for. An epoch refers to one full cycle + * through the training dataset. + */ + n_epochs?: 'auto' | number; + } + + export interface Integration { + /** + * The type of integration to enable. Currently, only "wandb" (Weights and Biases) + * is supported. + */ + type: 'wandb'; + + /** + * The settings for your integration with Weights and Biases. This payload + * specifies the project that metrics will be sent to. Optionally, you can set an + * explicit display name for your run, add tags to your run, and set a default + * entity (team, username, etc) to be associated with your run. + */ + wandb: Integration.Wandb; + } + + export namespace Integration { + /** + * The settings for your integration with Weights and Biases. This payload + * specifies the project that metrics will be sent to. Optionally, you can set an + * explicit display name for your run, add tags to your run, and set a default + * entity (team, username, etc) to be associated with your run. + */ + export interface Wandb { + /** + * The name of the project that the new run will be created under. + */ + project: string; + + /** + * The entity to use for the run. This allows you to set the team or username of + * the WandB user that you would like associated with the run. If not set, the + * default entity for the registered WandB API key is used. + */ + entity?: string | null; + + /** + * A display name to set for the run. If not set, we will use the Job ID as the + * name. + */ + name?: string | null; + + /** + * A list of tags to be attached to the newly created run. These tags are passed + * through directly to WandB. Some default tags are generated by OpenAI: + * "openai/finetune", "openai/{base-model}", "openai/{ftjob-abcdef}". + */ + tags?: Array; + } + } +} + +export interface JobListParams extends CursorPageParams {} + +export interface JobListEventsParams extends CursorPageParams {} + +export namespace Jobs { + export import FineTuningJob = JobsAPI.FineTuningJob; + export import FineTuningJobEvent = JobsAPI.FineTuningJobEvent; + export import FineTuningJobIntegration = JobsAPI.FineTuningJobIntegration; + export import FineTuningJobWandbIntegration = JobsAPI.FineTuningJobWandbIntegration; + export import FineTuningJobWandbIntegrationObject = JobsAPI.FineTuningJobWandbIntegrationObject; + export import FineTuningJobsPage = JobsAPI.FineTuningJobsPage; + export import FineTuningJobEventsPage = JobsAPI.FineTuningJobEventsPage; + export import JobCreateParams = JobsAPI.JobCreateParams; + export import JobListParams = JobsAPI.JobListParams; + export import JobListEventsParams = JobsAPI.JobListEventsParams; + export import Checkpoints = CheckpointsAPI.Checkpoints; + export import FineTuningJobCheckpoint = CheckpointsAPI.FineTuningJobCheckpoint; + export import FineTuningJobCheckpointsPage = CheckpointsAPI.FineTuningJobCheckpointsPage; + export import CheckpointListParams = CheckpointsAPI.CheckpointListParams; +} diff --git a/backend/node_modules/openai/src/resources/images.ts b/backend/node_modules/openai/src/resources/images.ts new file mode 100644 index 0000000000000000000000000000000000000000..2153d2dec24919513810e31f9de42754b254cf16 --- /dev/null +++ b/backend/node_modules/openai/src/resources/images.ts @@ -0,0 +1,215 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import * as Core from "../core"; +import { APIResource } from "../resource"; +import * as ImagesAPI from "./images"; +import { type Uploadable, multipartFormRequestOptions } from "../core"; + +export class Images extends APIResource { + /** + * Creates a variation of a given image. + */ + createVariation( + body: ImageCreateVariationParams, + options?: Core.RequestOptions, + ): Core.APIPromise { + return this._client.post('/images/variations', multipartFormRequestOptions({ body, ...options })); + } + + /** + * Creates an edited or extended image given an original image and a prompt. + */ + edit(body: ImageEditParams, options?: Core.RequestOptions): Core.APIPromise { + return this._client.post('/images/edits', multipartFormRequestOptions({ body, ...options })); + } + + /** + * Creates an image given a prompt. + */ + generate(body: ImageGenerateParams, options?: Core.RequestOptions): Core.APIPromise { + return this._client.post('/images/generations', { body, ...options }); + } +} + +/** + * Represents the url or the content of an image generated by the OpenAI API. + */ +export interface Image { + /** + * The base64-encoded JSON of the generated image, if `response_format` is + * `b64_json`. + */ + b64_json?: string; + + /** + * The prompt that was used to generate the image, if there was any revision to the + * prompt. + */ + revised_prompt?: string; + + /** + * The URL of the generated image, if `response_format` is `url` (default). + */ + url?: string; +} + +export interface ImagesResponse { + created: number; + + data: Array; +} + +export interface ImageCreateVariationParams { + /** + * The image to use as the basis for the variation(s). Must be a valid PNG file, + * less than 4MB, and square. + */ + image: Uploadable; + + /** + * The model to use for image generation. Only `dall-e-2` is supported at this + * time. + */ + model?: (string & {}) | 'dall-e-2' | null; + + /** + * The number of images to generate. Must be between 1 and 10. For `dall-e-3`, only + * `n=1` is supported. + */ + n?: number | null; + + /** + * The format in which the generated images are returned. Must be one of `url` or + * `b64_json`. URLs are only valid for 60 minutes after the image has been + * generated. + */ + response_format?: 'url' | 'b64_json' | null; + + /** + * The size of the generated images. Must be one of `256x256`, `512x512`, or + * `1024x1024`. + */ + size?: '256x256' | '512x512' | '1024x1024' | null; + + /** + * A unique identifier representing your end-user, which can help OpenAI to monitor + * and detect abuse. + * [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + */ + user?: string; +} + +export interface ImageEditParams { + /** + * The image to edit. Must be a valid PNG file, less than 4MB, and square. If mask + * is not provided, image must have transparency, which will be used as the mask. + */ + image: Uploadable; + + /** + * A text description of the desired image(s). The maximum length is 1000 + * characters. + */ + prompt: string; + + /** + * An additional image whose fully transparent areas (e.g. where alpha is zero) + * indicate where `image` should be edited. Must be a valid PNG file, less than + * 4MB, and have the same dimensions as `image`. + */ + mask?: Uploadable; + + /** + * The model to use for image generation. Only `dall-e-2` is supported at this + * time. + */ + model?: (string & {}) | 'dall-e-2' | null; + + /** + * The number of images to generate. Must be between 1 and 10. + */ + n?: number | null; + + /** + * The format in which the generated images are returned. Must be one of `url` or + * `b64_json`. URLs are only valid for 60 minutes after the image has been + * generated. + */ + response_format?: 'url' | 'b64_json' | null; + + /** + * The size of the generated images. Must be one of `256x256`, `512x512`, or + * `1024x1024`. + */ + size?: '256x256' | '512x512' | '1024x1024' | null; + + /** + * A unique identifier representing your end-user, which can help OpenAI to monitor + * and detect abuse. + * [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + */ + user?: string; +} + +export interface ImageGenerateParams { + /** + * A text description of the desired image(s). The maximum length is 1000 + * characters for `dall-e-2` and 4000 characters for `dall-e-3`. + */ + prompt: string; + + /** + * The model to use for image generation. + */ + model?: (string & {}) | 'dall-e-2' | 'dall-e-3' | null; + + /** + * The number of images to generate. Must be between 1 and 10. For `dall-e-3`, only + * `n=1` is supported. + */ + n?: number | null; + + /** + * The quality of the image that will be generated. `hd` creates images with finer + * details and greater consistency across the image. This param is only supported + * for `dall-e-3`. + */ + quality?: 'standard' | 'hd'; + + /** + * The format in which the generated images are returned. Must be one of `url` or + * `b64_json`. URLs are only valid for 60 minutes after the image has been + * generated. + */ + response_format?: 'url' | 'b64_json' | null; + + /** + * The size of the generated images. Must be one of `256x256`, `512x512`, or + * `1024x1024` for `dall-e-2`. Must be one of `1024x1024`, `1792x1024`, or + * `1024x1792` for `dall-e-3` models. + */ + size?: '256x256' | '512x512' | '1024x1024' | '1792x1024' | '1024x1792' | null; + + /** + * The style of the generated images. Must be one of `vivid` or `natural`. Vivid + * causes the model to lean towards generating hyper-real and dramatic images. + * Natural causes the model to produce more natural, less hyper-real looking + * images. This param is only supported for `dall-e-3`. + */ + style?: 'vivid' | 'natural' | null; + + /** + * A unique identifier representing your end-user, which can help OpenAI to monitor + * and detect abuse. + * [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + */ + user?: string; +} + +export namespace Images { + export import Image = ImagesAPI.Image; + export import ImagesResponse = ImagesAPI.ImagesResponse; + export import ImageCreateVariationParams = ImagesAPI.ImageCreateVariationParams; + export import ImageEditParams = ImagesAPI.ImageEditParams; + export import ImageGenerateParams = ImagesAPI.ImageGenerateParams; +} diff --git a/backend/node_modules/openai/src/resources/index.ts b/backend/node_modules/openai/src/resources/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..282e57ea15c333f328c4db3895db9189a84b374c --- /dev/null +++ b/backend/node_modules/openai/src/resources/index.ts @@ -0,0 +1,37 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export * from './chat/index'; +export * from './shared'; +export { Audio } from './audio/audio'; +export { Batch, BatchError, BatchRequestCounts, BatchCreateParams, Batches } from './batches'; +export { Beta } from './beta/beta'; +export { + Completion, + CompletionChoice, + CompletionUsage, + CompletionCreateParams, + CompletionCreateParamsNonStreaming, + CompletionCreateParamsStreaming, + Completions, +} from './completions'; +export { CreateEmbeddingResponse, Embedding, EmbeddingCreateParams, Embeddings } from './embeddings'; +export { + FileContent, + FileDeleted, + FileObject, + FileCreateParams, + FileListParams, + FileObjectsPage, + Files, +} from './files'; +export { FineTuning } from './fine-tuning/fine-tuning'; +export { + Image, + ImagesResponse, + ImageCreateVariationParams, + ImageEditParams, + ImageGenerateParams, + Images, +} from './images'; +export { Model, ModelDeleted, ModelsPage, Models } from './models'; +export { Moderation, ModerationCreateResponse, ModerationCreateParams, Moderations } from './moderations'; diff --git a/backend/node_modules/openai/src/resources/models.ts b/backend/node_modules/openai/src/resources/models.ts new file mode 100644 index 0000000000000000000000000000000000000000..32923a7a3bbb12570010395c24b1623aef68c8fd --- /dev/null +++ b/backend/node_modules/openai/src/resources/models.ts @@ -0,0 +1,76 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import * as Core from "../core"; +import { APIResource } from "../resource"; +import * as ModelsAPI from "./models"; +import { Page } from "../pagination"; + +export class Models extends APIResource { + /** + * Retrieves a model instance, providing basic information about the model such as + * the owner and permissioning. + */ + retrieve(model: string, options?: Core.RequestOptions): Core.APIPromise { + return this._client.get(`/models/${model}`, options); + } + + /** + * Lists the currently available models, and provides basic information about each + * one such as the owner and availability. + */ + list(options?: Core.RequestOptions): Core.PagePromise { + return this._client.getAPIList('/models', ModelsPage, options); + } + + /** + * Delete a fine-tuned model. You must have the Owner role in your organization to + * delete a model. + */ + del(model: string, options?: Core.RequestOptions): Core.APIPromise { + return this._client.delete(`/models/${model}`, options); + } +} + +/** + * Note: no pagination actually occurs yet, this is for forwards-compatibility. + */ +export class ModelsPage extends Page {} + +/** + * Describes an OpenAI model offering that can be used with the API. + */ +export interface Model { + /** + * The model identifier, which can be referenced in the API endpoints. + */ + id: string; + + /** + * The Unix timestamp (in seconds) when the model was created. + */ + created: number; + + /** + * The object type, which is always "model". + */ + object: 'model'; + + /** + * The organization that owns the model. + */ + owned_by: string; +} + +export interface ModelDeleted { + id: string; + + deleted: boolean; + + object: string; +} + +export namespace Models { + export import Model = ModelsAPI.Model; + export import ModelDeleted = ModelsAPI.ModelDeleted; + export import ModelsPage = ModelsAPI.ModelsPage; +} diff --git a/backend/node_modules/openai/src/resources/moderations.ts b/backend/node_modules/openai/src/resources/moderations.ts new file mode 100644 index 0000000000000000000000000000000000000000..4ff7de8a1a1acbff859e6bf462813b64ef34b067 --- /dev/null +++ b/backend/node_modules/openai/src/resources/moderations.ts @@ -0,0 +1,214 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import * as Core from "../core"; +import { APIResource } from "../resource"; +import * as ModerationsAPI from "./moderations"; + +export class Moderations extends APIResource { + /** + * Classifies if text is potentially harmful. + */ + create( + body: ModerationCreateParams, + options?: Core.RequestOptions, + ): Core.APIPromise { + return this._client.post('/moderations', { body, ...options }); + } +} + +export interface Moderation { + /** + * A list of the categories, and whether they are flagged or not. + */ + categories: Moderation.Categories; + + /** + * A list of the categories along with their scores as predicted by model. + */ + category_scores: Moderation.CategoryScores; + + /** + * Whether any of the below categories are flagged. + */ + flagged: boolean; +} + +export namespace Moderation { + /** + * A list of the categories, and whether they are flagged or not. + */ + export interface Categories { + /** + * Content that expresses, incites, or promotes harassing language towards any + * target. + */ + harassment: boolean; + + /** + * Harassment content that also includes violence or serious harm towards any + * target. + */ + 'harassment/threatening': boolean; + + /** + * Content that expresses, incites, or promotes hate based on race, gender, + * ethnicity, religion, nationality, sexual orientation, disability status, or + * caste. Hateful content aimed at non-protected groups (e.g., chess players) is + * harassment. + */ + hate: boolean; + + /** + * Hateful content that also includes violence or serious harm towards the targeted + * group based on race, gender, ethnicity, religion, nationality, sexual + * orientation, disability status, or caste. + */ + 'hate/threatening': boolean; + + /** + * Content that promotes, encourages, or depicts acts of self-harm, such as + * suicide, cutting, and eating disorders. + */ + 'self-harm': boolean; + + /** + * Content that encourages performing acts of self-harm, such as suicide, cutting, + * and eating disorders, or that gives instructions or advice on how to commit such + * acts. + */ + 'self-harm/instructions': boolean; + + /** + * Content where the speaker expresses that they are engaging or intend to engage + * in acts of self-harm, such as suicide, cutting, and eating disorders. + */ + 'self-harm/intent': boolean; + + /** + * Content meant to arouse sexual excitement, such as the description of sexual + * activity, or that promotes sexual services (excluding sex education and + * wellness). + */ + sexual: boolean; + + /** + * Sexual content that includes an individual who is under 18 years old. + */ + 'sexual/minors': boolean; + + /** + * Content that depicts death, violence, or physical injury. + */ + violence: boolean; + + /** + * Content that depicts death, violence, or physical injury in graphic detail. + */ + 'violence/graphic': boolean; + } + + /** + * A list of the categories along with their scores as predicted by model. + */ + export interface CategoryScores { + /** + * The score for the category 'harassment'. + */ + harassment: number; + + /** + * The score for the category 'harassment/threatening'. + */ + 'harassment/threatening': number; + + /** + * The score for the category 'hate'. + */ + hate: number; + + /** + * The score for the category 'hate/threatening'. + */ + 'hate/threatening': number; + + /** + * The score for the category 'self-harm'. + */ + 'self-harm': number; + + /** + * The score for the category 'self-harm/instructions'. + */ + 'self-harm/instructions': number; + + /** + * The score for the category 'self-harm/intent'. + */ + 'self-harm/intent': number; + + /** + * The score for the category 'sexual'. + */ + sexual: number; + + /** + * The score for the category 'sexual/minors'. + */ + 'sexual/minors': number; + + /** + * The score for the category 'violence'. + */ + violence: number; + + /** + * The score for the category 'violence/graphic'. + */ + 'violence/graphic': number; + } +} + +/** + * Represents if a given text input is potentially harmful. + */ +export interface ModerationCreateResponse { + /** + * The unique identifier for the moderation request. + */ + id: string; + + /** + * The model used to generate the moderation results. + */ + model: string; + + /** + * A list of moderation objects. + */ + results: Array; +} + +export interface ModerationCreateParams { + /** + * The input text to classify + */ + input: string | Array; + + /** + * Two content moderations models are available: `text-moderation-stable` and + * `text-moderation-latest`. + * + * The default is `text-moderation-latest` which will be automatically upgraded + * over time. This ensures you are always using our most accurate model. If you use + * `text-moderation-stable`, we will provide advanced notice before updating the + * model. Accuracy of `text-moderation-stable` may be slightly lower than for + * `text-moderation-latest`. + */ + model?: (string & {}) | 'text-moderation-latest' | 'text-moderation-stable'; +} + +export namespace Moderations { + export import Moderation = ModerationsAPI.Moderation; + export import ModerationCreateResponse = ModerationsAPI.ModerationCreateResponse; + export import ModerationCreateParams = ModerationsAPI.ModerationCreateParams; +} diff --git a/backend/node_modules/openai/src/resources/shared.ts b/backend/node_modules/openai/src/resources/shared.ts new file mode 100644 index 0000000000000000000000000000000000000000..93fa05fa4cedec8e4e1bb2eb0c0521855fe20a72 --- /dev/null +++ b/backend/node_modules/openai/src/resources/shared.ts @@ -0,0 +1,47 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export interface ErrorObject { + code: string | null; + + message: string; + + param: string | null; + + type: string; +} + +export interface FunctionDefinition { + /** + * The name of the function to be called. Must be a-z, A-Z, 0-9, or contain + * underscores and dashes, with a maximum length of 64. + */ + name: string; + + /** + * A description of what the function does, used by the model to choose when and + * how to call the function. + */ + description?: string; + + /** + * The parameters the functions accepts, described as a JSON Schema object. See the + * [guide](https://platform.openai.com/docs/guides/text-generation/function-calling) + * for examples, and the + * [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for + * documentation about the format. + * + * Omitting `parameters` defines a function with an empty parameter list. + */ + parameters?: FunctionParameters; +} + +/** + * The parameters the functions accepts, described as a JSON Schema object. See the + * [guide](https://platform.openai.com/docs/guides/text-generation/function-calling) + * for examples, and the + * [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for + * documentation about the format. + * + * Omitting `parameters` defines a function with an empty parameter list. + */ +export type FunctionParameters = Record; diff --git a/backend/node_modules/openai/src/shims/node.ts b/backend/node_modules/openai/src/shims/node.ts new file mode 100644 index 0000000000000000000000000000000000000000..73df5600ccecaec9138f2e2e636159688f05131e --- /dev/null +++ b/backend/node_modules/openai/src/shims/node.ts @@ -0,0 +1,50 @@ +// @ts-ignore +import * as types from '../_shims/node-types'; +import { setShims } from '../_shims/registry'; +import { getRuntime } from '../_shims/node-runtime'; +setShims(getRuntime()); + +declare module '../_shims/manual-types' { + export namespace manual { + // @ts-ignore + export type Agent = types.Agent; + // @ts-ignore + export import fetch = types.fetch; + // @ts-ignore + export type Request = types.Request; + // @ts-ignore + export type RequestInfo = types.RequestInfo; + // @ts-ignore + export type RequestInit = types.RequestInit; + // @ts-ignore + export type Response = types.Response; + // @ts-ignore + export type ResponseInit = types.ResponseInit; + // @ts-ignore + export type ResponseType = types.ResponseType; + // @ts-ignore + export type BodyInit = types.BodyInit; + // @ts-ignore + export type Headers = types.Headers; + // @ts-ignore + export type HeadersInit = types.HeadersInit; + // @ts-ignore + export type BlobPropertyBag = types.BlobPropertyBag; + // @ts-ignore + export type FilePropertyBag = types.FilePropertyBag; + // @ts-ignore + export type FileFromPathOptions = types.FileFromPathOptions; + // @ts-ignore + export import FormData = types.FormData; + // @ts-ignore + export import File = types.File; + // @ts-ignore + export import Blob = types.Blob; + // @ts-ignore + export type Readable = types.Readable; + // @ts-ignore + export type FsReadStream = types.FsReadStream; + // @ts-ignore + export import ReadableStream = types.ReadableStream; + } +} diff --git a/backend/node_modules/openai/src/shims/web.ts b/backend/node_modules/openai/src/shims/web.ts new file mode 100644 index 0000000000000000000000000000000000000000..f72d78444e03511cb08867c3893600c0cc616ee5 --- /dev/null +++ b/backend/node_modules/openai/src/shims/web.ts @@ -0,0 +1,50 @@ +// @ts-ignore +import * as types from '../_shims/web-types'; +import { setShims } from '../_shims/registry'; +import { getRuntime } from '../_shims/web-runtime'; +setShims(getRuntime({ manuallyImported: true })); + +declare module '../_shims/manual-types' { + export namespace manual { + // @ts-ignore + export type Agent = types.Agent; + // @ts-ignore + export import fetch = types.fetch; + // @ts-ignore + export type Request = types.Request; + // @ts-ignore + export type RequestInfo = types.RequestInfo; + // @ts-ignore + export type RequestInit = types.RequestInit; + // @ts-ignore + export type Response = types.Response; + // @ts-ignore + export type ResponseInit = types.ResponseInit; + // @ts-ignore + export type ResponseType = types.ResponseType; + // @ts-ignore + export type BodyInit = types.BodyInit; + // @ts-ignore + export type Headers = types.Headers; + // @ts-ignore + export type HeadersInit = types.HeadersInit; + // @ts-ignore + export type BlobPropertyBag = types.BlobPropertyBag; + // @ts-ignore + export type FilePropertyBag = types.FilePropertyBag; + // @ts-ignore + export type FileFromPathOptions = types.FileFromPathOptions; + // @ts-ignore + export import FormData = types.FormData; + // @ts-ignore + export import File = types.File; + // @ts-ignore + export import Blob = types.Blob; + // @ts-ignore + export type Readable = types.Readable; + // @ts-ignore + export type FsReadStream = types.FsReadStream; + // @ts-ignore + export import ReadableStream = types.ReadableStream; + } +} diff --git a/backend/node_modules/openai/src/streaming.ts b/backend/node_modules/openai/src/streaming.ts new file mode 100644 index 0000000000000000000000000000000000000000..c9a8cf2437734cfa4ae60934a052d70ede3de539 --- /dev/null +++ b/backend/node_modules/openai/src/streaming.ts @@ -0,0 +1,508 @@ +import { ReadableStream, type Response } from './_shims/index'; +import { OpenAIError } from './error'; + +import { APIError } from "./error"; + +type Bytes = string | ArrayBuffer | Uint8Array | Buffer | null | undefined; + +export type ServerSentEvent = { + event: string | null; + data: string; + raw: string[]; +}; + +export class Stream implements AsyncIterable { + controller: AbortController; + + constructor( + private iterator: () => AsyncIterator, + controller: AbortController, + ) { + this.controller = controller; + } + + static fromSSEResponse(response: Response, controller: AbortController) { + let consumed = false; + + async function* iterator(): AsyncIterator { + if (consumed) { + throw new Error('Cannot iterate over a consumed stream, use `.tee()` to split the stream.'); + } + consumed = true; + let done = false; + try { + for await (const sse of _iterSSEMessages(response, controller)) { + if (done) continue; + + if (sse.data.startsWith('[DONE]')) { + done = true; + continue; + } + + if (sse.event === null) { + let data; + + try { + data = JSON.parse(sse.data); + } catch (e) { + console.error(`Could not parse message into JSON:`, sse.data); + console.error(`From chunk:`, sse.raw); + throw e; + } + + if (data && data.error) { + throw new APIError(undefined, data.error, undefined, undefined); + } + + yield data; + } else { + let data; + try { + data = JSON.parse(sse.data); + } catch (e) { + console.error(`Could not parse message into JSON:`, sse.data); + console.error(`From chunk:`, sse.raw); + throw e; + } + // TODO: Is this where the error should be thrown? + if (sse.event == 'error') { + throw new APIError(undefined, data.error, data.message, undefined); + } + yield { event: sse.event, data: data } as any; + } + } + done = true; + } catch (e) { + // If the user calls `stream.controller.abort()`, we should exit without throwing. + if (e instanceof Error && e.name === 'AbortError') return; + throw e; + } finally { + // If the user `break`s, abort the ongoing request. + if (!done) controller.abort(); + } + } + + return new Stream(iterator, controller); + } + + /** + * Generates a Stream from a newline-separated ReadableStream + * where each item is a JSON value. + */ + static fromReadableStream(readableStream: ReadableStream, controller: AbortController) { + let consumed = false; + + async function* iterLines(): AsyncGenerator { + const lineDecoder = new LineDecoder(); + + const iter = readableStreamAsyncIterable(readableStream); + for await (const chunk of iter) { + for (const line of lineDecoder.decode(chunk)) { + yield line; + } + } + + for (const line of lineDecoder.flush()) { + yield line; + } + } + + async function* iterator(): AsyncIterator { + if (consumed) { + throw new Error('Cannot iterate over a consumed stream, use `.tee()` to split the stream.'); + } + consumed = true; + let done = false; + try { + for await (const line of iterLines()) { + if (done) continue; + if (line) yield JSON.parse(line); + } + done = true; + } catch (e) { + // If the user calls `stream.controller.abort()`, we should exit without throwing. + if (e instanceof Error && e.name === 'AbortError') return; + throw e; + } finally { + // If the user `break`s, abort the ongoing request. + if (!done) controller.abort(); + } + } + + return new Stream(iterator, controller); + } + + [Symbol.asyncIterator](): AsyncIterator { + return this.iterator(); + } + + /** + * Splits the stream into two streams which can be + * independently read from at different speeds. + */ + tee(): [Stream, Stream] { + const left: Array>> = []; + const right: Array>> = []; + const iterator = this.iterator(); + + const teeIterator = (queue: Array>>): AsyncIterator => { + return { + next: () => { + if (queue.length === 0) { + const result = iterator.next(); + left.push(result); + right.push(result); + } + return queue.shift()!; + }, + }; + }; + + return [ + new Stream(() => teeIterator(left), this.controller), + new Stream(() => teeIterator(right), this.controller), + ]; + } + + /** + * Converts this stream to a newline-separated ReadableStream of + * JSON stringified values in the stream + * which can be turned back into a Stream with `Stream.fromReadableStream()`. + */ + toReadableStream(): ReadableStream { + const self = this; + let iter: AsyncIterator; + const encoder = new TextEncoder(); + + return new ReadableStream({ + async start() { + iter = self[Symbol.asyncIterator](); + }, + async pull(ctrl: any) { + try { + const { value, done } = await iter.next(); + if (done) return ctrl.close(); + + const bytes = encoder.encode(JSON.stringify(value) + '\n'); + + ctrl.enqueue(bytes); + } catch (err) { + ctrl.error(err); + } + }, + async cancel() { + await iter.return?.(); + }, + }); + } +} + +export async function* _iterSSEMessages( + response: Response, + controller: AbortController, +): AsyncGenerator { + if (!response.body) { + controller.abort(); + throw new OpenAIError(`Attempted to iterate over a response with no body`); + } + + const sseDecoder = new SSEDecoder(); + const lineDecoder = new LineDecoder(); + + const iter = readableStreamAsyncIterable(response.body); + for await (const sseChunk of iterSSEChunks(iter)) { + for (const line of lineDecoder.decode(sseChunk)) { + const sse = sseDecoder.decode(line); + if (sse) yield sse; + } + } + + for (const line of lineDecoder.flush()) { + const sse = sseDecoder.decode(line); + if (sse) yield sse; + } +} + +/** + * Given an async iterable iterator, iterates over it and yields full + * SSE chunks, i.e. yields when a double new-line is encountered. + */ +async function* iterSSEChunks(iterator: AsyncIterableIterator): AsyncGenerator { + let data = new Uint8Array(); + + for await (const chunk of iterator) { + if (chunk == null) { + continue; + } + + const binaryChunk = + chunk instanceof ArrayBuffer ? new Uint8Array(chunk) + : typeof chunk === 'string' ? new TextEncoder().encode(chunk) + : chunk; + + let newData = new Uint8Array(data.length + binaryChunk.length); + newData.set(data); + newData.set(binaryChunk, data.length); + data = newData; + + let patternIndex; + while ((patternIndex = findDoubleNewlineIndex(data)) !== -1) { + yield data.slice(0, patternIndex); + data = data.slice(patternIndex); + } + } + + if (data.length > 0) { + yield data; + } +} + +function findDoubleNewlineIndex(buffer: Uint8Array): number { + // This function searches the buffer for the end patterns (\r\r, \n\n, \r\n\r\n) + // and returns the index right after the first occurrence of any pattern, + // or -1 if none of the patterns are found. + const newline = 0x0a; // \n + const carriage = 0x0d; // \r + + for (let i = 0; i < buffer.length - 2; i++) { + if (buffer[i] === newline && buffer[i + 1] === newline) { + // \n\n + return i + 2; + } + if (buffer[i] === carriage && buffer[i + 1] === carriage) { + // \r\r + return i + 2; + } + if ( + buffer[i] === carriage && + buffer[i + 1] === newline && + i + 3 < buffer.length && + buffer[i + 2] === carriage && + buffer[i + 3] === newline + ) { + // \r\n\r\n + return i + 4; + } + } + + return -1; +} + +class SSEDecoder { + private data: string[]; + private event: string | null; + private chunks: string[]; + + constructor() { + this.event = null; + this.data = []; + this.chunks = []; + } + + decode(line: string) { + if (line.endsWith('\r')) { + line = line.substring(0, line.length - 1); + } + + if (!line) { + // empty line and we didn't previously encounter any messages + if (!this.event && !this.data.length) return null; + + const sse: ServerSentEvent = { + event: this.event, + data: this.data.join('\n'), + raw: this.chunks, + }; + + this.event = null; + this.data = []; + this.chunks = []; + + return sse; + } + + this.chunks.push(line); + + if (line.startsWith(':')) { + return null; + } + + let [fieldname, _, value] = partition(line, ':'); + + if (value.startsWith(' ')) { + value = value.substring(1); + } + + if (fieldname === 'event') { + this.event = value; + } else if (fieldname === 'data') { + this.data.push(value); + } + + return null; + } +} + +/** + * A re-implementation of httpx's `LineDecoder` in Python that handles incrementally + * reading lines from text. + * + * https://github.com/encode/httpx/blob/920333ea98118e9cf617f246905d7b202510941c/httpx/_decoders.py#L258 + */ +class LineDecoder { + // prettier-ignore + static NEWLINE_CHARS = new Set(['\n', '\r']); + static NEWLINE_REGEXP = /\r\n|[\n\r]/g; + + buffer: string[]; + trailingCR: boolean; + textDecoder: any; // TextDecoder found in browsers; not typed to avoid pulling in either "dom" or "node" types. + + constructor() { + this.buffer = []; + this.trailingCR = false; + } + + decode(chunk: Bytes): string[] { + let text = this.decodeText(chunk); + + if (this.trailingCR) { + text = '\r' + text; + this.trailingCR = false; + } + if (text.endsWith('\r')) { + this.trailingCR = true; + text = text.slice(0, -1); + } + + if (!text) { + return []; + } + + const trailingNewline = LineDecoder.NEWLINE_CHARS.has(text[text.length - 1] || ''); + let lines = text.split(LineDecoder.NEWLINE_REGEXP); + + // if there is a trailing new line then the last entry will be an empty + // string which we don't care about + if (trailingNewline) { + lines.pop(); + } + + if (lines.length === 1 && !trailingNewline) { + this.buffer.push(lines[0]!); + return []; + } + + if (this.buffer.length > 0) { + lines = [this.buffer.join('') + lines[0], ...lines.slice(1)]; + this.buffer = []; + } + + if (!trailingNewline) { + this.buffer = [lines.pop() || '']; + } + + return lines; + } + + decodeText(bytes: Bytes): string { + if (bytes == null) return ''; + if (typeof bytes === 'string') return bytes; + + // Node: + if (typeof Buffer !== 'undefined') { + if (bytes instanceof Buffer) { + return bytes.toString(); + } + if (bytes instanceof Uint8Array) { + return Buffer.from(bytes).toString(); + } + + throw new OpenAIError( + `Unexpected: received non-Uint8Array (${bytes.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`, + ); + } + + // Browser + if (typeof TextDecoder !== 'undefined') { + if (bytes instanceof Uint8Array || bytes instanceof ArrayBuffer) { + this.textDecoder ??= new TextDecoder('utf8'); + return this.textDecoder.decode(bytes); + } + + throw new OpenAIError( + `Unexpected: received non-Uint8Array/ArrayBuffer (${ + (bytes as any).constructor.name + }) in a web platform. Please report this error.`, + ); + } + + throw new OpenAIError( + `Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.`, + ); + } + + flush(): string[] { + if (!this.buffer.length && !this.trailingCR) { + return []; + } + + const lines = [this.buffer.join('')]; + this.buffer = []; + this.trailingCR = false; + return lines; + } +} + +/** This is an internal helper function that's just used for testing */ +export function _decodeChunks(chunks: string[]): string[] { + const decoder = new LineDecoder(); + const lines: string[] = []; + for (const chunk of chunks) { + lines.push(...decoder.decode(chunk)); + } + + return lines; +} + +function partition(str: string, delimiter: string): [string, string, string] { + const index = str.indexOf(delimiter); + if (index !== -1) { + return [str.substring(0, index), delimiter, str.substring(index + delimiter.length)]; + } + + return [str, '', '']; +} + +/** + * Most browsers don't yet have async iterable support for ReadableStream, + * and Node has a very different way of reading bytes from its "ReadableStream". + * + * This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490 + */ +export function readableStreamAsyncIterable(stream: any): AsyncIterableIterator { + if (stream[Symbol.asyncIterator]) return stream; + + const reader = stream.getReader(); + return { + async next() { + try { + const result = await reader.read(); + if (result?.done) reader.releaseLock(); // release lock when stream becomes closed + return result; + } catch (e) { + reader.releaseLock(); // release lock when stream becomes errored + throw e; + } + }, + async return() { + const cancelPromise = reader.cancel(); + reader.releaseLock(); + await cancelPromise; + return { done: true, value: undefined }; + }, + [Symbol.asyncIterator]() { + return this; + }, + }; +} diff --git a/backend/node_modules/openai/src/tsconfig.json b/backend/node_modules/openai/src/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..e9f2d70b0c9509fe4342bfcb7402742b30022743 --- /dev/null +++ b/backend/node_modules/openai/src/tsconfig.json @@ -0,0 +1,11 @@ +{ + // this config is included in the published src directory to prevent TS errors + // from appearing when users go to source, and VSCode opens the source .ts file + // via declaration maps + "include": ["index.ts"], + "compilerOptions": { + "target": "es2015", + "lib": ["DOM"], + "moduleResolution": "node" + } +} diff --git a/backend/node_modules/openai/src/uploads.ts b/backend/node_modules/openai/src/uploads.ts new file mode 100644 index 0000000000000000000000000000000000000000..081827c9a17464b5d791ac5dd6a1a344db12d342 --- /dev/null +++ b/backend/node_modules/openai/src/uploads.ts @@ -0,0 +1,248 @@ +import { type RequestOptions } from './core'; +import { + FormData, + File, + type Blob, + type FilePropertyBag, + getMultipartRequestOptions, + type FsReadStream, + isFsReadStream, +} from './_shims/index'; +import { MultipartBody } from './_shims/MultipartBody'; +export { fileFromPath } from './_shims/index'; + +type BlobLikePart = string | ArrayBuffer | ArrayBufferView | BlobLike | Uint8Array | DataView; +export type BlobPart = string | ArrayBuffer | ArrayBufferView | Blob | Uint8Array | DataView; + +/** + * Typically, this is a native "File" class. + * + * We provide the {@link toFile} utility to convert a variety of objects + * into the File class. + * + * For convenience, you can also pass a fetch Response, or in Node, + * the result of fs.createReadStream(). + */ +export type Uploadable = FileLike | ResponseLike | FsReadStream; + +/** + * Intended to match web.Blob, node.Blob, node-fetch.Blob, etc. + */ +export interface BlobLike { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/size) */ + readonly size: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/type) */ + readonly type: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text) */ + text(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/slice) */ + slice(start?: number, end?: number): BlobLike; + // unfortunately @types/node-fetch@^2.6.4 doesn't type the arrayBuffer method +} + +/** + * Intended to match web.File, node.File, node-fetch.File, etc. + */ +export interface FileLike extends BlobLike { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified) */ + readonly lastModified: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name) */ + readonly name: string; +} + +/** + * Intended to match web.Response, node.Response, node-fetch.Response, etc. + */ +export interface ResponseLike { + url: string; + blob(): Promise; +} + +export const isResponseLike = (value: any): value is ResponseLike => + value != null && + typeof value === 'object' && + typeof value.url === 'string' && + typeof value.blob === 'function'; + +export const isFileLike = (value: any): value is FileLike => + value != null && + typeof value === 'object' && + typeof value.name === 'string' && + typeof value.lastModified === 'number' && + isBlobLike(value); + +/** + * The BlobLike type omits arrayBuffer() because @types/node-fetch@^2.6.4 lacks it; but this check + * adds the arrayBuffer() method type because it is available and used at runtime + */ +export const isBlobLike = (value: any): value is BlobLike & { arrayBuffer(): Promise } => + value != null && + typeof value === 'object' && + typeof value.size === 'number' && + typeof value.type === 'string' && + typeof value.text === 'function' && + typeof value.slice === 'function' && + typeof value.arrayBuffer === 'function'; + +export const isUploadable = (value: any): value is Uploadable => { + return isFileLike(value) || isResponseLike(value) || isFsReadStream(value); +}; + +export type ToFileInput = Uploadable | Exclude | AsyncIterable; + +/** + * Helper for creating a {@link File} to pass to an SDK upload method from a variety of different data formats + * @param value the raw content of the file. Can be an {@link Uploadable}, {@link BlobLikePart}, or {@link AsyncIterable} of {@link BlobLikePart}s + * @param {string=} name the name of the file. If omitted, toFile will try to determine a file name from bits if possible + * @param {Object=} options additional properties + * @param {string=} options.type the MIME type of the content + * @param {number=} options.lastModified the last modified timestamp + * @returns a {@link File} with the given properties + */ +export async function toFile( + value: ToFileInput | PromiseLike, + name?: string | null | undefined, + options?: FilePropertyBag | undefined, +): Promise { + // If it's a promise, resolve it. + value = await value; + + // Use the file's options if there isn't one provided + options ??= isFileLike(value) ? { lastModified: value.lastModified, type: value.type } : {}; + + if (isResponseLike(value)) { + const blob = await value.blob(); + name ||= new URL(value.url).pathname.split(/[\\/]/).pop() ?? 'unknown_file'; + + return new File([blob as any], name, options); + } + + const bits = await getBytes(value); + + name ||= getName(value) ?? 'unknown_file'; + + if (!options.type) { + const type = (bits[0] as any)?.type; + if (typeof type === 'string') { + options = { ...options, type }; + } + } + + return new File(bits, name, options); +} + +async function getBytes(value: ToFileInput): Promise> { + let parts: Array = []; + if ( + typeof value === 'string' || + ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc. + value instanceof ArrayBuffer + ) { + parts.push(value); + } else if (isBlobLike(value)) { + parts.push(await value.arrayBuffer()); + } else if ( + isAsyncIterableIterator(value) // includes Readable, ReadableStream, etc. + ) { + for await (const chunk of value) { + parts.push(chunk as BlobPart); // TODO, consider validating? + } + } else { + throw new Error( + `Unexpected data type: ${typeof value}; constructor: ${value?.constructor + ?.name}; props: ${propsForError(value)}`, + ); + } + + return parts; +} + +function propsForError(value: any): string { + const props = Object.getOwnPropertyNames(value); + return `[${props.map((p) => `"${p}"`).join(', ')}]`; +} + +function getName(value: any): string | undefined { + return ( + getStringFromMaybeBuffer(value.name) || + getStringFromMaybeBuffer(value.filename) || + // For fs.ReadStream + getStringFromMaybeBuffer(value.path)?.split(/[\\/]/).pop() + ); +} + +const getStringFromMaybeBuffer = (x: string | Buffer | unknown): string | undefined => { + if (typeof x === 'string') return x; + if (typeof Buffer !== 'undefined' && x instanceof Buffer) return String(x); + return undefined; +}; + +const isAsyncIterableIterator = (value: any): value is AsyncIterableIterator => + value != null && typeof value === 'object' && typeof value[Symbol.asyncIterator] === 'function'; + +export const isMultipartBody = (body: any): body is MultipartBody => + body && typeof body === 'object' && body.body && body[Symbol.toStringTag] === 'MultipartBody'; + +/** + * Returns a multipart/form-data request if any part of the given request body contains a File / Blob value. + * Otherwise returns the request as is. + */ +export const maybeMultipartFormRequestOptions = async >( + opts: RequestOptions, +): Promise> => { + if (!hasUploadableValue(opts.body)) return opts; + + const form = await createForm(opts.body); + return getMultipartRequestOptions(form, opts); +}; + +export const multipartFormRequestOptions = async >( + opts: RequestOptions, +): Promise> => { + const form = await createForm(opts.body); + return getMultipartRequestOptions(form, opts); +}; + +export const createForm = async >(body: T | undefined): Promise => { + const form = new FormData(); + await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue(form, key, value))); + return form; +}; + +const hasUploadableValue = (value: unknown): boolean => { + if (isUploadable(value)) return true; + if (Array.isArray(value)) return value.some(hasUploadableValue); + if (value && typeof value === 'object') { + for (const k in value) { + if (hasUploadableValue((value as any)[k])) return true; + } + } + return false; +}; + +const addFormValue = async (form: FormData, key: string, value: unknown): Promise => { + if (value === undefined) return; + if (value == null) { + throw new TypeError( + `Received null for "${key}"; to pass null in FormData, you must use the string 'null'`, + ); + } + + // TODO: make nested formats configurable + if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { + form.append(key, String(value)); + } else if (isUploadable(value)) { + const file = await toFile(value); + form.append(key, file as File); + } else if (Array.isArray(value)) { + await Promise.all(value.map((entry) => addFormValue(form, key + '[]', entry))); + } else if (typeof value === 'object') { + await Promise.all( + Object.entries(value).map(([name, prop]) => addFormValue(form, `${key}[${name}]`, prop)), + ); + } else { + throw new TypeError( + `Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`, + ); + } +}; diff --git a/backend/node_modules/openai/src/version.ts b/backend/node_modules/openai/src/version.ts new file mode 100644 index 0000000000000000000000000000000000000000..7ca672a0d0aa05baf16feb8419c7a1cc243392e0 --- /dev/null +++ b/backend/node_modules/openai/src/version.ts @@ -0,0 +1 @@ +export const VERSION = '4.35.0'; // x-release-please-version diff --git a/backend/node_modules/openai/streaming.d.ts b/backend/node_modules/openai/streaming.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..271494615436db96e36e493198aa4917e5195d09 --- /dev/null +++ b/backend/node_modules/openai/streaming.d.ts @@ -0,0 +1,41 @@ + +import { ReadableStream, type Response } from "./_shims/index.js"; +export type ServerSentEvent = { + event: string | null; + data: string; + raw: string[]; +}; +export declare class Stream implements AsyncIterable { + private iterator; + controller: AbortController; + constructor(iterator: () => AsyncIterator, controller: AbortController); + static fromSSEResponse(response: Response, controller: AbortController): Stream; + /** + * Generates a Stream from a newline-separated ReadableStream + * where each item is a JSON value. + */ + static fromReadableStream(readableStream: ReadableStream, controller: AbortController): Stream; + [Symbol.asyncIterator](): AsyncIterator; + /** + * Splits the stream into two streams which can be + * independently read from at different speeds. + */ + tee(): [Stream, Stream]; + /** + * Converts this stream to a newline-separated ReadableStream of + * JSON stringified values in the stream + * which can be turned back into a Stream with `Stream.fromReadableStream()`. + */ + toReadableStream(): ReadableStream; +} +export declare function _iterSSEMessages(response: Response, controller: AbortController): AsyncGenerator; +/** This is an internal helper function that's just used for testing */ +export declare function _decodeChunks(chunks: string[]): string[]; +/** + * Most browsers don't yet have async iterable support for ReadableStream, + * and Node has a very different way of reading bytes from its "ReadableStream". + * + * This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490 + */ +export declare function readableStreamAsyncIterable(stream: any): AsyncIterableIterator; +//# sourceMappingURL=streaming.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/streaming.d.ts.map b/backend/node_modules/openai/streaming.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..37c0f8d7b5f463d10f49ff683f524dae64e3d9db --- /dev/null +++ b/backend/node_modules/openai/streaming.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"streaming.d.ts","sourceRoot":"","sources":["src/streaming.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,cAAc,EAAE,KAAK,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAO/D,MAAM,MAAM,eAAe,GAAG;IAC5B,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB,IAAI,EAAE,MAAM,CAAC;IACb,GAAG,EAAE,MAAM,EAAE,CAAC;CACf,CAAC;AAEF,qBAAa,MAAM,CAAC,IAAI,CAAE,YAAW,aAAa,CAAC,IAAI,CAAC;IAIpD,OAAO,CAAC,QAAQ;IAHlB,UAAU,EAAE,eAAe,CAAC;gBAGlB,QAAQ,EAAE,MAAM,aAAa,CAAC,IAAI,CAAC,EAC3C,UAAU,EAAE,eAAe;IAK7B,MAAM,CAAC,eAAe,CAAC,IAAI,EAAE,QAAQ,EAAE,QAAQ,EAAE,UAAU,EAAE,eAAe;IAgE5E;;;OAGG;IACH,MAAM,CAAC,kBAAkB,CAAC,IAAI,EAAE,cAAc,EAAE,cAAc,EAAE,UAAU,EAAE,eAAe;IA2C3F,CAAC,MAAM,CAAC,aAAa,CAAC,IAAI,aAAa,CAAC,IAAI,CAAC;IAI7C;;;OAGG;IACH,GAAG,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC;IAwBnC;;;;OAIG;IACH,gBAAgB,IAAI,cAAc;CA0BnC;AAED,wBAAuB,gBAAgB,CACrC,QAAQ,EAAE,QAAQ,EAClB,UAAU,EAAE,eAAe,GAC1B,cAAc,CAAC,eAAe,EAAE,IAAI,EAAE,OAAO,CAAC,CAqBhD;AAyOD,uEAAuE;AACvE,wBAAgB,aAAa,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG,MAAM,EAAE,CAQxD;AAWD;;;;;GAKG;AACH,wBAAgB,2BAA2B,CAAC,CAAC,EAAE,MAAM,EAAE,GAAG,GAAG,qBAAqB,CAAC,CAAC,CAAC,CAyBpF"} \ No newline at end of file diff --git a/backend/node_modules/openai/streaming.js b/backend/node_modules/openai/streaming.js new file mode 100644 index 0000000000000000000000000000000000000000..8de507423e751d7ee469bb3e09459218056780a8 --- /dev/null +++ b/backend/node_modules/openai/streaming.js @@ -0,0 +1,433 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.readableStreamAsyncIterable = exports._decodeChunks = exports._iterSSEMessages = exports.Stream = void 0; +const index_1 = require("./_shims/index.js"); +const error_1 = require("./error.js"); +const error_2 = require("openai/error"); +class Stream { + constructor(iterator, controller) { + this.iterator = iterator; + this.controller = controller; + } + static fromSSEResponse(response, controller) { + let consumed = false; + async function* iterator() { + if (consumed) { + throw new Error('Cannot iterate over a consumed stream, use `.tee()` to split the stream.'); + } + consumed = true; + let done = false; + try { + for await (const sse of _iterSSEMessages(response, controller)) { + if (done) + continue; + if (sse.data.startsWith('[DONE]')) { + done = true; + continue; + } + if (sse.event === null) { + let data; + try { + data = JSON.parse(sse.data); + } + catch (e) { + console.error(`Could not parse message into JSON:`, sse.data); + console.error(`From chunk:`, sse.raw); + throw e; + } + if (data && data.error) { + throw new error_2.APIError(undefined, data.error, undefined, undefined); + } + yield data; + } + else { + let data; + try { + data = JSON.parse(sse.data); + } + catch (e) { + console.error(`Could not parse message into JSON:`, sse.data); + console.error(`From chunk:`, sse.raw); + throw e; + } + // TODO: Is this where the error should be thrown? + if (sse.event == 'error') { + throw new error_2.APIError(undefined, data.error, data.message, undefined); + } + yield { event: sse.event, data: data }; + } + } + done = true; + } + catch (e) { + // If the user calls `stream.controller.abort()`, we should exit without throwing. + if (e instanceof Error && e.name === 'AbortError') + return; + throw e; + } + finally { + // If the user `break`s, abort the ongoing request. + if (!done) + controller.abort(); + } + } + return new Stream(iterator, controller); + } + /** + * Generates a Stream from a newline-separated ReadableStream + * where each item is a JSON value. + */ + static fromReadableStream(readableStream, controller) { + let consumed = false; + async function* iterLines() { + const lineDecoder = new LineDecoder(); + const iter = readableStreamAsyncIterable(readableStream); + for await (const chunk of iter) { + for (const line of lineDecoder.decode(chunk)) { + yield line; + } + } + for (const line of lineDecoder.flush()) { + yield line; + } + } + async function* iterator() { + if (consumed) { + throw new Error('Cannot iterate over a consumed stream, use `.tee()` to split the stream.'); + } + consumed = true; + let done = false; + try { + for await (const line of iterLines()) { + if (done) + continue; + if (line) + yield JSON.parse(line); + } + done = true; + } + catch (e) { + // If the user calls `stream.controller.abort()`, we should exit without throwing. + if (e instanceof Error && e.name === 'AbortError') + return; + throw e; + } + finally { + // If the user `break`s, abort the ongoing request. + if (!done) + controller.abort(); + } + } + return new Stream(iterator, controller); + } + [Symbol.asyncIterator]() { + return this.iterator(); + } + /** + * Splits the stream into two streams which can be + * independently read from at different speeds. + */ + tee() { + const left = []; + const right = []; + const iterator = this.iterator(); + const teeIterator = (queue) => { + return { + next: () => { + if (queue.length === 0) { + const result = iterator.next(); + left.push(result); + right.push(result); + } + return queue.shift(); + }, + }; + }; + return [ + new Stream(() => teeIterator(left), this.controller), + new Stream(() => teeIterator(right), this.controller), + ]; + } + /** + * Converts this stream to a newline-separated ReadableStream of + * JSON stringified values in the stream + * which can be turned back into a Stream with `Stream.fromReadableStream()`. + */ + toReadableStream() { + const self = this; + let iter; + const encoder = new TextEncoder(); + return new index_1.ReadableStream({ + async start() { + iter = self[Symbol.asyncIterator](); + }, + async pull(ctrl) { + try { + const { value, done } = await iter.next(); + if (done) + return ctrl.close(); + const bytes = encoder.encode(JSON.stringify(value) + '\n'); + ctrl.enqueue(bytes); + } + catch (err) { + ctrl.error(err); + } + }, + async cancel() { + await iter.return?.(); + }, + }); + } +} +exports.Stream = Stream; +async function* _iterSSEMessages(response, controller) { + if (!response.body) { + controller.abort(); + throw new error_1.OpenAIError(`Attempted to iterate over a response with no body`); + } + const sseDecoder = new SSEDecoder(); + const lineDecoder = new LineDecoder(); + const iter = readableStreamAsyncIterable(response.body); + for await (const sseChunk of iterSSEChunks(iter)) { + for (const line of lineDecoder.decode(sseChunk)) { + const sse = sseDecoder.decode(line); + if (sse) + yield sse; + } + } + for (const line of lineDecoder.flush()) { + const sse = sseDecoder.decode(line); + if (sse) + yield sse; + } +} +exports._iterSSEMessages = _iterSSEMessages; +/** + * Given an async iterable iterator, iterates over it and yields full + * SSE chunks, i.e. yields when a double new-line is encountered. + */ +async function* iterSSEChunks(iterator) { + let data = new Uint8Array(); + for await (const chunk of iterator) { + if (chunk == null) { + continue; + } + const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) + : typeof chunk === 'string' ? new TextEncoder().encode(chunk) + : chunk; + let newData = new Uint8Array(data.length + binaryChunk.length); + newData.set(data); + newData.set(binaryChunk, data.length); + data = newData; + let patternIndex; + while ((patternIndex = findDoubleNewlineIndex(data)) !== -1) { + yield data.slice(0, patternIndex); + data = data.slice(patternIndex); + } + } + if (data.length > 0) { + yield data; + } +} +function findDoubleNewlineIndex(buffer) { + // This function searches the buffer for the end patterns (\r\r, \n\n, \r\n\r\n) + // and returns the index right after the first occurrence of any pattern, + // or -1 if none of the patterns are found. + const newline = 0x0a; // \n + const carriage = 0x0d; // \r + for (let i = 0; i < buffer.length - 2; i++) { + if (buffer[i] === newline && buffer[i + 1] === newline) { + // \n\n + return i + 2; + } + if (buffer[i] === carriage && buffer[i + 1] === carriage) { + // \r\r + return i + 2; + } + if (buffer[i] === carriage && + buffer[i + 1] === newline && + i + 3 < buffer.length && + buffer[i + 2] === carriage && + buffer[i + 3] === newline) { + // \r\n\r\n + return i + 4; + } + } + return -1; +} +class SSEDecoder { + constructor() { + this.event = null; + this.data = []; + this.chunks = []; + } + decode(line) { + if (line.endsWith('\r')) { + line = line.substring(0, line.length - 1); + } + if (!line) { + // empty line and we didn't previously encounter any messages + if (!this.event && !this.data.length) + return null; + const sse = { + event: this.event, + data: this.data.join('\n'), + raw: this.chunks, + }; + this.event = null; + this.data = []; + this.chunks = []; + return sse; + } + this.chunks.push(line); + if (line.startsWith(':')) { + return null; + } + let [fieldname, _, value] = partition(line, ':'); + if (value.startsWith(' ')) { + value = value.substring(1); + } + if (fieldname === 'event') { + this.event = value; + } + else if (fieldname === 'data') { + this.data.push(value); + } + return null; + } +} +/** + * A re-implementation of httpx's `LineDecoder` in Python that handles incrementally + * reading lines from text. + * + * https://github.com/encode/httpx/blob/920333ea98118e9cf617f246905d7b202510941c/httpx/_decoders.py#L258 + */ +class LineDecoder { + constructor() { + this.buffer = []; + this.trailingCR = false; + } + decode(chunk) { + let text = this.decodeText(chunk); + if (this.trailingCR) { + text = '\r' + text; + this.trailingCR = false; + } + if (text.endsWith('\r')) { + this.trailingCR = true; + text = text.slice(0, -1); + } + if (!text) { + return []; + } + const trailingNewline = LineDecoder.NEWLINE_CHARS.has(text[text.length - 1] || ''); + let lines = text.split(LineDecoder.NEWLINE_REGEXP); + // if there is a trailing new line then the last entry will be an empty + // string which we don't care about + if (trailingNewline) { + lines.pop(); + } + if (lines.length === 1 && !trailingNewline) { + this.buffer.push(lines[0]); + return []; + } + if (this.buffer.length > 0) { + lines = [this.buffer.join('') + lines[0], ...lines.slice(1)]; + this.buffer = []; + } + if (!trailingNewline) { + this.buffer = [lines.pop() || '']; + } + return lines; + } + decodeText(bytes) { + if (bytes == null) + return ''; + if (typeof bytes === 'string') + return bytes; + // Node: + if (typeof Buffer !== 'undefined') { + if (bytes instanceof Buffer) { + return bytes.toString(); + } + if (bytes instanceof Uint8Array) { + return Buffer.from(bytes).toString(); + } + throw new error_1.OpenAIError(`Unexpected: received non-Uint8Array (${bytes.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`); + } + // Browser + if (typeof TextDecoder !== 'undefined') { + if (bytes instanceof Uint8Array || bytes instanceof ArrayBuffer) { + this.textDecoder ?? (this.textDecoder = new TextDecoder('utf8')); + return this.textDecoder.decode(bytes); + } + throw new error_1.OpenAIError(`Unexpected: received non-Uint8Array/ArrayBuffer (${bytes.constructor.name}) in a web platform. Please report this error.`); + } + throw new error_1.OpenAIError(`Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.`); + } + flush() { + if (!this.buffer.length && !this.trailingCR) { + return []; + } + const lines = [this.buffer.join('')]; + this.buffer = []; + this.trailingCR = false; + return lines; + } +} +// prettier-ignore +LineDecoder.NEWLINE_CHARS = new Set(['\n', '\r']); +LineDecoder.NEWLINE_REGEXP = /\r\n|[\n\r]/g; +/** This is an internal helper function that's just used for testing */ +function _decodeChunks(chunks) { + const decoder = new LineDecoder(); + const lines = []; + for (const chunk of chunks) { + lines.push(...decoder.decode(chunk)); + } + return lines; +} +exports._decodeChunks = _decodeChunks; +function partition(str, delimiter) { + const index = str.indexOf(delimiter); + if (index !== -1) { + return [str.substring(0, index), delimiter, str.substring(index + delimiter.length)]; + } + return [str, '', '']; +} +/** + * Most browsers don't yet have async iterable support for ReadableStream, + * and Node has a very different way of reading bytes from its "ReadableStream". + * + * This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490 + */ +function readableStreamAsyncIterable(stream) { + if (stream[Symbol.asyncIterator]) + return stream; + const reader = stream.getReader(); + return { + async next() { + try { + const result = await reader.read(); + if (result?.done) + reader.releaseLock(); // release lock when stream becomes closed + return result; + } + catch (e) { + reader.releaseLock(); // release lock when stream becomes errored + throw e; + } + }, + async return() { + const cancelPromise = reader.cancel(); + reader.releaseLock(); + await cancelPromise; + return { done: true, value: undefined }; + }, + [Symbol.asyncIterator]() { + return this; + }, + }; +} +exports.readableStreamAsyncIterable = readableStreamAsyncIterable; +//# sourceMappingURL=streaming.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/streaming.js.map b/backend/node_modules/openai/streaming.js.map new file mode 100644 index 0000000000000000000000000000000000000000..636b39b74f07b559eed53476563205cd69d1f14f --- /dev/null +++ b/backend/node_modules/openai/streaming.js.map @@ -0,0 +1 @@ +{"version":3,"file":"streaming.js","sourceRoot":"","sources":["src/streaming.ts"],"names":[],"mappings":";;;AAAA,6CAA+D;AAC/D,sCAAsC;AAEtC,wCAAwC;AAUxC,MAAa,MAAM;IAGjB,YACU,QAAmC,EAC3C,UAA2B;QADnB,aAAQ,GAAR,QAAQ,CAA2B;QAG3C,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;IAC/B,CAAC;IAED,MAAM,CAAC,eAAe,CAAO,QAAkB,EAAE,UAA2B;QAC1E,IAAI,QAAQ,GAAG,KAAK,CAAC;QAErB,KAAK,SAAS,CAAC,CAAC,QAAQ;YACtB,IAAI,QAAQ,EAAE;gBACZ,MAAM,IAAI,KAAK,CAAC,0EAA0E,CAAC,CAAC;aAC7F;YACD,QAAQ,GAAG,IAAI,CAAC;YAChB,IAAI,IAAI,GAAG,KAAK,CAAC;YACjB,IAAI;gBACF,IAAI,KAAK,EAAE,MAAM,GAAG,IAAI,gBAAgB,CAAC,QAAQ,EAAE,UAAU,CAAC,EAAE;oBAC9D,IAAI,IAAI;wBAAE,SAAS;oBAEnB,IAAI,GAAG,CAAC,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,EAAE;wBACjC,IAAI,GAAG,IAAI,CAAC;wBACZ,SAAS;qBACV;oBAED,IAAI,GAAG,CAAC,KAAK,KAAK,IAAI,EAAE;wBACtB,IAAI,IAAI,CAAC;wBAET,IAAI;4BACF,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;yBAC7B;wBAAC,OAAO,CAAC,EAAE;4BACV,OAAO,CAAC,KAAK,CAAC,oCAAoC,EAAE,GAAG,CAAC,IAAI,CAAC,CAAC;4BAC9D,OAAO,CAAC,K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AAE,CAAC;gBACnC,IAAI,MAAM,EAAE,IAAI;oBAAE,MAAM,CAAC,WAAW,EAAE,CAAC,CAAC,0CAA0C;gBAClF,OAAO,MAAM,CAAC;aACf;YAAC,OAAO,CAAC,EAAE;gBACV,MAAM,CAAC,WAAW,EAAE,CAAC,CAAC,2CAA2C;gBACjE,MAAM,CAAC,CAAC;aACT;QACH,CAAC;QACD,KAAK,CAAC,MAAM;YACV,MAAM,aAAa,GAAG,MAAM,CAAC,MAAM,EAAE,CAAC;YACtC,MAAM,CAAC,WAAW,EAAE,CAAC;YACrB,MAAM,aAAa,CAAC;YACpB,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,SAAS,EAAE,CAAC;QAC1C,CAAC;QACD,CAAC,MAAM,CAAC,aAAa,CAAC;YACpB,OAAO,IAAI,CAAC;QACd,CAAC;KACF,CAAC;AACJ,CAAC;AAzBD,kEAyBC"} \ No newline at end of file diff --git a/backend/node_modules/openai/streaming.mjs b/backend/node_modules/openai/streaming.mjs new file mode 100644 index 0000000000000000000000000000000000000000..db474d8cfa9ab619db24593442a2b0cbe5208b40 --- /dev/null +++ b/backend/node_modules/openai/streaming.mjs @@ -0,0 +1,426 @@ +import { ReadableStream } from "./_shims/index.mjs"; +import { OpenAIError } from "./error.mjs"; +import { APIError } from 'openai/error'; +export class Stream { + constructor(iterator, controller) { + this.iterator = iterator; + this.controller = controller; + } + static fromSSEResponse(response, controller) { + let consumed = false; + async function* iterator() { + if (consumed) { + throw new Error('Cannot iterate over a consumed stream, use `.tee()` to split the stream.'); + } + consumed = true; + let done = false; + try { + for await (const sse of _iterSSEMessages(response, controller)) { + if (done) + continue; + if (sse.data.startsWith('[DONE]')) { + done = true; + continue; + } + if (sse.event === null) { + let data; + try { + data = JSON.parse(sse.data); + } + catch (e) { + console.error(`Could not parse message into JSON:`, sse.data); + console.error(`From chunk:`, sse.raw); + throw e; + } + if (data && data.error) { + throw new APIError(undefined, data.error, undefined, undefined); + } + yield data; + } + else { + let data; + try { + data = JSON.parse(sse.data); + } + catch (e) { + console.error(`Could not parse message into JSON:`, sse.data); + console.error(`From chunk:`, sse.raw); + throw e; + } + // TODO: Is this where the error should be thrown? + if (sse.event == 'error') { + throw new APIError(undefined, data.error, data.message, undefined); + } + yield { event: sse.event, data: data }; + } + } + done = true; + } + catch (e) { + // If the user calls `stream.controller.abort()`, we should exit without throwing. + if (e instanceof Error && e.name === 'AbortError') + return; + throw e; + } + finally { + // If the user `break`s, abort the ongoing request. + if (!done) + controller.abort(); + } + } + return new Stream(iterator, controller); + } + /** + * Generates a Stream from a newline-separated ReadableStream + * where each item is a JSON value. + */ + static fromReadableStream(readableStream, controller) { + let consumed = false; + async function* iterLines() { + const lineDecoder = new LineDecoder(); + const iter = readableStreamAsyncIterable(readableStream); + for await (const chunk of iter) { + for (const line of lineDecoder.decode(chunk)) { + yield line; + } + } + for (const line of lineDecoder.flush()) { + yield line; + } + } + async function* iterator() { + if (consumed) { + throw new Error('Cannot iterate over a consumed stream, use `.tee()` to split the stream.'); + } + consumed = true; + let done = false; + try { + for await (const line of iterLines()) { + if (done) + continue; + if (line) + yield JSON.parse(line); + } + done = true; + } + catch (e) { + // If the user calls `stream.controller.abort()`, we should exit without throwing. + if (e instanceof Error && e.name === 'AbortError') + return; + throw e; + } + finally { + // If the user `break`s, abort the ongoing request. + if (!done) + controller.abort(); + } + } + return new Stream(iterator, controller); + } + [Symbol.asyncIterator]() { + return this.iterator(); + } + /** + * Splits the stream into two streams which can be + * independently read from at different speeds. + */ + tee() { + const left = []; + const right = []; + const iterator = this.iterator(); + const teeIterator = (queue) => { + return { + next: () => { + if (queue.length === 0) { + const result = iterator.next(); + left.push(result); + right.push(result); + } + return queue.shift(); + }, + }; + }; + return [ + new Stream(() => teeIterator(left), this.controller), + new Stream(() => teeIterator(right), this.controller), + ]; + } + /** + * Converts this stream to a newline-separated ReadableStream of + * JSON stringified values in the stream + * which can be turned back into a Stream with `Stream.fromReadableStream()`. + */ + toReadableStream() { + const self = this; + let iter; + const encoder = new TextEncoder(); + return new ReadableStream({ + async start() { + iter = self[Symbol.asyncIterator](); + }, + async pull(ctrl) { + try { + const { value, done } = await iter.next(); + if (done) + return ctrl.close(); + const bytes = encoder.encode(JSON.stringify(value) + '\n'); + ctrl.enqueue(bytes); + } + catch (err) { + ctrl.error(err); + } + }, + async cancel() { + await iter.return?.(); + }, + }); + } +} +export async function* _iterSSEMessages(response, controller) { + if (!response.body) { + controller.abort(); + throw new OpenAIError(`Attempted to iterate over a response with no body`); + } + const sseDecoder = new SSEDecoder(); + const lineDecoder = new LineDecoder(); + const iter = readableStreamAsyncIterable(response.body); + for await (const sseChunk of iterSSEChunks(iter)) { + for (const line of lineDecoder.decode(sseChunk)) { + const sse = sseDecoder.decode(line); + if (sse) + yield sse; + } + } + for (const line of lineDecoder.flush()) { + const sse = sseDecoder.decode(line); + if (sse) + yield sse; + } +} +/** + * Given an async iterable iterator, iterates over it and yields full + * SSE chunks, i.e. yields when a double new-line is encountered. + */ +async function* iterSSEChunks(iterator) { + let data = new Uint8Array(); + for await (const chunk of iterator) { + if (chunk == null) { + continue; + } + const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) + : typeof chunk === 'string' ? new TextEncoder().encode(chunk) + : chunk; + let newData = new Uint8Array(data.length + binaryChunk.length); + newData.set(data); + newData.set(binaryChunk, data.length); + data = newData; + let patternIndex; + while ((patternIndex = findDoubleNewlineIndex(data)) !== -1) { + yield data.slice(0, patternIndex); + data = data.slice(patternIndex); + } + } + if (data.length > 0) { + yield data; + } +} +function findDoubleNewlineIndex(buffer) { + // This function searches the buffer for the end patterns (\r\r, \n\n, \r\n\r\n) + // and returns the index right after the first occurrence of any pattern, + // or -1 if none of the patterns are found. + const newline = 0x0a; // \n + const carriage = 0x0d; // \r + for (let i = 0; i < buffer.length - 2; i++) { + if (buffer[i] === newline && buffer[i + 1] === newline) { + // \n\n + return i + 2; + } + if (buffer[i] === carriage && buffer[i + 1] === carriage) { + // \r\r + return i + 2; + } + if (buffer[i] === carriage && + buffer[i + 1] === newline && + i + 3 < buffer.length && + buffer[i + 2] === carriage && + buffer[i + 3] === newline) { + // \r\n\r\n + return i + 4; + } + } + return -1; +} +class SSEDecoder { + constructor() { + this.event = null; + this.data = []; + this.chunks = []; + } + decode(line) { + if (line.endsWith('\r')) { + line = line.substring(0, line.length - 1); + } + if (!line) { + // empty line and we didn't previously encounter any messages + if (!this.event && !this.data.length) + return null; + const sse = { + event: this.event, + data: this.data.join('\n'), + raw: this.chunks, + }; + this.event = null; + this.data = []; + this.chunks = []; + return sse; + } + this.chunks.push(line); + if (line.startsWith(':')) { + return null; + } + let [fieldname, _, value] = partition(line, ':'); + if (value.startsWith(' ')) { + value = value.substring(1); + } + if (fieldname === 'event') { + this.event = value; + } + else if (fieldname === 'data') { + this.data.push(value); + } + return null; + } +} +/** + * A re-implementation of httpx's `LineDecoder` in Python that handles incrementally + * reading lines from text. + * + * https://github.com/encode/httpx/blob/920333ea98118e9cf617f246905d7b202510941c/httpx/_decoders.py#L258 + */ +class LineDecoder { + constructor() { + this.buffer = []; + this.trailingCR = false; + } + decode(chunk) { + let text = this.decodeText(chunk); + if (this.trailingCR) { + text = '\r' + text; + this.trailingCR = false; + } + if (text.endsWith('\r')) { + this.trailingCR = true; + text = text.slice(0, -1); + } + if (!text) { + return []; + } + const trailingNewline = LineDecoder.NEWLINE_CHARS.has(text[text.length - 1] || ''); + let lines = text.split(LineDecoder.NEWLINE_REGEXP); + // if there is a trailing new line then the last entry will be an empty + // string which we don't care about + if (trailingNewline) { + lines.pop(); + } + if (lines.length === 1 && !trailingNewline) { + this.buffer.push(lines[0]); + return []; + } + if (this.buffer.length > 0) { + lines = [this.buffer.join('') + lines[0], ...lines.slice(1)]; + this.buffer = []; + } + if (!trailingNewline) { + this.buffer = [lines.pop() || '']; + } + return lines; + } + decodeText(bytes) { + if (bytes == null) + return ''; + if (typeof bytes === 'string') + return bytes; + // Node: + if (typeof Buffer !== 'undefined') { + if (bytes instanceof Buffer) { + return bytes.toString(); + } + if (bytes instanceof Uint8Array) { + return Buffer.from(bytes).toString(); + } + throw new OpenAIError(`Unexpected: received non-Uint8Array (${bytes.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`); + } + // Browser + if (typeof TextDecoder !== 'undefined') { + if (bytes instanceof Uint8Array || bytes instanceof ArrayBuffer) { + this.textDecoder ?? (this.textDecoder = new TextDecoder('utf8')); + return this.textDecoder.decode(bytes); + } + throw new OpenAIError(`Unexpected: received non-Uint8Array/ArrayBuffer (${bytes.constructor.name}) in a web platform. Please report this error.`); + } + throw new OpenAIError(`Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.`); + } + flush() { + if (!this.buffer.length && !this.trailingCR) { + return []; + } + const lines = [this.buffer.join('')]; + this.buffer = []; + this.trailingCR = false; + return lines; + } +} +// prettier-ignore +LineDecoder.NEWLINE_CHARS = new Set(['\n', '\r']); +LineDecoder.NEWLINE_REGEXP = /\r\n|[\n\r]/g; +/** This is an internal helper function that's just used for testing */ +export function _decodeChunks(chunks) { + const decoder = new LineDecoder(); + const lines = []; + for (const chunk of chunks) { + lines.push(...decoder.decode(chunk)); + } + return lines; +} +function partition(str, delimiter) { + const index = str.indexOf(delimiter); + if (index !== -1) { + return [str.substring(0, index), delimiter, str.substring(index + delimiter.length)]; + } + return [str, '', '']; +} +/** + * Most browsers don't yet have async iterable support for ReadableStream, + * and Node has a very different way of reading bytes from its "ReadableStream". + * + * This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490 + */ +export function readableStreamAsyncIterable(stream) { + if (stream[Symbol.asyncIterator]) + return stream; + const reader = stream.getReader(); + return { + async next() { + try { + const result = await reader.read(); + if (result?.done) + reader.releaseLock(); // release lock when stream becomes closed + return result; + } + catch (e) { + reader.releaseLock(); // release lock when stream becomes errored + throw e; + } + }, + async return() { + const cancelPromise = reader.cancel(); + reader.releaseLock(); + await cancelPromise; + return { done: true, value: undefined }; + }, + [Symbol.asyncIterator]() { + return this; + }, + }; +} +//# sourceMappingURL=streaming.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/streaming.mjs.map b/backend/node_modules/openai/streaming.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..8f46d7b22717ac80bbb20c1899c370e755a0f62b --- /dev/null +++ b/backend/node_modules/openai/streaming.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"streaming.mjs","sourceRoot":"","sources":["src/streaming.ts"],"names":[],"mappings":"OAAO,EAAE,cAAc,EAAiB;OACjC,EAAE,WAAW,EAAE;OAEf,EAAE,QAAQ,EAAE,MAAM,cAAc;AAUvC,MAAM,OAAO,MAAM;IAGjB,YACU,QAAmC,EAC3C,UAA2B;QADnB,aAAQ,GAAR,QAAQ,CAA2B;QAG3C,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;IAC/B,CAAC;IAED,MAAM,CAAC,eAAe,CAAO,QAAkB,EAAE,UAA2B;QAC1E,IAAI,QAAQ,GAAG,KAAK,CAAC;QAErB,KAAK,SAAS,CAAC,CAAC,QAAQ;YACtB,IAAI,QAAQ,EAAE;gBACZ,MAAM,IAAI,KAAK,CAAC,0EAA0E,CAAC,CAAC;aAC7F;YACD,QAAQ,GAAG,IAAI,CAAC;YAChB,IAAI,IAAI,GAAG,KAAK,CAAC;YACjB,IAAI;gBACF,IAAI,KAAK,EAAE,MAAM,GAAG,IAAI,gBAAgB,CAAC,QAAQ,EAAE,UAAU,CAAC,EAAE;oBAC9D,IAAI,IAAI;wBAAE,SAAS;oBAEnB,IAAI,GAAG,CAAC,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,EAAE;wBACjC,IAAI,GAAG,IAAI,CAAC;wBACZ,SAAS;qBACV;oBAED,IAAI,GAAG,CAAC,KAAK,KAAK,IAAI,EAAE;wBACtB,IAAI,IAAI,CAAC;wBAET,IAAI;4BACF,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,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AM,CAAC,SAAS,EAAE,CAAC;IAClC,OAAO;QACL,KAAK,CAAC,IAAI;YACR,IAAI;gBACF,MAAM,MAAM,GAAG,MAAM,MAAM,CAAC,IAAI,EAAE,CAAC;gBACnC,IAAI,MAAM,EAAE,IAAI;oBAAE,MAAM,CAAC,WAAW,EAAE,CAAC,CAAC,0CAA0C;gBAClF,OAAO,MAAM,CAAC;aACf;YAAC,OAAO,CAAC,EAAE;gBACV,MAAM,CAAC,WAAW,EAAE,CAAC,CAAC,2CAA2C;gBACjE,MAAM,CAAC,CAAC;aACT;QACH,CAAC;QACD,KAAK,CAAC,MAAM;YACV,MAAM,aAAa,GAAG,MAAM,CAAC,MAAM,EAAE,CAAC;YACtC,MAAM,CAAC,WAAW,EAAE,CAAC;YACrB,MAAM,aAAa,CAAC;YACpB,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,SAAS,EAAE,CAAC;QAC1C,CAAC;QACD,CAAC,MAAM,CAAC,aAAa,CAAC;YACpB,OAAO,IAAI,CAAC;QACd,CAAC;KACF,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/openai/uploads.d.ts b/backend/node_modules/openai/uploads.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..55faa0c5a7b49b230f85341897421c0dc643a63f --- /dev/null +++ b/backend/node_modules/openai/uploads.d.ts @@ -0,0 +1,75 @@ +import { type RequestOptions } from "./core.js"; +import { FormData, type Blob, type FilePropertyBag, type FsReadStream } from "./_shims/index.js"; +import { MultipartBody } from "./_shims/MultipartBody.js"; +export { fileFromPath } from "./_shims/index.js"; +type BlobLikePart = string | ArrayBuffer | ArrayBufferView | BlobLike | Uint8Array | DataView; +export type BlobPart = string | ArrayBuffer | ArrayBufferView | Blob | Uint8Array | DataView; +/** + * Typically, this is a native "File" class. + * + * We provide the {@link toFile} utility to convert a variety of objects + * into the File class. + * + * For convenience, you can also pass a fetch Response, or in Node, + * the result of fs.createReadStream(). + */ +export type Uploadable = FileLike | ResponseLike | FsReadStream; +/** + * Intended to match web.Blob, node.Blob, node-fetch.Blob, etc. + */ +export interface BlobLike { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/size) */ + readonly size: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/type) */ + readonly type: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text) */ + text(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/slice) */ + slice(start?: number, end?: number): BlobLike; +} +/** + * Intended to match web.File, node.File, node-fetch.File, etc. + */ +export interface FileLike extends BlobLike { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified) */ + readonly lastModified: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name) */ + readonly name: string; +} +/** + * Intended to match web.Response, node.Response, node-fetch.Response, etc. + */ +export interface ResponseLike { + url: string; + blob(): Promise; +} +export declare const isResponseLike: (value: any) => value is ResponseLike; +export declare const isFileLike: (value: any) => value is FileLike; +/** + * The BlobLike type omits arrayBuffer() because @types/node-fetch@^2.6.4 lacks it; but this check + * adds the arrayBuffer() method type because it is available and used at runtime + */ +export declare const isBlobLike: (value: any) => value is BlobLike & { + arrayBuffer(): Promise; +}; +export declare const isUploadable: (value: any) => value is Uploadable; +export type ToFileInput = Uploadable | Exclude | AsyncIterable; +/** + * Helper for creating a {@link File} to pass to an SDK upload method from a variety of different data formats + * @param value the raw content of the file. Can be an {@link Uploadable}, {@link BlobLikePart}, or {@link AsyncIterable} of {@link BlobLikePart}s + * @param {string=} name the name of the file. If omitted, toFile will try to determine a file name from bits if possible + * @param {Object=} options additional properties + * @param {string=} options.type the MIME type of the content + * @param {number=} options.lastModified the last modified timestamp + * @returns a {@link File} with the given properties + */ +export declare function toFile(value: ToFileInput | PromiseLike, name?: string | null | undefined, options?: FilePropertyBag | undefined): Promise; +export declare const isMultipartBody: (body: any) => body is MultipartBody; +/** + * Returns a multipart/form-data request if any part of the given request body contains a File / Blob value. + * Otherwise returns the request as is. + */ +export declare const maybeMultipartFormRequestOptions: >(opts: RequestOptions) => Promise>; +export declare const multipartFormRequestOptions: >(opts: RequestOptions) => Promise>; +export declare const createForm: >(body: T | undefined) => Promise; +//# sourceMappingURL=uploads.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/uploads.d.ts.map b/backend/node_modules/openai/uploads.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..bc6af28f82f210c94aefdef2ddddd764aebf3ca2 --- /dev/null +++ b/backend/node_modules/openai/uploads.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"uploads.d.ts","sourceRoot":"","sources":["src/uploads.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,cAAc,EAAE,MAAM,QAAQ,CAAC;AAC7C,OAAO,EACL,QAAQ,EAER,KAAK,IAAI,EACT,KAAK,eAAe,EAEpB,KAAK,YAAY,EAElB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AACvD,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAE9C,KAAK,YAAY,GAAG,MAAM,GAAG,WAAW,GAAG,eAAe,GAAG,QAAQ,GAAG,UAAU,GAAG,QAAQ,CAAC;AAC9F,MAAM,MAAM,QAAQ,GAAG,MAAM,GAAG,WAAW,GAAG,eAAe,GAAG,IAAI,GAAG,UAAU,GAAG,QAAQ,CAAC;AAE7F;;;;;;;;GAQG;AACH,MAAM,MAAM,UAAU,GAAG,QAAQ,GAAG,YAAY,GAAG,YAAY,CAAC;AAEhE;;GAEG;AACH,MAAM,WAAW,QAAQ;IACvB,4EAA4E;IAC5E,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,4EAA4E;IAC5E,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,4EAA4E;IAC5E,IAAI,IAAI,OAAO,CAAC,MAAM,CAAC,CAAC;IACxB,6EAA6E;IAC7E,KAAK,C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uploads.js new file mode 100644 index 0000000000000000000000000000000000000000..0b921f8330e179763dae2631f3dc648dded561e8 --- /dev/null +++ b/backend/node_modules/openai/uploads.js @@ -0,0 +1,165 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createForm = exports.multipartFormRequestOptions = exports.maybeMultipartFormRequestOptions = exports.isMultipartBody = exports.toFile = exports.isUploadable = exports.isBlobLike = exports.isFileLike = exports.isResponseLike = exports.fileFromPath = void 0; +const index_1 = require("./_shims/index.js"); +var index_2 = require("./_shims/index.js"); +Object.defineProperty(exports, "fileFromPath", { enumerable: true, get: function () { return index_2.fileFromPath; } }); +const isResponseLike = (value) => value != null && + typeof value === 'object' && + typeof value.url === 'string' && + typeof value.blob === 'function'; +exports.isResponseLike = isResponseLike; +const isFileLike = (value) => value != null && + typeof value === 'object' && + typeof value.name === 'string' && + typeof value.lastModified === 'number' && + (0, exports.isBlobLike)(value); +exports.isFileLike = isFileLike; +/** + * The BlobLike type omits arrayBuffer() because @types/node-fetch@^2.6.4 lacks it; but this check + * adds the arrayBuffer() method type because it is available and used at runtime + */ +const isBlobLike = (value) => value != null && + typeof value === 'object' && + typeof value.size === 'number' && + typeof value.type === 'string' && + typeof value.text === 'function' && + typeof value.slice === 'function' && + typeof value.arrayBuffer === 'function'; +exports.isBlobLike = isBlobLike; +const isUploadable = (value) => { + return (0, exports.isFileLike)(value) || (0, exports.isResponseLike)(value) || (0, index_1.isFsReadStream)(value); +}; +exports.isUploadable = isUploadable; +/** + * Helper for creating a {@link File} to pass to an SDK upload method from a variety of different data formats + * @param value the raw content of the file. Can be an {@link Uploadable}, {@link BlobLikePart}, or {@link AsyncIterable} of {@link BlobLikePart}s + * @param {string=} name the name of the file. If omitted, toFile will try to determine a file name from bits if possible + * @param {Object=} options additional properties + * @param {string=} options.type the MIME type of the content + * @param {number=} options.lastModified the last modified timestamp + * @returns a {@link File} with the given properties + */ +async function toFile(value, name, options) { + // If it's a promise, resolve it. + value = await value; + // Use the file's options if there isn't one provided + options ?? (options = (0, exports.isFileLike)(value) ? { lastModified: value.lastModified, type: value.type } : {}); + if ((0, exports.isResponseLike)(value)) { + const blob = await value.blob(); + name || (name = new URL(value.url).pathname.split(/[\\/]/).pop() ?? 'unknown_file'); + return new index_1.File([blob], name, options); + } + const bits = await getBytes(value); + name || (name = getName(value) ?? 'unknown_file'); + if (!options.type) { + const type = bits[0]?.type; + if (typeof type === 'string') { + options = { ...options, type }; + } + } + return new index_1.File(bits, name, options); +} +exports.toFile = toFile; +async function getBytes(value) { + let parts = []; + if (typeof value === 'string' || + ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc. + value instanceof ArrayBuffer) { + parts.push(value); + } + else if ((0, exports.isBlobLike)(value)) { + parts.push(await value.arrayBuffer()); + } + else if (isAsyncIterableIterator(value) // includes Readable, ReadableStream, etc. + ) { + for await (const chunk of value) { + parts.push(chunk); // TODO, consider validating? + } + } + else { + throw new Error(`Unexpected data type: ${typeof value}; constructor: ${value?.constructor + ?.name}; props: ${propsForError(value)}`); + } + return parts; +} +function propsForError(value) { + const props = Object.getOwnPropertyNames(value); + return `[${props.map((p) => `"${p}"`).join(', ')}]`; +} +function getName(value) { + return (getStringFromMaybeBuffer(value.name) || + getStringFromMaybeBuffer(value.filename) || + // For fs.ReadStream + getStringFromMaybeBuffer(value.path)?.split(/[\\/]/).pop()); +} +const getStringFromMaybeBuffer = (x) => { + if (typeof x === 'string') + return x; + if (typeof Buffer !== 'undefined' && x instanceof Buffer) + return String(x); + return undefined; +}; +const isAsyncIterableIterator = (value) => value != null && typeof value === 'object' && typeof value[Symbol.asyncIterator] === 'function'; +const isMultipartBody = (body) => body && typeof body === 'object' && body.body && body[Symbol.toStringTag] === 'MultipartBody'; +exports.isMultipartBody = isMultipartBody; +/** + * Returns a multipart/form-data request if any part of the given request body contains a File / Blob value. + * Otherwise returns the request as is. + */ +const maybeMultipartFormRequestOptions = async (opts) => { + if (!hasUploadableValue(opts.body)) + return opts; + const form = await (0, exports.createForm)(opts.body); + return (0, index_1.getMultipartRequestOptions)(form, opts); +}; +exports.maybeMultipartFormRequestOptions = maybeMultipartFormRequestOptions; +const multipartFormRequestOptions = async (opts) => { + const form = await (0, exports.createForm)(opts.body); + return (0, index_1.getMultipartRequestOptions)(form, opts); +}; +exports.multipartFormRequestOptions = multipartFormRequestOptions; +const createForm = async (body) => { + const form = new index_1.FormData(); + await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue(form, key, value))); + return form; +}; +exports.createForm = createForm; +const hasUploadableValue = (value) => { + if ((0, exports.isUploadable)(value)) + return true; + if (Array.isArray(value)) + return value.some(hasUploadableValue); + if (value && typeof value === 'object') { + for (const k in value) { + if (hasUploadableValue(value[k])) + return true; + } + } + return false; +}; +const addFormValue = async (form, key, value) => { + if (value === undefined) + return; + if (value == null) { + throw new TypeError(`Received null for "${key}"; to pass null in FormData, you must use the string 'null'`); + } + // TODO: make nested formats configurable + if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { + form.append(key, String(value)); + } + else if ((0, exports.isUploadable)(value)) { + const file = await toFile(value); + form.append(key, file); + } + else if (Array.isArray(value)) { + await Promise.all(value.map((entry) => addFormValue(form, key + '[]', entry))); + } + else if (typeof value === 'object') { + await Promise.all(Object.entries(value).map(([name, prop]) => addFormValue(form, `${key}[${name}]`, prop))); + } + else { + throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`); + } +}; +//# sourceMappingURL=uploads.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/uploads.js.map b/backend/node_modules/openai/uploads.js.map new file mode 100644 index 0000000000000000000000000000000000000000..772d42ba0ddcd7d431a51b9826b9b3a19c18aa1c --- /dev/null +++ b/backend/node_modules/openai/uploads.js.map @@ -0,0 +1 @@ +{"version":3,"file":"uploads.js","sourceRoot":"","sources":["src/uploads.ts"],"names":[],"mappings":";;;AACA,6CAQwB;AAExB,2CAA8C;AAArC,qGAAA,YAAY,OAAA;AAiDd,MAAM,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C;SAAM,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE;QAC/B,MAAM,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,YAAY,CAAC,IAAI,EAAE,GAAG,GAAG,IAAI,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC;KAChF;SAAM,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;QACpC,MAAM,OAAO,CAAC,GAAG,CACf,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,IAAI,CAAC,EAAE,EAAE,CAAC,YAAY,CAAC,IAAI,EAAE,GAAG,GAAG,IAAI,IAAI,GAAG,EAAE,IAAI,CAAC,CAAC,CACzF,CAAC;KACH;SAAM;QACL,MAAM,IAAI,SAAS,CACjB,wGAAwG,KAAK,UAAU,CACxH,CAAC;KACH;AACH,CAAC,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/openai/uploads.mjs b/backend/node_modules/openai/uploads.mjs new file mode 100644 index 0000000000000000000000000000000000000000..a365385aaea478135730c9ef90fc5d02d80188ff --- /dev/null +++ b/backend/node_modules/openai/uploads.mjs @@ -0,0 +1,152 @@ +import { FormData, File, getMultipartRequestOptions, isFsReadStream, } from "./_shims/index.mjs"; +export { fileFromPath } from "./_shims/index.mjs"; +export const isResponseLike = (value) => value != null && + typeof value === 'object' && + typeof value.url === 'string' && + typeof value.blob === 'function'; +export const isFileLike = (value) => value != null && + typeof value === 'object' && + typeof value.name === 'string' && + typeof value.lastModified === 'number' && + isBlobLike(value); +/** + * The BlobLike type omits arrayBuffer() because @types/node-fetch@^2.6.4 lacks it; but this check + * adds the arrayBuffer() method type because it is available and used at runtime + */ +export const isBlobLike = (value) => value != null && + typeof value === 'object' && + typeof value.size === 'number' && + typeof value.type === 'string' && + typeof value.text === 'function' && + typeof value.slice === 'function' && + typeof value.arrayBuffer === 'function'; +export const isUploadable = (value) => { + return isFileLike(value) || isResponseLike(value) || isFsReadStream(value); +}; +/** + * Helper for creating a {@link File} to pass to an SDK upload method from a variety of different data formats + * @param value the raw content of the file. Can be an {@link Uploadable}, {@link BlobLikePart}, or {@link AsyncIterable} of {@link BlobLikePart}s + * @param {string=} name the name of the file. If omitted, toFile will try to determine a file name from bits if possible + * @param {Object=} options additional properties + * @param {string=} options.type the MIME type of the content + * @param {number=} options.lastModified the last modified timestamp + * @returns a {@link File} with the given properties + */ +export async function toFile(value, name, options) { + // If it's a promise, resolve it. + value = await value; + // Use the file's options if there isn't one provided + options ?? (options = isFileLike(value) ? { lastModified: value.lastModified, type: value.type } : {}); + if (isResponseLike(value)) { + const blob = await value.blob(); + name || (name = new URL(value.url).pathname.split(/[\\/]/).pop() ?? 'unknown_file'); + return new File([blob], name, options); + } + const bits = await getBytes(value); + name || (name = getName(value) ?? 'unknown_file'); + if (!options.type) { + const type = bits[0]?.type; + if (typeof type === 'string') { + options = { ...options, type }; + } + } + return new File(bits, name, options); +} +async function getBytes(value) { + let parts = []; + if (typeof value === 'string' || + ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc. + value instanceof ArrayBuffer) { + parts.push(value); + } + else if (isBlobLike(value)) { + parts.push(await value.arrayBuffer()); + } + else if (isAsyncIterableIterator(value) // includes Readable, ReadableStream, etc. + ) { + for await (const chunk of value) { + parts.push(chunk); // TODO, consider validating? + } + } + else { + throw new Error(`Unexpected data type: ${typeof value}; constructor: ${value?.constructor + ?.name}; props: ${propsForError(value)}`); + } + return parts; +} +function propsForError(value) { + const props = Object.getOwnPropertyNames(value); + return `[${props.map((p) => `"${p}"`).join(', ')}]`; +} +function getName(value) { + return (getStringFromMaybeBuffer(value.name) || + getStringFromMaybeBuffer(value.filename) || + // For fs.ReadStream + getStringFromMaybeBuffer(value.path)?.split(/[\\/]/).pop()); +} +const getStringFromMaybeBuffer = (x) => { + if (typeof x === 'string') + return x; + if (typeof Buffer !== 'undefined' && x instanceof Buffer) + return String(x); + return undefined; +}; +const isAsyncIterableIterator = (value) => value != null && typeof value === 'object' && typeof value[Symbol.asyncIterator] === 'function'; +export const isMultipartBody = (body) => body && typeof body === 'object' && body.body && body[Symbol.toStringTag] === 'MultipartBody'; +/** + * Returns a multipart/form-data request if any part of the given request body contains a File / Blob value. + * Otherwise returns the request as is. + */ +export const maybeMultipartFormRequestOptions = async (opts) => { + if (!hasUploadableValue(opts.body)) + return opts; + const form = await createForm(opts.body); + return getMultipartRequestOptions(form, opts); +}; +export const multipartFormRequestOptions = async (opts) => { + const form = await createForm(opts.body); + return getMultipartRequestOptions(form, opts); +}; +export const createForm = async (body) => { + const form = new FormData(); + await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue(form, key, value))); + return form; +}; +const hasUploadableValue = (value) => { + if (isUploadable(value)) + return true; + if (Array.isArray(value)) + return value.some(hasUploadableValue); + if (value && typeof value === 'object') { + for (const k in value) { + if (hasUploadableValue(value[k])) + return true; + } + } + return false; +}; +const addFormValue = async (form, key, value) => { + if (value === undefined) + return; + if (value == null) { + throw new TypeError(`Received null for "${key}"; to pass null in FormData, you must use the string 'null'`); + } + // TODO: make nested formats configurable + if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { + form.append(key, String(value)); + } + else if (isUploadable(value)) { + const file = await toFile(value); + form.append(key, file); + } + else if (Array.isArray(value)) { + await Promise.all(value.map((entry) => addFormValue(form, key + '[]', entry))); + } + else if (typeof value === 'object') { + await Promise.all(Object.entries(value).map(([name, prop]) => addFormValue(form, `${key}[${name}]`, prop))); + } + else { + throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`); + } +}; +//# sourceMappingURL=uploads.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/uploads.mjs.map b/backend/node_modules/openai/uploads.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..9485e0128431e67a2580f37ffed93bd54836d76a --- /dev/null +++ b/backend/node_modules/openai/uploads.mjs.map @@ -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C,KAAK,CAAC,EAAE;QAC/B,MAAM,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,YAAY,CAAC,IAAI,EAAE,GAAG,GAAG,IAAI,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC;KAChF;SAAM,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;QACpC,MAAM,OAAO,CAAC,GAAG,CACf,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,IAAI,CAAC,EAAE,EAAE,CAAC,YAAY,CAAC,IAAI,EAAE,GAAG,GAAG,IAAI,IAAI,GAAG,EAAE,IAAI,CAAC,CAAC,CACzF,CAAC;KACH;SAAM;QACL,MAAM,IAAI,SAAS,CACjB,wGAAwG,KAAK,UAAU,CACxH,CAAC;KACH;AACH,CAAC,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/openai/version.d.ts b/backend/node_modules/openai/version.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..78814365b34d8780e48917452aefccc9da093cfa --- /dev/null +++ b/backend/node_modules/openai/version.d.ts @@ -0,0 +1,2 @@ +export declare const VERSION = "4.35.0"; +//# sourceMappingURL=version.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/openai/version.d.ts.map b/backend/node_modules/openai/version.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..e072bdd7a15c376e22ed360f66cda149fff769ac --- /dev/null +++ b/backend/node_modules/openai/version.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"version.d.ts","sourceRoot":"","sources":["src/version.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,OAAO,WAAW,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/openai/version.js b/backend/node_modules/openai/version.js new file mode 100644 index 0000000000000000000000000000000000000000..85f8ae7eb863ab56dc6183385237faa89bdcc6ad --- /dev/null +++ b/backend/node_modules/openai/version.js @@ -0,0 +1,5 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.VERSION = void 0; +exports.VERSION = '4.35.0'; // x-release-please-version +//# sourceMappingURL=version.js.map \ No newline at end of file diff --git a/backend/node_modules/openai/version.js.map b/backend/node_modules/openai/version.js.map new file mode 100644 index 0000000000000000000000000000000000000000..e9a6b4f01739d8724dad65ade9271280801ba000 --- /dev/null +++ b/backend/node_modules/openai/version.js.map @@ -0,0 +1 @@ +{"version":3,"file":"version.js","sourceRoot":"","sources":["src/version.ts"],"names":[],"mappings":";;;AAAa,QAAA,OAAO,GAAG,QAAQ,CAAC,CAAC,2BAA2B"} \ No newline at end of file diff --git a/backend/node_modules/openai/version.mjs b/backend/node_modules/openai/version.mjs new file mode 100644 index 0000000000000000000000000000000000000000..775ae274d16a87939cb1d84559f851e36468a6e2 --- /dev/null +++ b/backend/node_modules/openai/version.mjs @@ -0,0 +1,2 @@ +export const VERSION = '4.35.0'; // x-release-please-version +//# sourceMappingURL=version.mjs.map \ No newline at end of file diff --git a/backend/node_modules/openai/version.mjs.map b/backend/node_modules/openai/version.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..0c09c723b1318a6966eaf1482f5f556f052a5491 --- /dev/null +++ b/backend/node_modules/openai/version.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"version.mjs","sourceRoot":"","sources":["src/version.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,OAAO,GAAG,QAAQ,CAAC,CAAC,2BAA2B"} \ No newline at end of file diff --git a/backend/node_modules/parseurl/HISTORY.md b/backend/node_modules/parseurl/HISTORY.md new file mode 100644 index 0000000000000000000000000000000000000000..8e409541d855de232cc24d29524282441d11cbc7 --- /dev/null +++ b/backend/node_modules/parseurl/HISTORY.md @@ -0,0 +1,58 @@ +1.3.3 / 2019-04-15 +================== + + * Fix Node.js 0.8 return value inconsistencies + +1.3.2 / 2017-09-09 +================== + + * perf: reduce overhead for full URLs + * perf: unroll the "fast-path" `RegExp` + +1.3.1 / 2016-01-17 +================== + + * perf: enable strict mode + +1.3.0 / 2014-08-09 +================== + + * Add `parseurl.original` for parsing `req.originalUrl` with fallback + * Return `undefined` if `req.url` is `undefined` + +1.2.0 / 2014-07-21 +================== + + * Cache URLs based on original value + * Remove no-longer-needed URL mis-parse work-around + * Simplify the "fast-path" `RegExp` + +1.1.3 / 2014-07-08 +================== + + * Fix typo + +1.1.2 / 2014-07-08 +================== + + * Seriously fix Node.js 0.8 compatibility + +1.1.1 / 2014-07-08 +================== + + * Fix Node.js 0.8 compatibility + +1.1.0 / 2014-07-08 +================== + + * Incorporate URL href-only parse fast-path + +1.0.1 / 2014-03-08 +================== + + * Add missing `require` + +1.0.0 / 2014-03-08 +================== + + * Genesis from `connect` diff --git a/backend/node_modules/parseurl/LICENSE b/backend/node_modules/parseurl/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..27653d3db7e584321691af8f1bc30d49fe105d3e --- /dev/null +++ b/backend/node_modules/parseurl/LICENSE @@ -0,0 +1,24 @@ + +(The MIT License) + +Copyright (c) 2014 Jonathan Ong +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/backend/node_modules/parseurl/README.md b/backend/node_modules/parseurl/README.md new file mode 100644 index 0000000000000000000000000000000000000000..443e716b85dc54a70d063109d4e9afa39022989d --- /dev/null +++ b/backend/node_modules/parseurl/README.md @@ -0,0 +1,133 @@ +# parseurl + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Parse a URL with memoization. + +## Install + +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 parseurl +``` + +## API + +```js +var parseurl = require('parseurl') +``` + +### parseurl(req) + +Parse the URL of the given request object (looks at the `req.url` property) +and return the result. The result is the same as `url.parse` in Node.js core. +Calling this function multiple times on the same `req` where `req.url` does +not change will return a cached parsed object, rather than parsing again. + +### parseurl.original(req) + +Parse the original URL of the given request object and return the result. +This works by trying to parse `req.originalUrl` if it is a string, otherwise +parses `req.url`. The result is the same as `url.parse` in Node.js core. +Calling this function multiple times on the same `req` where `req.originalUrl` +does not change will return a cached parsed object, rather than parsing again. + +## Benchmark + +```bash +$ npm run-script bench + +> parseurl@1.3.3 bench nodejs-parseurl +> node benchmark/index.js + + http_parser@2.8.0 + node@10.6.0 + v8@6.7.288.46-node.13 + uv@1.21.0 + zlib@1.2.11 + ares@1.14.0 + modules@64 + nghttp2@1.32.0 + napi@3 + openssl@1.1.0h + icu@61.1 + unicode@10.0 + cldr@33.0 + tz@2018c + +> node benchmark/fullurl.js + + Parsing URL "http://localhost:8888/foo/bar?user=tj&pet=fluffy" + + 4 tests completed. + + fasturl x 2,207,842 ops/sec ±3.76% (184 runs sampled) + nativeurl - legacy x 507,180 ops/sec ±0.82% (191 runs sampled) + nativeurl - whatwg x 290,044 ops/sec ±1.96% (189 runs sampled) + parseurl x 488,907 ops/sec ±2.13% (192 runs sampled) + +> node benchmark/pathquery.js + + Parsing URL "/foo/bar?user=tj&pet=fluffy" + + 4 tests completed. + + fasturl x 3,812,564 ops/sec ±3.15% (188 runs sampled) + nativeurl - legacy x 2,651,631 ops/sec ±1.68% (189 runs sampled) + nativeurl - whatwg x 161,837 ops/sec ±2.26% (189 runs sampled) + parseurl x 4,166,338 ops/sec ±2.23% (184 runs sampled) + +> node benchmark/samerequest.js + + Parsing URL "/foo/bar?user=tj&pet=fluffy" on same request object + + 4 tests completed. + + fasturl x 3,821,651 ops/sec ±2.42% (185 runs sampled) + nativeurl - legacy x 2,651,162 ops/sec ±1.90% (187 runs sampled) + nativeurl - whatwg x 175,166 ops/sec ±1.44% (188 runs sampled) + parseurl x 14,912,606 ops/sec ±3.59% (183 runs sampled) + +> node benchmark/simplepath.js + + Parsing URL "/foo/bar" + + 4 tests completed. + + fasturl x 12,421,765 ops/sec ±2.04% (191 runs sampled) + nativeurl - legacy x 7,546,036 ops/sec ±1.41% (188 runs sampled) + nativeurl - whatwg x 198,843 ops/sec ±1.83% (189 runs sampled) + parseurl x 24,244,006 ops/sec ±0.51% (194 runs sampled) + +> node benchmark/slash.js + + Parsing URL "/" + + 4 tests completed. + + fasturl x 17,159,456 ops/sec ±3.25% (188 runs sampled) + nativeurl - legacy x 11,635,097 ops/sec ±3.79% (184 runs sampled) + nativeurl - whatwg x 240,693 ops/sec ±0.83% (189 runs sampled) + parseurl x 42,279,067 ops/sec ±0.55% (190 runs sampled) +``` + +## License + + [MIT](LICENSE) + +[coveralls-image]: https://badgen.net/coveralls/c/github/pillarjs/parseurl/master +[coveralls-url]: https://coveralls.io/r/pillarjs/parseurl?branch=master +[node-image]: https://badgen.net/npm/node/parseurl +[node-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/parseurl +[npm-url]: https://npmjs.org/package/parseurl +[npm-version-image]: https://badgen.net/npm/v/parseurl +[travis-image]: https://badgen.net/travis/pillarjs/parseurl/master +[travis-url]: https://travis-ci.org/pillarjs/parseurl diff --git a/backend/node_modules/parseurl/index.js b/backend/node_modules/parseurl/index.js new file mode 100644 index 0000000000000000000000000000000000000000..ece722327959f3bd9721488a035947387f1c1db1 --- /dev/null +++ b/backend/node_modules/parseurl/index.js @@ -0,0 +1,158 @@ +/*! + * parseurl + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2014-2017 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var url = require('url') +var parse = url.parse +var Url = url.Url + +/** + * Module exports. + * @public + */ + +module.exports = parseurl +module.exports.original = originalurl + +/** + * Parse the `req` url with memoization. + * + * @param {ServerRequest} req + * @return {Object} + * @public + */ + +function parseurl (req) { + var url = req.url + + if (url === undefined) { + // URL is undefined + return undefined + } + + var parsed = req._parsedUrl + + if (fresh(url, parsed)) { + // Return cached URL parse + return parsed + } + + // Parse the URL + parsed = fastparse(url) + parsed._raw = url + + return (req._parsedUrl = parsed) +}; + +/** + * Parse the `req` original url with fallback and memoization. + * + * @param {ServerRequest} req + * @return {Object} + * @public + */ + +function originalurl (req) { + var url = req.originalUrl + + if (typeof url !== 'string') { + // Fallback + return parseurl(req) + } + + var parsed = req._parsedOriginalUrl + + if (fresh(url, parsed)) { + // Return cached URL parse + return parsed + } + + // Parse the URL + parsed = fastparse(url) + parsed._raw = url + + return (req._parsedOriginalUrl = parsed) +}; + +/** + * Parse the `str` url with fast-path short-cut. + * + * @param {string} str + * @return {Object} + * @private + */ + +function fastparse (str) { + if (typeof str !== 'string' || str.charCodeAt(0) !== 0x2f /* / */) { + return parse(str) + } + + var pathname = str + var query = null + var search = null + + // This takes the regexp from https://github.com/joyent/node/pull/7878 + // Which is /^(\/[^?#\s]*)(\?[^#\s]*)?$/ + // And unrolls it into a for loop + for (var i = 1; i < str.length; i++) { + switch (str.charCodeAt(i)) { + case 0x3f: /* ? */ + if (search === null) { + pathname = str.substring(0, i) + query = str.substring(i + 1) + search = str.substring(i) + } + break + case 0x09: /* \t */ + case 0x0a: /* \n */ + case 0x0c: /* \f */ + case 0x0d: /* \r */ + case 0x20: /* */ + case 0x23: /* # */ + case 0xa0: + case 0xfeff: + return parse(str) + } + } + + var url = Url !== undefined + ? new Url() + : {} + + url.path = str + url.href = str + url.pathname = pathname + + if (search !== null) { + url.query = query + url.search = search + } + + return url +} + +/** + * Determine if parsed is still fresh for url. + * + * @param {string} url + * @param {object} parsedUrl + * @return {boolean} + * @private + */ + +function fresh (url, parsedUrl) { + return typeof parsedUrl === 'object' && + parsedUrl !== null && + (Url === undefined || parsedUrl instanceof Url) && + parsedUrl._raw === url +} diff --git a/backend/node_modules/parseurl/package.json b/backend/node_modules/parseurl/package.json new file mode 100644 index 0000000000000000000000000000000000000000..6b443ca7a84aa09444101a104dd8f8946dc9fa58 --- /dev/null +++ b/backend/node_modules/parseurl/package.json @@ -0,0 +1,40 @@ +{ + "name": "parseurl", + "description": "parse a url with memoization", + "version": "1.3.3", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)" + ], + "repository": "pillarjs/parseurl", + "license": "MIT", + "devDependencies": { + "beautify-benchmark": "0.2.4", + "benchmark": "2.1.4", + "eslint": "5.16.0", + "eslint-config-standard": "12.0.0", + "eslint-plugin-import": "2.17.1", + "eslint-plugin-node": "7.0.1", + "eslint-plugin-promise": "4.1.1", + "eslint-plugin-standard": "4.0.0", + "fast-url-parser": "1.1.3", + "istanbul": "0.4.5", + "mocha": "6.1.3" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "bench": "node benchmark/index.js", + "lint": "eslint .", + "test": "mocha --check-leaks --bail --reporter spec test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --check-leaks --reporter dot test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --check-leaks --reporter spec test/" + } +} diff --git a/backend/node_modules/path-to-regexp/History.md b/backend/node_modules/path-to-regexp/History.md new file mode 100644 index 0000000000000000000000000000000000000000..7f6587846f67047b7f9ecddbb176abd25dc3741d --- /dev/null +++ b/backend/node_modules/path-to-regexp/History.md @@ -0,0 +1,36 @@ +0.1.7 / 2015-07-28 +================== + + * Fixed regression with escaped round brackets and matching groups. + +0.1.6 / 2015-06-19 +================== + + * Replace `index` feature by outputting all parameters, unnamed and named. + +0.1.5 / 2015-05-08 +================== + + * Add an index property for position in match result. + +0.1.4 / 2015-03-05 +================== + + * Add license information + +0.1.3 / 2014-07-06 +================== + + * Better array support + * Improved support for trailing slash in non-ending mode + +0.1.0 / 2014-03-06 +================== + + * add options.end + +0.0.2 / 2013-02-10 +================== + + * Update to match current express + * add .license property to component.json diff --git a/backend/node_modules/path-to-regexp/LICENSE b/backend/node_modules/path-to-regexp/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..983fbe8aec3f4e2d4add592bb1083b00d7366f66 --- /dev/null +++ b/backend/node_modules/path-to-regexp/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Blake Embrey (hello@blakeembrey.com) + +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/backend/node_modules/path-to-regexp/Readme.md b/backend/node_modules/path-to-regexp/Readme.md new file mode 100644 index 0000000000000000000000000000000000000000..95452a6e9ee2ca18ec76107d4f7c78a5ef7991db --- /dev/null +++ b/backend/node_modules/path-to-regexp/Readme.md @@ -0,0 +1,35 @@ +# Path-to-RegExp + +Turn an Express-style path string such as `/user/:name` into a regular expression. + +**Note:** This is a legacy branch. You should upgrade to `1.x`. + +## Usage + +```javascript +var pathToRegexp = require('path-to-regexp'); +``` + +### pathToRegexp(path, keys, options) + + - **path** A string in the express format, an array of such strings, or a regular expression + - **keys** An array to be populated with the keys present in the url. Once the function completes, this will be an array of strings. + - **options** + - **options.sensitive** Defaults to false, set this to true to make routes case sensitive + - **options.strict** Defaults to false, set this to true to make the trailing slash matter. + - **options.end** Defaults to true, set this to false to only match the prefix of the URL. + +```javascript +var keys = []; +var exp = pathToRegexp('/foo/:bar', keys); +//keys = ['bar'] +//exp = /^\/foo\/(?:([^\/]+?))\/?$/i +``` + +## Live Demo + +You can see a live demo of this library in use at [express-route-tester](http://forbeslindesay.github.com/express-route-tester/). + +## License + + MIT diff --git a/backend/node_modules/path-to-regexp/index.js b/backend/node_modules/path-to-regexp/index.js new file mode 100644 index 0000000000000000000000000000000000000000..500d1dad0ef117b52778cbf060b9bde54d6860a4 --- /dev/null +++ b/backend/node_modules/path-to-regexp/index.js @@ -0,0 +1,129 @@ +/** + * Expose `pathtoRegexp`. + */ + +module.exports = pathtoRegexp; + +/** + * Match matching groups in a regular expression. + */ +var MATCHING_GROUP_REGEXP = /\((?!\?)/g; + +/** + * Normalize the given path string, + * returning a regular expression. + * + * An empty array should be passed, + * which will contain the placeholder + * key names. For example "/user/:id" will + * then contain ["id"]. + * + * @param {String|RegExp|Array} path + * @param {Array} keys + * @param {Object} options + * @return {RegExp} + * @api private + */ + +function pathtoRegexp(path, keys, options) { + options = options || {}; + keys = keys || []; + var strict = options.strict; + var end = options.end !== false; + var flags = options.sensitive ? '' : 'i'; + var extraOffset = 0; + var keysOffset = keys.length; + var i = 0; + var name = 0; + var m; + + if (path instanceof RegExp) { + while (m = MATCHING_GROUP_REGEXP.exec(path.source)) { + keys.push({ + name: name++, + optional: false, + offset: m.index + }); + } + + return path; + } + + if (Array.isArray(path)) { + // Map array parts into regexps and return their source. We also pass + // the same keys and options instance into every generation to get + // consistent matching groups before we join the sources together. + path = path.map(function (value) { + return pathtoRegexp(value, keys, options).source; + }); + + return new RegExp('(?:' + path.join('|') + ')', flags); + } + + path = ('^' + path + (strict ? '' : path[path.length - 1] === '/' ? '?' : '/?')) + .replace(/\/\(/g, '/(?:') + .replace(/([\/\.])/g, '\\$1') + .replace(/(\\\/)?(\\\.)?:(\w+)(\(.*?\))?(\*)?(\?)?/g, function (match, slash, format, key, capture, star, optional, offset) { + slash = slash || ''; + format = format || ''; + capture = capture || '([^\\/' + format + ']+?)'; + optional = optional || ''; + + keys.push({ + name: key, + optional: !!optional, + offset: offset + extraOffset + }); + + var result = '' + + (optional ? '' : slash) + + '(?:' + + format + (optional ? slash : '') + capture + + (star ? '((?:[\\/' + format + '].+?)?)' : '') + + ')' + + optional; + + extraOffset += result.length - match.length; + + return result; + }) + .replace(/\*/g, function (star, index) { + var len = keys.length + + while (len-- > keysOffset && keys[len].offset > index) { + keys[len].offset += 3; // Replacement length minus asterisk length. + } + + return '(.*)'; + }); + + // This is a workaround for handling unnamed matching groups. + while (m = MATCHING_GROUP_REGEXP.exec(path)) { + var escapeCount = 0; + var index = m.index; + + while (path.charAt(--index) === '\\') { + escapeCount++; + } + + // It's possible to escape the bracket. + if (escapeCount % 2 === 1) { + continue; + } + + if (keysOffset + i === keys.length || keys[keysOffset + i].offset > m.index) { + keys.splice(keysOffset + i, 0, { + name: name++, // Unnamed matching groups must be consistently linear. + optional: false, + offset: m.index + }); + } + + i++; + } + + // If the path is non-ending, match until the end or a slash. + path += (end ? '$' : (path[path.length - 1] === '/' ? '' : '(?=\\/|$)')); + + return new RegExp(path, flags); +}; diff --git a/backend/node_modules/path-to-regexp/package.json b/backend/node_modules/path-to-regexp/package.json new file mode 100644 index 0000000000000000000000000000000000000000..d4e51b5743a8a3742825a3418ac3a87e8b3f735f --- /dev/null +++ b/backend/node_modules/path-to-regexp/package.json @@ -0,0 +1,30 @@ +{ + "name": "path-to-regexp", + "description": "Express style path to RegExp utility", + "version": "0.1.7", + "files": [ + "index.js", + "LICENSE" + ], + "scripts": { + "test": "istanbul cover _mocha -- -R spec" + }, + "keywords": [ + "express", + "regexp" + ], + "component": { + "scripts": { + "path-to-regexp": "index.js" + } + }, + "license": "MIT", + "repository": { + "type": "git", + "url": "https://github.com/component/path-to-regexp.git" + }, + "devDependencies": { + "mocha": "^1.17.1", + "istanbul": "^0.2.6" + } +} diff --git a/backend/node_modules/process-nextick-args/index.js b/backend/node_modules/process-nextick-args/index.js new file mode 100644 index 0000000000000000000000000000000000000000..3eecf11488531cd40aed422f0a68bdf0e6a8611a --- /dev/null +++ b/backend/node_modules/process-nextick-args/index.js @@ -0,0 +1,45 @@ +'use strict'; + +if (typeof process === 'undefined' || + !process.version || + process.version.indexOf('v0.') === 0 || + process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) { + module.exports = { nextTick: nextTick }; +} else { + module.exports = process +} + +function nextTick(fn, arg1, arg2, arg3) { + if (typeof fn !== 'function') { + throw new TypeError('"callback" argument must be a function'); + } + var len = arguments.length; + var args, i; + switch (len) { + case 0: + case 1: + return process.nextTick(fn); + case 2: + return process.nextTick(function afterTickOne() { + fn.call(null, arg1); + }); + case 3: + return process.nextTick(function afterTickTwo() { + fn.call(null, arg1, arg2); + }); + case 4: + return process.nextTick(function afterTickThree() { + fn.call(null, arg1, arg2, arg3); + }); + default: + args = new Array(len - 1); + i = 0; + while (i < args.length) { + args[i++] = arguments[i]; + } + return process.nextTick(function afterTick() { + fn.apply(null, args); + }); + } +} + diff --git a/backend/node_modules/process-nextick-args/license.md b/backend/node_modules/process-nextick-args/license.md new file mode 100644 index 0000000000000000000000000000000000000000..c67e3532b542455fad8c4004ef297534d7f480b2 --- /dev/null +++ b/backend/node_modules/process-nextick-args/license.md @@ -0,0 +1,19 @@ +# Copyright (c) 2015 Calvin Metcalf + +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/backend/node_modules/process-nextick-args/package.json b/backend/node_modules/process-nextick-args/package.json new file mode 100644 index 0000000000000000000000000000000000000000..6070b723fcd3476052a28040412e61d7df2511f4 --- /dev/null +++ b/backend/node_modules/process-nextick-args/package.json @@ -0,0 +1,25 @@ +{ + "name": "process-nextick-args", + "version": "2.0.1", + "description": "process.nextTick but always with args", + "main": "index.js", + "files": [ + "index.js" + ], + "scripts": { + "test": "node test.js" + }, + "repository": { + "type": "git", + "url": "https://github.com/calvinmetcalf/process-nextick-args.git" + }, + "author": "", + "license": "MIT", + "bugs": { + "url": "https://github.com/calvinmetcalf/process-nextick-args/issues" + }, + "homepage": "https://github.com/calvinmetcalf/process-nextick-args", + "devDependencies": { + "tap": "~0.2.6" + } +} diff --git a/backend/node_modules/process-nextick-args/readme.md b/backend/node_modules/process-nextick-args/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..ecb432c9b21ffd44bded842812586d3dab132c69 --- /dev/null +++ b/backend/node_modules/process-nextick-args/readme.md @@ -0,0 +1,18 @@ +process-nextick-args +===== + +[![Build Status](https://travis-ci.org/calvinmetcalf/process-nextick-args.svg?branch=master)](https://travis-ci.org/calvinmetcalf/process-nextick-args) + +```bash +npm install --save process-nextick-args +``` + +Always be able to pass arguments to process.nextTick, no matter the platform + +```js +var pna = require('process-nextick-args'); + +pna.nextTick(function (a, b, c) { + console.log(a, b, c); +}, 'step', 3, 'profit'); +``` diff --git a/backend/node_modules/proxy-addr/HISTORY.md b/backend/node_modules/proxy-addr/HISTORY.md new file mode 100644 index 0000000000000000000000000000000000000000..8480242a0c43af25ec8d685e941b6a79a65c8fb4 --- /dev/null +++ b/backend/node_modules/proxy-addr/HISTORY.md @@ -0,0 +1,161 @@ +2.0.7 / 2021-05-31 +================== + + * deps: forwarded@0.2.0 + - Use `req.socket` over deprecated `req.connection` + +2.0.6 / 2020-02-24 +================== + + * deps: ipaddr.js@1.9.1 + +2.0.5 / 2019-04-16 +================== + + * deps: ipaddr.js@1.9.0 + +2.0.4 / 2018-07-26 +================== + + * deps: ipaddr.js@1.8.0 + +2.0.3 / 2018-02-19 +================== + + * deps: ipaddr.js@1.6.0 + +2.0.2 / 2017-09-24 +================== + + * deps: forwarded@~0.1.2 + - perf: improve header parsing + - perf: reduce overhead when no `X-Forwarded-For` header + +2.0.1 / 2017-09-10 +================== + + * deps: forwarded@~0.1.1 + - Fix trimming leading / trailing OWS + - perf: hoist regular expression + * deps: ipaddr.js@1.5.2 + +2.0.0 / 2017-08-08 +================== + + * Drop support for Node.js below 0.10 + +1.1.5 / 2017-07-25 +================== + + * Fix array argument being altered + * deps: ipaddr.js@1.4.0 + +1.1.4 / 2017-03-24 +================== + + * deps: ipaddr.js@1.3.0 + +1.1.3 / 2017-01-14 +================== + + * deps: ipaddr.js@1.2.0 + +1.1.2 / 2016-05-29 +================== + + * deps: ipaddr.js@1.1.1 + - Fix IPv6-mapped IPv4 validation edge cases + +1.1.1 / 2016-05-03 +================== + + * Fix regression matching mixed versions against multiple subnets + +1.1.0 / 2016-05-01 +================== + + * Fix accepting various invalid netmasks + - IPv4 netmasks must be contingous + - IPv6 addresses cannot be used as a netmask + * deps: ipaddr.js@1.1.0 + +1.0.10 / 2015-12-09 +=================== + + * deps: ipaddr.js@1.0.5 + - Fix regression in `isValid` with non-string arguments + +1.0.9 / 2015-12-01 +================== + + * deps: ipaddr.js@1.0.4 + - Fix accepting some invalid IPv6 addresses + - Reject CIDRs with negative or overlong masks + * perf: enable strict mode + +1.0.8 / 2015-05-10 +================== + + * deps: ipaddr.js@1.0.1 + +1.0.7 / 2015-03-16 +================== + + * deps: ipaddr.js@0.1.9 + - Fix OOM on certain inputs to `isValid` + +1.0.6 / 2015-02-01 +================== + + * deps: ipaddr.js@0.1.8 + +1.0.5 / 2015-01-08 +================== + + * deps: ipaddr.js@0.1.6 + +1.0.4 / 2014-11-23 +================== + + * deps: ipaddr.js@0.1.5 + - Fix edge cases with `isValid` + +1.0.3 / 2014-09-21 +================== + + * Use `forwarded` npm module + +1.0.2 / 2014-09-18 +================== + + * Fix a global leak when multiple subnets are trusted + * Support Node.js 0.6 + * deps: ipaddr.js@0.1.3 + +1.0.1 / 2014-06-03 +================== + + * Fix links in npm package + +1.0.0 / 2014-05-08 +================== + + * Add `trust` argument to determine proxy trust on + * Accepts custom function + * Accepts IPv4/IPv6 address(es) + * Accepts subnets + * Accepts pre-defined names + * Add optional `trust` argument to `proxyaddr.all` to + stop at first untrusted + * Add `proxyaddr.compile` to pre-compile `trust` function + to make subsequent calls faster + +0.0.1 / 2014-05-04 +================== + + * Fix bad npm publish + +0.0.0 / 2014-05-04 +================== + + * Initial release diff --git a/backend/node_modules/proxy-addr/LICENSE b/backend/node_modules/proxy-addr/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..cab251c2b9a81318267600f68130faa3a290e5fd --- /dev/null +++ b/backend/node_modules/proxy-addr/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014-2016 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/backend/node_modules/proxy-addr/README.md b/backend/node_modules/proxy-addr/README.md new file mode 100644 index 0000000000000000000000000000000000000000..69c0b63eab22e32821df374c5e84a37c665c28c3 --- /dev/null +++ b/backend/node_modules/proxy-addr/README.md @@ -0,0 +1,139 @@ +# proxy-addr + +[![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] +[![Test Coverage][coveralls-image]][coveralls-url] + +Determine address of proxied request + +## Install + +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 proxy-addr +``` + +## API + +```js +var proxyaddr = require('proxy-addr') +``` + +### proxyaddr(req, trust) + +Return the address of the request, using the given `trust` parameter. + +The `trust` argument is a function that returns `true` if you trust +the address, `false` if you don't. The closest untrusted address is +returned. + +```js +proxyaddr(req, function (addr) { return addr === '127.0.0.1' }) +proxyaddr(req, function (addr, i) { return i < 1 }) +``` + +The `trust` arugment may also be a single IP address string or an +array of trusted addresses, as plain IP addresses, CIDR-formatted +strings, or IP/netmask strings. + +```js +proxyaddr(req, '127.0.0.1') +proxyaddr(req, ['127.0.0.0/8', '10.0.0.0/8']) +proxyaddr(req, ['127.0.0.0/255.0.0.0', '192.168.0.0/255.255.0.0']) +``` + +This module also supports IPv6. Your IPv6 addresses will be normalized +automatically (i.e. `fe80::00ed:1` equals `fe80:0:0:0:0:0:ed:1`). + +```js +proxyaddr(req, '::1') +proxyaddr(req, ['::1/128', 'fe80::/10']) +``` + +This module will automatically work with IPv4-mapped IPv6 addresses +as well to support node.js in IPv6-only mode. This means that you do +not have to specify both `::ffff:a00:1` and `10.0.0.1`. + +As a convenience, this module also takes certain pre-defined names +in addition to IP addresses, which expand into IP addresses: + +```js +proxyaddr(req, 'loopback') +proxyaddr(req, ['loopback', 'fc00:ac:1ab5:fff::1/64']) +``` + + * `loopback`: IPv4 and IPv6 loopback addresses (like `::1` and + `127.0.0.1`). + * `linklocal`: IPv4 and IPv6 link-local addresses (like + `fe80::1:1:1:1` and `169.254.0.1`). + * `uniquelocal`: IPv4 private addresses and IPv6 unique-local + addresses (like `fc00:ac:1ab5:fff::1` and `192.168.0.1`). + +When `trust` is specified as a function, it will be called for each +address to determine if it is a trusted address. The function is +given two arguments: `addr` and `i`, where `addr` is a string of +the address to check and `i` is a number that represents the distance +from the socket address. + +### proxyaddr.all(req, [trust]) + +Return all the addresses of the request, optionally stopping at the +first untrusted. This array is ordered from closest to furthest +(i.e. `arr[0] === req.connection.remoteAddress`). + +```js +proxyaddr.all(req) +``` + +The optional `trust` argument takes the same arguments as `trust` +does in `proxyaddr(req, trust)`. + +```js +proxyaddr.all(req, 'loopback') +``` + +### proxyaddr.compile(val) + +Compiles argument `val` into a `trust` function. This function takes +the same arguments as `trust` does in `proxyaddr(req, trust)` and +returns a function suitable for `proxyaddr(req, trust)`. + +```js +var trust = proxyaddr.compile('loopback') +var addr = proxyaddr(req, trust) +``` + +This function is meant to be optimized for use against every request. +It is recommend to compile a trust function up-front for the trusted +configuration and pass that to `proxyaddr(req, trust)` for each request. + +## Testing + +```sh +$ npm test +``` + +## Benchmarks + +```sh +$ npm run-script bench +``` + +## License + +[MIT](LICENSE) + +[ci-image]: https://badgen.net/github/checks/jshttp/proxy-addr/master?label=ci +[ci-url]: https://github.com/jshttp/proxy-addr/actions?query=workflow%3Aci +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/proxy-addr/master +[coveralls-url]: https://coveralls.io/r/jshttp/proxy-addr?branch=master +[node-image]: https://badgen.net/npm/node/proxy-addr +[node-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/proxy-addr +[npm-url]: https://npmjs.org/package/proxy-addr +[npm-version-image]: https://badgen.net/npm/v/proxy-addr diff --git a/backend/node_modules/proxy-addr/index.js b/backend/node_modules/proxy-addr/index.js new file mode 100644 index 0000000000000000000000000000000000000000..a909b05064a377ed49b5aea673d0849970f050e9 --- /dev/null +++ b/backend/node_modules/proxy-addr/index.js @@ -0,0 +1,327 @@ +/*! + * proxy-addr + * Copyright(c) 2014-2016 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = proxyaddr +module.exports.all = alladdrs +module.exports.compile = compile + +/** + * Module dependencies. + * @private + */ + +var forwarded = require('forwarded') +var ipaddr = require('ipaddr.js') + +/** + * Variables. + * @private + */ + +var DIGIT_REGEXP = /^[0-9]+$/ +var isip = ipaddr.isValid +var parseip = ipaddr.parse + +/** + * Pre-defined IP ranges. + * @private + */ + +var IP_RANGES = { + linklocal: ['169.254.0.0/16', 'fe80::/10'], + loopback: ['127.0.0.1/8', '::1/128'], + uniquelocal: ['10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', 'fc00::/7'] +} + +/** + * Get all addresses in the request, optionally stopping + * at the first untrusted. + * + * @param {Object} request + * @param {Function|Array|String} [trust] + * @public + */ + +function alladdrs (req, trust) { + // get addresses + var addrs = forwarded(req) + + if (!trust) { + // Return all addresses + return addrs + } + + if (typeof trust !== 'function') { + trust = compile(trust) + } + + for (var i = 0; i < addrs.length - 1; i++) { + if (trust(addrs[i], i)) continue + + addrs.length = i + 1 + } + + return addrs +} + +/** + * Compile argument into trust function. + * + * @param {Array|String} val + * @private + */ + +function compile (val) { + if (!val) { + throw new TypeError('argument is required') + } + + var trust + + if (typeof val === 'string') { + trust = [val] + } else if (Array.isArray(val)) { + trust = val.slice() + } else { + throw new TypeError('unsupported trust argument') + } + + for (var i = 0; i < trust.length; i++) { + val = trust[i] + + if (!Object.prototype.hasOwnProperty.call(IP_RANGES, val)) { + continue + } + + // Splice in pre-defined range + val = IP_RANGES[val] + trust.splice.apply(trust, [i, 1].concat(val)) + i += val.length - 1 + } + + return compileTrust(compileRangeSubnets(trust)) +} + +/** + * Compile `arr` elements into range subnets. + * + * @param {Array} arr + * @private + */ + +function compileRangeSubnets (arr) { + var rangeSubnets = new Array(arr.length) + + for (var i = 0; i < arr.length; i++) { + rangeSubnets[i] = parseipNotation(arr[i]) + } + + return rangeSubnets +} + +/** + * Compile range subnet array into trust function. + * + * @param {Array} rangeSubnets + * @private + */ + +function compileTrust (rangeSubnets) { + // Return optimized function based on length + var len = rangeSubnets.length + return len === 0 + ? trustNone + : len === 1 + ? trustSingle(rangeSubnets[0]) + : trustMulti(rangeSubnets) +} + +/** + * Parse IP notation string into range subnet. + * + * @param {String} note + * @private + */ + +function parseipNotation (note) { + var pos = note.lastIndexOf('/') + var str = pos !== -1 + ? note.substring(0, pos) + : note + + if (!isip(str)) { + throw new TypeError('invalid IP address: ' + str) + } + + var ip = parseip(str) + + if (pos === -1 && ip.kind() === 'ipv6' && ip.isIPv4MappedAddress()) { + // Store as IPv4 + ip = ip.toIPv4Address() + } + + var max = ip.kind() === 'ipv6' + ? 128 + : 32 + + var range = pos !== -1 + ? note.substring(pos + 1, note.length) + : null + + if (range === null) { + range = max + } else if (DIGIT_REGEXP.test(range)) { + range = parseInt(range, 10) + } else if (ip.kind() === 'ipv4' && isip(range)) { + range = parseNetmask(range) + } else { + range = null + } + + if (range <= 0 || range > max) { + throw new TypeError('invalid range on address: ' + note) + } + + return [ip, range] +} + +/** + * Parse netmask string into CIDR range. + * + * @param {String} netmask + * @private + */ + +function parseNetmask (netmask) { + var ip = parseip(netmask) + var kind = ip.kind() + + return kind === 'ipv4' + ? ip.prefixLengthFromSubnetMask() + : null +} + +/** + * Determine address of proxied request. + * + * @param {Object} request + * @param {Function|Array|String} trust + * @public + */ + +function proxyaddr (req, trust) { + if (!req) { + throw new TypeError('req argument is required') + } + + if (!trust) { + throw new TypeError('trust argument is required') + } + + var addrs = alladdrs(req, trust) + var addr = addrs[addrs.length - 1] + + return addr +} + +/** + * Static trust function to trust nothing. + * + * @private + */ + +function trustNone () { + return false +} + +/** + * Compile trust function for multiple subnets. + * + * @param {Array} subnets + * @private + */ + +function trustMulti (subnets) { + return function trust (addr) { + if (!isip(addr)) return false + + var ip = parseip(addr) + var ipconv + var kind = ip.kind() + + for (var i = 0; i < subnets.length; i++) { + var subnet = subnets[i] + var subnetip = subnet[0] + var subnetkind = subnetip.kind() + var subnetrange = subnet[1] + var trusted = ip + + if (kind !== subnetkind) { + if (subnetkind === 'ipv4' && !ip.isIPv4MappedAddress()) { + // Incompatible IP addresses + continue + } + + if (!ipconv) { + // Convert IP to match subnet IP kind + ipconv = subnetkind === 'ipv4' + ? ip.toIPv4Address() + : ip.toIPv4MappedAddress() + } + + trusted = ipconv + } + + if (trusted.match(subnetip, subnetrange)) { + return true + } + } + + return false + } +} + +/** + * Compile trust function for single subnet. + * + * @param {Object} subnet + * @private + */ + +function trustSingle (subnet) { + var subnetip = subnet[0] + var subnetkind = subnetip.kind() + var subnetisipv4 = subnetkind === 'ipv4' + var subnetrange = subnet[1] + + return function trust (addr) { + if (!isip(addr)) return false + + var ip = parseip(addr) + var kind = ip.kind() + + if (kind !== subnetkind) { + if (subnetisipv4 && !ip.isIPv4MappedAddress()) { + // Incompatible IP addresses + return false + } + + // Convert IP to match subnet IP kind + ip = subnetisipv4 + ? ip.toIPv4Address() + : ip.toIPv4MappedAddress() + } + + return ip.match(subnetip, subnetrange) + } +} diff --git a/backend/node_modules/proxy-addr/package.json b/backend/node_modules/proxy-addr/package.json new file mode 100644 index 0000000000000000000000000000000000000000..24ba8f7db3cf17d87cff4bd53977b5239d459f90 --- /dev/null +++ b/backend/node_modules/proxy-addr/package.json @@ -0,0 +1,47 @@ +{ + "name": "proxy-addr", + "description": "Determine address of proxied request", + "version": "2.0.7", + "author": "Douglas Christopher Wilson ", + "license": "MIT", + "keywords": [ + "ip", + "proxy", + "x-forwarded-for" + ], + "repository": "jshttp/proxy-addr", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "devDependencies": { + "benchmark": "2.1.4", + "beautify-benchmark": "0.2.4", + "deep-equal": "1.0.1", + "eslint": "7.26.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.23.4", + "eslint-plugin-markdown": "2.2.0", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "4.3.1", + "eslint-plugin-standard": "4.1.0", + "mocha": "8.4.0", + "nyc": "15.1.0" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.10" + }, + "scripts": { + "bench": "node benchmark/index.js", + "lint": "eslint .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test" + } +} diff --git a/backend/node_modules/qs/.editorconfig b/backend/node_modules/qs/.editorconfig new file mode 100644 index 0000000000000000000000000000000000000000..2f084445078afdcca59b27f9f677170f906aa0a9 --- /dev/null +++ b/backend/node_modules/qs/.editorconfig @@ -0,0 +1,43 @@ +root = true + +[*] +indent_style = space +indent_size = 4 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +max_line_length = 160 +quote_type = single + +[test/*] +max_line_length = off + +[LICENSE.md] +indent_size = off + +[*.md] +max_line_length = off + +[*.json] +max_line_length = off + +[Makefile] +max_line_length = off + +[CHANGELOG.md] +indent_style = space +indent_size = 2 + +[LICENSE] +indent_size = 2 +max_line_length = off + +[coverage/**/*] +indent_size = off +indent_style = off +indent = off +max_line_length = off + +[.nycrc] +indent_style = tab diff --git a/backend/node_modules/qs/.eslintrc b/backend/node_modules/qs/.eslintrc new file mode 100644 index 0000000000000000000000000000000000000000..35220cd9113c7943656e9c2c79c5193adfc30fe6 --- /dev/null +++ b/backend/node_modules/qs/.eslintrc @@ -0,0 +1,38 @@ +{ + "root": true, + + "extends": "@ljharb", + + "ignorePatterns": [ + "dist/", + ], + + "rules": { + "complexity": 0, + "consistent-return": 1, + "func-name-matching": 0, + "id-length": [2, { "min": 1, "max": 25, "properties": "never" }], + "indent": [2, 4], + "max-lines-per-function": [2, { "max": 150 }], + "max-params": [2, 16], + "max-statements": [2, 53], + "multiline-comment-style": 0, + "no-continue": 1, + "no-magic-numbers": 0, + "no-restricted-syntax": [2, "BreakStatement", "DebuggerStatement", "ForInStatement", "LabeledStatement", "WithStatement"], + }, + + "overrides": [ + { + "files": "test/**", + "rules": { + "function-paren-newline": 0, + "max-lines-per-function": 0, + "max-statements": 0, + "no-buffer-constructor": 0, + "no-extend-native": 0, + "no-throw-literal": 0, + }, + }, + ], +} diff --git a/backend/node_modules/qs/.github/FUNDING.yml b/backend/node_modules/qs/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..0355f4f5fbecd763def967aca1130cd2dfbb3479 --- /dev/null +++ b/backend/node_modules/qs/.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/qs +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 a single custom sponsorship URL diff --git a/backend/node_modules/qs/.nycrc b/backend/node_modules/qs/.nycrc new file mode 100644 index 0000000000000000000000000000000000000000..1d57cabe1b647c742d82f896933bf4af5dfcdc0d --- /dev/null +++ b/backend/node_modules/qs/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "dist" + ] +} diff --git a/backend/node_modules/qs/CHANGELOG.md b/backend/node_modules/qs/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..37b1d3f04e97c31a1066f85ec4873080841e9781 --- /dev/null +++ b/backend/node_modules/qs/CHANGELOG.md @@ -0,0 +1,546 @@ +## **6.11.0 +- [New] [Fix] `stringify`: revert 0e903c0; add `commaRoundTrip` option (#442) +- [readme] fix version badge + +## **6.10.5** +- [Fix] `stringify`: with `arrayFormat: comma`, properly include an explicit `[]` on a single-item array (#434) + +## **6.10.4** +- [Fix] `stringify`: with `arrayFormat: comma`, include an explicit `[]` on a single-item array (#441) +- [meta] use `npmignore` to autogenerate an npmignore file +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `has-symbol`, `object-inspect`, `tape` + +## **6.10.3** +- [Fix] `parse`: ignore `__proto__` keys (#428) +- [Robustness] `stringify`: avoid relying on a global `undefined` (#427) +- [actions] reuse common workflows +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `object-inspect`, `tape` + +## **6.10.2** +- [Fix] `stringify`: actually fix cyclic references (#426) +- [Fix] `stringify`: avoid encoding arrayformat comma when `encodeValuesOnly = true` (#424) +- [readme] remove travis badge; add github actions/codecov badges; update URLs +- [Docs] add note and links for coercing primitive values (#408) +- [actions] update codecov uploader +- [actions] update workflows +- [Tests] clean up stringify tests slightly +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `object-inspect`, `safe-publish-latest`, `tape` + +## **6.10.1** +- [Fix] `stringify`: avoid exception on repeated object values (#402) + +## **6.10.0** +- [New] `stringify`: throw on cycles, instead of an infinite loop (#395, #394, #393) +- [New] `parse`: add `allowSparse` option for collapsing arrays with missing indices (#312) +- [meta] fix README.md (#399) +- [meta] only run `npm run dist` in publish, not install +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `has-symbols`, `tape` +- [Tests] fix tests on node v0.6 +- [Tests] use `ljharb/actions/node/install` instead of `ljharb/actions/node/run` +- [Tests] Revert "[meta] ignore eclint transitive audit warning" + +## **6.9.7** +- [Fix] `parse`: ignore `__proto__` keys (#428) +- [Fix] `stringify`: avoid encoding arrayformat comma when `encodeValuesOnly = true` (#424) +- [Robustness] `stringify`: avoid relying on a global `undefined` (#427) +- [readme] remove travis badge; add github actions/codecov badges; update URLs +- [Docs] add note and links for coercing primitive values (#408) +- [Tests] clean up stringify tests slightly +- [meta] fix README.md (#399) +- Revert "[meta] ignore eclint transitive audit warning" +- [actions] backport actions from main +- [Dev Deps] backport updates from main + +## **6.9.6** +- [Fix] restore `dist` dir; mistakenly removed in d4f6c32 + +## **6.9.5** +- [Fix] `stringify`: do not encode parens for RFC1738 +- [Fix] `stringify`: fix arrayFormat comma with empty array/objects (#350) +- [Refactor] `format`: remove `util.assign` call +- [meta] add "Allow Edits" workflow; update rebase workflow +- [actions] switch Automatic Rebase workflow to `pull_request_target` event +- [Tests] `stringify`: add tests for #378 +- [Tests] migrate tests to Github Actions +- [Tests] run `nyc` on all tests; use `tape` runner +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `browserify`, `mkdirp`, `object-inspect`, `tape`; add `aud` + +## **6.9.4** +- [Fix] `stringify`: when `arrayFormat` is `comma`, respect `serializeDate` (#364) +- [Refactor] `stringify`: reduce branching (part of #350) +- [Refactor] move `maybeMap` to `utils` +- [Dev Deps] update `browserify`, `tape` + +## **6.9.3** +- [Fix] proper comma parsing of URL-encoded commas (#361) +- [Fix] parses comma delimited array while having percent-encoded comma treated as normal text (#336) + +## **6.9.2** +- [Fix] `parse`: Fix parsing array from object with `comma` true (#359) +- [Fix] `parse`: throw a TypeError instead of an Error for bad charset (#349) +- [meta] ignore eclint transitive audit warning +- [meta] fix indentation in package.json +- [meta] add tidelift marketing copy +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `object-inspect`, `has-symbols`, `tape`, `mkdirp`, `iconv-lite` +- [actions] add automatic rebasing / merge commit blocking + +## **6.9.1** +- [Fix] `parse`: with comma true, handle field that holds an array of arrays (#335) +- [Fix] `parse`: with comma true, do not split non-string values (#334) +- [meta] add `funding` field +- [Dev Deps] update `eslint`, `@ljharb/eslint-config` +- [Tests] use shared travis-ci config + +## **6.9.0** +- [New] `parse`/`stringify`: Pass extra key/value argument to `decoder` (#333) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `evalmd` +- [Tests] `parse`: add passing `arrayFormat` tests +- [Tests] add `posttest` using `npx aud` to run `npm audit` without a lockfile +- [Tests] up to `node` `v12.10`, `v11.15`, `v10.16`, `v8.16` +- [Tests] `Buffer.from` in node v5.0-v5.9 and v4.0-v4.4 requires a TypedArray + +## **6.8.3** +- [Fix] `parse`: ignore `__proto__` keys (#428) +- [Robustness] `stringify`: avoid relying on a global `undefined` (#427) +- [Fix] `stringify`: avoid encoding arrayformat comma when `encodeValuesOnly = true` (#424) +- [readme] remove travis badge; add github actions/codecov badges; update URLs +- [Tests] clean up stringify tests slightly +- [Docs] add note and links for coercing primitive values (#408) +- [meta] fix README.md (#399) +- [actions] backport actions from main +- [Dev Deps] backport updates from main +- [Refactor] `stringify`: reduce branching +- [meta] do not publish workflow files + +## **6.8.2** +- [Fix] proper comma parsing of URL-encoded commas (#361) +- [Fix] parses comma delimited array while having percent-encoded comma treated as normal text (#336) + +## **6.8.1** +- [Fix] `parse`: Fix parsing array from object with `comma` true (#359) +- [Fix] `parse`: throw a TypeError instead of an Error for bad charset (#349) +- [Fix] `parse`: with comma true, handle field that holds an array of arrays (#335) +- [fix] `parse`: with comma true, do not split non-string values (#334) +- [meta] add tidelift marketing copy +- [meta] add `funding` field +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape`, `safe-publish-latest`, `evalmd`, `has-symbols`, `iconv-lite`, `mkdirp`, `object-inspect` +- [Tests] `parse`: add passing `arrayFormat` tests +- [Tests] use shared travis-ci configs +- [Tests] `Buffer.from` in node v5.0-v5.9 and v4.0-v4.4 requires a TypedArray +- [actions] add automatic rebasing / merge commit blocking + +## **6.8.0** +- [New] add `depth=false` to preserve the original key; [Fix] `depth=0` should preserve the original key (#326) +- [New] [Fix] stringify symbols and bigints +- [Fix] ensure node 0.12 can stringify Symbols +- [Fix] fix for an impossible situation: when the formatter is called with a non-string value +- [Refactor] `formats`: tiny bit of cleanup. +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `browserify`, `safe-publish-latest`, `iconv-lite`, `tape` +- [Tests] add tests for `depth=0` and `depth=false` behavior, both current and intuitive/intended (#326) +- [Tests] use `eclint` instead of `editorconfig-tools` +- [docs] readme: add security note +- [meta] add github sponsorship +- [meta] add FUNDING.yml +- [meta] Clean up license text so it’s properly detected as BSD-3-Clause + +## **6.7.3** +- [Fix] `parse`: ignore `__proto__` keys (#428) +- [Fix] `stringify`: avoid encoding arrayformat comma when `encodeValuesOnly = true` (#424) +- [Robustness] `stringify`: avoid relying on a global `undefined` (#427) +- [readme] remove travis badge; add github actions/codecov badges; update URLs +- [Docs] add note and links for coercing primitive values (#408) +- [meta] fix README.md (#399) +- [meta] do not publish workflow files +- [actions] backport actions from main +- [Dev Deps] backport updates from main +- [Tests] use `nyc` for coverage +- [Tests] clean up stringify tests slightly + +## **6.7.2** +- [Fix] proper comma parsing of URL-encoded commas (#361) +- [Fix] parses comma delimited array while having percent-encoded comma treated as normal text (#336) + +## **6.7.1** +- [Fix] `parse`: Fix parsing array from object with `comma` true (#359) +- [Fix] `parse`: with comma true, handle field that holds an array of arrays (#335) +- [fix] `parse`: with comma true, do not split non-string values (#334) +- [Fix] `parse`: throw a TypeError instead of an Error for bad charset (#349) +- [Fix] fix for an impossible situation: when the formatter is called with a non-string value +- [Refactor] `formats`: tiny bit of cleanup. +- readme: add security note +- [meta] add tidelift marketing copy +- [meta] add `funding` field +- [meta] add FUNDING.yml +- [meta] Clean up license text so it’s properly detected as BSD-3-Clause +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape`, `safe-publish-latest`, `evalmd`, `iconv-lite`, `mkdirp`, `object-inspect`, `browserify` +- [Tests] `parse`: add passing `arrayFormat` tests +- [Tests] use shared travis-ci configs +- [Tests] `Buffer.from` in node v5.0-v5.9 and v4.0-v4.4 requires a TypedArray +- [Tests] add tests for `depth=0` and `depth=false` behavior, both current and intuitive/intended +- [Tests] use `eclint` instead of `editorconfig-tools` +- [actions] add automatic rebasing / merge commit blocking + +## **6.7.0** +- [New] `stringify`/`parse`: add `comma` as an `arrayFormat` option (#276, #219) +- [Fix] correctly parse nested arrays (#212) +- [Fix] `utils.merge`: avoid a crash with a null target and a truthy non-array source, also with an array source +- [Robustness] `stringify`: cache `Object.prototype.hasOwnProperty` +- [Refactor] `utils`: `isBuffer`: small tweak; add tests +- [Refactor] use cached `Array.isArray` +- [Refactor] `parse`/`stringify`: make a function to normalize the options +- [Refactor] `utils`: reduce observable [[Get]]s +- [Refactor] `stringify`/`utils`: cache `Array.isArray` +- [Tests] always use `String(x)` over `x.toString()` +- [Tests] fix Buffer tests to work in node < 4.5 and node < 5.10 +- [Tests] temporarily allow coverage to fail + +## **6.6.1** +- [Fix] `parse`: ignore `__proto__` keys (#428) +- [Fix] fix for an impossible situation: when the formatter is called with a non-string value +- [Fix] `utils.merge`: avoid a crash with a null target and an array source +- [Fix] `utils.merge`: avoid a crash with a null target and a truthy non-array source +- [Fix] correctly parse nested arrays +- [Robustness] `stringify`: avoid relying on a global `undefined` (#427) +- [Robustness] `stringify`: cache `Object.prototype.hasOwnProperty` +- [Refactor] `formats`: tiny bit of cleanup. +- [Refactor] `utils`: `isBuffer`: small tweak; add tests +- [Refactor]: `stringify`/`utils`: cache `Array.isArray` +- [Refactor] `utils`: reduce observable [[Get]]s +- [Refactor] use cached `Array.isArray` +- [Refactor] `parse`/`stringify`: make a function to normalize the options +- [readme] remove travis badge; add github actions/codecov badges; update URLs +- [Docs] Clarify the need for "arrayLimit" option +- [meta] fix README.md (#399) +- [meta] do not publish workflow files +- [meta] Clean up license text so it’s properly detected as BSD-3-Clause +- [meta] add FUNDING.yml +- [meta] Fixes typo in CHANGELOG.md +- [actions] backport actions from main +- [Tests] fix Buffer tests to work in node < 4.5 and node < 5.10 +- [Tests] always use `String(x)` over `x.toString()` +- [Dev Deps] backport from main + +## **6.6.0** +- [New] Add support for iso-8859-1, utf8 "sentinel" and numeric entities (#268) +- [New] move two-value combine to a `utils` function (#189) +- [Fix] `stringify`: fix a crash with `strictNullHandling` and a custom `filter`/`serializeDate` (#279) +- [Fix] when `parseArrays` is false, properly handle keys ending in `[]` (#260) +- [Fix] `stringify`: do not crash in an obscure combo of `interpretNumericEntities`, a bad custom `decoder`, & `iso-8859-1` +- [Fix] `utils`: `merge`: fix crash when `source` is a truthy primitive & no options are provided +- [refactor] `stringify`: Avoid arr = arr.concat(...), push to the existing instance (#269) +- [Refactor] `parse`: only need to reassign the var once +- [Refactor] `parse`/`stringify`: clean up `charset` options checking; fix defaults +- [Refactor] add missing defaults +- [Refactor] `parse`: one less `concat` call +- [Refactor] `utils`: `compactQueue`: make it explicitly side-effecting +- [Dev Deps] update `browserify`, `eslint`, `@ljharb/eslint-config`, `iconv-lite`, `safe-publish-latest`, `tape` +- [Tests] up to `node` `v10.10`, `v9.11`, `v8.12`, `v6.14`, `v4.9`; pin included builds to LTS + +## **6.5.3** +- [Fix] `parse`: ignore `__proto__` keys (#428) +- [Fix]` `utils.merge`: avoid a crash with a null target and a truthy non-array source +- [Fix] correctly parse nested arrays +- [Fix] `stringify`: fix a crash with `strictNullHandling` and a custom `filter`/`serializeDate` (#279) +- [Fix] `utils`: `merge`: fix crash when `source` is a truthy primitive & no options are provided +- [Fix] when `parseArrays` is false, properly handle keys ending in `[]` +- [Fix] fix for an impossible situation: when the formatter is called with a non-string value +- [Fix] `utils.merge`: avoid a crash with a null target and an array source +- [Refactor] `utils`: reduce observable [[Get]]s +- [Refactor] use cached `Array.isArray` +- [Refactor] `stringify`: Avoid arr = arr.concat(...), push to the existing instance (#269) +- [Refactor] `parse`: only need to reassign the var once +- [Robustness] `stringify`: avoid relying on a global `undefined` (#427) +- [readme] remove travis badge; add github actions/codecov badges; update URLs +- [Docs] Clean up license text so it’s properly detected as BSD-3-Clause +- [Docs] Clarify the need for "arrayLimit" option +- [meta] fix README.md (#399) +- [meta] add FUNDING.yml +- [actions] backport actions from main +- [Tests] always use `String(x)` over `x.toString()` +- [Tests] remove nonexistent tape option +- [Dev Deps] backport from main + +## **6.5.2** +- [Fix] use `safer-buffer` instead of `Buffer` constructor +- [Refactor] utils: `module.exports` one thing, instead of mutating `exports` (#230) +- [Dev Deps] update `browserify`, `eslint`, `iconv-lite`, `safer-buffer`, `tape`, `browserify` + +## **6.5.1** +- [Fix] Fix parsing & compacting very deep objects (#224) +- [Refactor] name utils functions +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` +- [Tests] up to `node` `v8.4`; use `nvm install-latest-npm` so newer npm doesn’t break older node +- [Tests] Use precise dist for Node.js 0.6 runtime (#225) +- [Tests] make 0.6 required, now that it’s passing +- [Tests] on `node` `v8.2`; fix npm on node 0.6 + +## **6.5.0** +- [New] add `utils.assign` +- [New] pass default encoder/decoder to custom encoder/decoder functions (#206) +- [New] `parse`/`stringify`: add `ignoreQueryPrefix`/`addQueryPrefix` options, respectively (#213) +- [Fix] Handle stringifying empty objects with addQueryPrefix (#217) +- [Fix] do not mutate `options` argument (#207) +- [Refactor] `parse`: cache index to reuse in else statement (#182) +- [Docs] add various badges to readme (#208) +- [Dev Deps] update `eslint`, `browserify`, `iconv-lite`, `tape` +- [Tests] up to `node` `v8.1`, `v7.10`, `v6.11`; npm v4.6 breaks on node < v1; npm v5+ breaks on node < v4 +- [Tests] add `editorconfig-tools` + +## **6.4.1** +- [Fix] `parse`: ignore `__proto__` keys (#428) +- [Fix] fix for an impossible situation: when the formatter is called with a non-string value +- [Fix] use `safer-buffer` instead of `Buffer` constructor +- [Fix] `utils.merge`: avoid a crash with a null target and an array source +- [Fix]` `utils.merge`: avoid a crash with a null target and a truthy non-array source +- [Fix] `stringify`: fix a crash with `strictNullHandling` and a custom `filter`/`serializeDate` (#279) +- [Fix] `utils`: `merge`: fix crash when `source` is a truthy primitive & no options are provided +- [Fix] when `parseArrays` is false, properly handle keys ending in `[]` +- [Robustness] `stringify`: avoid relying on a global `undefined` (#427) +- [Refactor] use cached `Array.isArray` +- [Refactor] `stringify`: Avoid arr = arr.concat(...), push to the existing instance (#269) +- [readme] remove travis badge; add github actions/codecov badges; update URLs +- [Docs] Clarify the need for "arrayLimit" option +- [meta] fix README.md (#399) +- [meta] Clean up license text so it’s properly detected as BSD-3-Clause +- [meta] add FUNDING.yml +- [actions] backport actions from main +- [Tests] remove nonexistent tape option +- [Dev Deps] backport from main + +## **6.4.0** +- [New] `qs.stringify`: add `encodeValuesOnly` option +- [Fix] follow `allowPrototypes` option during merge (#201, #201) +- [Fix] support keys starting with brackets (#202, #200) +- [Fix] chmod a-x +- [Dev Deps] update `eslint` +- [Tests] up to `node` `v7.7`, `v6.10`,` v4.8`; disable osx builds since they block linux builds +- [eslint] reduce warnings + +## **6.3.3** +- [Fix] `parse`: ignore `__proto__` keys (#428) +- [Fix] fix for an impossible situation: when the formatter is called with a non-string value +- [Fix] `utils.merge`: avoid a crash with a null target and an array source +- [Fix]` `utils.merge`: avoid a crash with a null target and a truthy non-array source +- [Fix] `stringify`: fix a crash with `strictNullHandling` and a custom `filter`/`serializeDate` (#279) +- [Fix] `utils`: `merge`: fix crash when `source` is a truthy primitive & no options are provided +- [Fix] when `parseArrays` is false, properly handle keys ending in `[]` +- [Robustness] `stringify`: avoid relying on a global `undefined` (#427) +- [Refactor] use cached `Array.isArray` +- [Refactor] `stringify`: Avoid arr = arr.concat(...), push to the existing instance (#269) +- [Docs] Clarify the need for "arrayLimit" option +- [meta] fix README.md (#399) +- [meta] Clean up license text so it’s properly detected as BSD-3-Clause +- [meta] add FUNDING.yml +- [actions] backport actions from main +- [Tests] use `safer-buffer` instead of `Buffer` constructor +- [Tests] remove nonexistent tape option +- [Dev Deps] backport from main + +## **6.3.2** +- [Fix] follow `allowPrototypes` option during merge (#201, #200) +- [Dev Deps] update `eslint` +- [Fix] chmod a-x +- [Fix] support keys starting with brackets (#202, #200) +- [Tests] up to `node` `v7.7`, `v6.10`,` v4.8`; disable osx builds since they block linux builds + +## **6.3.1** +- [Fix] ensure that `allowPrototypes: false` does not ever shadow Object.prototype properties (thanks, @snyk!) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `browserify`, `iconv-lite`, `qs-iconv`, `tape` +- [Tests] on all node minors; improve test matrix +- [Docs] document stringify option `allowDots` (#195) +- [Docs] add empty object and array values example (#195) +- [Docs] Fix minor inconsistency/typo (#192) +- [Docs] document stringify option `sort` (#191) +- [Refactor] `stringify`: throw faster with an invalid encoder +- [Refactor] remove unnecessary escapes (#184) +- Remove contributing.md, since `qs` is no longer part of `hapi` (#183) + +## **6.3.0** +- [New] Add support for RFC 1738 (#174, #173) +- [New] `stringify`: Add `serializeDate` option to customize Date serialization (#159) +- [Fix] ensure `utils.merge` handles merging two arrays +- [Refactor] only constructors should be capitalized +- [Refactor] capitalized var names are for constructors only +- [Refactor] avoid using a sparse array +- [Robustness] `formats`: cache `String#replace` +- [Dev Deps] update `browserify`, `eslint`, `@ljharb/eslint-config`; add `safe-publish-latest` +- [Tests] up to `node` `v6.8`, `v4.6`; improve test matrix +- [Tests] flesh out arrayLimit/arrayFormat tests (#107) +- [Tests] skip Object.create tests when null objects are not available +- [Tests] Turn on eslint for test files (#175) + +## **6.2.4** +- [Fix] `parse`: ignore `__proto__` keys (#428) +- [Fix] `utils.merge`: avoid a crash with a null target and an array source +- [Fix] `utils.merge`: avoid a crash with a null target and a truthy non-array source +- [Fix] `utils`: `merge`: fix crash when `source` is a truthy primitive & no options are provided +- [Fix] when `parseArrays` is false, properly handle keys ending in `[]` +- [Robustness] `stringify`: avoid relying on a global `undefined` (#427) +- [Refactor] use cached `Array.isArray` +- [Docs] Clarify the need for "arrayLimit" option +- [meta] fix README.md (#399) +- [meta] Clean up license text so it’s properly detected as BSD-3-Clause +- [meta] add FUNDING.yml +- [actions] backport actions from main +- [Tests] use `safer-buffer` instead of `Buffer` constructor +- [Tests] remove nonexistent tape option +- [Dev Deps] backport from main + +## **6.2.3** +- [Fix] follow `allowPrototypes` option during merge (#201, #200) +- [Fix] chmod a-x +- [Fix] support keys starting with brackets (#202, #200) +- [Tests] up to `node` `v7.7`, `v6.10`,` v4.8`; disable osx builds since they block linux builds + +## **6.2.2** +- [Fix] ensure that `allowPrototypes: false` does not ever shadow Object.prototype properties + +## **6.2.1** +- [Fix] ensure `key[]=x&key[]&key[]=y` results in 3, not 2, values +- [Refactor] Be explicit and use `Object.prototype.hasOwnProperty.call` +- [Tests] remove `parallelshell` since it does not reliably report failures +- [Tests] up to `node` `v6.3`, `v5.12` +- [Dev Deps] update `tape`, `eslint`, `@ljharb/eslint-config`, `qs-iconv` + +## [**6.2.0**](https://github.com/ljharb/qs/issues?milestone=36&state=closed) +- [New] pass Buffers to the encoder/decoder directly (#161) +- [New] add "encoder" and "decoder" options, for custom param encoding/decoding (#160) +- [Fix] fix compacting of nested sparse arrays (#150) + +## **6.1.2 +- [Fix] follow `allowPrototypes` option during merge (#201, #200) +- [Fix] chmod a-x +- [Fix] support keys starting with brackets (#202, #200) +- [Tests] up to `node` `v7.7`, `v6.10`,` v4.8`; disable osx builds since they block linux builds + +## **6.1.1** +- [Fix] ensure that `allowPrototypes: false` does not ever shadow Object.prototype properties + +## [**6.1.0**](https://github.com/ljharb/qs/issues?milestone=35&state=closed) +- [New] allowDots option for `stringify` (#151) +- [Fix] "sort" option should work at a depth of 3 or more (#151) +- [Fix] Restore `dist` directory; will be removed in v7 (#148) + +## **6.0.4** +- [Fix] follow `allowPrototypes` option during merge (#201, #200) +- [Fix] chmod a-x +- [Fix] support keys starting with brackets (#202, #200) +- [Tests] up to `node` `v7.7`, `v6.10`,` v4.8`; disable osx builds since they block linux builds + +## **6.0.3** +- [Fix] ensure that `allowPrototypes: false` does not ever shadow Object.prototype properties +- [Fix] Restore `dist` directory; will be removed in v7 (#148) + +## [**6.0.2**](https://github.com/ljharb/qs/issues?milestone=33&state=closed) +- Revert ES6 requirement and restore support for node down to v0.8. + +## [**6.0.1**](https://github.com/ljharb/qs/issues?milestone=32&state=closed) +- [**#127**](https://github.com/ljharb/qs/pull/127) Fix engines definition in package.json + +## [**6.0.0**](https://github.com/ljharb/qs/issues?milestone=31&state=closed) +- [**#124**](https://github.com/ljharb/qs/issues/124) Use ES6 and drop support for node < v4 + +## **5.2.1** +- [Fix] ensure `key[]=x&key[]&key[]=y` results in 3, not 2, values + +## [**5.2.0**](https://github.com/ljharb/qs/issues?milestone=30&state=closed) +- [**#64**](https://github.com/ljharb/qs/issues/64) Add option to sort object keys in the query string + +## [**5.1.0**](https://github.com/ljharb/qs/issues?milestone=29&state=closed) +- [**#117**](https://github.com/ljharb/qs/issues/117) make URI encoding stringified results optional +- [**#106**](https://github.com/ljharb/qs/issues/106) Add flag `skipNulls` to optionally skip null values in stringify + +## [**5.0.0**](https://github.com/ljharb/qs/issues?milestone=28&state=closed) +- [**#114**](https://github.com/ljharb/qs/issues/114) default allowDots to false +- [**#100**](https://github.com/ljharb/qs/issues/100) include dist to npm + +## [**4.0.0**](https://github.com/ljharb/qs/issues?milestone=26&state=closed) +- [**#98**](https://github.com/ljharb/qs/issues/98) make returning plain objects and allowing prototype overwriting properties optional + +## [**3.1.0**](https://github.com/ljharb/qs/issues?milestone=24&state=closed) +- [**#89**](https://github.com/ljharb/qs/issues/89) Add option to disable "Transform dot notation to bracket notation" + +## [**3.0.0**](https://github.com/ljharb/qs/issues?milestone=23&state=closed) +- [**#80**](https://github.com/ljharb/qs/issues/80) qs.parse silently drops properties +- [**#77**](https://github.com/ljharb/qs/issues/77) Perf boost +- [**#60**](https://github.com/ljharb/qs/issues/60) Add explicit option to disable array parsing +- [**#74**](https://github.com/ljharb/qs/issues/74) Bad parse when turning array into object +- [**#81**](https://github.com/ljharb/qs/issues/81) Add a `filter` option +- [**#68**](https://github.com/ljharb/qs/issues/68) Fixed issue with recursion and passing strings into objects. +- [**#66**](https://github.com/ljharb/qs/issues/66) Add mixed array and object dot notation support Closes: #47 +- [**#76**](https://github.com/ljharb/qs/issues/76) RFC 3986 +- [**#85**](https://github.com/ljharb/qs/issues/85) No equal sign +- [**#84**](https://github.com/ljharb/qs/issues/84) update license attribute + +## [**2.4.1**](https://github.com/ljharb/qs/issues?milestone=20&state=closed) +- [**#73**](https://github.com/ljharb/qs/issues/73) Property 'hasOwnProperty' of object # is not a function + +## [**2.4.0**](https://github.com/ljharb/qs/issues?milestone=19&state=closed) +- [**#70**](https://github.com/ljharb/qs/issues/70) Add arrayFormat option + +## [**2.3.3**](https://github.com/ljharb/qs/issues?milestone=18&state=closed) +- [**#59**](https://github.com/ljharb/qs/issues/59) make sure array indexes are >= 0, closes #57 +- [**#58**](https://github.com/ljharb/qs/issues/58) make qs usable for browser loader + +## [**2.3.2**](https://github.com/ljharb/qs/issues?milestone=17&state=closed) +- [**#55**](https://github.com/ljharb/qs/issues/55) allow merging a string into an object + +## [**2.3.1**](https://github.com/ljharb/qs/issues?milestone=16&state=closed) +- [**#52**](https://github.com/ljharb/qs/issues/52) Return "undefined" and "false" instead of throwing "TypeError". + +## [**2.3.0**](https://github.com/ljharb/qs/issues?milestone=15&state=closed) +- [**#50**](https://github.com/ljharb/qs/issues/50) add option to omit array indices, closes #46 + +## [**2.2.5**](https://github.com/ljharb/qs/issues?milestone=14&state=closed) +- [**#39**](https://github.com/ljharb/qs/issues/39) Is there an alternative to Buffer.isBuffer? +- [**#49**](https://github.com/ljharb/qs/issues/49) refactor utils.merge, fixes #45 +- [**#41**](https://github.com/ljharb/qs/issues/41) avoid browserifying Buffer, for #39 + +## [**2.2.4**](https://github.com/ljharb/qs/issues?milestone=13&state=closed) +- [**#38**](https://github.com/ljharb/qs/issues/38) how to handle object keys beginning with a number + +## [**2.2.3**](https://github.com/ljharb/qs/issues?milestone=12&state=closed) +- [**#37**](https://github.com/ljharb/qs/issues/37) parser discards first empty value in array +- [**#36**](https://github.com/ljharb/qs/issues/36) Update to lab 4.x + +## [**2.2.2**](https://github.com/ljharb/qs/issues?milestone=11&state=closed) +- [**#33**](https://github.com/ljharb/qs/issues/33) Error when plain object in a value +- [**#34**](https://github.com/ljharb/qs/issues/34) use Object.prototype.hasOwnProperty.call instead of obj.hasOwnProperty +- [**#24**](https://github.com/ljharb/qs/issues/24) Changelog? Semver? + +## [**2.2.1**](https://github.com/ljharb/qs/issues?milestone=10&state=closed) +- [**#32**](https://github.com/ljharb/qs/issues/32) account for circular references properly, closes #31 +- [**#31**](https://github.com/ljharb/qs/issues/31) qs.parse stackoverflow on circular objects + +## [**2.2.0**](https://github.com/ljharb/qs/issues?milestone=9&state=closed) +- [**#26**](https://github.com/ljharb/qs/issues/26) Don't use Buffer global if it's not present +- [**#30**](https://github.com/ljharb/qs/issues/30) Bug when merging non-object values into arrays +- [**#29**](https://github.com/ljharb/qs/issues/29) Don't call Utils.clone at the top of Utils.merge +- [**#23**](https://github.com/ljharb/qs/issues/23) Ability to not limit parameters? + +## [**2.1.0**](https://github.com/ljharb/qs/issues?milestone=8&state=closed) +- [**#22**](https://github.com/ljharb/qs/issues/22) Enable using a RegExp as delimiter + +## [**2.0.0**](https://github.com/ljharb/qs/issues?milestone=7&state=closed) +- [**#18**](https://github.com/ljharb/qs/issues/18) Why is there arrayLimit? +- [**#20**](https://github.com/ljharb/qs/issues/20) Configurable parametersLimit +- [**#21**](https://github.com/ljharb/qs/issues/21) make all limits optional, for #18, for #20 + +## [**1.2.2**](https://github.com/ljharb/qs/issues?milestone=6&state=closed) +- [**#19**](https://github.com/ljharb/qs/issues/19) Don't overwrite null values + +## [**1.2.1**](https://github.com/ljharb/qs/issues?milestone=5&state=closed) +- [**#16**](https://github.com/ljharb/qs/issues/16) ignore non-string delimiters +- [**#15**](https://github.com/ljharb/qs/issues/15) Close code block + +## [**1.2.0**](https://github.com/ljharb/qs/issues?milestone=4&state=closed) +- [**#12**](https://github.com/ljharb/qs/issues/12) Add optional delim argument +- [**#13**](https://github.com/ljharb/qs/issues/13) fix #11: flattened keys in array are now correctly parsed + +## [**1.1.0**](https://github.com/ljharb/qs/issues?milestone=3&state=closed) +- [**#7**](https://github.com/ljharb/qs/issues/7) Empty values of a POST array disappear after being submitted +- [**#9**](https://github.com/ljharb/qs/issues/9) Should not omit equals signs (=) when value is null +- [**#6**](https://github.com/ljharb/qs/issues/6) Minor grammar fix in README + +## [**1.0.2**](https://github.com/ljharb/qs/issues?milestone=2&state=closed) +- [**#5**](https://github.com/ljharb/qs/issues/5) array holes incorrectly copied into object on large index diff --git a/backend/node_modules/qs/LICENSE.md b/backend/node_modules/qs/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..fecf6b6942d17bc7ae41a5e106dc98815c0db652 --- /dev/null +++ b/backend/node_modules/qs/LICENSE.md @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2014, Nathan LaFreniere and other [contributors](https://github.com/ljharb/qs/graphs/contributors) +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/backend/node_modules/qs/README.md b/backend/node_modules/qs/README.md new file mode 100644 index 0000000000000000000000000000000000000000..11be8531dd587984a378408c61dee80057842c63 --- /dev/null +++ b/backend/node_modules/qs/README.md @@ -0,0 +1,625 @@ +# qs [![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] + +A querystring parsing and stringifying library with some added security. + +Lead Maintainer: [Jordan Harband](https://github.com/ljharb) + +The **qs** module was originally created and maintained by [TJ Holowaychuk](https://github.com/visionmedia/node-querystring). + +## Usage + +```javascript +var qs = require('qs'); +var assert = require('assert'); + +var obj = qs.parse('a=c'); +assert.deepEqual(obj, { a: 'c' }); + +var str = qs.stringify(obj); +assert.equal(str, 'a=c'); +``` + +### Parsing Objects + +[](#preventEval) +```javascript +qs.parse(string, [options]); +``` + +**qs** allows you to create nested objects within your query strings, by surrounding the name of sub-keys with square brackets `[]`. +For example, the string `'foo[bar]=baz'` converts to: + +```javascript +assert.deepEqual(qs.parse('foo[bar]=baz'), { + foo: { + bar: 'baz' + } +}); +``` + +When using the `plainObjects` option the parsed value is returned as a null object, created via `Object.create(null)` and as such you should be aware that prototype methods will not exist on it and a user may set those names to whatever value they like: + +```javascript +var nullObject = qs.parse('a[hasOwnProperty]=b', { plainObjects: true }); +assert.deepEqual(nullObject, { a: { hasOwnProperty: 'b' } }); +``` + +By default parameters that would overwrite properties on the object prototype are ignored, if you wish to keep the data from those fields either use `plainObjects` as mentioned above, or set `allowPrototypes` to `true` which will allow user input to overwrite those properties. *WARNING* It is generally a bad idea to enable this option as it can cause problems when attempting to use the properties that have been overwritten. Always be careful with this option. + +```javascript +var protoObject = qs.parse('a[hasOwnProperty]=b', { allowPrototypes: true }); +assert.deepEqual(protoObject, { a: { hasOwnProperty: 'b' } }); +``` + +URI encoded strings work too: + +```javascript +assert.deepEqual(qs.parse('a%5Bb%5D=c'), { + a: { b: 'c' } +}); +``` + +You can also nest your objects, like `'foo[bar][baz]=foobarbaz'`: + +```javascript +assert.deepEqual(qs.parse('foo[bar][baz]=foobarbaz'), { + foo: { + bar: { + baz: 'foobarbaz' + } + } +}); +``` + +By default, when nesting objects **qs** will only parse up to 5 children deep. This means if you attempt to parse a string like +`'a[b][c][d][e][f][g][h][i]=j'` your resulting object will be: + +```javascript +var expected = { + a: { + b: { + c: { + d: { + e: { + f: { + '[g][h][i]': 'j' + } + } + } + } + } + } +}; +var string = 'a[b][c][d][e][f][g][h][i]=j'; +assert.deepEqual(qs.parse(string), expected); +``` + +This depth can be overridden by passing a `depth` option to `qs.parse(string, [options])`: + +```javascript +var deep = qs.parse('a[b][c][d][e][f][g][h][i]=j', { depth: 1 }); +assert.deepEqual(deep, { a: { b: { '[c][d][e][f][g][h][i]': 'j' } } }); +``` + +The depth limit helps mitigate abuse when **qs** is used to parse user input, and it is recommended to keep it a reasonably small number. + +For similar reasons, by default **qs** will only parse up to 1000 parameters. This can be overridden by passing a `parameterLimit` option: + +```javascript +var limited = qs.parse('a=b&c=d', { parameterLimit: 1 }); +assert.deepEqual(limited, { a: 'b' }); +``` + +To bypass the leading question mark, use `ignoreQueryPrefix`: + +```javascript +var prefixed = qs.parse('?a=b&c=d', { ignoreQueryPrefix: true }); +assert.deepEqual(prefixed, { a: 'b', c: 'd' }); +``` + +An optional delimiter can also be passed: + +```javascript +var delimited = qs.parse('a=b;c=d', { delimiter: ';' }); +assert.deepEqual(delimited, { a: 'b', c: 'd' }); +``` + +Delimiters can be a regular expression too: + +```javascript +var regexed = qs.parse('a=b;c=d,e=f', { delimiter: /[;,]/ }); +assert.deepEqual(regexed, { a: 'b', c: 'd', e: 'f' }); +``` + +Option `allowDots` can be used to enable dot notation: + +```javascript +var withDots = qs.parse('a.b=c', { allowDots: true }); +assert.deepEqual(withDots, { a: { b: 'c' } }); +``` + +If you have to deal with legacy browsers or services, there's +also support for decoding percent-encoded octets as iso-8859-1: + +```javascript +var oldCharset = qs.parse('a=%A7', { charset: 'iso-8859-1' }); +assert.deepEqual(oldCharset, { a: '§' }); +``` + +Some services add an initial `utf8=✓` value to forms so that old +Internet Explorer versions are more likely to submit the form as +utf-8. Additionally, the server can check the value against wrong +encodings of the checkmark character and detect that a query string +or `application/x-www-form-urlencoded` body was *not* sent as +utf-8, eg. if the form had an `accept-charset` parameter or the +containing page had a different character set. + +**qs** supports this mechanism via the `charsetSentinel` option. +If specified, the `utf8` parameter will be omitted from the +returned object. It will be used to switch to `iso-8859-1`/`utf-8` +mode depending on how the checkmark is encoded. + +**Important**: When you specify both the `charset` option and the +`charsetSentinel` option, the `charset` will be overridden when +the request contains a `utf8` parameter from which the actual +charset can be deduced. In that sense the `charset` will behave +as the default charset rather than the authoritative charset. + +```javascript +var detectedAsUtf8 = qs.parse('utf8=%E2%9C%93&a=%C3%B8', { + charset: 'iso-8859-1', + charsetSentinel: true +}); +assert.deepEqual(detectedAsUtf8, { a: 'ø' }); + +// Browsers encode the checkmark as ✓ when submitting as iso-8859-1: +var detectedAsIso8859_1 = qs.parse('utf8=%26%2310003%3B&a=%F8', { + charset: 'utf-8', + charsetSentinel: true +}); +assert.deepEqual(detectedAsIso8859_1, { a: 'ø' }); +``` + +If you want to decode the `&#...;` syntax to the actual character, +you can specify the `interpretNumericEntities` option as well: + +```javascript +var detectedAsIso8859_1 = qs.parse('a=%26%239786%3B', { + charset: 'iso-8859-1', + interpretNumericEntities: true +}); +assert.deepEqual(detectedAsIso8859_1, { a: '☺' }); +``` + +It also works when the charset has been detected in `charsetSentinel` +mode. + +### Parsing Arrays + +**qs** can also parse arrays using a similar `[]` notation: + +```javascript +var withArray = qs.parse('a[]=b&a[]=c'); +assert.deepEqual(withArray, { a: ['b', 'c'] }); +``` + +You may specify an index as well: + +```javascript +var withIndexes = qs.parse('a[1]=c&a[0]=b'); +assert.deepEqual(withIndexes, { a: ['b', 'c'] }); +``` + +Note that the only difference between an index in an array and a key in an object is that the value between the brackets must be a number +to create an array. When creating arrays with specific indices, **qs** will compact a sparse array to only the existing values preserving +their order: + +```javascript +var noSparse = qs.parse('a[1]=b&a[15]=c'); +assert.deepEqual(noSparse, { a: ['b', 'c'] }); +``` + +You may also use `allowSparse` option to parse sparse arrays: + +```javascript +var sparseArray = qs.parse('a[1]=2&a[3]=5', { allowSparse: true }); +assert.deepEqual(sparseArray, { a: [, '2', , '5'] }); +``` + +Note that an empty string is also a value, and will be preserved: + +```javascript +var withEmptyString = qs.parse('a[]=&a[]=b'); +assert.deepEqual(withEmptyString, { a: ['', 'b'] }); + +var withIndexedEmptyString = qs.parse('a[0]=b&a[1]=&a[2]=c'); +assert.deepEqual(withIndexedEmptyString, { a: ['b', '', 'c'] }); +``` + +**qs** will also limit specifying indices in an array to a maximum index of `20`. Any array members with an index of greater than `20` will +instead be converted to an object with the index as the key. This is needed to handle cases when someone sent, for example, `a[999999999]` and it will take significant time to iterate over this huge array. + +```javascript +var withMaxIndex = qs.parse('a[100]=b'); +assert.deepEqual(withMaxIndex, { a: { '100': 'b' } }); +``` + +This limit can be overridden by passing an `arrayLimit` option: + +```javascript +var withArrayLimit = qs.parse('a[1]=b', { arrayLimit: 0 }); +assert.deepEqual(withArrayLimit, { a: { '1': 'b' } }); +``` + +To disable array parsing entirely, set `parseArrays` to `false`. + +```javascript +var noParsingArrays = qs.parse('a[]=b', { parseArrays: false }); +assert.deepEqual(noParsingArrays, { a: { '0': 'b' } }); +``` + +If you mix notations, **qs** will merge the two items into an object: + +```javascript +var mixedNotation = qs.parse('a[0]=b&a[b]=c'); +assert.deepEqual(mixedNotation, { a: { '0': 'b', b: 'c' } }); +``` + +You can also create arrays of objects: + +```javascript +var arraysOfObjects = qs.parse('a[][b]=c'); +assert.deepEqual(arraysOfObjects, { a: [{ b: 'c' }] }); +``` + +Some people use comma to join array, **qs** can parse it: +```javascript +var arraysOfObjects = qs.parse('a=b,c', { comma: true }) +assert.deepEqual(arraysOfObjects, { a: ['b', 'c'] }) +``` +(_this cannot convert nested objects, such as `a={b:1},{c:d}`_) + +### Parsing primitive/scalar values (numbers, booleans, null, etc) + +By default, all values are parsed as strings. This behavior will not change and is explained in [issue #91](https://github.com/ljharb/qs/issues/91). + +```javascript +var primitiveValues = qs.parse('a=15&b=true&c=null'); +assert.deepEqual(primitiveValues, { a: '15', b: 'true', c: 'null' }); +``` + +If you wish to auto-convert values which look like numbers, booleans, and other values into their primitive counterparts, you can use the [query-types Express JS middleware](https://github.com/xpepermint/query-types) which will auto-convert all request query parameters. + +### Stringifying + +[](#preventEval) +```javascript +qs.stringify(object, [options]); +``` + +When stringifying, **qs** by default URI encodes output. Objects are stringified as you would expect: + +```javascript +assert.equal(qs.stringify({ a: 'b' }), 'a=b'); +assert.equal(qs.stringify({ a: { b: 'c' } }), 'a%5Bb%5D=c'); +``` + +This encoding can be disabled by setting the `encode` option to `false`: + +```javascript +var unencoded = qs.stringify({ a: { b: 'c' } }, { encode: false }); +assert.equal(unencoded, 'a[b]=c'); +``` + +Encoding can be disabled for keys by setting the `encodeValuesOnly` option to `true`: +```javascript +var encodedValues = qs.stringify( + { a: 'b', c: ['d', 'e=f'], f: [['g'], ['h']] }, + { encodeValuesOnly: true } +); +assert.equal(encodedValues,'a=b&c[0]=d&c[1]=e%3Df&f[0][0]=g&f[1][0]=h'); +``` + +This encoding can also be replaced by a custom encoding method set as `encoder` option: + +```javascript +var encoded = qs.stringify({ a: { b: 'c' } }, { encoder: function (str) { + // Passed in values `a`, `b`, `c` + return // Return encoded string +}}) +``` + +_(Note: the `encoder` option does not apply if `encode` is `false`)_ + +Analogue to the `encoder` there is a `decoder` option for `parse` to override decoding of properties and values: + +```javascript +var decoded = qs.parse('x=z', { decoder: function (str) { + // Passed in values `x`, `z` + return // Return decoded string +}}) +``` + +You can encode keys and values using different logic by using the type argument provided to the encoder: + +```javascript +var encoded = qs.stringify({ a: { b: 'c' } }, { encoder: function (str, defaultEncoder, charset, type) { + if (type === 'key') { + return // Encoded key + } else if (type === 'value') { + return // Encoded value + } +}}) +``` + +The type argument is also provided to the decoder: + +```javascript +var decoded = qs.parse('x=z', { decoder: function (str, defaultDecoder, charset, type) { + if (type === 'key') { + return // Decoded key + } else if (type === 'value') { + return // Decoded value + } +}}) +``` + +Examples beyond this point will be shown as though the output is not URI encoded for clarity. Please note that the return values in these cases *will* be URI encoded during real usage. + +When arrays are stringified, by default they are given explicit indices: + +```javascript +qs.stringify({ a: ['b', 'c', 'd'] }); +// 'a[0]=b&a[1]=c&a[2]=d' +``` + +You may override this by setting the `indices` option to `false`: + +```javascript +qs.stringify({ a: ['b', 'c', 'd'] }, { indices: false }); +// 'a=b&a=c&a=d' +``` + +You may use the `arrayFormat` option to specify the format of the output array: + +```javascript +qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'indices' }) +// 'a[0]=b&a[1]=c' +qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'brackets' }) +// 'a[]=b&a[]=c' +qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'repeat' }) +// 'a=b&a=c' +qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'comma' }) +// 'a=b,c' +``` + +Note: when using `arrayFormat` set to `'comma'`, you can also pass the `commaRoundTrip` option set to `true` or `false`, to append `[]` on single-item arrays, so that they can round trip through a parse. + +When objects are stringified, by default they use bracket notation: + +```javascript +qs.stringify({ a: { b: { c: 'd', e: 'f' } } }); +// 'a[b][c]=d&a[b][e]=f' +``` + +You may override this to use dot notation by setting the `allowDots` option to `true`: + +```javascript +qs.stringify({ a: { b: { c: 'd', e: 'f' } } }, { allowDots: true }); +// 'a.b.c=d&a.b.e=f' +``` + +Empty strings and null values will omit the value, but the equals sign (=) remains in place: + +```javascript +assert.equal(qs.stringify({ a: '' }), 'a='); +``` + +Key with no values (such as an empty object or array) will return nothing: + +```javascript +assert.equal(qs.stringify({ a: [] }), ''); +assert.equal(qs.stringify({ a: {} }), ''); +assert.equal(qs.stringify({ a: [{}] }), ''); +assert.equal(qs.stringify({ a: { b: []} }), ''); +assert.equal(qs.stringify({ a: { b: {}} }), ''); +``` + +Properties that are set to `undefined` will be omitted entirely: + +```javascript +assert.equal(qs.stringify({ a: null, b: undefined }), 'a='); +``` + +The query string may optionally be prepended with a question mark: + +```javascript +assert.equal(qs.stringify({ a: 'b', c: 'd' }, { addQueryPrefix: true }), '?a=b&c=d'); +``` + +The delimiter may be overridden with stringify as well: + +```javascript +assert.equal(qs.stringify({ a: 'b', c: 'd' }, { delimiter: ';' }), 'a=b;c=d'); +``` + +If you only want to override the serialization of `Date` objects, you can provide a `serializeDate` option: + +```javascript +var date = new Date(7); +assert.equal(qs.stringify({ a: date }), 'a=1970-01-01T00:00:00.007Z'.replace(/:/g, '%3A')); +assert.equal( + qs.stringify({ a: date }, { serializeDate: function (d) { return d.getTime(); } }), + 'a=7' +); +``` + +You may use the `sort` option to affect the order of parameter keys: + +```javascript +function alphabeticalSort(a, b) { + return a.localeCompare(b); +} +assert.equal(qs.stringify({ a: 'c', z: 'y', b : 'f' }, { sort: alphabeticalSort }), 'a=c&b=f&z=y'); +``` + +Finally, you can use the `filter` option to restrict which keys will be included in the stringified output. +If you pass a function, it will be called for each key to obtain the replacement value. Otherwise, if you +pass an array, it will be used to select properties and array indices for stringification: + +```javascript +function filterFunc(prefix, value) { + if (prefix == 'b') { + // Return an `undefined` value to omit a property. + return; + } + if (prefix == 'e[f]') { + return value.getTime(); + } + if (prefix == 'e[g][0]') { + return value * 2; + } + return value; +} +qs.stringify({ a: 'b', c: 'd', e: { f: new Date(123), g: [2] } }, { filter: filterFunc }); +// 'a=b&c=d&e[f]=123&e[g][0]=4' +qs.stringify({ a: 'b', c: 'd', e: 'f' }, { filter: ['a', 'e'] }); +// 'a=b&e=f' +qs.stringify({ a: ['b', 'c', 'd'], e: 'f' }, { filter: ['a', 0, 2] }); +// 'a[0]=b&a[2]=d' +``` + +### Handling of `null` values + +By default, `null` values are treated like empty strings: + +```javascript +var withNull = qs.stringify({ a: null, b: '' }); +assert.equal(withNull, 'a=&b='); +``` + +Parsing does not distinguish between parameters with and without equal signs. Both are converted to empty strings. + +```javascript +var equalsInsensitive = qs.parse('a&b='); +assert.deepEqual(equalsInsensitive, { a: '', b: '' }); +``` + +To distinguish between `null` values and empty strings use the `strictNullHandling` flag. In the result string the `null` +values have no `=` sign: + +```javascript +var strictNull = qs.stringify({ a: null, b: '' }, { strictNullHandling: true }); +assert.equal(strictNull, 'a&b='); +``` + +To parse values without `=` back to `null` use the `strictNullHandling` flag: + +```javascript +var parsedStrictNull = qs.parse('a&b=', { strictNullHandling: true }); +assert.deepEqual(parsedStrictNull, { a: null, b: '' }); +``` + +To completely skip rendering keys with `null` values, use the `skipNulls` flag: + +```javascript +var nullsSkipped = qs.stringify({ a: 'b', c: null}, { skipNulls: true }); +assert.equal(nullsSkipped, 'a=b'); +``` + +If you're communicating with legacy systems, you can switch to `iso-8859-1` +using the `charset` option: + +```javascript +var iso = qs.stringify({ æ: 'æ' }, { charset: 'iso-8859-1' }); +assert.equal(iso, '%E6=%E6'); +``` + +Characters that don't exist in `iso-8859-1` will be converted to numeric +entities, similar to what browsers do: + +```javascript +var numeric = qs.stringify({ a: '☺' }, { charset: 'iso-8859-1' }); +assert.equal(numeric, 'a=%26%239786%3B'); +``` + +You can use the `charsetSentinel` option to announce the character by +including an `utf8=✓` parameter with the proper encoding if the checkmark, +similar to what Ruby on Rails and others do when submitting forms. + +```javascript +var sentinel = qs.stringify({ a: '☺' }, { charsetSentinel: true }); +assert.equal(sentinel, 'utf8=%E2%9C%93&a=%E2%98%BA'); + +var isoSentinel = qs.stringify({ a: 'æ' }, { charsetSentinel: true, charset: 'iso-8859-1' }); +assert.equal(isoSentinel, 'utf8=%26%2310003%3B&a=%E6'); +``` + +### Dealing with special character sets + +By default the encoding and decoding of characters is done in `utf-8`, +and `iso-8859-1` support is also built in via the `charset` parameter. + +If you wish to encode querystrings to a different character set (i.e. +[Shift JIS](https://en.wikipedia.org/wiki/Shift_JIS)) you can use the +[`qs-iconv`](https://github.com/martinheidegger/qs-iconv) library: + +```javascript +var encoder = require('qs-iconv/encoder')('shift_jis'); +var shiftJISEncoded = qs.stringify({ a: 'こんにちは!' }, { encoder: encoder }); +assert.equal(shiftJISEncoded, 'a=%82%B1%82%F1%82%C9%82%BF%82%CD%81I'); +``` + +This also works for decoding of query strings: + +```javascript +var decoder = require('qs-iconv/decoder')('shift_jis'); +var obj = qs.parse('a=%82%B1%82%F1%82%C9%82%BF%82%CD%81I', { decoder: decoder }); +assert.deepEqual(obj, { a: 'こんにちは!' }); +``` + +### RFC 3986 and RFC 1738 space encoding + +RFC3986 used as default option and encodes ' ' to *%20* which is backward compatible. +In the same time, output can be stringified as per RFC1738 with ' ' equal to '+'. + +``` +assert.equal(qs.stringify({ a: 'b c' }), 'a=b%20c'); +assert.equal(qs.stringify({ a: 'b c' }, { format : 'RFC3986' }), 'a=b%20c'); +assert.equal(qs.stringify({ a: 'b c' }, { format : 'RFC1738' }), 'a=b+c'); +``` + +## Security + +Please email [@ljharb](https://github.com/ljharb) or see https://tidelift.com/security if you have a potential security vulnerability to report. + +## qs for enterprise + +Available as part of the Tidelift Subscription + +The maintainers of qs and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-qs?utm_source=npm-qs&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) + +[package-url]: https://npmjs.org/package/qs +[npm-version-svg]: https://versionbadg.es/ljharb/qs.svg +[deps-svg]: https://david-dm.org/ljharb/qs.svg +[deps-url]: https://david-dm.org/ljharb/qs +[dev-deps-svg]: https://david-dm.org/ljharb/qs/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/qs#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/qs.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/qs.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/qs.svg +[downloads-url]: https://npm-stat.com/charts.html?package=qs +[codecov-image]: https://codecov.io/gh/ljharb/qs/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/qs/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/qs +[actions-url]: https://github.com/ljharb/qs/actions diff --git a/backend/node_modules/qs/dist/qs.js b/backend/node_modules/qs/dist/qs.js new file mode 100644 index 0000000000000000000000000000000000000000..1c620a48d38da78120ae19850e9a00c1e17b9b0a --- /dev/null +++ b/backend/node_modules/qs/dist/qs.js @@ -0,0 +1,2054 @@ +(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Qs = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i -1) { + return val.split(','); + } + + return val; +}; + +// This is what browsers will submit when the ✓ character occurs in an +// application/x-www-form-urlencoded body and the encoding of the page containing +// the form is iso-8859-1, or when the submitted form has an accept-charset +// attribute of iso-8859-1. Presumably also with other charsets that do not contain +// the ✓ character, such as us-ascii. +var isoSentinel = 'utf8=%26%2310003%3B'; // encodeURIComponent('✓') + +// These are the percent-encoded utf-8 octets representing a checkmark, indicating that the request actually is utf-8 encoded. +var charsetSentinel = 'utf8=%E2%9C%93'; // encodeURIComponent('✓') + +var parseValues = function parseQueryStringValues(str, options) { + var obj = {}; + var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, '') : str; + var limit = options.parameterLimit === Infinity ? undefined : options.parameterLimit; + var parts = cleanStr.split(options.delimiter, limit); + var skipIndex = -1; // Keep track of where the utf8 sentinel was found + var i; + + var charset = options.charset; + if (options.charsetSentinel) { + for (i = 0; i < parts.length; ++i) { + if (parts[i].indexOf('utf8=') === 0) { + if (parts[i] === charsetSentinel) { + charset = 'utf-8'; + } else if (parts[i] === isoSentinel) { + charset = 'iso-8859-1'; + } + skipIndex = i; + i = parts.length; // The eslint settings do not allow break; + } + } + } + + for (i = 0; i < parts.length; ++i) { + if (i === skipIndex) { + continue; + } + var part = parts[i]; + + var bracketEqualsPos = part.indexOf(']='); + var pos = bracketEqualsPos === -1 ? part.indexOf('=') : bracketEqualsPos + 1; + + var key, val; + if (pos === -1) { + key = options.decoder(part, defaults.decoder, charset, 'key'); + val = options.strictNullHandling ? null : ''; + } else { + key = options.decoder(part.slice(0, pos), defaults.decoder, charset, 'key'); + val = utils.maybeMap( + parseArrayValue(part.slice(pos + 1), options), + function (encodedVal) { + return options.decoder(encodedVal, defaults.decoder, charset, 'value'); + } + ); + } + + if (val && options.interpretNumericEntities && charset === 'iso-8859-1') { + val = interpretNumericEntities(val); + } + + if (part.indexOf('[]=') > -1) { + val = isArray(val) ? [val] : val; + } + + if (has.call(obj, key)) { + obj[key] = utils.combine(obj[key], val); + } else { + obj[key] = val; + } + } + + return obj; +}; + +var parseObject = function (chain, val, options, valuesParsed) { + var leaf = valuesParsed ? val : parseArrayValue(val, options); + + for (var i = chain.length - 1; i >= 0; --i) { + var obj; + var root = chain[i]; + + if (root === '[]' && options.parseArrays) { + obj = [].concat(leaf); + } else { + obj = options.plainObjects ? Object.create(null) : {}; + var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root; + var index = parseInt(cleanRoot, 10); + if (!options.parseArrays && cleanRoot === '') { + obj = { 0: leaf }; + } else if ( + !isNaN(index) + && root !== cleanRoot + && String(index) === cleanRoot + && index >= 0 + && (options.parseArrays && index <= options.arrayLimit) + ) { + obj = []; + obj[index] = leaf; + } else if (cleanRoot !== '__proto__') { + obj[cleanRoot] = leaf; + } + } + + leaf = obj; + } + + return leaf; +}; + +var parseKeys = function parseQueryStringKeys(givenKey, val, options, valuesParsed) { + if (!givenKey) { + return; + } + + // Transform dot notation to bracket notation + var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, '[$1]') : givenKey; + + // The regex chunks + + var brackets = /(\[[^[\]]*])/; + var child = /(\[[^[\]]*])/g; + + // Get the parent + + var segment = options.depth > 0 && brackets.exec(key); + var parent = segment ? key.slice(0, segment.index) : key; + + // Stash the parent if it exists + + var keys = []; + if (parent) { + // If we aren't using plain objects, optionally prefix keys that would overwrite object prototype properties + if (!options.plainObjects && has.call(Object.prototype, parent)) { + if (!options.allowPrototypes) { + return; + } + } + + keys.push(parent); + } + + // Loop through children appending to the array until we hit depth + + var i = 0; + while (options.depth > 0 && (segment = child.exec(key)) !== null && i < options.depth) { + i += 1; + if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) { + if (!options.allowPrototypes) { + return; + } + } + keys.push(segment[1]); + } + + // If there's a remainder, just add whatever is left + + if (segment) { + keys.push('[' + key.slice(segment.index) + ']'); + } + + return parseObject(keys, val, options, valuesParsed); +}; + +var normalizeParseOptions = function normalizeParseOptions(opts) { + if (!opts) { + return defaults; + } + + if (opts.decoder !== null && opts.decoder !== undefined && typeof opts.decoder !== 'function') { + throw new TypeError('Decoder has to be a function.'); + } + + if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') { + throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined'); + } + var charset = typeof opts.charset === 'undefined' ? defaults.charset : opts.charset; + + return { + allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots, + allowPrototypes: typeof opts.allowPrototypes === 'boolean' ? opts.allowPrototypes : defaults.allowPrototypes, + allowSparse: typeof opts.allowSparse === 'boolean' ? opts.allowSparse : defaults.allowSparse, + arrayLimit: typeof opts.arrayLimit === 'number' ? opts.arrayLimit : defaults.arrayLimit, + charset: charset, + charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel, + comma: typeof opts.comma === 'boolean' ? opts.comma : defaults.comma, + decoder: typeof opts.decoder === 'function' ? opts.decoder : defaults.decoder, + delimiter: typeof opts.delimiter === 'string' || utils.isRegExp(opts.delimiter) ? opts.delimiter : defaults.delimiter, + // eslint-disable-next-line no-implicit-coercion, no-extra-parens + depth: (typeof opts.depth === 'number' || opts.depth === false) ? +opts.depth : defaults.depth, + ignoreQueryPrefix: opts.ignoreQueryPrefix === true, + interpretNumericEntities: typeof opts.interpretNumericEntities === 'boolean' ? opts.interpretNumericEntities : defaults.interpretNumericEntities, + parameterLimit: typeof opts.parameterLimit === 'number' ? opts.parameterLimit : defaults.parameterLimit, + parseArrays: opts.parseArrays !== false, + plainObjects: typeof opts.plainObjects === 'boolean' ? opts.plainObjects : defaults.plainObjects, + strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling + }; +}; + +module.exports = function (str, opts) { + var options = normalizeParseOptions(opts); + + if (str === '' || str === null || typeof str === 'undefined') { + return options.plainObjects ? Object.create(null) : {}; + } + + var tempObj = typeof str === 'string' ? parseValues(str, options) : str; + var obj = options.plainObjects ? Object.create(null) : {}; + + // Iterate over the keys and setup the new object + + var keys = Object.keys(tempObj); + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + var newObj = parseKeys(key, tempObj[key], options, typeof str === 'string'); + obj = utils.merge(obj, newObj, options); + } + + if (options.allowSparse === true) { + return obj; + } + + return utils.compact(obj); +}; + +},{"./utils":5}],4:[function(require,module,exports){ +'use strict'; + +var getSideChannel = require('side-channel'); +var utils = require('./utils'); +var formats = require('./formats'); +var has = Object.prototype.hasOwnProperty; + +var arrayPrefixGenerators = { + brackets: function brackets(prefix) { + return prefix + '[]'; + }, + comma: 'comma', + indices: function indices(prefix, key) { + return prefix + '[' + key + ']'; + }, + repeat: function repeat(prefix) { + return prefix; + } +}; + +var isArray = Array.isArray; +var split = String.prototype.split; +var push = Array.prototype.push; +var pushToArray = function (arr, valueOrArray) { + push.apply(arr, isArray(valueOrArray) ? valueOrArray : [valueOrArray]); +}; + +var toISO = Date.prototype.toISOString; + +var defaultFormat = formats['default']; +var defaults = { + addQueryPrefix: false, + allowDots: false, + charset: 'utf-8', + charsetSentinel: false, + delimiter: '&', + encode: true, + encoder: utils.encode, + encodeValuesOnly: false, + format: defaultFormat, + formatter: formats.formatters[defaultFormat], + // deprecated + indices: false, + serializeDate: function serializeDate(date) { + return toISO.call(date); + }, + skipNulls: false, + strictNullHandling: false +}; + +var isNonNullishPrimitive = function isNonNullishPrimitive(v) { + return typeof v === 'string' + || typeof v === 'number' + || typeof v === 'boolean' + || typeof v === 'symbol' + || typeof v === 'bigint'; +}; + +var sentinel = {}; + +var stringify = function stringify( + object, + prefix, + generateArrayPrefix, + commaRoundTrip, + strictNullHandling, + skipNulls, + encoder, + filter, + sort, + allowDots, + serializeDate, + format, + formatter, + encodeValuesOnly, + charset, + sideChannel +) { + var obj = object; + + var tmpSc = sideChannel; + var step = 0; + var findFlag = false; + while ((tmpSc = tmpSc.get(sentinel)) !== void undefined && !findFlag) { + // Where object last appeared in the ref tree + var pos = tmpSc.get(object); + step += 1; + if (typeof pos !== 'undefined') { + if (pos === step) { + throw new RangeError('Cyclic object value'); + } else { + findFlag = true; // Break while + } + } + if (typeof tmpSc.get(sentinel) === 'undefined') { + step = 0; + } + } + + if (typeof filter === 'function') { + obj = filter(prefix, obj); + } else if (obj instanceof Date) { + obj = serializeDate(obj); + } else if (generateArrayPrefix === 'comma' && isArray(obj)) { + obj = utils.maybeMap(obj, function (value) { + if (value instanceof Date) { + return serializeDate(value); + } + return value; + }); + } + + if (obj === null) { + if (strictNullHandling) { + return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder, charset, 'key', format) : prefix; + } + + obj = ''; + } + + if (isNonNullishPrimitive(obj) || utils.isBuffer(obj)) { + if (encoder) { + var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset, 'key', format); + if (generateArrayPrefix === 'comma' && encodeValuesOnly) { + var valuesArray = split.call(String(obj), ','); + var valuesJoined = ''; + for (var i = 0; i < valuesArray.length; ++i) { + valuesJoined += (i === 0 ? '' : ',') + formatter(encoder(valuesArray[i], defaults.encoder, charset, 'value', format)); + } + return [formatter(keyValue) + (commaRoundTrip && isArray(obj) && valuesArray.length === 1 ? '[]' : '') + '=' + valuesJoined]; + } + return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults.encoder, charset, 'value', format))]; + } + return [formatter(prefix) + '=' + formatter(String(obj))]; + } + + var values = []; + + if (typeof obj === 'undefined') { + return values; + } + + var objKeys; + if (generateArrayPrefix === 'comma' && isArray(obj)) { + // we need to join elements in + objKeys = [{ value: obj.length > 0 ? obj.join(',') || null : void undefined }]; + } else if (isArray(filter)) { + objKeys = filter; + } else { + var keys = Object.keys(obj); + objKeys = sort ? keys.sort(sort) : keys; + } + + var adjustedPrefix = commaRoundTrip && isArray(obj) && obj.length === 1 ? prefix + '[]' : prefix; + + for (var j = 0; j < objKeys.length; ++j) { + var key = objKeys[j]; + var value = typeof key === 'object' && typeof key.value !== 'undefined' ? key.value : obj[key]; + + if (skipNulls && value === null) { + continue; + } + + var keyPrefix = isArray(obj) + ? typeof generateArrayPrefix === 'function' ? generateArrayPrefix(adjustedPrefix, key) : adjustedPrefix + : adjustedPrefix + (allowDots ? '.' + key : '[' + key + ']'); + + sideChannel.set(object, step); + var valueSideChannel = getSideChannel(); + valueSideChannel.set(sentinel, sideChannel); + pushToArray(values, stringify( + value, + keyPrefix, + generateArrayPrefix, + commaRoundTrip, + strictNullHandling, + skipNulls, + encoder, + filter, + sort, + allowDots, + serializeDate, + format, + formatter, + encodeValuesOnly, + charset, + valueSideChannel + )); + } + + return values; +}; + +var normalizeStringifyOptions = function normalizeStringifyOptions(opts) { + if (!opts) { + return defaults; + } + + if (opts.encoder !== null && typeof opts.encoder !== 'undefined' && typeof opts.encoder !== 'function') { + throw new TypeError('Encoder has to be a function.'); + } + + var charset = opts.charset || defaults.charset; + if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') { + throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined'); + } + + var format = formats['default']; + if (typeof opts.format !== 'undefined') { + if (!has.call(formats.formatters, opts.format)) { + throw new TypeError('Unknown format option provided.'); + } + format = opts.format; + } + var formatter = formats.formatters[format]; + + var filter = defaults.filter; + if (typeof opts.filter === 'function' || isArray(opts.filter)) { + filter = opts.filter; + } + + return { + addQueryPrefix: typeof opts.addQueryPrefix === 'boolean' ? opts.addQueryPrefix : defaults.addQueryPrefix, + allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots, + charset: charset, + charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel, + delimiter: typeof opts.delimiter === 'undefined' ? defaults.delimiter : opts.delimiter, + encode: typeof opts.encode === 'boolean' ? opts.encode : defaults.encode, + encoder: typeof opts.encoder === 'function' ? opts.encoder : defaults.encoder, + encodeValuesOnly: typeof opts.encodeValuesOnly === 'boolean' ? opts.encodeValuesOnly : defaults.encodeValuesOnly, + filter: filter, + format: format, + formatter: formatter, + serializeDate: typeof opts.serializeDate === 'function' ? opts.serializeDate : defaults.serializeDate, + skipNulls: typeof opts.skipNulls === 'boolean' ? opts.skipNulls : defaults.skipNulls, + sort: typeof opts.sort === 'function' ? opts.sort : null, + strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling + }; +}; + +module.exports = function (object, opts) { + var obj = object; + var options = normalizeStringifyOptions(opts); + + var objKeys; + var filter; + + if (typeof options.filter === 'function') { + filter = options.filter; + obj = filter('', obj); + } else if (isArray(options.filter)) { + filter = options.filter; + objKeys = filter; + } + + var keys = []; + + if (typeof obj !== 'object' || obj === null) { + return ''; + } + + var arrayFormat; + if (opts && opts.arrayFormat in arrayPrefixGenerators) { + arrayFormat = opts.arrayFormat; + } else if (opts && 'indices' in opts) { + arrayFormat = opts.indices ? 'indices' : 'repeat'; + } else { + arrayFormat = 'indices'; + } + + var generateArrayPrefix = arrayPrefixGenerators[arrayFormat]; + if (opts && 'commaRoundTrip' in opts && typeof opts.commaRoundTrip !== 'boolean') { + throw new TypeError('`commaRoundTrip` must be a boolean, or absent'); + } + var commaRoundTrip = generateArrayPrefix === 'comma' && opts && opts.commaRoundTrip; + + if (!objKeys) { + objKeys = Object.keys(obj); + } + + if (options.sort) { + objKeys.sort(options.sort); + } + + var sideChannel = getSideChannel(); + for (var i = 0; i < objKeys.length; ++i) { + var key = objKeys[i]; + + if (options.skipNulls && obj[key] === null) { + continue; + } + pushToArray(keys, stringify( + obj[key], + key, + generateArrayPrefix, + commaRoundTrip, + options.strictNullHandling, + options.skipNulls, + options.encode ? options.encoder : null, + options.filter, + options.sort, + options.allowDots, + options.serializeDate, + options.format, + options.formatter, + options.encodeValuesOnly, + options.charset, + sideChannel + )); + } + + var joined = keys.join(options.delimiter); + var prefix = options.addQueryPrefix === true ? '?' : ''; + + if (options.charsetSentinel) { + if (options.charset === 'iso-8859-1') { + // encodeURIComponent('✓'), the "numeric entity" representation of a checkmark + prefix += 'utf8=%26%2310003%3B&'; + } else { + // encodeURIComponent('✓') + prefix += 'utf8=%E2%9C%93&'; + } + } + + return joined.length > 0 ? prefix + joined : ''; +}; + +},{"./formats":1,"./utils":5,"side-channel":16}],5:[function(require,module,exports){ +'use strict'; + +var formats = require('./formats'); + +var has = Object.prototype.hasOwnProperty; +var isArray = Array.isArray; + +var hexTable = (function () { + var array = []; + for (var i = 0; i < 256; ++i) { + array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase()); + } + + return array; +}()); + +var compactQueue = function compactQueue(queue) { + while (queue.length > 1) { + var item = queue.pop(); + var obj = item.obj[item.prop]; + + if (isArray(obj)) { + var compacted = []; + + for (var j = 0; j < obj.length; ++j) { + if (typeof obj[j] !== 'undefined') { + compacted.push(obj[j]); + } + } + + item.obj[item.prop] = compacted; + } + } +}; + +var arrayToObject = function arrayToObject(source, options) { + var obj = options && options.plainObjects ? Object.create(null) : {}; + for (var i = 0; i < source.length; ++i) { + if (typeof source[i] !== 'undefined') { + obj[i] = source[i]; + } + } + + return obj; +}; + +var merge = function merge(target, source, options) { + /* eslint no-param-reassign: 0 */ + if (!source) { + return target; + } + + if (typeof source !== 'object') { + if (isArray(target)) { + target.push(source); + } else if (target && typeof target === 'object') { + if ((options && (options.plainObjects || options.allowPrototypes)) || !has.call(Object.prototype, source)) { + target[source] = true; + } + } else { + return [target, source]; + } + + return target; + } + + if (!target || typeof target !== 'object') { + return [target].concat(source); + } + + var mergeTarget = target; + if (isArray(target) && !isArray(source)) { + mergeTarget = arrayToObject(target, options); + } + + if (isArray(target) && isArray(source)) { + source.forEach(function (item, i) { + if (has.call(target, i)) { + var targetItem = target[i]; + if (targetItem && typeof targetItem === 'object' && item && typeof item === 'object') { + target[i] = merge(targetItem, item, options); + } else { + target.push(item); + } + } else { + target[i] = item; + } + }); + return target; + } + + return Object.keys(source).reduce(function (acc, key) { + var value = source[key]; + + if (has.call(acc, key)) { + acc[key] = merge(acc[key], value, options); + } else { + acc[key] = value; + } + return acc; + }, mergeTarget); +}; + +var assign = function assignSingleSource(target, source) { + return Object.keys(source).reduce(function (acc, key) { + acc[key] = source[key]; + return acc; + }, target); +}; + +var decode = function (str, decoder, charset) { + var strWithoutPlus = str.replace(/\+/g, ' '); + if (charset === 'iso-8859-1') { + // unescape never throws, no try...catch needed: + return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape); + } + // utf-8 + try { + return decodeURIComponent(strWithoutPlus); + } catch (e) { + return strWithoutPlus; + } +}; + +var encode = function encode(str, defaultEncoder, charset, kind, format) { + // This code was originally written by Brian White (mscdex) for the io.js core querystring library. + // It has been adapted here for stricter adherence to RFC 3986 + if (str.length === 0) { + return str; + } + + var string = str; + if (typeof str === 'symbol') { + string = Symbol.prototype.toString.call(str); + } else if (typeof str !== 'string') { + string = String(str); + } + + if (charset === 'iso-8859-1') { + return escape(string).replace(/%u[0-9a-f]{4}/gi, function ($0) { + return '%26%23' + parseInt($0.slice(2), 16) + '%3B'; + }); + } + + var out = ''; + for (var i = 0; i < string.length; ++i) { + var c = string.charCodeAt(i); + + if ( + c === 0x2D // - + || c === 0x2E // . + || c === 0x5F // _ + || c === 0x7E // ~ + || (c >= 0x30 && c <= 0x39) // 0-9 + || (c >= 0x41 && c <= 0x5A) // a-z + || (c >= 0x61 && c <= 0x7A) // A-Z + || (format === formats.RFC1738 && (c === 0x28 || c === 0x29)) // ( ) + ) { + out += string.charAt(i); + continue; + } + + if (c < 0x80) { + out = out + hexTable[c]; + continue; + } + + if (c < 0x800) { + out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]); + continue; + } + + if (c < 0xD800 || c >= 0xE000) { + out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]); + continue; + } + + i += 1; + c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF)); + /* eslint operator-linebreak: [2, "before"] */ + out += hexTable[0xF0 | (c >> 18)] + + hexTable[0x80 | ((c >> 12) & 0x3F)] + + hexTable[0x80 | ((c >> 6) & 0x3F)] + + hexTable[0x80 | (c & 0x3F)]; + } + + return out; +}; + +var compact = function compact(value) { + var queue = [{ obj: { o: value }, prop: 'o' }]; + var refs = []; + + for (var i = 0; i < queue.length; ++i) { + var item = queue[i]; + var obj = item.obj[item.prop]; + + var keys = Object.keys(obj); + for (var j = 0; j < keys.length; ++j) { + var key = keys[j]; + var val = obj[key]; + if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) { + queue.push({ obj: obj, prop: key }); + refs.push(val); + } + } + } + + compactQueue(queue); + + return value; +}; + +var isRegExp = function isRegExp(obj) { + return Object.prototype.toString.call(obj) === '[object RegExp]'; +}; + +var isBuffer = function isBuffer(obj) { + if (!obj || typeof obj !== 'object') { + return false; + } + + return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); +}; + +var combine = function combine(a, b) { + return [].concat(a, b); +}; + +var maybeMap = function maybeMap(val, fn) { + if (isArray(val)) { + var mapped = []; + for (var i = 0; i < val.length; i += 1) { + mapped.push(fn(val[i])); + } + return mapped; + } + return fn(val); +}; + +module.exports = { + arrayToObject: arrayToObject, + assign: assign, + combine: combine, + compact: compact, + decode: decode, + encode: encode, + isBuffer: isBuffer, + isRegExp: isRegExp, + maybeMap: maybeMap, + merge: merge +}; + +},{"./formats":1}],6:[function(require,module,exports){ + +},{}],7:[function(require,module,exports){ +'use strict'; + +var GetIntrinsic = require('get-intrinsic'); + +var callBind = require('./'); + +var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf')); + +module.exports = function callBoundIntrinsic(name, allowMissing) { + var intrinsic = GetIntrinsic(name, !!allowMissing); + if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) { + return callBind(intrinsic); + } + return intrinsic; +}; + +},{"./":8,"get-intrinsic":11}],8:[function(require,module,exports){ +'use strict'; + +var bind = require('function-bind'); +var GetIntrinsic = require('get-intrinsic'); + +var $apply = GetIntrinsic('%Function.prototype.apply%'); +var $call = GetIntrinsic('%Function.prototype.call%'); +var $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply); + +var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%', true); +var $defineProperty = GetIntrinsic('%Object.defineProperty%', true); +var $max = GetIntrinsic('%Math.max%'); + +if ($defineProperty) { + try { + $defineProperty({}, 'a', { value: 1 }); + } catch (e) { + // IE 8 has a broken defineProperty + $defineProperty = null; + } +} + +module.exports = function callBind(originalFunction) { + var func = $reflectApply(bind, $call, arguments); + if ($gOPD && $defineProperty) { + var desc = $gOPD(func, 'length'); + if (desc.configurable) { + // original length, plus the receiver, minus any additional arguments (after the receiver) + $defineProperty( + func, + 'length', + { value: 1 + $max(0, originalFunction.length - (arguments.length - 1)) } + ); + } + } + return func; +}; + +var applyBind = function applyBind() { + return $reflectApply(bind, $apply, arguments); +}; + +if ($defineProperty) { + $defineProperty(module.exports, 'apply', { value: applyBind }); +} else { + module.exports.apply = applyBind; +} + +},{"function-bind":10,"get-intrinsic":11}],9:[function(require,module,exports){ +'use strict'; + +/* eslint no-invalid-this: 1 */ + +var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; +var slice = Array.prototype.slice; +var toStr = Object.prototype.toString; +var funcType = '[object Function]'; + +module.exports = function bind(that) { + var target = this; + if (typeof target !== 'function' || toStr.call(target) !== funcType) { + throw new TypeError(ERROR_MESSAGE + target); + } + var args = slice.call(arguments, 1); + + var bound; + var binder = function () { + if (this instanceof bound) { + var result = target.apply( + this, + args.concat(slice.call(arguments)) + ); + if (Object(result) === result) { + return result; + } + return this; + } else { + return target.apply( + that, + args.concat(slice.call(arguments)) + ); + } + }; + + var boundLength = Math.max(0, target.length - args.length); + var boundArgs = []; + for (var i = 0; i < boundLength; i++) { + boundArgs.push('$' + i); + } + + bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder); + + if (target.prototype) { + var Empty = function Empty() {}; + Empty.prototype = target.prototype; + bound.prototype = new Empty(); + Empty.prototype = null; + } + + return bound; +}; + +},{}],10:[function(require,module,exports){ +'use strict'; + +var implementation = require('./implementation'); + +module.exports = Function.prototype.bind || implementation; + +},{"./implementation":9}],11:[function(require,module,exports){ +'use strict'; + +var undefined; + +var $SyntaxError = SyntaxError; +var $Function = Function; +var $TypeError = TypeError; + +// eslint-disable-next-line consistent-return +var getEvalledConstructor = function (expressionSyntax) { + try { + return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')(); + } catch (e) {} +}; + +var $gOPD = Object.getOwnPropertyDescriptor; +if ($gOPD) { + try { + $gOPD({}, ''); + } catch (e) { + $gOPD = null; // this is IE 8, which has a broken gOPD + } +} + +var throwTypeError = function () { + throw new $TypeError(); +}; +var ThrowTypeError = $gOPD + ? (function () { + try { + // eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties + arguments.callee; // IE 8 does not throw here + return throwTypeError; + } catch (calleeThrows) { + try { + // IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '') + return $gOPD(arguments, 'callee').get; + } catch (gOPDthrows) { + return throwTypeError; + } + } + }()) + : throwTypeError; + +var hasSymbols = require('has-symbols')(); + +var getProto = Object.getPrototypeOf || function (x) { return x.__proto__; }; // eslint-disable-line no-proto + +var needsEval = {}; + +var TypedArray = typeof Uint8Array === 'undefined' ? undefined : getProto(Uint8Array); + +var INTRINSICS = { + '%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError, + '%Array%': Array, + '%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer, + '%ArrayIteratorPrototype%': hasSymbols ? getProto([][Symbol.iterator]()) : undefined, + '%AsyncFromSyncIteratorPrototype%': undefined, + '%AsyncFunction%': needsEval, + '%AsyncGenerator%': needsEval, + '%AsyncGeneratorFunction%': needsEval, + '%AsyncIteratorPrototype%': needsEval, + '%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics, + '%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt, + '%Boolean%': Boolean, + '%DataView%': typeof DataView === 'undefined' ? undefined : DataView, + '%Date%': Date, + '%decodeURI%': decodeURI, + '%decodeURIComponent%': decodeURIComponent, + '%encodeURI%': encodeURI, + '%encodeURIComponent%': encodeURIComponent, + '%Error%': Error, + '%eval%': eval, // eslint-disable-line no-eval + '%EvalError%': EvalError, + '%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array, + '%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array, + '%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry, + '%Function%': $Function, + '%GeneratorFunction%': needsEval, + '%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array, + '%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array, + '%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array, + '%isFinite%': isFinite, + '%isNaN%': isNaN, + '%IteratorPrototype%': hasSymbols ? getProto(getProto([][Symbol.iterator]())) : undefined, + '%JSON%': typeof JSON === 'object' ? JSON : undefined, + '%Map%': typeof Map === 'undefined' ? undefined : Map, + '%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols ? undefined : getProto(new Map()[Symbol.iterator]()), + '%Math%': Math, + '%Number%': Number, + '%Object%': Object, + '%parseFloat%': parseFloat, + '%parseInt%': parseInt, + '%Promise%': typeof Promise === 'undefined' ? undefined : Promise, + '%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy, + '%RangeError%': RangeError, + '%ReferenceError%': ReferenceError, + '%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect, + '%RegExp%': RegExp, + '%Set%': typeof Set === 'undefined' ? undefined : Set, + '%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols ? undefined : getProto(new Set()[Symbol.iterator]()), + '%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer, + '%String%': String, + '%StringIteratorPrototype%': hasSymbols ? getProto(''[Symbol.iterator]()) : undefined, + '%Symbol%': hasSymbols ? Symbol : undefined, + '%SyntaxError%': $SyntaxError, + '%ThrowTypeError%': ThrowTypeError, + '%TypedArray%': TypedArray, + '%TypeError%': $TypeError, + '%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array, + '%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray, + '%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array, + '%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array, + '%URIError%': URIError, + '%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap, + '%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef, + '%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet +}; + +var doEval = function doEval(name) { + var value; + if (name === '%AsyncFunction%') { + value = getEvalledConstructor('async function () {}'); + } else if (name === '%GeneratorFunction%') { + value = getEvalledConstructor('function* () {}'); + } else if (name === '%AsyncGeneratorFunction%') { + value = getEvalledConstructor('async function* () {}'); + } else if (name === '%AsyncGenerator%') { + var fn = doEval('%AsyncGeneratorFunction%'); + if (fn) { + value = fn.prototype; + } + } else if (name === '%AsyncIteratorPrototype%') { + var gen = doEval('%AsyncGenerator%'); + if (gen) { + value = getProto(gen.prototype); + } + } + + INTRINSICS[name] = value; + + return value; +}; + +var LEGACY_ALIASES = { + '%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'], + '%ArrayPrototype%': ['Array', 'prototype'], + '%ArrayProto_entries%': ['Array', 'prototype', 'entries'], + '%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'], + '%ArrayProto_keys%': ['Array', 'prototype', 'keys'], + '%ArrayProto_values%': ['Array', 'prototype', 'values'], + '%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'], + '%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'], + '%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'], + '%BooleanPrototype%': ['Boolean', 'prototype'], + '%DataViewPrototype%': ['DataView', 'prototype'], + '%DatePrototype%': ['Date', 'prototype'], + '%ErrorPrototype%': ['Error', 'prototype'], + '%EvalErrorPrototype%': ['EvalError', 'prototype'], + '%Float32ArrayPrototype%': ['Float32Array', 'prototype'], + '%Float64ArrayPrototype%': ['Float64Array', 'prototype'], + '%FunctionPrototype%': ['Function', 'prototype'], + '%Generator%': ['GeneratorFunction', 'prototype'], + '%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'], + '%Int8ArrayPrototype%': ['Int8Array', 'prototype'], + '%Int16ArrayPrototype%': ['Int16Array', 'prototype'], + '%Int32ArrayPrototype%': ['Int32Array', 'prototype'], + '%JSONParse%': ['JSON', 'parse'], + '%JSONStringify%': ['JSON', 'stringify'], + '%MapPrototype%': ['Map', 'prototype'], + '%NumberPrototype%': ['Number', 'prototype'], + '%ObjectPrototype%': ['Object', 'prototype'], + '%ObjProto_toString%': ['Object', 'prototype', 'toString'], + '%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'], + '%PromisePrototype%': ['Promise', 'prototype'], + '%PromiseProto_then%': ['Promise', 'prototype', 'then'], + '%Promise_all%': ['Promise', 'all'], + '%Promise_reject%': ['Promise', 'reject'], + '%Promise_resolve%': ['Promise', 'resolve'], + '%RangeErrorPrototype%': ['RangeError', 'prototype'], + '%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'], + '%RegExpPrototype%': ['RegExp', 'prototype'], + '%SetPrototype%': ['Set', 'prototype'], + '%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'], + '%StringPrototype%': ['String', 'prototype'], + '%SymbolPrototype%': ['Symbol', 'prototype'], + '%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'], + '%TypedArrayPrototype%': ['TypedArray', 'prototype'], + '%TypeErrorPrototype%': ['TypeError', 'prototype'], + '%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'], + '%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'], + '%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'], + '%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'], + '%URIErrorPrototype%': ['URIError', 'prototype'], + '%WeakMapPrototype%': ['WeakMap', 'prototype'], + '%WeakSetPrototype%': ['WeakSet', 'prototype'] +}; + +var bind = require('function-bind'); +var hasOwn = require('has'); +var $concat = bind.call(Function.call, Array.prototype.concat); +var $spliceApply = bind.call(Function.apply, Array.prototype.splice); +var $replace = bind.call(Function.call, String.prototype.replace); +var $strSlice = bind.call(Function.call, String.prototype.slice); + +/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */ +var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; +var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */ +var stringToPath = function stringToPath(string) { + var first = $strSlice(string, 0, 1); + var last = $strSlice(string, -1); + if (first === '%' && last !== '%') { + throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`'); + } else if (last === '%' && first !== '%') { + throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`'); + } + var result = []; + $replace(string, rePropName, function (match, number, quote, subString) { + result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match; + }); + return result; +}; +/* end adaptation */ + +var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) { + var intrinsicName = name; + var alias; + if (hasOwn(LEGACY_ALIASES, intrinsicName)) { + alias = LEGACY_ALIASES[intrinsicName]; + intrinsicName = '%' + alias[0] + '%'; + } + + if (hasOwn(INTRINSICS, intrinsicName)) { + var value = INTRINSICS[intrinsicName]; + if (value === needsEval) { + value = doEval(intrinsicName); + } + if (typeof value === 'undefined' && !allowMissing) { + throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!'); + } + + return { + alias: alias, + name: intrinsicName, + value: value + }; + } + + throw new $SyntaxError('intrinsic ' + name + ' does not exist!'); +}; + +module.exports = function GetIntrinsic(name, allowMissing) { + if (typeof name !== 'string' || name.length === 0) { + throw new $TypeError('intrinsic name must be a non-empty string'); + } + if (arguments.length > 1 && typeof allowMissing !== 'boolean') { + throw new $TypeError('"allowMissing" argument must be a boolean'); + } + + var parts = stringToPath(name); + var intrinsicBaseName = parts.length > 0 ? parts[0] : ''; + + var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing); + var intrinsicRealName = intrinsic.name; + var value = intrinsic.value; + var skipFurtherCaching = false; + + var alias = intrinsic.alias; + if (alias) { + intrinsicBaseName = alias[0]; + $spliceApply(parts, $concat([0, 1], alias)); + } + + for (var i = 1, isOwn = true; i < parts.length; i += 1) { + var part = parts[i]; + var first = $strSlice(part, 0, 1); + var last = $strSlice(part, -1); + if ( + ( + (first === '"' || first === "'" || first === '`') + || (last === '"' || last === "'" || last === '`') + ) + && first !== last + ) { + throw new $SyntaxError('property names with quotes must have matching quotes'); + } + if (part === 'constructor' || !isOwn) { + skipFurtherCaching = true; + } + + intrinsicBaseName += '.' + part; + intrinsicRealName = '%' + intrinsicBaseName + '%'; + + if (hasOwn(INTRINSICS, intrinsicRealName)) { + value = INTRINSICS[intrinsicRealName]; + } else if (value != null) { + if (!(part in value)) { + if (!allowMissing) { + throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.'); + } + return void undefined; + } + if ($gOPD && (i + 1) >= parts.length) { + var desc = $gOPD(value, part); + isOwn = !!desc; + + // By convention, when a data property is converted to an accessor + // property to emulate a data property that does not suffer from + // the override mistake, that accessor's getter is marked with + // an `originalValue` property. Here, when we detect this, we + // uphold the illusion by pretending to see that original data + // property, i.e., returning the value rather than the getter + // itself. + if (isOwn && 'get' in desc && !('originalValue' in desc.get)) { + value = desc.get; + } else { + value = value[part]; + } + } else { + isOwn = hasOwn(value, part); + value = value[part]; + } + + if (isOwn && !skipFurtherCaching) { + INTRINSICS[intrinsicRealName] = value; + } + } + } + return value; +}; + +},{"function-bind":10,"has":14,"has-symbols":12}],12:[function(require,module,exports){ +'use strict'; + +var origSymbol = typeof Symbol !== 'undefined' && Symbol; +var hasSymbolSham = require('./shams'); + +module.exports = function hasNativeSymbols() { + if (typeof origSymbol !== 'function') { return false; } + if (typeof Symbol !== 'function') { return false; } + if (typeof origSymbol('foo') !== 'symbol') { return false; } + if (typeof Symbol('bar') !== 'symbol') { return false; } + + return hasSymbolSham(); +}; + +},{"./shams":13}],13:[function(require,module,exports){ +'use strict'; + +/* eslint complexity: [2, 18], max-statements: [2, 33] */ +module.exports = function hasSymbols() { + if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; } + if (typeof Symbol.iterator === 'symbol') { return true; } + + var obj = {}; + var sym = Symbol('test'); + var symObj = Object(sym); + if (typeof sym === 'string') { return false; } + + if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; } + if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; } + + // temp disabled per https://github.com/ljharb/object.assign/issues/17 + // if (sym instanceof Symbol) { return false; } + // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4 + // if (!(symObj instanceof Symbol)) { return false; } + + // if (typeof Symbol.prototype.toString !== 'function') { return false; } + // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; } + + var symVal = 42; + obj[sym] = symVal; + for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop + if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; } + + if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; } + + var syms = Object.getOwnPropertySymbols(obj); + if (syms.length !== 1 || syms[0] !== sym) { return false; } + + if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; } + + if (typeof Object.getOwnPropertyDescriptor === 'function') { + var descriptor = Object.getOwnPropertyDescriptor(obj, sym); + if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; } + } + + return true; +}; + +},{}],14:[function(require,module,exports){ +'use strict'; + +var bind = require('function-bind'); + +module.exports = bind.call(Function.call, Object.prototype.hasOwnProperty); + +},{"function-bind":10}],15:[function(require,module,exports){ +var hasMap = typeof Map === 'function' && Map.prototype; +var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, 'size') : null; +var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === 'function' ? mapSizeDescriptor.get : null; +var mapForEach = hasMap && Map.prototype.forEach; +var hasSet = typeof Set === 'function' && Set.prototype; +var setSizeDescriptor = Object.getOwnPropertyDescriptor && hasSet ? Object.getOwnPropertyDescriptor(Set.prototype, 'size') : null; +var setSize = hasSet && setSizeDescriptor && typeof setSizeDescriptor.get === 'function' ? setSizeDescriptor.get : null; +var setForEach = hasSet && Set.prototype.forEach; +var hasWeakMap = typeof WeakMap === 'function' && WeakMap.prototype; +var weakMapHas = hasWeakMap ? WeakMap.prototype.has : null; +var hasWeakSet = typeof WeakSet === 'function' && WeakSet.prototype; +var weakSetHas = hasWeakSet ? WeakSet.prototype.has : null; +var hasWeakRef = typeof WeakRef === 'function' && WeakRef.prototype; +var weakRefDeref = hasWeakRef ? WeakRef.prototype.deref : null; +var booleanValueOf = Boolean.prototype.valueOf; +var objectToString = Object.prototype.toString; +var functionToString = Function.prototype.toString; +var $match = String.prototype.match; +var $slice = String.prototype.slice; +var $replace = String.prototype.replace; +var $toUpperCase = String.prototype.toUpperCase; +var $toLowerCase = String.prototype.toLowerCase; +var $test = RegExp.prototype.test; +var $concat = Array.prototype.concat; +var $join = Array.prototype.join; +var $arrSlice = Array.prototype.slice; +var $floor = Math.floor; +var bigIntValueOf = typeof BigInt === 'function' ? BigInt.prototype.valueOf : null; +var gOPS = Object.getOwnPropertySymbols; +var symToString = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? Symbol.prototype.toString : null; +var hasShammedSymbols = typeof Symbol === 'function' && typeof Symbol.iterator === 'object'; +// ie, `has-tostringtag/shams +var toStringTag = typeof Symbol === 'function' && Symbol.toStringTag && (typeof Symbol.toStringTag === hasShammedSymbols ? 'object' : 'symbol') + ? Symbol.toStringTag + : null; +var isEnumerable = Object.prototype.propertyIsEnumerable; + +var gPO = (typeof Reflect === 'function' ? Reflect.getPrototypeOf : Object.getPrototypeOf) || ( + [].__proto__ === Array.prototype // eslint-disable-line no-proto + ? function (O) { + return O.__proto__; // eslint-disable-line no-proto + } + : null +); + +function addNumericSeparator(num, str) { + if ( + num === Infinity + || num === -Infinity + || num !== num + || (num && num > -1000 && num < 1000) + || $test.call(/e/, str) + ) { + return str; + } + var sepRegex = /[0-9](?=(?:[0-9]{3})+(?![0-9]))/g; + if (typeof num === 'number') { + var int = num < 0 ? -$floor(-num) : $floor(num); // trunc(num) + if (int !== num) { + var intStr = String(int); + var dec = $slice.call(str, intStr.length + 1); + return $replace.call(intStr, sepRegex, '$&_') + '.' + $replace.call($replace.call(dec, /([0-9]{3})/g, '$&_'), /_$/, ''); + } + } + return $replace.call(str, sepRegex, '$&_'); +} + +var utilInspect = require('./util.inspect'); +var inspectCustom = utilInspect.custom; +var inspectSymbol = isSymbol(inspectCustom) ? inspectCustom : null; + +module.exports = function inspect_(obj, options, depth, seen) { + var opts = options || {}; + + if (has(opts, 'quoteStyle') && (opts.quoteStyle !== 'single' && opts.quoteStyle !== 'double')) { + throw new TypeError('option "quoteStyle" must be "single" or "double"'); + } + if ( + has(opts, 'maxStringLength') && (typeof opts.maxStringLength === 'number' + ? opts.maxStringLength < 0 && opts.maxStringLength !== Infinity + : opts.maxStringLength !== null + ) + ) { + throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`'); + } + var customInspect = has(opts, 'customInspect') ? opts.customInspect : true; + if (typeof customInspect !== 'boolean' && customInspect !== 'symbol') { + throw new TypeError('option "customInspect", if provided, must be `true`, `false`, or `\'symbol\'`'); + } + + if ( + has(opts, 'indent') + && opts.indent !== null + && opts.indent !== '\t' + && !(parseInt(opts.indent, 10) === opts.indent && opts.indent > 0) + ) { + throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`'); + } + if (has(opts, 'numericSeparator') && typeof opts.numericSeparator !== 'boolean') { + throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`'); + } + var numericSeparator = opts.numericSeparator; + + if (typeof obj === 'undefined') { + return 'undefined'; + } + if (obj === null) { + return 'null'; + } + if (typeof obj === 'boolean') { + return obj ? 'true' : 'false'; + } + + if (typeof obj === 'string') { + return inspectString(obj, opts); + } + if (typeof obj === 'number') { + if (obj === 0) { + return Infinity / obj > 0 ? '0' : '-0'; + } + var str = String(obj); + return numericSeparator ? addNumericSeparator(obj, str) : str; + } + if (typeof obj === 'bigint') { + var bigIntStr = String(obj) + 'n'; + return numericSeparator ? addNumericSeparator(obj, bigIntStr) : bigIntStr; + } + + var maxDepth = typeof opts.depth === 'undefined' ? 5 : opts.depth; + if (typeof depth === 'undefined') { depth = 0; } + if (depth >= maxDepth && maxDepth > 0 && typeof obj === 'object') { + return isArray(obj) ? '[Array]' : '[Object]'; + } + + var indent = getIndent(opts, depth); + + if (typeof seen === 'undefined') { + seen = []; + } else if (indexOf(seen, obj) >= 0) { + return '[Circular]'; + } + + function inspect(value, from, noIndent) { + if (from) { + seen = $arrSlice.call(seen); + seen.push(from); + } + if (noIndent) { + var newOpts = { + depth: opts.depth + }; + if (has(opts, 'quoteStyle')) { + newOpts.quoteStyle = opts.quoteStyle; + } + return inspect_(value, newOpts, depth + 1, seen); + } + return inspect_(value, opts, depth + 1, seen); + } + + if (typeof obj === 'function' && !isRegExp(obj)) { // in older engines, regexes are callable + var name = nameOf(obj); + var keys = arrObjKeys(obj, inspect); + return '[Function' + (name ? ': ' + name : ' (anonymous)') + ']' + (keys.length > 0 ? ' { ' + $join.call(keys, ', ') + ' }' : ''); + } + if (isSymbol(obj)) { + var symString = hasShammedSymbols ? $replace.call(String(obj), /^(Symbol\(.*\))_[^)]*$/, '$1') : symToString.call(obj); + return typeof obj === 'object' && !hasShammedSymbols ? markBoxed(symString) : symString; + } + if (isElement(obj)) { + var s = '<' + $toLowerCase.call(String(obj.nodeName)); + var attrs = obj.attributes || []; + for (var i = 0; i < attrs.length; i++) { + s += ' ' + attrs[i].name + '=' + wrapQuotes(quote(attrs[i].value), 'double', opts); + } + s += '>'; + if (obj.childNodes && obj.childNodes.length) { s += '...'; } + s += ''; + return s; + } + if (isArray(obj)) { + if (obj.length === 0) { return '[]'; } + var xs = arrObjKeys(obj, inspect); + if (indent && !singleLineValues(xs)) { + return '[' + indentedJoin(xs, indent) + ']'; + } + return '[ ' + $join.call(xs, ', ') + ' ]'; + } + if (isError(obj)) { + var parts = arrObjKeys(obj, inspect); + if (!('cause' in Error.prototype) && 'cause' in obj && !isEnumerable.call(obj, 'cause')) { + return '{ [' + String(obj) + '] ' + $join.call($concat.call('[cause]: ' + inspect(obj.cause), parts), ', ') + ' }'; + } + if (parts.length === 0) { return '[' + String(obj) + ']'; } + return '{ [' + String(obj) + '] ' + $join.call(parts, ', ') + ' }'; + } + if (typeof obj === 'object' && customInspect) { + if (inspectSymbol && typeof obj[inspectSymbol] === 'function' && utilInspect) { + return utilInspect(obj, { depth: maxDepth - depth }); + } else if (customInspect !== 'symbol' && typeof obj.inspect === 'function') { + return obj.inspect(); + } + } + if (isMap(obj)) { + var mapParts = []; + mapForEach.call(obj, function (value, key) { + mapParts.push(inspect(key, obj, true) + ' => ' + inspect(value, obj)); + }); + return collectionOf('Map', mapSize.call(obj), mapParts, indent); + } + if (isSet(obj)) { + var setParts = []; + setForEach.call(obj, function (value) { + setParts.push(inspect(value, obj)); + }); + return collectionOf('Set', setSize.call(obj), setParts, indent); + } + if (isWeakMap(obj)) { + return weakCollectionOf('WeakMap'); + } + if (isWeakSet(obj)) { + return weakCollectionOf('WeakSet'); + } + if (isWeakRef(obj)) { + return weakCollectionOf('WeakRef'); + } + if (isNumber(obj)) { + return markBoxed(inspect(Number(obj))); + } + if (isBigInt(obj)) { + return markBoxed(inspect(bigIntValueOf.call(obj))); + } + if (isBoolean(obj)) { + return markBoxed(booleanValueOf.call(obj)); + } + if (isString(obj)) { + return markBoxed(inspect(String(obj))); + } + if (!isDate(obj) && !isRegExp(obj)) { + var ys = arrObjKeys(obj, inspect); + var isPlainObject = gPO ? gPO(obj) === Object.prototype : obj instanceof Object || obj.constructor === Object; + var protoTag = obj instanceof Object ? '' : 'null prototype'; + var stringTag = !isPlainObject && toStringTag && Object(obj) === obj && toStringTag in obj ? $slice.call(toStr(obj), 8, -1) : protoTag ? 'Object' : ''; + var constructorTag = isPlainObject || typeof obj.constructor !== 'function' ? '' : obj.constructor.name ? obj.constructor.name + ' ' : ''; + var tag = constructorTag + (stringTag || protoTag ? '[' + $join.call($concat.call([], stringTag || [], protoTag || []), ': ') + '] ' : ''); + if (ys.length === 0) { return tag + '{}'; } + if (indent) { + return tag + '{' + indentedJoin(ys, indent) + '}'; + } + return tag + '{ ' + $join.call(ys, ', ') + ' }'; + } + return String(obj); +}; + +function wrapQuotes(s, defaultStyle, opts) { + var quoteChar = (opts.quoteStyle || defaultStyle) === 'double' ? '"' : "'"; + return quoteChar + s + quoteChar; +} + +function quote(s) { + return $replace.call(String(s), /"/g, '"'); +} + +function isArray(obj) { return toStr(obj) === '[object Array]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } +function isDate(obj) { return toStr(obj) === '[object Date]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } +function isRegExp(obj) { return toStr(obj) === '[object RegExp]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } +function isError(obj) { return toStr(obj) === '[object Error]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } +function isString(obj) { return toStr(obj) === '[object String]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } +function isNumber(obj) { return toStr(obj) === '[object Number]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } +function isBoolean(obj) { return toStr(obj) === '[object Boolean]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } + +// Symbol and BigInt do have Symbol.toStringTag by spec, so that can't be used to eliminate false positives +function isSymbol(obj) { + if (hasShammedSymbols) { + return obj && typeof obj === 'object' && obj instanceof Symbol; + } + if (typeof obj === 'symbol') { + return true; + } + if (!obj || typeof obj !== 'object' || !symToString) { + return false; + } + try { + symToString.call(obj); + return true; + } catch (e) {} + return false; +} + +function isBigInt(obj) { + if (!obj || typeof obj !== 'object' || !bigIntValueOf) { + return false; + } + try { + bigIntValueOf.call(obj); + return true; + } catch (e) {} + return false; +} + +var hasOwn = Object.prototype.hasOwnProperty || function (key) { return key in this; }; +function has(obj, key) { + return hasOwn.call(obj, key); +} + +function toStr(obj) { + return objectToString.call(obj); +} + +function nameOf(f) { + if (f.name) { return f.name; } + var m = $match.call(functionToString.call(f), /^function\s*([\w$]+)/); + if (m) { return m[1]; } + return null; +} + +function indexOf(xs, x) { + if (xs.indexOf) { return xs.indexOf(x); } + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) { return i; } + } + return -1; +} + +function isMap(x) { + if (!mapSize || !x || typeof x !== 'object') { + return false; + } + try { + mapSize.call(x); + try { + setSize.call(x); + } catch (s) { + return true; + } + return x instanceof Map; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; +} + +function isWeakMap(x) { + if (!weakMapHas || !x || typeof x !== 'object') { + return false; + } + try { + weakMapHas.call(x, weakMapHas); + try { + weakSetHas.call(x, weakSetHas); + } catch (s) { + return true; + } + return x instanceof WeakMap; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; +} + +function isWeakRef(x) { + if (!weakRefDeref || !x || typeof x !== 'object') { + return false; + } + try { + weakRefDeref.call(x); + return true; + } catch (e) {} + return false; +} + +function isSet(x) { + if (!setSize || !x || typeof x !== 'object') { + return false; + } + try { + setSize.call(x); + try { + mapSize.call(x); + } catch (m) { + return true; + } + return x instanceof Set; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; +} + +function isWeakSet(x) { + if (!weakSetHas || !x || typeof x !== 'object') { + return false; + } + try { + weakSetHas.call(x, weakSetHas); + try { + weakMapHas.call(x, weakMapHas); + } catch (s) { + return true; + } + return x instanceof WeakSet; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; +} + +function isElement(x) { + if (!x || typeof x !== 'object') { return false; } + if (typeof HTMLElement !== 'undefined' && x instanceof HTMLElement) { + return true; + } + return typeof x.nodeName === 'string' && typeof x.getAttribute === 'function'; +} + +function inspectString(str, opts) { + if (str.length > opts.maxStringLength) { + var remaining = str.length - opts.maxStringLength; + var trailer = '... ' + remaining + ' more character' + (remaining > 1 ? 's' : ''); + return inspectString($slice.call(str, 0, opts.maxStringLength), opts) + trailer; + } + // eslint-disable-next-line no-control-regex + var s = $replace.call($replace.call(str, /(['\\])/g, '\\$1'), /[\x00-\x1f]/g, lowbyte); + return wrapQuotes(s, 'single', opts); +} + +function lowbyte(c) { + var n = c.charCodeAt(0); + var x = { + 8: 'b', + 9: 't', + 10: 'n', + 12: 'f', + 13: 'r' + }[n]; + if (x) { return '\\' + x; } + return '\\x' + (n < 0x10 ? '0' : '') + $toUpperCase.call(n.toString(16)); +} + +function markBoxed(str) { + return 'Object(' + str + ')'; +} + +function weakCollectionOf(type) { + return type + ' { ? }'; +} + +function collectionOf(type, size, entries, indent) { + var joinedEntries = indent ? indentedJoin(entries, indent) : $join.call(entries, ', '); + return type + ' (' + size + ') {' + joinedEntries + '}'; +} + +function singleLineValues(xs) { + for (var i = 0; i < xs.length; i++) { + if (indexOf(xs[i], '\n') >= 0) { + return false; + } + } + return true; +} + +function getIndent(opts, depth) { + var baseIndent; + if (opts.indent === '\t') { + baseIndent = '\t'; + } else if (typeof opts.indent === 'number' && opts.indent > 0) { + baseIndent = $join.call(Array(opts.indent + 1), ' '); + } else { + return null; + } + return { + base: baseIndent, + prev: $join.call(Array(depth + 1), baseIndent) + }; +} + +function indentedJoin(xs, indent) { + if (xs.length === 0) { return ''; } + var lineJoiner = '\n' + indent.prev + indent.base; + return lineJoiner + $join.call(xs, ',' + lineJoiner) + '\n' + indent.prev; +} + +function arrObjKeys(obj, inspect) { + var isArr = isArray(obj); + var xs = []; + if (isArr) { + xs.length = obj.length; + for (var i = 0; i < obj.length; i++) { + xs[i] = has(obj, i) ? inspect(obj[i], obj) : ''; + } + } + var syms = typeof gOPS === 'function' ? gOPS(obj) : []; + var symMap; + if (hasShammedSymbols) { + symMap = {}; + for (var k = 0; k < syms.length; k++) { + symMap['$' + syms[k]] = syms[k]; + } + } + + for (var key in obj) { // eslint-disable-line no-restricted-syntax + if (!has(obj, key)) { continue; } // eslint-disable-line no-restricted-syntax, no-continue + if (isArr && String(Number(key)) === key && key < obj.length) { continue; } // eslint-disable-line no-restricted-syntax, no-continue + if (hasShammedSymbols && symMap['$' + key] instanceof Symbol) { + // this is to prevent shammed Symbols, which are stored as strings, from being included in the string key section + continue; // eslint-disable-line no-restricted-syntax, no-continue + } else if ($test.call(/[^\w$]/, key)) { + xs.push(inspect(key, obj) + ': ' + inspect(obj[key], obj)); + } else { + xs.push(key + ': ' + inspect(obj[key], obj)); + } + } + if (typeof gOPS === 'function') { + for (var j = 0; j < syms.length; j++) { + if (isEnumerable.call(obj, syms[j])) { + xs.push('[' + inspect(syms[j]) + ']: ' + inspect(obj[syms[j]], obj)); + } + } + } + return xs; +} + +},{"./util.inspect":6}],16:[function(require,module,exports){ +'use strict'; + +var GetIntrinsic = require('get-intrinsic'); +var callBound = require('call-bind/callBound'); +var inspect = require('object-inspect'); + +var $TypeError = GetIntrinsic('%TypeError%'); +var $WeakMap = GetIntrinsic('%WeakMap%', true); +var $Map = GetIntrinsic('%Map%', true); + +var $weakMapGet = callBound('WeakMap.prototype.get', true); +var $weakMapSet = callBound('WeakMap.prototype.set', true); +var $weakMapHas = callBound('WeakMap.prototype.has', true); +var $mapGet = callBound('Map.prototype.get', true); +var $mapSet = callBound('Map.prototype.set', true); +var $mapHas = callBound('Map.prototype.has', true); + +/* + * This function traverses the list returning the node corresponding to the + * given key. + * + * That node is also moved to the head of the list, so that if it's accessed + * again we don't need to traverse the whole list. By doing so, all the recently + * used nodes can be accessed relatively quickly. + */ +var listGetNode = function (list, key) { // eslint-disable-line consistent-return + for (var prev = list, curr; (curr = prev.next) !== null; prev = curr) { + if (curr.key === key) { + prev.next = curr.next; + curr.next = list.next; + list.next = curr; // eslint-disable-line no-param-reassign + return curr; + } + } +}; + +var listGet = function (objects, key) { + var node = listGetNode(objects, key); + return node && node.value; +}; +var listSet = function (objects, key, value) { + var node = listGetNode(objects, key); + if (node) { + node.value = value; + } else { + // Prepend the new node to the beginning of the list + objects.next = { // eslint-disable-line no-param-reassign + key: key, + next: objects.next, + value: value + }; + } +}; +var listHas = function (objects, key) { + return !!listGetNode(objects, key); +}; + +module.exports = function getSideChannel() { + var $wm; + var $m; + var $o; + var channel = { + assert: function (key) { + if (!channel.has(key)) { + throw new $TypeError('Side channel does not contain ' + inspect(key)); + } + }, + get: function (key) { // eslint-disable-line consistent-return + if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { + if ($wm) { + return $weakMapGet($wm, key); + } + } else if ($Map) { + if ($m) { + return $mapGet($m, key); + } + } else { + if ($o) { // eslint-disable-line no-lonely-if + return listGet($o, key); + } + } + }, + has: function (key) { + if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { + if ($wm) { + return $weakMapHas($wm, key); + } + } else if ($Map) { + if ($m) { + return $mapHas($m, key); + } + } else { + if ($o) { // eslint-disable-line no-lonely-if + return listHas($o, key); + } + } + return false; + }, + set: function (key, value) { + if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { + if (!$wm) { + $wm = new $WeakMap(); + } + $weakMapSet($wm, key, value); + } else if ($Map) { + if (!$m) { + $m = new $Map(); + } + $mapSet($m, key, value); + } else { + if (!$o) { + /* + * Initialize the linked list as an empty node, so that we don't have + * to special-case handling of the first node: we can always refer to + * it as (previous node).next, instead of something like (list).head + */ + $o = { key: {}, next: null }; + } + listSet($o, key, value); + } + } + }; + return channel; +}; + +},{"call-bind/callBound":7,"get-intrinsic":11,"object-inspect":15}]},{},[2])(2) +}); diff --git a/backend/node_modules/qs/lib/formats.js b/backend/node_modules/qs/lib/formats.js new file mode 100644 index 0000000000000000000000000000000000000000..f36cf206b90ff764e9709be64d57f6da60b6307e --- /dev/null +++ b/backend/node_modules/qs/lib/formats.js @@ -0,0 +1,23 @@ +'use strict'; + +var replace = String.prototype.replace; +var percentTwenties = /%20/g; + +var Format = { + RFC1738: 'RFC1738', + RFC3986: 'RFC3986' +}; + +module.exports = { + 'default': Format.RFC3986, + formatters: { + RFC1738: function (value) { + return replace.call(value, percentTwenties, '+'); + }, + RFC3986: function (value) { + return String(value); + } + }, + RFC1738: Format.RFC1738, + RFC3986: Format.RFC3986 +}; diff --git a/backend/node_modules/qs/lib/index.js b/backend/node_modules/qs/lib/index.js new file mode 100644 index 0000000000000000000000000000000000000000..0d6a97dcf096449e7100cb63bb05f232a7f790a5 --- /dev/null +++ b/backend/node_modules/qs/lib/index.js @@ -0,0 +1,11 @@ +'use strict'; + +var stringify = require('./stringify'); +var parse = require('./parse'); +var formats = require('./formats'); + +module.exports = { + formats: formats, + parse: parse, + stringify: stringify +}; diff --git a/backend/node_modules/qs/lib/parse.js b/backend/node_modules/qs/lib/parse.js new file mode 100644 index 0000000000000000000000000000000000000000..a4ac4fa07e8a59cb712bdc62ac2ba985afd9eca8 --- /dev/null +++ b/backend/node_modules/qs/lib/parse.js @@ -0,0 +1,263 @@ +'use strict'; + +var utils = require('./utils'); + +var has = Object.prototype.hasOwnProperty; +var isArray = Array.isArray; + +var defaults = { + allowDots: false, + allowPrototypes: false, + allowSparse: false, + arrayLimit: 20, + charset: 'utf-8', + charsetSentinel: false, + comma: false, + decoder: utils.decode, + delimiter: '&', + depth: 5, + ignoreQueryPrefix: false, + interpretNumericEntities: false, + parameterLimit: 1000, + parseArrays: true, + plainObjects: false, + strictNullHandling: false +}; + +var interpretNumericEntities = function (str) { + return str.replace(/&#(\d+);/g, function ($0, numberStr) { + return String.fromCharCode(parseInt(numberStr, 10)); + }); +}; + +var parseArrayValue = function (val, options) { + if (val && typeof val === 'string' && options.comma && val.indexOf(',') > -1) { + return val.split(','); + } + + return val; +}; + +// This is what browsers will submit when the ✓ character occurs in an +// application/x-www-form-urlencoded body and the encoding of the page containing +// the form is iso-8859-1, or when the submitted form has an accept-charset +// attribute of iso-8859-1. Presumably also with other charsets that do not contain +// the ✓ character, such as us-ascii. +var isoSentinel = 'utf8=%26%2310003%3B'; // encodeURIComponent('✓') + +// These are the percent-encoded utf-8 octets representing a checkmark, indicating that the request actually is utf-8 encoded. +var charsetSentinel = 'utf8=%E2%9C%93'; // encodeURIComponent('✓') + +var parseValues = function parseQueryStringValues(str, options) { + var obj = {}; + var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, '') : str; + var limit = options.parameterLimit === Infinity ? undefined : options.parameterLimit; + var parts = cleanStr.split(options.delimiter, limit); + var skipIndex = -1; // Keep track of where the utf8 sentinel was found + var i; + + var charset = options.charset; + if (options.charsetSentinel) { + for (i = 0; i < parts.length; ++i) { + if (parts[i].indexOf('utf8=') === 0) { + if (parts[i] === charsetSentinel) { + charset = 'utf-8'; + } else if (parts[i] === isoSentinel) { + charset = 'iso-8859-1'; + } + skipIndex = i; + i = parts.length; // The eslint settings do not allow break; + } + } + } + + for (i = 0; i < parts.length; ++i) { + if (i === skipIndex) { + continue; + } + var part = parts[i]; + + var bracketEqualsPos = part.indexOf(']='); + var pos = bracketEqualsPos === -1 ? part.indexOf('=') : bracketEqualsPos + 1; + + var key, val; + if (pos === -1) { + key = options.decoder(part, defaults.decoder, charset, 'key'); + val = options.strictNullHandling ? null : ''; + } else { + key = options.decoder(part.slice(0, pos), defaults.decoder, charset, 'key'); + val = utils.maybeMap( + parseArrayValue(part.slice(pos + 1), options), + function (encodedVal) { + return options.decoder(encodedVal, defaults.decoder, charset, 'value'); + } + ); + } + + if (val && options.interpretNumericEntities && charset === 'iso-8859-1') { + val = interpretNumericEntities(val); + } + + if (part.indexOf('[]=') > -1) { + val = isArray(val) ? [val] : val; + } + + if (has.call(obj, key)) { + obj[key] = utils.combine(obj[key], val); + } else { + obj[key] = val; + } + } + + return obj; +}; + +var parseObject = function (chain, val, options, valuesParsed) { + var leaf = valuesParsed ? val : parseArrayValue(val, options); + + for (var i = chain.length - 1; i >= 0; --i) { + var obj; + var root = chain[i]; + + if (root === '[]' && options.parseArrays) { + obj = [].concat(leaf); + } else { + obj = options.plainObjects ? Object.create(null) : {}; + var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root; + var index = parseInt(cleanRoot, 10); + if (!options.parseArrays && cleanRoot === '') { + obj = { 0: leaf }; + } else if ( + !isNaN(index) + && root !== cleanRoot + && String(index) === cleanRoot + && index >= 0 + && (options.parseArrays && index <= options.arrayLimit) + ) { + obj = []; + obj[index] = leaf; + } else if (cleanRoot !== '__proto__') { + obj[cleanRoot] = leaf; + } + } + + leaf = obj; + } + + return leaf; +}; + +var parseKeys = function parseQueryStringKeys(givenKey, val, options, valuesParsed) { + if (!givenKey) { + return; + } + + // Transform dot notation to bracket notation + var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, '[$1]') : givenKey; + + // The regex chunks + + var brackets = /(\[[^[\]]*])/; + var child = /(\[[^[\]]*])/g; + + // Get the parent + + var segment = options.depth > 0 && brackets.exec(key); + var parent = segment ? key.slice(0, segment.index) : key; + + // Stash the parent if it exists + + var keys = []; + if (parent) { + // If we aren't using plain objects, optionally prefix keys that would overwrite object prototype properties + if (!options.plainObjects && has.call(Object.prototype, parent)) { + if (!options.allowPrototypes) { + return; + } + } + + keys.push(parent); + } + + // Loop through children appending to the array until we hit depth + + var i = 0; + while (options.depth > 0 && (segment = child.exec(key)) !== null && i < options.depth) { + i += 1; + if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) { + if (!options.allowPrototypes) { + return; + } + } + keys.push(segment[1]); + } + + // If there's a remainder, just add whatever is left + + if (segment) { + keys.push('[' + key.slice(segment.index) + ']'); + } + + return parseObject(keys, val, options, valuesParsed); +}; + +var normalizeParseOptions = function normalizeParseOptions(opts) { + if (!opts) { + return defaults; + } + + if (opts.decoder !== null && opts.decoder !== undefined && typeof opts.decoder !== 'function') { + throw new TypeError('Decoder has to be a function.'); + } + + if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') { + throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined'); + } + var charset = typeof opts.charset === 'undefined' ? defaults.charset : opts.charset; + + return { + allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots, + allowPrototypes: typeof opts.allowPrototypes === 'boolean' ? opts.allowPrototypes : defaults.allowPrototypes, + allowSparse: typeof opts.allowSparse === 'boolean' ? opts.allowSparse : defaults.allowSparse, + arrayLimit: typeof opts.arrayLimit === 'number' ? opts.arrayLimit : defaults.arrayLimit, + charset: charset, + charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel, + comma: typeof opts.comma === 'boolean' ? opts.comma : defaults.comma, + decoder: typeof opts.decoder === 'function' ? opts.decoder : defaults.decoder, + delimiter: typeof opts.delimiter === 'string' || utils.isRegExp(opts.delimiter) ? opts.delimiter : defaults.delimiter, + // eslint-disable-next-line no-implicit-coercion, no-extra-parens + depth: (typeof opts.depth === 'number' || opts.depth === false) ? +opts.depth : defaults.depth, + ignoreQueryPrefix: opts.ignoreQueryPrefix === true, + interpretNumericEntities: typeof opts.interpretNumericEntities === 'boolean' ? opts.interpretNumericEntities : defaults.interpretNumericEntities, + parameterLimit: typeof opts.parameterLimit === 'number' ? opts.parameterLimit : defaults.parameterLimit, + parseArrays: opts.parseArrays !== false, + plainObjects: typeof opts.plainObjects === 'boolean' ? opts.plainObjects : defaults.plainObjects, + strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling + }; +}; + +module.exports = function (str, opts) { + var options = normalizeParseOptions(opts); + + if (str === '' || str === null || typeof str === 'undefined') { + return options.plainObjects ? Object.create(null) : {}; + } + + var tempObj = typeof str === 'string' ? parseValues(str, options) : str; + var obj = options.plainObjects ? Object.create(null) : {}; + + // Iterate over the keys and setup the new object + + var keys = Object.keys(tempObj); + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + var newObj = parseKeys(key, tempObj[key], options, typeof str === 'string'); + obj = utils.merge(obj, newObj, options); + } + + if (options.allowSparse === true) { + return obj; + } + + return utils.compact(obj); +}; diff --git a/backend/node_modules/qs/lib/stringify.js b/backend/node_modules/qs/lib/stringify.js new file mode 100644 index 0000000000000000000000000000000000000000..48ec0306b8a0400e32a81254687f329a6102bf25 --- /dev/null +++ b/backend/node_modules/qs/lib/stringify.js @@ -0,0 +1,326 @@ +'use strict'; + +var getSideChannel = require('side-channel'); +var utils = require('./utils'); +var formats = require('./formats'); +var has = Object.prototype.hasOwnProperty; + +var arrayPrefixGenerators = { + brackets: function brackets(prefix) { + return prefix + '[]'; + }, + comma: 'comma', + indices: function indices(prefix, key) { + return prefix + '[' + key + ']'; + }, + repeat: function repeat(prefix) { + return prefix; + } +}; + +var isArray = Array.isArray; +var split = String.prototype.split; +var push = Array.prototype.push; +var pushToArray = function (arr, valueOrArray) { + push.apply(arr, isArray(valueOrArray) ? valueOrArray : [valueOrArray]); +}; + +var toISO = Date.prototype.toISOString; + +var defaultFormat = formats['default']; +var defaults = { + addQueryPrefix: false, + allowDots: false, + charset: 'utf-8', + charsetSentinel: false, + delimiter: '&', + encode: true, + encoder: utils.encode, + encodeValuesOnly: false, + format: defaultFormat, + formatter: formats.formatters[defaultFormat], + // deprecated + indices: false, + serializeDate: function serializeDate(date) { + return toISO.call(date); + }, + skipNulls: false, + strictNullHandling: false +}; + +var isNonNullishPrimitive = function isNonNullishPrimitive(v) { + return typeof v === 'string' + || typeof v === 'number' + || typeof v === 'boolean' + || typeof v === 'symbol' + || typeof v === 'bigint'; +}; + +var sentinel = {}; + +var stringify = function stringify( + object, + prefix, + generateArrayPrefix, + commaRoundTrip, + strictNullHandling, + skipNulls, + encoder, + filter, + sort, + allowDots, + serializeDate, + format, + formatter, + encodeValuesOnly, + charset, + sideChannel +) { + var obj = object; + + var tmpSc = sideChannel; + var step = 0; + var findFlag = false; + while ((tmpSc = tmpSc.get(sentinel)) !== void undefined && !findFlag) { + // Where object last appeared in the ref tree + var pos = tmpSc.get(object); + step += 1; + if (typeof pos !== 'undefined') { + if (pos === step) { + throw new RangeError('Cyclic object value'); + } else { + findFlag = true; // Break while + } + } + if (typeof tmpSc.get(sentinel) === 'undefined') { + step = 0; + } + } + + if (typeof filter === 'function') { + obj = filter(prefix, obj); + } else if (obj instanceof Date) { + obj = serializeDate(obj); + } else if (generateArrayPrefix === 'comma' && isArray(obj)) { + obj = utils.maybeMap(obj, function (value) { + if (value instanceof Date) { + return serializeDate(value); + } + return value; + }); + } + + if (obj === null) { + if (strictNullHandling) { + return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder, charset, 'key', format) : prefix; + } + + obj = ''; + } + + if (isNonNullishPrimitive(obj) || utils.isBuffer(obj)) { + if (encoder) { + var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset, 'key', format); + if (generateArrayPrefix === 'comma' && encodeValuesOnly) { + var valuesArray = split.call(String(obj), ','); + var valuesJoined = ''; + for (var i = 0; i < valuesArray.length; ++i) { + valuesJoined += (i === 0 ? '' : ',') + formatter(encoder(valuesArray[i], defaults.encoder, charset, 'value', format)); + } + return [formatter(keyValue) + (commaRoundTrip && isArray(obj) && valuesArray.length === 1 ? '[]' : '') + '=' + valuesJoined]; + } + return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults.encoder, charset, 'value', format))]; + } + return [formatter(prefix) + '=' + formatter(String(obj))]; + } + + var values = []; + + if (typeof obj === 'undefined') { + return values; + } + + var objKeys; + if (generateArrayPrefix === 'comma' && isArray(obj)) { + // we need to join elements in + objKeys = [{ value: obj.length > 0 ? obj.join(',') || null : void undefined }]; + } else if (isArray(filter)) { + objKeys = filter; + } else { + var keys = Object.keys(obj); + objKeys = sort ? keys.sort(sort) : keys; + } + + var adjustedPrefix = commaRoundTrip && isArray(obj) && obj.length === 1 ? prefix + '[]' : prefix; + + for (var j = 0; j < objKeys.length; ++j) { + var key = objKeys[j]; + var value = typeof key === 'object' && typeof key.value !== 'undefined' ? key.value : obj[key]; + + if (skipNulls && value === null) { + continue; + } + + var keyPrefix = isArray(obj) + ? typeof generateArrayPrefix === 'function' ? generateArrayPrefix(adjustedPrefix, key) : adjustedPrefix + : adjustedPrefix + (allowDots ? '.' + key : '[' + key + ']'); + + sideChannel.set(object, step); + var valueSideChannel = getSideChannel(); + valueSideChannel.set(sentinel, sideChannel); + pushToArray(values, stringify( + value, + keyPrefix, + generateArrayPrefix, + commaRoundTrip, + strictNullHandling, + skipNulls, + encoder, + filter, + sort, + allowDots, + serializeDate, + format, + formatter, + encodeValuesOnly, + charset, + valueSideChannel + )); + } + + return values; +}; + +var normalizeStringifyOptions = function normalizeStringifyOptions(opts) { + if (!opts) { + return defaults; + } + + if (opts.encoder !== null && typeof opts.encoder !== 'undefined' && typeof opts.encoder !== 'function') { + throw new TypeError('Encoder has to be a function.'); + } + + var charset = opts.charset || defaults.charset; + if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') { + throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined'); + } + + var format = formats['default']; + if (typeof opts.format !== 'undefined') { + if (!has.call(formats.formatters, opts.format)) { + throw new TypeError('Unknown format option provided.'); + } + format = opts.format; + } + var formatter = formats.formatters[format]; + + var filter = defaults.filter; + if (typeof opts.filter === 'function' || isArray(opts.filter)) { + filter = opts.filter; + } + + return { + addQueryPrefix: typeof opts.addQueryPrefix === 'boolean' ? opts.addQueryPrefix : defaults.addQueryPrefix, + allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots, + charset: charset, + charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel, + delimiter: typeof opts.delimiter === 'undefined' ? defaults.delimiter : opts.delimiter, + encode: typeof opts.encode === 'boolean' ? opts.encode : defaults.encode, + encoder: typeof opts.encoder === 'function' ? opts.encoder : defaults.encoder, + encodeValuesOnly: typeof opts.encodeValuesOnly === 'boolean' ? opts.encodeValuesOnly : defaults.encodeValuesOnly, + filter: filter, + format: format, + formatter: formatter, + serializeDate: typeof opts.serializeDate === 'function' ? opts.serializeDate : defaults.serializeDate, + skipNulls: typeof opts.skipNulls === 'boolean' ? opts.skipNulls : defaults.skipNulls, + sort: typeof opts.sort === 'function' ? opts.sort : null, + strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling + }; +}; + +module.exports = function (object, opts) { + var obj = object; + var options = normalizeStringifyOptions(opts); + + var objKeys; + var filter; + + if (typeof options.filter === 'function') { + filter = options.filter; + obj = filter('', obj); + } else if (isArray(options.filter)) { + filter = options.filter; + objKeys = filter; + } + + var keys = []; + + if (typeof obj !== 'object' || obj === null) { + return ''; + } + + var arrayFormat; + if (opts && opts.arrayFormat in arrayPrefixGenerators) { + arrayFormat = opts.arrayFormat; + } else if (opts && 'indices' in opts) { + arrayFormat = opts.indices ? 'indices' : 'repeat'; + } else { + arrayFormat = 'indices'; + } + + var generateArrayPrefix = arrayPrefixGenerators[arrayFormat]; + if (opts && 'commaRoundTrip' in opts && typeof opts.commaRoundTrip !== 'boolean') { + throw new TypeError('`commaRoundTrip` must be a boolean, or absent'); + } + var commaRoundTrip = generateArrayPrefix === 'comma' && opts && opts.commaRoundTrip; + + if (!objKeys) { + objKeys = Object.keys(obj); + } + + if (options.sort) { + objKeys.sort(options.sort); + } + + var sideChannel = getSideChannel(); + for (var i = 0; i < objKeys.length; ++i) { + var key = objKeys[i]; + + if (options.skipNulls && obj[key] === null) { + continue; + } + pushToArray(keys, stringify( + obj[key], + key, + generateArrayPrefix, + commaRoundTrip, + options.strictNullHandling, + options.skipNulls, + options.encode ? options.encoder : null, + options.filter, + options.sort, + options.allowDots, + options.serializeDate, + options.format, + options.formatter, + options.encodeValuesOnly, + options.charset, + sideChannel + )); + } + + var joined = keys.join(options.delimiter); + var prefix = options.addQueryPrefix === true ? '?' : ''; + + if (options.charsetSentinel) { + if (options.charset === 'iso-8859-1') { + // encodeURIComponent('✓'), the "numeric entity" representation of a checkmark + prefix += 'utf8=%26%2310003%3B&'; + } else { + // encodeURIComponent('✓') + prefix += 'utf8=%E2%9C%93&'; + } + } + + return joined.length > 0 ? prefix + joined : ''; +}; diff --git a/backend/node_modules/qs/lib/utils.js b/backend/node_modules/qs/lib/utils.js new file mode 100644 index 0000000000000000000000000000000000000000..1e545381131a9665a5561d22fc0cfe05d5a60315 --- /dev/null +++ b/backend/node_modules/qs/lib/utils.js @@ -0,0 +1,252 @@ +'use strict'; + +var formats = require('./formats'); + +var has = Object.prototype.hasOwnProperty; +var isArray = Array.isArray; + +var hexTable = (function () { + var array = []; + for (var i = 0; i < 256; ++i) { + array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase()); + } + + return array; +}()); + +var compactQueue = function compactQueue(queue) { + while (queue.length > 1) { + var item = queue.pop(); + var obj = item.obj[item.prop]; + + if (isArray(obj)) { + var compacted = []; + + for (var j = 0; j < obj.length; ++j) { + if (typeof obj[j] !== 'undefined') { + compacted.push(obj[j]); + } + } + + item.obj[item.prop] = compacted; + } + } +}; + +var arrayToObject = function arrayToObject(source, options) { + var obj = options && options.plainObjects ? Object.create(null) : {}; + for (var i = 0; i < source.length; ++i) { + if (typeof source[i] !== 'undefined') { + obj[i] = source[i]; + } + } + + return obj; +}; + +var merge = function merge(target, source, options) { + /* eslint no-param-reassign: 0 */ + if (!source) { + return target; + } + + if (typeof source !== 'object') { + if (isArray(target)) { + target.push(source); + } else if (target && typeof target === 'object') { + if ((options && (options.plainObjects || options.allowPrototypes)) || !has.call(Object.prototype, source)) { + target[source] = true; + } + } else { + return [target, source]; + } + + return target; + } + + if (!target || typeof target !== 'object') { + return [target].concat(source); + } + + var mergeTarget = target; + if (isArray(target) && !isArray(source)) { + mergeTarget = arrayToObject(target, options); + } + + if (isArray(target) && isArray(source)) { + source.forEach(function (item, i) { + if (has.call(target, i)) { + var targetItem = target[i]; + if (targetItem && typeof targetItem === 'object' && item && typeof item === 'object') { + target[i] = merge(targetItem, item, options); + } else { + target.push(item); + } + } else { + target[i] = item; + } + }); + return target; + } + + return Object.keys(source).reduce(function (acc, key) { + var value = source[key]; + + if (has.call(acc, key)) { + acc[key] = merge(acc[key], value, options); + } else { + acc[key] = value; + } + return acc; + }, mergeTarget); +}; + +var assign = function assignSingleSource(target, source) { + return Object.keys(source).reduce(function (acc, key) { + acc[key] = source[key]; + return acc; + }, target); +}; + +var decode = function (str, decoder, charset) { + var strWithoutPlus = str.replace(/\+/g, ' '); + if (charset === 'iso-8859-1') { + // unescape never throws, no try...catch needed: + return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape); + } + // utf-8 + try { + return decodeURIComponent(strWithoutPlus); + } catch (e) { + return strWithoutPlus; + } +}; + +var encode = function encode(str, defaultEncoder, charset, kind, format) { + // This code was originally written by Brian White (mscdex) for the io.js core querystring library. + // It has been adapted here for stricter adherence to RFC 3986 + if (str.length === 0) { + return str; + } + + var string = str; + if (typeof str === 'symbol') { + string = Symbol.prototype.toString.call(str); + } else if (typeof str !== 'string') { + string = String(str); + } + + if (charset === 'iso-8859-1') { + return escape(string).replace(/%u[0-9a-f]{4}/gi, function ($0) { + return '%26%23' + parseInt($0.slice(2), 16) + '%3B'; + }); + } + + var out = ''; + for (var i = 0; i < string.length; ++i) { + var c = string.charCodeAt(i); + + if ( + c === 0x2D // - + || c === 0x2E // . + || c === 0x5F // _ + || c === 0x7E // ~ + || (c >= 0x30 && c <= 0x39) // 0-9 + || (c >= 0x41 && c <= 0x5A) // a-z + || (c >= 0x61 && c <= 0x7A) // A-Z + || (format === formats.RFC1738 && (c === 0x28 || c === 0x29)) // ( ) + ) { + out += string.charAt(i); + continue; + } + + if (c < 0x80) { + out = out + hexTable[c]; + continue; + } + + if (c < 0x800) { + out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]); + continue; + } + + if (c < 0xD800 || c >= 0xE000) { + out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]); + continue; + } + + i += 1; + c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF)); + /* eslint operator-linebreak: [2, "before"] */ + out += hexTable[0xF0 | (c >> 18)] + + hexTable[0x80 | ((c >> 12) & 0x3F)] + + hexTable[0x80 | ((c >> 6) & 0x3F)] + + hexTable[0x80 | (c & 0x3F)]; + } + + return out; +}; + +var compact = function compact(value) { + var queue = [{ obj: { o: value }, prop: 'o' }]; + var refs = []; + + for (var i = 0; i < queue.length; ++i) { + var item = queue[i]; + var obj = item.obj[item.prop]; + + var keys = Object.keys(obj); + for (var j = 0; j < keys.length; ++j) { + var key = keys[j]; + var val = obj[key]; + if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) { + queue.push({ obj: obj, prop: key }); + refs.push(val); + } + } + } + + compactQueue(queue); + + return value; +}; + +var isRegExp = function isRegExp(obj) { + return Object.prototype.toString.call(obj) === '[object RegExp]'; +}; + +var isBuffer = function isBuffer(obj) { + if (!obj || typeof obj !== 'object') { + return false; + } + + return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); +}; + +var combine = function combine(a, b) { + return [].concat(a, b); +}; + +var maybeMap = function maybeMap(val, fn) { + if (isArray(val)) { + var mapped = []; + for (var i = 0; i < val.length; i += 1) { + mapped.push(fn(val[i])); + } + return mapped; + } + return fn(val); +}; + +module.exports = { + arrayToObject: arrayToObject, + assign: assign, + combine: combine, + compact: compact, + decode: decode, + encode: encode, + isBuffer: isBuffer, + isRegExp: isRegExp, + maybeMap: maybeMap, + merge: merge +}; diff --git a/backend/node_modules/qs/package.json b/backend/node_modules/qs/package.json new file mode 100644 index 0000000000000000000000000000000000000000..2ff42f375b878d370a5444146b43e117c0f4d748 --- /dev/null +++ b/backend/node_modules/qs/package.json @@ -0,0 +1,77 @@ +{ + "name": "qs", + "description": "A querystring parser that supports nesting and arrays, with a depth limit", + "homepage": "https://github.com/ljharb/qs", + "version": "6.11.0", + "repository": { + "type": "git", + "url": "https://github.com/ljharb/qs.git" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "main": "lib/index.js", + "contributors": [ + { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + } + ], + "keywords": [ + "querystring", + "qs", + "query", + "url", + "parse", + "stringify" + ], + "engines": { + "node": ">=0.6" + }, + "dependencies": { + "side-channel": "^1.0.4" + }, + "devDependencies": { + "@ljharb/eslint-config": "^21.0.0", + "aud": "^2.0.0", + "browserify": "^16.5.2", + "eclint": "^2.8.1", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "for-each": "^0.3.3", + "has-symbols": "^1.0.3", + "iconv-lite": "^0.5.1", + "in-publish": "^2.0.1", + "mkdirp": "^0.5.5", + "npmignore": "^0.3.0", + "nyc": "^10.3.2", + "object-inspect": "^1.12.2", + "qs-iconv": "^1.0.4", + "safe-publish-latest": "^2.0.0", + "safer-buffer": "^2.1.2", + "tape": "^5.5.3" + }, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublishOnly": "safe-publish-latest && npm run dist", + "prepublish": "not-in-publish || npm run prepublishOnly", + "pretest": "npm run --silent readme && npm run --silent lint", + "test": "npm run tests-only", + "tests-only": "nyc tape 'test/**/*.js'", + "posttest": "aud --production", + "readme": "evalmd README.md", + "postlint": "eclint check $(git ls-files | xargs find 2> /dev/null | grep -vE 'node_modules|\\.git' | grep -v dist/)", + "lint": "eslint --ext=js,mjs .", + "dist": "mkdirp dist && browserify --standalone Qs lib/index.js > dist/qs.js" + }, + "license": "BSD-3-Clause", + "publishConfig": { + "ignore": [ + "!dist/*", + "bower.json", + "component.json", + ".github/workflows" + ] + } +} diff --git a/backend/node_modules/qs/test/parse.js b/backend/node_modules/qs/test/parse.js new file mode 100644 index 0000000000000000000000000000000000000000..7d7b4dd8aea13754a32dca91e432e80ef3f6af67 --- /dev/null +++ b/backend/node_modules/qs/test/parse.js @@ -0,0 +1,855 @@ +'use strict'; + +var test = require('tape'); +var qs = require('../'); +var utils = require('../lib/utils'); +var iconv = require('iconv-lite'); +var SaferBuffer = require('safer-buffer').Buffer; + +test('parse()', function (t) { + t.test('parses a simple string', function (st) { + st.deepEqual(qs.parse('0=foo'), { 0: 'foo' }); + st.deepEqual(qs.parse('foo=c++'), { foo: 'c ' }); + st.deepEqual(qs.parse('a[>=]=23'), { a: { '>=': '23' } }); + st.deepEqual(qs.parse('a[<=>]==23'), { a: { '<=>': '=23' } }); + st.deepEqual(qs.parse('a[==]=23'), { a: { '==': '23' } }); + st.deepEqual(qs.parse('foo', { strictNullHandling: true }), { foo: null }); + st.deepEqual(qs.parse('foo'), { foo: '' }); + st.deepEqual(qs.parse('foo='), { foo: '' }); + st.deepEqual(qs.parse('foo=bar'), { foo: 'bar' }); + st.deepEqual(qs.parse(' foo = bar = baz '), { ' foo ': ' bar = baz ' }); + st.deepEqual(qs.parse('foo=bar=baz'), { foo: 'bar=baz' }); + st.deepEqual(qs.parse('foo=bar&bar=baz'), { foo: 'bar', bar: 'baz' }); + st.deepEqual(qs.parse('foo2=bar2&baz2='), { foo2: 'bar2', baz2: '' }); + st.deepEqual(qs.parse('foo=bar&baz', { strictNullHandling: true }), { foo: 'bar', baz: null }); + st.deepEqual(qs.parse('foo=bar&baz'), { foo: 'bar', baz: '' }); + st.deepEqual(qs.parse('cht=p3&chd=t:60,40&chs=250x100&chl=Hello|World'), { + cht: 'p3', + chd: 't:60,40', + chs: '250x100', + chl: 'Hello|World' + }); + st.end(); + }); + + t.test('arrayFormat: brackets allows only explicit arrays', function (st) { + st.deepEqual(qs.parse('a[]=b&a[]=c', { arrayFormat: 'brackets' }), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a[0]=b&a[1]=c', { arrayFormat: 'brackets' }), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a=b,c', { arrayFormat: 'brackets' }), { a: 'b,c' }); + st.deepEqual(qs.parse('a=b&a=c', { arrayFormat: 'brackets' }), { a: ['b', 'c'] }); + st.end(); + }); + + t.test('arrayFormat: indices allows only indexed arrays', function (st) { + st.deepEqual(qs.parse('a[]=b&a[]=c', { arrayFormat: 'indices' }), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a[0]=b&a[1]=c', { arrayFormat: 'indices' }), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a=b,c', { arrayFormat: 'indices' }), { a: 'b,c' }); + st.deepEqual(qs.parse('a=b&a=c', { arrayFormat: 'indices' }), { a: ['b', 'c'] }); + st.end(); + }); + + t.test('arrayFormat: comma allows only comma-separated arrays', function (st) { + st.deepEqual(qs.parse('a[]=b&a[]=c', { arrayFormat: 'comma' }), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a[0]=b&a[1]=c', { arrayFormat: 'comma' }), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a=b,c', { arrayFormat: 'comma' }), { a: 'b,c' }); + st.deepEqual(qs.parse('a=b&a=c', { arrayFormat: 'comma' }), { a: ['b', 'c'] }); + st.end(); + }); + + t.test('arrayFormat: repeat allows only repeated values', function (st) { + st.deepEqual(qs.parse('a[]=b&a[]=c', { arrayFormat: 'repeat' }), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a[0]=b&a[1]=c', { arrayFormat: 'repeat' }), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a=b,c', { arrayFormat: 'repeat' }), { a: 'b,c' }); + st.deepEqual(qs.parse('a=b&a=c', { arrayFormat: 'repeat' }), { a: ['b', 'c'] }); + st.end(); + }); + + t.test('allows enabling dot notation', function (st) { + st.deepEqual(qs.parse('a.b=c'), { 'a.b': 'c' }); + st.deepEqual(qs.parse('a.b=c', { allowDots: true }), { a: { b: 'c' } }); + st.end(); + }); + + t.deepEqual(qs.parse('a[b]=c'), { a: { b: 'c' } }, 'parses a single nested string'); + t.deepEqual(qs.parse('a[b][c]=d'), { a: { b: { c: 'd' } } }, 'parses a double nested string'); + t.deepEqual( + qs.parse('a[b][c][d][e][f][g][h]=i'), + { a: { b: { c: { d: { e: { f: { '[g][h]': 'i' } } } } } } }, + 'defaults to a depth of 5' + ); + + t.test('only parses one level when depth = 1', function (st) { + st.deepEqual(qs.parse('a[b][c]=d', { depth: 1 }), { a: { b: { '[c]': 'd' } } }); + st.deepEqual(qs.parse('a[b][c][d]=e', { depth: 1 }), { a: { b: { '[c][d]': 'e' } } }); + st.end(); + }); + + t.test('uses original key when depth = 0', function (st) { + st.deepEqual(qs.parse('a[0]=b&a[1]=c', { depth: 0 }), { 'a[0]': 'b', 'a[1]': 'c' }); + st.deepEqual(qs.parse('a[0][0]=b&a[0][1]=c&a[1]=d&e=2', { depth: 0 }), { 'a[0][0]': 'b', 'a[0][1]': 'c', 'a[1]': 'd', e: '2' }); + st.end(); + }); + + t.test('uses original key when depth = false', function (st) { + st.deepEqual(qs.parse('a[0]=b&a[1]=c', { depth: false }), { 'a[0]': 'b', 'a[1]': 'c' }); + st.deepEqual(qs.parse('a[0][0]=b&a[0][1]=c&a[1]=d&e=2', { depth: false }), { 'a[0][0]': 'b', 'a[0][1]': 'c', 'a[1]': 'd', e: '2' }); + st.end(); + }); + + t.deepEqual(qs.parse('a=b&a=c'), { a: ['b', 'c'] }, 'parses a simple array'); + + t.test('parses an explicit array', function (st) { + st.deepEqual(qs.parse('a[]=b'), { a: ['b'] }); + st.deepEqual(qs.parse('a[]=b&a[]=c'), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a[]=b&a[]=c&a[]=d'), { a: ['b', 'c', 'd'] }); + st.end(); + }); + + t.test('parses a mix of simple and explicit arrays', function (st) { + st.deepEqual(qs.parse('a=b&a[]=c'), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a[]=b&a=c'), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a[0]=b&a=c'), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a=b&a[0]=c'), { a: ['b', 'c'] }); + + st.deepEqual(qs.parse('a[1]=b&a=c', { arrayLimit: 20 }), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a[]=b&a=c', { arrayLimit: 0 }), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a[]=b&a=c'), { a: ['b', 'c'] }); + + st.deepEqual(qs.parse('a=b&a[1]=c', { arrayLimit: 20 }), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a=b&a[]=c', { arrayLimit: 0 }), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a=b&a[]=c'), { a: ['b', 'c'] }); + + st.end(); + }); + + t.test('parses a nested array', function (st) { + st.deepEqual(qs.parse('a[b][]=c&a[b][]=d'), { a: { b: ['c', 'd'] } }); + st.deepEqual(qs.parse('a[>=]=25'), { a: { '>=': '25' } }); + st.end(); + }); + + t.test('allows to specify array indices', function (st) { + st.deepEqual(qs.parse('a[1]=c&a[0]=b&a[2]=d'), { a: ['b', 'c', 'd'] }); + st.deepEqual(qs.parse('a[1]=c&a[0]=b'), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a[1]=c', { arrayLimit: 20 }), { a: ['c'] }); + st.deepEqual(qs.parse('a[1]=c', { arrayLimit: 0 }), { a: { 1: 'c' } }); + st.deepEqual(qs.parse('a[1]=c'), { a: ['c'] }); + st.end(); + }); + + t.test('limits specific array indices to arrayLimit', function (st) { + st.deepEqual(qs.parse('a[20]=a', { arrayLimit: 20 }), { a: ['a'] }); + st.deepEqual(qs.parse('a[21]=a', { arrayLimit: 20 }), { a: { 21: 'a' } }); + + st.deepEqual(qs.parse('a[20]=a'), { a: ['a'] }); + st.deepEqual(qs.parse('a[21]=a'), { a: { 21: 'a' } }); + st.end(); + }); + + t.deepEqual(qs.parse('a[12b]=c'), { a: { '12b': 'c' } }, 'supports keys that begin with a number'); + + t.test('supports encoded = signs', function (st) { + st.deepEqual(qs.parse('he%3Dllo=th%3Dere'), { 'he=llo': 'th=ere' }); + st.end(); + }); + + t.test('is ok with url encoded strings', function (st) { + st.deepEqual(qs.parse('a[b%20c]=d'), { a: { 'b c': 'd' } }); + st.deepEqual(qs.parse('a[b]=c%20d'), { a: { b: 'c d' } }); + st.end(); + }); + + t.test('allows brackets in the value', function (st) { + st.deepEqual(qs.parse('pets=["tobi"]'), { pets: '["tobi"]' }); + st.deepEqual(qs.parse('operators=[">=", "<="]'), { operators: '[">=", "<="]' }); + st.end(); + }); + + t.test('allows empty values', function (st) { + st.deepEqual(qs.parse(''), {}); + st.deepEqual(qs.parse(null), {}); + st.deepEqual(qs.parse(undefined), {}); + st.end(); + }); + + t.test('transforms arrays to objects', function (st) { + st.deepEqual(qs.parse('foo[0]=bar&foo[bad]=baz'), { foo: { 0: 'bar', bad: 'baz' } }); + st.deepEqual(qs.parse('foo[bad]=baz&foo[0]=bar'), { foo: { bad: 'baz', 0: 'bar' } }); + st.deepEqual(qs.parse('foo[bad]=baz&foo[]=bar'), { foo: { bad: 'baz', 0: 'bar' } }); + st.deepEqual(qs.parse('foo[]=bar&foo[bad]=baz'), { foo: { 0: 'bar', bad: 'baz' } }); + st.deepEqual(qs.parse('foo[bad]=baz&foo[]=bar&foo[]=foo'), { foo: { bad: 'baz', 0: 'bar', 1: 'foo' } }); + st.deepEqual(qs.parse('foo[0][a]=a&foo[0][b]=b&foo[1][a]=aa&foo[1][b]=bb'), { foo: [{ a: 'a', b: 'b' }, { a: 'aa', b: 'bb' }] }); + + st.deepEqual(qs.parse('a[]=b&a[t]=u&a[hasOwnProperty]=c', { allowPrototypes: false }), { a: { 0: 'b', t: 'u' } }); + st.deepEqual(qs.parse('a[]=b&a[t]=u&a[hasOwnProperty]=c', { allowPrototypes: true }), { a: { 0: 'b', t: 'u', hasOwnProperty: 'c' } }); + st.deepEqual(qs.parse('a[]=b&a[hasOwnProperty]=c&a[x]=y', { allowPrototypes: false }), { a: { 0: 'b', x: 'y' } }); + st.deepEqual(qs.parse('a[]=b&a[hasOwnProperty]=c&a[x]=y', { allowPrototypes: true }), { a: { 0: 'b', hasOwnProperty: 'c', x: 'y' } }); + st.end(); + }); + + t.test('transforms arrays to objects (dot notation)', function (st) { + st.deepEqual(qs.parse('foo[0].baz=bar&fool.bad=baz', { allowDots: true }), { foo: [{ baz: 'bar' }], fool: { bad: 'baz' } }); + st.deepEqual(qs.parse('foo[0].baz=bar&fool.bad.boo=baz', { allowDots: true }), { foo: [{ baz: 'bar' }], fool: { bad: { boo: 'baz' } } }); + st.deepEqual(qs.parse('foo[0][0].baz=bar&fool.bad=baz', { allowDots: true }), { foo: [[{ baz: 'bar' }]], fool: { bad: 'baz' } }); + st.deepEqual(qs.parse('foo[0].baz[0]=15&foo[0].bar=2', { allowDots: true }), { foo: [{ baz: ['15'], bar: '2' }] }); + st.deepEqual(qs.parse('foo[0].baz[0]=15&foo[0].baz[1]=16&foo[0].bar=2', { allowDots: true }), { foo: [{ baz: ['15', '16'], bar: '2' }] }); + st.deepEqual(qs.parse('foo.bad=baz&foo[0]=bar', { allowDots: true }), { foo: { bad: 'baz', 0: 'bar' } }); + st.deepEqual(qs.parse('foo.bad=baz&foo[]=bar', { allowDots: true }), { foo: { bad: 'baz', 0: 'bar' } }); + st.deepEqual(qs.parse('foo[]=bar&foo.bad=baz', { allowDots: true }), { foo: { 0: 'bar', bad: 'baz' } }); + st.deepEqual(qs.parse('foo.bad=baz&foo[]=bar&foo[]=foo', { allowDots: true }), { foo: { bad: 'baz', 0: 'bar', 1: 'foo' } }); + st.deepEqual(qs.parse('foo[0].a=a&foo[0].b=b&foo[1].a=aa&foo[1].b=bb', { allowDots: true }), { foo: [{ a: 'a', b: 'b' }, { a: 'aa', b: 'bb' }] }); + st.end(); + }); + + t.test('correctly prunes undefined values when converting an array to an object', function (st) { + st.deepEqual(qs.parse('a[2]=b&a[99999999]=c'), { a: { 2: 'b', 99999999: 'c' } }); + st.end(); + }); + + t.test('supports malformed uri characters', function (st) { + st.deepEqual(qs.parse('{%:%}', { strictNullHandling: true }), { '{%:%}': null }); + st.deepEqual(qs.parse('{%:%}='), { '{%:%}': '' }); + st.deepEqual(qs.parse('foo=%:%}'), { foo: '%:%}' }); + st.end(); + }); + + t.test('doesn\'t produce empty keys', function (st) { + st.deepEqual(qs.parse('_r=1&'), { _r: '1' }); + st.end(); + }); + + t.test('cannot access Object prototype', function (st) { + qs.parse('constructor[prototype][bad]=bad'); + qs.parse('bad[constructor][prototype][bad]=bad'); + st.equal(typeof Object.prototype.bad, 'undefined'); + st.end(); + }); + + t.test('parses arrays of objects', function (st) { + st.deepEqual(qs.parse('a[][b]=c'), { a: [{ b: 'c' }] }); + st.deepEqual(qs.parse('a[0][b]=c'), { a: [{ b: 'c' }] }); + st.end(); + }); + + t.test('allows for empty strings in arrays', function (st) { + st.deepEqual(qs.parse('a[]=b&a[]=&a[]=c'), { a: ['b', '', 'c'] }); + + st.deepEqual( + qs.parse('a[0]=b&a[1]&a[2]=c&a[19]=', { strictNullHandling: true, arrayLimit: 20 }), + { a: ['b', null, 'c', ''] }, + 'with arrayLimit 20 + array indices: null then empty string works' + ); + st.deepEqual( + qs.parse('a[]=b&a[]&a[]=c&a[]=', { strictNullHandling: true, arrayLimit: 0 }), + { a: ['b', null, 'c', ''] }, + 'with arrayLimit 0 + array brackets: null then empty string works' + ); + + st.deepEqual( + qs.parse('a[0]=b&a[1]=&a[2]=c&a[19]', { strictNullHandling: true, arrayLimit: 20 }), + { a: ['b', '', 'c', null] }, + 'with arrayLimit 20 + array indices: empty string then null works' + ); + st.deepEqual( + qs.parse('a[]=b&a[]=&a[]=c&a[]', { strictNullHandling: true, arrayLimit: 0 }), + { a: ['b', '', 'c', null] }, + 'with arrayLimit 0 + array brackets: empty string then null works' + ); + + st.deepEqual( + qs.parse('a[]=&a[]=b&a[]=c'), + { a: ['', 'b', 'c'] }, + 'array brackets: empty strings work' + ); + st.end(); + }); + + t.test('compacts sparse arrays', function (st) { + st.deepEqual(qs.parse('a[10]=1&a[2]=2', { arrayLimit: 20 }), { a: ['2', '1'] }); + st.deepEqual(qs.parse('a[1][b][2][c]=1', { arrayLimit: 20 }), { a: [{ b: [{ c: '1' }] }] }); + st.deepEqual(qs.parse('a[1][2][3][c]=1', { arrayLimit: 20 }), { a: [[[{ c: '1' }]]] }); + st.deepEqual(qs.parse('a[1][2][3][c][1]=1', { arrayLimit: 20 }), { a: [[[{ c: ['1'] }]]] }); + st.end(); + }); + + t.test('parses sparse arrays', function (st) { + /* eslint no-sparse-arrays: 0 */ + st.deepEqual(qs.parse('a[4]=1&a[1]=2', { allowSparse: true }), { a: [, '2', , , '1'] }); + st.deepEqual(qs.parse('a[1][b][2][c]=1', { allowSparse: true }), { a: [, { b: [, , { c: '1' }] }] }); + st.deepEqual(qs.parse('a[1][2][3][c]=1', { allowSparse: true }), { a: [, [, , [, , , { c: '1' }]]] }); + st.deepEqual(qs.parse('a[1][2][3][c][1]=1', { allowSparse: true }), { a: [, [, , [, , , { c: [, '1'] }]]] }); + st.end(); + }); + + t.test('parses semi-parsed strings', function (st) { + st.deepEqual(qs.parse({ 'a[b]': 'c' }), { a: { b: 'c' } }); + st.deepEqual(qs.parse({ 'a[b]': 'c', 'a[d]': 'e' }), { a: { b: 'c', d: 'e' } }); + st.end(); + }); + + t.test('parses buffers correctly', function (st) { + var b = SaferBuffer.from('test'); + st.deepEqual(qs.parse({ a: b }), { a: b }); + st.end(); + }); + + t.test('parses jquery-param strings', function (st) { + // readable = 'filter[0][]=int1&filter[0][]==&filter[0][]=77&filter[]=and&filter[2][]=int2&filter[2][]==&filter[2][]=8' + var encoded = 'filter%5B0%5D%5B%5D=int1&filter%5B0%5D%5B%5D=%3D&filter%5B0%5D%5B%5D=77&filter%5B%5D=and&filter%5B2%5D%5B%5D=int2&filter%5B2%5D%5B%5D=%3D&filter%5B2%5D%5B%5D=8'; + var expected = { filter: [['int1', '=', '77'], 'and', ['int2', '=', '8']] }; + st.deepEqual(qs.parse(encoded), expected); + st.end(); + }); + + t.test('continues parsing when no parent is found', function (st) { + st.deepEqual(qs.parse('[]=&a=b'), { 0: '', a: 'b' }); + st.deepEqual(qs.parse('[]&a=b', { strictNullHandling: true }), { 0: null, a: 'b' }); + st.deepEqual(qs.parse('[foo]=bar'), { foo: 'bar' }); + st.end(); + }); + + t.test('does not error when parsing a very long array', function (st) { + var str = 'a[]=a'; + while (Buffer.byteLength(str) < 128 * 1024) { + str = str + '&' + str; + } + + st.doesNotThrow(function () { + qs.parse(str); + }); + + st.end(); + }); + + t.test('should not throw when a native prototype has an enumerable property', function (st) { + Object.prototype.crash = ''; + Array.prototype.crash = ''; + st.doesNotThrow(qs.parse.bind(null, 'a=b')); + st.deepEqual(qs.parse('a=b'), { a: 'b' }); + st.doesNotThrow(qs.parse.bind(null, 'a[][b]=c')); + st.deepEqual(qs.parse('a[][b]=c'), { a: [{ b: 'c' }] }); + delete Object.prototype.crash; + delete Array.prototype.crash; + st.end(); + }); + + t.test('parses a string with an alternative string delimiter', function (st) { + st.deepEqual(qs.parse('a=b;c=d', { delimiter: ';' }), { a: 'b', c: 'd' }); + st.end(); + }); + + t.test('parses a string with an alternative RegExp delimiter', function (st) { + st.deepEqual(qs.parse('a=b; c=d', { delimiter: /[;,] */ }), { a: 'b', c: 'd' }); + st.end(); + }); + + t.test('does not use non-splittable objects as delimiters', function (st) { + st.deepEqual(qs.parse('a=b&c=d', { delimiter: true }), { a: 'b', c: 'd' }); + st.end(); + }); + + t.test('allows overriding parameter limit', function (st) { + st.deepEqual(qs.parse('a=b&c=d', { parameterLimit: 1 }), { a: 'b' }); + st.end(); + }); + + t.test('allows setting the parameter limit to Infinity', function (st) { + st.deepEqual(qs.parse('a=b&c=d', { parameterLimit: Infinity }), { a: 'b', c: 'd' }); + st.end(); + }); + + t.test('allows overriding array limit', function (st) { + st.deepEqual(qs.parse('a[0]=b', { arrayLimit: -1 }), { a: { 0: 'b' } }); + st.deepEqual(qs.parse('a[-1]=b', { arrayLimit: -1 }), { a: { '-1': 'b' } }); + st.deepEqual(qs.parse('a[0]=b&a[1]=c', { arrayLimit: 0 }), { a: { 0: 'b', 1: 'c' } }); + st.end(); + }); + + t.test('allows disabling array parsing', function (st) { + var indices = qs.parse('a[0]=b&a[1]=c', { parseArrays: false }); + st.deepEqual(indices, { a: { 0: 'b', 1: 'c' } }); + st.equal(Array.isArray(indices.a), false, 'parseArrays:false, indices case is not an array'); + + var emptyBrackets = qs.parse('a[]=b', { parseArrays: false }); + st.deepEqual(emptyBrackets, { a: { 0: 'b' } }); + st.equal(Array.isArray(emptyBrackets.a), false, 'parseArrays:false, empty brackets case is not an array'); + + st.end(); + }); + + t.test('allows for query string prefix', function (st) { + st.deepEqual(qs.parse('?foo=bar', { ignoreQueryPrefix: true }), { foo: 'bar' }); + st.deepEqual(qs.parse('foo=bar', { ignoreQueryPrefix: true }), { foo: 'bar' }); + st.deepEqual(qs.parse('?foo=bar', { ignoreQueryPrefix: false }), { '?foo': 'bar' }); + + st.end(); + }); + + t.test('parses an object', function (st) { + var input = { + 'user[name]': { 'pop[bob]': 3 }, + 'user[email]': null + }; + + var expected = { + user: { + name: { 'pop[bob]': 3 }, + email: null + } + }; + + var result = qs.parse(input); + + st.deepEqual(result, expected); + st.end(); + }); + + t.test('parses string with comma as array divider', function (st) { + st.deepEqual(qs.parse('foo=bar,tee', { comma: true }), { foo: ['bar', 'tee'] }); + st.deepEqual(qs.parse('foo[bar]=coffee,tee', { comma: true }), { foo: { bar: ['coffee', 'tee'] } }); + st.deepEqual(qs.parse('foo=', { comma: true }), { foo: '' }); + st.deepEqual(qs.parse('foo', { comma: true }), { foo: '' }); + st.deepEqual(qs.parse('foo', { comma: true, strictNullHandling: true }), { foo: null }); + + // test cases inversed from from stringify tests + st.deepEqual(qs.parse('a[0]=c'), { a: ['c'] }); + st.deepEqual(qs.parse('a[]=c'), { a: ['c'] }); + st.deepEqual(qs.parse('a[]=c', { comma: true }), { a: ['c'] }); + + st.deepEqual(qs.parse('a[0]=c&a[1]=d'), { a: ['c', 'd'] }); + st.deepEqual(qs.parse('a[]=c&a[]=d'), { a: ['c', 'd'] }); + st.deepEqual(qs.parse('a=c,d', { comma: true }), { a: ['c', 'd'] }); + + st.end(); + }); + + t.test('parses values with comma as array divider', function (st) { + st.deepEqual(qs.parse({ foo: 'bar,tee' }, { comma: false }), { foo: 'bar,tee' }); + st.deepEqual(qs.parse({ foo: 'bar,tee' }, { comma: true }), { foo: ['bar', 'tee'] }); + st.end(); + }); + + t.test('use number decoder, parses string that has one number with comma option enabled', function (st) { + var decoder = function (str, defaultDecoder, charset, type) { + if (!isNaN(Number(str))) { + return parseFloat(str); + } + return defaultDecoder(str, defaultDecoder, charset, type); + }; + + st.deepEqual(qs.parse('foo=1', { comma: true, decoder: decoder }), { foo: 1 }); + st.deepEqual(qs.parse('foo=0', { comma: true, decoder: decoder }), { foo: 0 }); + + st.end(); + }); + + t.test('parses brackets holds array of arrays when having two parts of strings with comma as array divider', function (st) { + st.deepEqual(qs.parse('foo[]=1,2,3&foo[]=4,5,6', { comma: true }), { foo: [['1', '2', '3'], ['4', '5', '6']] }); + st.deepEqual(qs.parse('foo[]=1,2,3&foo[]=', { comma: true }), { foo: [['1', '2', '3'], ''] }); + st.deepEqual(qs.parse('foo[]=1,2,3&foo[]=,', { comma: true }), { foo: [['1', '2', '3'], ['', '']] }); + st.deepEqual(qs.parse('foo[]=1,2,3&foo[]=a', { comma: true }), { foo: [['1', '2', '3'], 'a'] }); + + st.end(); + }); + + t.test('parses comma delimited array while having percent-encoded comma treated as normal text', function (st) { + st.deepEqual(qs.parse('foo=a%2Cb', { comma: true }), { foo: 'a,b' }); + st.deepEqual(qs.parse('foo=a%2C%20b,d', { comma: true }), { foo: ['a, b', 'd'] }); + st.deepEqual(qs.parse('foo=a%2C%20b,c%2C%20d', { comma: true }), { foo: ['a, b', 'c, d'] }); + + st.end(); + }); + + t.test('parses an object in dot notation', function (st) { + var input = { + 'user.name': { 'pop[bob]': 3 }, + 'user.email.': null + }; + + var expected = { + user: { + name: { 'pop[bob]': 3 }, + email: null + } + }; + + var result = qs.parse(input, { allowDots: true }); + + st.deepEqual(result, expected); + st.end(); + }); + + t.test('parses an object and not child values', function (st) { + var input = { + 'user[name]': { 'pop[bob]': { test: 3 } }, + 'user[email]': null + }; + + var expected = { + user: { + name: { 'pop[bob]': { test: 3 } }, + email: null + } + }; + + var result = qs.parse(input); + + st.deepEqual(result, expected); + st.end(); + }); + + t.test('does not blow up when Buffer global is missing', function (st) { + var tempBuffer = global.Buffer; + delete global.Buffer; + var result = qs.parse('a=b&c=d'); + global.Buffer = tempBuffer; + st.deepEqual(result, { a: 'b', c: 'd' }); + st.end(); + }); + + t.test('does not crash when parsing circular references', function (st) { + var a = {}; + a.b = a; + + var parsed; + + st.doesNotThrow(function () { + parsed = qs.parse({ 'foo[bar]': 'baz', 'foo[baz]': a }); + }); + + st.equal('foo' in parsed, true, 'parsed has "foo" property'); + st.equal('bar' in parsed.foo, true); + st.equal('baz' in parsed.foo, true); + st.equal(parsed.foo.bar, 'baz'); + st.deepEqual(parsed.foo.baz, a); + st.end(); + }); + + t.test('does not crash when parsing deep objects', function (st) { + var parsed; + var str = 'foo'; + + for (var i = 0; i < 5000; i++) { + str += '[p]'; + } + + str += '=bar'; + + st.doesNotThrow(function () { + parsed = qs.parse(str, { depth: 5000 }); + }); + + st.equal('foo' in parsed, true, 'parsed has "foo" property'); + + var depth = 0; + var ref = parsed.foo; + while ((ref = ref.p)) { + depth += 1; + } + + st.equal(depth, 5000, 'parsed is 5000 properties deep'); + + st.end(); + }); + + t.test('parses null objects correctly', { skip: !Object.create }, function (st) { + var a = Object.create(null); + a.b = 'c'; + + st.deepEqual(qs.parse(a), { b: 'c' }); + var result = qs.parse({ a: a }); + st.equal('a' in result, true, 'result has "a" property'); + st.deepEqual(result.a, a); + st.end(); + }); + + t.test('parses dates correctly', function (st) { + var now = new Date(); + st.deepEqual(qs.parse({ a: now }), { a: now }); + st.end(); + }); + + t.test('parses regular expressions correctly', function (st) { + var re = /^test$/; + st.deepEqual(qs.parse({ a: re }), { a: re }); + st.end(); + }); + + t.test('does not allow overwriting prototype properties', function (st) { + st.deepEqual(qs.parse('a[hasOwnProperty]=b', { allowPrototypes: false }), {}); + st.deepEqual(qs.parse('hasOwnProperty=b', { allowPrototypes: false }), {}); + + st.deepEqual( + qs.parse('toString', { allowPrototypes: false }), + {}, + 'bare "toString" results in {}' + ); + + st.end(); + }); + + t.test('can allow overwriting prototype properties', function (st) { + st.deepEqual(qs.parse('a[hasOwnProperty]=b', { allowPrototypes: true }), { a: { hasOwnProperty: 'b' } }); + st.deepEqual(qs.parse('hasOwnProperty=b', { allowPrototypes: true }), { hasOwnProperty: 'b' }); + + st.deepEqual( + qs.parse('toString', { allowPrototypes: true }), + { toString: '' }, + 'bare "toString" results in { toString: "" }' + ); + + st.end(); + }); + + t.test('params starting with a closing bracket', function (st) { + st.deepEqual(qs.parse(']=toString'), { ']': 'toString' }); + st.deepEqual(qs.parse(']]=toString'), { ']]': 'toString' }); + st.deepEqual(qs.parse(']hello]=toString'), { ']hello]': 'toString' }); + st.end(); + }); + + t.test('params starting with a starting bracket', function (st) { + st.deepEqual(qs.parse('[=toString'), { '[': 'toString' }); + st.deepEqual(qs.parse('[[=toString'), { '[[': 'toString' }); + st.deepEqual(qs.parse('[hello[=toString'), { '[hello[': 'toString' }); + st.end(); + }); + + t.test('add keys to objects', function (st) { + st.deepEqual( + qs.parse('a[b]=c&a=d'), + { a: { b: 'c', d: true } }, + 'can add keys to objects' + ); + + st.deepEqual( + qs.parse('a[b]=c&a=toString'), + { a: { b: 'c' } }, + 'can not overwrite prototype' + ); + + st.deepEqual( + qs.parse('a[b]=c&a=toString', { allowPrototypes: true }), + { a: { b: 'c', toString: true } }, + 'can overwrite prototype with allowPrototypes true' + ); + + st.deepEqual( + qs.parse('a[b]=c&a=toString', { plainObjects: true }), + { __proto__: null, a: { __proto__: null, b: 'c', toString: true } }, + 'can overwrite prototype with plainObjects true' + ); + + st.end(); + }); + + t.test('dunder proto is ignored', function (st) { + var payload = 'categories[__proto__]=login&categories[__proto__]&categories[length]=42'; + var result = qs.parse(payload, { allowPrototypes: true }); + + st.deepEqual( + result, + { + categories: { + length: '42' + } + }, + 'silent [[Prototype]] payload' + ); + + var plainResult = qs.parse(payload, { allowPrototypes: true, plainObjects: true }); + + st.deepEqual( + plainResult, + { + __proto__: null, + categories: { + __proto__: null, + length: '42' + } + }, + 'silent [[Prototype]] payload: plain objects' + ); + + var query = qs.parse('categories[__proto__]=cats&categories[__proto__]=dogs&categories[some][json]=toInject', { allowPrototypes: true }); + + st.notOk(Array.isArray(query.categories), 'is not an array'); + st.notOk(query.categories instanceof Array, 'is not instanceof an array'); + st.deepEqual(query.categories, { some: { json: 'toInject' } }); + st.equal(JSON.stringify(query.categories), '{"some":{"json":"toInject"}}', 'stringifies as a non-array'); + + st.deepEqual( + qs.parse('foo[__proto__][hidden]=value&foo[bar]=stuffs', { allowPrototypes: true }), + { + foo: { + bar: 'stuffs' + } + }, + 'hidden values' + ); + + st.deepEqual( + qs.parse('foo[__proto__][hidden]=value&foo[bar]=stuffs', { allowPrototypes: true, plainObjects: true }), + { + __proto__: null, + foo: { + __proto__: null, + bar: 'stuffs' + } + }, + 'hidden values: plain objects' + ); + + st.end(); + }); + + t.test('can return null objects', { skip: !Object.create }, function (st) { + var expected = Object.create(null); + expected.a = Object.create(null); + expected.a.b = 'c'; + expected.a.hasOwnProperty = 'd'; + st.deepEqual(qs.parse('a[b]=c&a[hasOwnProperty]=d', { plainObjects: true }), expected); + st.deepEqual(qs.parse(null, { plainObjects: true }), Object.create(null)); + var expectedArray = Object.create(null); + expectedArray.a = Object.create(null); + expectedArray.a[0] = 'b'; + expectedArray.a.c = 'd'; + st.deepEqual(qs.parse('a[]=b&a[c]=d', { plainObjects: true }), expectedArray); + st.end(); + }); + + t.test('can parse with custom encoding', function (st) { + st.deepEqual(qs.parse('%8c%a7=%91%e5%8d%e3%95%7b', { + decoder: function (str) { + var reg = /%([0-9A-F]{2})/ig; + var result = []; + var parts = reg.exec(str); + while (parts) { + result.push(parseInt(parts[1], 16)); + parts = reg.exec(str); + } + return String(iconv.decode(SaferBuffer.from(result), 'shift_jis')); + } + }), { 県: '大阪府' }); + st.end(); + }); + + t.test('receives the default decoder as a second argument', function (st) { + st.plan(1); + qs.parse('a', { + decoder: function (str, defaultDecoder) { + st.equal(defaultDecoder, utils.decode); + } + }); + st.end(); + }); + + t.test('throws error with wrong decoder', function (st) { + st['throws'](function () { + qs.parse({}, { decoder: 'string' }); + }, new TypeError('Decoder has to be a function.')); + st.end(); + }); + + t.test('does not mutate the options argument', function (st) { + var options = {}; + qs.parse('a[b]=true', options); + st.deepEqual(options, {}); + st.end(); + }); + + t.test('throws if an invalid charset is specified', function (st) { + st['throws'](function () { + qs.parse('a=b', { charset: 'foobar' }); + }, new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined')); + st.end(); + }); + + t.test('parses an iso-8859-1 string if asked to', function (st) { + st.deepEqual(qs.parse('%A2=%BD', { charset: 'iso-8859-1' }), { '¢': '½' }); + st.end(); + }); + + var urlEncodedCheckmarkInUtf8 = '%E2%9C%93'; + var urlEncodedOSlashInUtf8 = '%C3%B8'; + var urlEncodedNumCheckmark = '%26%2310003%3B'; + var urlEncodedNumSmiley = '%26%239786%3B'; + + t.test('prefers an utf-8 charset specified by the utf8 sentinel to a default charset of iso-8859-1', function (st) { + st.deepEqual(qs.parse('utf8=' + urlEncodedCheckmarkInUtf8 + '&' + urlEncodedOSlashInUtf8 + '=' + urlEncodedOSlashInUtf8, { charsetSentinel: true, charset: 'iso-8859-1' }), { ø: 'ø' }); + st.end(); + }); + + t.test('prefers an iso-8859-1 charset specified by the utf8 sentinel to a default charset of utf-8', function (st) { + st.deepEqual(qs.parse('utf8=' + urlEncodedNumCheckmark + '&' + urlEncodedOSlashInUtf8 + '=' + urlEncodedOSlashInUtf8, { charsetSentinel: true, charset: 'utf-8' }), { 'ø': 'ø' }); + st.end(); + }); + + t.test('does not require the utf8 sentinel to be defined before the parameters whose decoding it affects', function (st) { + st.deepEqual(qs.parse('a=' + urlEncodedOSlashInUtf8 + '&utf8=' + urlEncodedNumCheckmark, { charsetSentinel: true, charset: 'utf-8' }), { a: 'ø' }); + st.end(); + }); + + t.test('should ignore an utf8 sentinel with an unknown value', function (st) { + st.deepEqual(qs.parse('utf8=foo&' + urlEncodedOSlashInUtf8 + '=' + urlEncodedOSlashInUtf8, { charsetSentinel: true, charset: 'utf-8' }), { ø: 'ø' }); + st.end(); + }); + + t.test('uses the utf8 sentinel to switch to utf-8 when no default charset is given', function (st) { + st.deepEqual(qs.parse('utf8=' + urlEncodedCheckmarkInUtf8 + '&' + urlEncodedOSlashInUtf8 + '=' + urlEncodedOSlashInUtf8, { charsetSentinel: true }), { ø: 'ø' }); + st.end(); + }); + + t.test('uses the utf8 sentinel to switch to iso-8859-1 when no default charset is given', function (st) { + st.deepEqual(qs.parse('utf8=' + urlEncodedNumCheckmark + '&' + urlEncodedOSlashInUtf8 + '=' + urlEncodedOSlashInUtf8, { charsetSentinel: true }), { 'ø': 'ø' }); + st.end(); + }); + + t.test('interprets numeric entities in iso-8859-1 when `interpretNumericEntities`', function (st) { + st.deepEqual(qs.parse('foo=' + urlEncodedNumSmiley, { charset: 'iso-8859-1', interpretNumericEntities: true }), { foo: '☺' }); + st.end(); + }); + + t.test('handles a custom decoder returning `null`, in the `iso-8859-1` charset, when `interpretNumericEntities`', function (st) { + st.deepEqual(qs.parse('foo=&bar=' + urlEncodedNumSmiley, { + charset: 'iso-8859-1', + decoder: function (str, defaultDecoder, charset) { + return str ? defaultDecoder(str, defaultDecoder, charset) : null; + }, + interpretNumericEntities: true + }), { foo: null, bar: '☺' }); + st.end(); + }); + + t.test('does not interpret numeric entities in iso-8859-1 when `interpretNumericEntities` is absent', function (st) { + st.deepEqual(qs.parse('foo=' + urlEncodedNumSmiley, { charset: 'iso-8859-1' }), { foo: '☺' }); + st.end(); + }); + + t.test('does not interpret numeric entities when the charset is utf-8, even when `interpretNumericEntities`', function (st) { + st.deepEqual(qs.parse('foo=' + urlEncodedNumSmiley, { charset: 'utf-8', interpretNumericEntities: true }), { foo: '☺' }); + st.end(); + }); + + t.test('does not interpret %uXXXX syntax in iso-8859-1 mode', function (st) { + st.deepEqual(qs.parse('%u263A=%u263A', { charset: 'iso-8859-1' }), { '%u263A': '%u263A' }); + st.end(); + }); + + t.test('allows for decoding keys and values differently', function (st) { + var decoder = function (str, defaultDecoder, charset, type) { + if (type === 'key') { + return defaultDecoder(str, defaultDecoder, charset, type).toLowerCase(); + } + if (type === 'value') { + return defaultDecoder(str, defaultDecoder, charset, type).toUpperCase(); + } + throw 'this should never happen! type: ' + type; + }; + + st.deepEqual(qs.parse('KeY=vAlUe', { decoder: decoder }), { key: 'VALUE' }); + st.end(); + }); + + t.end(); +}); diff --git a/backend/node_modules/qs/test/stringify.js b/backend/node_modules/qs/test/stringify.js new file mode 100644 index 0000000000000000000000000000000000000000..f0cdfefadca42648a4c8712ac6e16c3d12906c92 --- /dev/null +++ b/backend/node_modules/qs/test/stringify.js @@ -0,0 +1,909 @@ +'use strict'; + +var test = require('tape'); +var qs = require('../'); +var utils = require('../lib/utils'); +var iconv = require('iconv-lite'); +var SaferBuffer = require('safer-buffer').Buffer; +var hasSymbols = require('has-symbols'); +var hasBigInt = typeof BigInt === 'function'; + +test('stringify()', function (t) { + t.test('stringifies a querystring object', function (st) { + st.equal(qs.stringify({ a: 'b' }), 'a=b'); + st.equal(qs.stringify({ a: 1 }), 'a=1'); + st.equal(qs.stringify({ a: 1, b: 2 }), 'a=1&b=2'); + st.equal(qs.stringify({ a: 'A_Z' }), 'a=A_Z'); + st.equal(qs.stringify({ a: '€' }), 'a=%E2%82%AC'); + st.equal(qs.stringify({ a: '' }), 'a=%EE%80%80'); + st.equal(qs.stringify({ a: 'א' }), 'a=%D7%90'); + st.equal(qs.stringify({ a: '𐐷' }), 'a=%F0%90%90%B7'); + st.end(); + }); + + t.test('stringifies falsy values', function (st) { + st.equal(qs.stringify(undefined), ''); + st.equal(qs.stringify(null), ''); + st.equal(qs.stringify(null, { strictNullHandling: true }), ''); + st.equal(qs.stringify(false), ''); + st.equal(qs.stringify(0), ''); + st.end(); + }); + + t.test('stringifies symbols', { skip: !hasSymbols() }, function (st) { + st.equal(qs.stringify(Symbol.iterator), ''); + st.equal(qs.stringify([Symbol.iterator]), '0=Symbol%28Symbol.iterator%29'); + st.equal(qs.stringify({ a: Symbol.iterator }), 'a=Symbol%28Symbol.iterator%29'); + st.equal( + qs.stringify({ a: [Symbol.iterator] }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), + 'a[]=Symbol%28Symbol.iterator%29' + ); + st.end(); + }); + + t.test('stringifies bigints', { skip: !hasBigInt }, function (st) { + var three = BigInt(3); + var encodeWithN = function (value, defaultEncoder, charset) { + var result = defaultEncoder(value, defaultEncoder, charset); + return typeof value === 'bigint' ? result + 'n' : result; + }; + st.equal(qs.stringify(three), ''); + st.equal(qs.stringify([three]), '0=3'); + st.equal(qs.stringify([three], { encoder: encodeWithN }), '0=3n'); + st.equal(qs.stringify({ a: three }), 'a=3'); + st.equal(qs.stringify({ a: three }, { encoder: encodeWithN }), 'a=3n'); + st.equal( + qs.stringify({ a: [three] }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), + 'a[]=3' + ); + st.equal( + qs.stringify({ a: [three] }, { encodeValuesOnly: true, encoder: encodeWithN, arrayFormat: 'brackets' }), + 'a[]=3n' + ); + st.end(); + }); + + t.test('adds query prefix', function (st) { + st.equal(qs.stringify({ a: 'b' }, { addQueryPrefix: true }), '?a=b'); + st.end(); + }); + + t.test('with query prefix, outputs blank string given an empty object', function (st) { + st.equal(qs.stringify({}, { addQueryPrefix: true }), ''); + st.end(); + }); + + t.test('stringifies nested falsy values', function (st) { + st.equal(qs.stringify({ a: { b: { c: null } } }), 'a%5Bb%5D%5Bc%5D='); + st.equal(qs.stringify({ a: { b: { c: null } } }, { strictNullHandling: true }), 'a%5Bb%5D%5Bc%5D'); + st.equal(qs.stringify({ a: { b: { c: false } } }), 'a%5Bb%5D%5Bc%5D=false'); + st.end(); + }); + + t.test('stringifies a nested object', function (st) { + st.equal(qs.stringify({ a: { b: 'c' } }), 'a%5Bb%5D=c'); + st.equal(qs.stringify({ a: { b: { c: { d: 'e' } } } }), 'a%5Bb%5D%5Bc%5D%5Bd%5D=e'); + st.end(); + }); + + t.test('stringifies a nested object with dots notation', function (st) { + st.equal(qs.stringify({ a: { b: 'c' } }, { allowDots: true }), 'a.b=c'); + st.equal(qs.stringify({ a: { b: { c: { d: 'e' } } } }, { allowDots: true }), 'a.b.c.d=e'); + st.end(); + }); + + t.test('stringifies an array value', function (st) { + st.equal( + qs.stringify({ a: ['b', 'c', 'd'] }, { arrayFormat: 'indices' }), + 'a%5B0%5D=b&a%5B1%5D=c&a%5B2%5D=d', + 'indices => indices' + ); + st.equal( + qs.stringify({ a: ['b', 'c', 'd'] }, { arrayFormat: 'brackets' }), + 'a%5B%5D=b&a%5B%5D=c&a%5B%5D=d', + 'brackets => brackets' + ); + st.equal( + qs.stringify({ a: ['b', 'c', 'd'] }, { arrayFormat: 'comma' }), + 'a=b%2Cc%2Cd', + 'comma => comma' + ); + st.equal( + qs.stringify({ a: ['b', 'c', 'd'] }), + 'a%5B0%5D=b&a%5B1%5D=c&a%5B2%5D=d', + 'default => indices' + ); + st.end(); + }); + + t.test('omits nulls when asked', function (st) { + st.equal(qs.stringify({ a: 'b', c: null }, { skipNulls: true }), 'a=b'); + st.end(); + }); + + t.test('omits nested nulls when asked', function (st) { + st.equal(qs.stringify({ a: { b: 'c', d: null } }, { skipNulls: true }), 'a%5Bb%5D=c'); + st.end(); + }); + + t.test('omits array indices when asked', function (st) { + st.equal(qs.stringify({ a: ['b', 'c', 'd'] }, { indices: false }), 'a=b&a=c&a=d'); + st.end(); + }); + + t.test('stringifies an array value with one item vs multiple items', function (st) { + st.test('non-array item', function (s2t) { + s2t.equal(qs.stringify({ a: 'c' }, { encodeValuesOnly: true, arrayFormat: 'indices' }), 'a=c'); + s2t.equal(qs.stringify({ a: 'c' }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), 'a=c'); + s2t.equal(qs.stringify({ a: 'c' }, { encodeValuesOnly: true, arrayFormat: 'comma' }), 'a=c'); + s2t.equal(qs.stringify({ a: 'c' }, { encodeValuesOnly: true }), 'a=c'); + + s2t.end(); + }); + + st.test('array with a single item', function (s2t) { + s2t.equal(qs.stringify({ a: ['c'] }, { encodeValuesOnly: true, arrayFormat: 'indices' }), 'a[0]=c'); + s2t.equal(qs.stringify({ a: ['c'] }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), 'a[]=c'); + s2t.equal(qs.stringify({ a: ['c'] }, { encodeValuesOnly: true, arrayFormat: 'comma' }), 'a=c'); + s2t.equal(qs.stringify({ a: ['c'] }, { encodeValuesOnly: true, arrayFormat: 'comma', commaRoundTrip: true }), 'a[]=c'); // so it parses back as an array + s2t.equal(qs.stringify({ a: ['c'] }, { encodeValuesOnly: true }), 'a[0]=c'); + + s2t.end(); + }); + + st.test('array with multiple items', function (s2t) { + s2t.equal(qs.stringify({ a: ['c', 'd'] }, { encodeValuesOnly: true, arrayFormat: 'indices' }), 'a[0]=c&a[1]=d'); + s2t.equal(qs.stringify({ a: ['c', 'd'] }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), 'a[]=c&a[]=d'); + s2t.equal(qs.stringify({ a: ['c', 'd'] }, { encodeValuesOnly: true, arrayFormat: 'comma' }), 'a=c,d'); + s2t.equal(qs.stringify({ a: ['c', 'd'] }, { encodeValuesOnly: true }), 'a[0]=c&a[1]=d'); + + s2t.end(); + }); + + st.end(); + }); + + t.test('stringifies a nested array value', function (st) { + st.equal(qs.stringify({ a: { b: ['c', 'd'] } }, { encodeValuesOnly: true, arrayFormat: 'indices' }), 'a[b][0]=c&a[b][1]=d'); + st.equal(qs.stringify({ a: { b: ['c', 'd'] } }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), 'a[b][]=c&a[b][]=d'); + st.equal(qs.stringify({ a: { b: ['c', 'd'] } }, { encodeValuesOnly: true, arrayFormat: 'comma' }), 'a[b]=c,d'); + st.equal(qs.stringify({ a: { b: ['c', 'd'] } }, { encodeValuesOnly: true }), 'a[b][0]=c&a[b][1]=d'); + st.end(); + }); + + t.test('stringifies a nested array value with dots notation', function (st) { + st.equal( + qs.stringify( + { a: { b: ['c', 'd'] } }, + { allowDots: true, encodeValuesOnly: true, arrayFormat: 'indices' } + ), + 'a.b[0]=c&a.b[1]=d', + 'indices: stringifies with dots + indices' + ); + st.equal( + qs.stringify( + { a: { b: ['c', 'd'] } }, + { allowDots: true, encodeValuesOnly: true, arrayFormat: 'brackets' } + ), + 'a.b[]=c&a.b[]=d', + 'brackets: stringifies with dots + brackets' + ); + st.equal( + qs.stringify( + { a: { b: ['c', 'd'] } }, + { allowDots: true, encodeValuesOnly: true, arrayFormat: 'comma' } + ), + 'a.b=c,d', + 'comma: stringifies with dots + comma' + ); + st.equal( + qs.stringify( + { a: { b: ['c', 'd'] } }, + { allowDots: true, encodeValuesOnly: true } + ), + 'a.b[0]=c&a.b[1]=d', + 'default: stringifies with dots + indices' + ); + st.end(); + }); + + t.test('stringifies an object inside an array', function (st) { + st.equal( + qs.stringify({ a: [{ b: 'c' }] }, { arrayFormat: 'indices' }), + 'a%5B0%5D%5Bb%5D=c', // a[0][b]=c + 'indices => brackets' + ); + st.equal( + qs.stringify({ a: [{ b: 'c' }] }, { arrayFormat: 'brackets' }), + 'a%5B%5D%5Bb%5D=c', // a[][b]=c + 'brackets => brackets' + ); + st.equal( + qs.stringify({ a: [{ b: 'c' }] }), + 'a%5B0%5D%5Bb%5D=c', + 'default => indices' + ); + + st.equal( + qs.stringify({ a: [{ b: { c: [1] } }] }, { arrayFormat: 'indices' }), + 'a%5B0%5D%5Bb%5D%5Bc%5D%5B0%5D=1', + 'indices => indices' + ); + + st.equal( + qs.stringify({ a: [{ b: { c: [1] } }] }, { arrayFormat: 'brackets' }), + 'a%5B%5D%5Bb%5D%5Bc%5D%5B%5D=1', + 'brackets => brackets' + ); + + st.equal( + qs.stringify({ a: [{ b: { c: [1] } }] }), + 'a%5B0%5D%5Bb%5D%5Bc%5D%5B0%5D=1', + 'default => indices' + ); + + st.end(); + }); + + t.test('stringifies an array with mixed objects and primitives', function (st) { + st.equal( + qs.stringify({ a: [{ b: 1 }, 2, 3] }, { encodeValuesOnly: true, arrayFormat: 'indices' }), + 'a[0][b]=1&a[1]=2&a[2]=3', + 'indices => indices' + ); + st.equal( + qs.stringify({ a: [{ b: 1 }, 2, 3] }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), + 'a[][b]=1&a[]=2&a[]=3', + 'brackets => brackets' + ); + st.equal( + qs.stringify({ a: [{ b: 1 }, 2, 3] }, { encodeValuesOnly: true, arrayFormat: 'comma' }), + '???', + 'brackets => brackets', + { skip: 'TODO: figure out what this should do' } + ); + st.equal( + qs.stringify({ a: [{ b: 1 }, 2, 3] }, { encodeValuesOnly: true }), + 'a[0][b]=1&a[1]=2&a[2]=3', + 'default => indices' + ); + + st.end(); + }); + + t.test('stringifies an object inside an array with dots notation', function (st) { + st.equal( + qs.stringify( + { a: [{ b: 'c' }] }, + { allowDots: true, encode: false, arrayFormat: 'indices' } + ), + 'a[0].b=c', + 'indices => indices' + ); + st.equal( + qs.stringify( + { a: [{ b: 'c' }] }, + { allowDots: true, encode: false, arrayFormat: 'brackets' } + ), + 'a[].b=c', + 'brackets => brackets' + ); + st.equal( + qs.stringify( + { a: [{ b: 'c' }] }, + { allowDots: true, encode: false } + ), + 'a[0].b=c', + 'default => indices' + ); + + st.equal( + qs.stringify( + { a: [{ b: { c: [1] } }] }, + { allowDots: true, encode: false, arrayFormat: 'indices' } + ), + 'a[0].b.c[0]=1', + 'indices => indices' + ); + st.equal( + qs.stringify( + { a: [{ b: { c: [1] } }] }, + { allowDots: true, encode: false, arrayFormat: 'brackets' } + ), + 'a[].b.c[]=1', + 'brackets => brackets' + ); + st.equal( + qs.stringify( + { a: [{ b: { c: [1] } }] }, + { allowDots: true, encode: false } + ), + 'a[0].b.c[0]=1', + 'default => indices' + ); + + st.end(); + }); + + t.test('does not omit object keys when indices = false', function (st) { + st.equal(qs.stringify({ a: [{ b: 'c' }] }, { indices: false }), 'a%5Bb%5D=c'); + st.end(); + }); + + t.test('uses indices notation for arrays when indices=true', function (st) { + st.equal(qs.stringify({ a: ['b', 'c'] }, { indices: true }), 'a%5B0%5D=b&a%5B1%5D=c'); + st.end(); + }); + + t.test('uses indices notation for arrays when no arrayFormat is specified', function (st) { + st.equal(qs.stringify({ a: ['b', 'c'] }), 'a%5B0%5D=b&a%5B1%5D=c'); + st.end(); + }); + + t.test('uses indices notation for arrays when no arrayFormat=indices', function (st) { + st.equal(qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'indices' }), 'a%5B0%5D=b&a%5B1%5D=c'); + st.end(); + }); + + t.test('uses repeat notation for arrays when no arrayFormat=repeat', function (st) { + st.equal(qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'repeat' }), 'a=b&a=c'); + st.end(); + }); + + t.test('uses brackets notation for arrays when no arrayFormat=brackets', function (st) { + st.equal(qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'brackets' }), 'a%5B%5D=b&a%5B%5D=c'); + st.end(); + }); + + t.test('stringifies a complicated object', function (st) { + st.equal(qs.stringify({ a: { b: 'c', d: 'e' } }), 'a%5Bb%5D=c&a%5Bd%5D=e'); + st.end(); + }); + + t.test('stringifies an empty value', function (st) { + st.equal(qs.stringify({ a: '' }), 'a='); + st.equal(qs.stringify({ a: null }, { strictNullHandling: true }), 'a'); + + st.equal(qs.stringify({ a: '', b: '' }), 'a=&b='); + st.equal(qs.stringify({ a: null, b: '' }, { strictNullHandling: true }), 'a&b='); + + st.equal(qs.stringify({ a: { b: '' } }), 'a%5Bb%5D='); + st.equal(qs.stringify({ a: { b: null } }, { strictNullHandling: true }), 'a%5Bb%5D'); + st.equal(qs.stringify({ a: { b: null } }, { strictNullHandling: false }), 'a%5Bb%5D='); + + st.end(); + }); + + t.test('stringifies an empty array in different arrayFormat', function (st) { + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false }), 'b[0]=&c=c'); + // arrayFormat default + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'indices' }), 'b[0]=&c=c'); + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'brackets' }), 'b[]=&c=c'); + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'repeat' }), 'b=&c=c'); + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'comma' }), 'b=&c=c'); + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'comma', commaRoundTrip: true }), 'b[]=&c=c'); + // with strictNullHandling + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'indices', strictNullHandling: true }), 'b[0]&c=c'); + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'brackets', strictNullHandling: true }), 'b[]&c=c'); + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'repeat', strictNullHandling: true }), 'b&c=c'); + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'comma', strictNullHandling: true }), 'b&c=c'); + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'comma', strictNullHandling: true, commaRoundTrip: true }), 'b[]&c=c'); + // with skipNulls + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'indices', skipNulls: true }), 'c=c'); + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'brackets', skipNulls: true }), 'c=c'); + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'repeat', skipNulls: true }), 'c=c'); + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'comma', skipNulls: true }), 'c=c'); + + st.end(); + }); + + t.test('stringifies a null object', { skip: !Object.create }, function (st) { + var obj = Object.create(null); + obj.a = 'b'; + st.equal(qs.stringify(obj), 'a=b'); + st.end(); + }); + + t.test('returns an empty string for invalid input', function (st) { + st.equal(qs.stringify(undefined), ''); + st.equal(qs.stringify(false), ''); + st.equal(qs.stringify(null), ''); + st.equal(qs.stringify(''), ''); + st.end(); + }); + + t.test('stringifies an object with a null object as a child', { skip: !Object.create }, function (st) { + var obj = { a: Object.create(null) }; + + obj.a.b = 'c'; + st.equal(qs.stringify(obj), 'a%5Bb%5D=c'); + st.end(); + }); + + t.test('drops keys with a value of undefined', function (st) { + st.equal(qs.stringify({ a: undefined }), ''); + + st.equal(qs.stringify({ a: { b: undefined, c: null } }, { strictNullHandling: true }), 'a%5Bc%5D'); + st.equal(qs.stringify({ a: { b: undefined, c: null } }, { strictNullHandling: false }), 'a%5Bc%5D='); + st.equal(qs.stringify({ a: { b: undefined, c: '' } }), 'a%5Bc%5D='); + st.end(); + }); + + t.test('url encodes values', function (st) { + st.equal(qs.stringify({ a: 'b c' }), 'a=b%20c'); + st.end(); + }); + + t.test('stringifies a date', function (st) { + var now = new Date(); + var str = 'a=' + encodeURIComponent(now.toISOString()); + st.equal(qs.stringify({ a: now }), str); + st.end(); + }); + + t.test('stringifies the weird object from qs', function (st) { + st.equal(qs.stringify({ 'my weird field': '~q1!2"\'w$5&7/z8)?' }), 'my%20weird%20field=~q1%212%22%27w%245%267%2Fz8%29%3F'); + st.end(); + }); + + t.test('skips properties that are part of the object prototype', function (st) { + Object.prototype.crash = 'test'; + st.equal(qs.stringify({ a: 'b' }), 'a=b'); + st.equal(qs.stringify({ a: { b: 'c' } }), 'a%5Bb%5D=c'); + delete Object.prototype.crash; + st.end(); + }); + + t.test('stringifies boolean values', function (st) { + st.equal(qs.stringify({ a: true }), 'a=true'); + st.equal(qs.stringify({ a: { b: true } }), 'a%5Bb%5D=true'); + st.equal(qs.stringify({ b: false }), 'b=false'); + st.equal(qs.stringify({ b: { c: false } }), 'b%5Bc%5D=false'); + st.end(); + }); + + t.test('stringifies buffer values', function (st) { + st.equal(qs.stringify({ a: SaferBuffer.from('test') }), 'a=test'); + st.equal(qs.stringify({ a: { b: SaferBuffer.from('test') } }), 'a%5Bb%5D=test'); + st.end(); + }); + + t.test('stringifies an object using an alternative delimiter', function (st) { + st.equal(qs.stringify({ a: 'b', c: 'd' }, { delimiter: ';' }), 'a=b;c=d'); + st.end(); + }); + + t.test('does not blow up when Buffer global is missing', function (st) { + var tempBuffer = global.Buffer; + delete global.Buffer; + var result = qs.stringify({ a: 'b', c: 'd' }); + global.Buffer = tempBuffer; + st.equal(result, 'a=b&c=d'); + st.end(); + }); + + t.test('does not crash when parsing circular references', function (st) { + var a = {}; + a.b = a; + + st['throws']( + function () { qs.stringify({ 'foo[bar]': 'baz', 'foo[baz]': a }); }, + /RangeError: Cyclic object value/, + 'cyclic values throw' + ); + + var circular = { + a: 'value' + }; + circular.a = circular; + st['throws']( + function () { qs.stringify(circular); }, + /RangeError: Cyclic object value/, + 'cyclic values throw' + ); + + var arr = ['a']; + st.doesNotThrow( + function () { qs.stringify({ x: arr, y: arr }); }, + 'non-cyclic values do not throw' + ); + + st.end(); + }); + + t.test('non-circular duplicated references can still work', function (st) { + var hourOfDay = { + 'function': 'hour_of_day' + }; + + var p1 = { + 'function': 'gte', + arguments: [hourOfDay, 0] + }; + var p2 = { + 'function': 'lte', + arguments: [hourOfDay, 23] + }; + + st.equal( + qs.stringify({ filters: { $and: [p1, p2] } }, { encodeValuesOnly: true }), + 'filters[$and][0][function]=gte&filters[$and][0][arguments][0][function]=hour_of_day&filters[$and][0][arguments][1]=0&filters[$and][1][function]=lte&filters[$and][1][arguments][0][function]=hour_of_day&filters[$and][1][arguments][1]=23' + ); + + st.end(); + }); + + t.test('selects properties when filter=array', function (st) { + st.equal(qs.stringify({ a: 'b' }, { filter: ['a'] }), 'a=b'); + st.equal(qs.stringify({ a: 1 }, { filter: [] }), ''); + + st.equal( + qs.stringify( + { a: { b: [1, 2, 3, 4], c: 'd' }, c: 'f' }, + { filter: ['a', 'b', 0, 2], arrayFormat: 'indices' } + ), + 'a%5Bb%5D%5B0%5D=1&a%5Bb%5D%5B2%5D=3', + 'indices => indices' + ); + st.equal( + qs.stringify( + { a: { b: [1, 2, 3, 4], c: 'd' }, c: 'f' }, + { filter: ['a', 'b', 0, 2], arrayFormat: 'brackets' } + ), + 'a%5Bb%5D%5B%5D=1&a%5Bb%5D%5B%5D=3', + 'brackets => brackets' + ); + st.equal( + qs.stringify( + { a: { b: [1, 2, 3, 4], c: 'd' }, c: 'f' }, + { filter: ['a', 'b', 0, 2] } + ), + 'a%5Bb%5D%5B0%5D=1&a%5Bb%5D%5B2%5D=3', + 'default => indices' + ); + + st.end(); + }); + + t.test('supports custom representations when filter=function', function (st) { + var calls = 0; + var obj = { a: 'b', c: 'd', e: { f: new Date(1257894000000) } }; + var filterFunc = function (prefix, value) { + calls += 1; + if (calls === 1) { + st.equal(prefix, '', 'prefix is empty'); + st.equal(value, obj); + } else if (prefix === 'c') { + return void 0; + } else if (value instanceof Date) { + st.equal(prefix, 'e[f]'); + return value.getTime(); + } + return value; + }; + + st.equal(qs.stringify(obj, { filter: filterFunc }), 'a=b&e%5Bf%5D=1257894000000'); + st.equal(calls, 5); + st.end(); + }); + + t.test('can disable uri encoding', function (st) { + st.equal(qs.stringify({ a: 'b' }, { encode: false }), 'a=b'); + st.equal(qs.stringify({ a: { b: 'c' } }, { encode: false }), 'a[b]=c'); + st.equal(qs.stringify({ a: 'b', c: null }, { strictNullHandling: true, encode: false }), 'a=b&c'); + st.end(); + }); + + t.test('can sort the keys', function (st) { + var sort = function (a, b) { + return a.localeCompare(b); + }; + st.equal(qs.stringify({ a: 'c', z: 'y', b: 'f' }, { sort: sort }), 'a=c&b=f&z=y'); + st.equal(qs.stringify({ a: 'c', z: { j: 'a', i: 'b' }, b: 'f' }, { sort: sort }), 'a=c&b=f&z%5Bi%5D=b&z%5Bj%5D=a'); + st.end(); + }); + + t.test('can sort the keys at depth 3 or more too', function (st) { + var sort = function (a, b) { + return a.localeCompare(b); + }; + st.equal( + qs.stringify( + { a: 'a', z: { zj: { zjb: 'zjb', zja: 'zja' }, zi: { zib: 'zib', zia: 'zia' } }, b: 'b' }, + { sort: sort, encode: false } + ), + 'a=a&b=b&z[zi][zia]=zia&z[zi][zib]=zib&z[zj][zja]=zja&z[zj][zjb]=zjb' + ); + st.equal( + qs.stringify( + { a: 'a', z: { zj: { zjb: 'zjb', zja: 'zja' }, zi: { zib: 'zib', zia: 'zia' } }, b: 'b' }, + { sort: null, encode: false } + ), + 'a=a&z[zj][zjb]=zjb&z[zj][zja]=zja&z[zi][zib]=zib&z[zi][zia]=zia&b=b' + ); + st.end(); + }); + + t.test('can stringify with custom encoding', function (st) { + st.equal(qs.stringify({ 県: '大阪府', '': '' }, { + encoder: function (str) { + if (str.length === 0) { + return ''; + } + var buf = iconv.encode(str, 'shiftjis'); + var result = []; + for (var i = 0; i < buf.length; ++i) { + result.push(buf.readUInt8(i).toString(16)); + } + return '%' + result.join('%'); + } + }), '%8c%a7=%91%e5%8d%e3%95%7b&='); + st.end(); + }); + + t.test('receives the default encoder as a second argument', function (st) { + st.plan(2); + qs.stringify({ a: 1 }, { + encoder: function (str, defaultEncoder) { + st.equal(defaultEncoder, utils.encode); + } + }); + st.end(); + }); + + t.test('throws error with wrong encoder', function (st) { + st['throws'](function () { + qs.stringify({}, { encoder: 'string' }); + }, new TypeError('Encoder has to be a function.')); + st.end(); + }); + + t.test('can use custom encoder for a buffer object', { skip: typeof Buffer === 'undefined' }, function (st) { + st.equal(qs.stringify({ a: SaferBuffer.from([1]) }, { + encoder: function (buffer) { + if (typeof buffer === 'string') { + return buffer; + } + return String.fromCharCode(buffer.readUInt8(0) + 97); + } + }), 'a=b'); + + st.equal(qs.stringify({ a: SaferBuffer.from('a b') }, { + encoder: function (buffer) { + return buffer; + } + }), 'a=a b'); + st.end(); + }); + + t.test('serializeDate option', function (st) { + var date = new Date(); + st.equal( + qs.stringify({ a: date }), + 'a=' + date.toISOString().replace(/:/g, '%3A'), + 'default is toISOString' + ); + + var mutatedDate = new Date(); + mutatedDate.toISOString = function () { + throw new SyntaxError(); + }; + st['throws'](function () { + mutatedDate.toISOString(); + }, SyntaxError); + st.equal( + qs.stringify({ a: mutatedDate }), + 'a=' + Date.prototype.toISOString.call(mutatedDate).replace(/:/g, '%3A'), + 'toISOString works even when method is not locally present' + ); + + var specificDate = new Date(6); + st.equal( + qs.stringify( + { a: specificDate }, + { serializeDate: function (d) { return d.getTime() * 7; } } + ), + 'a=42', + 'custom serializeDate function called' + ); + + st.equal( + qs.stringify( + { a: [date] }, + { + serializeDate: function (d) { return d.getTime(); }, + arrayFormat: 'comma' + } + ), + 'a=' + date.getTime(), + 'works with arrayFormat comma' + ); + st.equal( + qs.stringify( + { a: [date] }, + { + serializeDate: function (d) { return d.getTime(); }, + arrayFormat: 'comma', + commaRoundTrip: true + } + ), + 'a%5B%5D=' + date.getTime(), + 'works with arrayFormat comma' + ); + + st.end(); + }); + + t.test('RFC 1738 serialization', function (st) { + st.equal(qs.stringify({ a: 'b c' }, { format: qs.formats.RFC1738 }), 'a=b+c'); + st.equal(qs.stringify({ 'a b': 'c d' }, { format: qs.formats.RFC1738 }), 'a+b=c+d'); + st.equal(qs.stringify({ 'a b': SaferBuffer.from('a b') }, { format: qs.formats.RFC1738 }), 'a+b=a+b'); + + st.equal(qs.stringify({ 'foo(ref)': 'bar' }, { format: qs.formats.RFC1738 }), 'foo(ref)=bar'); + + st.end(); + }); + + t.test('RFC 3986 spaces serialization', function (st) { + st.equal(qs.stringify({ a: 'b c' }, { format: qs.formats.RFC3986 }), 'a=b%20c'); + st.equal(qs.stringify({ 'a b': 'c d' }, { format: qs.formats.RFC3986 }), 'a%20b=c%20d'); + st.equal(qs.stringify({ 'a b': SaferBuffer.from('a b') }, { format: qs.formats.RFC3986 }), 'a%20b=a%20b'); + + st.end(); + }); + + t.test('Backward compatibility to RFC 3986', function (st) { + st.equal(qs.stringify({ a: 'b c' }), 'a=b%20c'); + st.equal(qs.stringify({ 'a b': SaferBuffer.from('a b') }), 'a%20b=a%20b'); + + st.end(); + }); + + t.test('Edge cases and unknown formats', function (st) { + ['UFO1234', false, 1234, null, {}, []].forEach(function (format) { + st['throws']( + function () { + qs.stringify({ a: 'b c' }, { format: format }); + }, + new TypeError('Unknown format option provided.') + ); + }); + st.end(); + }); + + t.test('encodeValuesOnly', function (st) { + st.equal( + qs.stringify( + { a: 'b', c: ['d', 'e=f'], f: [['g'], ['h']] }, + { encodeValuesOnly: true } + ), + 'a=b&c[0]=d&c[1]=e%3Df&f[0][0]=g&f[1][0]=h' + ); + st.equal( + qs.stringify( + { a: 'b', c: ['d', 'e'], f: [['g'], ['h']] } + ), + 'a=b&c%5B0%5D=d&c%5B1%5D=e&f%5B0%5D%5B0%5D=g&f%5B1%5D%5B0%5D=h' + ); + st.end(); + }); + + t.test('encodeValuesOnly - strictNullHandling', function (st) { + st.equal( + qs.stringify( + { a: { b: null } }, + { encodeValuesOnly: true, strictNullHandling: true } + ), + 'a[b]' + ); + st.end(); + }); + + t.test('throws if an invalid charset is specified', function (st) { + st['throws'](function () { + qs.stringify({ a: 'b' }, { charset: 'foobar' }); + }, new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined')); + st.end(); + }); + + t.test('respects a charset of iso-8859-1', function (st) { + st.equal(qs.stringify({ æ: 'æ' }, { charset: 'iso-8859-1' }), '%E6=%E6'); + st.end(); + }); + + t.test('encodes unrepresentable chars as numeric entities in iso-8859-1 mode', function (st) { + st.equal(qs.stringify({ a: '☺' }, { charset: 'iso-8859-1' }), 'a=%26%239786%3B'); + st.end(); + }); + + t.test('respects an explicit charset of utf-8 (the default)', function (st) { + st.equal(qs.stringify({ a: 'æ' }, { charset: 'utf-8' }), 'a=%C3%A6'); + st.end(); + }); + + t.test('adds the right sentinel when instructed to and the charset is utf-8', function (st) { + st.equal(qs.stringify({ a: 'æ' }, { charsetSentinel: true, charset: 'utf-8' }), 'utf8=%E2%9C%93&a=%C3%A6'); + st.end(); + }); + + t.test('adds the right sentinel when instructed to and the charset is iso-8859-1', function (st) { + st.equal(qs.stringify({ a: 'æ' }, { charsetSentinel: true, charset: 'iso-8859-1' }), 'utf8=%26%2310003%3B&a=%E6'); + st.end(); + }); + + t.test('does not mutate the options argument', function (st) { + var options = {}; + qs.stringify({}, options); + st.deepEqual(options, {}); + st.end(); + }); + + t.test('strictNullHandling works with custom filter', function (st) { + var filter = function (prefix, value) { + return value; + }; + + var options = { strictNullHandling: true, filter: filter }; + st.equal(qs.stringify({ key: null }, options), 'key'); + st.end(); + }); + + t.test('strictNullHandling works with null serializeDate', function (st) { + var serializeDate = function () { + return null; + }; + var options = { strictNullHandling: true, serializeDate: serializeDate }; + var date = new Date(); + st.equal(qs.stringify({ key: date }, options), 'key'); + st.end(); + }); + + t.test('allows for encoding keys and values differently', function (st) { + var encoder = function (str, defaultEncoder, charset, type) { + if (type === 'key') { + return defaultEncoder(str, defaultEncoder, charset, type).toLowerCase(); + } + if (type === 'value') { + return defaultEncoder(str, defaultEncoder, charset, type).toUpperCase(); + } + throw 'this should never happen! type: ' + type; + }; + + st.deepEqual(qs.stringify({ KeY: 'vAlUe' }, { encoder: encoder }), 'key=VALUE'); + st.end(); + }); + + t.test('objects inside arrays', function (st) { + var obj = { a: { b: { c: 'd', e: 'f' } } }; + var withArray = { a: { b: [{ c: 'd', e: 'f' }] } }; + + st.equal(qs.stringify(obj, { encode: false }), 'a[b][c]=d&a[b][e]=f', 'no array, no arrayFormat'); + st.equal(qs.stringify(obj, { encode: false, arrayFormat: 'bracket' }), 'a[b][c]=d&a[b][e]=f', 'no array, bracket'); + st.equal(qs.stringify(obj, { encode: false, arrayFormat: 'indices' }), 'a[b][c]=d&a[b][e]=f', 'no array, indices'); + st.equal(qs.stringify(obj, { encode: false, arrayFormat: 'comma' }), 'a[b][c]=d&a[b][e]=f', 'no array, comma'); + + st.equal(qs.stringify(withArray, { encode: false }), 'a[b][0][c]=d&a[b][0][e]=f', 'array, no arrayFormat'); + st.equal(qs.stringify(withArray, { encode: false, arrayFormat: 'bracket' }), 'a[b][0][c]=d&a[b][0][e]=f', 'array, bracket'); + st.equal(qs.stringify(withArray, { encode: false, arrayFormat: 'indices' }), 'a[b][0][c]=d&a[b][0][e]=f', 'array, indices'); + st.equal( + qs.stringify(withArray, { encode: false, arrayFormat: 'comma' }), + '???', + 'array, comma', + { skip: 'TODO: figure out what this should do' } + ); + + st.end(); + }); + + t.test('stringifies sparse arrays', function (st) { + /* eslint no-sparse-arrays: 0 */ + st.equal(qs.stringify({ a: [, '2', , , '1'] }, { encodeValuesOnly: true }), 'a[1]=2&a[4]=1'); + st.equal(qs.stringify({ a: [, { b: [, , { c: '1' }] }] }, { encodeValuesOnly: true }), 'a[1][b][2][c]=1'); + st.equal(qs.stringify({ a: [, [, , [, , , { c: '1' }]]] }, { encodeValuesOnly: true }), 'a[1][2][3][c]=1'); + st.equal(qs.stringify({ a: [, [, , [, , , { c: [, '1'] }]]] }, { encodeValuesOnly: true }), 'a[1][2][3][c][1]=1'); + + st.end(); + }); + + t.end(); +}); diff --git a/backend/node_modules/qs/test/utils.js b/backend/node_modules/qs/test/utils.js new file mode 100644 index 0000000000000000000000000000000000000000..aa84dfdc62beb79b5b980fca5d6ba40c19caa123 --- /dev/null +++ b/backend/node_modules/qs/test/utils.js @@ -0,0 +1,136 @@ +'use strict'; + +var test = require('tape'); +var inspect = require('object-inspect'); +var SaferBuffer = require('safer-buffer').Buffer; +var forEach = require('for-each'); +var utils = require('../lib/utils'); + +test('merge()', function (t) { + t.deepEqual(utils.merge(null, true), [null, true], 'merges true into null'); + + t.deepEqual(utils.merge(null, [42]), [null, 42], 'merges null into an array'); + + t.deepEqual(utils.merge({ a: 'b' }, { a: 'c' }), { a: ['b', 'c'] }, 'merges two objects with the same key'); + + var oneMerged = utils.merge({ foo: 'bar' }, { foo: { first: '123' } }); + t.deepEqual(oneMerged, { foo: ['bar', { first: '123' }] }, 'merges a standalone and an object into an array'); + + var twoMerged = utils.merge({ foo: ['bar', { first: '123' }] }, { foo: { second: '456' } }); + t.deepEqual(twoMerged, { foo: { 0: 'bar', 1: { first: '123' }, second: '456' } }, 'merges a standalone and two objects into an array'); + + var sandwiched = utils.merge({ foo: ['bar', { first: '123', second: '456' }] }, { foo: 'baz' }); + t.deepEqual(sandwiched, { foo: ['bar', { first: '123', second: '456' }, 'baz'] }, 'merges an object sandwiched by two standalones into an array'); + + var nestedArrays = utils.merge({ foo: ['baz'] }, { foo: ['bar', 'xyzzy'] }); + t.deepEqual(nestedArrays, { foo: ['baz', 'bar', 'xyzzy'] }); + + var noOptionsNonObjectSource = utils.merge({ foo: 'baz' }, 'bar'); + t.deepEqual(noOptionsNonObjectSource, { foo: 'baz', bar: true }); + + t.test( + 'avoids invoking array setters unnecessarily', + { skip: typeof Object.defineProperty !== 'function' }, + function (st) { + var setCount = 0; + var getCount = 0; + var observed = []; + Object.defineProperty(observed, 0, { + get: function () { + getCount += 1; + return { bar: 'baz' }; + }, + set: function () { setCount += 1; } + }); + utils.merge(observed, [null]); + st.equal(setCount, 0); + st.equal(getCount, 1); + observed[0] = observed[0]; // eslint-disable-line no-self-assign + st.equal(setCount, 1); + st.equal(getCount, 2); + st.end(); + } + ); + + t.end(); +}); + +test('assign()', function (t) { + var target = { a: 1, b: 2 }; + var source = { b: 3, c: 4 }; + var result = utils.assign(target, source); + + t.equal(result, target, 'returns the target'); + t.deepEqual(target, { a: 1, b: 3, c: 4 }, 'target and source are merged'); + t.deepEqual(source, { b: 3, c: 4 }, 'source is untouched'); + + t.end(); +}); + +test('combine()', function (t) { + t.test('both arrays', function (st) { + var a = [1]; + var b = [2]; + var combined = utils.combine(a, b); + + st.deepEqual(a, [1], 'a is not mutated'); + st.deepEqual(b, [2], 'b is not mutated'); + st.notEqual(a, combined, 'a !== combined'); + st.notEqual(b, combined, 'b !== combined'); + st.deepEqual(combined, [1, 2], 'combined is a + b'); + + st.end(); + }); + + t.test('one array, one non-array', function (st) { + var aN = 1; + var a = [aN]; + var bN = 2; + var b = [bN]; + + var combinedAnB = utils.combine(aN, b); + st.deepEqual(b, [bN], 'b is not mutated'); + st.notEqual(aN, combinedAnB, 'aN + b !== aN'); + st.notEqual(a, combinedAnB, 'aN + b !== a'); + st.notEqual(bN, combinedAnB, 'aN + b !== bN'); + st.notEqual(b, combinedAnB, 'aN + b !== b'); + st.deepEqual([1, 2], combinedAnB, 'first argument is array-wrapped when not an array'); + + var combinedABn = utils.combine(a, bN); + st.deepEqual(a, [aN], 'a is not mutated'); + st.notEqual(aN, combinedABn, 'a + bN !== aN'); + st.notEqual(a, combinedABn, 'a + bN !== a'); + st.notEqual(bN, combinedABn, 'a + bN !== bN'); + st.notEqual(b, combinedABn, 'a + bN !== b'); + st.deepEqual([1, 2], combinedABn, 'second argument is array-wrapped when not an array'); + + st.end(); + }); + + t.test('neither is an array', function (st) { + var combined = utils.combine(1, 2); + st.notEqual(1, combined, '1 + 2 !== 1'); + st.notEqual(2, combined, '1 + 2 !== 2'); + st.deepEqual([1, 2], combined, 'both arguments are array-wrapped when not an array'); + + st.end(); + }); + + t.end(); +}); + +test('isBuffer()', function (t) { + forEach([null, undefined, true, false, '', 'abc', 42, 0, NaN, {}, [], function () {}, /a/g], function (x) { + t.equal(utils.isBuffer(x), false, inspect(x) + ' is not a buffer'); + }); + + var fakeBuffer = { constructor: Buffer }; + t.equal(utils.isBuffer(fakeBuffer), false, 'fake buffer is not a buffer'); + + var saferBuffer = SaferBuffer.from('abc'); + t.equal(utils.isBuffer(saferBuffer), true, 'SaferBuffer instance is a buffer'); + + var buffer = Buffer.from && Buffer.alloc ? Buffer.from('abc') : new Buffer('abc'); + t.equal(utils.isBuffer(buffer), true, 'real Buffer instance is a buffer'); + t.end(); +}); diff --git a/backend/node_modules/range-parser/HISTORY.md b/backend/node_modules/range-parser/HISTORY.md new file mode 100644 index 0000000000000000000000000000000000000000..70a973d800ef108fda6ee25ad76ec626594b656d --- /dev/null +++ b/backend/node_modules/range-parser/HISTORY.md @@ -0,0 +1,56 @@ +1.2.1 / 2019-05-10 +================== + + * Improve error when `str` is not a string + +1.2.0 / 2016-06-01 +================== + + * Add `combine` option to combine overlapping ranges + +1.1.0 / 2016-05-13 +================== + + * Fix incorrectly returning -1 when there is at least one valid range + * perf: remove internal function + +1.0.3 / 2015-10-29 +================== + + * perf: enable strict mode + +1.0.2 / 2014-09-08 +================== + + * Support Node.js 0.6 + +1.0.1 / 2014-09-07 +================== + + * Move repository to jshttp + +1.0.0 / 2013-12-11 +================== + + * Add repository to package.json + * Add MIT license + +0.0.4 / 2012-06-17 +================== + + * Change ret -1 for unsatisfiable and -2 when invalid + +0.0.3 / 2012-06-17 +================== + + * Fix last-byte-pos default to len - 1 + +0.0.2 / 2012-06-14 +================== + + * Add `.type` + +0.0.1 / 2012-06-11 +================== + + * Initial release diff --git a/backend/node_modules/range-parser/LICENSE b/backend/node_modules/range-parser/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..359995436311ca2c69c0d05c1b7ad389aa63e9b9 --- /dev/null +++ b/backend/node_modules/range-parser/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2012-2014 TJ Holowaychuk +Copyright (c) 2015-2016 Douglas Christopher Wilson + +```js +var parseRange = require('range-parser') +``` + +### parseRange(size, header, options) + +Parse the given `header` string where `size` is the maximum size of the resource. +An array of ranges will be returned or negative numbers indicating an error parsing. + + * `-2` signals a malformed header string + * `-1` signals an unsatisfiable range + + + +```js +// parse header from request +var range = parseRange(size, req.headers.range) + +// the type of the range +if (range.type === 'bytes') { + // the ranges + range.forEach(function (r) { + // do something with r.start and r.end + }) +} +``` + +#### Options + +These properties are accepted in the options object. + +##### combine + +Specifies if overlapping & adjacent ranges should be combined, defaults to `false`. +When `true`, ranges will be combined and returned as if they were specified that +way in the header. + + + +```js +parseRange(100, 'bytes=50-55,0-10,5-10,56-60', { combine: true }) +// => [ +// { start: 0, end: 10 }, +// { start: 50, end: 60 } +// ] +``` + +## License + +[MIT](LICENSE) + +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/range-parser/master +[coveralls-url]: https://coveralls.io/r/jshttp/range-parser?branch=master +[node-image]: https://badgen.net/npm/node/range-parser +[node-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/range-parser +[npm-url]: https://npmjs.org/package/range-parser +[npm-version-image]: https://badgen.net/npm/v/range-parser +[travis-image]: https://badgen.net/travis/jshttp/range-parser/master +[travis-url]: https://travis-ci.org/jshttp/range-parser diff --git a/backend/node_modules/range-parser/index.js b/backend/node_modules/range-parser/index.js new file mode 100644 index 0000000000000000000000000000000000000000..b7dc5c0f15fe00172c496cae3bc48f238a3a8469 --- /dev/null +++ b/backend/node_modules/range-parser/index.js @@ -0,0 +1,162 @@ +/*! + * range-parser + * Copyright(c) 2012-2014 TJ Holowaychuk + * Copyright(c) 2015-2016 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = rangeParser + +/** + * Parse "Range" header `str` relative to the given file `size`. + * + * @param {Number} size + * @param {String} str + * @param {Object} [options] + * @return {Array} + * @public + */ + +function rangeParser (size, str, options) { + if (typeof str !== 'string') { + throw new TypeError('argument str must be a string') + } + + var index = str.indexOf('=') + + if (index === -1) { + return -2 + } + + // split the range string + var arr = str.slice(index + 1).split(',') + var ranges = [] + + // add ranges type + ranges.type = str.slice(0, index) + + // parse all ranges + for (var i = 0; i < arr.length; i++) { + var range = arr[i].split('-') + var start = parseInt(range[0], 10) + var end = parseInt(range[1], 10) + + // -nnn + if (isNaN(start)) { + start = size - end + end = size - 1 + // nnn- + } else if (isNaN(end)) { + end = size - 1 + } + + // limit last-byte-pos to current length + if (end > size - 1) { + end = size - 1 + } + + // invalid or unsatisifiable + if (isNaN(start) || isNaN(end) || start > end || start < 0) { + continue + } + + // add range + ranges.push({ + start: start, + end: end + }) + } + + if (ranges.length < 1) { + // unsatisifiable + return -1 + } + + return options && options.combine + ? combineRanges(ranges) + : ranges +} + +/** + * Combine overlapping & adjacent ranges. + * @private + */ + +function combineRanges (ranges) { + var ordered = ranges.map(mapWithIndex).sort(sortByRangeStart) + + for (var j = 0, i = 1; i < ordered.length; i++) { + var range = ordered[i] + var current = ordered[j] + + if (range.start > current.end + 1) { + // next range + ordered[++j] = range + } else if (range.end > current.end) { + // extend range + current.end = range.end + current.index = Math.min(current.index, range.index) + } + } + + // trim ordered array + ordered.length = j + 1 + + // generate combined range + var combined = ordered.sort(sortByRangeIndex).map(mapWithoutIndex) + + // copy ranges type + combined.type = ranges.type + + return combined +} + +/** + * Map function to add index value to ranges. + * @private + */ + +function mapWithIndex (range, index) { + return { + start: range.start, + end: range.end, + index: index + } +} + +/** + * Map function to remove index value from ranges. + * @private + */ + +function mapWithoutIndex (range) { + return { + start: range.start, + end: range.end + } +} + +/** + * Sort function to sort ranges by index. + * @private + */ + +function sortByRangeIndex (a, b) { + return a.index - b.index +} + +/** + * Sort function to sort ranges by start position. + * @private + */ + +function sortByRangeStart (a, b) { + return a.start - b.start +} diff --git a/backend/node_modules/range-parser/package.json b/backend/node_modules/range-parser/package.json new file mode 100644 index 0000000000000000000000000000000000000000..abea6d852e9baa772152be996c4a6ed5b2e8e514 --- /dev/null +++ b/backend/node_modules/range-parser/package.json @@ -0,0 +1,44 @@ +{ + "name": "range-parser", + "author": "TJ Holowaychuk (http://tjholowaychuk.com)", + "description": "Range header field string parser", + "version": "1.2.1", + "contributors": [ + "Douglas Christopher Wilson ", + "James Wyatt Cready ", + "Jonathan Ong (http://jongleberry.com)" + ], + "license": "MIT", + "keywords": [ + "range", + "parser", + "http" + ], + "repository": "jshttp/range-parser", + "devDependencies": { + "deep-equal": "1.0.1", + "eslint": "5.16.0", + "eslint-config-standard": "12.0.0", + "eslint-plugin-markdown": "1.0.0", + "eslint-plugin-import": "2.17.2", + "eslint-plugin-node": "8.0.1", + "eslint-plugin-promise": "4.1.1", + "eslint-plugin-standard": "4.0.0", + "mocha": "6.1.4", + "nyc": "14.1.1" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec", + "test-cov": "nyc --reporter=html --reporter=text npm test", + "test-travis": "nyc --reporter=text npm test" + } +} diff --git a/backend/node_modules/raw-body/HISTORY.md b/backend/node_modules/raw-body/HISTORY.md new file mode 100644 index 0000000000000000000000000000000000000000..baf0e2d889a10d66ced544f78a4eb5ffa4a24ae6 --- /dev/null +++ b/backend/node_modules/raw-body/HISTORY.md @@ -0,0 +1,308 @@ +2.5.2 / 2023-02-21 +================== + + * Fix error message for non-stream argument + +2.5.1 / 2022-02-28 +================== + + * Fix error on early async hooks implementations + +2.5.0 / 2022-02-21 +================== + + * Prevent loss of async hooks context + * Prevent hanging when stream is not readable + * deps: http-errors@2.0.0 + - deps: depd@2.0.0 + - deps: statuses@2.0.1 + +2.4.3 / 2022-02-14 +================== + + * deps: bytes@3.1.2 + +2.4.2 / 2021-11-16 +================== + + * deps: bytes@3.1.1 + * deps: http-errors@1.8.1 + - deps: setprototypeof@1.2.0 + - deps: toidentifier@1.0.1 + +2.4.1 / 2019-06-25 +================== + + * deps: http-errors@1.7.3 + - deps: inherits@2.0.4 + +2.4.0 / 2019-04-17 +================== + + * deps: bytes@3.1.0 + - Add petabyte (`pb`) support + * deps: http-errors@1.7.2 + - Set constructor name when possible + - deps: setprototypeof@1.1.1 + - deps: statuses@'>= 1.5.0 < 2' + * deps: iconv-lite@0.4.24 + - Added encoding MIK + +2.3.3 / 2018-05-08 +================== + + * deps: http-errors@1.6.3 + - deps: depd@~1.1.2 + - deps: setprototypeof@1.1.0 + - deps: statuses@'>= 1.3.1 < 2' + * deps: iconv-lite@0.4.23 + - Fix loading encoding with year appended + - Fix deprecation warnings on Node.js 10+ + +2.3.2 / 2017-09-09 +================== + + * deps: iconv-lite@0.4.19 + - Fix ISO-8859-1 regression + - Update Windows-1255 + +2.3.1 / 2017-09-07 +================== + + * deps: bytes@3.0.0 + * deps: http-errors@1.6.2 + - deps: depd@1.1.1 + * perf: skip buffer decoding on overage chunk + +2.3.0 / 2017-08-04 +================== + + * Add TypeScript definitions + * Use `http-errors` for standard emitted errors + * deps: bytes@2.5.0 + * deps: iconv-lite@0.4.18 + - Add support for React Native + - Add a warning if not loaded as utf-8 + - Fix CESU-8 decoding in Node.js 8 + - Improve speed of ISO-8859-1 encoding + +2.2.0 / 2017-01-02 +================== + + * deps: iconv-lite@0.4.15 + - Added encoding MS-31J + - Added encoding MS-932 + - Added encoding MS-936 + - Added encoding MS-949 + - Added encoding MS-950 + - Fix GBK/GB18030 handling of Euro character + +2.1.7 / 2016-06-19 +================== + + * deps: bytes@2.4.0 + * perf: remove double-cleanup on happy path + +2.1.6 / 2016-03-07 +================== + + * deps: bytes@2.3.0 + - Drop partial bytes on all parsed units + - Fix parsing byte string that looks like hex + +2.1.5 / 2015-11-30 +================== + + * deps: bytes@2.2.0 + * deps: iconv-lite@0.4.13 + +2.1.4 / 2015-09-27 +================== + + * Fix masking critical errors from `iconv-lite` + * deps: iconv-lite@0.4.12 + - Fix CESU-8 decoding in Node.js 4.x + +2.1.3 / 2015-09-12 +================== + + * Fix sync callback when attaching data listener causes sync read + - Node.js 0.10 compatibility issue + +2.1.2 / 2015-07-05 +================== + + * Fix error stack traces to skip `makeError` + * deps: iconv-lite@0.4.11 + - Add encoding CESU-8 + +2.1.1 / 2015-06-14 +================== + + * Use `unpipe` module for unpiping requests + +2.1.0 / 2015-05-28 +================== + + * deps: iconv-lite@0.4.10 + - Improved UTF-16 endianness detection + - Leading BOM is now removed when decoding + - The encoding UTF-16 without BOM now defaults to UTF-16LE when detection fails + +2.0.2 / 2015-05-21 +================== + + * deps: bytes@2.1.0 + - Slight optimizations + +2.0.1 / 2015-05-10 +================== + + * Fix a false-positive when unpiping in Node.js 0.8 + +2.0.0 / 2015-05-08 +================== + + * Return a promise without callback instead of thunk + * deps: bytes@2.0.1 + - units no longer case sensitive when parsing + +1.3.4 / 2015-04-15 +================== + + * Fix hanging callback if request aborts during read + * deps: iconv-lite@0.4.8 + - Add encoding alias UNICODE-1-1-UTF-7 + +1.3.3 / 2015-02-08 +================== + + * deps: iconv-lite@0.4.7 + - Gracefully support enumerables on `Object.prototype` + +1.3.2 / 2015-01-20 +================== + + * deps: iconv-lite@0.4.6 + - Fix rare aliases of single-byte encodings + +1.3.1 / 2014-11-21 +================== + + * deps: iconv-lite@0.4.5 + - Fix Windows-31J and X-SJIS encoding support + +1.3.0 / 2014-07-20 +================== + + * Fully unpipe the stream on error + - Fixes `Cannot switch to old mode now` error on Node.js 0.10+ + +1.2.3 / 2014-07-20 +================== + + * deps: iconv-lite@0.4.4 + - Added encoding UTF-7 + +1.2.2 / 2014-06-19 +================== + + * Send invalid encoding error to callback + +1.2.1 / 2014-06-15 +================== + + * deps: iconv-lite@0.4.3 + - Added encodings UTF-16BE and UTF-16 with BOM + +1.2.0 / 2014-06-13 +================== + + * Passing string as `options` interpreted as encoding + * Support all encodings from `iconv-lite` + +1.1.7 / 2014-06-12 +================== + + * use `string_decoder` module from npm + +1.1.6 / 2014-05-27 +================== + + * check encoding for old streams1 + * support node.js < 0.10.6 + +1.1.5 / 2014-05-14 +================== + + * bump bytes + +1.1.4 / 2014-04-19 +================== + + * allow true as an option + * bump bytes + +1.1.3 / 2014-03-02 +================== + + * fix case when length=null + +1.1.2 / 2013-12-01 +================== + + * be less strict on state.encoding check + +1.1.1 / 2013-11-27 +================== + + * add engines + +1.1.0 / 2013-11-27 +================== + + * add err.statusCode and err.type + * allow for encoding option to be true + * pause the stream instead of dumping on error + * throw if the stream's encoding is set + +1.0.1 / 2013-11-19 +================== + + * dont support streams1, throw if dev set encoding + +1.0.0 / 2013-11-17 +================== + + * rename `expected` option to `length` + +0.2.0 / 2013-11-15 +================== + + * republish + +0.1.1 / 2013-11-15 +================== + + * use bytes + +0.1.0 / 2013-11-11 +================== + + * generator support + +0.0.3 / 2013-10-10 +================== + + * update repo + +0.0.2 / 2013-09-14 +================== + + * dump stream on bad headers + * listen to events after defining received and buffers + +0.0.1 / 2013-09-14 +================== + + * Initial release diff --git a/backend/node_modules/raw-body/LICENSE b/backend/node_modules/raw-body/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..1029a7a7c79e867208857f4830072b35229b8844 --- /dev/null +++ b/backend/node_modules/raw-body/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2013-2014 Jonathan Ong +Copyright (c) 2014-2022 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/backend/node_modules/raw-body/README.md b/backend/node_modules/raw-body/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d9b36d611830efeaae613bd8dff4082d7fd55971 --- /dev/null +++ b/backend/node_modules/raw-body/README.md @@ -0,0 +1,223 @@ +# raw-body + +[![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] + +Gets the entire buffer of a stream either as a `Buffer` or a string. +Validates the stream's length against an expected length and maximum limit. +Ideal for parsing request bodies. + +## Install + +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 raw-body +``` + +### TypeScript + +This module includes a [TypeScript](https://www.typescriptlang.org/) +declaration file to enable auto complete in compatible editors and type +information for TypeScript projects. This module depends on the Node.js +types, so install `@types/node`: + +```sh +$ npm install @types/node +``` + +## API + +```js +var getRawBody = require('raw-body') +``` + +### getRawBody(stream, [options], [callback]) + +**Returns a promise if no callback specified and global `Promise` exists.** + +Options: + +- `length` - The length of the stream. + If the contents of the stream do not add up to this length, + an `400` error code is returned. +- `limit` - The byte limit of the body. + This is the number of bytes or any string format supported by + [bytes](https://www.npmjs.com/package/bytes), + for example `1000`, `'500kb'` or `'3mb'`. + If the body ends up being larger than this limit, + a `413` error code is returned. +- `encoding` - The encoding to use to decode the body into a string. + By default, a `Buffer` instance will be returned when no encoding is specified. + Most likely, you want `utf-8`, so setting `encoding` to `true` will decode as `utf-8`. + You can use any type of encoding supported by [iconv-lite](https://www.npmjs.org/package/iconv-lite#readme). + +You can also pass a string in place of options to just specify the encoding. + +If an error occurs, the stream will be paused, everything unpiped, +and you are responsible for correctly disposing the stream. +For HTTP requests, you may need to finish consuming the stream if +you want to keep the socket open for future requests. For streams +that use file descriptors, you should `stream.destroy()` or +`stream.close()` to prevent leaks. + +## Errors + +This module creates errors depending on the error condition during reading. +The error may be an error from the underlying Node.js implementation, but is +otherwise an error created by this module, which has the following attributes: + + * `limit` - the limit in bytes + * `length` and `expected` - the expected length of the stream + * `received` - the received bytes + * `encoding` - the invalid encoding + * `status` and `statusCode` - the corresponding status code for the error + * `type` - the error type + +### Types + +The errors from this module have a `type` property which allows for the programmatic +determination of the type of error returned. + +#### encoding.unsupported + +This error will occur when the `encoding` option is specified, but the value does +not map to an encoding supported by the [iconv-lite](https://www.npmjs.org/package/iconv-lite#readme) +module. + +#### entity.too.large + +This error will occur when the `limit` option is specified, but the stream has +an entity that is larger. + +#### request.aborted + +This error will occur when the request stream is aborted by the client before +reading the body has finished. + +#### request.size.invalid + +This error will occur when the `length` option is specified, but the stream has +emitted more bytes. + +#### stream.encoding.set + +This error will occur when the given stream has an encoding set on it, making it +a decoded stream. The stream should not have an encoding set and is expected to +emit `Buffer` objects. + +#### stream.not.readable + +This error will occur when the given stream is not readable. + +## Examples + +### Simple Express example + +```js +var contentType = require('content-type') +var express = require('express') +var getRawBody = require('raw-body') + +var app = express() + +app.use(function (req, res, next) { + getRawBody(req, { + length: req.headers['content-length'], + limit: '1mb', + encoding: contentType.parse(req).parameters.charset + }, function (err, string) { + if (err) return next(err) + req.text = string + next() + }) +}) + +// now access req.text +``` + +### Simple Koa example + +```js +var contentType = require('content-type') +var getRawBody = require('raw-body') +var koa = require('koa') + +var app = koa() + +app.use(function * (next) { + this.text = yield getRawBody(this.req, { + length: this.req.headers['content-length'], + limit: '1mb', + encoding: contentType.parse(this.req).parameters.charset + }) + yield next +}) + +// now access this.text +``` + +### Using as a promise + +To use this library as a promise, simply omit the `callback` and a promise is +returned, provided that a global `Promise` is defined. + +```js +var getRawBody = require('raw-body') +var http = require('http') + +var server = http.createServer(function (req, res) { + getRawBody(req) + .then(function (buf) { + res.statusCode = 200 + res.end(buf.length + ' bytes submitted') + }) + .catch(function (err) { + res.statusCode = 500 + res.end(err.message) + }) +}) + +server.listen(3000) +``` + +### Using with TypeScript + +```ts +import * as getRawBody from 'raw-body'; +import * as http from 'http'; + +const server = http.createServer((req, res) => { + getRawBody(req) + .then((buf) => { + res.statusCode = 200; + res.end(buf.length + ' bytes submitted'); + }) + .catch((err) => { + res.statusCode = err.statusCode; + res.end(err.message); + }); +}); + +server.listen(3000); +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/raw-body.svg +[npm-url]: https://npmjs.org/package/raw-body +[node-version-image]: https://img.shields.io/node/v/raw-body.svg +[node-version-url]: https://nodejs.org/en/download/ +[coveralls-image]: https://img.shields.io/coveralls/stream-utils/raw-body/master.svg +[coveralls-url]: https://coveralls.io/r/stream-utils/raw-body?branch=master +[downloads-image]: https://img.shields.io/npm/dm/raw-body.svg +[downloads-url]: https://npmjs.org/package/raw-body +[github-actions-ci-image]: https://img.shields.io/github/actions/workflow/status/stream-utils/raw-body/ci.yml?branch=master&label=ci +[github-actions-ci-url]: https://github.com/jshttp/stream-utils/raw-body?query=workflow%3Aci diff --git a/backend/node_modules/raw-body/SECURITY.md b/backend/node_modules/raw-body/SECURITY.md new file mode 100644 index 0000000000000000000000000000000000000000..2421efc4b12f32ab85d704489d910da9d1a0aa40 --- /dev/null +++ b/backend/node_modules/raw-body/SECURITY.md @@ -0,0 +1,24 @@ +# Security Policies and Procedures + +## Reporting a Bug + +The `raw-body` team and community take all security bugs seriously. Thank you +for improving the security of Express. We appreciate your efforts and +responsible disclosure and will make every effort to acknowledge your +contributions. + +Report security bugs by emailing the current owners of `raw-body`. This information +can be found in the npm registry using the command `npm owner ls raw-body`. +If unsure or unable to get the information from the above, open an issue +in the [project issue tracker](https://github.com/stream-utils/raw-body/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/backend/node_modules/raw-body/index.d.ts b/backend/node_modules/raw-body/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..dcbbebd4c8f3a6f2cc12c4f862d90b8f2e4eaa28 --- /dev/null +++ b/backend/node_modules/raw-body/index.d.ts @@ -0,0 +1,87 @@ +import { Readable } from 'stream'; + +declare namespace getRawBody { + export type Encoding = string | true; + + export interface Options { + /** + * The expected length of the stream. + */ + length?: number | string | null; + /** + * The byte limit of the body. This is the number of bytes or any string + * format supported by `bytes`, for example `1000`, `'500kb'` or `'3mb'`. + */ + limit?: number | string | null; + /** + * The encoding to use to decode the body into a string. By default, a + * `Buffer` instance will be returned when no encoding is specified. Most + * likely, you want `utf-8`, so setting encoding to `true` will decode as + * `utf-8`. You can use any type of encoding supported by `iconv-lite`. + */ + encoding?: Encoding | null; + } + + export interface RawBodyError extends Error { + /** + * The limit in bytes. + */ + limit?: number; + /** + * The expected length of the stream. + */ + length?: number; + expected?: number; + /** + * The received bytes. + */ + received?: number; + /** + * The encoding. + */ + encoding?: string; + /** + * The corresponding status code for the error. + */ + status: number; + statusCode: number; + /** + * The error type. + */ + type: string; + } +} + +/** + * Gets the entire buffer of a stream either as a `Buffer` or a string. + * Validates the stream's length against an expected length and maximum + * limit. Ideal for parsing request bodies. + */ +declare function getRawBody( + stream: Readable, + callback: (err: getRawBody.RawBodyError, body: Buffer) => void +): void; + +declare function getRawBody( + stream: Readable, + options: (getRawBody.Options & { encoding: getRawBody.Encoding }) | getRawBody.Encoding, + callback: (err: getRawBody.RawBodyError, body: string) => void +): void; + +declare function getRawBody( + stream: Readable, + options: getRawBody.Options, + callback: (err: getRawBody.RawBodyError, body: Buffer) => void +): void; + +declare function getRawBody( + stream: Readable, + options: (getRawBody.Options & { encoding: getRawBody.Encoding }) | getRawBody.Encoding +): Promise; + +declare function getRawBody( + stream: Readable, + options?: getRawBody.Options +): Promise; + +export = getRawBody; diff --git a/backend/node_modules/raw-body/index.js b/backend/node_modules/raw-body/index.js new file mode 100644 index 0000000000000000000000000000000000000000..9cdcd12217303cdbbf1c2524978db7ba3379555e --- /dev/null +++ b/backend/node_modules/raw-body/index.js @@ -0,0 +1,336 @@ +/*! + * raw-body + * Copyright(c) 2013-2014 Jonathan Ong + * Copyright(c) 2014-2022 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var asyncHooks = tryRequireAsyncHooks() +var bytes = require('bytes') +var createError = require('http-errors') +var iconv = require('iconv-lite') +var unpipe = require('unpipe') + +/** + * Module exports. + * @public + */ + +module.exports = getRawBody + +/** + * Module variables. + * @private + */ + +var ICONV_ENCODING_MESSAGE_REGEXP = /^Encoding not recognized: / + +/** + * Get the decoder for a given encoding. + * + * @param {string} encoding + * @private + */ + +function getDecoder (encoding) { + if (!encoding) return null + + try { + return iconv.getDecoder(encoding) + } catch (e) { + // error getting decoder + if (!ICONV_ENCODING_MESSAGE_REGEXP.test(e.message)) throw e + + // the encoding was not found + throw createError(415, 'specified encoding unsupported', { + encoding: encoding, + type: 'encoding.unsupported' + }) + } +} + +/** + * Get the raw body of a stream (typically HTTP). + * + * @param {object} stream + * @param {object|string|function} [options] + * @param {function} [callback] + * @public + */ + +function getRawBody (stream, options, callback) { + var done = callback + var opts = options || {} + + // light validation + if (stream === undefined) { + throw new TypeError('argument stream is required') + } else if (typeof stream !== 'object' || stream === null || typeof stream.on !== 'function') { + throw new TypeError('argument stream must be a stream') + } + + if (options === true || typeof options === 'string') { + // short cut for encoding + opts = { + encoding: options + } + } + + if (typeof options === 'function') { + done = options + opts = {} + } + + // validate callback is a function, if provided + if (done !== undefined && typeof done !== 'function') { + throw new TypeError('argument callback must be a function') + } + + // require the callback without promises + if (!done && !global.Promise) { + throw new TypeError('argument callback is required') + } + + // get encoding + var encoding = opts.encoding !== true + ? opts.encoding + : 'utf-8' + + // convert the limit to an integer + var limit = bytes.parse(opts.limit) + + // convert the expected length to an integer + var length = opts.length != null && !isNaN(opts.length) + ? parseInt(opts.length, 10) + : null + + if (done) { + // classic callback style + return readStream(stream, encoding, length, limit, wrap(done)) + } + + return new Promise(function executor (resolve, reject) { + readStream(stream, encoding, length, limit, function onRead (err, buf) { + if (err) return reject(err) + resolve(buf) + }) + }) +} + +/** + * Halt a stream. + * + * @param {Object} stream + * @private + */ + +function halt (stream) { + // unpipe everything from the stream + unpipe(stream) + + // pause stream + if (typeof stream.pause === 'function') { + stream.pause() + } +} + +/** + * Read the data from the stream. + * + * @param {object} stream + * @param {string} encoding + * @param {number} length + * @param {number} limit + * @param {function} callback + * @public + */ + +function readStream (stream, encoding, length, limit, callback) { + var complete = false + var sync = true + + // check the length and limit options. + // note: we intentionally leave the stream paused, + // so users should handle the stream themselves. + if (limit !== null && length !== null && length > limit) { + return done(createError(413, 'request entity too large', { + expected: length, + length: length, + limit: limit, + type: 'entity.too.large' + })) + } + + // streams1: assert request encoding is buffer. + // streams2+: assert the stream encoding is buffer. + // stream._decoder: streams1 + // state.encoding: streams2 + // state.decoder: streams2, specifically < 0.10.6 + var state = stream._readableState + if (stream._decoder || (state && (state.encoding || state.decoder))) { + // developer error + return done(createError(500, 'stream encoding should not be set', { + type: 'stream.encoding.set' + })) + } + + if (typeof stream.readable !== 'undefined' && !stream.readable) { + return done(createError(500, 'stream is not readable', { + type: 'stream.not.readable' + })) + } + + var received = 0 + var decoder + + try { + decoder = getDecoder(encoding) + } catch (err) { + return done(err) + } + + var buffer = decoder + ? '' + : [] + + // attach listeners + stream.on('aborted', onAborted) + stream.on('close', cleanup) + stream.on('data', onData) + stream.on('end', onEnd) + stream.on('error', onEnd) + + // mark sync section complete + sync = false + + function done () { + var args = new Array(arguments.length) + + // copy arguments + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i] + } + + // mark complete + complete = true + + if (sync) { + process.nextTick(invokeCallback) + } else { + invokeCallback() + } + + function invokeCallback () { + cleanup() + + if (args[0]) { + // halt the stream on error + halt(stream) + } + + callback.apply(null, args) + } + } + + function onAborted () { + if (complete) return + + done(createError(400, 'request aborted', { + code: 'ECONNABORTED', + expected: length, + length: length, + received: received, + type: 'request.aborted' + })) + } + + function onData (chunk) { + if (complete) return + + received += chunk.length + + if (limit !== null && received > limit) { + done(createError(413, 'request entity too large', { + limit: limit, + received: received, + type: 'entity.too.large' + })) + } else if (decoder) { + buffer += decoder.write(chunk) + } else { + buffer.push(chunk) + } + } + + function onEnd (err) { + if (complete) return + if (err) return done(err) + + if (length !== null && received !== length) { + done(createError(400, 'request size did not match content length', { + expected: length, + length: length, + received: received, + type: 'request.size.invalid' + })) + } else { + var string = decoder + ? buffer + (decoder.end() || '') + : Buffer.concat(buffer) + done(null, string) + } + } + + function cleanup () { + buffer = null + + stream.removeListener('aborted', onAborted) + stream.removeListener('data', onData) + stream.removeListener('end', onEnd) + stream.removeListener('error', onEnd) + stream.removeListener('close', cleanup) + } +} + +/** + * Try to require async_hooks + * @private + */ + +function tryRequireAsyncHooks () { + try { + return require('async_hooks') + } catch (e) { + return {} + } +} + +/** + * Wrap function with async resource, if possible. + * AsyncResource.bind static method backported. + * @private + */ + +function wrap (fn) { + var res + + // create anonymous resource + if (asyncHooks.AsyncResource) { + res = new asyncHooks.AsyncResource(fn.name || 'bound-anonymous-fn') + } + + // incompatible node.js + if (!res || !res.runInAsyncScope) { + return fn + } + + // return bound function + return res.runInAsyncScope.bind(res, fn, null) +} diff --git a/backend/node_modules/raw-body/package.json b/backend/node_modules/raw-body/package.json new file mode 100644 index 0000000000000000000000000000000000000000..aabb1c368d95562e18fbbae384868303ae4bd590 --- /dev/null +++ b/backend/node_modules/raw-body/package.json @@ -0,0 +1,49 @@ +{ + "name": "raw-body", + "description": "Get and validate the raw body of a readable stream.", + "version": "2.5.2", + "author": "Jonathan Ong (http://jongleberry.com)", + "contributors": [ + "Douglas Christopher Wilson ", + "Raynos " + ], + "license": "MIT", + "repository": "stream-utils/raw-body", + "dependencies": { + "bytes": "3.1.2", + "http-errors": "2.0.0", + "iconv-lite": "0.4.24", + "unpipe": "1.0.0" + }, + "devDependencies": { + "bluebird": "3.7.2", + "eslint": "8.34.0", + "eslint-config-standard": "15.0.1", + "eslint-plugin-import": "2.27.5", + "eslint-plugin-markdown": "3.0.0", + "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", + "readable-stream": "2.3.7", + "safe-buffer": "5.2.1" + }, + "engines": { + "node": ">= 0.8" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "SECURITY.md", + "index.d.ts", + "index.js" + ], + "scripts": { + "lint": "eslint .", + "test": "mocha --trace-deprecation --reporter spec --bail --check-leaks test/", + "test-ci": "nyc --reporter=lcovonly --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test" + } +} diff --git a/backend/node_modules/readable-stream/.travis.yml b/backend/node_modules/readable-stream/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..f62cdac0686da613ecdbf214fb2b43a828cb6ce9 --- /dev/null +++ b/backend/node_modules/readable-stream/.travis.yml @@ -0,0 +1,34 @@ +sudo: false +language: node_js +before_install: + - (test $NPM_LEGACY && npm install -g npm@2 && npm install -g npm@3) || true +notifications: + email: false +matrix: + fast_finish: true + include: + - node_js: '0.8' + env: NPM_LEGACY=true + - node_js: '0.10' + env: NPM_LEGACY=true + - node_js: '0.11' + env: NPM_LEGACY=true + - node_js: '0.12' + env: NPM_LEGACY=true + - node_js: 1 + env: NPM_LEGACY=true + - node_js: 2 + env: NPM_LEGACY=true + - node_js: 3 + env: NPM_LEGACY=true + - node_js: 4 + - node_js: 5 + - node_js: 6 + - node_js: 7 + - node_js: 8 + - node_js: 9 +script: "npm run test" +env: + global: + - secure: rE2Vvo7vnjabYNULNyLFxOyt98BoJexDqsiOnfiD6kLYYsiQGfr/sbZkPMOFm9qfQG7pjqx+zZWZjGSswhTt+626C0t/njXqug7Yps4c3dFblzGfreQHp7wNX5TFsvrxd6dAowVasMp61sJcRnB2w8cUzoe3RAYUDHyiHktwqMc= + - secure: g9YINaKAdMatsJ28G9jCGbSaguXCyxSTy+pBO6Ch0Cf57ZLOTka3HqDj8p3nV28LUIHZ3ut5WO43CeYKwt4AUtLpBS3a0dndHdY6D83uY6b2qh5hXlrcbeQTq2cvw2y95F7hm4D1kwrgZ7ViqaKggRcEupAL69YbJnxeUDKWEdI= diff --git a/backend/node_modules/readable-stream/CONTRIBUTING.md b/backend/node_modules/readable-stream/CONTRIBUTING.md new file mode 100644 index 0000000000000000000000000000000000000000..f478d58dca85b2c396e2da8a2251be0071c4e9e0 --- /dev/null +++ b/backend/node_modules/readable-stream/CONTRIBUTING.md @@ -0,0 +1,38 @@ +# Developer's Certificate of Origin 1.1 + +By making a contribution to this project, I certify that: + +* (a) The contribution was created in whole or in part by me and I + have the right to submit it under the open source license + indicated in the file; or + +* (b) The contribution is based upon previous work that, to the best + of my knowledge, is covered under an appropriate open source + license and I have the right under that license to submit that + work with modifications, whether created in whole or in part + by me, under the same open source license (unless I am + permitted to submit under a different license), as indicated + in the file; or + +* (c) The contribution was provided directly to me by some other + person who certified (a), (b) or (c) and I have not modified + it. + +* (d) I understand and agree that this project and the contribution + are public and that a record of the contribution (including all + personal information I submit with it, including my sign-off) is + maintained indefinitely and may be redistributed consistent with + this project or the open source license(s) involved. + +## Moderation Policy + +The [Node.js Moderation Policy] applies to this WG. + +## Code of Conduct + +The [Node.js Code of Conduct][] applies to this WG. + +[Node.js Code of Conduct]: +https://github.com/nodejs/node/blob/master/CODE_OF_CONDUCT.md +[Node.js Moderation Policy]: +https://github.com/nodejs/TSC/blob/master/Moderation-Policy.md diff --git a/backend/node_modules/readable-stream/GOVERNANCE.md b/backend/node_modules/readable-stream/GOVERNANCE.md new file mode 100644 index 0000000000000000000000000000000000000000..16ffb93f24bece9519cc4a220a0c1d3c91481453 --- /dev/null +++ b/backend/node_modules/readable-stream/GOVERNANCE.md @@ -0,0 +1,136 @@ +### Streams Working Group + +The Node.js Streams is jointly governed by a Working Group +(WG) +that is responsible for high-level guidance of the project. + +The WG has final authority over this project including: + +* Technical direction +* Project governance and process (including this policy) +* Contribution policy +* GitHub repository hosting +* Conduct guidelines +* Maintaining the list of additional Collaborators + +For the current list of WG members, see the project +[README.md](./README.md#current-project-team-members). + +### Collaborators + +The readable-stream GitHub repository is +maintained by the WG and additional Collaborators who are added by the +WG on an ongoing basis. + +Individuals making significant and valuable contributions are made +Collaborators and given commit-access to the project. These +individuals are identified by the WG and their addition as +Collaborators is discussed during the WG meeting. + +_Note:_ If you make a significant contribution and are not considered +for commit-access log an issue or contact a WG member directly and it +will be brought up in the next WG meeting. + +Modifications of the contents of the readable-stream repository are +made on +a collaborative basis. Anybody with a GitHub account may propose a +modification via pull request and it will be considered by the project +Collaborators. All pull requests must be reviewed and accepted by a +Collaborator with sufficient expertise who is able to take full +responsibility for the change. In the case of pull requests proposed +by an existing Collaborator, an additional Collaborator is required +for sign-off. Consensus should be sought if additional Collaborators +participate and there is disagreement around a particular +modification. See _Consensus Seeking Process_ below for further detail +on the consensus model used for governance. + +Collaborators may opt to elevate significant or controversial +modifications, or modifications that have not found consensus to the +WG for discussion by assigning the ***WG-agenda*** tag to a pull +request or issue. The WG should serve as the final arbiter where +required. + +For the current list of Collaborators, see the project +[README.md](./README.md#members). + +### WG Membership + +WG seats are not time-limited. There is no fixed size of the WG. +However, the expected target is between 6 and 12, to ensure adequate +coverage of important areas of expertise, balanced with the ability to +make decisions efficiently. + +There is no specific set of requirements or qualifications for WG +membership beyond these rules. + +The WG may add additional members to the WG by unanimous consensus. + +A WG member may be removed from the WG by voluntary resignation, or by +unanimous consensus of all other WG members. + +Changes to WG membership should be posted in the agenda, and may be +suggested as any other agenda item (see "WG Meetings" below). + +If an addition or removal is proposed during a meeting, and the full +WG is not in attendance to participate, then the addition or removal +is added to the agenda for the subsequent meeting. This is to ensure +that all members are given the opportunity to participate in all +membership decisions. If a WG member is unable to attend a meeting +where a planned membership decision is being made, then their consent +is assumed. + +No more than 1/3 of the WG members may be affiliated with the same +employer. If removal or resignation of a WG member, or a change of +employment by a WG member, creates a situation where more than 1/3 of +the WG membership shares an employer, then the situation must be +immediately remedied by the resignation or removal of one or more WG +members affiliated with the over-represented employer(s). + +### WG Meetings + +The WG meets occasionally on a Google Hangout On Air. A designated moderator +approved by the WG runs the meeting. Each meeting should be +published to YouTube. + +Items are added to the WG agenda that are considered contentious or +are modifications of governance, contribution policy, WG membership, +or release process. + +The intention of the agenda is not to approve or review all patches; +that should happen continuously on GitHub and be handled by the larger +group of Collaborators. + +Any community member or contributor can ask that something be added to +the next meeting's agenda by logging a GitHub Issue. Any Collaborator, +WG member or the moderator can add the item to the agenda by adding +the ***WG-agenda*** tag to the issue. + +Prior to each WG meeting the moderator will share the Agenda with +members of the WG. WG members can add any items they like to the +agenda at the beginning of each meeting. The moderator and the WG +cannot veto or remove items. + +The WG may invite persons or representatives from certain projects to +participate in a non-voting capacity. + +The moderator is responsible for summarizing the discussion of each +agenda item and sends it as a pull request after the meeting. + +### Consensus Seeking Process + +The WG follows a +[Consensus +Seeking](http://en.wikipedia.org/wiki/Consensus-seeking_decision-making) +decision-making model. + +When an agenda item has appeared to reach a consensus the moderator +will ask "Does anyone object?" as a final call for dissent from the +consensus. + +If an agenda item cannot reach a consensus a WG member can call for +either a closing vote or a vote to table the issue to the next +meeting. The call for a vote must be seconded by a majority of the WG +or else the discussion will continue. Simple majority wins. + +Note that changes to WG membership require a majority consensus. See +"WG Membership" above. diff --git a/backend/node_modules/readable-stream/LICENSE b/backend/node_modules/readable-stream/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..2873b3b2e595072e66330369d83e8af46655970c --- /dev/null +++ b/backend/node_modules/readable-stream/LICENSE @@ -0,0 +1,47 @@ +Node.js is licensed for use as follows: + +""" +Copyright Node.js contributors. 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. +""" + +This license applies to parts of Node.js originating from the +https://github.com/joyent/node repository: + +""" +Copyright Joyent, Inc. and other Node contributors. 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. +""" diff --git a/backend/node_modules/readable-stream/README.md b/backend/node_modules/readable-stream/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f1c5a9314f17aa36e8b5adaa6bf66786448aa6b0 --- /dev/null +++ b/backend/node_modules/readable-stream/README.md @@ -0,0 +1,58 @@ +# readable-stream + +***Node-core v8.17.0 streams for userland*** [![Build Status](https://travis-ci.org/nodejs/readable-stream.svg?branch=master)](https://travis-ci.org/nodejs/readable-stream) + + +[![NPM](https://nodei.co/npm/readable-stream.png?downloads=true&downloadRank=true)](https://nodei.co/npm/readable-stream/) +[![NPM](https://nodei.co/npm-dl/readable-stream.png?&months=6&height=3)](https://nodei.co/npm/readable-stream/) + + +[![Sauce Test Status](https://saucelabs.com/browser-matrix/readable-stream.svg)](https://saucelabs.com/u/readable-stream) + +```bash +npm install --save readable-stream +``` + +***Node-core streams for userland*** + +This package is a mirror of the Streams2 and Streams3 implementations in +Node-core. + +Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v8.17.0/docs/api/stream.html). + +If you want to guarantee a stable streams base, regardless of what version of +Node you, or the users of your libraries are using, use **readable-stream** *only* and avoid the *"stream"* module in Node-core, for background see [this blogpost](http://r.va.gg/2014/06/why-i-dont-use-nodes-core-stream-module.html). + +As of version 2.0.0 **readable-stream** uses semantic versioning. + +# Streams Working Group + +`readable-stream` is maintained by the Streams Working Group, which +oversees the development and maintenance of the Streams API within +Node.js. The responsibilities of the Streams Working Group include: + +* Addressing stream issues on the Node.js issue tracker. +* Authoring and editing stream documentation within the Node.js project. +* Reviewing changes to stream subclasses within the Node.js project. +* Redirecting changes to streams from the Node.js project to this + project. +* Assisting in the implementation of stream providers within Node.js. +* Recommending versions of `readable-stream` to be included in Node.js. +* Messaging about the future of streams to give the community advance + notice of changes. + + +## Team Members + +* **Chris Dickinson** ([@chrisdickinson](https://github.com/chrisdickinson)) <christopher.s.dickinson@gmail.com> + - Release GPG key: 9554F04D7259F04124DE6B476D5A82AC7E37093B +* **Calvin Metcalf** ([@calvinmetcalf](https://github.com/calvinmetcalf)) <calvin.metcalf@gmail.com> + - Release GPG key: F3EF5F62A87FC27A22E643F714CE4FF5015AA242 +* **Rod Vagg** ([@rvagg](https://github.com/rvagg)) <rod@vagg.org> + - Release GPG key: DD8F2338BAE7501E3DD5AC78C273792F7D83545D +* **Sam Newman** ([@sonewman](https://github.com/sonewman)) <newmansam@outlook.com> +* **Mathias Buus** ([@mafintosh](https://github.com/mafintosh)) <mathiasbuus@gmail.com> +* **Domenic Denicola** ([@domenic](https://github.com/domenic)) <d@domenic.me> +* **Matteo Collina** ([@mcollina](https://github.com/mcollina)) <matteo.collina@gmail.com> + - Release GPG key: 3ABC01543F22DD2239285CDD818674489FBC127E +* **Irina Shestak** ([@lrlna](https://github.com/lrlna)) <shestak.irina@gmail.com> diff --git a/backend/node_modules/readable-stream/doc/wg-meetings/2015-01-30.md b/backend/node_modules/readable-stream/doc/wg-meetings/2015-01-30.md new file mode 100644 index 0000000000000000000000000000000000000000..83275f192e4077d32942525aaf510fa449a7c417 --- /dev/null +++ b/backend/node_modules/readable-stream/doc/wg-meetings/2015-01-30.md @@ -0,0 +1,60 @@ +# streams WG Meeting 2015-01-30 + +## Links + +* **Google Hangouts Video**: http://www.youtube.com/watch?v=I9nDOSGfwZg +* **GitHub Issue**: https://github.com/iojs/readable-stream/issues/106 +* **Original Minutes Google Doc**: https://docs.google.com/document/d/17aTgLnjMXIrfjgNaTUnHQO7m3xgzHR2VXBTmi03Qii4/ + +## Agenda + +Extracted from https://github.com/iojs/readable-stream/labels/wg-agenda prior to meeting. + +* adopt a charter [#105](https://github.com/iojs/readable-stream/issues/105) +* release and versioning strategy [#101](https://github.com/iojs/readable-stream/issues/101) +* simpler stream creation [#102](https://github.com/iojs/readable-stream/issues/102) +* proposal: deprecate implicit flowing of streams [#99](https://github.com/iojs/readable-stream/issues/99) + +## Minutes + +### adopt a charter + +* group: +1's all around + +### What versioning scheme should be adopted? +* group: +1’s 3.0.0 +* domenic+group: pulling in patches from other sources where appropriate +* mikeal: version independently, suggesting versions for io.js +* mikeal+domenic: work with TC to notify in advance of changes +simpler stream creation + +### streamline creation of streams +* sam: streamline creation of streams +* domenic: nice simple solution posted + but, we lose the opportunity to change the model + may not be backwards incompatible (double check keys) + + **action item:** domenic will check + +### remove implicit flowing of streams on(‘data’) +* add isFlowing / isPaused +* mikeal: worrying that we’re documenting polyfill methods – confuses users +* domenic: more reflective API is probably good, with warning labels for users +* new section for mad scientists (reflective stream access) +* calvin: name the “third state” +* mikeal: maybe borrow the name from whatwg? +* domenic: we’re missing the “third state” +* consensus: kind of difficult to name the third state +* mikeal: figure out differences in states / compat +* mathias: always flow on data – eliminates third state + * explore what it breaks + +**action items:** +* ask isaac for ability to list packages by what public io.js APIs they use (esp. Stream) +* ask rod/build for infrastructure +* **chris**: explore the “flow on data” approach +* add isPaused/isFlowing +* add new docs section +* move isPaused to that section + + diff --git a/backend/node_modules/readable-stream/duplex-browser.js b/backend/node_modules/readable-stream/duplex-browser.js new file mode 100644 index 0000000000000000000000000000000000000000..f8b2db83dbe733d7720264a9840202e29ebeffbd --- /dev/null +++ b/backend/node_modules/readable-stream/duplex-browser.js @@ -0,0 +1 @@ +module.exports = require('./lib/_stream_duplex.js'); diff --git a/backend/node_modules/readable-stream/duplex.js b/backend/node_modules/readable-stream/duplex.js new file mode 100644 index 0000000000000000000000000000000000000000..46924cbfdf53871b574d3f6f5b4bc6064b824aaa --- /dev/null +++ b/backend/node_modules/readable-stream/duplex.js @@ -0,0 +1 @@ +module.exports = require('./readable').Duplex diff --git a/backend/node_modules/readable-stream/lib/_stream_duplex.js b/backend/node_modules/readable-stream/lib/_stream_duplex.js new file mode 100644 index 0000000000000000000000000000000000000000..57003c32d256c0a1fe20dadd279abef2d463074f --- /dev/null +++ b/backend/node_modules/readable-stream/lib/_stream_duplex.js @@ -0,0 +1,131 @@ +// Copyright Joyent, Inc. and other Node 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. + +// a duplex stream is just a stream that is both readable and writable. +// Since JS doesn't have multiple prototypal inheritance, this class +// prototypally inherits from Readable, and then parasitically from +// Writable. + +'use strict'; + +/**/ + +var pna = require('process-nextick-args'); +/**/ + +/**/ +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) { + keys.push(key); + }return keys; +}; +/**/ + +module.exports = Duplex; + +/**/ +var util = Object.create(require('core-util-is')); +util.inherits = require('inherits'); +/**/ + +var Readable = require('./_stream_readable'); +var Writable = require('./_stream_writable'); + +util.inherits(Duplex, Readable); + +{ + // avoid scope creep, the keys array can then be collected + var keys = objectKeys(Writable.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } +} + +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + + Readable.call(this, options); + Writable.call(this, options); + + if (options && options.readable === false) this.readable = false; + + if (options && options.writable === false) this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + + this.once('end', onend); +} + +Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + return this._writableState.highWaterMark; + } +}); + +// the no-half-open enforcer +function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + pna.nextTick(onEndNT, this); +} + +function onEndNT(self) { + self.end(); +} + +Object.defineProperty(Duplex.prototype, 'destroyed', { + get: function () { + if (this._readableState === undefined || this._writableState === undefined) { + return false; + } + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (this._readableState === undefined || this._writableState === undefined) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } +}); + +Duplex.prototype._destroy = function (err, cb) { + this.push(null); + this.end(); + + pna.nextTick(cb, err); +}; \ No newline at end of file diff --git a/backend/node_modules/readable-stream/lib/_stream_passthrough.js b/backend/node_modules/readable-stream/lib/_stream_passthrough.js new file mode 100644 index 0000000000000000000000000000000000000000..612edb4d8b443fabc4ddac619da420bad62fc5b0 --- /dev/null +++ b/backend/node_modules/readable-stream/lib/_stream_passthrough.js @@ -0,0 +1,47 @@ +// Copyright Joyent, Inc. and other Node 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. + +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. + +'use strict'; + +module.exports = PassThrough; + +var Transform = require('./_stream_transform'); + +/**/ +var util = Object.create(require('core-util-is')); +util.inherits = require('inherits'); +/**/ + +util.inherits(PassThrough, Transform); + +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + + Transform.call(this, options); +} + +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); +}; \ No newline at end of file diff --git a/backend/node_modules/readable-stream/lib/_stream_readable.js b/backend/node_modules/readable-stream/lib/_stream_readable.js new file mode 100644 index 0000000000000000000000000000000000000000..3af95cb2dbf1e9fa93d261b030b0b090df507ff7 --- /dev/null +++ b/backend/node_modules/readable-stream/lib/_stream_readable.js @@ -0,0 +1,1019 @@ +// Copyright Joyent, Inc. and other Node 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. + +'use strict'; + +/**/ + +var pna = require('process-nextick-args'); +/**/ + +module.exports = Readable; + +/**/ +var isArray = require('isarray'); +/**/ + +/**/ +var Duplex; +/**/ + +Readable.ReadableState = ReadableState; + +/**/ +var EE = require('events').EventEmitter; + +var EElistenerCount = function (emitter, type) { + return emitter.listeners(type).length; +}; +/**/ + +/**/ +var Stream = require('./internal/streams/stream'); +/**/ + +/**/ + +var Buffer = require('safe-buffer').Buffer; +var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} + +/**/ + +/**/ +var util = Object.create(require('core-util-is')); +util.inherits = require('inherits'); +/**/ + +/**/ +var debugUtil = require('util'); +var debug = void 0; +if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); +} else { + debug = function () {}; +} +/**/ + +var BufferList = require('./internal/streams/BufferList'); +var destroyImpl = require('./internal/streams/destroy'); +var StringDecoder; + +util.inherits(Readable, Stream); + +var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; + +function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); + + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; +} + +function ReadableState(options, stream) { + Duplex = Duplex || require('./_stream_duplex'); + + options = options || {}; + + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + var isDuplex = stream instanceof Duplex; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + + if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var readableHwm = options.readableHighWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + + if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm; + + // cast to ints. + this.highWaterMark = Math.floor(this.highWaterMark); + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the event 'readable'/'data' is emitted + // immediately, or on a later tick. We set this to true at first, because + // any actions that shouldn't happen until "later" should generally also + // not happen before the first read call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + + // has it been destroyed + this.destroyed = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} + +function Readable(options) { + Duplex = Duplex || require('./_stream_duplex'); + + if (!(this instanceof Readable)) return new Readable(options); + + this._readableState = new ReadableState(options, this); + + // legacy + this.readable = true; + + if (options) { + if (typeof options.read === 'function') this._read = options.read; + + if (typeof options.destroy === 'function') this._destroy = options.destroy; + } + + Stream.call(this); +} + +Object.defineProperty(Readable.prototype, 'destroyed', { + get: function () { + if (this._readableState === undefined) { + return false; + } + return this._readableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._readableState) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + } +}); + +Readable.prototype.destroy = destroyImpl.destroy; +Readable.prototype._undestroy = destroyImpl.undestroy; +Readable.prototype._destroy = function (err, cb) { + this.push(null); + cb(err); +}; + +// Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. +Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + var skipChunkCheck; + + if (!state.objectMode) { + if (typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + skipChunkCheck = true; + } + } else { + skipChunkCheck = true; + } + + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); +}; + +// Unshift should *always* be something directly out of read() +Readable.prototype.unshift = function (chunk) { + return readableAddChunk(this, chunk, null, true, false); +}; + +function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { + var state = stream._readableState; + if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { + chunk = _uint8ArrayToBuffer(chunk); + } + + if (addToFront) { + if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true); + } else if (state.ended) { + stream.emit('error', new Error('stream.push() after EOF')); + } else { + state.reading = false; + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); + } else { + addChunk(stream, state, chunk, false); + } + } + } else if (!addToFront) { + state.reading = false; + } + } + + return needMoreData(state); +} + +function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + + if (state.needReadable) emitReadable(stream); + } + maybeReadMore(stream, state); +} + +function chunkInvalid(state, chunk) { + var er; + if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; +} + +// if it's past the high water mark, we can push in some more. +// Also, if we have no data yet, we can stand some +// more bytes. This is to work around cases where hwm=0, +// such as the repl. Also, if the push() triggered a +// readable event, and the user called read(largeNumber) such that +// needReadable was set, then we ought to push more, so that another +// 'readable' event will be triggered. +function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); +} + +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; + +// backwards compatibility. +Readable.prototype.setEncoding = function (enc) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; +}; + +// Don't raise the hwm > 8MB +var MAX_HWM = 0x800000; +function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; +} + +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; +} + +// you can override either this method, or the async _read(n) below. +Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } + + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; + } + + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + + if (ret !== null) this.emit('data', ret); + + return ret; +}; + +function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); +} + +// Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. +function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream); + } +} + +function emitReadable_(stream) { + debug('emit readable'); + stream.emit('readable'); + flow(stream); +} + +// at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + pna.nextTick(maybeReadMore_, stream, state); + } +} + +function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; + } + state.readingMore = false; +} + +// abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. +Readable.prototype._read = function (n) { + this.emit('error', new Error('_read() is not implemented')); +}; + +Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + + var endFn = doEnd ? onend : unpipe; + if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable, unpipeInfo) { + debug('onunpipe'); + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } + } + } + + function onend() { + debug('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', unpipe); + src.removeListener('data', ondata); + + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', state.awaitDrain); + state.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + + return dest; +}; + +function pipeOnDrain(src) { + return function () { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow(src); + } + }; +} + +Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + var unpipeInfo = { hasUnpiped: false }; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + + if (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this, unpipeInfo); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var i = 0; i < len; i++) { + dests[i].emit('unpipe', this, { hasUnpiped: false }); + }return this; + } + + // try to find the right one. + var index = indexOf(state.pipes, dest); + if (index === -1) return this; + + state.pipes.splice(index, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + + dest.emit('unpipe', this, unpipeInfo); + + return this; +}; + +// set up data events if they are asked for +// Ensure readable listeners eventually get something +Readable.prototype.on = function (ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + pna.nextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this); + } + } + } + + return res; +}; +Readable.prototype.addListener = Readable.prototype.on; + +function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); +} + +// pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. +Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + resume(this, state); + } + return this; +}; + +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + pna.nextTick(resume_, stream, state); + } +} + +function resume_(stream, state) { + if (!state.reading) { + debug('resume read 0'); + stream.read(0); + } + + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); +} + +Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; +}; + +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} +} + +// wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. +Readable.prototype.wrap = function (stream) { + var _this = this; + + var state = this._readableState; + var paused = false; + + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); + } + + _this.push(null); + }); + + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + + var ret = _this.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } + + // proxy certain important events. + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + } + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + this._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + + return this; +}; + +Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + return this._readableState.highWaterMark; + } +}); + +// exposed for testing purposes only. +Readable._fromList = fromList; + +// Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); + } + + return ret; +} + +// Extracts only enough buffered data to satisfy the amount requested. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + } + return ret; +} + +// Copies a specified amount of characters from the list of buffered data +// chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; +} + +// Copies a specified amount of bytes from the list of buffered data chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBuffer(n, list) { + var ret = Buffer.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; +} + +function endReadable(stream) { + var state = stream._readableState; + + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + + if (!state.endEmitted) { + state.ended = true; + pna.nextTick(endReadableNT, state, stream); + } +} + +function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } +} + +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; +} \ No newline at end of file diff --git a/backend/node_modules/readable-stream/lib/_stream_transform.js b/backend/node_modules/readable-stream/lib/_stream_transform.js new file mode 100644 index 0000000000000000000000000000000000000000..fcfc105af8e9a124bea4b82011f6cb7d6d2a7158 --- /dev/null +++ b/backend/node_modules/readable-stream/lib/_stream_transform.js @@ -0,0 +1,214 @@ +// Copyright Joyent, Inc. and other Node 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. + +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. + +'use strict'; + +module.exports = Transform; + +var Duplex = require('./_stream_duplex'); + +/**/ +var util = Object.create(require('core-util-is')); +util.inherits = require('inherits'); +/**/ + +util.inherits(Transform, Duplex); + +function afterTransform(er, data) { + var ts = this._transformState; + ts.transforming = false; + + var cb = ts.writecb; + + if (!cb) { + return this.emit('error', new Error('write callback called multiple times')); + } + + ts.writechunk = null; + ts.writecb = null; + + if (data != null) // single equals check for both `null` and `undefined` + this.push(data); + + cb(er); + + var rs = this._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + this._read(rs.highWaterMark); + } +} + +function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + + Duplex.call(this, options); + + this._transformState = { + afterTransform: afterTransform.bind(this), + needTransform: false, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + + if (typeof options.flush === 'function') this._flush = options.flush; + } + + // When the writable side finishes, then flush out anything remaining. + this.on('prefinish', prefinish); +} + +function prefinish() { + var _this = this; + + if (typeof this._flush === 'function') { + this._flush(function (er, data) { + done(_this, er, data); + }); + } else { + done(this, null, null); + } +} + +Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; + +// This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. +Transform.prototype._transform = function (chunk, encoding, cb) { + throw new Error('_transform() is not implemented'); +}; + +Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } +}; + +// Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. +Transform.prototype._read = function (n) { + var ts = this._transformState; + + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } +}; + +Transform.prototype._destroy = function (err, cb) { + var _this2 = this; + + Duplex.prototype._destroy.call(this, err, function (err2) { + cb(err2); + _this2.emit('close'); + }); +}; + +function done(stream, er, data) { + if (er) return stream.emit('error', er); + + if (data != null) // single equals check for both `null` and `undefined` + stream.push(data); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0'); + + if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming'); + + return stream.push(null); +} \ No newline at end of file diff --git a/backend/node_modules/readable-stream/lib/_stream_writable.js b/backend/node_modules/readable-stream/lib/_stream_writable.js new file mode 100644 index 0000000000000000000000000000000000000000..e1e897ff3b098a263aa105d5704dbadce42d5862 --- /dev/null +++ b/backend/node_modules/readable-stream/lib/_stream_writable.js @@ -0,0 +1,685 @@ +// Copyright Joyent, Inc. and other Node 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. + +// A bit simpler than readable streams. +// Implement an async ._write(chunk, encoding, cb), and it'll handle all +// the drain event emission and buffering. + +'use strict'; + +/**/ + +var pna = require('process-nextick-args'); +/**/ + +module.exports = Writable; + +/* */ +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; +} + +// It seems a linked list but it is not +// there will be only 2 of these for each stream +function CorkedRequest(state) { + var _this = this; + + this.next = null; + this.entry = null; + this.finish = function () { + onCorkedFinish(_this, state); + }; +} +/* */ + +/**/ +var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick; +/**/ + +/**/ +var Duplex; +/**/ + +Writable.WritableState = WritableState; + +/**/ +var util = Object.create(require('core-util-is')); +util.inherits = require('inherits'); +/**/ + +/**/ +var internalUtil = { + deprecate: require('util-deprecate') +}; +/**/ + +/**/ +var Stream = require('./internal/streams/stream'); +/**/ + +/**/ + +var Buffer = require('safe-buffer').Buffer; +var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} + +/**/ + +var destroyImpl = require('./internal/streams/destroy'); + +util.inherits(Writable, Stream); + +function nop() {} + +function WritableState(options, stream) { + Duplex = Duplex || require('./_stream_duplex'); + + options = options || {}; + + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + var isDuplex = stream instanceof Duplex; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var writableHwm = options.writableHighWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + + if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm; + + // cast to ints. + this.highWaterMark = Math.floor(this.highWaterMark); + + // if _final has been called + this.finalCalled = false; + + // drain event flag. + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // has it been destroyed + this.destroyed = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); +} + +WritableState.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; +}; + +(function () { + try { + Object.defineProperty(WritableState.prototype, 'buffer', { + get: internalUtil.deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') + }); + } catch (_) {} +})(); + +// Test _writableState for inheritance to account for Duplex streams, +// whose prototype chain only points to Readable. +var realHasInstance; +if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable, Symbol.hasInstance, { + value: function (object) { + if (realHasInstance.call(this, object)) return true; + if (this !== Writable) return false; + + return object && object._writableState instanceof WritableState; + } + }); +} else { + realHasInstance = function (object) { + return object instanceof this; + }; +} + +function Writable(options) { + Duplex = Duplex || require('./_stream_duplex'); + + // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. + + // Trying to use the custom `instanceof` for Writable here will also break the + // Node.js LazyTransform implementation, which has a non-trivial getter for + // `_writableState` that would lead to infinite recursion. + if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) { + return new Writable(options); + } + + this._writableState = new WritableState(options, this); + + // legacy. + this.writable = true; + + if (options) { + if (typeof options.write === 'function') this._write = options.write; + + if (typeof options.writev === 'function') this._writev = options.writev; + + if (typeof options.destroy === 'function') this._destroy = options.destroy; + + if (typeof options.final === 'function') this._final = options.final; + } + + Stream.call(this); +} + +// Otherwise people can pipe Writable streams, which is just wrong. +Writable.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); +}; + +function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + pna.nextTick(cb, er); +} + +// Checks that a user-supplied chunk is valid, especially for the particular +// mode the stream is in. Currently this means that `null` is never accepted +// and undefined/non-string values are only allowed in object mode. +function validChunk(stream, state, chunk, cb) { + var valid = true; + var er = false; + + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + if (er) { + stream.emit('error', er); + pna.nextTick(cb, er); + valid = false; + } + return valid; +} + +Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + var isBuf = !state.objectMode && _isUint8Array(chunk); + + if (isBuf && !Buffer.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer(chunk); + } + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + + if (typeof cb !== 'function') cb = nop; + + if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); + } + + return ret; +}; + +Writable.prototype.cork = function () { + var state = this._writableState; + + state.corked++; +}; + +Writable.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + + if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } +}; + +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; +}; + +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; +} + +Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + return this._writableState.highWaterMark; + } +}); + +// if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. +function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + var newChunk = decodeChunk(state, chunk, encoding); + if (chunk !== newChunk) { + isBuf = true; + encoding = 'buffer'; + chunk = newChunk; + } + } + var len = state.objectMode ? 1 : chunk.length; + + state.length += len; + + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = { + chunk: chunk, + encoding: encoding, + isBuf: isBuf, + callback: cb, + next: null + }; + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + + return ret; +} + +function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} + +function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + + if (sync) { + // defer the callback if we are being called synchronously + // to avoid piling up things on the stack + pna.nextTick(cb, er); + // this can emit finish, and it will always happen + // after error + pna.nextTick(finishMaybe, stream, state); + stream._writableState.errorEmitted = true; + stream.emit('error', er); + } else { + // the caller expect this to happen before if + // it is async + cb(er); + stream._writableState.errorEmitted = true; + stream.emit('error', er); + // this can emit finish, but finish must + // always follow error + finishMaybe(stream, state); + } +} + +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} + +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + + onwriteStateUpdate(state); + + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + + if (sync) { + /**/ + asyncWrite(afterWrite, stream, state, finished, cb); + /**/ + } else { + afterWrite(stream, state, finished, cb); + } + } +} + +function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); +} + +// Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} + +// if there's something in the buffer waiting, then process it +function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + + var count = 0; + var allBuffers = true; + while (entry) { + buffer[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; + } + buffer.allBuffers = allBuffers; + + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + state.bufferedRequestCount = 0; + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + state.bufferedRequestCount--; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + + if (entry === null) state.lastBufferedRequest = null; + } + + state.bufferedRequest = entry; + state.bufferProcessing = false; +} + +Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('_write() is not implemented')); +}; + +Writable.prototype._writev = null; + +Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending) endWritable(this, state, cb); +}; + +function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; +} +function callFinal(stream, state) { + stream._final(function (err) { + state.pendingcb--; + if (err) { + stream.emit('error', err); + } + state.prefinished = true; + stream.emit('prefinish'); + finishMaybe(stream, state); + }); +} +function prefinish(stream, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream._final === 'function') { + state.pendingcb++; + state.finalCalled = true; + pna.nextTick(callFinal, stream, state); + } else { + state.prefinished = true; + stream.emit('prefinish'); + } + } +} + +function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + prefinish(stream, state); + if (state.pendingcb === 0) { + state.finished = true; + stream.emit('finish'); + } + } + return need; +} + +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) pna.nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; +} + +function onCorkedFinish(corkReq, state, err) { + var entry = corkReq.entry; + corkReq.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + + // reuse the free corkReq. + state.corkedRequestsFree.next = corkReq; +} + +Object.defineProperty(Writable.prototype, 'destroyed', { + get: function () { + if (this._writableState === undefined) { + return false; + } + return this._writableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._writableState) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._writableState.destroyed = value; + } +}); + +Writable.prototype.destroy = destroyImpl.destroy; +Writable.prototype._undestroy = destroyImpl.undestroy; +Writable.prototype._destroy = function (err, cb) { + this.end(); + cb(err); +}; \ No newline at end of file diff --git a/backend/node_modules/readable-stream/lib/internal/streams/BufferList.js b/backend/node_modules/readable-stream/lib/internal/streams/BufferList.js new file mode 100644 index 0000000000000000000000000000000000000000..5e080976c3932d544595c14704a7943a9fd9f282 --- /dev/null +++ b/backend/node_modules/readable-stream/lib/internal/streams/BufferList.js @@ -0,0 +1,78 @@ +'use strict'; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var Buffer = require('safe-buffer').Buffer; +var util = require('util'); + +function copyBuffer(src, target, offset) { + src.copy(target, offset); +} + +module.exports = function () { + function BufferList() { + _classCallCheck(this, BufferList); + + this.head = null; + this.tail = null; + this.length = 0; + } + + BufferList.prototype.push = function push(v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + }; + + BufferList.prototype.unshift = function unshift(v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + }; + + BufferList.prototype.shift = function shift() { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + }; + + BufferList.prototype.clear = function clear() { + this.head = this.tail = null; + this.length = 0; + }; + + BufferList.prototype.join = function join(s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; + }; + + BufferList.prototype.concat = function concat(n) { + if (this.length === 0) return Buffer.alloc(0); + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + copyBuffer(p.data, ret, i); + i += p.data.length; + p = p.next; + } + return ret; + }; + + return BufferList; +}(); + +if (util && util.inspect && util.inspect.custom) { + module.exports.prototype[util.inspect.custom] = function () { + var obj = util.inspect({ length: this.length }); + return this.constructor.name + ' ' + obj; + }; +} \ No newline at end of file diff --git a/backend/node_modules/readable-stream/lib/internal/streams/destroy.js b/backend/node_modules/readable-stream/lib/internal/streams/destroy.js new file mode 100644 index 0000000000000000000000000000000000000000..85a821407fce47a9c8f9521ca92538d67d0857ad --- /dev/null +++ b/backend/node_modules/readable-stream/lib/internal/streams/destroy.js @@ -0,0 +1,84 @@ +'use strict'; + +/**/ + +var pna = require('process-nextick-args'); +/**/ + +// undocumented cb() API, needed for core, not for public API +function destroy(err, cb) { + var _this = this; + + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; + + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err) { + if (!this._writableState) { + pna.nextTick(emitErrorNT, this, err); + } else if (!this._writableState.errorEmitted) { + this._writableState.errorEmitted = true; + pna.nextTick(emitErrorNT, this, err); + } + } + + return this; + } + + // we set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks + + if (this._readableState) { + this._readableState.destroyed = true; + } + + // if this is a duplex stream mark the writable part as destroyed as well + if (this._writableState) { + this._writableState.destroyed = true; + } + + this._destroy(err || null, function (err) { + if (!cb && err) { + if (!_this._writableState) { + pna.nextTick(emitErrorNT, _this, err); + } else if (!_this._writableState.errorEmitted) { + _this._writableState.errorEmitted = true; + pna.nextTick(emitErrorNT, _this, err); + } + } else if (cb) { + cb(err); + } + }); + + return this; +} + +function undestroy() { + if (this._readableState) { + this._readableState.destroyed = false; + this._readableState.reading = false; + this._readableState.ended = false; + this._readableState.endEmitted = false; + } + + if (this._writableState) { + this._writableState.destroyed = false; + this._writableState.ended = false; + this._writableState.ending = false; + this._writableState.finalCalled = false; + this._writableState.prefinished = false; + this._writableState.finished = false; + this._writableState.errorEmitted = false; + } +} + +function emitErrorNT(self, err) { + self.emit('error', err); +} + +module.exports = { + destroy: destroy, + undestroy: undestroy +}; \ No newline at end of file diff --git a/backend/node_modules/readable-stream/lib/internal/streams/stream-browser.js b/backend/node_modules/readable-stream/lib/internal/streams/stream-browser.js new file mode 100644 index 0000000000000000000000000000000000000000..9332a3fdae7060505c0a081614e697fa6cb56dc0 --- /dev/null +++ b/backend/node_modules/readable-stream/lib/internal/streams/stream-browser.js @@ -0,0 +1 @@ +module.exports = require('events').EventEmitter; diff --git a/backend/node_modules/readable-stream/lib/internal/streams/stream.js b/backend/node_modules/readable-stream/lib/internal/streams/stream.js new file mode 100644 index 0000000000000000000000000000000000000000..ce2ad5b6ee57f4778a1f4838f7970093c7941c1c --- /dev/null +++ b/backend/node_modules/readable-stream/lib/internal/streams/stream.js @@ -0,0 +1 @@ +module.exports = require('stream'); diff --git a/backend/node_modules/readable-stream/node_modules/safe-buffer/LICENSE b/backend/node_modules/readable-stream/node_modules/safe-buffer/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..0c068ceecbd48fc4e8279e6451793fec2bf12178 --- /dev/null +++ b/backend/node_modules/readable-stream/node_modules/safe-buffer/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Feross Aboukhadijeh + +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/backend/node_modules/readable-stream/node_modules/safe-buffer/README.md b/backend/node_modules/readable-stream/node_modules/safe-buffer/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e9a81afd0406f030ba21169f0c7a1dba70b3a93b --- /dev/null +++ b/backend/node_modules/readable-stream/node_modules/safe-buffer/README.md @@ -0,0 +1,584 @@ +# safe-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] + +[travis-image]: https://img.shields.io/travis/feross/safe-buffer/master.svg +[travis-url]: https://travis-ci.org/feross/safe-buffer +[npm-image]: https://img.shields.io/npm/v/safe-buffer.svg +[npm-url]: https://npmjs.org/package/safe-buffer +[downloads-image]: https://img.shields.io/npm/dm/safe-buffer.svg +[downloads-url]: https://npmjs.org/package/safe-buffer +[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg +[standard-url]: https://standardjs.com + +#### Safer Node.js Buffer API + +**Use the new Node.js Buffer APIs (`Buffer.from`, `Buffer.alloc`, +`Buffer.allocUnsafe`, `Buffer.allocUnsafeSlow`) in all versions of Node.js.** + +**Uses the built-in implementation when available.** + +## install + +``` +npm install safe-buffer +``` + +## usage + +The goal of this package is to provide a safe replacement for the node.js `Buffer`. + +It's a drop-in replacement for `Buffer`. You can use it by adding one `require` line to +the top of your node.js modules: + +```js +var Buffer = require('safe-buffer').Buffer + +// Existing buffer code will continue to work without issues: + +new Buffer('hey', 'utf8') +new Buffer([1, 2, 3], 'utf8') +new Buffer(obj) +new Buffer(16) // create an uninitialized buffer (potentially unsafe) + +// But you can use these new explicit APIs to make clear what you want: + +Buffer.from('hey', 'utf8') // convert from many types to a Buffer +Buffer.alloc(16) // create a zero-filled buffer (safe) +Buffer.allocUnsafe(16) // create an uninitialized buffer (potentially unsafe) +``` + +## api + +### Class Method: Buffer.from(array) + + +* `array` {Array} + +Allocates a new `Buffer` using an `array` of octets. + +```js +const buf = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]); + // creates a new Buffer containing ASCII bytes + // ['b','u','f','f','e','r'] +``` + +A `TypeError` will be thrown if `array` is not an `Array`. + +### Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) + + +* `arrayBuffer` {ArrayBuffer} The `.buffer` property of a `TypedArray` or + a `new ArrayBuffer()` +* `byteOffset` {Number} Default: `0` +* `length` {Number} 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. + +```js +const arr = new Uint16Array(2); +arr[0] = 5000; +arr[1] = 4000; + +const buf = Buffer.from(arr.buffer); // shares the memory with arr; + +console.log(buf); + // Prints: + +// changing the TypedArray changes the Buffer also +arr[1] = 6000; + +console.log(buf); + // Prints: +``` + +The optional `byteOffset` and `length` arguments specify a memory range within +the `arrayBuffer` that will be shared by the `Buffer`. + +```js +const ab = new ArrayBuffer(10); +const buf = Buffer.from(ab, 0, 2); +console.log(buf.length); + // Prints: 2 +``` + +A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer`. + +### Class Method: Buffer.from(buffer) + + +* `buffer` {Buffer} + +Copies the passed `buffer` data onto a new `Buffer` instance. + +```js +const buf1 = Buffer.from('buffer'); +const buf2 = Buffer.from(buf1); + +buf1[0] = 0x61; +console.log(buf1.toString()); + // 'auffer' +console.log(buf2.toString()); + // 'buffer' (copy is not changed) +``` + +A `TypeError` will be thrown if `buffer` is not a `Buffer`. + +### Class Method: Buffer.from(str[, encoding]) + + +* `str` {String} String to encode. +* `encoding` {String} Encoding to use, Default: `'utf8'` + +Creates a new `Buffer` containing the given JavaScript string `str`. If +provided, the `encoding` parameter identifies the character encoding. +If not provided, `encoding` defaults to `'utf8'`. + +```js +const buf1 = Buffer.from('this is a tést'); +console.log(buf1.toString()); + // prints: this is a tést +console.log(buf1.toString('ascii')); + // prints: this is a tC)st + +const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); +console.log(buf2.toString()); + // prints: this is a tést +``` + +A `TypeError` will be thrown if `str` is not a string. + +### Class Method: Buffer.alloc(size[, fill[, encoding]]) + + +* `size` {Number} +* `fill` {Value} Default: `undefined` +* `encoding` {String} Default: `utf8` + +Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the +`Buffer` will be *zero-filled*. + +```js +const buf = Buffer.alloc(5); +console.log(buf); + // +``` + +The `size` must be less than or equal to the value of +`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is +`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will +be created if a `size` less than or equal to 0 is specified. + +If `fill` is specified, the allocated `Buffer` will be initialized by calling +`buf.fill(fill)`. See [`buf.fill()`][] for more information. + +```js +const buf = Buffer.alloc(5, 'a'); +console.log(buf); + // +``` + +If both `fill` and `encoding` are specified, the allocated `Buffer` will be +initialized by calling `buf.fill(fill, encoding)`. For example: + +```js +const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); +console.log(buf); + // +``` + +Calling `Buffer.alloc(size)` can be significantly slower than the alternative +`Buffer.allocUnsafe(size)` but ensures that the newly created `Buffer` instance +contents will *never contain sensitive data*. + +A `TypeError` will be thrown if `size` is not a number. + +### Class Method: Buffer.allocUnsafe(size) + + +* `size` {Number} + +Allocates a new *non-zero-filled* `Buffer` of `size` bytes. The `size` must +be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit +architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is +thrown. A zero-length Buffer will be created if a `size` less than or equal to +0 is specified. + +The underlying memory for `Buffer` instances created in this way is *not +initialized*. The contents of the newly created `Buffer` are unknown and +*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such +`Buffer` instances to zeroes. + +```js +const buf = Buffer.allocUnsafe(5); +console.log(buf); + // + // (octets will be different, every time) +buf.fill(0); +console.log(buf); + // +``` + +A `TypeError` will be thrown if `size` is not a number. + +Note that the `Buffer` module pre-allocates an internal `Buffer` instance of +size `Buffer.poolSize` that is used as a pool for the fast allocation of new +`Buffer` instances created using `Buffer.allocUnsafe(size)` (and the deprecated +`new Buffer(size)` constructor) only when `size` is less than or equal to +`Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). The default +value of `Buffer.poolSize` is `8192` but can be modified. + +Use of this pre-allocated internal memory pool is a key difference between +calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. +Specifically, `Buffer.alloc(size, fill)` will *never* use the internal Buffer +pool, while `Buffer.allocUnsafe(size).fill(fill)` *will* use the internal +Buffer pool if `size` is less than or equal to half `Buffer.poolSize`. The +difference is subtle but can be important when an application requires the +additional performance that `Buffer.allocUnsafe(size)` provides. + +### Class Method: Buffer.allocUnsafeSlow(size) + + +* `size` {Number} + +Allocates a new *non-zero-filled* and non-pooled `Buffer` of `size` bytes. The +`size` must be less than or equal to the value of +`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is +`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will +be created if a `size` less than or equal to 0 is specified. + +The underlying memory for `Buffer` instances created in this way is *not +initialized*. The contents of the newly created `Buffer` are unknown and +*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such +`Buffer` instances to zeroes. + +When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, +allocations under 4KB are, by default, sliced from a single pre-allocated +`Buffer`. This allows applications to avoid the garbage collection overhead of +creating many individually allocated Buffers. This approach improves both +performance and memory usage by eliminating the need to track and cleanup as +many `Persistent` objects. + +However, in the case where a developer may need to retain a small chunk of +memory from a pool for an indeterminate amount of time, it may be appropriate +to create an un-pooled Buffer instance using `Buffer.allocUnsafeSlow()` then +copy out the relevant bits. + +```js +// need to keep around a few small chunks of memory +const store = []; + +socket.on('readable', () => { + const data = socket.read(); + // allocate for retained data + const sb = Buffer.allocUnsafeSlow(10); + // copy the data into the new allocation + data.copy(sb, 0, 0, 10); + store.push(sb); +}); +``` + +Use of `Buffer.allocUnsafeSlow()` should be used only as a last resort *after* +a developer has observed undue memory retention in their applications. + +A `TypeError` will be thrown if `size` is not a number. + +### All the Rest + +The rest of the `Buffer` API is exactly the same as in node.js. +[See the docs](https://nodejs.org/api/buffer.html). + + +## Related links + +- [Node.js issue: Buffer(number) is unsafe](https://github.com/nodejs/node/issues/4660) +- [Node.js Enhancement Proposal: Buffer.from/Buffer.alloc/Buffer.zalloc/Buffer() soft-deprecate](https://github.com/nodejs/node-eps/pull/4) + +## Why is `Buffer` unsafe? + +Today, the node.js `Buffer` constructor is overloaded to handle many different argument +types like `String`, `Array`, `Object`, `TypedArrayView` (`Uint8Array`, etc.), +`ArrayBuffer`, and also `Number`. + +The API is optimized for convenience: you can throw any type at it, and it will try to do +what you want. + +Because the Buffer constructor is so powerful, you often see code like this: + +```js +// Convert UTF-8 strings to hex +function toHex (str) { + return new Buffer(str).toString('hex') +} +``` + +***But what happens if `toHex` is called with a `Number` argument?*** + +### Remote Memory Disclosure + +If an attacker can make your program call the `Buffer` constructor with a `Number` +argument, then they can make it allocate uninitialized memory from the node.js process. +This could potentially disclose TLS private keys, user data, or database passwords. + +When the `Buffer` constructor is passed a `Number` argument, it returns an +**UNINITIALIZED** block of memory of the specified `size`. When you create a `Buffer` like +this, you **MUST** overwrite the contents before returning it to the user. + +From the [node.js docs](https://nodejs.org/api/buffer.html#buffer_new_buffer_size): + +> `new Buffer(size)` +> +> - `size` Number +> +> The underlying memory for `Buffer` instances created in this way is not initialized. +> **The contents of a newly created `Buffer` are unknown and could contain sensitive +> data.** Use `buf.fill(0)` to initialize a Buffer to zeroes. + +(Emphasis our own.) + +Whenever the programmer intended to create an uninitialized `Buffer` you often see code +like this: + +```js +var buf = new Buffer(16) + +// Immediately overwrite the uninitialized buffer with data from another buffer +for (var i = 0; i < buf.length; i++) { + buf[i] = otherBuf[i] +} +``` + + +### Would this ever be a problem in real code? + +Yes. It's surprisingly common to forget to check the type of your variables in a +dynamically-typed language like JavaScript. + +Usually the consequences of assuming the wrong type is that your program crashes with an +uncaught exception. But the failure mode for forgetting to check the type of arguments to +the `Buffer` constructor is more catastrophic. + +Here's an example of a vulnerable service that takes a JSON payload and converts it to +hex: + +```js +// Take a JSON payload {str: "some string"} and convert it to hex +var server = http.createServer(function (req, res) { + var data = '' + req.setEncoding('utf8') + req.on('data', function (chunk) { + data += chunk + }) + req.on('end', function () { + var body = JSON.parse(data) + res.end(new Buffer(body.str).toString('hex')) + }) +}) + +server.listen(8080) +``` + +In this example, an http client just has to send: + +```json +{ + "str": 1000 +} +``` + +and it will get back 1,000 bytes of uninitialized memory from the server. + +This is a very serious bug. It's similar in severity to the +[the Heartbleed bug](http://heartbleed.com/) that allowed disclosure of OpenSSL process +memory by remote attackers. + + +### Which real-world packages were vulnerable? + +#### [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht) + +[Mathias Buus](https://github.com/mafintosh) and I +([Feross Aboukhadijeh](http://feross.org/)) found this issue in one of our own packages, +[`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht). The bug would allow +anyone on the internet to send a series of messages to a user of `bittorrent-dht` and get +them to reveal 20 bytes at a time of uninitialized memory from the node.js process. + +Here's +[the commit](https://github.com/feross/bittorrent-dht/commit/6c7da04025d5633699800a99ec3fbadf70ad35b8) +that fixed it. We released a new fixed version, created a +[Node Security Project disclosure](https://nodesecurity.io/advisories/68), and deprecated all +vulnerable versions on npm so users will get a warning to upgrade to a newer version. + +#### [`ws`](https://www.npmjs.com/package/ws) + +That got us wondering if there were other vulnerable packages. Sure enough, within a short +period of time, we found the same issue in [`ws`](https://www.npmjs.com/package/ws), the +most popular WebSocket implementation in node.js. + +If certain APIs were called with `Number` parameters instead of `String` or `Buffer` as +expected, then uninitialized server memory would be disclosed to the remote peer. + +These were the vulnerable methods: + +```js +socket.send(number) +socket.ping(number) +socket.pong(number) +``` + +Here's a vulnerable socket server with some echo functionality: + +```js +server.on('connection', function (socket) { + socket.on('message', function (message) { + message = JSON.parse(message) + if (message.type === 'echo') { + socket.send(message.data) // send back the user's message + } + }) +}) +``` + +`socket.send(number)` called on the server, will disclose server memory. + +Here's [the release](https://github.com/websockets/ws/releases/tag/1.0.1) where the issue +was fixed, with a more detailed explanation. Props to +[Arnout Kazemier](https://github.com/3rd-Eden) for the quick fix. Here's the +[Node Security Project disclosure](https://nodesecurity.io/advisories/67). + + +### What's the solution? + +It's important that node.js offers a fast way to get memory otherwise performance-critical +applications would needlessly get a lot slower. + +But we need a better way to *signal our intent* as programmers. **When we want +uninitialized memory, we should request it explicitly.** + +Sensitive functionality should not be packed into a developer-friendly API that loosely +accepts many different types. This type of API encourages the lazy practice of passing +variables in without checking the type very carefully. + +#### A new API: `Buffer.allocUnsafe(number)` + +The functionality of creating buffers with uninitialized memory should be part of another +API. We propose `Buffer.allocUnsafe(number)`. This way, it's not part of an API that +frequently gets user input of all sorts of different types passed into it. + +```js +var buf = Buffer.allocUnsafe(16) // careful, uninitialized memory! + +// Immediately overwrite the uninitialized buffer with data from another buffer +for (var i = 0; i < buf.length; i++) { + buf[i] = otherBuf[i] +} +``` + + +### How do we fix node.js core? + +We sent [a PR to node.js core](https://github.com/nodejs/node/pull/4514) (merged as +`semver-major`) which defends against one case: + +```js +var str = 16 +new Buffer(str, 'utf8') +``` + +In this situation, it's implied that the programmer intended the first argument to be a +string, since they passed an encoding as a second argument. Today, node.js will allocate +uninitialized memory in the case of `new Buffer(number, encoding)`, which is probably not +what the programmer intended. + +But this is only a partial solution, since if the programmer does `new Buffer(variable)` +(without an `encoding` parameter) there's no way to know what they intended. If `variable` +is sometimes a number, then uninitialized memory will sometimes be returned. + +### What's the real long-term fix? + +We could deprecate and remove `new Buffer(number)` and use `Buffer.allocUnsafe(number)` when +we need uninitialized memory. But that would break 1000s of packages. + +~~We believe the best solution is to:~~ + +~~1. Change `new Buffer(number)` to return safe, zeroed-out memory~~ + +~~2. Create a new API for creating uninitialized Buffers. We propose: `Buffer.allocUnsafe(number)`~~ + +#### Update + +We now support adding three new APIs: + +- `Buffer.from(value)` - convert from any type to a buffer +- `Buffer.alloc(size)` - create a zero-filled buffer +- `Buffer.allocUnsafe(size)` - create an uninitialized buffer with given size + +This solves the core problem that affected `ws` and `bittorrent-dht` which is +`Buffer(variable)` getting tricked into taking a number argument. + +This way, existing code continues working and the impact on the npm ecosystem will be +minimal. Over time, npm maintainers can migrate performance-critical code to use +`Buffer.allocUnsafe(number)` instead of `new Buffer(number)`. + + +### Conclusion + +We think there's a serious design issue with the `Buffer` API as it exists today. It +promotes insecure software by putting high-risk functionality into a convenient API +with friendly "developer ergonomics". + +This wasn't merely a theoretical exercise because we found the issue in some of the +most popular npm packages. + +Fortunately, there's an easy fix that can be applied today. Use `safe-buffer` in place of +`buffer`. + +```js +var Buffer = require('safe-buffer').Buffer +``` + +Eventually, we hope that node.js core can switch to this new, safer behavior. We believe +the impact on the ecosystem would be minimal since it's not a breaking change. +Well-maintained, popular packages would be updated to use `Buffer.alloc` quickly, while +older, insecure packages would magically become safe from this attack vector. + + +## links + +- [Node.js PR: buffer: throw if both length and enc are passed](https://github.com/nodejs/node/pull/4514) +- [Node Security Project disclosure for `ws`](https://nodesecurity.io/advisories/67) +- [Node Security Project disclosure for`bittorrent-dht`](https://nodesecurity.io/advisories/68) + + +## credit + +The original issues in `bittorrent-dht` +([disclosure](https://nodesecurity.io/advisories/68)) and +`ws` ([disclosure](https://nodesecurity.io/advisories/67)) were discovered by +[Mathias Buus](https://github.com/mafintosh) and +[Feross Aboukhadijeh](http://feross.org/). + +Thanks to [Adam Baldwin](https://github.com/evilpacket) for helping disclose these issues +and for his work running the [Node Security Project](https://nodesecurity.io/). + +Thanks to [John Hiesey](https://github.com/jhiesey) for proofreading this README and +auditing the code. + + +## license + +MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org) diff --git a/backend/node_modules/readable-stream/node_modules/safe-buffer/index.d.ts b/backend/node_modules/readable-stream/node_modules/safe-buffer/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e9fed809a5ab515658d6e71f7ba5f631be769be4 --- /dev/null +++ b/backend/node_modules/readable-stream/node_modules/safe-buffer/index.d.ts @@ -0,0 +1,187 @@ +declare module "safe-buffer" { + export class Buffer { + length: number + write(string: string, offset?: number, length?: number, encoding?: string): number; + toString(encoding?: string, start?: number, end?: number): string; + toJSON(): { type: 'Buffer', data: any[] }; + equals(otherBuffer: Buffer): boolean; + compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; + copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + slice(start?: number, end?: number): Buffer; + writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readUInt8(offset: number, noAssert?: boolean): number; + readUInt16LE(offset: number, noAssert?: boolean): number; + readUInt16BE(offset: number, noAssert?: boolean): number; + readUInt32LE(offset: number, noAssert?: boolean): number; + readUInt32BE(offset: number, noAssert?: boolean): number; + readInt8(offset: number, noAssert?: boolean): number; + readInt16LE(offset: number, noAssert?: boolean): number; + readInt16BE(offset: number, noAssert?: boolean): number; + readInt32LE(offset: number, noAssert?: boolean): number; + readInt32BE(offset: number, noAssert?: boolean): number; + readFloatLE(offset: number, noAssert?: boolean): number; + readFloatBE(offset: number, noAssert?: boolean): number; + readDoubleLE(offset: number, noAssert?: boolean): number; + readDoubleBE(offset: number, noAssert?: boolean): number; + swap16(): Buffer; + swap32(): Buffer; + swap64(): Buffer; + writeUInt8(value: number, offset: number, noAssert?: boolean): number; + writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeInt8(value: number, offset: number, noAssert?: boolean): number; + writeInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeFloatLE(value: number, offset: number, noAssert?: boolean): number; + writeFloatBE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; + fill(value: any, offset?: number, end?: number): this; + indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; + + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + */ + constructor (str: string, encoding?: string); + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + */ + constructor (size: number); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + constructor (array: Uint8Array); + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}. + * + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + */ + constructor (arrayBuffer: ArrayBuffer); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + constructor (array: any[]); + /** + * Copies the passed {buffer} data onto a new {Buffer} instance. + * + * @param buffer The buffer to copy. + */ + constructor (buffer: Buffer); + prototype: Buffer; + /** + * Allocates a new Buffer using an {array} of octets. + * + * @param array + */ + static from(array: any[]): Buffer; + /** + * 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. + * + * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer() + * @param byteOffset + * @param length + */ + static from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer; + /** + * Copies the passed {buffer} data onto a new Buffer instance. + * + * @param buffer + */ + static from(buffer: Buffer): Buffer; + /** + * Creates a new Buffer containing the given JavaScript string {str}. + * If provided, the {encoding} parameter identifies the character encoding. + * If not provided, {encoding} defaults to 'utf8'. + * + * @param str + */ + static from(str: string, encoding?: string): Buffer; + /** + * Returns true if {obj} is a Buffer + * + * @param obj object to test. + */ + static isBuffer(obj: any): obj is Buffer; + /** + * Returns true if {encoding} is a valid encoding argument. + * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' + * + * @param encoding string to test. + */ + static isEncoding(encoding: string): boolean; + /** + * Gives the actual byte length of a string. encoding defaults to 'utf8'. + * This is not the same as String.prototype.length since that returns the number of characters in a string. + * + * @param string string to test. + * @param encoding encoding used to evaluate (defaults to 'utf8') + */ + static byteLength(string: string, encoding?: string): number; + /** + * Returns a buffer which is the result of concatenating all the buffers in the list together. + * + * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. + * If the list has exactly one item, then the first item of the list is returned. + * If the list has more than one item, then a new Buffer is created. + * + * @param list An array of Buffer objects to concatenate + * @param totalLength Total length of the buffers when concatenated. + * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. + */ + static concat(list: Buffer[], totalLength?: number): Buffer; + /** + * The same as buf1.compare(buf2). + */ + static compare(buf1: Buffer, buf2: Buffer): number; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @param fill if specified, buffer will be initialized by calling buf.fill(fill). + * If parameter is omitted, buffer will be filled with zeros. + * @param encoding encoding used for call to buf.fill while initalizing + */ + static alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer; + /** + * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + static allocUnsafe(size: number): Buffer; + /** + * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + static allocUnsafeSlow(size: number): Buffer; + } +} \ No newline at end of file diff --git a/backend/node_modules/readable-stream/node_modules/safe-buffer/index.js b/backend/node_modules/readable-stream/node_modules/safe-buffer/index.js new file mode 100644 index 0000000000000000000000000000000000000000..22438dabbbceef6954a1a7a68038f8c440a90c79 --- /dev/null +++ b/backend/node_modules/readable-stream/node_modules/safe-buffer/index.js @@ -0,0 +1,62 @@ +/* eslint-disable node/no-deprecated-api */ +var buffer = require('buffer') +var Buffer = buffer.Buffer + +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] + } +} +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer +} + +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) +} + +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) + +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + } else { + buf.fill(0) + } + return buf +} + +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +} + +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} diff --git a/backend/node_modules/readable-stream/node_modules/safe-buffer/package.json b/backend/node_modules/readable-stream/node_modules/safe-buffer/package.json new file mode 100644 index 0000000000000000000000000000000000000000..623fbc3f6b0c480fb0b3257fc666b1db827378bf --- /dev/null +++ b/backend/node_modules/readable-stream/node_modules/safe-buffer/package.json @@ -0,0 +1,37 @@ +{ + "name": "safe-buffer", + "description": "Safer Node.js Buffer API", + "version": "5.1.2", + "author": { + "name": "Feross Aboukhadijeh", + "email": "feross@feross.org", + "url": "http://feross.org" + }, + "bugs": { + "url": "https://github.com/feross/safe-buffer/issues" + }, + "devDependencies": { + "standard": "*", + "tape": "^4.0.0" + }, + "homepage": "https://github.com/feross/safe-buffer", + "keywords": [ + "buffer", + "buffer allocate", + "node security", + "safe", + "safe-buffer", + "security", + "uninitialized" + ], + "license": "MIT", + "main": "index.js", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "git://github.com/feross/safe-buffer.git" + }, + "scripts": { + "test": "standard && tape test/*.js" + } +} diff --git a/backend/node_modules/readable-stream/package.json b/backend/node_modules/readable-stream/package.json new file mode 100644 index 0000000000000000000000000000000000000000..514c178e92045e082de6358f427d981f5b74d3d9 --- /dev/null +++ b/backend/node_modules/readable-stream/package.json @@ -0,0 +1,52 @@ +{ + "name": "readable-stream", + "version": "2.3.8", + "description": "Streams3, a user-land copy of the stream library from Node.js", + "main": "readable.js", + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + }, + "devDependencies": { + "assert": "^1.4.0", + "babel-polyfill": "^6.9.1", + "buffer": "^4.9.0", + "lolex": "^2.3.2", + "nyc": "^6.4.0", + "tap": "^0.7.0", + "tape": "^4.8.0" + }, + "scripts": { + "test": "tap test/parallel/*.js test/ours/*.js && node test/verify-dependencies.js", + "ci": "tap test/parallel/*.js test/ours/*.js --tap | tee test.tap && node test/verify-dependencies.js", + "cover": "nyc npm test", + "report": "nyc report --reporter=lcov" + }, + "repository": { + "type": "git", + "url": "git://github.com/nodejs/readable-stream" + }, + "keywords": [ + "readable", + "stream", + "pipe" + ], + "browser": { + "util": false, + "./readable.js": "./readable-browser.js", + "./writable.js": "./writable-browser.js", + "./duplex.js": "./duplex-browser.js", + "./lib/internal/streams/stream.js": "./lib/internal/streams/stream-browser.js" + }, + "nyc": { + "include": [ + "lib/**.js" + ] + }, + "license": "MIT" +} diff --git a/backend/node_modules/readable-stream/passthrough.js b/backend/node_modules/readable-stream/passthrough.js new file mode 100644 index 0000000000000000000000000000000000000000..ffd791d7ff275a58d537ea89153175a23edee5fb --- /dev/null +++ b/backend/node_modules/readable-stream/passthrough.js @@ -0,0 +1 @@ +module.exports = require('./readable').PassThrough diff --git a/backend/node_modules/readable-stream/readable-browser.js b/backend/node_modules/readable-stream/readable-browser.js new file mode 100644 index 0000000000000000000000000000000000000000..e50372592ee6c63a7fc43cb912dd9639e3fa7eb1 --- /dev/null +++ b/backend/node_modules/readable-stream/readable-browser.js @@ -0,0 +1,7 @@ +exports = module.exports = require('./lib/_stream_readable.js'); +exports.Stream = exports; +exports.Readable = exports; +exports.Writable = require('./lib/_stream_writable.js'); +exports.Duplex = require('./lib/_stream_duplex.js'); +exports.Transform = require('./lib/_stream_transform.js'); +exports.PassThrough = require('./lib/_stream_passthrough.js'); diff --git a/backend/node_modules/readable-stream/readable.js b/backend/node_modules/readable-stream/readable.js new file mode 100644 index 0000000000000000000000000000000000000000..ec89ec53306497adae0014c4a8aba6d51d1aff6c --- /dev/null +++ b/backend/node_modules/readable-stream/readable.js @@ -0,0 +1,19 @@ +var Stream = require('stream'); +if (process.env.READABLE_STREAM === 'disable' && Stream) { + module.exports = Stream; + exports = module.exports = Stream.Readable; + exports.Readable = Stream.Readable; + exports.Writable = Stream.Writable; + exports.Duplex = Stream.Duplex; + exports.Transform = Stream.Transform; + exports.PassThrough = Stream.PassThrough; + exports.Stream = Stream; +} else { + exports = module.exports = require('./lib/_stream_readable.js'); + exports.Stream = Stream || exports; + exports.Readable = exports; + exports.Writable = require('./lib/_stream_writable.js'); + exports.Duplex = require('./lib/_stream_duplex.js'); + exports.Transform = require('./lib/_stream_transform.js'); + exports.PassThrough = require('./lib/_stream_passthrough.js'); +} diff --git a/backend/node_modules/readable-stream/transform.js b/backend/node_modules/readable-stream/transform.js new file mode 100644 index 0000000000000000000000000000000000000000..b1baba26da03dc8bbc5d9da33cd55f3f88c99115 --- /dev/null +++ b/backend/node_modules/readable-stream/transform.js @@ -0,0 +1 @@ +module.exports = require('./readable').Transform diff --git a/backend/node_modules/readable-stream/writable-browser.js b/backend/node_modules/readable-stream/writable-browser.js new file mode 100644 index 0000000000000000000000000000000000000000..ebdde6a85dcb19bfdbfc2ec2e34b13a54c0e5bf0 --- /dev/null +++ b/backend/node_modules/readable-stream/writable-browser.js @@ -0,0 +1 @@ +module.exports = require('./lib/_stream_writable.js'); diff --git a/backend/node_modules/readable-stream/writable.js b/backend/node_modules/readable-stream/writable.js new file mode 100644 index 0000000000000000000000000000000000000000..3211a6f80d1abc9db7099cd1e8fa200ad2ccfdbe --- /dev/null +++ b/backend/node_modules/readable-stream/writable.js @@ -0,0 +1,8 @@ +var Stream = require("stream") +var Writable = require("./lib/_stream_writable.js") + +if (process.env.READABLE_STREAM === 'disable') { + module.exports = Stream && Stream.Writable || Writable +} else { + module.exports = Writable +} diff --git a/backend/node_modules/safe-buffer/LICENSE b/backend/node_modules/safe-buffer/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..0c068ceecbd48fc4e8279e6451793fec2bf12178 --- /dev/null +++ b/backend/node_modules/safe-buffer/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Feross Aboukhadijeh + +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/backend/node_modules/safe-buffer/README.md b/backend/node_modules/safe-buffer/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e9a81afd0406f030ba21169f0c7a1dba70b3a93b --- /dev/null +++ b/backend/node_modules/safe-buffer/README.md @@ -0,0 +1,584 @@ +# safe-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] + +[travis-image]: https://img.shields.io/travis/feross/safe-buffer/master.svg +[travis-url]: https://travis-ci.org/feross/safe-buffer +[npm-image]: https://img.shields.io/npm/v/safe-buffer.svg +[npm-url]: https://npmjs.org/package/safe-buffer +[downloads-image]: https://img.shields.io/npm/dm/safe-buffer.svg +[downloads-url]: https://npmjs.org/package/safe-buffer +[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg +[standard-url]: https://standardjs.com + +#### Safer Node.js Buffer API + +**Use the new Node.js Buffer APIs (`Buffer.from`, `Buffer.alloc`, +`Buffer.allocUnsafe`, `Buffer.allocUnsafeSlow`) in all versions of Node.js.** + +**Uses the built-in implementation when available.** + +## install + +``` +npm install safe-buffer +``` + +## usage + +The goal of this package is to provide a safe replacement for the node.js `Buffer`. + +It's a drop-in replacement for `Buffer`. You can use it by adding one `require` line to +the top of your node.js modules: + +```js +var Buffer = require('safe-buffer').Buffer + +// Existing buffer code will continue to work without issues: + +new Buffer('hey', 'utf8') +new Buffer([1, 2, 3], 'utf8') +new Buffer(obj) +new Buffer(16) // create an uninitialized buffer (potentially unsafe) + +// But you can use these new explicit APIs to make clear what you want: + +Buffer.from('hey', 'utf8') // convert from many types to a Buffer +Buffer.alloc(16) // create a zero-filled buffer (safe) +Buffer.allocUnsafe(16) // create an uninitialized buffer (potentially unsafe) +``` + +## api + +### Class Method: Buffer.from(array) + + +* `array` {Array} + +Allocates a new `Buffer` using an `array` of octets. + +```js +const buf = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]); + // creates a new Buffer containing ASCII bytes + // ['b','u','f','f','e','r'] +``` + +A `TypeError` will be thrown if `array` is not an `Array`. + +### Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) + + +* `arrayBuffer` {ArrayBuffer} The `.buffer` property of a `TypedArray` or + a `new ArrayBuffer()` +* `byteOffset` {Number} Default: `0` +* `length` {Number} 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. + +```js +const arr = new Uint16Array(2); +arr[0] = 5000; +arr[1] = 4000; + +const buf = Buffer.from(arr.buffer); // shares the memory with arr; + +console.log(buf); + // Prints: + +// changing the TypedArray changes the Buffer also +arr[1] = 6000; + +console.log(buf); + // Prints: +``` + +The optional `byteOffset` and `length` arguments specify a memory range within +the `arrayBuffer` that will be shared by the `Buffer`. + +```js +const ab = new ArrayBuffer(10); +const buf = Buffer.from(ab, 0, 2); +console.log(buf.length); + // Prints: 2 +``` + +A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer`. + +### Class Method: Buffer.from(buffer) + + +* `buffer` {Buffer} + +Copies the passed `buffer` data onto a new `Buffer` instance. + +```js +const buf1 = Buffer.from('buffer'); +const buf2 = Buffer.from(buf1); + +buf1[0] = 0x61; +console.log(buf1.toString()); + // 'auffer' +console.log(buf2.toString()); + // 'buffer' (copy is not changed) +``` + +A `TypeError` will be thrown if `buffer` is not a `Buffer`. + +### Class Method: Buffer.from(str[, encoding]) + + +* `str` {String} String to encode. +* `encoding` {String} Encoding to use, Default: `'utf8'` + +Creates a new `Buffer` containing the given JavaScript string `str`. If +provided, the `encoding` parameter identifies the character encoding. +If not provided, `encoding` defaults to `'utf8'`. + +```js +const buf1 = Buffer.from('this is a tést'); +console.log(buf1.toString()); + // prints: this is a tést +console.log(buf1.toString('ascii')); + // prints: this is a tC)st + +const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); +console.log(buf2.toString()); + // prints: this is a tést +``` + +A `TypeError` will be thrown if `str` is not a string. + +### Class Method: Buffer.alloc(size[, fill[, encoding]]) + + +* `size` {Number} +* `fill` {Value} Default: `undefined` +* `encoding` {String} Default: `utf8` + +Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the +`Buffer` will be *zero-filled*. + +```js +const buf = Buffer.alloc(5); +console.log(buf); + // +``` + +The `size` must be less than or equal to the value of +`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is +`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will +be created if a `size` less than or equal to 0 is specified. + +If `fill` is specified, the allocated `Buffer` will be initialized by calling +`buf.fill(fill)`. See [`buf.fill()`][] for more information. + +```js +const buf = Buffer.alloc(5, 'a'); +console.log(buf); + // +``` + +If both `fill` and `encoding` are specified, the allocated `Buffer` will be +initialized by calling `buf.fill(fill, encoding)`. For example: + +```js +const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); +console.log(buf); + // +``` + +Calling `Buffer.alloc(size)` can be significantly slower than the alternative +`Buffer.allocUnsafe(size)` but ensures that the newly created `Buffer` instance +contents will *never contain sensitive data*. + +A `TypeError` will be thrown if `size` is not a number. + +### Class Method: Buffer.allocUnsafe(size) + + +* `size` {Number} + +Allocates a new *non-zero-filled* `Buffer` of `size` bytes. The `size` must +be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit +architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is +thrown. A zero-length Buffer will be created if a `size` less than or equal to +0 is specified. + +The underlying memory for `Buffer` instances created in this way is *not +initialized*. The contents of the newly created `Buffer` are unknown and +*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such +`Buffer` instances to zeroes. + +```js +const buf = Buffer.allocUnsafe(5); +console.log(buf); + // + // (octets will be different, every time) +buf.fill(0); +console.log(buf); + // +``` + +A `TypeError` will be thrown if `size` is not a number. + +Note that the `Buffer` module pre-allocates an internal `Buffer` instance of +size `Buffer.poolSize` that is used as a pool for the fast allocation of new +`Buffer` instances created using `Buffer.allocUnsafe(size)` (and the deprecated +`new Buffer(size)` constructor) only when `size` is less than or equal to +`Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). The default +value of `Buffer.poolSize` is `8192` but can be modified. + +Use of this pre-allocated internal memory pool is a key difference between +calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. +Specifically, `Buffer.alloc(size, fill)` will *never* use the internal Buffer +pool, while `Buffer.allocUnsafe(size).fill(fill)` *will* use the internal +Buffer pool if `size` is less than or equal to half `Buffer.poolSize`. The +difference is subtle but can be important when an application requires the +additional performance that `Buffer.allocUnsafe(size)` provides. + +### Class Method: Buffer.allocUnsafeSlow(size) + + +* `size` {Number} + +Allocates a new *non-zero-filled* and non-pooled `Buffer` of `size` bytes. The +`size` must be less than or equal to the value of +`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is +`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will +be created if a `size` less than or equal to 0 is specified. + +The underlying memory for `Buffer` instances created in this way is *not +initialized*. The contents of the newly created `Buffer` are unknown and +*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such +`Buffer` instances to zeroes. + +When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, +allocations under 4KB are, by default, sliced from a single pre-allocated +`Buffer`. This allows applications to avoid the garbage collection overhead of +creating many individually allocated Buffers. This approach improves both +performance and memory usage by eliminating the need to track and cleanup as +many `Persistent` objects. + +However, in the case where a developer may need to retain a small chunk of +memory from a pool for an indeterminate amount of time, it may be appropriate +to create an un-pooled Buffer instance using `Buffer.allocUnsafeSlow()` then +copy out the relevant bits. + +```js +// need to keep around a few small chunks of memory +const store = []; + +socket.on('readable', () => { + const data = socket.read(); + // allocate for retained data + const sb = Buffer.allocUnsafeSlow(10); + // copy the data into the new allocation + data.copy(sb, 0, 0, 10); + store.push(sb); +}); +``` + +Use of `Buffer.allocUnsafeSlow()` should be used only as a last resort *after* +a developer has observed undue memory retention in their applications. + +A `TypeError` will be thrown if `size` is not a number. + +### All the Rest + +The rest of the `Buffer` API is exactly the same as in node.js. +[See the docs](https://nodejs.org/api/buffer.html). + + +## Related links + +- [Node.js issue: Buffer(number) is unsafe](https://github.com/nodejs/node/issues/4660) +- [Node.js Enhancement Proposal: Buffer.from/Buffer.alloc/Buffer.zalloc/Buffer() soft-deprecate](https://github.com/nodejs/node-eps/pull/4) + +## Why is `Buffer` unsafe? + +Today, the node.js `Buffer` constructor is overloaded to handle many different argument +types like `String`, `Array`, `Object`, `TypedArrayView` (`Uint8Array`, etc.), +`ArrayBuffer`, and also `Number`. + +The API is optimized for convenience: you can throw any type at it, and it will try to do +what you want. + +Because the Buffer constructor is so powerful, you often see code like this: + +```js +// Convert UTF-8 strings to hex +function toHex (str) { + return new Buffer(str).toString('hex') +} +``` + +***But what happens if `toHex` is called with a `Number` argument?*** + +### Remote Memory Disclosure + +If an attacker can make your program call the `Buffer` constructor with a `Number` +argument, then they can make it allocate uninitialized memory from the node.js process. +This could potentially disclose TLS private keys, user data, or database passwords. + +When the `Buffer` constructor is passed a `Number` argument, it returns an +**UNINITIALIZED** block of memory of the specified `size`. When you create a `Buffer` like +this, you **MUST** overwrite the contents before returning it to the user. + +From the [node.js docs](https://nodejs.org/api/buffer.html#buffer_new_buffer_size): + +> `new Buffer(size)` +> +> - `size` Number +> +> The underlying memory for `Buffer` instances created in this way is not initialized. +> **The contents of a newly created `Buffer` are unknown and could contain sensitive +> data.** Use `buf.fill(0)` to initialize a Buffer to zeroes. + +(Emphasis our own.) + +Whenever the programmer intended to create an uninitialized `Buffer` you often see code +like this: + +```js +var buf = new Buffer(16) + +// Immediately overwrite the uninitialized buffer with data from another buffer +for (var i = 0; i < buf.length; i++) { + buf[i] = otherBuf[i] +} +``` + + +### Would this ever be a problem in real code? + +Yes. It's surprisingly common to forget to check the type of your variables in a +dynamically-typed language like JavaScript. + +Usually the consequences of assuming the wrong type is that your program crashes with an +uncaught exception. But the failure mode for forgetting to check the type of arguments to +the `Buffer` constructor is more catastrophic. + +Here's an example of a vulnerable service that takes a JSON payload and converts it to +hex: + +```js +// Take a JSON payload {str: "some string"} and convert it to hex +var server = http.createServer(function (req, res) { + var data = '' + req.setEncoding('utf8') + req.on('data', function (chunk) { + data += chunk + }) + req.on('end', function () { + var body = JSON.parse(data) + res.end(new Buffer(body.str).toString('hex')) + }) +}) + +server.listen(8080) +``` + +In this example, an http client just has to send: + +```json +{ + "str": 1000 +} +``` + +and it will get back 1,000 bytes of uninitialized memory from the server. + +This is a very serious bug. It's similar in severity to the +[the Heartbleed bug](http://heartbleed.com/) that allowed disclosure of OpenSSL process +memory by remote attackers. + + +### Which real-world packages were vulnerable? + +#### [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht) + +[Mathias Buus](https://github.com/mafintosh) and I +([Feross Aboukhadijeh](http://feross.org/)) found this issue in one of our own packages, +[`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht). The bug would allow +anyone on the internet to send a series of messages to a user of `bittorrent-dht` and get +them to reveal 20 bytes at a time of uninitialized memory from the node.js process. + +Here's +[the commit](https://github.com/feross/bittorrent-dht/commit/6c7da04025d5633699800a99ec3fbadf70ad35b8) +that fixed it. We released a new fixed version, created a +[Node Security Project disclosure](https://nodesecurity.io/advisories/68), and deprecated all +vulnerable versions on npm so users will get a warning to upgrade to a newer version. + +#### [`ws`](https://www.npmjs.com/package/ws) + +That got us wondering if there were other vulnerable packages. Sure enough, within a short +period of time, we found the same issue in [`ws`](https://www.npmjs.com/package/ws), the +most popular WebSocket implementation in node.js. + +If certain APIs were called with `Number` parameters instead of `String` or `Buffer` as +expected, then uninitialized server memory would be disclosed to the remote peer. + +These were the vulnerable methods: + +```js +socket.send(number) +socket.ping(number) +socket.pong(number) +``` + +Here's a vulnerable socket server with some echo functionality: + +```js +server.on('connection', function (socket) { + socket.on('message', function (message) { + message = JSON.parse(message) + if (message.type === 'echo') { + socket.send(message.data) // send back the user's message + } + }) +}) +``` + +`socket.send(number)` called on the server, will disclose server memory. + +Here's [the release](https://github.com/websockets/ws/releases/tag/1.0.1) where the issue +was fixed, with a more detailed explanation. Props to +[Arnout Kazemier](https://github.com/3rd-Eden) for the quick fix. Here's the +[Node Security Project disclosure](https://nodesecurity.io/advisories/67). + + +### What's the solution? + +It's important that node.js offers a fast way to get memory otherwise performance-critical +applications would needlessly get a lot slower. + +But we need a better way to *signal our intent* as programmers. **When we want +uninitialized memory, we should request it explicitly.** + +Sensitive functionality should not be packed into a developer-friendly API that loosely +accepts many different types. This type of API encourages the lazy practice of passing +variables in without checking the type very carefully. + +#### A new API: `Buffer.allocUnsafe(number)` + +The functionality of creating buffers with uninitialized memory should be part of another +API. We propose `Buffer.allocUnsafe(number)`. This way, it's not part of an API that +frequently gets user input of all sorts of different types passed into it. + +```js +var buf = Buffer.allocUnsafe(16) // careful, uninitialized memory! + +// Immediately overwrite the uninitialized buffer with data from another buffer +for (var i = 0; i < buf.length; i++) { + buf[i] = otherBuf[i] +} +``` + + +### How do we fix node.js core? + +We sent [a PR to node.js core](https://github.com/nodejs/node/pull/4514) (merged as +`semver-major`) which defends against one case: + +```js +var str = 16 +new Buffer(str, 'utf8') +``` + +In this situation, it's implied that the programmer intended the first argument to be a +string, since they passed an encoding as a second argument. Today, node.js will allocate +uninitialized memory in the case of `new Buffer(number, encoding)`, which is probably not +what the programmer intended. + +But this is only a partial solution, since if the programmer does `new Buffer(variable)` +(without an `encoding` parameter) there's no way to know what they intended. If `variable` +is sometimes a number, then uninitialized memory will sometimes be returned. + +### What's the real long-term fix? + +We could deprecate and remove `new Buffer(number)` and use `Buffer.allocUnsafe(number)` when +we need uninitialized memory. But that would break 1000s of packages. + +~~We believe the best solution is to:~~ + +~~1. Change `new Buffer(number)` to return safe, zeroed-out memory~~ + +~~2. Create a new API for creating uninitialized Buffers. We propose: `Buffer.allocUnsafe(number)`~~ + +#### Update + +We now support adding three new APIs: + +- `Buffer.from(value)` - convert from any type to a buffer +- `Buffer.alloc(size)` - create a zero-filled buffer +- `Buffer.allocUnsafe(size)` - create an uninitialized buffer with given size + +This solves the core problem that affected `ws` and `bittorrent-dht` which is +`Buffer(variable)` getting tricked into taking a number argument. + +This way, existing code continues working and the impact on the npm ecosystem will be +minimal. Over time, npm maintainers can migrate performance-critical code to use +`Buffer.allocUnsafe(number)` instead of `new Buffer(number)`. + + +### Conclusion + +We think there's a serious design issue with the `Buffer` API as it exists today. It +promotes insecure software by putting high-risk functionality into a convenient API +with friendly "developer ergonomics". + +This wasn't merely a theoretical exercise because we found the issue in some of the +most popular npm packages. + +Fortunately, there's an easy fix that can be applied today. Use `safe-buffer` in place of +`buffer`. + +```js +var Buffer = require('safe-buffer').Buffer +``` + +Eventually, we hope that node.js core can switch to this new, safer behavior. We believe +the impact on the ecosystem would be minimal since it's not a breaking change. +Well-maintained, popular packages would be updated to use `Buffer.alloc` quickly, while +older, insecure packages would magically become safe from this attack vector. + + +## links + +- [Node.js PR: buffer: throw if both length and enc are passed](https://github.com/nodejs/node/pull/4514) +- [Node Security Project disclosure for `ws`](https://nodesecurity.io/advisories/67) +- [Node Security Project disclosure for`bittorrent-dht`](https://nodesecurity.io/advisories/68) + + +## credit + +The original issues in `bittorrent-dht` +([disclosure](https://nodesecurity.io/advisories/68)) and +`ws` ([disclosure](https://nodesecurity.io/advisories/67)) were discovered by +[Mathias Buus](https://github.com/mafintosh) and +[Feross Aboukhadijeh](http://feross.org/). + +Thanks to [Adam Baldwin](https://github.com/evilpacket) for helping disclose these issues +and for his work running the [Node Security Project](https://nodesecurity.io/). + +Thanks to [John Hiesey](https://github.com/jhiesey) for proofreading this README and +auditing the code. + + +## license + +MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org) diff --git a/backend/node_modules/safe-buffer/index.d.ts b/backend/node_modules/safe-buffer/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e9fed809a5ab515658d6e71f7ba5f631be769be4 --- /dev/null +++ b/backend/node_modules/safe-buffer/index.d.ts @@ -0,0 +1,187 @@ +declare module "safe-buffer" { + export class Buffer { + length: number + write(string: string, offset?: number, length?: number, encoding?: string): number; + toString(encoding?: string, start?: number, end?: number): string; + toJSON(): { type: 'Buffer', data: any[] }; + equals(otherBuffer: Buffer): boolean; + compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; + copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + slice(start?: number, end?: number): Buffer; + writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readUInt8(offset: number, noAssert?: boolean): number; + readUInt16LE(offset: number, noAssert?: boolean): number; + readUInt16BE(offset: number, noAssert?: boolean): number; + readUInt32LE(offset: number, noAssert?: boolean): number; + readUInt32BE(offset: number, noAssert?: boolean): number; + readInt8(offset: number, noAssert?: boolean): number; + readInt16LE(offset: number, noAssert?: boolean): number; + readInt16BE(offset: number, noAssert?: boolean): number; + readInt32LE(offset: number, noAssert?: boolean): number; + readInt32BE(offset: number, noAssert?: boolean): number; + readFloatLE(offset: number, noAssert?: boolean): number; + readFloatBE(offset: number, noAssert?: boolean): number; + readDoubleLE(offset: number, noAssert?: boolean): number; + readDoubleBE(offset: number, noAssert?: boolean): number; + swap16(): Buffer; + swap32(): Buffer; + swap64(): Buffer; + writeUInt8(value: number, offset: number, noAssert?: boolean): number; + writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeInt8(value: number, offset: number, noAssert?: boolean): number; + writeInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeFloatLE(value: number, offset: number, noAssert?: boolean): number; + writeFloatBE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; + fill(value: any, offset?: number, end?: number): this; + indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; + + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + */ + constructor (str: string, encoding?: string); + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + */ + constructor (size: number); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + constructor (array: Uint8Array); + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}. + * + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + */ + constructor (arrayBuffer: ArrayBuffer); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + constructor (array: any[]); + /** + * Copies the passed {buffer} data onto a new {Buffer} instance. + * + * @param buffer The buffer to copy. + */ + constructor (buffer: Buffer); + prototype: Buffer; + /** + * Allocates a new Buffer using an {array} of octets. + * + * @param array + */ + static from(array: any[]): Buffer; + /** + * 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. + * + * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer() + * @param byteOffset + * @param length + */ + static from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer; + /** + * Copies the passed {buffer} data onto a new Buffer instance. + * + * @param buffer + */ + static from(buffer: Buffer): Buffer; + /** + * Creates a new Buffer containing the given JavaScript string {str}. + * If provided, the {encoding} parameter identifies the character encoding. + * If not provided, {encoding} defaults to 'utf8'. + * + * @param str + */ + static from(str: string, encoding?: string): Buffer; + /** + * Returns true if {obj} is a Buffer + * + * @param obj object to test. + */ + static isBuffer(obj: any): obj is Buffer; + /** + * Returns true if {encoding} is a valid encoding argument. + * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' + * + * @param encoding string to test. + */ + static isEncoding(encoding: string): boolean; + /** + * Gives the actual byte length of a string. encoding defaults to 'utf8'. + * This is not the same as String.prototype.length since that returns the number of characters in a string. + * + * @param string string to test. + * @param encoding encoding used to evaluate (defaults to 'utf8') + */ + static byteLength(string: string, encoding?: string): number; + /** + * Returns a buffer which is the result of concatenating all the buffers in the list together. + * + * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. + * If the list has exactly one item, then the first item of the list is returned. + * If the list has more than one item, then a new Buffer is created. + * + * @param list An array of Buffer objects to concatenate + * @param totalLength Total length of the buffers when concatenated. + * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. + */ + static concat(list: Buffer[], totalLength?: number): Buffer; + /** + * The same as buf1.compare(buf2). + */ + static compare(buf1: Buffer, buf2: Buffer): number; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @param fill if specified, buffer will be initialized by calling buf.fill(fill). + * If parameter is omitted, buffer will be filled with zeros. + * @param encoding encoding used for call to buf.fill while initalizing + */ + static alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer; + /** + * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + static allocUnsafe(size: number): Buffer; + /** + * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + static allocUnsafeSlow(size: number): Buffer; + } +} \ No newline at end of file diff --git a/backend/node_modules/safe-buffer/index.js b/backend/node_modules/safe-buffer/index.js new file mode 100644 index 0000000000000000000000000000000000000000..f8d3ec98852f449b44b7d89fc82bae737c69f3fc --- /dev/null +++ b/backend/node_modules/safe-buffer/index.js @@ -0,0 +1,65 @@ +/*! safe-buffer. MIT License. Feross Aboukhadijeh */ +/* eslint-disable node/no-deprecated-api */ +var buffer = require('buffer') +var Buffer = buffer.Buffer + +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] + } +} +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer +} + +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.prototype = Object.create(Buffer.prototype) + +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) + +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + } else { + buf.fill(0) + } + return buf +} + +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +} + +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} diff --git a/backend/node_modules/safe-buffer/package.json b/backend/node_modules/safe-buffer/package.json new file mode 100644 index 0000000000000000000000000000000000000000..f2869e256477a974a2a5b97a5d1c2e8f875183a8 --- /dev/null +++ b/backend/node_modules/safe-buffer/package.json @@ -0,0 +1,51 @@ +{ + "name": "safe-buffer", + "description": "Safer Node.js Buffer API", + "version": "5.2.1", + "author": { + "name": "Feross Aboukhadijeh", + "email": "feross@feross.org", + "url": "https://feross.org" + }, + "bugs": { + "url": "https://github.com/feross/safe-buffer/issues" + }, + "devDependencies": { + "standard": "*", + "tape": "^5.0.0" + }, + "homepage": "https://github.com/feross/safe-buffer", + "keywords": [ + "buffer", + "buffer allocate", + "node security", + "safe", + "safe-buffer", + "security", + "uninitialized" + ], + "license": "MIT", + "main": "index.js", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "git://github.com/feross/safe-buffer.git" + }, + "scripts": { + "test": "standard && tape test/*.js" + }, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] +} diff --git a/backend/node_modules/safer-buffer/LICENSE b/backend/node_modules/safer-buffer/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..4fe9e6f10036e619c2407f08ead54802bbfbcbd1 --- /dev/null +++ b/backend/node_modules/safer-buffer/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Nikita Skovoroda + +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/backend/node_modules/safer-buffer/Porting-Buffer.md b/backend/node_modules/safer-buffer/Porting-Buffer.md new file mode 100644 index 0000000000000000000000000000000000000000..68d86bab032fabc624b2e312ec3a87666a12b07c --- /dev/null +++ b/backend/node_modules/safer-buffer/Porting-Buffer.md @@ -0,0 +1,268 @@ +# Porting to the Buffer.from/Buffer.alloc API + + +## Overview + +- [Variant 1: Drop support for Node.js ≤ 4.4.x and 5.0.0 — 5.9.x.](#variant-1) (*recommended*) +- [Variant 2: Use a polyfill](#variant-2) +- [Variant 3: manual detection, with safeguards](#variant-3) + +### Finding problematic bits of code using grep + +Just run `grep -nrE '[^a-zA-Z](Slow)?Buffer\s*\(' --exclude-dir node_modules`. + +It will find all the potentially unsafe places in your own code (with some considerably unlikely +exceptions). + +### Finding problematic bits of code using Node.js 8 + +If you’re using Node.js ≥ 8.0.0 (which is recommended), Node.js exposes multiple options that help with finding the relevant pieces of code: + +- `--trace-warnings` will make Node.js show a stack trace for this warning and other warnings that are printed by Node.js. +- `--trace-deprecation` does the same thing, but only for deprecation warnings. +- `--pending-deprecation` will show more types of deprecation warnings. In particular, it will show the `Buffer()` deprecation warning, even on Node.js 8. + +You can set these flags using an environment variable: + +```console +$ export NODE_OPTIONS='--trace-warnings --pending-deprecation' +$ cat example.js +'use strict'; +const foo = new Buffer('foo'); +$ node example.js +(node:7147) [DEP0005] DeprecationWarning: The Buffer() and new Buffer() constructors are not recommended for use due to security and usability concerns. Please use the new Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() construction methods instead. + at showFlaggedDeprecation (buffer.js:127:13) + at new Buffer (buffer.js:148:3) + at Object. (/path/to/example.js:2:13) + [... more stack trace lines ...] +``` + +### Finding problematic bits of code using linters + +Eslint rules [no-buffer-constructor](https://eslint.org/docs/rules/no-buffer-constructor) +or +[node/no-deprecated-api](https://github.com/mysticatea/eslint-plugin-node/blob/master/docs/rules/no-deprecated-api.md) +also find calls to deprecated `Buffer()` API. Those rules are included in some pre-sets. + +There is a drawback, though, that it doesn't always +[work correctly](https://github.com/chalker/safer-buffer#why-not-safe-buffer) when `Buffer` is +overriden e.g. with a polyfill, so recommended is a combination of this and some other method +described above. + + +## Variant 1: Drop support for Node.js ≤ 4.4.x and 5.0.0 — 5.9.x. + +This is the recommended solution nowadays that would imply only minimal overhead. + +The Node.js 5.x release line has been unsupported since July 2016, and the Node.js 4.x release line reaches its End of Life in April 2018 (→ [Schedule](https://github.com/nodejs/Release#release-schedule)). This means that these versions of Node.js will *not* receive any updates, even in case of security issues, so using these release lines should be avoided, if at all possible. + +What you would do in this case is to convert all `new Buffer()` or `Buffer()` calls to use `Buffer.alloc()` or `Buffer.from()`, in the following way: + +- For `new Buffer(number)`, replace it with `Buffer.alloc(number)`. +- For `new Buffer(string)` (or `new Buffer(string, encoding)`), replace it with `Buffer.from(string)` (or `Buffer.from(string, encoding)`). +- For all other combinations of arguments (these are much rarer), also replace `new Buffer(...arguments)` with `Buffer.from(...arguments)`. + +Note that `Buffer.alloc()` is also _faster_ on the current Node.js versions than +`new Buffer(size).fill(0)`, which is what you would otherwise need to ensure zero-filling. + +Enabling eslint rule [no-buffer-constructor](https://eslint.org/docs/rules/no-buffer-constructor) +or +[node/no-deprecated-api](https://github.com/mysticatea/eslint-plugin-node/blob/master/docs/rules/no-deprecated-api.md) +is recommended to avoid accidential unsafe Buffer API usage. + +There is also a [JSCodeshift codemod](https://github.com/joyeecheung/node-dep-codemod#dep005) +for automatically migrating Buffer constructors to `Buffer.alloc()` or `Buffer.from()`. +Note that it currently only works with cases where the arguments are literals or where the +constructor is invoked with two arguments. + +_If you currently support those older Node.js versions and dropping them would be a semver-major change +for you, or if you support older branches of your packages, consider using [Variant 2](#variant-2) +or [Variant 3](#variant-3) on older branches, so people using those older branches will also receive +the fix. That way, you will eradicate potential issues caused by unguarded Buffer API usage and +your users will not observe a runtime deprecation warning when running your code on Node.js 10._ + + +## Variant 2: Use a polyfill + +Utilize [safer-buffer](https://www.npmjs.com/package/safer-buffer) as a polyfill to support older +Node.js versions. + +You would take exacly the same steps as in [Variant 1](#variant-1), but with a polyfill +`const Buffer = require('safer-buffer').Buffer` in all files where you use the new `Buffer` api. + +Make sure that you do not use old `new Buffer` API — in any files where the line above is added, +using old `new Buffer()` API will _throw_. It will be easy to notice that in CI, though. + +Alternatively, you could use [buffer-from](https://www.npmjs.com/package/buffer-from) and/or +[buffer-alloc](https://www.npmjs.com/package/buffer-alloc) [ponyfills](https://ponyfill.com/) — +those are great, the only downsides being 4 deps in the tree and slightly more code changes to +migrate off them (as you would be using e.g. `Buffer.from` under a different name). If you need only +`Buffer.from` polyfilled — `buffer-from` alone which comes with no extra dependencies. + +_Alternatively, you could use [safe-buffer](https://www.npmjs.com/package/safe-buffer) — it also +provides a polyfill, but takes a different approach which has +[it's drawbacks](https://github.com/chalker/safer-buffer#why-not-safe-buffer). It will allow you +to also use the older `new Buffer()` API in your code, though — but that's arguably a benefit, as +it is problematic, can cause issues in your code, and will start emitting runtime deprecation +warnings starting with Node.js 10._ + +Note that in either case, it is important that you also remove all calls to the old Buffer +API manually — just throwing in `safe-buffer` doesn't fix the problem by itself, it just provides +a polyfill for the new API. I have seen people doing that mistake. + +Enabling eslint rule [no-buffer-constructor](https://eslint.org/docs/rules/no-buffer-constructor) +or +[node/no-deprecated-api](https://github.com/mysticatea/eslint-plugin-node/blob/master/docs/rules/no-deprecated-api.md) +is recommended. + +_Don't forget to drop the polyfill usage once you drop support for Node.js < 4.5.0._ + + +## Variant 3 — manual detection, with safeguards + +This is useful if you create Buffer instances in only a few places (e.g. one), or you have your own +wrapper around them. + +### Buffer(0) + +This special case for creating empty buffers can be safely replaced with `Buffer.concat([])`, which +returns the same result all the way down to Node.js 0.8.x. + +### Buffer(notNumber) + +Before: + +```js +var buf = new Buffer(notNumber, encoding); +``` + +After: + +```js +var buf; +if (Buffer.from && Buffer.from !== Uint8Array.from) { + buf = Buffer.from(notNumber, encoding); +} else { + if (typeof notNumber === 'number') + throw new Error('The "size" argument must be of type number.'); + buf = new Buffer(notNumber, encoding); +} +``` + +`encoding` is optional. + +Note that the `typeof notNumber` before `new Buffer` is required (for cases when `notNumber` argument is not +hard-coded) and _is not caused by the deprecation of Buffer constructor_ — it's exactly _why_ the +Buffer constructor is deprecated. Ecosystem packages lacking this type-check caused numereous +security issues — situations when unsanitized user input could end up in the `Buffer(arg)` create +problems ranging from DoS to leaking sensitive information to the attacker from the process memory. + +When `notNumber` argument is hardcoded (e.g. literal `"abc"` or `[0,1,2]`), the `typeof` check can +be omitted. + +Also note that using TypeScript does not fix this problem for you — when libs written in +`TypeScript` are used from JS, or when user input ends up there — it behaves exactly as pure JS, as +all type checks are translation-time only and are not present in the actual JS code which TS +compiles to. + +### Buffer(number) + +For Node.js 0.10.x (and below) support: + +```js +var buf; +if (Buffer.alloc) { + buf = Buffer.alloc(number); +} else { + buf = new Buffer(number); + buf.fill(0); +} +``` + +Otherwise (Node.js ≥ 0.12.x): + +```js +const buf = Buffer.alloc ? Buffer.alloc(number) : new Buffer(number).fill(0); +``` + +## Regarding Buffer.allocUnsafe + +Be extra cautious when using `Buffer.allocUnsafe`: + * Don't use it if you don't have a good reason to + * e.g. you probably won't ever see a performance difference for small buffers, in fact, those + might be even faster with `Buffer.alloc()`, + * if your code is not in the hot code path — you also probably won't notice a difference, + * keep in mind that zero-filling minimizes the potential risks. + * If you use it, make sure that you never return the buffer in a partially-filled state, + * if you are writing to it sequentially — always truncate it to the actuall written length + +Errors in handling buffers allocated with `Buffer.allocUnsafe` could result in various issues, +ranged from undefined behaviour of your code to sensitive data (user input, passwords, certs) +leaking to the remote attacker. + +_Note that the same applies to `new Buffer` usage without zero-filling, depending on the Node.js +version (and lacking type checks also adds DoS to the list of potential problems)._ + + +## FAQ + + +### What is wrong with the `Buffer` constructor? + +The `Buffer` constructor could be used to create a buffer in many different ways: + +- `new Buffer(42)` creates a `Buffer` of 42 bytes. Before Node.js 8, this buffer contained + *arbitrary memory* for performance reasons, which could include anything ranging from + program source code to passwords and encryption keys. +- `new Buffer('abc')` creates a `Buffer` that contains the UTF-8-encoded version of + the string `'abc'`. A second argument could specify another encoding: For example, + `new Buffer(string, 'base64')` could be used to convert a Base64 string into the original + sequence of bytes that it represents. +- There are several other combinations of arguments. + +This meant that, in code like `var buffer = new Buffer(foo);`, *it is not possible to tell +what exactly the contents of the generated buffer are* without knowing the type of `foo`. + +Sometimes, the value of `foo` comes from an external source. For example, this function +could be exposed as a service on a web server, converting a UTF-8 string into its Base64 form: + +``` +function stringToBase64(req, res) { + // The request body should have the format of `{ string: 'foobar' }` + const rawBytes = new Buffer(req.body.string) + const encoded = rawBytes.toString('base64') + res.end({ encoded: encoded }) +} +``` + +Note that this code does *not* validate the type of `req.body.string`: + +- `req.body.string` is expected to be a string. If this is the case, all goes well. +- `req.body.string` is controlled by the client that sends the request. +- If `req.body.string` is the *number* `50`, the `rawBytes` would be 50 bytes: + - Before Node.js 8, the content would be uninitialized + - After Node.js 8, the content would be `50` bytes with the value `0` + +Because of the missing type check, an attacker could intentionally send a number +as part of the request. Using this, they can either: + +- Read uninitialized memory. This **will** leak passwords, encryption keys and other + kinds of sensitive information. (Information leak) +- Force the program to allocate a large amount of memory. For example, when specifying + `500000000` as the input value, each request will allocate 500MB of memory. + This can be used to either exhaust the memory available of a program completely + and make it crash, or slow it down significantly. (Denial of Service) + +Both of these scenarios are considered serious security issues in a real-world +web server context. + +when using `Buffer.from(req.body.string)` instead, passing a number will always +throw an exception instead, giving a controlled behaviour that can always be +handled by the program. + + +### The `Buffer()` constructor has been deprecated for a while. Is this really an issue? + +Surveys of code in the `npm` ecosystem have shown that the `Buffer()` constructor is still +widely used. This includes new code, and overall usage of such code has actually been +*increasing*. diff --git a/backend/node_modules/safer-buffer/Readme.md b/backend/node_modules/safer-buffer/Readme.md new file mode 100644 index 0000000000000000000000000000000000000000..14b0822909320ff4ffafb1526212866f159470c5 --- /dev/null +++ b/backend/node_modules/safer-buffer/Readme.md @@ -0,0 +1,156 @@ +# safer-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![javascript style guide][standard-image]][standard-url] [![Security Responsible Disclosure][secuirty-image]][secuirty-url] + +[travis-image]: https://travis-ci.org/ChALkeR/safer-buffer.svg?branch=master +[travis-url]: https://travis-ci.org/ChALkeR/safer-buffer +[npm-image]: https://img.shields.io/npm/v/safer-buffer.svg +[npm-url]: https://npmjs.org/package/safer-buffer +[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg +[standard-url]: https://standardjs.com +[secuirty-image]: https://img.shields.io/badge/Security-Responsible%20Disclosure-green.svg +[secuirty-url]: https://github.com/nodejs/security-wg/blob/master/processes/responsible_disclosure_template.md + +Modern Buffer API polyfill without footguns, working on Node.js from 0.8 to current. + +## How to use? + +First, port all `Buffer()` and `new Buffer()` calls to `Buffer.alloc()` and `Buffer.from()` API. + +Then, to achieve compatibility with outdated Node.js versions (`<4.5.0` and 5.x `<5.9.0`), use +`const Buffer = require('safer-buffer').Buffer` in all files where you make calls to the new +Buffer API. _Use `var` instead of `const` if you need that for your Node.js version range support._ + +Also, see the +[porting Buffer](https://github.com/ChALkeR/safer-buffer/blob/master/Porting-Buffer.md) guide. + +## Do I need it? + +Hopefully, not — dropping support for outdated Node.js versions should be fine nowdays, and that +is the recommended path forward. You _do_ need to port to the `Buffer.alloc()` and `Buffer.from()` +though. + +See the [porting guide](https://github.com/ChALkeR/safer-buffer/blob/master/Porting-Buffer.md) +for a better description. + +## Why not [safe-buffer](https://npmjs.com/safe-buffer)? + +_In short: while `safe-buffer` serves as a polyfill for the new API, it allows old API usage and +itself contains footguns._ + +`safe-buffer` could be used safely to get the new API while still keeping support for older +Node.js versions (like this module), but while analyzing ecosystem usage of the old Buffer API +I found out that `safe-buffer` is itself causing problems in some cases. + +For example, consider the following snippet: + +```console +$ cat example.unsafe.js +console.log(Buffer(20)) +$ ./node-v6.13.0-linux-x64/bin/node example.unsafe.js + +$ standard example.unsafe.js +standard: Use JavaScript Standard Style (https://standardjs.com) + /home/chalker/repo/safer-buffer/example.unsafe.js:2:13: 'Buffer()' was deprecated since v6. Use 'Buffer.alloc()' or 'Buffer.from()' (use 'https://www.npmjs.com/package/safe-buffer' for '<4.5.0') instead. +``` + +This is allocates and writes to console an uninitialized chunk of memory. +[standard](https://www.npmjs.com/package/standard) linter (among others) catch that and warn people +to avoid using unsafe API. + +Let's now throw in `safe-buffer`! + +```console +$ cat example.safe-buffer.js +const Buffer = require('safe-buffer').Buffer +console.log(Buffer(20)) +$ standard example.safe-buffer.js +$ ./node-v6.13.0-linux-x64/bin/node example.safe-buffer.js + +``` + +See the problem? Adding in `safe-buffer` _magically removes the lint warning_, but the behavior +remains identiсal to what we had before, and when launched on Node.js 6.x LTS — this dumps out +chunks of uninitialized memory. +_And this code will still emit runtime warnings on Node.js 10.x and above._ + +That was done by design. I first considered changing `safe-buffer`, prohibiting old API usage or +emitting warnings on it, but that significantly diverges from `safe-buffer` design. After some +discussion, it was decided to move my approach into a separate package, and _this is that separate +package_. + +This footgun is not imaginary — I observed top-downloaded packages doing that kind of thing, +«fixing» the lint warning by blindly including `safe-buffer` without any actual changes. + +Also in some cases, even if the API _was_ migrated to use of safe Buffer API — a random pull request +can bring unsafe Buffer API usage back to the codebase by adding new calls — and that could go +unnoticed even if you have a linter prohibiting that (becase of the reason stated above), and even +pass CI. _I also observed that being done in popular packages._ + +Some examples: + * [webdriverio](https://github.com/webdriverio/webdriverio/commit/05cbd3167c12e4930f09ef7cf93b127ba4effae4#diff-124380949022817b90b622871837d56cR31) + (a module with 548 759 downloads/month), + * [websocket-stream](https://github.com/maxogden/websocket-stream/commit/c9312bd24d08271687d76da0fe3c83493871cf61) + (218 288 d/m, fix in [maxogden/websocket-stream#142](https://github.com/maxogden/websocket-stream/pull/142)), + * [node-serialport](https://github.com/node-serialport/node-serialport/commit/e8d9d2b16c664224920ce1c895199b1ce2def48c) + (113 138 d/m, fix in [node-serialport/node-serialport#1510](https://github.com/node-serialport/node-serialport/pull/1510)), + * [karma](https://github.com/karma-runner/karma/commit/3d94b8cf18c695104ca195334dc75ff054c74eec) + (3 973 193 d/m, fix in [karma-runner/karma#2947](https://github.com/karma-runner/karma/pull/2947)), + * [spdy-transport](https://github.com/spdy-http2/spdy-transport/commit/5375ac33f4a62a4f65bcfc2827447d42a5dbe8b1) + (5 970 727 d/m, fix in [spdy-http2/spdy-transport#53](https://github.com/spdy-http2/spdy-transport/pull/53)). + * And there are a lot more over the ecosystem. + +I filed a PR at +[mysticatea/eslint-plugin-node#110](https://github.com/mysticatea/eslint-plugin-node/pull/110) to +partially fix that (for cases when that lint rule is used), but it is a semver-major change for +linter rules and presets, so it would take significant time for that to reach actual setups. +_It also hasn't been released yet (2018-03-20)._ + +Also, `safer-buffer` discourages the usage of `.allocUnsafe()`, which is often done by a mistake. +It still supports it with an explicit concern barier, by placing it under +`require('safer-buffer/dangereous')`. + +## But isn't throwing bad? + +Not really. It's an error that could be noticed and fixed early, instead of causing havoc later like +unguarded `new Buffer()` calls that end up receiving user input can do. + +This package affects only the files where `var Buffer = require('safer-buffer').Buffer` was done, so +it is really simple to keep track of things and make sure that you don't mix old API usage with that. +Also, CI should hint anything that you might have missed. + +New commits, if tested, won't land new usage of unsafe Buffer API this way. +_Node.js 10.x also deals with that by printing a runtime depecation warning._ + +### Would it affect third-party modules? + +No, unless you explicitly do an awful thing like monkey-patching or overriding the built-in `Buffer`. +Don't do that. + +### But I don't want throwing… + +That is also fine! + +Also, it could be better in some cases when you don't comprehensive enough test coverage. + +In that case — just don't override `Buffer` and use +`var SaferBuffer = require('safer-buffer').Buffer` instead. + +That way, everything using `Buffer` natively would still work, but there would be two drawbacks: + +* `Buffer.from`/`Buffer.alloc` won't be polyfilled — use `SaferBuffer.from` and + `SaferBuffer.alloc` instead. +* You are still open to accidentally using the insecure deprecated API — use a linter to catch that. + +Note that using a linter to catch accidential `Buffer` constructor usage in this case is strongly +recommended. `Buffer` is not overriden in this usecase, so linters won't get confused. + +## «Without footguns»? + +Well, it is still possible to do _some_ things with `Buffer` API, e.g. accessing `.buffer` property +on older versions and duping things from there. You shouldn't do that in your code, probabably. + +The intention is to remove the most significant footguns that affect lots of packages in the +ecosystem, and to do it in the proper way. + +Also, this package doesn't protect against security issues affecting some Node.js versions, so for +usage in your own production code, it is still recommended to update to a Node.js version +[supported by upstream](https://github.com/nodejs/release#release-schedule). diff --git a/backend/node_modules/safer-buffer/dangerous.js b/backend/node_modules/safer-buffer/dangerous.js new file mode 100644 index 0000000000000000000000000000000000000000..ca41fdc549b6553e811d35e44730a51bec68be99 --- /dev/null +++ b/backend/node_modules/safer-buffer/dangerous.js @@ -0,0 +1,58 @@ +/* eslint-disable node/no-deprecated-api */ + +'use strict' + +var buffer = require('buffer') +var Buffer = buffer.Buffer +var safer = require('./safer.js') +var Safer = safer.Buffer + +var dangerous = {} + +var key + +for (key in safer) { + if (!safer.hasOwnProperty(key)) continue + dangerous[key] = safer[key] +} + +var Dangereous = dangerous.Buffer = {} + +// Copy Safer API +for (key in Safer) { + if (!Safer.hasOwnProperty(key)) continue + Dangereous[key] = Safer[key] +} + +// Copy those missing unsafe methods, if they are present +for (key in Buffer) { + if (!Buffer.hasOwnProperty(key)) continue + if (Dangereous.hasOwnProperty(key)) continue + Dangereous[key] = Buffer[key] +} + +if (!Dangereous.allocUnsafe) { + Dangereous.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size) + } + if (size < 0 || size >= 2 * (1 << 30)) { + throw new RangeError('The value "' + size + '" is invalid for option "size"') + } + return Buffer(size) + } +} + +if (!Dangereous.allocUnsafeSlow) { + Dangereous.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size) + } + if (size < 0 || size >= 2 * (1 << 30)) { + throw new RangeError('The value "' + size + '" is invalid for option "size"') + } + return buffer.SlowBuffer(size) + } +} + +module.exports = dangerous diff --git a/backend/node_modules/safer-buffer/package.json b/backend/node_modules/safer-buffer/package.json new file mode 100644 index 0000000000000000000000000000000000000000..d452b04aef3bb41ead6816e2b5de24f27279680c --- /dev/null +++ b/backend/node_modules/safer-buffer/package.json @@ -0,0 +1,34 @@ +{ + "name": "safer-buffer", + "version": "2.1.2", + "description": "Modern Buffer API polyfill without footguns", + "main": "safer.js", + "scripts": { + "browserify-test": "browserify --external tape tests.js > browserify-tests.js && tape browserify-tests.js", + "test": "standard && tape tests.js" + }, + "author": { + "name": "Nikita Skovoroda", + "email": "chalkerx@gmail.com", + "url": "https://github.com/ChALkeR" + }, + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/ChALkeR/safer-buffer.git" + }, + "bugs": { + "url": "https://github.com/ChALkeR/safer-buffer/issues" + }, + "devDependencies": { + "standard": "^11.0.1", + "tape": "^4.9.0" + }, + "files": [ + "Porting-Buffer.md", + "Readme.md", + "tests.js", + "dangerous.js", + "safer.js" + ] +} diff --git a/backend/node_modules/safer-buffer/safer.js b/backend/node_modules/safer-buffer/safer.js new file mode 100644 index 0000000000000000000000000000000000000000..37c7e1aa6cbd4effd94ee28bd7b0655756b80cea --- /dev/null +++ b/backend/node_modules/safer-buffer/safer.js @@ -0,0 +1,77 @@ +/* eslint-disable node/no-deprecated-api */ + +'use strict' + +var buffer = require('buffer') +var Buffer = buffer.Buffer + +var safer = {} + +var key + +for (key in buffer) { + if (!buffer.hasOwnProperty(key)) continue + if (key === 'SlowBuffer' || key === 'Buffer') continue + safer[key] = buffer[key] +} + +var Safer = safer.Buffer = {} +for (key in Buffer) { + if (!Buffer.hasOwnProperty(key)) continue + if (key === 'allocUnsafe' || key === 'allocUnsafeSlow') continue + Safer[key] = Buffer[key] +} + +safer.Buffer.prototype = Buffer.prototype + +if (!Safer.from || Safer.from === Uint8Array.from) { + Safer.from = function (value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('The "value" argument must not be of type number. Received type ' + typeof value) + } + if (value && typeof value.length === 'undefined') { + throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type ' + typeof value) + } + return Buffer(value, encodingOrOffset, length) + } +} + +if (!Safer.alloc) { + Safer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size) + } + if (size < 0 || size >= 2 * (1 << 30)) { + throw new RangeError('The value "' + size + '" is invalid for option "size"') + } + var buf = Buffer(size) + if (!fill || fill.length === 0) { + buf.fill(0) + } else if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + return buf + } +} + +if (!safer.kStringMaxLength) { + try { + safer.kStringMaxLength = process.binding('buffer').kStringMaxLength + } catch (e) { + // we can't determine kStringMaxLength in environments where process.binding + // is unsupported, so let's not set it + } +} + +if (!safer.constants) { + safer.constants = { + MAX_LENGTH: safer.kMaxLength + } + if (safer.kStringMaxLength) { + safer.constants.MAX_STRING_LENGTH = safer.kStringMaxLength + } +} + +module.exports = safer diff --git a/backend/node_modules/safer-buffer/tests.js b/backend/node_modules/safer-buffer/tests.js new file mode 100644 index 0000000000000000000000000000000000000000..7ed2777c92a7991807c516027d5f73d0b47e781b --- /dev/null +++ b/backend/node_modules/safer-buffer/tests.js @@ -0,0 +1,406 @@ +/* eslint-disable node/no-deprecated-api */ + +'use strict' + +var test = require('tape') + +var buffer = require('buffer') + +var index = require('./') +var safer = require('./safer') +var dangerous = require('./dangerous') + +/* Inheritance tests */ + +test('Default is Safer', function (t) { + t.equal(index, safer) + t.notEqual(safer, dangerous) + t.notEqual(index, dangerous) + t.end() +}) + +test('Is not a function', function (t) { + [index, safer, dangerous].forEach(function (impl) { + t.equal(typeof impl, 'object') + t.equal(typeof impl.Buffer, 'object') + }); + [buffer].forEach(function (impl) { + t.equal(typeof impl, 'object') + t.equal(typeof impl.Buffer, 'function') + }) + t.end() +}) + +test('Constructor throws', function (t) { + [index, safer, dangerous].forEach(function (impl) { + t.throws(function () { impl.Buffer() }) + t.throws(function () { impl.Buffer(0) }) + t.throws(function () { impl.Buffer('a') }) + t.throws(function () { impl.Buffer('a', 'utf-8') }) + t.throws(function () { return new impl.Buffer() }) + t.throws(function () { return new impl.Buffer(0) }) + t.throws(function () { return new impl.Buffer('a') }) + t.throws(function () { return new impl.Buffer('a', 'utf-8') }) + }) + t.end() +}) + +test('Safe methods exist', function (t) { + [index, safer, dangerous].forEach(function (impl) { + t.equal(typeof impl.Buffer.alloc, 'function', 'alloc') + t.equal(typeof impl.Buffer.from, 'function', 'from') + }) + t.end() +}) + +test('Unsafe methods exist only in Dangerous', function (t) { + [index, safer].forEach(function (impl) { + t.equal(typeof impl.Buffer.allocUnsafe, 'undefined') + t.equal(typeof impl.Buffer.allocUnsafeSlow, 'undefined') + }); + [dangerous].forEach(function (impl) { + t.equal(typeof impl.Buffer.allocUnsafe, 'function') + t.equal(typeof impl.Buffer.allocUnsafeSlow, 'function') + }) + t.end() +}) + +test('Generic methods/properties are defined and equal', function (t) { + ['poolSize', 'isBuffer', 'concat', 'byteLength'].forEach(function (method) { + [index, safer, dangerous].forEach(function (impl) { + t.equal(impl.Buffer[method], buffer.Buffer[method], method) + t.notEqual(typeof impl.Buffer[method], 'undefined', method) + }) + }) + t.end() +}) + +test('Built-in buffer static methods/properties are inherited', function (t) { + Object.keys(buffer).forEach(function (method) { + if (method === 'SlowBuffer' || method === 'Buffer') return; + [index, safer, dangerous].forEach(function (impl) { + t.equal(impl[method], buffer[method], method) + t.notEqual(typeof impl[method], 'undefined', method) + }) + }) + t.end() +}) + +test('Built-in Buffer static methods/properties are inherited', function (t) { + Object.keys(buffer.Buffer).forEach(function (method) { + if (method === 'allocUnsafe' || method === 'allocUnsafeSlow') return; + [index, safer, dangerous].forEach(function (impl) { + t.equal(impl.Buffer[method], buffer.Buffer[method], method) + t.notEqual(typeof impl.Buffer[method], 'undefined', method) + }) + }) + t.end() +}) + +test('.prototype property of Buffer is inherited', function (t) { + [index, safer, dangerous].forEach(function (impl) { + t.equal(impl.Buffer.prototype, buffer.Buffer.prototype, 'prototype') + t.notEqual(typeof impl.Buffer.prototype, 'undefined', 'prototype') + }) + t.end() +}) + +test('All Safer methods are present in Dangerous', function (t) { + Object.keys(safer).forEach(function (method) { + if (method === 'Buffer') return; + [index, safer, dangerous].forEach(function (impl) { + t.equal(impl[method], safer[method], method) + if (method !== 'kStringMaxLength') { + t.notEqual(typeof impl[method], 'undefined', method) + } + }) + }) + Object.keys(safer.Buffer).forEach(function (method) { + [index, safer, dangerous].forEach(function (impl) { + t.equal(impl.Buffer[method], safer.Buffer[method], method) + t.notEqual(typeof impl.Buffer[method], 'undefined', method) + }) + }) + t.end() +}) + +test('Safe methods from Dangerous methods are present in Safer', function (t) { + Object.keys(dangerous).forEach(function (method) { + if (method === 'Buffer') return; + [index, safer, dangerous].forEach(function (impl) { + t.equal(impl[method], dangerous[method], method) + if (method !== 'kStringMaxLength') { + t.notEqual(typeof impl[method], 'undefined', method) + } + }) + }) + Object.keys(dangerous.Buffer).forEach(function (method) { + if (method === 'allocUnsafe' || method === 'allocUnsafeSlow') return; + [index, safer, dangerous].forEach(function (impl) { + t.equal(impl.Buffer[method], dangerous.Buffer[method], method) + t.notEqual(typeof impl.Buffer[method], 'undefined', method) + }) + }) + t.end() +}) + +/* Behaviour tests */ + +test('Methods return Buffers', function (t) { + [index, safer, dangerous].forEach(function (impl) { + t.ok(buffer.Buffer.isBuffer(impl.Buffer.alloc(0))) + t.ok(buffer.Buffer.isBuffer(impl.Buffer.alloc(0, 10))) + t.ok(buffer.Buffer.isBuffer(impl.Buffer.alloc(0, 'a'))) + t.ok(buffer.Buffer.isBuffer(impl.Buffer.alloc(10))) + t.ok(buffer.Buffer.isBuffer(impl.Buffer.alloc(10, 'x'))) + t.ok(buffer.Buffer.isBuffer(impl.Buffer.alloc(9, 'ab'))) + t.ok(buffer.Buffer.isBuffer(impl.Buffer.from(''))) + t.ok(buffer.Buffer.isBuffer(impl.Buffer.from('string'))) + t.ok(buffer.Buffer.isBuffer(impl.Buffer.from('string', 'utf-8'))) + t.ok(buffer.Buffer.isBuffer(impl.Buffer.from('b25ldHdvdGhyZWU=', 'base64'))) + t.ok(buffer.Buffer.isBuffer(impl.Buffer.from([0, 42, 3]))) + t.ok(buffer.Buffer.isBuffer(impl.Buffer.from(new Uint8Array([0, 42, 3])))) + t.ok(buffer.Buffer.isBuffer(impl.Buffer.from([]))) + }); + ['allocUnsafe', 'allocUnsafeSlow'].forEach(function (method) { + t.ok(buffer.Buffer.isBuffer(dangerous.Buffer[method](0))) + t.ok(buffer.Buffer.isBuffer(dangerous.Buffer[method](10))) + }) + t.end() +}) + +test('Constructor is buffer.Buffer', function (t) { + [index, safer, dangerous].forEach(function (impl) { + t.equal(impl.Buffer.alloc(0).constructor, buffer.Buffer) + t.equal(impl.Buffer.alloc(0, 10).constructor, buffer.Buffer) + t.equal(impl.Buffer.alloc(0, 'a').constructor, buffer.Buffer) + t.equal(impl.Buffer.alloc(10).constructor, buffer.Buffer) + t.equal(impl.Buffer.alloc(10, 'x').constructor, buffer.Buffer) + t.equal(impl.Buffer.alloc(9, 'ab').constructor, buffer.Buffer) + t.equal(impl.Buffer.from('').constructor, buffer.Buffer) + t.equal(impl.Buffer.from('string').constructor, buffer.Buffer) + t.equal(impl.Buffer.from('string', 'utf-8').constructor, buffer.Buffer) + t.equal(impl.Buffer.from('b25ldHdvdGhyZWU=', 'base64').constructor, buffer.Buffer) + t.equal(impl.Buffer.from([0, 42, 3]).constructor, buffer.Buffer) + t.equal(impl.Buffer.from(new Uint8Array([0, 42, 3])).constructor, buffer.Buffer) + t.equal(impl.Buffer.from([]).constructor, buffer.Buffer) + }); + [0, 10, 100].forEach(function (arg) { + t.equal(dangerous.Buffer.allocUnsafe(arg).constructor, buffer.Buffer) + t.equal(dangerous.Buffer.allocUnsafeSlow(arg).constructor, buffer.SlowBuffer(0).constructor) + }) + t.end() +}) + +test('Invalid calls throw', function (t) { + [index, safer, dangerous].forEach(function (impl) { + t.throws(function () { impl.Buffer.from(0) }) + t.throws(function () { impl.Buffer.from(10) }) + t.throws(function () { impl.Buffer.from(10, 'utf-8') }) + t.throws(function () { impl.Buffer.from('string', 'invalid encoding') }) + t.throws(function () { impl.Buffer.from(-10) }) + t.throws(function () { impl.Buffer.from(1e90) }) + t.throws(function () { impl.Buffer.from(Infinity) }) + t.throws(function () { impl.Buffer.from(-Infinity) }) + t.throws(function () { impl.Buffer.from(NaN) }) + t.throws(function () { impl.Buffer.from(null) }) + t.throws(function () { impl.Buffer.from(undefined) }) + t.throws(function () { impl.Buffer.from() }) + t.throws(function () { impl.Buffer.from({}) }) + t.throws(function () { impl.Buffer.alloc('') }) + t.throws(function () { impl.Buffer.alloc('string') }) + t.throws(function () { impl.Buffer.alloc('string', 'utf-8') }) + t.throws(function () { impl.Buffer.alloc('b25ldHdvdGhyZWU=', 'base64') }) + t.throws(function () { impl.Buffer.alloc(-10) }) + t.throws(function () { impl.Buffer.alloc(1e90) }) + t.throws(function () { impl.Buffer.alloc(2 * (1 << 30)) }) + t.throws(function () { impl.Buffer.alloc(Infinity) }) + t.throws(function () { impl.Buffer.alloc(-Infinity) }) + t.throws(function () { impl.Buffer.alloc(null) }) + t.throws(function () { impl.Buffer.alloc(undefined) }) + t.throws(function () { impl.Buffer.alloc() }) + t.throws(function () { impl.Buffer.alloc([]) }) + t.throws(function () { impl.Buffer.alloc([0, 42, 3]) }) + t.throws(function () { impl.Buffer.alloc({}) }) + }); + ['allocUnsafe', 'allocUnsafeSlow'].forEach(function (method) { + t.throws(function () { dangerous.Buffer[method]('') }) + t.throws(function () { dangerous.Buffer[method]('string') }) + t.throws(function () { dangerous.Buffer[method]('string', 'utf-8') }) + t.throws(function () { dangerous.Buffer[method](2 * (1 << 30)) }) + t.throws(function () { dangerous.Buffer[method](Infinity) }) + if (dangerous.Buffer[method] === buffer.Buffer.allocUnsafe) { + t.skip('Skipping, older impl of allocUnsafe coerced negative sizes to 0') + } else { + t.throws(function () { dangerous.Buffer[method](-10) }) + t.throws(function () { dangerous.Buffer[method](-1e90) }) + t.throws(function () { dangerous.Buffer[method](-Infinity) }) + } + t.throws(function () { dangerous.Buffer[method](null) }) + t.throws(function () { dangerous.Buffer[method](undefined) }) + t.throws(function () { dangerous.Buffer[method]() }) + t.throws(function () { dangerous.Buffer[method]([]) }) + t.throws(function () { dangerous.Buffer[method]([0, 42, 3]) }) + t.throws(function () { dangerous.Buffer[method]({}) }) + }) + t.end() +}) + +test('Buffers have appropriate lengths', function (t) { + [index, safer, dangerous].forEach(function (impl) { + t.equal(impl.Buffer.alloc(0).length, 0) + t.equal(impl.Buffer.alloc(10).length, 10) + t.equal(impl.Buffer.from('').length, 0) + t.equal(impl.Buffer.from('string').length, 6) + t.equal(impl.Buffer.from('string', 'utf-8').length, 6) + t.equal(impl.Buffer.from('b25ldHdvdGhyZWU=', 'base64').length, 11) + t.equal(impl.Buffer.from([0, 42, 3]).length, 3) + t.equal(impl.Buffer.from(new Uint8Array([0, 42, 3])).length, 3) + t.equal(impl.Buffer.from([]).length, 0) + }); + ['allocUnsafe', 'allocUnsafeSlow'].forEach(function (method) { + t.equal(dangerous.Buffer[method](0).length, 0) + t.equal(dangerous.Buffer[method](10).length, 10) + }) + t.end() +}) + +test('Buffers have appropriate lengths (2)', function (t) { + t.equal(index.Buffer.alloc, safer.Buffer.alloc) + t.equal(index.Buffer.alloc, dangerous.Buffer.alloc) + var ok = true; + [ safer.Buffer.alloc, + dangerous.Buffer.allocUnsafe, + dangerous.Buffer.allocUnsafeSlow + ].forEach(function (method) { + for (var i = 0; i < 1e2; i++) { + var length = Math.round(Math.random() * 1e5) + var buf = method(length) + if (!buffer.Buffer.isBuffer(buf)) ok = false + if (buf.length !== length) ok = false + } + }) + t.ok(ok) + t.end() +}) + +test('.alloc(size) is zero-filled and has correct length', function (t) { + t.equal(index.Buffer.alloc, safer.Buffer.alloc) + t.equal(index.Buffer.alloc, dangerous.Buffer.alloc) + var ok = true + for (var i = 0; i < 1e2; i++) { + var length = Math.round(Math.random() * 2e6) + var buf = index.Buffer.alloc(length) + if (!buffer.Buffer.isBuffer(buf)) ok = false + if (buf.length !== length) ok = false + var j + for (j = 0; j < length; j++) { + if (buf[j] !== 0) ok = false + } + buf.fill(1) + for (j = 0; j < length; j++) { + if (buf[j] !== 1) ok = false + } + } + t.ok(ok) + t.end() +}) + +test('.allocUnsafe / .allocUnsafeSlow are fillable and have correct lengths', function (t) { + ['allocUnsafe', 'allocUnsafeSlow'].forEach(function (method) { + var ok = true + for (var i = 0; i < 1e2; i++) { + var length = Math.round(Math.random() * 2e6) + var buf = dangerous.Buffer[method](length) + if (!buffer.Buffer.isBuffer(buf)) ok = false + if (buf.length !== length) ok = false + buf.fill(0, 0, length) + var j + for (j = 0; j < length; j++) { + if (buf[j] !== 0) ok = false + } + buf.fill(1, 0, length) + for (j = 0; j < length; j++) { + if (buf[j] !== 1) ok = false + } + } + t.ok(ok, method) + }) + t.end() +}) + +test('.alloc(size, fill) is `fill`-filled', function (t) { + t.equal(index.Buffer.alloc, safer.Buffer.alloc) + t.equal(index.Buffer.alloc, dangerous.Buffer.alloc) + var ok = true + for (var i = 0; i < 1e2; i++) { + var length = Math.round(Math.random() * 2e6) + var fill = Math.round(Math.random() * 255) + var buf = index.Buffer.alloc(length, fill) + if (!buffer.Buffer.isBuffer(buf)) ok = false + if (buf.length !== length) ok = false + for (var j = 0; j < length; j++) { + if (buf[j] !== fill) ok = false + } + } + t.ok(ok) + t.end() +}) + +test('.alloc(size, fill) is `fill`-filled', function (t) { + t.equal(index.Buffer.alloc, safer.Buffer.alloc) + t.equal(index.Buffer.alloc, dangerous.Buffer.alloc) + var ok = true + for (var i = 0; i < 1e2; i++) { + var length = Math.round(Math.random() * 2e6) + var fill = Math.round(Math.random() * 255) + var buf = index.Buffer.alloc(length, fill) + if (!buffer.Buffer.isBuffer(buf)) ok = false + if (buf.length !== length) ok = false + for (var j = 0; j < length; j++) { + if (buf[j] !== fill) ok = false + } + } + t.ok(ok) + t.deepEqual(index.Buffer.alloc(9, 'a'), index.Buffer.alloc(9, 97)) + t.notDeepEqual(index.Buffer.alloc(9, 'a'), index.Buffer.alloc(9, 98)) + + var tmp = new buffer.Buffer(2) + tmp.fill('ok') + if (tmp[1] === tmp[0]) { + // Outdated Node.js + t.deepEqual(index.Buffer.alloc(5, 'ok'), index.Buffer.from('ooooo')) + } else { + t.deepEqual(index.Buffer.alloc(5, 'ok'), index.Buffer.from('okoko')) + } + t.notDeepEqual(index.Buffer.alloc(5, 'ok'), index.Buffer.from('kokok')) + + t.end() +}) + +test('safer.Buffer.from returns results same as Buffer constructor', function (t) { + [index, safer, dangerous].forEach(function (impl) { + t.deepEqual(impl.Buffer.from(''), new buffer.Buffer('')) + t.deepEqual(impl.Buffer.from('string'), new buffer.Buffer('string')) + t.deepEqual(impl.Buffer.from('string', 'utf-8'), new buffer.Buffer('string', 'utf-8')) + t.deepEqual(impl.Buffer.from('b25ldHdvdGhyZWU=', 'base64'), new buffer.Buffer('b25ldHdvdGhyZWU=', 'base64')) + t.deepEqual(impl.Buffer.from([0, 42, 3]), new buffer.Buffer([0, 42, 3])) + t.deepEqual(impl.Buffer.from(new Uint8Array([0, 42, 3])), new buffer.Buffer(new Uint8Array([0, 42, 3]))) + t.deepEqual(impl.Buffer.from([]), new buffer.Buffer([])) + }) + t.end() +}) + +test('safer.Buffer.from returns consistent results', function (t) { + [index, safer, dangerous].forEach(function (impl) { + t.deepEqual(impl.Buffer.from(''), impl.Buffer.alloc(0)) + t.deepEqual(impl.Buffer.from([]), impl.Buffer.alloc(0)) + t.deepEqual(impl.Buffer.from(new Uint8Array([])), impl.Buffer.alloc(0)) + t.deepEqual(impl.Buffer.from('string', 'utf-8'), impl.Buffer.from('string')) + t.deepEqual(impl.Buffer.from('string'), impl.Buffer.from([115, 116, 114, 105, 110, 103])) + t.deepEqual(impl.Buffer.from('string'), impl.Buffer.from(impl.Buffer.from('string'))) + t.deepEqual(impl.Buffer.from('b25ldHdvdGhyZWU=', 'base64'), impl.Buffer.from('onetwothree')) + t.notDeepEqual(impl.Buffer.from('b25ldHdvdGhyZWU='), impl.Buffer.from('onetwothree')) + }) + t.end() +}) diff --git a/backend/node_modules/send/HISTORY.md b/backend/node_modules/send/HISTORY.md new file mode 100644 index 0000000000000000000000000000000000000000..a7397749461af4597af065fe6289a0a189aa7688 --- /dev/null +++ b/backend/node_modules/send/HISTORY.md @@ -0,0 +1,521 @@ +0.18.0 / 2022-03-23 +=================== + + * Fix emitted 416 error missing headers property + * Limit the headers removed for 304 response + * deps: depd@2.0.0 + - Replace internal `eval` usage with `Function` constructor + - Use instance methods on `process` to check for listeners + * deps: destroy@1.2.0 + * deps: http-errors@2.0.0 + - deps: depd@2.0.0 + - deps: statuses@2.0.1 + * deps: on-finished@2.4.1 + * deps: statuses@2.0.1 + +0.17.2 / 2021-12-11 +=================== + + * pref: ignore empty http tokens + * deps: http-errors@1.8.1 + - deps: inherits@2.0.4 + - deps: toidentifier@1.0.1 + - deps: setprototypeof@1.2.0 + * deps: ms@2.1.3 + +0.17.1 / 2019-05-10 +=================== + + * Set stricter CSP header in redirect & error responses + * deps: range-parser@~1.2.1 + +0.17.0 / 2019-05-03 +=================== + + * deps: http-errors@~1.7.2 + - Set constructor name when possible + - Use `toidentifier` module to make class names + - deps: depd@~1.1.2 + - deps: setprototypeof@1.1.1 + - deps: statuses@'>= 1.5.0 < 2' + * deps: mime@1.6.0 + - Add extensions for JPEG-2000 images + - Add new `font/*` types from IANA + - Add WASM mapping + - Update `.bdoc` to `application/bdoc` + - Update `.bmp` to `image/bmp` + - Update `.m4a` to `audio/mp4` + - Update `.rtf` to `application/rtf` + - Update `.wav` to `audio/wav` + - Update `.xml` to `application/xml` + - Update generic extensions to `application/octet-stream`: + `.deb`, `.dll`, `.dmg`, `.exe`, `.iso`, `.msi` + - Use mime-score module to resolve extension conflicts + * deps: ms@2.1.1 + - Add `week`/`w` support + - Fix negative number handling + * deps: statuses@~1.5.0 + * perf: remove redundant `path.normalize` call + +0.16.2 / 2018-02-07 +=================== + + * Fix incorrect end tag in default error & redirects + * deps: depd@~1.1.2 + - perf: remove argument reassignment + * deps: encodeurl@~1.0.2 + - Fix encoding `%` as last character + * deps: statuses@~1.4.0 + +0.16.1 / 2017-09-29 +=================== + + * Fix regression in edge-case behavior for empty `path` + +0.16.0 / 2017-09-27 +=================== + + * Add `immutable` option + * Fix missing `` in default error & redirects + * Use instance methods on steam to check for listeners + * deps: mime@1.4.1 + - Add 70 new types for file extensions + - Set charset as "UTF-8" for .js and .json + * perf: improve path validation speed + +0.15.6 / 2017-09-22 +=================== + + * deps: debug@2.6.9 + * perf: improve `If-Match` token parsing + +0.15.5 / 2017-09-20 +=================== + + * deps: etag@~1.8.1 + - perf: replace regular expression with substring + * deps: fresh@0.5.2 + - Fix handling of modified headers with invalid dates + - perf: improve ETag match loop + - perf: improve `If-None-Match` token parsing + +0.15.4 / 2017-08-05 +=================== + + * deps: debug@2.6.8 + * deps: depd@~1.1.1 + - Remove unnecessary `Buffer` loading + * deps: http-errors@~1.6.2 + - deps: depd@1.1.1 + +0.15.3 / 2017-05-16 +=================== + + * deps: debug@2.6.7 + - deps: ms@2.0.0 + * deps: ms@2.0.0 + +0.15.2 / 2017-04-26 +=================== + + * deps: debug@2.6.4 + - Fix `DEBUG_MAX_ARRAY_LENGTH` + - deps: ms@0.7.3 + * deps: ms@1.0.0 + +0.15.1 / 2017-03-04 +=================== + + * Fix issue when `Date.parse` does not return `NaN` on invalid date + * Fix strict violation in broken environments + +0.15.0 / 2017-02-25 +=================== + + * Support `If-Match` and `If-Unmodified-Since` headers + * Add `res` and `path` arguments to `directory` event + * Remove usage of `res._headers` private field + - Improves compatibility with Node.js 8 nightly + * Send complete HTML document in redirect & error responses + * Set default CSP header in redirect & error responses + * Use `res.getHeaderNames()` when available + * Use `res.headersSent` when available + * deps: debug@2.6.1 + - Allow colors in workers + - Deprecated `DEBUG_FD` environment variable set to `3` or higher + - Fix error when running under React Native + - Use same color for same namespace + - deps: ms@0.7.2 + * deps: etag@~1.8.0 + * deps: fresh@0.5.0 + - Fix false detection of `no-cache` request directive + - Fix incorrect result when `If-None-Match` has both `*` and ETags + - Fix weak `ETag` matching to match spec + - perf: delay reading header values until needed + - perf: enable strict mode + - perf: hoist regular expressions + - perf: remove duplicate conditional + - perf: remove unnecessary boolean coercions + - perf: skip checking modified time if ETag check failed + - perf: skip parsing `If-None-Match` when no `ETag` header + - perf: use `Date.parse` instead of `new Date` + * deps: http-errors@~1.6.1 + - Make `message` property enumerable for `HttpError`s + - deps: setprototypeof@1.0.3 + +0.14.2 / 2017-01-23 +=================== + + * deps: http-errors@~1.5.1 + - deps: inherits@2.0.3 + - deps: setprototypeof@1.0.2 + - deps: statuses@'>= 1.3.1 < 2' + * deps: ms@0.7.2 + * deps: statuses@~1.3.1 + +0.14.1 / 2016-06-09 +=================== + + * Fix redirect error when `path` contains raw non-URL characters + * Fix redirect when `path` starts with multiple forward slashes + +0.14.0 / 2016-06-06 +=================== + + * Add `acceptRanges` option + * Add `cacheControl` option + * Attempt to combine multiple ranges into single range + * Correctly inherit from `Stream` class + * Fix `Content-Range` header in 416 responses when using `start`/`end` options + * Fix `Content-Range` header missing from default 416 responses + * Ignore non-byte `Range` headers + * deps: http-errors@~1.5.0 + - Add `HttpError` export, for `err instanceof createError.HttpError` + - Support new code `421 Misdirected Request` + - Use `setprototypeof` module to replace `__proto__` setting + - deps: inherits@2.0.1 + - deps: statuses@'>= 1.3.0 < 2' + - perf: enable strict mode + * deps: range-parser@~1.2.0 + - Fix incorrectly returning -1 when there is at least one valid range + - perf: remove internal function + * deps: statuses@~1.3.0 + - Add `421 Misdirected Request` + - perf: enable strict mode + * perf: remove argument reassignment + +0.13.2 / 2016-03-05 +=================== + + * Fix invalid `Content-Type` header when `send.mime.default_type` unset + +0.13.1 / 2016-01-16 +=================== + + * deps: depd@~1.1.0 + - Support web browser loading + - perf: enable strict mode + * deps: destroy@~1.0.4 + - perf: enable strict mode + * deps: escape-html@~1.0.3 + - perf: enable strict mode + - perf: optimize string replacement + - perf: use faster string coercion + * deps: range-parser@~1.0.3 + - perf: enable strict mode + +0.13.0 / 2015-06-16 +=================== + + * Allow Node.js HTTP server to set `Date` response header + * Fix incorrectly removing `Content-Location` on 304 response + * Improve the default redirect response headers + * Send appropriate headers on default error response + * Use `http-errors` for standard emitted errors + * Use `statuses` instead of `http` module for status messages + * deps: escape-html@1.0.2 + * deps: etag@~1.7.0 + - Improve stat performance by removing hashing + * deps: fresh@0.3.0 + - Add weak `ETag` matching support + * deps: on-finished@~2.3.0 + - Add defined behavior for HTTP `CONNECT` requests + - Add defined behavior for HTTP `Upgrade` requests + - deps: ee-first@1.1.1 + * perf: enable strict mode + * perf: remove unnecessary array allocations + +0.12.3 / 2015-05-13 +=================== + + * deps: debug@~2.2.0 + - deps: ms@0.7.1 + * deps: depd@~1.0.1 + * deps: etag@~1.6.0 + - Improve support for JXcore + - Support "fake" stats objects in environments without `fs` + * deps: ms@0.7.1 + - Prevent extraordinarily long inputs + * deps: on-finished@~2.2.1 + +0.12.2 / 2015-03-13 +=================== + + * Throw errors early for invalid `extensions` or `index` options + * deps: debug@~2.1.3 + - Fix high intensity foreground color for bold + - deps: ms@0.7.0 + +0.12.1 / 2015-02-17 +=================== + + * Fix regression sending zero-length files + +0.12.0 / 2015-02-16 +=================== + + * Always read the stat size from the file + * Fix mutating passed-in `options` + * deps: mime@1.3.4 + +0.11.1 / 2015-01-20 +=================== + + * Fix `root` path disclosure + +0.11.0 / 2015-01-05 +=================== + + * deps: debug@~2.1.1 + * deps: etag@~1.5.1 + - deps: crc@3.2.1 + * deps: ms@0.7.0 + - Add `milliseconds` + - Add `msecs` + - Add `secs` + - Add `mins` + - Add `hrs` + - Add `yrs` + * deps: on-finished@~2.2.0 + +0.10.1 / 2014-10-22 +=================== + + * deps: on-finished@~2.1.1 + - Fix handling of pipelined requests + +0.10.0 / 2014-10-15 +=================== + + * deps: debug@~2.1.0 + - Implement `DEBUG_FD` env variable support + * deps: depd@~1.0.0 + * deps: etag@~1.5.0 + - Improve string performance + - Slightly improve speed for weak ETags over 1KB + +0.9.3 / 2014-09-24 +================== + + * deps: etag@~1.4.0 + - Support "fake" stats objects + +0.9.2 / 2014-09-15 +================== + + * deps: depd@0.4.5 + * deps: etag@~1.3.1 + * deps: range-parser@~1.0.2 + +0.9.1 / 2014-09-07 +================== + + * deps: fresh@0.2.4 + +0.9.0 / 2014-09-07 +================== + + * Add `lastModified` option + * Use `etag` to generate `ETag` header + * deps: debug@~2.0.0 + +0.8.5 / 2014-09-04 +================== + + * Fix malicious path detection for empty string path + +0.8.4 / 2014-09-04 +================== + + * Fix a path traversal issue when using `root` + +0.8.3 / 2014-08-16 +================== + + * deps: destroy@1.0.3 + - renamed from dethroy + * deps: on-finished@2.1.0 + +0.8.2 / 2014-08-14 +================== + + * Work around `fd` leak in Node.js 0.10 for `fs.ReadStream` + * deps: dethroy@1.0.2 + +0.8.1 / 2014-08-05 +================== + + * Fix `extensions` behavior when file already has extension + +0.8.0 / 2014-08-05 +================== + + * Add `extensions` option + +0.7.4 / 2014-08-04 +================== + + * Fix serving index files without root dir + +0.7.3 / 2014-07-29 +================== + + * Fix incorrect 403 on Windows and Node.js 0.11 + +0.7.2 / 2014-07-27 +================== + + * deps: depd@0.4.4 + - Work-around v8 generating empty stack traces + +0.7.1 / 2014-07-26 +================== + + * deps: depd@0.4.3 + - Fix exception when global `Error.stackTraceLimit` is too low + +0.7.0 / 2014-07-20 +================== + + * Deprecate `hidden` option; use `dotfiles` option + * Add `dotfiles` option + * deps: debug@1.0.4 + * deps: depd@0.4.2 + - Add `TRACE_DEPRECATION` environment variable + - Remove non-standard grey color from color output + - Support `--no-deprecation` argument + - Support `--trace-deprecation` argument + +0.6.0 / 2014-07-11 +================== + + * Deprecate `from` option; use `root` option + * Deprecate `send.etag()` -- use `etag` in `options` + * Deprecate `send.hidden()` -- use `hidden` in `options` + * Deprecate `send.index()` -- use `index` in `options` + * Deprecate `send.maxage()` -- use `maxAge` in `options` + * Deprecate `send.root()` -- use `root` in `options` + * Cap `maxAge` value to 1 year + * deps: debug@1.0.3 + - Add support for multiple wildcards in namespaces + +0.5.0 / 2014-06-28 +================== + + * Accept string for `maxAge` (converted by `ms`) + * Add `headers` event + * Include link in default redirect response + * Use `EventEmitter.listenerCount` to count listeners + +0.4.3 / 2014-06-11 +================== + + * Do not throw un-catchable error on file open race condition + * Use `escape-html` for HTML escaping + * deps: debug@1.0.2 + - fix some debugging output colors on node.js 0.8 + * deps: finished@1.2.2 + * deps: fresh@0.2.2 + +0.4.2 / 2014-06-09 +================== + + * fix "event emitter leak" warnings + * deps: debug@1.0.1 + * deps: finished@1.2.1 + +0.4.1 / 2014-06-02 +================== + + * Send `max-age` in `Cache-Control` in correct format + +0.4.0 / 2014-05-27 +================== + + * Calculate ETag with md5 for reduced collisions + * Fix wrong behavior when index file matches directory + * Ignore stream errors after request ends + - Goodbye `EBADF, read` + * Skip directories in index file search + * deps: debug@0.8.1 + +0.3.0 / 2014-04-24 +================== + + * Fix sending files with dots without root set + * Coerce option types + * Accept API options in options object + * Set etags to "weak" + * Include file path in etag + * Make "Can't set headers after they are sent." catchable + * Send full entity-body for multi range requests + * Default directory access to 403 when index disabled + * Support multiple index paths + * Support "If-Range" header + * Control whether to generate etags + * deps: mime@1.2.11 + +0.2.0 / 2014-01-29 +================== + + * update range-parser and fresh + +0.1.4 / 2013-08-11 +================== + + * update fresh + +0.1.3 / 2013-07-08 +================== + + * Revert "Fix fd leak" + +0.1.2 / 2013-07-03 +================== + + * Fix fd leak + +0.1.0 / 2012-08-25 +================== + + * add options parameter to send() that is passed to fs.createReadStream() [kanongil] + +0.0.4 / 2012-08-16 +================== + + * allow custom "Accept-Ranges" definition + +0.0.3 / 2012-07-16 +================== + + * fix normalization of the root directory. Closes #3 + +0.0.2 / 2012-07-09 +================== + + * add passing of req explicitly for now (YUCK) + +0.0.1 / 2010-01-03 +================== + + * Initial release diff --git a/backend/node_modules/send/LICENSE b/backend/node_modules/send/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..b6ea1c1fd44ff6f4af6a8e4e5d4793004b9e8524 --- /dev/null +++ b/backend/node_modules/send/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2012 TJ Holowaychuk +Copyright (c) 2014-2022 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/backend/node_modules/send/README.md b/backend/node_modules/send/README.md new file mode 100644 index 0000000000000000000000000000000000000000..fadf8383c056f23dc8634cec647e2244bd94fce7 --- /dev/null +++ b/backend/node_modules/send/README.md @@ -0,0 +1,327 @@ +# send + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Linux Build][github-actions-ci-image]][github-actions-ci-url] +[![Windows Build][appveyor-image]][appveyor-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Send is a library for streaming files from the file system as a http response +supporting partial responses (Ranges), conditional-GET negotiation (If-Match, +If-Unmodified-Since, If-None-Match, If-Modified-Since), high test coverage, +and granular events which may be leveraged to take appropriate actions in your +application or framework. + +Looking to serve up entire folders mapped to URLs? Try [serve-static](https://www.npmjs.org/package/serve-static). + +## 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 send +``` + +## API + +```js +var send = require('send') +``` + +### send(req, path, [options]) + +Create a new `SendStream` for the given path to send to a `res`. The `req` is +the Node.js HTTP request and the `path` is a urlencoded path to send (urlencoded, +not the actual file-system path). + +#### Options + +##### acceptRanges + +Enable or disable accepting ranged requests, defaults to true. +Disabling this will not send `Accept-Ranges` and ignore the contents +of the `Range` request header. + +##### cacheControl + +Enable or disable setting `Cache-Control` response header, defaults to +true. Disabling this will ignore the `immutable` and `maxAge` options. + +##### dotfiles + +Set how "dotfiles" are treated when encountered. A dotfile is a file +or directory that begins with a dot ("."). Note this check is done on +the path itself without checking if the path actually exists on the +disk. If `root` is specified, only the dotfiles above the root are +checked (i.e. the root itself can be within a dotfile when when set +to "deny"). + + - `'allow'` No special treatment for dotfiles. + - `'deny'` Send a 403 for any request for a dotfile. + - `'ignore'` Pretend like the dotfile does not exist and 404. + +The default value is _similar_ to `'ignore'`, with the exception that +this default will not ignore the files within a directory that begins +with a dot, for backward-compatibility. + +##### end + +Byte offset at which the stream ends, defaults to the length of the file +minus 1. The end is inclusive in the stream, meaning `end: 3` will include +the 4th byte in the stream. + +##### etag + +Enable or disable etag generation, defaults to true. + +##### extensions + +If a given file doesn't exist, try appending one of the given extensions, +in the given order. By default, this is disabled (set to `false`). An +example value that will serve extension-less HTML files: `['html', 'htm']`. +This is skipped if the requested file already has an extension. + +##### immutable + +Enable or disable the `immutable` directive in the `Cache-Control` response +header, defaults to `false`. If set to `true`, the `maxAge` option should +also be specified to enable caching. The `immutable` directive will prevent +supported clients from making conditional requests during the life of the +`maxAge` option to check if the file has changed. + +##### index + +By default send supports "index.html" files, to disable this +set `false` or to supply a new index pass a string or an array +in preferred order. + +##### lastModified + +Enable or disable `Last-Modified` header, defaults to true. Uses the file +system's last modified value. + +##### maxAge + +Provide a max-age in milliseconds for http caching, defaults to 0. +This can also be a string accepted by the +[ms](https://www.npmjs.org/package/ms#readme) module. + +##### root + +Serve files relative to `path`. + +##### start + +Byte offset at which the stream starts, defaults to 0. The start is inclusive, +meaning `start: 2` will include the 3rd byte in the stream. + +#### Events + +The `SendStream` is an event emitter and will emit the following events: + + - `error` an error occurred `(err)` + - `directory` a directory was requested `(res, path)` + - `file` a file was requested `(path, stat)` + - `headers` the headers are about to be set on a file `(res, path, stat)` + - `stream` file streaming has started `(stream)` + - `end` streaming has completed + +#### .pipe + +The `pipe` method is used to pipe the response into the Node.js HTTP response +object, typically `send(req, path, options).pipe(res)`. + +### .mime + +The `mime` export is the global instance of of the +[`mime` npm module](https://www.npmjs.com/package/mime). + +This is used to configure the MIME types that are associated with file extensions +as well as other options for how to resolve the MIME type of a file (like the +default type to use for an unknown file extension). + +## Error-handling + +By default when no `error` listeners are present an automatic response will be +made, otherwise you have full control over the response, aka you may show a 5xx +page etc. + +## Caching + +It does _not_ perform internal caching, you should use a reverse proxy cache +such as Varnish for this, or those fancy things called CDNs. If your +application is small enough that it would benefit from single-node memory +caching, it's small enough that it does not need caching at all ;). + +## Debugging + +To enable `debug()` instrumentation output export __DEBUG__: + +``` +$ DEBUG=send node app +``` + +## Running tests + +``` +$ npm install +$ npm test +``` + +## Examples + +### Serve a specific file + +This simple example will send a specific file to all requests. + +```js +var http = require('http') +var send = require('send') + +var server = http.createServer(function onRequest (req, res) { + send(req, '/path/to/index.html') + .pipe(res) +}) + +server.listen(3000) +``` + +### Serve all files from a directory + +This simple example will just serve up all the files in a +given directory as the top-level. For example, a request +`GET /foo.txt` will send back `/www/public/foo.txt`. + +```js +var http = require('http') +var parseUrl = require('parseurl') +var send = require('send') + +var server = http.createServer(function onRequest (req, res) { + send(req, parseUrl(req).pathname, { root: '/www/public' }) + .pipe(res) +}) + +server.listen(3000) +``` + +### Custom file types + +```js +var http = require('http') +var parseUrl = require('parseurl') +var send = require('send') + +// Default unknown types to text/plain +send.mime.default_type = 'text/plain' + +// Add a custom type +send.mime.define({ + 'application/x-my-type': ['x-mt', 'x-mtt'] +}) + +var server = http.createServer(function onRequest (req, res) { + send(req, parseUrl(req).pathname, { root: '/www/public' }) + .pipe(res) +}) + +server.listen(3000) +``` + +### Custom directory index view + +This is a example of serving up a structure of directories with a +custom function to render a listing of a directory. + +```js +var http = require('http') +var fs = require('fs') +var parseUrl = require('parseurl') +var send = require('send') + +// Transfer arbitrary files from within /www/example.com/public/* +// with a custom handler for directory listing +var server = http.createServer(function onRequest (req, res) { + send(req, parseUrl(req).pathname, { index: false, root: '/www/public' }) + .once('directory', directory) + .pipe(res) +}) + +server.listen(3000) + +// Custom directory handler +function directory (res, path) { + var stream = this + + // redirect to trailing slash for consistent url + if (!stream.hasTrailingSlash()) { + return stream.redirect(path) + } + + // get directory list + fs.readdir(path, function onReaddir (err, list) { + if (err) return stream.error(err) + + // render an index for the directory + res.setHeader('Content-Type', 'text/plain; charset=UTF-8') + res.end(list.join('\n') + '\n') + }) +} +``` + +### Serving from a root directory with custom error-handling + +```js +var http = require('http') +var parseUrl = require('parseurl') +var send = require('send') + +var server = http.createServer(function onRequest (req, res) { + // your custom error-handling logic: + function error (err) { + res.statusCode = err.status || 500 + res.end(err.message) + } + + // your custom headers + function headers (res, path, stat) { + // serve all files for download + res.setHeader('Content-Disposition', 'attachment') + } + + // your custom directory handling logic: + function redirect () { + res.statusCode = 301 + res.setHeader('Location', req.url + '/') + res.end('Redirecting to ' + req.url + '/') + } + + // transfer arbitrary files from within + // /www/example.com/public/* + send(req, parseUrl(req).pathname, { root: '/www/public' }) + .on('error', error) + .on('directory', redirect) + .on('headers', headers) + .pipe(res) +}) + +server.listen(3000) +``` + +## License + +[MIT](LICENSE) + +[appveyor-image]: https://badgen.net/appveyor/ci/dougwilson/send/master?label=windows +[appveyor-url]: https://ci.appveyor.com/project/dougwilson/send +[coveralls-image]: https://badgen.net/coveralls/c/github/pillarjs/send/master +[coveralls-url]: https://coveralls.io/r/pillarjs/send?branch=master +[github-actions-ci-image]: https://badgen.net/github/checks/pillarjs/send/master?label=linux +[github-actions-ci-url]: https://github.com/pillarjs/send/actions/workflows/ci.yml +[node-image]: https://badgen.net/npm/node/send +[node-url]: https://nodejs.org/en/download/ +[npm-downloads-image]: https://badgen.net/npm/dm/send +[npm-url]: https://npmjs.org/package/send +[npm-version-image]: https://badgen.net/npm/v/send diff --git a/backend/node_modules/send/SECURITY.md b/backend/node_modules/send/SECURITY.md new file mode 100644 index 0000000000000000000000000000000000000000..46b48f7b0733cdfa849734a92b51bfc213a2ee49 --- /dev/null +++ b/backend/node_modules/send/SECURITY.md @@ -0,0 +1,24 @@ +# Security Policies and Procedures + +## Reporting a Bug + +The `send` team and community take all security bugs seriously. Thank you +for improving the security of Express. 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 `send`. This information +can be found in the npm registry using the command `npm owner ls send`. +If unsure or unable to get the information from the above, open an issue +in the [project issue tracker](https://github.com/pillarjs/send/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/backend/node_modules/send/index.js b/backend/node_modules/send/index.js new file mode 100644 index 0000000000000000000000000000000000000000..89afd7e584a50233d6948255c4a4f52edbaf297c --- /dev/null +++ b/backend/node_modules/send/index.js @@ -0,0 +1,1143 @@ +/*! + * send + * Copyright(c) 2012 TJ Holowaychuk + * Copyright(c) 2014-2022 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var createError = require('http-errors') +var debug = require('debug')('send') +var deprecate = require('depd')('send') +var destroy = require('destroy') +var encodeUrl = require('encodeurl') +var escapeHtml = require('escape-html') +var etag = require('etag') +var fresh = require('fresh') +var fs = require('fs') +var mime = require('mime') +var ms = require('ms') +var onFinished = require('on-finished') +var parseRange = require('range-parser') +var path = require('path') +var statuses = require('statuses') +var Stream = require('stream') +var util = require('util') + +/** + * Path function references. + * @private + */ + +var extname = path.extname +var join = path.join +var normalize = path.normalize +var resolve = path.resolve +var sep = path.sep + +/** + * Regular expression for identifying a bytes Range header. + * @private + */ + +var BYTES_RANGE_REGEXP = /^ *bytes=/ + +/** + * Maximum value allowed for the max age. + * @private + */ + +var MAX_MAXAGE = 60 * 60 * 24 * 365 * 1000 // 1 year + +/** + * Regular expression to match a path with a directory up component. + * @private + */ + +var UP_PATH_REGEXP = /(?:^|[\\/])\.\.(?:[\\/]|$)/ + +/** + * Module exports. + * @public + */ + +module.exports = send +module.exports.mime = mime + +/** + * Return a `SendStream` for `req` and `path`. + * + * @param {object} req + * @param {string} path + * @param {object} [options] + * @return {SendStream} + * @public + */ + +function send (req, path, options) { + return new SendStream(req, path, options) +} + +/** + * Initialize a `SendStream` with the given `path`. + * + * @param {Request} req + * @param {String} path + * @param {object} [options] + * @private + */ + +function SendStream (req, path, options) { + Stream.call(this) + + var opts = options || {} + + this.options = opts + this.path = path + this.req = req + + this._acceptRanges = opts.acceptRanges !== undefined + ? Boolean(opts.acceptRanges) + : true + + this._cacheControl = opts.cacheControl !== undefined + ? Boolean(opts.cacheControl) + : true + + this._etag = opts.etag !== undefined + ? Boolean(opts.etag) + : true + + this._dotfiles = opts.dotfiles !== undefined + ? opts.dotfiles + : 'ignore' + + if (this._dotfiles !== 'ignore' && this._dotfiles !== 'allow' && this._dotfiles !== 'deny') { + throw new TypeError('dotfiles option must be "allow", "deny", or "ignore"') + } + + this._hidden = Boolean(opts.hidden) + + if (opts.hidden !== undefined) { + deprecate('hidden: use dotfiles: \'' + (this._hidden ? 'allow' : 'ignore') + '\' instead') + } + + // legacy support + if (opts.dotfiles === undefined) { + this._dotfiles = undefined + } + + this._extensions = opts.extensions !== undefined + ? normalizeList(opts.extensions, 'extensions option') + : [] + + this._immutable = opts.immutable !== undefined + ? Boolean(opts.immutable) + : false + + this._index = opts.index !== undefined + ? normalizeList(opts.index, 'index option') + : ['index.html'] + + this._lastModified = opts.lastModified !== undefined + ? Boolean(opts.lastModified) + : true + + this._maxage = opts.maxAge || opts.maxage + this._maxage = typeof this._maxage === 'string' + ? ms(this._maxage) + : Number(this._maxage) + this._maxage = !isNaN(this._maxage) + ? Math.min(Math.max(0, this._maxage), MAX_MAXAGE) + : 0 + + this._root = opts.root + ? resolve(opts.root) + : null + + if (!this._root && opts.from) { + this.from(opts.from) + } +} + +/** + * Inherits from `Stream`. + */ + +util.inherits(SendStream, Stream) + +/** + * Enable or disable etag generation. + * + * @param {Boolean} val + * @return {SendStream} + * @api public + */ + +SendStream.prototype.etag = deprecate.function(function etag (val) { + this._etag = Boolean(val) + debug('etag %s', this._etag) + return this +}, 'send.etag: pass etag as option') + +/** + * Enable or disable "hidden" (dot) files. + * + * @param {Boolean} path + * @return {SendStream} + * @api public + */ + +SendStream.prototype.hidden = deprecate.function(function hidden (val) { + this._hidden = Boolean(val) + this._dotfiles = undefined + debug('hidden %s', this._hidden) + return this +}, 'send.hidden: use dotfiles option') + +/** + * Set index `paths`, set to a falsy + * value to disable index support. + * + * @param {String|Boolean|Array} paths + * @return {SendStream} + * @api public + */ + +SendStream.prototype.index = deprecate.function(function index (paths) { + var index = !paths ? [] : normalizeList(paths, 'paths argument') + debug('index %o', paths) + this._index = index + return this +}, 'send.index: pass index as option') + +/** + * Set root `path`. + * + * @param {String} path + * @return {SendStream} + * @api public + */ + +SendStream.prototype.root = function root (path) { + this._root = resolve(String(path)) + debug('root %s', this._root) + return this +} + +SendStream.prototype.from = deprecate.function(SendStream.prototype.root, + 'send.from: pass root as option') + +SendStream.prototype.root = deprecate.function(SendStream.prototype.root, + 'send.root: pass root as option') + +/** + * Set max-age to `maxAge`. + * + * @param {Number} maxAge + * @return {SendStream} + * @api public + */ + +SendStream.prototype.maxage = deprecate.function(function maxage (maxAge) { + this._maxage = typeof maxAge === 'string' + ? ms(maxAge) + : Number(maxAge) + this._maxage = !isNaN(this._maxage) + ? Math.min(Math.max(0, this._maxage), MAX_MAXAGE) + : 0 + debug('max-age %d', this._maxage) + return this +}, 'send.maxage: pass maxAge as option') + +/** + * Emit error with `status`. + * + * @param {number} status + * @param {Error} [err] + * @private + */ + +SendStream.prototype.error = function error (status, err) { + // emit if listeners instead of responding + if (hasListeners(this, 'error')) { + return this.emit('error', createHttpError(status, err)) + } + + var res = this.res + var msg = statuses.message[status] || String(status) + var doc = createHtmlDocument('Error', escapeHtml(msg)) + + // clear existing headers + clearHeaders(res) + + // add error headers + if (err && err.headers) { + setHeaders(res, err.headers) + } + + // send basic response + res.statusCode = status + res.setHeader('Content-Type', 'text/html; charset=UTF-8') + res.setHeader('Content-Length', Buffer.byteLength(doc)) + res.setHeader('Content-Security-Policy', "default-src 'none'") + res.setHeader('X-Content-Type-Options', 'nosniff') + res.end(doc) +} + +/** + * Check if the pathname ends with "/". + * + * @return {boolean} + * @private + */ + +SendStream.prototype.hasTrailingSlash = function hasTrailingSlash () { + return this.path[this.path.length - 1] === '/' +} + +/** + * Check if this is a conditional GET request. + * + * @return {Boolean} + * @api private + */ + +SendStream.prototype.isConditionalGET = function isConditionalGET () { + return this.req.headers['if-match'] || + this.req.headers['if-unmodified-since'] || + this.req.headers['if-none-match'] || + this.req.headers['if-modified-since'] +} + +/** + * Check if the request preconditions failed. + * + * @return {boolean} + * @private + */ + +SendStream.prototype.isPreconditionFailure = function isPreconditionFailure () { + var req = this.req + var res = this.res + + // if-match + var match = req.headers['if-match'] + if (match) { + var etag = res.getHeader('ETag') + return !etag || (match !== '*' && parseTokenList(match).every(function (match) { + return match !== etag && match !== 'W/' + etag && 'W/' + match !== etag + })) + } + + // if-unmodified-since + var unmodifiedSince = parseHttpDate(req.headers['if-unmodified-since']) + if (!isNaN(unmodifiedSince)) { + var lastModified = parseHttpDate(res.getHeader('Last-Modified')) + return isNaN(lastModified) || lastModified > unmodifiedSince + } + + return false +} + +/** + * Strip various content header fields for a change in entity. + * + * @private + */ + +SendStream.prototype.removeContentHeaderFields = function removeContentHeaderFields () { + var res = this.res + + res.removeHeader('Content-Encoding') + res.removeHeader('Content-Language') + res.removeHeader('Content-Length') + res.removeHeader('Content-Range') + res.removeHeader('Content-Type') +} + +/** + * Respond with 304 not modified. + * + * @api private + */ + +SendStream.prototype.notModified = function notModified () { + var res = this.res + debug('not modified') + this.removeContentHeaderFields() + res.statusCode = 304 + res.end() +} + +/** + * Raise error that headers already sent. + * + * @api private + */ + +SendStream.prototype.headersAlreadySent = function headersAlreadySent () { + var err = new Error('Can\'t set headers after they are sent.') + debug('headers already sent') + this.error(500, err) +} + +/** + * Check if the request is cacheable, aka + * responded with 2xx or 304 (see RFC 2616 section 14.2{5,6}). + * + * @return {Boolean} + * @api private + */ + +SendStream.prototype.isCachable = function isCachable () { + var statusCode = this.res.statusCode + return (statusCode >= 200 && statusCode < 300) || + statusCode === 304 +} + +/** + * Handle stat() error. + * + * @param {Error} error + * @private + */ + +SendStream.prototype.onStatError = function onStatError (error) { + switch (error.code) { + case 'ENAMETOOLONG': + case 'ENOENT': + case 'ENOTDIR': + this.error(404, error) + break + default: + this.error(500, error) + break + } +} + +/** + * Check if the cache is fresh. + * + * @return {Boolean} + * @api private + */ + +SendStream.prototype.isFresh = function isFresh () { + return fresh(this.req.headers, { + etag: this.res.getHeader('ETag'), + 'last-modified': this.res.getHeader('Last-Modified') + }) +} + +/** + * Check if the range is fresh. + * + * @return {Boolean} + * @api private + */ + +SendStream.prototype.isRangeFresh = function isRangeFresh () { + var ifRange = this.req.headers['if-range'] + + if (!ifRange) { + return true + } + + // if-range as etag + if (ifRange.indexOf('"') !== -1) { + var etag = this.res.getHeader('ETag') + return Boolean(etag && ifRange.indexOf(etag) !== -1) + } + + // if-range as modified date + var lastModified = this.res.getHeader('Last-Modified') + return parseHttpDate(lastModified) <= parseHttpDate(ifRange) +} + +/** + * Redirect to path. + * + * @param {string} path + * @private + */ + +SendStream.prototype.redirect = function redirect (path) { + var res = this.res + + if (hasListeners(this, 'directory')) { + this.emit('directory', res, path) + return + } + + if (this.hasTrailingSlash()) { + this.error(403) + return + } + + var loc = encodeUrl(collapseLeadingSlashes(this.path + '/')) + var doc = createHtmlDocument('Redirecting', 'Redirecting to ' + + escapeHtml(loc) + '') + + // redirect + res.statusCode = 301 + res.setHeader('Content-Type', 'text/html; charset=UTF-8') + res.setHeader('Content-Length', Buffer.byteLength(doc)) + res.setHeader('Content-Security-Policy', "default-src 'none'") + res.setHeader('X-Content-Type-Options', 'nosniff') + res.setHeader('Location', loc) + res.end(doc) +} + +/** + * Pipe to `res. + * + * @param {Stream} res + * @return {Stream} res + * @api public + */ + +SendStream.prototype.pipe = function pipe (res) { + // root path + var root = this._root + + // references + this.res = res + + // decode the path + var path = decode(this.path) + if (path === -1) { + this.error(400) + return res + } + + // null byte(s) + if (~path.indexOf('\0')) { + this.error(400) + return res + } + + var parts + if (root !== null) { + // normalize + if (path) { + path = normalize('.' + sep + path) + } + + // malicious path + if (UP_PATH_REGEXP.test(path)) { + debug('malicious path "%s"', path) + this.error(403) + return res + } + + // explode path parts + parts = path.split(sep) + + // join / normalize from optional root dir + path = normalize(join(root, path)) + } else { + // ".." is malicious without "root" + if (UP_PATH_REGEXP.test(path)) { + debug('malicious path "%s"', path) + this.error(403) + return res + } + + // explode path parts + parts = normalize(path).split(sep) + + // resolve the path + path = resolve(path) + } + + // dotfile handling + if (containsDotFile(parts)) { + var access = this._dotfiles + + // legacy support + if (access === undefined) { + access = parts[parts.length - 1][0] === '.' + ? (this._hidden ? 'allow' : 'ignore') + : 'allow' + } + + debug('%s dotfile "%s"', access, path) + switch (access) { + case 'allow': + break + case 'deny': + this.error(403) + return res + case 'ignore': + default: + this.error(404) + return res + } + } + + // index file support + if (this._index.length && this.hasTrailingSlash()) { + this.sendIndex(path) + return res + } + + this.sendFile(path) + return res +} + +/** + * Transfer `path`. + * + * @param {String} path + * @api public + */ + +SendStream.prototype.send = function send (path, stat) { + var len = stat.size + var options = this.options + var opts = {} + var res = this.res + var req = this.req + var ranges = req.headers.range + var offset = options.start || 0 + + if (headersSent(res)) { + // impossible to send now + this.headersAlreadySent() + return + } + + debug('pipe "%s"', path) + + // set header fields + this.setHeader(path, stat) + + // set content-type + this.type(path) + + // conditional GET support + if (this.isConditionalGET()) { + if (this.isPreconditionFailure()) { + this.error(412) + return + } + + if (this.isCachable() && this.isFresh()) { + this.notModified() + return + } + } + + // adjust len to start/end options + len = Math.max(0, len - offset) + if (options.end !== undefined) { + var bytes = options.end - offset + 1 + if (len > bytes) len = bytes + } + + // Range support + if (this._acceptRanges && BYTES_RANGE_REGEXP.test(ranges)) { + // parse + ranges = parseRange(len, ranges, { + combine: true + }) + + // If-Range support + if (!this.isRangeFresh()) { + debug('range stale') + ranges = -2 + } + + // unsatisfiable + if (ranges === -1) { + debug('range unsatisfiable') + + // Content-Range + res.setHeader('Content-Range', contentRange('bytes', len)) + + // 416 Requested Range Not Satisfiable + return this.error(416, { + headers: { 'Content-Range': res.getHeader('Content-Range') } + }) + } + + // valid (syntactically invalid/multiple ranges are treated as a regular response) + if (ranges !== -2 && ranges.length === 1) { + debug('range %j', ranges) + + // Content-Range + res.statusCode = 206 + res.setHeader('Content-Range', contentRange('bytes', len, ranges[0])) + + // adjust for requested range + offset += ranges[0].start + len = ranges[0].end - ranges[0].start + 1 + } + } + + // clone options + for (var prop in options) { + opts[prop] = options[prop] + } + + // set read options + opts.start = offset + opts.end = Math.max(offset, offset + len - 1) + + // content-length + res.setHeader('Content-Length', len) + + // HEAD support + if (req.method === 'HEAD') { + res.end() + return + } + + this.stream(path, opts) +} + +/** + * Transfer file for `path`. + * + * @param {String} path + * @api private + */ +SendStream.prototype.sendFile = function sendFile (path) { + var i = 0 + var self = this + + debug('stat "%s"', path) + fs.stat(path, function onstat (err, stat) { + if (err && err.code === 'ENOENT' && !extname(path) && path[path.length - 1] !== sep) { + // not found, check extensions + return next(err) + } + if (err) return self.onStatError(err) + if (stat.isDirectory()) return self.redirect(path) + self.emit('file', path, stat) + self.send(path, stat) + }) + + function next (err) { + if (self._extensions.length <= i) { + return err + ? self.onStatError(err) + : self.error(404) + } + + var p = path + '.' + self._extensions[i++] + + debug('stat "%s"', p) + fs.stat(p, function (err, stat) { + if (err) return next(err) + if (stat.isDirectory()) return next() + self.emit('file', p, stat) + self.send(p, stat) + }) + } +} + +/** + * Transfer index for `path`. + * + * @param {String} path + * @api private + */ +SendStream.prototype.sendIndex = function sendIndex (path) { + var i = -1 + var self = this + + function next (err) { + if (++i >= self._index.length) { + if (err) return self.onStatError(err) + return self.error(404) + } + + var p = join(path, self._index[i]) + + debug('stat "%s"', p) + fs.stat(p, function (err, stat) { + if (err) return next(err) + if (stat.isDirectory()) return next() + self.emit('file', p, stat) + self.send(p, stat) + }) + } + + next() +} + +/** + * Stream `path` to the response. + * + * @param {String} path + * @param {Object} options + * @api private + */ + +SendStream.prototype.stream = function stream (path, options) { + var self = this + var res = this.res + + // pipe + var stream = fs.createReadStream(path, options) + this.emit('stream', stream) + stream.pipe(res) + + // cleanup + function cleanup () { + destroy(stream, true) + } + + // response finished, cleanup + onFinished(res, cleanup) + + // error handling + stream.on('error', function onerror (err) { + // clean up stream early + cleanup() + + // error + self.onStatError(err) + }) + + // end + stream.on('end', function onend () { + self.emit('end') + }) +} + +/** + * Set content-type based on `path` + * if it hasn't been explicitly set. + * + * @param {String} path + * @api private + */ + +SendStream.prototype.type = function type (path) { + var res = this.res + + if (res.getHeader('Content-Type')) return + + var type = mime.lookup(path) + + if (!type) { + debug('no content-type') + return + } + + var charset = mime.charsets.lookup(type) + + debug('content-type %s', type) + res.setHeader('Content-Type', type + (charset ? '; charset=' + charset : '')) +} + +/** + * Set response header fields, most + * fields may be pre-defined. + * + * @param {String} path + * @param {Object} stat + * @api private + */ + +SendStream.prototype.setHeader = function setHeader (path, stat) { + var res = this.res + + this.emit('headers', res, path, stat) + + if (this._acceptRanges && !res.getHeader('Accept-Ranges')) { + debug('accept ranges') + res.setHeader('Accept-Ranges', 'bytes') + } + + if (this._cacheControl && !res.getHeader('Cache-Control')) { + var cacheControl = 'public, max-age=' + Math.floor(this._maxage / 1000) + + if (this._immutable) { + cacheControl += ', immutable' + } + + debug('cache-control %s', cacheControl) + res.setHeader('Cache-Control', cacheControl) + } + + if (this._lastModified && !res.getHeader('Last-Modified')) { + var modified = stat.mtime.toUTCString() + debug('modified %s', modified) + res.setHeader('Last-Modified', modified) + } + + if (this._etag && !res.getHeader('ETag')) { + var val = etag(stat) + debug('etag %s', val) + res.setHeader('ETag', val) + } +} + +/** + * Clear all headers from a response. + * + * @param {object} res + * @private + */ + +function clearHeaders (res) { + var headers = getHeaderNames(res) + + for (var i = 0; i < headers.length; i++) { + res.removeHeader(headers[i]) + } +} + +/** + * Collapse all leading slashes into a single slash + * + * @param {string} str + * @private + */ +function collapseLeadingSlashes (str) { + for (var i = 0; i < str.length; i++) { + if (str[i] !== '/') { + break + } + } + + return i > 1 + ? '/' + str.substr(i) + : str +} + +/** + * Determine if path parts contain a dotfile. + * + * @api private + */ + +function containsDotFile (parts) { + for (var i = 0; i < parts.length; i++) { + var part = parts[i] + if (part.length > 1 && part[0] === '.') { + return true + } + } + + return false +} + +/** + * Create a Content-Range header. + * + * @param {string} type + * @param {number} size + * @param {array} [range] + */ + +function contentRange (type, size, range) { + return type + ' ' + (range ? range.start + '-' + range.end : '*') + '/' + size +} + +/** + * Create a minimal HTML document. + * + * @param {string} title + * @param {string} body + * @private + */ + +function createHtmlDocument (title, body) { + return '\n' + + '\n' + + '\n' + + '\n' + + '' + title + '\n' + + '\n' + + '\n' + + '
' + body + '
\n' + + '\n' + + '\n' +} + +/** + * Create a HttpError object from simple arguments. + * + * @param {number} status + * @param {Error|object} err + * @private + */ + +function createHttpError (status, err) { + if (!err) { + return createError(status) + } + + return err instanceof Error + ? createError(status, err, { expose: false }) + : createError(status, err) +} + +/** + * decodeURIComponent. + * + * Allows V8 to only deoptimize this fn instead of all + * of send(). + * + * @param {String} path + * @api private + */ + +function decode (path) { + try { + return decodeURIComponent(path) + } catch (err) { + return -1 + } +} + +/** + * Get the header names on a respnse. + * + * @param {object} res + * @returns {array[string]} + * @private + */ + +function getHeaderNames (res) { + return typeof res.getHeaderNames !== 'function' + ? Object.keys(res._headers || {}) + : res.getHeaderNames() +} + +/** + * Determine if emitter has listeners of a given type. + * + * The way to do this check is done three different ways in Node.js >= 0.8 + * so this consolidates them into a minimal set using instance methods. + * + * @param {EventEmitter} emitter + * @param {string} type + * @returns {boolean} + * @private + */ + +function hasListeners (emitter, type) { + var count = typeof emitter.listenerCount !== 'function' + ? emitter.listeners(type).length + : emitter.listenerCount(type) + + return count > 0 +} + +/** + * Determine if the response headers have been sent. + * + * @param {object} res + * @returns {boolean} + * @private + */ + +function headersSent (res) { + return typeof res.headersSent !== 'boolean' + ? Boolean(res._header) + : res.headersSent +} + +/** + * Normalize the index option into an array. + * + * @param {boolean|string|array} val + * @param {string} name + * @private + */ + +function normalizeList (val, name) { + var list = [].concat(val || []) + + for (var i = 0; i < list.length; i++) { + if (typeof list[i] !== 'string') { + throw new TypeError(name + ' must be array of strings or false') + } + } + + return list +} + +/** + * Parse an HTTP Date into a number. + * + * @param {string} date + * @private + */ + +function parseHttpDate (date) { + var timestamp = date && Date.parse(date) + + return typeof timestamp === 'number' + ? timestamp + : NaN +} + +/** + * Parse a HTTP token list. + * + * @param {string} str + * @private + */ + +function parseTokenList (str) { + var end = 0 + var list = [] + var start = 0 + + // gather tokens + for (var i = 0, len = str.length; i < len; i++) { + switch (str.charCodeAt(i)) { + case 0x20: /* */ + if (start === end) { + start = end = i + 1 + } + break + case 0x2c: /* , */ + if (start !== end) { + list.push(str.substring(start, end)) + } + start = end = i + 1 + break + default: + end = i + 1 + break + } + } + + // final token + if (start !== end) { + list.push(str.substring(start, end)) + } + + return list +} + +/** + * Set an object of headers on a response. + * + * @param {object} res + * @param {object} headers + * @private + */ + +function setHeaders (res, headers) { + var keys = Object.keys(headers) + + for (var i = 0; i < keys.length; i++) { + var key = keys[i] + res.setHeader(key, headers[key]) + } +} diff --git a/backend/node_modules/send/node_modules/ms/index.js b/backend/node_modules/send/node_modules/ms/index.js new file mode 100644 index 0000000000000000000000000000000000000000..ea734fb73820316ed1c0f6a2f6e96dce0e3eb6f0 --- /dev/null +++ b/backend/node_modules/send/node_modules/ms/index.js @@ -0,0 +1,162 @@ +/** + * Helpers. + */ + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var w = d * 7; +var y = d * 365.25; + +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ + +module.exports = function (val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isFinite(val)) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; + +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + +function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'weeks': + case 'week': + case 'w': + return n * w; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } +} + +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + 'd'; + } + if (msAbs >= h) { + return Math.round(ms / h) + 'h'; + } + if (msAbs >= m) { + return Math.round(ms / m) + 'm'; + } + if (msAbs >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; +} + +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, 'day'); + } + if (msAbs >= h) { + return plural(ms, msAbs, h, 'hour'); + } + if (msAbs >= m) { + return plural(ms, msAbs, m, 'minute'); + } + if (msAbs >= s) { + return plural(ms, msAbs, s, 'second'); + } + return ms + ' ms'; +} + +/** + * Pluralization helper. + */ + +function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); +} diff --git a/backend/node_modules/send/node_modules/ms/license.md b/backend/node_modules/send/node_modules/ms/license.md new file mode 100644 index 0000000000000000000000000000000000000000..fa5d39b6213f8a5e142b643575f99d9149cc71c6 --- /dev/null +++ b/backend/node_modules/send/node_modules/ms/license.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2020 Vercel, Inc. + +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/backend/node_modules/send/node_modules/ms/package.json b/backend/node_modules/send/node_modules/ms/package.json new file mode 100644 index 0000000000000000000000000000000000000000..49971890df8e2b9a4a5f4909fbd6678b862d8a50 --- /dev/null +++ b/backend/node_modules/send/node_modules/ms/package.json @@ -0,0 +1,38 @@ +{ + "name": "ms", + "version": "2.1.3", + "description": "Tiny millisecond conversion utility", + "repository": "vercel/ms", + "main": "./index", + "files": [ + "index.js" + ], + "scripts": { + "precommit": "lint-staged", + "lint": "eslint lib/* bin/*", + "test": "mocha tests.js" + }, + "eslintConfig": { + "extends": "eslint:recommended", + "env": { + "node": true, + "es6": true + } + }, + "lint-staged": { + "*.js": [ + "npm run lint", + "prettier --single-quote --write", + "git add" + ] + }, + "license": "MIT", + "devDependencies": { + "eslint": "4.18.2", + "expect.js": "0.3.1", + "husky": "0.14.3", + "lint-staged": "5.0.0", + "mocha": "4.0.1", + "prettier": "2.0.5" + } +} diff --git a/backend/node_modules/send/node_modules/ms/readme.md b/backend/node_modules/send/node_modules/ms/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..0fc1abb3b8e30a3ab97023d243127c75b1b3a4d7 --- /dev/null +++ b/backend/node_modules/send/node_modules/ms/readme.md @@ -0,0 +1,59 @@ +# ms + +![CI](https://github.com/vercel/ms/workflows/CI/badge.svg) + +Use this package to easily convert various time formats to milliseconds. + +## Examples + +```js +ms('2 days') // 172800000 +ms('1d') // 86400000 +ms('10h') // 36000000 +ms('2.5 hrs') // 9000000 +ms('2h') // 7200000 +ms('1m') // 60000 +ms('5s') // 5000 +ms('1y') // 31557600000 +ms('100') // 100 +ms('-3 days') // -259200000 +ms('-1h') // -3600000 +ms('-200') // -200 +``` + +### Convert from Milliseconds + +```js +ms(60000) // "1m" +ms(2 * 60000) // "2m" +ms(-3 * 60000) // "-3m" +ms(ms('10 hours')) // "10h" +``` + +### Time Format Written-Out + +```js +ms(60000, { long: true }) // "1 minute" +ms(2 * 60000, { long: true }) // "2 minutes" +ms(-3 * 60000, { long: true }) // "-3 minutes" +ms(ms('10 hours'), { long: true }) // "10 hours" +``` + +## Features + +- Works both in [Node.js](https://nodejs.org) and in the browser +- If a number is supplied to `ms`, a string with a unit is returned +- If a string that contains the number is supplied, it returns it as a number (e.g.: it returns `100` for `'100'`) +- If you pass a string with a number and a valid unit, the number of equivalent milliseconds is returned + +## Related Packages + +- [ms.macro](https://github.com/knpwrs/ms.macro) - Run `ms` as a macro at build-time. + +## Caught a Bug? + +1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device +2. Link the package to the global module directory: `npm link` +3. Within the module you want to test your local development instance of ms, just link it to the dependencies: `npm link ms`. Instead of the default one from npm, Node.js will now use your clone of ms! + +As always, you can run the tests using: `npm test` diff --git a/backend/node_modules/send/package.json b/backend/node_modules/send/package.json new file mode 100644 index 0000000000000000000000000000000000000000..7f269d515c8bf4d94510578600a9bf9fc9f43fd3 --- /dev/null +++ b/backend/node_modules/send/package.json @@ -0,0 +1,62 @@ +{ + "name": "send", + "description": "Better streaming static file server with Range and conditional-GET support", + "version": "0.18.0", + "author": "TJ Holowaychuk ", + "contributors": [ + "Douglas Christopher Wilson ", + "James Wyatt Cready ", + "Jesús Leganés Combarro " + ], + "license": "MIT", + "repository": "pillarjs/send", + "keywords": [ + "static", + "file", + "server" + ], + "dependencies": { + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "fresh": "0.5.2", + "http-errors": "2.0.0", + "mime": "1.6.0", + "ms": "2.1.3", + "on-finished": "2.4.1", + "range-parser": "~1.2.1", + "statuses": "2.0.1" + }, + "devDependencies": { + "after": "0.8.2", + "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": "5.2.0", + "eslint-plugin-standard": "4.1.0", + "mocha": "9.2.2", + "nyc": "15.1.0", + "supertest": "6.2.2" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "SECURITY.md", + "index.js" + ], + "engines": { + "node": ">= 0.8.0" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --check-leaks --reporter spec --bail", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test" + } +} diff --git a/backend/node_modules/serve-static/HISTORY.md b/backend/node_modules/serve-static/HISTORY.md new file mode 100644 index 0000000000000000000000000000000000000000..6b58456353c6160bba320b1852b0be55e691bb41 --- /dev/null +++ b/backend/node_modules/serve-static/HISTORY.md @@ -0,0 +1,471 @@ +1.15.0 / 2022-03-24 +=================== + + * deps: send@0.18.0 + - Fix emitted 416 error missing headers property + - Limit the headers removed for 304 response + - deps: depd@2.0.0 + - deps: destroy@1.2.0 + - deps: http-errors@2.0.0 + - deps: on-finished@2.4.1 + - deps: statuses@2.0.1 + +1.14.2 / 2021-12-15 +=================== + + * deps: send@0.17.2 + - deps: http-errors@1.8.1 + - deps: ms@2.1.3 + - pref: ignore empty http tokens + +1.14.1 / 2019-05-10 +=================== + + * Set stricter CSP header in redirect response + * deps: send@0.17.1 + - deps: range-parser@~1.2.1 + +1.14.0 / 2019-05-07 +=================== + + * deps: parseurl@~1.3.3 + * deps: send@0.17.0 + - deps: http-errors@~1.7.2 + - deps: mime@1.6.0 + - deps: ms@2.1.1 + - deps: statuses@~1.5.0 + - perf: remove redundant `path.normalize` call + +1.13.2 / 2018-02-07 +=================== + + * Fix incorrect end tag in redirects + * deps: encodeurl@~1.0.2 + - Fix encoding `%` as last character + * deps: send@0.16.2 + - deps: depd@~1.1.2 + - deps: encodeurl@~1.0.2 + - deps: statuses@~1.4.0 + +1.13.1 / 2017-09-29 +=================== + + * Fix regression when `root` is incorrectly set to a file + * deps: send@0.16.1 + +1.13.0 / 2017-09-27 +=================== + + * deps: send@0.16.0 + - Add 70 new types for file extensions + - Add `immutable` option + - Fix missing `` in default error & redirects + - Set charset as "UTF-8" for .js and .json + - Use instance methods on steam to check for listeners + - deps: mime@1.4.1 + - perf: improve path validation speed + +1.12.6 / 2017-09-22 +=================== + + * deps: send@0.15.6 + - deps: debug@2.6.9 + - perf: improve `If-Match` token parsing + * perf: improve slash collapsing + +1.12.5 / 2017-09-21 +=================== + + * deps: parseurl@~1.3.2 + - perf: reduce overhead for full URLs + - perf: unroll the "fast-path" `RegExp` + * deps: send@0.15.5 + - Fix handling of modified headers with invalid dates + - deps: etag@~1.8.1 + - deps: fresh@0.5.2 + +1.12.4 / 2017-08-05 +=================== + + * deps: send@0.15.4 + - deps: debug@2.6.8 + - deps: depd@~1.1.1 + - deps: http-errors@~1.6.2 + +1.12.3 / 2017-05-16 +=================== + + * deps: send@0.15.3 + - deps: debug@2.6.7 + +1.12.2 / 2017-04-26 +=================== + + * deps: send@0.15.2 + - deps: debug@2.6.4 + +1.12.1 / 2017-03-04 +=================== + + * deps: send@0.15.1 + - Fix issue when `Date.parse` does not return `NaN` on invalid date + - Fix strict violation in broken environments + +1.12.0 / 2017-02-25 +=================== + + * Send complete HTML document in redirect response + * Set default CSP header in redirect response + * deps: send@0.15.0 + - Fix false detection of `no-cache` request directive + - Fix incorrect result when `If-None-Match` has both `*` and ETags + - Fix weak `ETag` matching to match spec + - Remove usage of `res._headers` private field + - Support `If-Match` and `If-Unmodified-Since` headers + - Use `res.getHeaderNames()` when available + - Use `res.headersSent` when available + - deps: debug@2.6.1 + - deps: etag@~1.8.0 + - deps: fresh@0.5.0 + - deps: http-errors@~1.6.1 + +1.11.2 / 2017-01-23 +=================== + + * deps: send@0.14.2 + - deps: http-errors@~1.5.1 + - deps: ms@0.7.2 + - deps: statuses@~1.3.1 + +1.11.1 / 2016-06-10 +=================== + + * Fix redirect error when `req.url` contains raw non-URL characters + * deps: send@0.14.1 + +1.11.0 / 2016-06-07 +=================== + + * Use status code 301 for redirects + * deps: send@0.14.0 + - Add `acceptRanges` option + - Add `cacheControl` option + - Attempt to combine multiple ranges into single range + - Correctly inherit from `Stream` class + - Fix `Content-Range` header in 416 responses when using `start`/`end` options + - Fix `Content-Range` header missing from default 416 responses + - Ignore non-byte `Range` headers + - deps: http-errors@~1.5.0 + - deps: range-parser@~1.2.0 + - deps: statuses@~1.3.0 + - perf: remove argument reassignment + +1.10.3 / 2016-05-30 +=================== + + * deps: send@0.13.2 + - Fix invalid `Content-Type` header when `send.mime.default_type` unset + +1.10.2 / 2016-01-19 +=================== + + * deps: parseurl@~1.3.1 + - perf: enable strict mode + +1.10.1 / 2016-01-16 +=================== + + * deps: escape-html@~1.0.3 + - perf: enable strict mode + - perf: optimize string replacement + - perf: use faster string coercion + * deps: send@0.13.1 + - deps: depd@~1.1.0 + - deps: destroy@~1.0.4 + - deps: escape-html@~1.0.3 + - deps: range-parser@~1.0.3 + +1.10.0 / 2015-06-17 +=================== + + * Add `fallthrough` option + - Allows declaring this middleware is the final destination + - Provides better integration with Express patterns + * Fix reading options from options prototype + * Improve the default redirect response headers + * deps: escape-html@1.0.2 + * deps: send@0.13.0 + - Allow Node.js HTTP server to set `Date` response header + - Fix incorrectly removing `Content-Location` on 304 response + - Improve the default redirect response headers + - Send appropriate headers on default error response + - Use `http-errors` for standard emitted errors + - Use `statuses` instead of `http` module for status messages + - deps: escape-html@1.0.2 + - deps: etag@~1.7.0 + - deps: fresh@0.3.0 + - deps: on-finished@~2.3.0 + - perf: enable strict mode + - perf: remove unnecessary array allocations + * perf: enable strict mode + * perf: remove argument reassignment + +1.9.3 / 2015-05-14 +================== + + * deps: send@0.12.3 + - deps: debug@~2.2.0 + - deps: depd@~1.0.1 + - deps: etag@~1.6.0 + - deps: ms@0.7.1 + - deps: on-finished@~2.2.1 + +1.9.2 / 2015-03-14 +================== + + * deps: send@0.12.2 + - Throw errors early for invalid `extensions` or `index` options + - deps: debug@~2.1.3 + +1.9.1 / 2015-02-17 +================== + + * deps: send@0.12.1 + - Fix regression sending zero-length files + +1.9.0 / 2015-02-16 +================== + + * deps: send@0.12.0 + - Always read the stat size from the file + - Fix mutating passed-in `options` + - deps: mime@1.3.4 + +1.8.1 / 2015-01-20 +================== + + * Fix redirect loop in Node.js 0.11.14 + * deps: send@0.11.1 + - Fix root path disclosure + +1.8.0 / 2015-01-05 +================== + + * deps: send@0.11.0 + - deps: debug@~2.1.1 + - deps: etag@~1.5.1 + - deps: ms@0.7.0 + - deps: on-finished@~2.2.0 + +1.7.2 / 2015-01-02 +================== + + * Fix potential open redirect when mounted at root + +1.7.1 / 2014-10-22 +================== + + * deps: send@0.10.1 + - deps: on-finished@~2.1.1 + +1.7.0 / 2014-10-15 +================== + + * deps: send@0.10.0 + - deps: debug@~2.1.0 + - deps: depd@~1.0.0 + - deps: etag@~1.5.0 + +1.6.5 / 2015-02-04 +================== + + * Fix potential open redirect when mounted at root + - Back-ported from v1.7.2 + +1.6.4 / 2014-10-08 +================== + + * Fix redirect loop when index file serving disabled + +1.6.3 / 2014-09-24 +================== + + * deps: send@0.9.3 + - deps: etag@~1.4.0 + +1.6.2 / 2014-09-15 +================== + + * deps: send@0.9.2 + - deps: depd@0.4.5 + - deps: etag@~1.3.1 + - deps: range-parser@~1.0.2 + +1.6.1 / 2014-09-07 +================== + + * deps: send@0.9.1 + - deps: fresh@0.2.4 + +1.6.0 / 2014-09-07 +================== + + * deps: send@0.9.0 + - Add `lastModified` option + - Use `etag` to generate `ETag` header + - deps: debug@~2.0.0 + +1.5.4 / 2014-09-04 +================== + + * deps: send@0.8.5 + - Fix a path traversal issue when using `root` + - Fix malicious path detection for empty string path + +1.5.3 / 2014-08-17 +================== + + * deps: send@0.8.3 + +1.5.2 / 2014-08-14 +================== + + * deps: send@0.8.2 + - Work around `fd` leak in Node.js 0.10 for `fs.ReadStream` + +1.5.1 / 2014-08-09 +================== + + * Fix parsing of weird `req.originalUrl` values + * deps: parseurl@~1.3.0 + * deps: utils-merge@1.0.0 + +1.5.0 / 2014-08-05 +================== + + * deps: send@0.8.1 + - Add `extensions` option + +1.4.4 / 2014-08-04 +================== + + * deps: send@0.7.4 + - Fix serving index files without root dir + +1.4.3 / 2014-07-29 +================== + + * deps: send@0.7.3 + - Fix incorrect 403 on Windows and Node.js 0.11 + +1.4.2 / 2014-07-27 +================== + + * deps: send@0.7.2 + - deps: depd@0.4.4 + +1.4.1 / 2014-07-26 +================== + + * deps: send@0.7.1 + - deps: depd@0.4.3 + +1.4.0 / 2014-07-21 +================== + + * deps: parseurl@~1.2.0 + - Cache URLs based on original value + - Remove no-longer-needed URL mis-parse work-around + - Simplify the "fast-path" `RegExp` + * deps: send@0.7.0 + - Add `dotfiles` option + - deps: debug@1.0.4 + - deps: depd@0.4.2 + +1.3.2 / 2014-07-11 +================== + + * deps: send@0.6.0 + - Cap `maxAge` value to 1 year + - deps: debug@1.0.3 + +1.3.1 / 2014-07-09 +================== + + * deps: parseurl@~1.1.3 + - faster parsing of href-only URLs + +1.3.0 / 2014-06-28 +================== + + * Add `setHeaders` option + * Include HTML link in redirect response + * deps: send@0.5.0 + - Accept string for `maxAge` (converted by `ms`) + +1.2.3 / 2014-06-11 +================== + + * deps: send@0.4.3 + - Do not throw un-catchable error on file open race condition + - Use `escape-html` for HTML escaping + - deps: debug@1.0.2 + - deps: finished@1.2.2 + - deps: fresh@0.2.2 + +1.2.2 / 2014-06-09 +================== + + * deps: send@0.4.2 + - fix "event emitter leak" warnings + - deps: debug@1.0.1 + - deps: finished@1.2.1 + +1.2.1 / 2014-06-02 +================== + + * use `escape-html` for escaping + * deps: send@0.4.1 + - Send `max-age` in `Cache-Control` in correct format + +1.2.0 / 2014-05-29 +================== + + * deps: send@0.4.0 + - Calculate ETag with md5 for reduced collisions + - Fix wrong behavior when index file matches directory + - Ignore stream errors after request ends + - Skip directories in index file search + - deps: debug@0.8.1 + +1.1.0 / 2014-04-24 +================== + + * Accept options directly to `send` module + * deps: send@0.3.0 + +1.0.4 / 2014-04-07 +================== + + * Resolve relative paths at middleware setup + * Use parseurl to parse the URL from request + +1.0.3 / 2014-03-20 +================== + + * Do not rely on connect-like environments + +1.0.2 / 2014-03-06 +================== + + * deps: send@0.2.0 + +1.0.1 / 2014-03-05 +================== + + * Add mime export for back-compat + +1.0.0 / 2014-03-05 +================== + + * Genesis from `connect` diff --git a/backend/node_modules/serve-static/LICENSE b/backend/node_modules/serve-static/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..cbe62e8e7f20b6aa70e4d138b1503837ae4e5f95 --- /dev/null +++ b/backend/node_modules/serve-static/LICENSE @@ -0,0 +1,25 @@ +(The MIT License) + +Copyright (c) 2010 Sencha Inc. +Copyright (c) 2011 LearnBoost +Copyright (c) 2011 TJ Holowaychuk +Copyright (c) 2014-2016 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/backend/node_modules/serve-static/README.md b/backend/node_modules/serve-static/README.md new file mode 100644 index 0000000000000000000000000000000000000000..262d944ab7510ecb39b47055189a92793c94aa26 --- /dev/null +++ b/backend/node_modules/serve-static/README.md @@ -0,0 +1,257 @@ +# serve-static + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Linux Build][github-actions-ci-image]][github-actions-ci-url] +[![Windows Build][appveyor-image]][appveyor-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +## Install + +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 serve-static +``` + +## API + +```js +var serveStatic = require('serve-static') +``` + +### serveStatic(root, options) + +Create a new middleware function to serve files from within a given root +directory. The file to serve will be determined by combining `req.url` +with the provided root directory. When a file is not found, instead of +sending a 404 response, this module will instead call `next()` to move on +to the next middleware, allowing for stacking and fall-backs. + +#### Options + +##### acceptRanges + +Enable or disable accepting ranged requests, defaults to true. +Disabling this will not send `Accept-Ranges` and ignore the contents +of the `Range` request header. + +##### cacheControl + +Enable or disable setting `Cache-Control` response header, defaults to +true. Disabling this will ignore the `immutable` and `maxAge` options. + +##### dotfiles + + Set how "dotfiles" are treated when encountered. A dotfile is a file +or directory that begins with a dot ("."). Note this check is done on +the path itself without checking if the path actually exists on the +disk. If `root` is specified, only the dotfiles above the root are +checked (i.e. the root itself can be within a dotfile when set +to "deny"). + + - `'allow'` No special treatment for dotfiles. + - `'deny'` Deny a request for a dotfile and 403/`next()`. + - `'ignore'` Pretend like the dotfile does not exist and 404/`next()`. + +The default value is similar to `'ignore'`, with the exception that this +default will not ignore the files within a directory that begins with a dot. + +##### etag + +Enable or disable etag generation, defaults to true. + +##### extensions + +Set file extension fallbacks. When set, if a file is not found, the given +extensions will be added to the file name and search for. The first that +exists will be served. Example: `['html', 'htm']`. + +The default value is `false`. + +##### fallthrough + +Set the middleware to have client errors fall-through as just unhandled +requests, otherwise forward a client error. The difference is that client +errors like a bad request or a request to a non-existent file will cause +this middleware to simply `next()` to your next middleware when this value +is `true`. When this value is `false`, these errors (even 404s), will invoke +`next(err)`. + +Typically `true` is desired such that multiple physical directories can be +mapped to the same web address or for routes to fill in non-existent files. + +The value `false` can be used if this middleware is mounted at a path that +is designed to be strictly a single file system directory, which allows for +short-circuiting 404s for less overhead. This middleware will also reply to +all methods. + +The default value is `true`. + +##### immutable + +Enable or disable the `immutable` directive in the `Cache-Control` response +header, defaults to `false`. If set to `true`, the `maxAge` option should +also be specified to enable caching. The `immutable` directive will prevent +supported clients from making conditional requests during the life of the +`maxAge` option to check if the file has changed. + +##### index + +By default this module will send "index.html" files in response to a request +on a directory. To disable this set `false` or to supply a new index pass a +string or an array in preferred order. + +##### lastModified + +Enable or disable `Last-Modified` header, defaults to true. Uses the file +system's last modified value. + +##### maxAge + +Provide a max-age in milliseconds for http caching, defaults to 0. This +can also be a string accepted by the [ms](https://www.npmjs.org/package/ms#readme) +module. + +##### redirect + +Redirect to trailing "/" when the pathname is a dir. Defaults to `true`. + +##### setHeaders + +Function to set custom headers on response. Alterations to the headers need to +occur synchronously. The function is called as `fn(res, path, stat)`, where +the arguments are: + + - `res` the response object + - `path` the file path that is being sent + - `stat` the stat object of the file that is being sent + +## Examples + +### Serve files with vanilla node.js http server + +```js +var finalhandler = require('finalhandler') +var http = require('http') +var serveStatic = require('serve-static') + +// Serve up public/ftp folder +var serve = serveStatic('public/ftp', { index: ['index.html', 'index.htm'] }) + +// Create server +var server = http.createServer(function onRequest (req, res) { + serve(req, res, finalhandler(req, res)) +}) + +// Listen +server.listen(3000) +``` + +### Serve all files as downloads + +```js +var contentDisposition = require('content-disposition') +var finalhandler = require('finalhandler') +var http = require('http') +var serveStatic = require('serve-static') + +// Serve up public/ftp folder +var serve = serveStatic('public/ftp', { + index: false, + setHeaders: setHeaders +}) + +// Set header to force download +function setHeaders (res, path) { + res.setHeader('Content-Disposition', contentDisposition(path)) +} + +// Create server +var server = http.createServer(function onRequest (req, res) { + serve(req, res, finalhandler(req, res)) +}) + +// Listen +server.listen(3000) +``` + +### Serving using express + +#### Simple + +This is a simple example of using Express. + +```js +var express = require('express') +var serveStatic = require('serve-static') + +var app = express() + +app.use(serveStatic('public/ftp', { index: ['default.html', 'default.htm'] })) +app.listen(3000) +``` + +#### Multiple roots + +This example shows a simple way to search through multiple directories. +Files are searched for in `public-optimized/` first, then `public/` second +as a fallback. + +```js +var express = require('express') +var path = require('path') +var serveStatic = require('serve-static') + +var app = express() + +app.use(serveStatic(path.join(__dirname, 'public-optimized'))) +app.use(serveStatic(path.join(__dirname, 'public'))) +app.listen(3000) +``` + +#### Different settings for paths + +This example shows how to set a different max age depending on the served +file type. In this example, HTML files are not cached, while everything else +is for 1 day. + +```js +var express = require('express') +var path = require('path') +var serveStatic = require('serve-static') + +var app = express() + +app.use(serveStatic(path.join(__dirname, 'public'), { + maxAge: '1d', + setHeaders: setCustomCacheControl +})) + +app.listen(3000) + +function setCustomCacheControl (res, path) { + if (serveStatic.mime.lookup(path) === 'text/html') { + // Custom Cache-Control for HTML files + res.setHeader('Cache-Control', 'public, max-age=0') + } +} +``` + +## License + +[MIT](LICENSE) + +[appveyor-image]: https://badgen.net/appveyor/ci/dougwilson/serve-static/master?label=windows +[appveyor-url]: https://ci.appveyor.com/project/dougwilson/serve-static +[coveralls-image]: https://badgen.net/coveralls/c/github/expressjs/serve-static/master +[coveralls-url]: https://coveralls.io/r/expressjs/serve-static?branch=master +[github-actions-ci-image]: https://badgen.net/github/checks/expressjs/serve-static/master?label=linux +[github-actions-ci-url]: https://github.com/expressjs/serve-static/actions/workflows/ci.yml +[node-image]: https://badgen.net/npm/node/serve-static +[node-url]: https://nodejs.org/en/download/ +[npm-downloads-image]: https://badgen.net/npm/dm/serve-static +[npm-url]: https://npmjs.org/package/serve-static +[npm-version-image]: https://badgen.net/npm/v/serve-static diff --git a/backend/node_modules/serve-static/index.js b/backend/node_modules/serve-static/index.js new file mode 100644 index 0000000000000000000000000000000000000000..b7d3984c447992f39583ddf4d8ecf01ffbb5b6db --- /dev/null +++ b/backend/node_modules/serve-static/index.js @@ -0,0 +1,210 @@ +/*! + * serve-static + * Copyright(c) 2010 Sencha Inc. + * Copyright(c) 2011 TJ Holowaychuk + * Copyright(c) 2014-2016 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var encodeUrl = require('encodeurl') +var escapeHtml = require('escape-html') +var parseUrl = require('parseurl') +var resolve = require('path').resolve +var send = require('send') +var url = require('url') + +/** + * Module exports. + * @public + */ + +module.exports = serveStatic +module.exports.mime = send.mime + +/** + * @param {string} root + * @param {object} [options] + * @return {function} + * @public + */ + +function serveStatic (root, options) { + if (!root) { + throw new TypeError('root path required') + } + + if (typeof root !== 'string') { + throw new TypeError('root path must be a string') + } + + // copy options object + var opts = Object.create(options || null) + + // fall-though + var fallthrough = opts.fallthrough !== false + + // default redirect + var redirect = opts.redirect !== false + + // headers listener + var setHeaders = opts.setHeaders + + if (setHeaders && typeof setHeaders !== 'function') { + throw new TypeError('option setHeaders must be function') + } + + // setup options for send + opts.maxage = opts.maxage || opts.maxAge || 0 + opts.root = resolve(root) + + // construct directory listener + var onDirectory = redirect + ? createRedirectDirectoryListener() + : createNotFoundDirectoryListener() + + return function serveStatic (req, res, next) { + if (req.method !== 'GET' && req.method !== 'HEAD') { + if (fallthrough) { + return next() + } + + // method not allowed + res.statusCode = 405 + res.setHeader('Allow', 'GET, HEAD') + res.setHeader('Content-Length', '0') + res.end() + return + } + + var forwardError = !fallthrough + var originalUrl = parseUrl.original(req) + var path = parseUrl(req).pathname + + // make sure redirect occurs at mount + if (path === '/' && originalUrl.pathname.substr(-1) !== '/') { + path = '' + } + + // create send stream + var stream = send(req, path, opts) + + // add directory handler + stream.on('directory', onDirectory) + + // add headers listener + if (setHeaders) { + stream.on('headers', setHeaders) + } + + // add file listener for fallthrough + if (fallthrough) { + stream.on('file', function onFile () { + // once file is determined, always forward error + forwardError = true + }) + } + + // forward errors + stream.on('error', function error (err) { + if (forwardError || !(err.statusCode < 500)) { + next(err) + return + } + + next() + }) + + // pipe + stream.pipe(res) + } +} + +/** + * Collapse all leading slashes into a single slash + * @private + */ +function collapseLeadingSlashes (str) { + for (var i = 0; i < str.length; i++) { + if (str.charCodeAt(i) !== 0x2f /* / */) { + break + } + } + + return i > 1 + ? '/' + str.substr(i) + : str +} + +/** + * Create a minimal HTML document. + * + * @param {string} title + * @param {string} body + * @private + */ + +function createHtmlDocument (title, body) { + return '\n' + + '\n' + + '\n' + + '\n' + + '' + title + '\n' + + '\n' + + '\n' + + '
' + body + '
\n' + + '\n' + + '\n' +} + +/** + * Create a directory listener that just 404s. + * @private + */ + +function createNotFoundDirectoryListener () { + return function notFound () { + this.error(404) + } +} + +/** + * Create a directory listener that performs a redirect. + * @private + */ + +function createRedirectDirectoryListener () { + return function redirect (res) { + if (this.hasTrailingSlash()) { + this.error(404) + return + } + + // get original URL + var originalUrl = parseUrl.original(this.req) + + // append trailing slash + originalUrl.path = null + originalUrl.pathname = collapseLeadingSlashes(originalUrl.pathname + '/') + + // reformat the URL + var loc = encodeUrl(url.format(originalUrl)) + var doc = createHtmlDocument('Redirecting', 'Redirecting to ' + + escapeHtml(loc) + '') + + // send redirect response + res.statusCode = 301 + res.setHeader('Content-Type', 'text/html; charset=UTF-8') + res.setHeader('Content-Length', Buffer.byteLength(doc)) + res.setHeader('Content-Security-Policy', "default-src 'none'") + res.setHeader('X-Content-Type-Options', 'nosniff') + res.setHeader('Location', loc) + res.end(doc) + } +} diff --git a/backend/node_modules/serve-static/package.json b/backend/node_modules/serve-static/package.json new file mode 100644 index 0000000000000000000000000000000000000000..9d935f5d8b3b562d6dd2e7adc21f03c35743e9de --- /dev/null +++ b/backend/node_modules/serve-static/package.json @@ -0,0 +1,42 @@ +{ + "name": "serve-static", + "description": "Serve static files", + "version": "1.15.0", + "author": "Douglas Christopher Wilson ", + "license": "MIT", + "repository": "expressjs/serve-static", + "dependencies": { + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "parseurl": "~1.3.3", + "send": "0.18.0" + }, + "devDependencies": { + "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": "5.2.0", + "eslint-plugin-standard": "4.1.0", + "mocha": "9.2.2", + "nyc": "15.1.0", + "safe-buffer": "5.2.1", + "supertest": "6.2.2" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "index.js" + ], + "engines": { + "node": ">= 0.8.0" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-ci": "nyc --reporter=lcov --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/backend/node_modules/set-function-length/.eslintrc b/backend/node_modules/set-function-length/.eslintrc new file mode 100644 index 0000000000000000000000000000000000000000..7cff50717edb2b4867273c28e147ec570bfa8f89 --- /dev/null +++ b/backend/node_modules/set-function-length/.eslintrc @@ -0,0 +1,27 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "id-length": "off", + "new-cap": ["error", { + "capIsNewExceptions": [ + "GetIntrinsic" + ], + }], + "no-extra-parens": "off", + }, + + "overrides": [ + { + "files": ["test/**/*.js"], + "rules": { + "id-length": "off", + "max-lines-per-function": "off", + "multiline-comment-style": "off", + "no-empty-function": "off", + }, + }, + ], +} diff --git a/backend/node_modules/set-function-length/.github/FUNDING.yml b/backend/node_modules/set-function-length/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..92feb6f9bc4063b604bf3a2790852792a03902fb --- /dev/null +++ b/backend/node_modules/set-function-length/.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/set-function-name +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 a single custom sponsorship URL diff --git a/backend/node_modules/set-function-length/.nycrc b/backend/node_modules/set-function-length/.nycrc new file mode 100644 index 0000000000000000000000000000000000000000..1826526e091b89c896e7099ccd891db79165e329 --- /dev/null +++ b/backend/node_modules/set-function-length/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "test" + ] +} diff --git a/backend/node_modules/set-function-length/CHANGELOG.md b/backend/node_modules/set-function-length/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..bac439d8783a8963dd44fd5ad74384a46ef14dc1 --- /dev/null +++ b/backend/node_modules/set-function-length/CHANGELOG.md @@ -0,0 +1,70 @@ +# 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.2.2](https://github.com/ljharb/set-function-length/compare/v1.2.1...v1.2.2) - 2024-03-09 + +### Commits + +- [types] use shared config [`027032f`](https://github.com/ljharb/set-function-length/commit/027032fe9cc439644a07248ea6a8d813fcc767cb) +- [actions] remove redundant finisher; use reusable workflow [`1fd4fb1`](https://github.com/ljharb/set-function-length/commit/1fd4fb1c58bd5170f0dcff7e320077c0aa2ffdeb) +- [types] use a handwritten d.ts file instead of emit [`01b9761`](https://github.com/ljharb/set-function-length/commit/01b9761742c95e1118e8c2d153ce2ae43d9731aa) +- [Deps] update `define-data-property`, `get-intrinsic`, `has-property-descriptors` [`bee8eaf`](https://github.com/ljharb/set-function-length/commit/bee8eaf7749f325357ade85cffeaeef679e513d4) +- [Dev Deps] update `call-bind`, `tape` [`5dae579`](https://github.com/ljharb/set-function-length/commit/5dae579fdc3aab91b14ebb58f9c19ee3f509d434) +- [Tests] use `@arethetypeswrong/cli` [`7e22425`](https://github.com/ljharb/set-function-length/commit/7e22425d15957fd3d6da0b6bca4afc0c8d255d2d) + +## [v1.2.1](https://github.com/ljharb/set-function-length/compare/v1.2.0...v1.2.1) - 2024-02-06 + +### Commits + +- [Dev Deps] update `call-bind`, `tape`, `typescript` [`d9a4601`](https://github.com/ljharb/set-function-length/commit/d9a460199c4c1fa37da9ebe055e2c884128f0738) +- [Deps] update `define-data-property`, `get-intrinsic` [`38d39ae`](https://github.com/ljharb/set-function-length/commit/38d39aed13a757ed36211d5b0437b88485090c6b) +- [Refactor] use `es-errors`, so things that only need those do not need `get-intrinsic` [`b4bfe5a`](https://github.com/ljharb/set-function-length/commit/b4bfe5ae0953b906d55b85f867eca5e7f673ebf4) + +## [v1.2.0](https://github.com/ljharb/set-function-length/compare/v1.1.1...v1.2.0) - 2024-01-14 + +### Commits + +- [New] add types [`f6d9088`](https://github.com/ljharb/set-function-length/commit/f6d9088b9283a3112b21c6776e8bef6d1f30558a) +- [Fix] ensure `env` properties are always booleans [`0c42f84`](https://github.com/ljharb/set-function-length/commit/0c42f84979086389b3229e1b4272697fd352275a) +- [Dev Deps] update `aud`, `call-bind`, `npmignore`, `tape` [`2b75f75`](https://github.com/ljharb/set-function-length/commit/2b75f75468093a4bb8ce8ca989b2edd2e80d95d1) +- [Deps] update `get-intrinsic`, `has-property-descriptors` [`19bf0fc`](https://github.com/ljharb/set-function-length/commit/19bf0fc4ffaa5ad425acbfa150516be9f3b6263a) +- [meta] add `sideEffects` flag [`8bb9b78`](https://github.com/ljharb/set-function-length/commit/8bb9b78c11c621123f725c9470222f43466c01d0) + +## [v1.1.1](https://github.com/ljharb/set-function-length/compare/v1.1.0...v1.1.1) - 2023-10-19 + +### Fixed + +- [Fix] move `define-data-property` to runtime deps [`#2`](https://github.com/ljharb/set-function-length/issues/2) + +### Commits + +- [Dev Deps] update `object-inspect`; add missing `call-bind` [`5aecf79`](https://github.com/ljharb/set-function-length/commit/5aecf79e7d6400957a5d9bd9ac20d4528908ca18) + +## [v1.1.0](https://github.com/ljharb/set-function-length/compare/v1.0.1...v1.1.0) - 2023-10-13 + +### Commits + +- [New] add `env` entry point [`475c87a`](https://github.com/ljharb/set-function-length/commit/475c87aa2f59b700aaed589d980624ec596acdcb) +- [Tests] add coverage with `nyc` [`14f0bf8`](https://github.com/ljharb/set-function-length/commit/14f0bf8c145ae60bf14a026420a06bb7be132c36) +- [eslint] fix linting failure [`fb516f9`](https://github.com/ljharb/set-function-length/commit/fb516f93c664057138c53559ef63c8622a093335) +- [Deps] update `define-data-property` [`d727e7c`](https://github.com/ljharb/set-function-length/commit/d727e7c6c9a40d7bf26797694e500ea68741feea) + +## [v1.0.1](https://github.com/ljharb/set-function-length/compare/v1.0.0...v1.0.1) - 2023-10-12 + +### Commits + +- [Refactor] use `get-intrinsic`, since it‘s in the dep graph anyways [`278a954`](https://github.com/ljharb/set-function-length/commit/278a954a06cd849051c569ff7aee56df6798933e) +- [meta] add `exports` [`72acfe5`](https://github.com/ljharb/set-function-length/commit/72acfe5a0310071fb205a72caba5ecbab24336a0) + +## v1.0.0 - 2023-10-12 + +### Commits + +- Initial implementation, tests, readme [`fce14e1`](https://github.com/ljharb/set-function-length/commit/fce14e17586460e4f294405173be72b6ffdf7e5f) +- Initial commit [`ca7ba85`](https://github.com/ljharb/set-function-length/commit/ca7ba857c7c283f9d26e21f14e71cd388f2cb722) +- npm init [`6a7e493`](https://github.com/ljharb/set-function-length/commit/6a7e493927736cebcaf5c1a84e69b8e6b7b744d8) +- Only apps should have lockfiles [`d2bf6c4`](https://github.com/ljharb/set-function-length/commit/d2bf6c43de8a51b02a0aa53e8d62cb50c4a2b0da) diff --git a/backend/node_modules/set-function-length/LICENSE b/backend/node_modules/set-function-length/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..0314929078de8a733a0af9c8ba5bc00aca094cc9 --- /dev/null +++ b/backend/node_modules/set-function-length/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Jordan Harband and 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/backend/node_modules/set-function-length/README.md b/backend/node_modules/set-function-length/README.md new file mode 100644 index 0000000000000000000000000000000000000000..15e3ac4b1ef6ada3bc5929bf990119bc079a9be3 --- /dev/null +++ b/backend/node_modules/set-function-length/README.md @@ -0,0 +1,56 @@ +# set-function-length [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Set a function’s length. + +Arguments: + - `fn`: the function + - `length`: the new length. Must be an integer between 0 and 2**32. + - `loose`: Optional. If true, and the length fails to be set, do not throw. Default false. + +Returns `fn`. + +## Usage + +```javascript +var setFunctionLength = require('set-function-length'); +var assert = require('assert'); + +function zero() {} +function one(_) {} +function two(_, __) {} + +assert.equal(zero.length, 0); +assert.equal(one.length, 1); +assert.equal(two.length, 2); + +assert.equal(setFunctionLength(zero, 10), zero); +assert.equal(setFunctionLength(one, 11), one); +assert.equal(setFunctionLength(two, 12), two); + +assert.equal(zero.length, 10); +assert.equal(one.length, 11); +assert.equal(two.length, 12); +``` + +[package-url]: https://npmjs.org/package/set-function-length +[npm-version-svg]: https://versionbadg.es/ljharb/set-function-length.svg +[deps-svg]: https://david-dm.org/ljharb/set-function-length.svg +[deps-url]: https://david-dm.org/ljharb/set-function-length +[dev-deps-svg]: https://david-dm.org/ljharb/set-function-length/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/set-function-length#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/set-function-length.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/set-function-length.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/set-function-length.svg +[downloads-url]: https://npm-stat.com/charts.html?package=set-function-length +[codecov-image]: https://codecov.io/gh/ljharb/set-function-length/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/set-function-length/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/set-function-length +[actions-url]: https://github.com/ljharb/set-function-length/actions diff --git a/backend/node_modules/set-function-length/env.d.ts b/backend/node_modules/set-function-length/env.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..970ea535b697b0caeebf85847060a90883a852df --- /dev/null +++ b/backend/node_modules/set-function-length/env.d.ts @@ -0,0 +1,9 @@ +declare const env: { + __proto__: null, + boundFnsHaveConfigurableLengths: boolean; + boundFnsHaveWritableLengths: boolean; + functionsHaveConfigurableLengths: boolean; + functionsHaveWritableLengths: boolean; +}; + +export = env; \ No newline at end of file diff --git a/backend/node_modules/set-function-length/env.js b/backend/node_modules/set-function-length/env.js new file mode 100644 index 0000000000000000000000000000000000000000..d9b0a2997b5998902ac7963f847964987c3cd6b5 --- /dev/null +++ b/backend/node_modules/set-function-length/env.js @@ -0,0 +1,25 @@ +'use strict'; + +var gOPD = require('gopd'); +var bind = require('function-bind'); + +var unbound = gOPD && gOPD(function () {}, 'length'); +// @ts-expect-error ts(2555) TS is overly strict with .call +var bound = gOPD && gOPD(bind.call(function () {}), 'length'); + +var functionsHaveConfigurableLengths = !!(unbound && unbound.configurable); + +var functionsHaveWritableLengths = !!(unbound && unbound.writable); + +var boundFnsHaveConfigurableLengths = !!(bound && bound.configurable); + +var boundFnsHaveWritableLengths = !!(bound && bound.writable); + +/** @type {import('./env')} */ +module.exports = { + __proto__: null, + boundFnsHaveConfigurableLengths: boundFnsHaveConfigurableLengths, + boundFnsHaveWritableLengths: boundFnsHaveWritableLengths, + functionsHaveConfigurableLengths: functionsHaveConfigurableLengths, + functionsHaveWritableLengths: functionsHaveWritableLengths +}; diff --git a/backend/node_modules/set-function-length/index.d.ts b/backend/node_modules/set-function-length/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0451ecd391adfac03186df30945ad1c537b3654c --- /dev/null +++ b/backend/node_modules/set-function-length/index.d.ts @@ -0,0 +1,7 @@ +declare namespace setFunctionLength { + type Func = (...args: unknown[]) => unknown; +} + +declare function setFunctionLength(fn: T, length: number, loose?: boolean): T; + +export = setFunctionLength; \ No newline at end of file diff --git a/backend/node_modules/set-function-length/index.js b/backend/node_modules/set-function-length/index.js new file mode 100644 index 0000000000000000000000000000000000000000..14ce74dae4ca6a2e7a03826b82c81b09e442573b --- /dev/null +++ b/backend/node_modules/set-function-length/index.js @@ -0,0 +1,42 @@ +'use strict'; + +var GetIntrinsic = require('get-intrinsic'); +var define = require('define-data-property'); +var hasDescriptors = require('has-property-descriptors')(); +var gOPD = require('gopd'); + +var $TypeError = require('es-errors/type'); +var $floor = GetIntrinsic('%Math.floor%'); + +/** @type {import('.')} */ +module.exports = function setFunctionLength(fn, length) { + if (typeof fn !== 'function') { + throw new $TypeError('`fn` is not a function'); + } + if (typeof length !== 'number' || length < 0 || length > 0xFFFFFFFF || $floor(length) !== length) { + throw new $TypeError('`length` must be a positive 32-bit integer'); + } + + var loose = arguments.length > 2 && !!arguments[2]; + + var functionLengthIsConfigurable = true; + var functionLengthIsWritable = true; + if ('length' in fn && gOPD) { + var desc = gOPD(fn, 'length'); + if (desc && !desc.configurable) { + functionLengthIsConfigurable = false; + } + if (desc && !desc.writable) { + functionLengthIsWritable = false; + } + } + + if (functionLengthIsConfigurable || functionLengthIsWritable || !loose) { + if (hasDescriptors) { + define(/** @type {Parameters[0]} */ (fn), 'length', length, true, true); + } else { + define(/** @type {Parameters[0]} */ (fn), 'length', length); + } + } + return fn; +}; diff --git a/backend/node_modules/set-function-length/package.json b/backend/node_modules/set-function-length/package.json new file mode 100644 index 0000000000000000000000000000000000000000..f6b88819a6b7375386b3423e6438ebf535354101 --- /dev/null +++ b/backend/node_modules/set-function-length/package.json @@ -0,0 +1,102 @@ +{ + "name": "set-function-length", + "version": "1.2.2", + "description": "Set a function's length property", + "main": "index.js", + "exports": { + ".": "./index.js", + "./env": "./env.js", + "./package.json": "./package.json" + }, + "sideEffects": false, + "directories": { + "test": "test" + }, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "tsc": "tsc -p .", + "posttsc": "attw -P", + "prelint": "evalmd README.md", + "lint": "eslint --ext=js,mjs .", + "postlint": "npm run tsc", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "aud --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/set-function-length.git" + }, + "keywords": [ + "javascript", + "ecmascript", + "set", + "function", + "length", + "function.length" + ], + "author": "Jordan Harband ", + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/set-function-length/issues" + }, + "homepage": "https://github.com/ljharb/set-function-length#readme", + "dependencies": { + "define-data-property": "^1.1.4", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "gopd": "^1.0.1", + "has-property-descriptors": "^1.0.2" + }, + "devDependencies": { + "@arethetypeswrong/cli": "^0.15.1", + "@ljharb/eslint-config": "^21.1.0", + "@ljharb/tsconfig": "^0.1.1", + "@types/call-bind": "^1.0.5", + "@types/define-properties": "^1.1.5", + "@types/es-value-fixtures": "^1.4.4", + "@types/for-each": "^0.3.3", + "@types/function-bind": "^1.1.10", + "@types/gopd": "^1.0.3", + "@types/has-property-descriptors": "^1.0.3", + "@types/object-inspect": "^1.8.4", + "@types/tape": "^5.6.4", + "aud": "^2.0.4", + "auto-changelog": "^2.4.0", + "call-bind": "^1.0.7", + "es-value-fixtures": "^1.4.2", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "for-each": "^0.3.3", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "object-inspect": "^1.13.1", + "safe-publish-latest": "^2.0.0", + "tape": "^5.7.5", + "typescript": "next" + }, + "engines": { + "node": ">= 0.4" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows", + "test" + ] + } +} diff --git a/backend/node_modules/set-function-length/tsconfig.json b/backend/node_modules/set-function-length/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..d9a6668c3ae6be748c78fbd5694053706b3d6942 --- /dev/null +++ b/backend/node_modules/set-function-length/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "@ljharb/tsconfig", + "compilerOptions": { + "target": "es2021", + }, + "exclude": [ + "coverage", + ], +} diff --git a/backend/node_modules/setprototypeof/LICENSE b/backend/node_modules/setprototypeof/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..61afa2f18532ecd749469c7d9bdd15940a852f5f --- /dev/null +++ b/backend/node_modules/setprototypeof/LICENSE @@ -0,0 +1,13 @@ +Copyright (c) 2015, Wes Todd + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +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. diff --git a/backend/node_modules/setprototypeof/README.md b/backend/node_modules/setprototypeof/README.md new file mode 100644 index 0000000000000000000000000000000000000000..791eeff0c094d51fc53009527cd13884666987ef --- /dev/null +++ b/backend/node_modules/setprototypeof/README.md @@ -0,0 +1,31 @@ +# Polyfill for `Object.setPrototypeOf` + +[![NPM Version](https://img.shields.io/npm/v/setprototypeof.svg)](https://npmjs.org/package/setprototypeof) +[![NPM Downloads](https://img.shields.io/npm/dm/setprototypeof.svg)](https://npmjs.org/package/setprototypeof) +[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg)](https://github.com/standard/standard) + +A simple cross platform implementation to set the prototype of an instianted object. Supports all modern browsers and at least back to IE8. + +## Usage: + +``` +$ npm install --save setprototypeof +``` + +```javascript +var setPrototypeOf = require('setprototypeof') + +var obj = {} +setPrototypeOf(obj, { + foo: function () { + return 'bar' + } +}) +obj.foo() // bar +``` + +TypeScript is also supported: + +```typescript +import setPrototypeOf from 'setprototypeof' +``` diff --git a/backend/node_modules/setprototypeof/index.d.ts b/backend/node_modules/setprototypeof/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f108ecd0a8ca1ec609529d3a0b76106c48e418a0 --- /dev/null +++ b/backend/node_modules/setprototypeof/index.d.ts @@ -0,0 +1,2 @@ +declare function setPrototypeOf(o: any, proto: object | null): any; +export = setPrototypeOf; diff --git a/backend/node_modules/setprototypeof/index.js b/backend/node_modules/setprototypeof/index.js new file mode 100644 index 0000000000000000000000000000000000000000..c5270551e93921ccd9eda9ce2b33e54490e57f05 --- /dev/null +++ b/backend/node_modules/setprototypeof/index.js @@ -0,0 +1,17 @@ +'use strict' +/* eslint no-proto: 0 */ +module.exports = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array ? setProtoOf : mixinProperties) + +function setProtoOf (obj, proto) { + obj.__proto__ = proto + return obj +} + +function mixinProperties (obj, proto) { + for (var prop in proto) { + if (!Object.prototype.hasOwnProperty.call(obj, prop)) { + obj[prop] = proto[prop] + } + } + return obj +} diff --git a/backend/node_modules/setprototypeof/package.json b/backend/node_modules/setprototypeof/package.json new file mode 100644 index 0000000000000000000000000000000000000000..f20915bea42e4016313176f9e8c1a154f457db3d --- /dev/null +++ b/backend/node_modules/setprototypeof/package.json @@ -0,0 +1,38 @@ +{ + "name": "setprototypeof", + "version": "1.2.0", + "description": "A small polyfill for Object.setprototypeof", + "main": "index.js", + "typings": "index.d.ts", + "scripts": { + "test": "standard && mocha", + "testallversions": "npm run node010 && npm run node4 && npm run node6 && npm run node9 && npm run node11", + "testversion": "docker run -it --rm -v $(PWD):/usr/src/app -w /usr/src/app node:${NODE_VER} npm install mocha@${MOCHA_VER:-latest} && npm t", + "node010": "NODE_VER=0.10 MOCHA_VER=3 npm run testversion", + "node4": "NODE_VER=4 npm run testversion", + "node6": "NODE_VER=6 npm run testversion", + "node9": "NODE_VER=9 npm run testversion", + "node11": "NODE_VER=11 npm run testversion", + "prepublishOnly": "npm t", + "postpublish": "git push origin && git push origin --tags" + }, + "repository": { + "type": "git", + "url": "https://github.com/wesleytodd/setprototypeof.git" + }, + "keywords": [ + "polyfill", + "object", + "setprototypeof" + ], + "author": "Wes Todd", + "license": "ISC", + "bugs": { + "url": "https://github.com/wesleytodd/setprototypeof/issues" + }, + "homepage": "https://github.com/wesleytodd/setprototypeof", + "devDependencies": { + "mocha": "^6.1.4", + "standard": "^13.0.2" + } +} diff --git a/backend/node_modules/setprototypeof/test/index.js b/backend/node_modules/setprototypeof/test/index.js new file mode 100644 index 0000000000000000000000000000000000000000..afeb4ddb2921824491502d0f68a0a3a44cf28aa1 --- /dev/null +++ b/backend/node_modules/setprototypeof/test/index.js @@ -0,0 +1,24 @@ +'use strict' +/* eslint-env mocha */ +/* eslint no-proto: 0 */ +var assert = require('assert') +var setPrototypeOf = require('..') + +describe('setProtoOf(obj, proto)', function () { + it('should merge objects', function () { + var obj = { a: 1, b: 2 } + var proto = { b: 3, c: 4 } + var mergeObj = setPrototypeOf(obj, proto) + + if (Object.getPrototypeOf) { + assert.strictEqual(Object.getPrototypeOf(obj), proto) + } else if ({ __proto__: [] } instanceof Array) { + assert.strictEqual(obj.__proto__, proto) + } else { + assert.strictEqual(obj.a, 1) + assert.strictEqual(obj.b, 2) + assert.strictEqual(obj.c, 4) + } + assert.strictEqual(mergeObj, obj) + }) +}) diff --git a/backend/node_modules/side-channel/.editorconfig b/backend/node_modules/side-channel/.editorconfig new file mode 100644 index 0000000000000000000000000000000000000000..72e0ebaa7f319d2bde03e55c8e58748245095f06 --- /dev/null +++ b/backend/node_modules/side-channel/.editorconfig @@ -0,0 +1,9 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +indent_style = tab +indent_size = 2 +trim_trailing_whitespace = true diff --git a/backend/node_modules/side-channel/.eslintrc b/backend/node_modules/side-channel/.eslintrc new file mode 100644 index 0000000000000000000000000000000000000000..93978e7d5b3d62d16972e7951ff9f683c7a006e4 --- /dev/null +++ b/backend/node_modules/side-channel/.eslintrc @@ -0,0 +1,11 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "max-lines-per-function": 0, + "multiline-comment-style": 1, + "new-cap": [2, { "capIsNewExceptions": ["GetIntrinsic"] }], + }, +} diff --git a/backend/node_modules/side-channel/.github/FUNDING.yml b/backend/node_modules/side-channel/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..2a94840c6ee509fc0eee1ca4574deea75163df27 --- /dev/null +++ b/backend/node_modules/side-channel/.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/side-channel +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/backend/node_modules/side-channel/.nycrc b/backend/node_modules/side-channel/.nycrc new file mode 100644 index 0000000000000000000000000000000000000000..1826526e091b89c896e7099ccd891db79165e329 --- /dev/null +++ b/backend/node_modules/side-channel/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "test" + ] +} diff --git a/backend/node_modules/side-channel/CHANGELOG.md b/backend/node_modules/side-channel/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..25369c5f234db81f57026b42900c794eab80a2ff --- /dev/null +++ b/backend/node_modules/side-channel/CHANGELOG.md @@ -0,0 +1,95 @@ +# 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.6](https://github.com/ljharb/side-channel/compare/v1.0.5...v1.0.6) - 2024-02-29 + +### Commits + +- add types [`9beef66`](https://github.com/ljharb/side-channel/commit/9beef6643e6d717ea57bedabf86448123a7dd9e9) +- [meta] simplify `exports` [`4334cf9`](https://github.com/ljharb/side-channel/commit/4334cf9df654151504c383b62a2f9ebdc8d9d5ac) +- [Deps] update `call-bind` [`d6043c4`](https://github.com/ljharb/side-channel/commit/d6043c4d8f4d7be9037dd0f0419c7a2e0e39ec6a) +- [Dev Deps] update `tape` [`6aca376`](https://github.com/ljharb/side-channel/commit/6aca3761868dc8cd5ff7fd9799bf6b95e09a6eb0) + +## [v1.0.5](https://github.com/ljharb/side-channel/compare/v1.0.4...v1.0.5) - 2024-02-06 + +### Commits + +- [actions] reuse common workflows [`3d2e1ff`](https://github.com/ljharb/side-channel/commit/3d2e1ffd16dd6eaaf3e40ff57951f840d2d63c04) +- [meta] use `npmignore` to autogenerate an npmignore file [`04296ea`](https://github.com/ljharb/side-channel/commit/04296ea17d1544b0a5d20fd5bfb31aa4f6513eb9) +- [meta] add `.editorconfig`; add `eclint` [`130f0a6`](https://github.com/ljharb/side-channel/commit/130f0a6adbc04d385c7456a601d38344dce3d6a9) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `safe-publish-latest`, `tape` [`d480c2f`](https://github.com/ljharb/side-channel/commit/d480c2fbe757489ae9b4275491ffbcc3ac4725e9) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `tape` [`ecbe70e`](https://github.com/ljharb/side-channel/commit/ecbe70e53a418234081a77971fec1fdfae20c841) +- [actions] update rebase action [`75240b9`](https://github.com/ljharb/side-channel/commit/75240b9963b816e8846400d2287cb68f88c7fba7) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `npmignore`, `tape` [`ae8d281`](https://github.com/ljharb/side-channel/commit/ae8d281572430099109870fd9430d2ca3f320b8d) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `tape` [`7125b88`](https://github.com/ljharb/side-channel/commit/7125b885fd0eacad4fee9b073b72d14065ece278) +- [Deps] update `call-bind`, `get-intrinsic`, `object-inspect` [`82577c9`](https://github.com/ljharb/side-channel/commit/82577c9796304519139a570f82a317211b5f3b86) +- [Deps] update `call-bind`, `get-intrinsic`, `object-inspect` [`550aadf`](https://github.com/ljharb/side-channel/commit/550aadf20475a6081fd70304cc54f77259a5c8a8) +- [Tests] increase coverage [`5130877`](https://github.com/ljharb/side-channel/commit/5130877a7b27c862e64e6d1c12a178b28808859d) +- [Deps] update `get-intrinsic`, `object-inspect` [`ba0194c`](https://github.com/ljharb/side-channel/commit/ba0194c505b1a8a0427be14cadd5b8a46d4d01b8) +- [meta] add missing `engines.node` [`985fd24`](https://github.com/ljharb/side-channel/commit/985fd249663cb06617a693a94fe08cad12f5cb70) +- [Refactor] use `es-errors`, so things that only need those do not need `get-intrinsic` [`40227a8`](https://github.com/ljharb/side-channel/commit/40227a87b01709ad2c0eebf87eb4223a800099b9) +- [Deps] update `get-intrinsic` [`a989b40`](https://github.com/ljharb/side-channel/commit/a989b4024958737ae7be9fbffdeff2078f33a0fd) +- [Deps] update `object-inspect` [`aec42d2`](https://github.com/ljharb/side-channel/commit/aec42d2ec541a31aaa02475692c87d489237d9a3) + +## [v1.0.4](https://github.com/ljharb/side-channel/compare/v1.0.3...v1.0.4) - 2020-12-29 + +### Commits + +- [Tests] migrate tests to Github Actions [`10909cb`](https://github.com/ljharb/side-channel/commit/10909cbf8ce9c0bf96f604cf13d7ffd5a22c2d40) +- [Refactor] Use a linked list rather than an array, and move accessed nodes to the beginning [`195613f`](https://github.com/ljharb/side-channel/commit/195613f28b5c1e6072ef0b61b5beebaf2b6a304e) +- [meta] do not publish github action workflow files [`290ec29`](https://github.com/ljharb/side-channel/commit/290ec29cd21a60585145b4a7237ec55228c52c27) +- [Tests] run `nyc` on all tests; use `tape` runner [`ea6d030`](https://github.com/ljharb/side-channel/commit/ea6d030ff3fe6be2eca39e859d644c51ecd88869) +- [actions] add "Allow Edits" workflow [`d464d8f`](https://github.com/ljharb/side-channel/commit/d464d8fe52b5eddf1504a0ed97f0941a90f32c15) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog` [`02daca8`](https://github.com/ljharb/side-channel/commit/02daca87c6809821c97be468d1afa2f5ef447383) +- [Refactor] use `call-bind` and `get-intrinsic` instead of `es-abstract` [`e09d481`](https://github.com/ljharb/side-channel/commit/e09d481528452ebafa5cdeae1af665c35aa2deee) +- [Deps] update `object.assign` [`ee83aa8`](https://github.com/ljharb/side-channel/commit/ee83aa81df313b5e46319a63adb05cf0c179079a) +- [actions] update rebase action to use checkout v2 [`7726b0b`](https://github.com/ljharb/side-channel/commit/7726b0b058b632fccea709f58960871defaaa9d7) + +## [v1.0.3](https://github.com/ljharb/side-channel/compare/v1.0.2...v1.0.3) - 2020-08-23 + +### Commits + +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `tape` [`1f10561`](https://github.com/ljharb/side-channel/commit/1f105611ef3acf32dec8032ae5c0baa5e56bb868) +- [Deps] update `es-abstract`, `object-inspect` [`bc20159`](https://github.com/ljharb/side-channel/commit/bc201597949a505e37cef9eaf24c7010831e6f03) +- [Dev Deps] update `@ljharb/eslint-config`, `tape` [`b9b2b22`](https://github.com/ljharb/side-channel/commit/b9b2b225f9e0ea72a6ec2b89348f0bd690bc9ed1) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`7055ab4`](https://github.com/ljharb/side-channel/commit/7055ab4de0860606efd2003674a74f1fe6ebc07e) +- [Dev Deps] update `auto-changelog`; add `aud` [`d278c37`](https://github.com/ljharb/side-channel/commit/d278c37d08227be4f84aa769fcd919e73feeba40) +- [actions] switch Automatic Rebase workflow to `pull_request_target` event [`3bcf982`](https://github.com/ljharb/side-channel/commit/3bcf982faa122745b39c33ce83d32fdf003741c6) +- [Tests] only audit prod deps [`18d01c4`](https://github.com/ljharb/side-channel/commit/18d01c4015b82a3d75044c4d5ba7917b2eac01ec) +- [Deps] update `es-abstract` [`6ab096d`](https://github.com/ljharb/side-channel/commit/6ab096d9de2b482cf5e0717e34e212f5b2b9bc9a) +- [Dev Deps] update `tape` [`9dc174c`](https://github.com/ljharb/side-channel/commit/9dc174cc651dfd300b4b72da936a0a7eda5f9452) +- [Deps] update `es-abstract` [`431d0f0`](https://github.com/ljharb/side-channel/commit/431d0f0ff11fbd2ae6f3115582a356d3a1cfce82) +- [Deps] update `es-abstract` [`49869fd`](https://github.com/ljharb/side-channel/commit/49869fd323bf4453f0ba515c0fb265cf5ab7b932) +- [meta] Add package.json to package's exports [`77d9cdc`](https://github.com/ljharb/side-channel/commit/77d9cdceb2a9e47700074f2ae0c0a202e7dac0d4) + +## [v1.0.2](https://github.com/ljharb/side-channel/compare/v1.0.1...v1.0.2) - 2019-12-20 + +### Commits + +- [Dev Deps] update `@ljharb/eslint-config`, `tape` [`4a526df`](https://github.com/ljharb/side-channel/commit/4a526df44e4701566ed001ec78546193f818b082) +- [Deps] update `es-abstract` [`d4f6e62`](https://github.com/ljharb/side-channel/commit/d4f6e629b6fb93a07415db7f30d3c90fd7f264fe) + +## [v1.0.1](https://github.com/ljharb/side-channel/compare/v1.0.0...v1.0.1) - 2019-12-01 + +### Commits + +- [Fix] add missing "exports" [`d212907`](https://github.com/ljharb/side-channel/commit/d2129073abf0701a5343bf28aa2145617604dc2e) + +## v1.0.0 - 2019-12-01 + +### Commits + +- Initial implementation [`dbebd3a`](https://github.com/ljharb/side-channel/commit/dbebd3a4b5ed64242f9a6810efe7c4214cd8cde4) +- Initial tests [`73bdefe`](https://github.com/ljharb/side-channel/commit/73bdefe568c9076cf8c0b8719bc2141aec0e19b8) +- Initial commit [`43c03e1`](https://github.com/ljharb/side-channel/commit/43c03e1c2849ec50a87b7a5cd76238a62b0b8770) +- npm init [`5c090a7`](https://github.com/ljharb/side-channel/commit/5c090a765d66a5527d9889b89aeff78dee91348c) +- [meta] add `auto-changelog` [`a5c4e56`](https://github.com/ljharb/side-channel/commit/a5c4e5675ec02d5eb4d84b4243aeea2a1d38fbec) +- [actions] add automatic rebasing / merge commit blocking [`bab1683`](https://github.com/ljharb/side-channel/commit/bab1683d8f9754b086e94397699fdc645e0d7077) +- [meta] add `funding` field; create FUNDING.yml [`63d7aea`](https://github.com/ljharb/side-channel/commit/63d7aeaf34f5650650ae97ca4b9fae685bd0937c) +- [Tests] add `npm run lint` [`46a5a81`](https://github.com/ljharb/side-channel/commit/46a5a81705cd2664f83df232c01dbbf2ee952885) +- Only apps should have lockfiles [`8b16b03`](https://github.com/ljharb/side-channel/commit/8b16b0305f00895d90c4e2e5773c854cfea0e448) +- [meta] add `safe-publish-latest` [`2f098ef`](https://github.com/ljharb/side-channel/commit/2f098ef092a39399cfe548b19a1fc03c2fd2f490) diff --git a/backend/node_modules/side-channel/LICENSE b/backend/node_modules/side-channel/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..3900dd7e2ffe6d5205fde1cd3f890aa51ea36234 --- /dev/null +++ b/backend/node_modules/side-channel/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 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/backend/node_modules/side-channel/README.md b/backend/node_modules/side-channel/README.md new file mode 100644 index 0000000000000000000000000000000000000000..7fa4f0680fe0c16093808cc57a8b84c42fbfdc84 --- /dev/null +++ b/backend/node_modules/side-channel/README.md @@ -0,0 +1,2 @@ +# side-channel +Store information about any JS value in a side channel. Uses WeakMap if available. diff --git a/backend/node_modules/side-channel/index.d.ts b/backend/node_modules/side-channel/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7cb112b90a75a22caea3edfe869689c16240f05b --- /dev/null +++ b/backend/node_modules/side-channel/index.d.ts @@ -0,0 +1,27 @@ +declare namespace getSideChannel { + type Key = unknown; + type ListNode = { + key: Key; + next: ListNode; + value: T; + }; + type RootNode = { + key: object; + next: null | ListNode; + }; + function listGetNode(list: RootNode, key: ListNode['key']): ListNode | void; + function listGet(objects: RootNode, key: ListNode['key']): T | void; + function listSet(objects: RootNode, key: ListNode['key'], value: T): void; + function listHas(objects: RootNode, key: ListNode['key']): boolean; + + type Channel = { + assert: (key: Key) => void; + has: (key: Key) => boolean; + get: (key: Key) => T; + set: (key: Key, value: T) => void; + } +} + +declare function getSideChannel(): getSideChannel.Channel; + +export = getSideChannel; diff --git a/backend/node_modules/side-channel/index.js b/backend/node_modules/side-channel/index.js new file mode 100644 index 0000000000000000000000000000000000000000..6b6926e112d9e79b002feb11914c21531a54e97b --- /dev/null +++ b/backend/node_modules/side-channel/index.js @@ -0,0 +1,129 @@ +'use strict'; + +var GetIntrinsic = require('get-intrinsic'); +var callBound = require('call-bind/callBound'); +var inspect = require('object-inspect'); + +var $TypeError = require('es-errors/type'); +var $WeakMap = GetIntrinsic('%WeakMap%', true); +var $Map = GetIntrinsic('%Map%', true); + +var $weakMapGet = callBound('WeakMap.prototype.get', true); +var $weakMapSet = callBound('WeakMap.prototype.set', true); +var $weakMapHas = callBound('WeakMap.prototype.has', true); +var $mapGet = callBound('Map.prototype.get', true); +var $mapSet = callBound('Map.prototype.set', true); +var $mapHas = callBound('Map.prototype.has', true); + +/* +* This function traverses the list returning the node corresponding to the given key. +* +* That node is also moved to the head of the list, so that if it's accessed again we don't need to traverse the whole list. By doing so, all the recently used nodes can be accessed relatively quickly. +*/ +/** @type {import('.').listGetNode} */ +var listGetNode = function (list, key) { // eslint-disable-line consistent-return + /** @type {typeof list | NonNullable<(typeof list)['next']>} */ + var prev = list; + /** @type {(typeof list)['next']} */ + var curr; + for (; (curr = prev.next) !== null; prev = curr) { + if (curr.key === key) { + prev.next = curr.next; + // eslint-disable-next-line no-extra-parens + curr.next = /** @type {NonNullable} */ (list.next); + list.next = curr; // eslint-disable-line no-param-reassign + return curr; + } + } +}; + +/** @type {import('.').listGet} */ +var listGet = function (objects, key) { + var node = listGetNode(objects, key); + return node && node.value; +}; +/** @type {import('.').listSet} */ +var listSet = function (objects, key, value) { + var node = listGetNode(objects, key); + if (node) { + node.value = value; + } else { + // Prepend the new node to the beginning of the list + objects.next = /** @type {import('.').ListNode} */ ({ // eslint-disable-line no-param-reassign, no-extra-parens + key: key, + next: objects.next, + value: value + }); + } +}; +/** @type {import('.').listHas} */ +var listHas = function (objects, key) { + return !!listGetNode(objects, key); +}; + +/** @type {import('.')} */ +module.exports = function getSideChannel() { + /** @type {WeakMap} */ var $wm; + /** @type {Map} */ var $m; + /** @type {import('.').RootNode} */ var $o; + + /** @type {import('.').Channel} */ + var channel = { + assert: function (key) { + if (!channel.has(key)) { + throw new $TypeError('Side channel does not contain ' + inspect(key)); + } + }, + get: function (key) { // eslint-disable-line consistent-return + if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { + if ($wm) { + return $weakMapGet($wm, key); + } + } else if ($Map) { + if ($m) { + return $mapGet($m, key); + } + } else { + if ($o) { // eslint-disable-line no-lonely-if + return listGet($o, key); + } + } + }, + has: function (key) { + if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { + if ($wm) { + return $weakMapHas($wm, key); + } + } else if ($Map) { + if ($m) { + return $mapHas($m, key); + } + } else { + if ($o) { // eslint-disable-line no-lonely-if + return listHas($o, key); + } + } + return false; + }, + set: function (key, value) { + if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { + if (!$wm) { + $wm = new $WeakMap(); + } + $weakMapSet($wm, key, value); + } else if ($Map) { + if (!$m) { + $m = new $Map(); + } + $mapSet($m, key, value); + } else { + if (!$o) { + // Initialize the linked list as an empty node, so that we don't have to special-case handling of the first node: we can always refer to it as (previous node).next, instead of something like (list).head + $o = { key: {}, next: null }; + } + listSet($o, key, value); + } + } + }; + return channel; +}; diff --git a/backend/node_modules/side-channel/package.json b/backend/node_modules/side-channel/package.json new file mode 100644 index 0000000000000000000000000000000000000000..02cffca6c8b30672e0d42e0ed418d4f87a6570e7 --- /dev/null +++ b/backend/node_modules/side-channel/package.json @@ -0,0 +1,84 @@ +{ + "name": "side-channel", + "version": "1.0.6", + "description": "Store information about any JS value in a side channel. Uses WeakMap if available.", + "main": "index.js", + "exports": { + "./package.json": "./package.json", + ".": "./index.js" + }, + "types": "./index.d.ts", + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prelint": "eclint check $(git ls-files | xargs find 2> /dev/null | grep -vE 'node_modules|\\.git')", + "lint": "eslint --ext=js,mjs .", + "postlint": "tsc -p .", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "aud --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/side-channel.git" + }, + "keywords": [ + "weakmap", + "map", + "side", + "channel", + "metadata" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/side-channel/issues" + }, + "homepage": "https://github.com/ljharb/side-channel#readme", + "devDependencies": { + "@ljharb/eslint-config": "^21.1.0", + "@types/call-bind": "^1.0.5", + "@types/get-intrinsic": "^1.2.2", + "@types/object-inspect": "^1.8.4", + "@types/tape": "^5.6.4", + "aud": "^2.0.4", + "auto-changelog": "^2.4.0", + "eclint": "^2.8.1", + "eslint": "=8.8.0", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.7.5", + "typescript": "next" + }, + "dependencies": { + "call-bind": "^1.0.7", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.4", + "object-inspect": "^1.13.1" + }, + "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/backend/node_modules/side-channel/test/index.js b/backend/node_modules/side-channel/test/index.js new file mode 100644 index 0000000000000000000000000000000000000000..8da3200735ce49c72b5f3a5054be48b3b24ee775 --- /dev/null +++ b/backend/node_modules/side-channel/test/index.js @@ -0,0 +1,83 @@ +'use strict'; + +var test = require('tape'); + +var getSideChannel = require('../'); + +test('export', function (t) { + t.equal(typeof getSideChannel, 'function', 'is a function'); + t.equal(getSideChannel.length, 0, 'takes no arguments'); + + var channel = getSideChannel(); + t.ok(channel, 'is truthy'); + t.equal(typeof channel, 'object', 'is an object'); + + t.end(); +}); + +test('assert', function (t) { + var channel = getSideChannel(); + t['throws']( + function () { channel.assert({}); }, + TypeError, + 'nonexistent value throws' + ); + + var o = {}; + channel.set(o, 'data'); + t.doesNotThrow(function () { channel.assert(o); }, 'existent value noops'); + + t.end(); +}); + +test('has', function (t) { + var channel = getSideChannel(); + /** @type {unknown[]} */ var o = []; + + t.equal(channel.has(o), false, 'nonexistent value yields false'); + + channel.set(o, 'foo'); + t.equal(channel.has(o), true, 'existent value yields true'); + + t.equal(channel.has('abc'), false, 'non object value non existent yields false'); + + channel.set('abc', 'foo'); + t.equal(channel.has('abc'), true, 'non object value that exists yields true'); + + t.end(); +}); + +test('get', function (t) { + var channel = getSideChannel(); + var o = {}; + t.equal(channel.get(o), undefined, 'nonexistent value yields undefined'); + + var data = {}; + channel.set(o, data); + t.equal(channel.get(o), data, '"get" yields data set by "set"'); + + t.end(); +}); + +test('set', function (t) { + var channel = getSideChannel(); + var o = function () {}; + t.equal(channel.get(o), undefined, 'value not set'); + + channel.set(o, 42); + t.equal(channel.get(o), 42, 'value was set'); + + channel.set(o, Infinity); + t.equal(channel.get(o), Infinity, 'value was set again'); + + var o2 = {}; + channel.set(o2, 17); + t.equal(channel.get(o), Infinity, 'o is not modified'); + t.equal(channel.get(o2), 17, 'o2 is set'); + + channel.set(o, 14); + t.equal(channel.get(o), 14, 'o is modified'); + t.equal(channel.get(o2), 17, 'o2 is not modified'); + + t.end(); +}); diff --git a/backend/node_modules/side-channel/tsconfig.json b/backend/node_modules/side-channel/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..fdfa1550da57bf5f0be63403a53207153949b21d --- /dev/null +++ b/backend/node_modules/side-channel/tsconfig.json @@ -0,0 +1,50 @@ +{ + "compilerOptions": { + /* Visit https://aka.ms/tsconfig.json to read more about this file */ + + /* Projects */ + + /* Language and Environment */ + "target": "es2022", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ + // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ + // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ + "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ + // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ + + /* Modules */ + "module": "commonjs", /* Specify what module code is generated. */ + // "rootDir": "./", /* Specify the root folder within your source files. */ + // "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */ + // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ + // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ + // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ + // "typeRoots": ["types"], /* Specify multiple folders that act like `./node_modules/@types`. */ + "resolveJsonModule": true, /* Enable importing .json files. */ + // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */ + + /* JavaScript Support */ + "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */ + "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ + "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */ + + /* Emit */ + "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ + "declarationMap": true, /* Create sourcemaps for d.ts files. */ + "noEmit": true, /* Disable emitting files from a compilation. */ + + /* Interop Constraints */ + "allowSyntheticDefaultImports": true, /* Allow `import x from y` when a module doesn't have a default export. */ + "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */ + "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ + + /* Type Checking */ + "strict": true, /* Enable all strict type-checking options. */ + + /* Completeness */ + // "skipLibCheck": true /* Skip type checking all .d.ts files. */ + }, + "exclude": [ + "coverage", + "test/list-exports" + ], +} diff --git a/backend/node_modules/statuses/HISTORY.md b/backend/node_modules/statuses/HISTORY.md new file mode 100644 index 0000000000000000000000000000000000000000..fa4556ef2cc396369f4b2dd8dc9a6f941d050ddb --- /dev/null +++ b/backend/node_modules/statuses/HISTORY.md @@ -0,0 +1,82 @@ +2.0.1 / 2021-01-03 +================== + + * Fix returning values from `Object.prototype` + +2.0.0 / 2020-04-19 +================== + + * Drop support for Node.js 0.6 + * Fix messaging casing of `418 I'm a Teapot` + * Remove code 306 + * Remove `status[code]` exports; use `status.message[code]` + * Remove `status[msg]` exports; use `status.code[msg]` + * Rename `425 Unordered Collection` to standard `425 Too Early` + * Rename `STATUS_CODES` export to `message` + * Return status message for `statuses(code)` when given code + +1.5.0 / 2018-03-27 +================== + + * Add `103 Early Hints` + +1.4.0 / 2017-10-20 +================== + + * Add `STATUS_CODES` export + +1.3.1 / 2016-11-11 +================== + + * Fix return type in JSDoc + +1.3.0 / 2016-05-17 +================== + + * Add `421 Misdirected Request` + * perf: enable strict mode + +1.2.1 / 2015-02-01 +================== + + * Fix message for status 451 + - `451 Unavailable For Legal Reasons` + +1.2.0 / 2014-09-28 +================== + + * Add `208 Already Repored` + * Add `226 IM Used` + * Add `306 (Unused)` + * Add `415 Unable For Legal Reasons` + * Add `508 Loop Detected` + +1.1.1 / 2014-09-24 +================== + + * Add missing 308 to `codes.json` + +1.1.0 / 2014-09-21 +================== + + * Add `codes.json` for universal support + +1.0.4 / 2014-08-20 +================== + + * Package cleanup + +1.0.3 / 2014-06-08 +================== + + * Add 308 to `.redirect` category + +1.0.2 / 2014-03-13 +================== + + * Add `.retry` category + +1.0.1 / 2014-03-12 +================== + + * Initial release diff --git a/backend/node_modules/statuses/LICENSE b/backend/node_modules/statuses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..28a31618205d7dbeed5b966fe9d2c682bd9367f5 --- /dev/null +++ b/backend/node_modules/statuses/LICENSE @@ -0,0 +1,23 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2016 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/backend/node_modules/statuses/README.md b/backend/node_modules/statuses/README.md new file mode 100644 index 0000000000000000000000000000000000000000..57967e6e62c56f9e3082b1054f9238d47a0106ae --- /dev/null +++ b/backend/node_modules/statuses/README.md @@ -0,0 +1,136 @@ +# statuses + +[![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][ci-image]][ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +HTTP status utility for node. + +This module provides a list of status codes and messages sourced from +a few different projects: + + * The [IANA Status Code Registry](https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml) + * The [Node.js project](https://nodejs.org/) + * The [NGINX project](https://www.nginx.com/) + * The [Apache HTTP Server project](https://httpd.apache.org/) + +## 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 statuses +``` + +## API + + + +```js +var status = require('statuses') +``` + +### status(code) + +Returns the status message string for a known HTTP status code. The code +may be a number or a string. An error is thrown for an unknown status code. + + + +```js +status(403) // => 'Forbidden' +status('403') // => 'Forbidden' +status(306) // throws +``` + +### status(msg) + +Returns the numeric status code for a known HTTP status message. The message +is case-insensitive. An error is thrown for an unknown status message. + + + +```js +status('forbidden') // => 403 +status('Forbidden') // => 403 +status('foo') // throws +``` + +### status.codes + +Returns an array of all the status codes as `Integer`s. + +### status.code[msg] + +Returns the numeric status code for a known status message (in lower-case), +otherwise `undefined`. + + + +```js +status['not found'] // => 404 +``` + +### status.empty[code] + +Returns `true` if a status code expects an empty body. + + + +```js +status.empty[200] // => undefined +status.empty[204] // => true +status.empty[304] // => true +``` + +### status.message[code] + +Returns the string message for a known numeric status code, otherwise +`undefined`. This object is the same format as the +[Node.js http module `http.STATUS_CODES`](https://nodejs.org/dist/latest/docs/api/http.html#http_http_status_codes). + + + +```js +status.message[404] // => 'Not Found' +``` + +### status.redirect[code] + +Returns `true` if a status code is a valid redirect status. + + + +```js +status.redirect[200] // => undefined +status.redirect[301] // => true +``` + +### status.retry[code] + +Returns `true` if you should retry the rest. + + + +```js +status.retry[501] // => undefined +status.retry[503] // => true +``` + +## License + +[MIT](LICENSE) + +[ci-image]: https://badgen.net/github/checks/jshttp/statuses/master?label=ci +[ci-url]: https://github.com/jshttp/statuses/actions?query=workflow%3Aci +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/statuses/master +[coveralls-url]: https://coveralls.io/r/jshttp/statuses?branch=master +[node-version-image]: https://badgen.net/npm/node/statuses +[node-version-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/statuses +[npm-url]: https://npmjs.org/package/statuses +[npm-version-image]: https://badgen.net/npm/v/statuses diff --git a/backend/node_modules/statuses/codes.json b/backend/node_modules/statuses/codes.json new file mode 100644 index 0000000000000000000000000000000000000000..1333ed10bab28344b55c217d80ce4f6cc2555793 --- /dev/null +++ b/backend/node_modules/statuses/codes.json @@ -0,0 +1,65 @@ +{ + "100": "Continue", + "101": "Switching Protocols", + "102": "Processing", + "103": "Early Hints", + "200": "OK", + "201": "Created", + "202": "Accepted", + "203": "Non-Authoritative Information", + "204": "No Content", + "205": "Reset Content", + "206": "Partial Content", + "207": "Multi-Status", + "208": "Already Reported", + "226": "IM Used", + "300": "Multiple Choices", + "301": "Moved Permanently", + "302": "Found", + "303": "See Other", + "304": "Not Modified", + "305": "Use Proxy", + "307": "Temporary Redirect", + "308": "Permanent Redirect", + "400": "Bad Request", + "401": "Unauthorized", + "402": "Payment Required", + "403": "Forbidden", + "404": "Not Found", + "405": "Method Not Allowed", + "406": "Not Acceptable", + "407": "Proxy Authentication Required", + "408": "Request Timeout", + "409": "Conflict", + "410": "Gone", + "411": "Length Required", + "412": "Precondition Failed", + "413": "Payload Too Large", + "414": "URI Too Long", + "415": "Unsupported Media Type", + "416": "Range Not Satisfiable", + "417": "Expectation Failed", + "418": "I'm a Teapot", + "421": "Misdirected Request", + "422": "Unprocessable Entity", + "423": "Locked", + "424": "Failed Dependency", + "425": "Too Early", + "426": "Upgrade Required", + "428": "Precondition Required", + "429": "Too Many Requests", + "431": "Request Header Fields Too Large", + "451": "Unavailable For Legal Reasons", + "500": "Internal Server Error", + "501": "Not Implemented", + "502": "Bad Gateway", + "503": "Service Unavailable", + "504": "Gateway Timeout", + "505": "HTTP Version Not Supported", + "506": "Variant Also Negotiates", + "507": "Insufficient Storage", + "508": "Loop Detected", + "509": "Bandwidth Limit Exceeded", + "510": "Not Extended", + "511": "Network Authentication Required" +} diff --git a/backend/node_modules/statuses/index.js b/backend/node_modules/statuses/index.js new file mode 100644 index 0000000000000000000000000000000000000000..ea351c553520e1bc62d53b97a316194c48ac49e6 --- /dev/null +++ b/backend/node_modules/statuses/index.js @@ -0,0 +1,146 @@ +/*! + * statuses + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2016 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var codes = require('./codes.json') + +/** + * Module exports. + * @public + */ + +module.exports = status + +// status code to message map +status.message = codes + +// status message (lower-case) to code map +status.code = createMessageToStatusCodeMap(codes) + +// array of status codes +status.codes = createStatusCodeList(codes) + +// status codes for redirects +status.redirect = { + 300: true, + 301: true, + 302: true, + 303: true, + 305: true, + 307: true, + 308: true +} + +// status codes for empty bodies +status.empty = { + 204: true, + 205: true, + 304: true +} + +// status codes for when you should retry the request +status.retry = { + 502: true, + 503: true, + 504: true +} + +/** + * Create a map of message to status code. + * @private + */ + +function createMessageToStatusCodeMap (codes) { + var map = {} + + Object.keys(codes).forEach(function forEachCode (code) { + var message = codes[code] + var status = Number(code) + + // populate map + map[message.toLowerCase()] = status + }) + + return map +} + +/** + * Create a list of all status codes. + * @private + */ + +function createStatusCodeList (codes) { + return Object.keys(codes).map(function mapCode (code) { + return Number(code) + }) +} + +/** + * Get the status code for given message. + * @private + */ + +function getStatusCode (message) { + var msg = message.toLowerCase() + + if (!Object.prototype.hasOwnProperty.call(status.code, msg)) { + throw new Error('invalid status message: "' + message + '"') + } + + return status.code[msg] +} + +/** + * Get the status message for given code. + * @private + */ + +function getStatusMessage (code) { + if (!Object.prototype.hasOwnProperty.call(status.message, code)) { + throw new Error('invalid status code: ' + code) + } + + return status.message[code] +} + +/** + * Get the status code. + * + * Given a number, this will throw if it is not a known status + * code, otherwise the code will be returned. Given a string, + * the string will be parsed for a number and return the code + * if valid, otherwise will lookup the code assuming this is + * the status message. + * + * @param {string|number} code + * @returns {number} + * @public + */ + +function status (code) { + if (typeof code === 'number') { + return getStatusMessage(code) + } + + if (typeof code !== 'string') { + throw new TypeError('code must be a number or string') + } + + // '403' + var n = parseInt(code, 10) + if (!isNaN(n)) { + return getStatusMessage(n) + } + + return getStatusCode(code) +} diff --git a/backend/node_modules/statuses/package.json b/backend/node_modules/statuses/package.json new file mode 100644 index 0000000000000000000000000000000000000000..8c3e719b50cdaa58f6a3fa38c84d8faeefdfc00f --- /dev/null +++ b/backend/node_modules/statuses/package.json @@ -0,0 +1,49 @@ +{ + "name": "statuses", + "description": "HTTP status utility", + "version": "2.0.1", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)" + ], + "repository": "jshttp/statuses", + "license": "MIT", + "keywords": [ + "http", + "status", + "code" + ], + "files": [ + "HISTORY.md", + "index.js", + "codes.json", + "LICENSE" + ], + "devDependencies": { + "csv-parse": "4.14.2", + "eslint": "7.17.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.22.1", + "eslint-plugin-markdown": "1.0.2", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "4.2.1", + "eslint-plugin-standard": "4.1.0", + "mocha": "8.2.1", + "nyc": "15.1.0", + "raw-body": "2.4.1", + "stream-to-array": "2.3.0" + }, + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "build": "node scripts/build.js", + "fetch": "node scripts/fetch-apache.js && node scripts/fetch-iana.js && node scripts/fetch-nginx.js && node scripts/fetch-node.js", + "lint": "eslint --plugin markdown --ext js,md .", + "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", + "update": "npm run fetch && npm run build", + "version": "node scripts/version-history.js && git add HISTORY.md" + } +} diff --git a/backend/node_modules/streamsearch/.eslintrc.js b/backend/node_modules/streamsearch/.eslintrc.js new file mode 100644 index 0000000000000000000000000000000000000000..be9311d02655a22381f13078bfe868bcbd85b3a6 --- /dev/null +++ b/backend/node_modules/streamsearch/.eslintrc.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = { + extends: '@mscdex/eslint-config', +}; diff --git a/backend/node_modules/streamsearch/.github/workflows/ci.yml b/backend/node_modules/streamsearch/.github/workflows/ci.yml new file mode 100644 index 0000000000000000000000000000000000000000..29d51782c77a93f2a32774350fb6e6229ebc3408 --- /dev/null +++ b/backend/node_modules/streamsearch/.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.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/backend/node_modules/streamsearch/.github/workflows/lint.yml b/backend/node_modules/streamsearch/.github/workflows/lint.yml new file mode 100644 index 0000000000000000000000000000000000000000..9f9e1f589a30be583a860f928382b3033c38749d --- /dev/null +++ b/backend/node_modules/streamsearch/.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/backend/node_modules/streamsearch/LICENSE b/backend/node_modules/streamsearch/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9ea90e03922d5e31b32e5ff84f4e51a6ca0760b5 --- /dev/null +++ b/backend/node_modules/streamsearch/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/backend/node_modules/streamsearch/README.md b/backend/node_modules/streamsearch/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c3934d1c7d57119aa31103bc6389838c646e2fc2 --- /dev/null +++ b/backend/node_modules/streamsearch/README.md @@ -0,0 +1,95 @@ +Description +=========== + +streamsearch is a module for [node.js](http://nodejs.org/) that allows searching a stream using the Boyer-Moore-Horspool algorithm. + +This module is based heavily on the Streaming Boyer-Moore-Horspool C++ implementation by Hongli Lai [here](https://github.com/FooBarWidget/boyer-moore-horspool). + + +Requirements +============ + +* [node.js](http://nodejs.org/) -- v10.0.0 or newer + + +Installation +============ + + npm install streamsearch + +Example +======= + +```js + const { inspect } = require('util'); + + const StreamSearch = require('streamsearch'); + + const needle = Buffer.from('\r\n'); + const ss = new StreamSearch(needle, (isMatch, data, start, end) => { + if (data) + console.log('data: ' + inspect(data.toString('latin1', start, end))); + if (isMatch) + console.log('match!'); + }); + + const chunks = [ + 'foo', + ' bar', + '\r', + '\n', + 'baz, hello\r', + '\n world.', + '\r\n Node.JS rules!!\r\n\r\n', + ]; + for (const chunk of chunks) + ss.push(Buffer.from(chunk)); + + // output: + // + // data: 'foo' + // data: ' bar' + // match! + // data: 'baz, hello' + // match! + // data: ' world.' + // match! + // data: ' Node.JS rules!!' + // match! + // data: '' + // match! +``` + + +API +=== + +Properties +---------- + +* **maxMatches** - < _integer_ > - The maximum number of matches. Defaults to `Infinity`. + +* **matches** - < _integer_ > - The current match count. + + +Functions +--------- + +* **(constructor)**(< _mixed_ >needle, < _function_ >callback) - Creates and returns a new instance for searching for a _Buffer_ or _string_ `needle`. `callback` is called any time there is non-matching data and/or there is a needle match. `callback` will be called with the following arguments: + + 1. `isMatch` - _boolean_ - Indicates whether a match has been found + + 2. `data` - _mixed_ - If set, this contains data that did not match the needle. + + 3. `start` - _integer_ - The index in `data` where the non-matching data begins (inclusive). + + 4. `end` - _integer_ - The index in `data` where the non-matching data ends (exclusive). + + 5. `isSafeData` - _boolean_ - Indicates if it is safe to store a reference to `data` (e.g. as-is or via `data.slice()`) or not, as in some cases `data` may point to a Buffer whose contents change over time. + +* **destroy**() - _(void)_ - Emits any last remaining unmatched data that may still be buffered and then resets internal state. + +* **push**(< _Buffer_ >chunk) - _integer_ - Processes `chunk`, searching for a match. The return value is the last processed index in `chunk` + 1. + +* **reset**() - _(void)_ - Resets internal state. Useful for when you wish to start searching a new/different stream for example. + diff --git a/backend/node_modules/streamsearch/lib/sbmh.js b/backend/node_modules/streamsearch/lib/sbmh.js new file mode 100644 index 0000000000000000000000000000000000000000..510cae26e67a58d4c1cdfb4ed5afd80c0f50c782 --- /dev/null +++ b/backend/node_modules/streamsearch/lib/sbmh.js @@ -0,0 +1,267 @@ +'use strict'; +/* + Based heavily on the Streaming Boyer-Moore-Horspool C++ implementation + by Hongli Lai at: https://github.com/FooBarWidget/boyer-moore-horspool +*/ +function memcmp(buf1, pos1, buf2, pos2, num) { + for (let i = 0; i < num; ++i) { + if (buf1[pos1 + i] !== buf2[pos2 + i]) + return false; + } + return true; +} + +class SBMH { + constructor(needle, cb) { + if (typeof cb !== 'function') + throw new Error('Missing match callback'); + + if (typeof needle === 'string') + needle = Buffer.from(needle); + else if (!Buffer.isBuffer(needle)) + throw new Error(`Expected Buffer for needle, got ${typeof needle}`); + + const needleLen = needle.length; + + this.maxMatches = Infinity; + this.matches = 0; + + this._cb = cb; + this._lookbehindSize = 0; + this._needle = needle; + this._bufPos = 0; + + this._lookbehind = Buffer.allocUnsafe(needleLen); + + // Initialize occurrence table. + this._occ = [ + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen + ]; + + // Populate occurrence table with analysis of the needle, ignoring the last + // letter. + if (needleLen > 1) { + for (let i = 0; i < needleLen - 1; ++i) + this._occ[needle[i]] = needleLen - 1 - i; + } + } + + reset() { + this.matches = 0; + this._lookbehindSize = 0; + this._bufPos = 0; + } + + push(chunk, pos) { + let result; + if (!Buffer.isBuffer(chunk)) + chunk = Buffer.from(chunk, 'latin1'); + const chunkLen = chunk.length; + this._bufPos = pos || 0; + while (result !== chunkLen && this.matches < this.maxMatches) + result = feed(this, chunk); + return result; + } + + destroy() { + const lbSize = this._lookbehindSize; + if (lbSize) + this._cb(false, this._lookbehind, 0, lbSize, false); + this.reset(); + } +} + +function feed(self, data) { + const len = data.length; + const needle = self._needle; + const needleLen = needle.length; + + // Positive: points to a position in `data` + // pos == 3 points to data[3] + // Negative: points to a position in the lookbehind buffer + // pos == -2 points to lookbehind[lookbehindSize - 2] + let pos = -self._lookbehindSize; + const lastNeedleCharPos = needleLen - 1; + const lastNeedleChar = needle[lastNeedleCharPos]; + const end = len - needleLen; + const occ = self._occ; + const lookbehind = self._lookbehind; + + if (pos < 0) { + // Lookbehind buffer is not empty. Perform Boyer-Moore-Horspool + // search with character lookup code that considers both the + // lookbehind buffer and the current round's haystack data. + // + // Loop until + // there is a match. + // or until + // we've moved past the position that requires the + // lookbehind buffer. In this case we switch to the + // optimized loop. + // or until + // the character to look at lies outside the haystack. + while (pos < 0 && pos <= end) { + const nextPos = pos + lastNeedleCharPos; + const ch = (nextPos < 0 + ? lookbehind[self._lookbehindSize + nextPos] + : data[nextPos]); + + if (ch === lastNeedleChar + && matchNeedle(self, data, pos, lastNeedleCharPos)) { + self._lookbehindSize = 0; + ++self.matches; + if (pos > -self._lookbehindSize) + self._cb(true, lookbehind, 0, self._lookbehindSize + pos, false); + else + self._cb(true, undefined, 0, 0, true); + + return (self._bufPos = pos + needleLen); + } + + pos += occ[ch]; + } + + // No match. + + // There's too few data for Boyer-Moore-Horspool to run, + // so let's use a different algorithm to skip as much as + // we can. + // Forward pos until + // the trailing part of lookbehind + data + // looks like the beginning of the needle + // or until + // pos == 0 + while (pos < 0 && !matchNeedle(self, data, pos, len - pos)) + ++pos; + + if (pos < 0) { + // Cut off part of the lookbehind buffer that has + // been processed and append the entire haystack + // into it. + const bytesToCutOff = self._lookbehindSize + pos; + + if (bytesToCutOff > 0) { + // The cut off data is guaranteed not to contain the needle. + self._cb(false, lookbehind, 0, bytesToCutOff, false); + } + + self._lookbehindSize -= bytesToCutOff; + lookbehind.copy(lookbehind, 0, bytesToCutOff, self._lookbehindSize); + lookbehind.set(data, self._lookbehindSize); + self._lookbehindSize += len; + + self._bufPos = len; + return len; + } + + // Discard lookbehind buffer. + self._cb(false, lookbehind, 0, self._lookbehindSize, false); + self._lookbehindSize = 0; + } + + pos += self._bufPos; + + const firstNeedleChar = needle[0]; + + // Lookbehind buffer is now empty. Perform Boyer-Moore-Horspool + // search with optimized character lookup code that only considers + // the current round's haystack data. + while (pos <= end) { + const ch = data[pos + lastNeedleCharPos]; + + if (ch === lastNeedleChar + && data[pos] === firstNeedleChar + && memcmp(needle, 0, data, pos, lastNeedleCharPos)) { + ++self.matches; + if (pos > 0) + self._cb(true, data, self._bufPos, pos, true); + else + self._cb(true, undefined, 0, 0, true); + + return (self._bufPos = pos + needleLen); + } + + pos += occ[ch]; + } + + // There was no match. If there's trailing haystack data that we cannot + // match yet using the Boyer-Moore-Horspool algorithm (because the trailing + // data is less than the needle size) then match using a modified + // algorithm that starts matching from the beginning instead of the end. + // Whatever trailing data is left after running this algorithm is added to + // the lookbehind buffer. + while (pos < len) { + if (data[pos] !== firstNeedleChar + || !memcmp(data, pos, needle, 0, len - pos)) { + ++pos; + continue; + } + data.copy(lookbehind, 0, pos, len); + self._lookbehindSize = len - pos; + break; + } + + // Everything until `pos` is guaranteed not to contain needle data. + if (pos > 0) + self._cb(false, data, self._bufPos, pos < len ? pos : len, true); + + self._bufPos = len; + return len; +} + +function matchNeedle(self, data, pos, len) { + const lb = self._lookbehind; + const lbSize = self._lookbehindSize; + const needle = self._needle; + + for (let i = 0; i < len; ++i, ++pos) { + const ch = (pos < 0 ? lb[lbSize + pos] : data[pos]); + if (ch !== needle[i]) + return false; + } + return true; +} + +module.exports = SBMH; diff --git a/backend/node_modules/streamsearch/package.json b/backend/node_modules/streamsearch/package.json new file mode 100644 index 0000000000000000000000000000000000000000..51df8f9707cebd8469d793a8d90050baac1c4d1d --- /dev/null +++ b/backend/node_modules/streamsearch/package.json @@ -0,0 +1,34 @@ +{ + "name": "streamsearch", + "version": "1.1.0", + "author": "Brian White ", + "description": "Streaming Boyer-Moore-Horspool searching for node.js", + "main": "./lib/sbmh.js", + "engines": { + "node": ">=10.0.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", + "lint:fix": "npm run lint -- --fix" + }, + "keywords": [ + "stream", + "horspool", + "boyer-moore-horspool", + "boyer-moore", + "search" + ], + "licenses": [{ + "type": "MIT", + "url": "http://github.com/mscdex/streamsearch/raw/master/LICENSE" + }], + "repository": { + "type": "git", + "url": "http://github.com/mscdex/streamsearch.git" + } +} diff --git a/backend/node_modules/streamsearch/test/test.js b/backend/node_modules/streamsearch/test/test.js new file mode 100644 index 0000000000000000000000000000000000000000..39a04d7f834bea5e8da37c4cf56973a7b3217dd5 --- /dev/null +++ b/backend/node_modules/streamsearch/test/test.js @@ -0,0 +1,70 @@ +'use strict'; + +const assert = require('assert'); + +const StreamSearch = require('../lib/sbmh.js'); + +[ + { + needle: '\r\n', + chunks: [ + 'foo', + ' bar', + '\r', + '\n', + 'baz, hello\r', + '\n world.', + '\r\n Node.JS rules!!\r\n\r\n', + ], + expect: [ + [false, 'foo'], + [false, ' bar'], + [ true, null], + [false, 'baz, hello'], + [ true, null], + [false, ' world.'], + [ true, null], + [ true, ' Node.JS rules!!'], + [ true, ''], + ], + }, + { + needle: '---foobarbaz', + chunks: [ + '---foobarbaz', + 'asdf', + '\r\n', + '---foobarba', + '---foobar', + 'ba', + '\r\n---foobarbaz--\r\n', + ], + expect: [ + [ true, null], + [false, 'asdf'], + [false, '\r\n'], + [false, '---foobarba'], + [false, '---foobarba'], + [ true, '\r\n'], + [false, '--\r\n'], + ], + }, +].forEach((test, i) => { + console.log(`Running test #${i + 1}`); + const { needle, chunks, expect } = test; + + const results = []; + const ss = new StreamSearch(Buffer.from(needle), + (isMatch, data, start, end) => { + if (data) + data = data.toString('latin1', start, end); + else + data = null; + results.push([isMatch, data]); + }); + + for (const chunk of chunks) + ss.push(Buffer.from(chunk)); + + assert.deepStrictEqual(results, expect); +}); diff --git a/backend/node_modules/string_decoder/.travis.yml b/backend/node_modules/string_decoder/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..3347a7254650582da5339323466f84fe079fc270 --- /dev/null +++ b/backend/node_modules/string_decoder/.travis.yml @@ -0,0 +1,50 @@ +sudo: false +language: node_js +before_install: + - npm install -g npm@2 + - test $NPM_LEGACY && npm install -g npm@latest-3 || npm install npm -g +notifications: + email: false +matrix: + fast_finish: true + include: + - node_js: '0.8' + env: + - TASK=test + - NPM_LEGACY=true + - node_js: '0.10' + env: + - TASK=test + - NPM_LEGACY=true + - node_js: '0.11' + env: + - TASK=test + - NPM_LEGACY=true + - node_js: '0.12' + env: + - TASK=test + - NPM_LEGACY=true + - node_js: 1 + env: + - TASK=test + - NPM_LEGACY=true + - node_js: 2 + env: + - TASK=test + - NPM_LEGACY=true + - node_js: 3 + env: + - TASK=test + - NPM_LEGACY=true + - node_js: 4 + env: TASK=test + - node_js: 5 + env: TASK=test + - node_js: 6 + env: TASK=test + - node_js: 7 + env: TASK=test + - node_js: 8 + env: TASK=test + - node_js: 9 + env: TASK=test diff --git a/backend/node_modules/string_decoder/LICENSE b/backend/node_modules/string_decoder/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..778edb20730ef48c01002248f4d51e7752c13487 --- /dev/null +++ b/backend/node_modules/string_decoder/LICENSE @@ -0,0 +1,48 @@ +Node.js is licensed for use as follows: + +""" +Copyright Node.js contributors. 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. +""" + +This license applies to parts of Node.js originating from the +https://github.com/joyent/node repository: + +""" +Copyright Joyent, Inc. and other Node contributors. 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. +""" + diff --git a/backend/node_modules/string_decoder/README.md b/backend/node_modules/string_decoder/README.md new file mode 100644 index 0000000000000000000000000000000000000000..5fd58315ed588027742dde690a31cd0a2610649d --- /dev/null +++ b/backend/node_modules/string_decoder/README.md @@ -0,0 +1,47 @@ +# string_decoder + +***Node-core v8.9.4 string_decoder for userland*** + + +[![NPM](https://nodei.co/npm/string_decoder.png?downloads=true&downloadRank=true)](https://nodei.co/npm/string_decoder/) +[![NPM](https://nodei.co/npm-dl/string_decoder.png?&months=6&height=3)](https://nodei.co/npm/string_decoder/) + + +```bash +npm install --save string_decoder +``` + +***Node-core string_decoder for userland*** + +This package is a mirror of the string_decoder implementation in Node-core. + +Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v8.9.4/docs/api/). + +As of version 1.0.0 **string_decoder** uses semantic versioning. + +## Previous versions + +Previous version numbers match the versions found in Node core, e.g. 0.10.24 matches Node 0.10.24, likewise 0.11.10 matches Node 0.11.10. + +## Update + +The *build/* directory contains a build script that will scrape the source from the [nodejs/node](https://github.com/nodejs/node) repo given a specific Node version. + +## Streams Working Group + +`string_decoder` is maintained by the Streams Working Group, which +oversees the development and maintenance of the Streams API within +Node.js. The responsibilities of the Streams Working Group include: + +* Addressing stream issues on the Node.js issue tracker. +* Authoring and editing stream documentation within the Node.js project. +* Reviewing changes to stream subclasses within the Node.js project. +* Redirecting changes to streams from the Node.js project to this + project. +* Assisting in the implementation of stream providers within Node.js. +* Recommending versions of `readable-stream` to be included in Node.js. +* Messaging about the future of streams to give the community advance + notice of changes. + +See [readable-stream](https://github.com/nodejs/readable-stream) for +more details. diff --git a/backend/node_modules/string_decoder/lib/string_decoder.js b/backend/node_modules/string_decoder/lib/string_decoder.js new file mode 100644 index 0000000000000000000000000000000000000000..2e89e63f7933e42b8ba543ede35d2a8fa3e4f100 --- /dev/null +++ b/backend/node_modules/string_decoder/lib/string_decoder.js @@ -0,0 +1,296 @@ +// Copyright Joyent, Inc. and other Node 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. + +'use strict'; + +/**/ + +var Buffer = require('safe-buffer').Buffer; +/**/ + +var isEncoding = Buffer.isEncoding || function (encoding) { + encoding = '' + encoding; + switch (encoding && encoding.toLowerCase()) { + case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': + return true; + default: + return false; + } +}; + +function _normalizeEncoding(enc) { + if (!enc) return 'utf8'; + var retried; + while (true) { + switch (enc) { + case 'utf8': + case 'utf-8': + return 'utf8'; + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return 'utf16le'; + case 'latin1': + case 'binary': + return 'latin1'; + case 'base64': + case 'ascii': + case 'hex': + return enc; + default: + if (retried) return; // undefined + enc = ('' + enc).toLowerCase(); + retried = true; + } + } +}; + +// Do not cache `Buffer.isEncoding` when checking encoding names as some +// modules monkey-patch it to support additional encodings +function normalizeEncoding(enc) { + var nenc = _normalizeEncoding(enc); + if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); + return nenc || enc; +} + +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. +exports.StringDecoder = StringDecoder; +function StringDecoder(encoding) { + this.encoding = normalizeEncoding(encoding); + var nb; + switch (this.encoding) { + case 'utf16le': + this.text = utf16Text; + this.end = utf16End; + nb = 4; + break; + case 'utf8': + this.fillLast = utf8FillLast; + nb = 4; + break; + case 'base64': + this.text = base64Text; + this.end = base64End; + nb = 3; + break; + default: + this.write = simpleWrite; + this.end = simpleEnd; + return; + } + this.lastNeed = 0; + this.lastTotal = 0; + this.lastChar = Buffer.allocUnsafe(nb); +} + +StringDecoder.prototype.write = function (buf) { + if (buf.length === 0) return ''; + var r; + var i; + if (this.lastNeed) { + r = this.fillLast(buf); + if (r === undefined) return ''; + i = this.lastNeed; + this.lastNeed = 0; + } else { + i = 0; + } + if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); + return r || ''; +}; + +StringDecoder.prototype.end = utf8End; + +// Returns only complete characters in a Buffer +StringDecoder.prototype.text = utf8Text; + +// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer +StringDecoder.prototype.fillLast = function (buf) { + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); + this.lastNeed -= buf.length; +}; + +// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a +// continuation byte. If an invalid byte is detected, -2 is returned. +function utf8CheckByte(byte) { + if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; + return byte >> 6 === 0x02 ? -1 : -2; +} + +// Checks at most 3 bytes at the end of a Buffer in order to detect an +// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) +// needed to complete the UTF-8 character (if applicable) are returned. +function utf8CheckIncomplete(self, buf, i) { + var j = buf.length - 1; + if (j < i) return 0; + var nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 1; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 2; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) { + if (nb === 2) nb = 0;else self.lastNeed = nb - 3; + } + return nb; + } + return 0; +} + +// Validates as many continuation bytes for a multi-byte UTF-8 character as +// needed or are available. If we see a non-continuation byte where we expect +// one, we "replace" the validated continuation bytes we've seen so far with +// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding +// behavior. The continuation byte check is included three times in the case +// where all of the continuation bytes for a character exist in the same buffer. +// It is also done this way as a slight performance increase instead of using a +// loop. +function utf8CheckExtraBytes(self, buf, p) { + if ((buf[0] & 0xC0) !== 0x80) { + self.lastNeed = 0; + return '\ufffd'; + } + if (self.lastNeed > 1 && buf.length > 1) { + if ((buf[1] & 0xC0) !== 0x80) { + self.lastNeed = 1; + return '\ufffd'; + } + if (self.lastNeed > 2 && buf.length > 2) { + if ((buf[2] & 0xC0) !== 0x80) { + self.lastNeed = 2; + return '\ufffd'; + } + } + } +} + +// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. +function utf8FillLast(buf) { + var p = this.lastTotal - this.lastNeed; + var r = utf8CheckExtraBytes(this, buf, p); + if (r !== undefined) return r; + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, p, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, p, 0, buf.length); + this.lastNeed -= buf.length; +} + +// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a +// partial character, the character's bytes are buffered until the required +// number of bytes are available. +function utf8Text(buf, i) { + var total = utf8CheckIncomplete(this, buf, i); + if (!this.lastNeed) return buf.toString('utf8', i); + this.lastTotal = total; + var end = buf.length - (total - this.lastNeed); + buf.copy(this.lastChar, 0, end); + return buf.toString('utf8', i, end); +} + +// For UTF-8, a replacement character is added when ending on a partial +// character. +function utf8End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + '\ufffd'; + return r; +} + +// UTF-16LE typically needs two bytes per character, but even if we have an even +// number of bytes available, we need to check if we end on a leading/high +// surrogate. In that case, we need to wait for the next two bytes in order to +// decode the last character properly. +function utf16Text(buf, i) { + if ((buf.length - i) % 2 === 0) { + var r = buf.toString('utf16le', i); + if (r) { + var c = r.charCodeAt(r.length - 1); + if (c >= 0xD800 && c <= 0xDBFF) { + this.lastNeed = 2; + this.lastTotal = 4; + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + return r.slice(0, -1); + } + } + return r; + } + this.lastNeed = 1; + this.lastTotal = 2; + this.lastChar[0] = buf[buf.length - 1]; + return buf.toString('utf16le', i, buf.length - 1); +} + +// For UTF-16LE we do not explicitly append special replacement characters if we +// end on a partial character, we simply let v8 handle that. +function utf16End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) { + var end = this.lastTotal - this.lastNeed; + return r + this.lastChar.toString('utf16le', 0, end); + } + return r; +} + +function base64Text(buf, i) { + var n = (buf.length - i) % 3; + if (n === 0) return buf.toString('base64', i); + this.lastNeed = 3 - n; + this.lastTotal = 3; + if (n === 1) { + this.lastChar[0] = buf[buf.length - 1]; + } else { + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + } + return buf.toString('base64', i, buf.length - n); +} + +function base64End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); + return r; +} + +// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) +function simpleWrite(buf) { + return buf.toString(this.encoding); +} + +function simpleEnd(buf) { + return buf && buf.length ? this.write(buf) : ''; +} \ No newline at end of file diff --git a/backend/node_modules/string_decoder/node_modules/safe-buffer/LICENSE b/backend/node_modules/string_decoder/node_modules/safe-buffer/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..0c068ceecbd48fc4e8279e6451793fec2bf12178 --- /dev/null +++ b/backend/node_modules/string_decoder/node_modules/safe-buffer/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Feross Aboukhadijeh + +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/backend/node_modules/string_decoder/node_modules/safe-buffer/README.md b/backend/node_modules/string_decoder/node_modules/safe-buffer/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e9a81afd0406f030ba21169f0c7a1dba70b3a93b --- /dev/null +++ b/backend/node_modules/string_decoder/node_modules/safe-buffer/README.md @@ -0,0 +1,584 @@ +# safe-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] + +[travis-image]: https://img.shields.io/travis/feross/safe-buffer/master.svg +[travis-url]: https://travis-ci.org/feross/safe-buffer +[npm-image]: https://img.shields.io/npm/v/safe-buffer.svg +[npm-url]: https://npmjs.org/package/safe-buffer +[downloads-image]: https://img.shields.io/npm/dm/safe-buffer.svg +[downloads-url]: https://npmjs.org/package/safe-buffer +[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg +[standard-url]: https://standardjs.com + +#### Safer Node.js Buffer API + +**Use the new Node.js Buffer APIs (`Buffer.from`, `Buffer.alloc`, +`Buffer.allocUnsafe`, `Buffer.allocUnsafeSlow`) in all versions of Node.js.** + +**Uses the built-in implementation when available.** + +## install + +``` +npm install safe-buffer +``` + +## usage + +The goal of this package is to provide a safe replacement for the node.js `Buffer`. + +It's a drop-in replacement for `Buffer`. You can use it by adding one `require` line to +the top of your node.js modules: + +```js +var Buffer = require('safe-buffer').Buffer + +// Existing buffer code will continue to work without issues: + +new Buffer('hey', 'utf8') +new Buffer([1, 2, 3], 'utf8') +new Buffer(obj) +new Buffer(16) // create an uninitialized buffer (potentially unsafe) + +// But you can use these new explicit APIs to make clear what you want: + +Buffer.from('hey', 'utf8') // convert from many types to a Buffer +Buffer.alloc(16) // create a zero-filled buffer (safe) +Buffer.allocUnsafe(16) // create an uninitialized buffer (potentially unsafe) +``` + +## api + +### Class Method: Buffer.from(array) + + +* `array` {Array} + +Allocates a new `Buffer` using an `array` of octets. + +```js +const buf = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]); + // creates a new Buffer containing ASCII bytes + // ['b','u','f','f','e','r'] +``` + +A `TypeError` will be thrown if `array` is not an `Array`. + +### Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) + + +* `arrayBuffer` {ArrayBuffer} The `.buffer` property of a `TypedArray` or + a `new ArrayBuffer()` +* `byteOffset` {Number} Default: `0` +* `length` {Number} 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. + +```js +const arr = new Uint16Array(2); +arr[0] = 5000; +arr[1] = 4000; + +const buf = Buffer.from(arr.buffer); // shares the memory with arr; + +console.log(buf); + // Prints: + +// changing the TypedArray changes the Buffer also +arr[1] = 6000; + +console.log(buf); + // Prints: +``` + +The optional `byteOffset` and `length` arguments specify a memory range within +the `arrayBuffer` that will be shared by the `Buffer`. + +```js +const ab = new ArrayBuffer(10); +const buf = Buffer.from(ab, 0, 2); +console.log(buf.length); + // Prints: 2 +``` + +A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer`. + +### Class Method: Buffer.from(buffer) + + +* `buffer` {Buffer} + +Copies the passed `buffer` data onto a new `Buffer` instance. + +```js +const buf1 = Buffer.from('buffer'); +const buf2 = Buffer.from(buf1); + +buf1[0] = 0x61; +console.log(buf1.toString()); + // 'auffer' +console.log(buf2.toString()); + // 'buffer' (copy is not changed) +``` + +A `TypeError` will be thrown if `buffer` is not a `Buffer`. + +### Class Method: Buffer.from(str[, encoding]) + + +* `str` {String} String to encode. +* `encoding` {String} Encoding to use, Default: `'utf8'` + +Creates a new `Buffer` containing the given JavaScript string `str`. If +provided, the `encoding` parameter identifies the character encoding. +If not provided, `encoding` defaults to `'utf8'`. + +```js +const buf1 = Buffer.from('this is a tést'); +console.log(buf1.toString()); + // prints: this is a tést +console.log(buf1.toString('ascii')); + // prints: this is a tC)st + +const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); +console.log(buf2.toString()); + // prints: this is a tést +``` + +A `TypeError` will be thrown if `str` is not a string. + +### Class Method: Buffer.alloc(size[, fill[, encoding]]) + + +* `size` {Number} +* `fill` {Value} Default: `undefined` +* `encoding` {String} Default: `utf8` + +Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the +`Buffer` will be *zero-filled*. + +```js +const buf = Buffer.alloc(5); +console.log(buf); + // +``` + +The `size` must be less than or equal to the value of +`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is +`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will +be created if a `size` less than or equal to 0 is specified. + +If `fill` is specified, the allocated `Buffer` will be initialized by calling +`buf.fill(fill)`. See [`buf.fill()`][] for more information. + +```js +const buf = Buffer.alloc(5, 'a'); +console.log(buf); + // +``` + +If both `fill` and `encoding` are specified, the allocated `Buffer` will be +initialized by calling `buf.fill(fill, encoding)`. For example: + +```js +const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); +console.log(buf); + // +``` + +Calling `Buffer.alloc(size)` can be significantly slower than the alternative +`Buffer.allocUnsafe(size)` but ensures that the newly created `Buffer` instance +contents will *never contain sensitive data*. + +A `TypeError` will be thrown if `size` is not a number. + +### Class Method: Buffer.allocUnsafe(size) + + +* `size` {Number} + +Allocates a new *non-zero-filled* `Buffer` of `size` bytes. The `size` must +be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit +architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is +thrown. A zero-length Buffer will be created if a `size` less than or equal to +0 is specified. + +The underlying memory for `Buffer` instances created in this way is *not +initialized*. The contents of the newly created `Buffer` are unknown and +*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such +`Buffer` instances to zeroes. + +```js +const buf = Buffer.allocUnsafe(5); +console.log(buf); + // + // (octets will be different, every time) +buf.fill(0); +console.log(buf); + // +``` + +A `TypeError` will be thrown if `size` is not a number. + +Note that the `Buffer` module pre-allocates an internal `Buffer` instance of +size `Buffer.poolSize` that is used as a pool for the fast allocation of new +`Buffer` instances created using `Buffer.allocUnsafe(size)` (and the deprecated +`new Buffer(size)` constructor) only when `size` is less than or equal to +`Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). The default +value of `Buffer.poolSize` is `8192` but can be modified. + +Use of this pre-allocated internal memory pool is a key difference between +calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. +Specifically, `Buffer.alloc(size, fill)` will *never* use the internal Buffer +pool, while `Buffer.allocUnsafe(size).fill(fill)` *will* use the internal +Buffer pool if `size` is less than or equal to half `Buffer.poolSize`. The +difference is subtle but can be important when an application requires the +additional performance that `Buffer.allocUnsafe(size)` provides. + +### Class Method: Buffer.allocUnsafeSlow(size) + + +* `size` {Number} + +Allocates a new *non-zero-filled* and non-pooled `Buffer` of `size` bytes. The +`size` must be less than or equal to the value of +`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is +`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will +be created if a `size` less than or equal to 0 is specified. + +The underlying memory for `Buffer` instances created in this way is *not +initialized*. The contents of the newly created `Buffer` are unknown and +*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such +`Buffer` instances to zeroes. + +When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, +allocations under 4KB are, by default, sliced from a single pre-allocated +`Buffer`. This allows applications to avoid the garbage collection overhead of +creating many individually allocated Buffers. This approach improves both +performance and memory usage by eliminating the need to track and cleanup as +many `Persistent` objects. + +However, in the case where a developer may need to retain a small chunk of +memory from a pool for an indeterminate amount of time, it may be appropriate +to create an un-pooled Buffer instance using `Buffer.allocUnsafeSlow()` then +copy out the relevant bits. + +```js +// need to keep around a few small chunks of memory +const store = []; + +socket.on('readable', () => { + const data = socket.read(); + // allocate for retained data + const sb = Buffer.allocUnsafeSlow(10); + // copy the data into the new allocation + data.copy(sb, 0, 0, 10); + store.push(sb); +}); +``` + +Use of `Buffer.allocUnsafeSlow()` should be used only as a last resort *after* +a developer has observed undue memory retention in their applications. + +A `TypeError` will be thrown if `size` is not a number. + +### All the Rest + +The rest of the `Buffer` API is exactly the same as in node.js. +[See the docs](https://nodejs.org/api/buffer.html). + + +## Related links + +- [Node.js issue: Buffer(number) is unsafe](https://github.com/nodejs/node/issues/4660) +- [Node.js Enhancement Proposal: Buffer.from/Buffer.alloc/Buffer.zalloc/Buffer() soft-deprecate](https://github.com/nodejs/node-eps/pull/4) + +## Why is `Buffer` unsafe? + +Today, the node.js `Buffer` constructor is overloaded to handle many different argument +types like `String`, `Array`, `Object`, `TypedArrayView` (`Uint8Array`, etc.), +`ArrayBuffer`, and also `Number`. + +The API is optimized for convenience: you can throw any type at it, and it will try to do +what you want. + +Because the Buffer constructor is so powerful, you often see code like this: + +```js +// Convert UTF-8 strings to hex +function toHex (str) { + return new Buffer(str).toString('hex') +} +``` + +***But what happens if `toHex` is called with a `Number` argument?*** + +### Remote Memory Disclosure + +If an attacker can make your program call the `Buffer` constructor with a `Number` +argument, then they can make it allocate uninitialized memory from the node.js process. +This could potentially disclose TLS private keys, user data, or database passwords. + +When the `Buffer` constructor is passed a `Number` argument, it returns an +**UNINITIALIZED** block of memory of the specified `size`. When you create a `Buffer` like +this, you **MUST** overwrite the contents before returning it to the user. + +From the [node.js docs](https://nodejs.org/api/buffer.html#buffer_new_buffer_size): + +> `new Buffer(size)` +> +> - `size` Number +> +> The underlying memory for `Buffer` instances created in this way is not initialized. +> **The contents of a newly created `Buffer` are unknown and could contain sensitive +> data.** Use `buf.fill(0)` to initialize a Buffer to zeroes. + +(Emphasis our own.) + +Whenever the programmer intended to create an uninitialized `Buffer` you often see code +like this: + +```js +var buf = new Buffer(16) + +// Immediately overwrite the uninitialized buffer with data from another buffer +for (var i = 0; i < buf.length; i++) { + buf[i] = otherBuf[i] +} +``` + + +### Would this ever be a problem in real code? + +Yes. It's surprisingly common to forget to check the type of your variables in a +dynamically-typed language like JavaScript. + +Usually the consequences of assuming the wrong type is that your program crashes with an +uncaught exception. But the failure mode for forgetting to check the type of arguments to +the `Buffer` constructor is more catastrophic. + +Here's an example of a vulnerable service that takes a JSON payload and converts it to +hex: + +```js +// Take a JSON payload {str: "some string"} and convert it to hex +var server = http.createServer(function (req, res) { + var data = '' + req.setEncoding('utf8') + req.on('data', function (chunk) { + data += chunk + }) + req.on('end', function () { + var body = JSON.parse(data) + res.end(new Buffer(body.str).toString('hex')) + }) +}) + +server.listen(8080) +``` + +In this example, an http client just has to send: + +```json +{ + "str": 1000 +} +``` + +and it will get back 1,000 bytes of uninitialized memory from the server. + +This is a very serious bug. It's similar in severity to the +[the Heartbleed bug](http://heartbleed.com/) that allowed disclosure of OpenSSL process +memory by remote attackers. + + +### Which real-world packages were vulnerable? + +#### [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht) + +[Mathias Buus](https://github.com/mafintosh) and I +([Feross Aboukhadijeh](http://feross.org/)) found this issue in one of our own packages, +[`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht). The bug would allow +anyone on the internet to send a series of messages to a user of `bittorrent-dht` and get +them to reveal 20 bytes at a time of uninitialized memory from the node.js process. + +Here's +[the commit](https://github.com/feross/bittorrent-dht/commit/6c7da04025d5633699800a99ec3fbadf70ad35b8) +that fixed it. We released a new fixed version, created a +[Node Security Project disclosure](https://nodesecurity.io/advisories/68), and deprecated all +vulnerable versions on npm so users will get a warning to upgrade to a newer version. + +#### [`ws`](https://www.npmjs.com/package/ws) + +That got us wondering if there were other vulnerable packages. Sure enough, within a short +period of time, we found the same issue in [`ws`](https://www.npmjs.com/package/ws), the +most popular WebSocket implementation in node.js. + +If certain APIs were called with `Number` parameters instead of `String` or `Buffer` as +expected, then uninitialized server memory would be disclosed to the remote peer. + +These were the vulnerable methods: + +```js +socket.send(number) +socket.ping(number) +socket.pong(number) +``` + +Here's a vulnerable socket server with some echo functionality: + +```js +server.on('connection', function (socket) { + socket.on('message', function (message) { + message = JSON.parse(message) + if (message.type === 'echo') { + socket.send(message.data) // send back the user's message + } + }) +}) +``` + +`socket.send(number)` called on the server, will disclose server memory. + +Here's [the release](https://github.com/websockets/ws/releases/tag/1.0.1) where the issue +was fixed, with a more detailed explanation. Props to +[Arnout Kazemier](https://github.com/3rd-Eden) for the quick fix. Here's the +[Node Security Project disclosure](https://nodesecurity.io/advisories/67). + + +### What's the solution? + +It's important that node.js offers a fast way to get memory otherwise performance-critical +applications would needlessly get a lot slower. + +But we need a better way to *signal our intent* as programmers. **When we want +uninitialized memory, we should request it explicitly.** + +Sensitive functionality should not be packed into a developer-friendly API that loosely +accepts many different types. This type of API encourages the lazy practice of passing +variables in without checking the type very carefully. + +#### A new API: `Buffer.allocUnsafe(number)` + +The functionality of creating buffers with uninitialized memory should be part of another +API. We propose `Buffer.allocUnsafe(number)`. This way, it's not part of an API that +frequently gets user input of all sorts of different types passed into it. + +```js +var buf = Buffer.allocUnsafe(16) // careful, uninitialized memory! + +// Immediately overwrite the uninitialized buffer with data from another buffer +for (var i = 0; i < buf.length; i++) { + buf[i] = otherBuf[i] +} +``` + + +### How do we fix node.js core? + +We sent [a PR to node.js core](https://github.com/nodejs/node/pull/4514) (merged as +`semver-major`) which defends against one case: + +```js +var str = 16 +new Buffer(str, 'utf8') +``` + +In this situation, it's implied that the programmer intended the first argument to be a +string, since they passed an encoding as a second argument. Today, node.js will allocate +uninitialized memory in the case of `new Buffer(number, encoding)`, which is probably not +what the programmer intended. + +But this is only a partial solution, since if the programmer does `new Buffer(variable)` +(without an `encoding` parameter) there's no way to know what they intended. If `variable` +is sometimes a number, then uninitialized memory will sometimes be returned. + +### What's the real long-term fix? + +We could deprecate and remove `new Buffer(number)` and use `Buffer.allocUnsafe(number)` when +we need uninitialized memory. But that would break 1000s of packages. + +~~We believe the best solution is to:~~ + +~~1. Change `new Buffer(number)` to return safe, zeroed-out memory~~ + +~~2. Create a new API for creating uninitialized Buffers. We propose: `Buffer.allocUnsafe(number)`~~ + +#### Update + +We now support adding three new APIs: + +- `Buffer.from(value)` - convert from any type to a buffer +- `Buffer.alloc(size)` - create a zero-filled buffer +- `Buffer.allocUnsafe(size)` - create an uninitialized buffer with given size + +This solves the core problem that affected `ws` and `bittorrent-dht` which is +`Buffer(variable)` getting tricked into taking a number argument. + +This way, existing code continues working and the impact on the npm ecosystem will be +minimal. Over time, npm maintainers can migrate performance-critical code to use +`Buffer.allocUnsafe(number)` instead of `new Buffer(number)`. + + +### Conclusion + +We think there's a serious design issue with the `Buffer` API as it exists today. It +promotes insecure software by putting high-risk functionality into a convenient API +with friendly "developer ergonomics". + +This wasn't merely a theoretical exercise because we found the issue in some of the +most popular npm packages. + +Fortunately, there's an easy fix that can be applied today. Use `safe-buffer` in place of +`buffer`. + +```js +var Buffer = require('safe-buffer').Buffer +``` + +Eventually, we hope that node.js core can switch to this new, safer behavior. We believe +the impact on the ecosystem would be minimal since it's not a breaking change. +Well-maintained, popular packages would be updated to use `Buffer.alloc` quickly, while +older, insecure packages would magically become safe from this attack vector. + + +## links + +- [Node.js PR: buffer: throw if both length and enc are passed](https://github.com/nodejs/node/pull/4514) +- [Node Security Project disclosure for `ws`](https://nodesecurity.io/advisories/67) +- [Node Security Project disclosure for`bittorrent-dht`](https://nodesecurity.io/advisories/68) + + +## credit + +The original issues in `bittorrent-dht` +([disclosure](https://nodesecurity.io/advisories/68)) and +`ws` ([disclosure](https://nodesecurity.io/advisories/67)) were discovered by +[Mathias Buus](https://github.com/mafintosh) and +[Feross Aboukhadijeh](http://feross.org/). + +Thanks to [Adam Baldwin](https://github.com/evilpacket) for helping disclose these issues +and for his work running the [Node Security Project](https://nodesecurity.io/). + +Thanks to [John Hiesey](https://github.com/jhiesey) for proofreading this README and +auditing the code. + + +## license + +MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org) diff --git a/backend/node_modules/string_decoder/node_modules/safe-buffer/index.d.ts b/backend/node_modules/string_decoder/node_modules/safe-buffer/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e9fed809a5ab515658d6e71f7ba5f631be769be4 --- /dev/null +++ b/backend/node_modules/string_decoder/node_modules/safe-buffer/index.d.ts @@ -0,0 +1,187 @@ +declare module "safe-buffer" { + export class Buffer { + length: number + write(string: string, offset?: number, length?: number, encoding?: string): number; + toString(encoding?: string, start?: number, end?: number): string; + toJSON(): { type: 'Buffer', data: any[] }; + equals(otherBuffer: Buffer): boolean; + compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; + copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + slice(start?: number, end?: number): Buffer; + writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readUInt8(offset: number, noAssert?: boolean): number; + readUInt16LE(offset: number, noAssert?: boolean): number; + readUInt16BE(offset: number, noAssert?: boolean): number; + readUInt32LE(offset: number, noAssert?: boolean): number; + readUInt32BE(offset: number, noAssert?: boolean): number; + readInt8(offset: number, noAssert?: boolean): number; + readInt16LE(offset: number, noAssert?: boolean): number; + readInt16BE(offset: number, noAssert?: boolean): number; + readInt32LE(offset: number, noAssert?: boolean): number; + readInt32BE(offset: number, noAssert?: boolean): number; + readFloatLE(offset: number, noAssert?: boolean): number; + readFloatBE(offset: number, noAssert?: boolean): number; + readDoubleLE(offset: number, noAssert?: boolean): number; + readDoubleBE(offset: number, noAssert?: boolean): number; + swap16(): Buffer; + swap32(): Buffer; + swap64(): Buffer; + writeUInt8(value: number, offset: number, noAssert?: boolean): number; + writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeInt8(value: number, offset: number, noAssert?: boolean): number; + writeInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeFloatLE(value: number, offset: number, noAssert?: boolean): number; + writeFloatBE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; + fill(value: any, offset?: number, end?: number): this; + indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; + + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + */ + constructor (str: string, encoding?: string); + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + */ + constructor (size: number); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + constructor (array: Uint8Array); + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}. + * + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + */ + constructor (arrayBuffer: ArrayBuffer); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + constructor (array: any[]); + /** + * Copies the passed {buffer} data onto a new {Buffer} instance. + * + * @param buffer The buffer to copy. + */ + constructor (buffer: Buffer); + prototype: Buffer; + /** + * Allocates a new Buffer using an {array} of octets. + * + * @param array + */ + static from(array: any[]): Buffer; + /** + * 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. + * + * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer() + * @param byteOffset + * @param length + */ + static from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer; + /** + * Copies the passed {buffer} data onto a new Buffer instance. + * + * @param buffer + */ + static from(buffer: Buffer): Buffer; + /** + * Creates a new Buffer containing the given JavaScript string {str}. + * If provided, the {encoding} parameter identifies the character encoding. + * If not provided, {encoding} defaults to 'utf8'. + * + * @param str + */ + static from(str: string, encoding?: string): Buffer; + /** + * Returns true if {obj} is a Buffer + * + * @param obj object to test. + */ + static isBuffer(obj: any): obj is Buffer; + /** + * Returns true if {encoding} is a valid encoding argument. + * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' + * + * @param encoding string to test. + */ + static isEncoding(encoding: string): boolean; + /** + * Gives the actual byte length of a string. encoding defaults to 'utf8'. + * This is not the same as String.prototype.length since that returns the number of characters in a string. + * + * @param string string to test. + * @param encoding encoding used to evaluate (defaults to 'utf8') + */ + static byteLength(string: string, encoding?: string): number; + /** + * Returns a buffer which is the result of concatenating all the buffers in the list together. + * + * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. + * If the list has exactly one item, then the first item of the list is returned. + * If the list has more than one item, then a new Buffer is created. + * + * @param list An array of Buffer objects to concatenate + * @param totalLength Total length of the buffers when concatenated. + * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. + */ + static concat(list: Buffer[], totalLength?: number): Buffer; + /** + * The same as buf1.compare(buf2). + */ + static compare(buf1: Buffer, buf2: Buffer): number; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @param fill if specified, buffer will be initialized by calling buf.fill(fill). + * If parameter is omitted, buffer will be filled with zeros. + * @param encoding encoding used for call to buf.fill while initalizing + */ + static alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer; + /** + * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + static allocUnsafe(size: number): Buffer; + /** + * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + static allocUnsafeSlow(size: number): Buffer; + } +} \ No newline at end of file diff --git a/backend/node_modules/string_decoder/node_modules/safe-buffer/index.js b/backend/node_modules/string_decoder/node_modules/safe-buffer/index.js new file mode 100644 index 0000000000000000000000000000000000000000..22438dabbbceef6954a1a7a68038f8c440a90c79 --- /dev/null +++ b/backend/node_modules/string_decoder/node_modules/safe-buffer/index.js @@ -0,0 +1,62 @@ +/* eslint-disable node/no-deprecated-api */ +var buffer = require('buffer') +var Buffer = buffer.Buffer + +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] + } +} +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer +} + +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) +} + +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) + +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + } else { + buf.fill(0) + } + return buf +} + +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +} + +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} diff --git a/backend/node_modules/string_decoder/node_modules/safe-buffer/package.json b/backend/node_modules/string_decoder/node_modules/safe-buffer/package.json new file mode 100644 index 0000000000000000000000000000000000000000..623fbc3f6b0c480fb0b3257fc666b1db827378bf --- /dev/null +++ b/backend/node_modules/string_decoder/node_modules/safe-buffer/package.json @@ -0,0 +1,37 @@ +{ + "name": "safe-buffer", + "description": "Safer Node.js Buffer API", + "version": "5.1.2", + "author": { + "name": "Feross Aboukhadijeh", + "email": "feross@feross.org", + "url": "http://feross.org" + }, + "bugs": { + "url": "https://github.com/feross/safe-buffer/issues" + }, + "devDependencies": { + "standard": "*", + "tape": "^4.0.0" + }, + "homepage": "https://github.com/feross/safe-buffer", + "keywords": [ + "buffer", + "buffer allocate", + "node security", + "safe", + "safe-buffer", + "security", + "uninitialized" + ], + "license": "MIT", + "main": "index.js", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "git://github.com/feross/safe-buffer.git" + }, + "scripts": { + "test": "standard && tape test/*.js" + } +} diff --git a/backend/node_modules/string_decoder/package.json b/backend/node_modules/string_decoder/package.json new file mode 100644 index 0000000000000000000000000000000000000000..518c3eb9fb1ffbf72bfdf6fed252117b73164673 --- /dev/null +++ b/backend/node_modules/string_decoder/package.json @@ -0,0 +1,31 @@ +{ + "name": "string_decoder", + "version": "1.1.1", + "description": "The string_decoder module from Node core", + "main": "lib/string_decoder.js", + "dependencies": { + "safe-buffer": "~5.1.0" + }, + "devDependencies": { + "babel-polyfill": "^6.23.0", + "core-util-is": "^1.0.2", + "inherits": "^2.0.3", + "tap": "~0.4.8" + }, + "scripts": { + "test": "tap test/parallel/*.js && node test/verify-dependencies", + "ci": "tap test/parallel/*.js test/ours/*.js --tap | tee test.tap && node test/verify-dependencies.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/nodejs/string_decoder.git" + }, + "homepage": "https://github.com/nodejs/string_decoder", + "keywords": [ + "string", + "decoder", + "browser", + "browserify" + ], + "license": "MIT" +} diff --git a/backend/node_modules/toidentifier/HISTORY.md b/backend/node_modules/toidentifier/HISTORY.md new file mode 100644 index 0000000000000000000000000000000000000000..cb7cc8927a64ac5d213480e3fba1b0d3dcbba3f6 --- /dev/null +++ b/backend/node_modules/toidentifier/HISTORY.md @@ -0,0 +1,9 @@ +1.0.1 / 2021-11-14 +================== + + * pref: enable strict mode + +1.0.0 / 2018-07-09 +================== + + * Initial release diff --git a/backend/node_modules/toidentifier/LICENSE b/backend/node_modules/toidentifier/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..de22d1597600c04a9a62ffa597463413baf741fb --- /dev/null +++ b/backend/node_modules/toidentifier/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2016 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/backend/node_modules/toidentifier/README.md b/backend/node_modules/toidentifier/README.md new file mode 100644 index 0000000000000000000000000000000000000000..57e8a78ab5218e7d424eabde5b6865997a14f500 --- /dev/null +++ b/backend/node_modules/toidentifier/README.md @@ -0,0 +1,61 @@ +# toidentifier + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Build Status][github-actions-ci-image]][github-actions-ci-url] +[![Test Coverage][codecov-image]][codecov-url] + +> Convert a string of words to a JavaScript identifier + +## Install + +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 toidentifier +``` + +## Example + +```js +var toIdentifier = require('toidentifier') + +console.log(toIdentifier('Bad Request')) +// => "BadRequest" +``` + +## API + +This CommonJS module exports a single default function: `toIdentifier`. + +### toIdentifier(string) + +Given a string as the argument, it will be transformed according to +the following rules and the new string will be returned: + +1. Split into words separated by space characters (`0x20`). +2. Upper case the first character of each word. +3. Join the words together with no separator. +4. Remove all non-word (`[0-9a-z_]`) characters. + +## License + +[MIT](LICENSE) + +[codecov-image]: https://img.shields.io/codecov/c/github/component/toidentifier.svg +[codecov-url]: https://codecov.io/gh/component/toidentifier +[downloads-image]: https://img.shields.io/npm/dm/toidentifier.svg +[downloads-url]: https://npmjs.org/package/toidentifier +[github-actions-ci-image]: https://img.shields.io/github/workflow/status/component/toidentifier/ci/master?label=ci +[github-actions-ci-url]: https://github.com/component/toidentifier?query=workflow%3Aci +[npm-image]: https://img.shields.io/npm/v/toidentifier.svg +[npm-url]: https://npmjs.org/package/toidentifier + + +## + +[npm]: https://www.npmjs.com/ + +[yarn]: https://yarnpkg.com/ diff --git a/backend/node_modules/toidentifier/index.js b/backend/node_modules/toidentifier/index.js new file mode 100644 index 0000000000000000000000000000000000000000..9295d024a8c94ee27b3e2b437769599ac5f2b65d --- /dev/null +++ b/backend/node_modules/toidentifier/index.js @@ -0,0 +1,32 @@ +/*! + * toidentifier + * Copyright(c) 2016 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = toIdentifier + +/** + * Trasform the given string into a JavaScript identifier + * + * @param {string} str + * @returns {string} + * @public + */ + +function toIdentifier (str) { + return str + .split(' ') + .map(function (token) { + return token.slice(0, 1).toUpperCase() + token.slice(1) + }) + .join('') + .replace(/[^ _0-9a-z]/gi, '') +} diff --git a/backend/node_modules/toidentifier/package.json b/backend/node_modules/toidentifier/package.json new file mode 100644 index 0000000000000000000000000000000000000000..42db1a664264217f0b57017aba9c6d05e3d8f827 --- /dev/null +++ b/backend/node_modules/toidentifier/package.json @@ -0,0 +1,38 @@ +{ + "name": "toidentifier", + "description": "Convert a string of words to a JavaScript identifier", + "version": "1.0.1", + "author": "Douglas Christopher Wilson ", + "contributors": [ + "Douglas Christopher Wilson ", + "Nick Baugh (http://niftylettuce.com/)" + ], + "repository": "component/toidentifier", + "devDependencies": { + "eslint": "7.32.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.25.3", + "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.1.3", + "nyc": "15.1.0" + }, + "engines": { + "node": ">=0.6" + }, + "license": "MIT", + "files": [ + "HISTORY.md", + "LICENSE", + "index.js" + ], + "scripts": { + "lint": "eslint .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-ci": "nyc --reporter=lcov --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/backend/node_modules/tr46/.npmignore b/backend/node_modules/tr46/.npmignore new file mode 100644 index 0000000000000000000000000000000000000000..96e9161fde31e9906718f689d5cc135e507a51e1 --- /dev/null +++ b/backend/node_modules/tr46/.npmignore @@ -0,0 +1,4 @@ +scripts/ +test/ + +!lib/mapping_table.json diff --git a/backend/node_modules/tr46/index.js b/backend/node_modules/tr46/index.js new file mode 100644 index 0000000000000000000000000000000000000000..9ce12ca2d026fa202f7a0d32e0a7c8526660ed78 --- /dev/null +++ b/backend/node_modules/tr46/index.js @@ -0,0 +1,193 @@ +"use strict"; + +var punycode = require("punycode"); +var mappingTable = require("./lib/mappingTable.json"); + +var PROCESSING_OPTIONS = { + TRANSITIONAL: 0, + NONTRANSITIONAL: 1 +}; + +function normalize(str) { // fix bug in v8 + return str.split('\u0000').map(function (s) { return s.normalize('NFC'); }).join('\u0000'); +} + +function findStatus(val) { + var start = 0; + var end = mappingTable.length - 1; + + while (start <= end) { + var mid = Math.floor((start + end) / 2); + + var target = mappingTable[mid]; + if (target[0][0] <= val && target[0][1] >= val) { + return target; + } else if (target[0][0] > val) { + end = mid - 1; + } else { + start = mid + 1; + } + } + + return null; +} + +var regexAstralSymbols = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g; + +function countSymbols(string) { + return string + // replace every surrogate pair with a BMP symbol + .replace(regexAstralSymbols, '_') + // then get the length + .length; +} + +function mapChars(domain_name, useSTD3, processing_option) { + var hasError = false; + var processed = ""; + + var len = countSymbols(domain_name); + for (var i = 0; i < len; ++i) { + var codePoint = domain_name.codePointAt(i); + var status = findStatus(codePoint); + + switch (status[1]) { + case "disallowed": + hasError = true; + processed += String.fromCodePoint(codePoint); + break; + case "ignored": + break; + case "mapped": + processed += String.fromCodePoint.apply(String, status[2]); + break; + case "deviation": + if (processing_option === PROCESSING_OPTIONS.TRANSITIONAL) { + processed += String.fromCodePoint.apply(String, status[2]); + } else { + processed += String.fromCodePoint(codePoint); + } + break; + case "valid": + processed += String.fromCodePoint(codePoint); + break; + case "disallowed_STD3_mapped": + if (useSTD3) { + hasError = true; + processed += String.fromCodePoint(codePoint); + } else { + processed += String.fromCodePoint.apply(String, status[2]); + } + break; + case "disallowed_STD3_valid": + if (useSTD3) { + hasError = true; + } + + processed += String.fromCodePoint(codePoint); + break; + } + } + + return { + string: processed, + error: hasError + }; +} + +var combiningMarksRegex = /[\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08E4-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C03\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D01-\u0D03\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u18A9\u1920-\u192B\u1930-\u193B\u19B0-\u19C0\u19C8\u19C9\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF5\u1DFC-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C4\uA8E0-\uA8F1\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2D]|\uD800[\uDDFD\uDEE0\uDF76-\uDF7A]|\uD802[\uDE01-\uDE03\uDE05\uDE06\uDE0C-\uDE0F\uDE38-\uDE3A\uDE3F\uDEE5\uDEE6]|\uD804[\uDC00-\uDC02\uDC38-\uDC46\uDC7F-\uDC82\uDCB0-\uDCBA\uDD00-\uDD02\uDD27-\uDD34\uDD73\uDD80-\uDD82\uDDB3-\uDDC0\uDE2C-\uDE37\uDEDF-\uDEEA\uDF01-\uDF03\uDF3C\uDF3E-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF57\uDF62\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDCB0-\uDCC3\uDDAF-\uDDB5\uDDB8-\uDDC0\uDE30-\uDE40\uDEAB-\uDEB7]|\uD81A[\uDEF0-\uDEF4\uDF30-\uDF36]|\uD81B[\uDF51-\uDF7E\uDF8F-\uDF92]|\uD82F[\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD83A[\uDCD0-\uDCD6]|\uDB40[\uDD00-\uDDEF]/; + +function validateLabel(label, processing_option) { + if (label.substr(0, 4) === "xn--") { + label = punycode.toUnicode(label); + processing_option = PROCESSING_OPTIONS.NONTRANSITIONAL; + } + + var error = false; + + if (normalize(label) !== label || + (label[3] === "-" && label[4] === "-") || + label[0] === "-" || label[label.length - 1] === "-" || + label.indexOf(".") !== -1 || + label.search(combiningMarksRegex) === 0) { + error = true; + } + + var len = countSymbols(label); + for (var i = 0; i < len; ++i) { + var status = findStatus(label.codePointAt(i)); + if ((processing === PROCESSING_OPTIONS.TRANSITIONAL && status[1] !== "valid") || + (processing === PROCESSING_OPTIONS.NONTRANSITIONAL && + status[1] !== "valid" && status[1] !== "deviation")) { + error = true; + break; + } + } + + return { + label: label, + error: error + }; +} + +function processing(domain_name, useSTD3, processing_option) { + var result = mapChars(domain_name, useSTD3, processing_option); + result.string = normalize(result.string); + + var labels = result.string.split("."); + for (var i = 0; i < labels.length; ++i) { + try { + var validation = validateLabel(labels[i]); + labels[i] = validation.label; + result.error = result.error || validation.error; + } catch(e) { + result.error = true; + } + } + + return { + string: labels.join("."), + error: result.error + }; +} + +module.exports.toASCII = function(domain_name, useSTD3, processing_option, verifyDnsLength) { + var result = processing(domain_name, useSTD3, processing_option); + var labels = result.string.split("."); + labels = labels.map(function(l) { + try { + return punycode.toASCII(l); + } catch(e) { + result.error = true; + return l; + } + }); + + if (verifyDnsLength) { + var total = labels.slice(0, labels.length - 1).join(".").length; + if (total.length > 253 || total.length === 0) { + result.error = true; + } + + for (var i=0; i < labels.length; ++i) { + if (labels.length > 63 || labels.length === 0) { + result.error = true; + break; + } + } + } + + if (result.error) return null; + return labels.join("."); +}; + +module.exports.toUnicode = function(domain_name, useSTD3) { + var result = processing(domain_name, useSTD3, PROCESSING_OPTIONS.NONTRANSITIONAL); + + return { + domain: result.string, + error: result.error + }; +}; + +module.exports.PROCESSING_OPTIONS = PROCESSING_OPTIONS; diff --git a/backend/node_modules/tr46/lib/.gitkeep b/backend/node_modules/tr46/lib/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/backend/node_modules/tr46/lib/mappingTable.json b/backend/node_modules/tr46/lib/mappingTable.json new file mode 100644 index 0000000000000000000000000000000000000000..89cf19a74072fb71a9865e0efc6588ba56cdab3f --- /dev/null +++ b/backend/node_modules/tr46/lib/mappingTable.json @@ -0,0 +1 @@ +[[[0,44],"disallowed_STD3_valid"],[[45,46],"valid"],[[47,47],"disallowed_STD3_valid"],[[48,57],"valid"],[[58,64],"disallowed_STD3_valid"],[[65,65],"mapped",[97]],[[66,66],"mapped",[98]],[[67,67],"mapped",[99]],[[68,68],"mapped",[100]],[[69,69],"mapped",[101]],[[70,70],"mapped",[102]],[[71,71],"mapped",[103]],[[72,72],"mapped",[104]],[[73,73],"mapped",[105]],[[74,74],"mapped",[106]],[[75,75],"mapped",[107]],[[76,76],"mapped",[108]],[[77,77],"mapped",[109]],[[78,78],"mapped",[110]],[[79,79],"mapped",[111]],[[80,80],"mapped",[112]],[[81,81],"mapped",[113]],[[82,82],"mapped",[114]],[[83,83],"mapped",[115]],[[84,84],"mapped",[116]],[[85,85],"mapped",[117]],[[86,86],"mapped",[118]],[[87,87],"mapped",[119]],[[88,88],"mapped",[120]],[[89,89],"mapped",[121]],[[90,90],"mapped",[122]],[[91,96],"disallowed_STD3_valid"],[[97,122],"valid"],[[123,127],"disallowed_STD3_valid"],[[128,159],"disallowed"],[[160,160],"disallowed_STD3_mapped",[32]],[[161,167],"valid",[],"NV8"],[[168,168],"disallowed_STD3_mapped",[32,776]],[[169,169],"valid",[],"NV8"],[[170,170],"mapped",[97]],[[171,172],"valid",[],"NV8"],[[173,173],"ignored"],[[174,174],"valid",[],"NV8"],[[175,175],"disallowed_STD3_mapped",[32,772]],[[176,177],"valid",[],"NV8"],[[178,178],"mapped",[50]],[[179,179],"mapped",[51]],[[180,180],"disallowed_STD3_mapped",[32,769]],[[181,181],"mapped",[956]],[[182,182],"valid",[],"NV8"],[[183,183],"valid"],[[184,184],"disallowed_STD3_mapped",[32,807]],[[185,185],"mapped",[49]],[[186,186],"mapped",[111]],[[187,187],"valid",[],"NV8"],[[188,188],"mapped",[49,8260,52]],[[189,189],"mapped",[49,8260,50]],[[190,190],"mapped",[51,8260,52]],[[191,191],"valid",[],"NV8"],[[192,192],"mapped",[224]],[[193,193],"mapped",[225]],[[194,194],"mapped",[226]],[[195,195],"mapped",[227]],[[196,196],"mapped",[228]],[[197,197],"mapped",[229]],[[198,198],"mapped",[230]],[[199,199],"mapped",[231]],[[200,200],"mapped",[232]],[[201,201],"mapped",[233]],[[202,202],"mapped",[234]],[[203,203],"mapped",[235]],[[204,204],"mapped",[236]],[[205,205],"mapped",[237]],[[206,206],"mapped",[238]],[[207,207],"mapped",[239]],[[208,208],"mapped",[240]],[[209,209],"mapped",[241]],[[210,210],"mapped",[242]],[[211,211],"mapped",[243]],[[212,212],"mapped",[244]],[[213,213],"mapped",[245]],[[214,214],"mapped",[246]],[[215,215],"valid",[],"NV8"],[[216,216],"mapped",[248]],[[217,217],"mapped",[249]],[[218,218],"mapped",[250]],[[219,219],"mapped",[251]],[[220,220],"mapped",[252]],[[221,221],"mapped",[253]],[[222,222],"mapped",[254]],[[223,223],"deviation",[115,115]],[[224,246],"valid"],[[247,247],"valid",[],"NV8"],[[248,255],"valid"],[[256,256],"mapped",[257]],[[257,257],"valid"],[[258,258],"mapped",[259]],[[259,259],"valid"],[[260,260],"mapped",[261]],[[261,261],"valid"],[[262,262],"mapped",[263]],[[263,263],"valid"],[[264,264],"mapped",[265]],[[265,265],"valid"],[[266,266],"mapped",[267]],[[267,267],"valid"],[[268,268],"mapped",[269]],[[269,269],"valid"],[[270,270],"mapped",[271]],[[271,271],"valid"],[[272,272],"mapped",[273]],[[273,273],"valid"],[[274,274],"mapped",[275]],[[275,275],"valid"],[[276,276],"mapped",[277]],[[277,277],"valid"],[[278,278],"mapped",[279]],[[279,279],"valid"],[[280,280],"mapped",[281]],[[281,281],"valid"],[[282,282],"mapped",[283]],[[283,283],"valid"],[[284,284],"mapped",[285]],[[285,285],"valid"],[[286,286],"mapped",[287]],[[287,287],"valid"],[[288,288],"mapped",[289]],[[289,289],"valid"],[[290,290],"mapped",[291]],[[291,291],"valid"],[[292,292],"mapped",[293]],[[293,293],"valid"],[[294,294],"mapped",[295]],[[295,295],"valid"],[[296,296],"mapped",[297]],[[297,297],"valid"],[[298,298],"mapped",[299]],[[299,299],"valid"],[[300,300],"mapped",[301]],[[301,301],"valid"],[[302,302],"mapped",[303]],[[303,303],"valid"],[[304,304],"mapped",[105,775]],[[305,305],"valid"],[[306,307],"mapped",[105,106]],[[308,308],"mapped",[309]],[[309,309],"valid"],[[310,310],"mapped",[311]],[[311,312],"valid"],[[313,313],"mapped",[314]],[[314,314],"valid"],[[315,315],"mapped",[316]],[[316,316],"valid"],[[317,317],"mapped",[318]],[[318,318],"valid"],[[319,320],"mapped",[108,183]],[[321,321],"mapped",[322]],[[322,322],"valid"],[[323,323],"mapped",[324]],[[324,324],"valid"],[[325,325],"mapped",[326]],[[326,326],"valid"],[[327,327],"mapped",[328]],[[328,328],"valid"],[[329,329],"mapped",[700,110]],[[330,330],"mapped",[331]],[[331,331],"valid"],[[332,332],"mapped",[333]],[[333,333],"valid"],[[334,334],"mapped",[335]],[[335,335],"valid"],[[336,336],"mapped",[337]],[[337,337],"valid"],[[338,338],"mapped",[339]],[[339,339],"valid"],[[340,340],"mapped",[341]],[[341,341],"valid"],[[342,342],"mapped",[343]],[[343,343],"valid"],[[344,344],"mapped",[345]],[[345,345],"valid"],[[346,346],"mapped",[347]],[[347,347],"valid"],[[348,348],"mapped",[349]],[[349,349],"valid"],[[350,350],"mapped",[351]],[[351,351],"valid"],[[352,352],"mapped",[353]],[[353,353],"valid"],[[354,354],"mapped",[355]],[[355,355],"valid"],[[356,356],"mapped",[357]],[[357,357],"valid"],[[358,358],"mapped",[359]],[[359,359],"valid"],[[360,360],"mapped",[361]],[[361,361],"valid"],[[362,362],"mapped",[363]],[[363,363],"valid"],[[364,364],"mapped",[365]],[[365,365],"valid"],[[366,366],"mapped",[367]],[[367,367],"valid"],[[368,368],"mapped",[369]],[[369,369],"valid"],[[370,370],"mapped",[371]],[[371,371],"valid"],[[372,372],"mapped",[373]],[[373,373],"valid"],[[374,374],"mapped",[375]],[[375,375],"valid"],[[376,376],"mapped",[255]],[[377,377],"mapped",[378]],[[378,378],"valid"],[[379,379],"mapped",[380]],[[380,380],"valid"],[[381,381],"mapped",[382]],[[382,382],"valid"],[[383,383],"mapped",[115]],[[384,384],"valid"],[[385,385],"mapped",[595]],[[386,386],"mapped",[387]],[[387,387],"valid"],[[388,388],"mapped",[389]],[[389,389],"valid"],[[390,390],"mapped",[596]],[[391,391],"mapped",[392]],[[392,392],"valid"],[[393,393],"mapped",[598]],[[394,394],"mapped",[599]],[[395,395],"mapped",[396]],[[396,397],"valid"],[[398,398],"mapped",[477]],[[399,399],"mapped",[601]],[[400,400],"mapped",[603]],[[401,401],"mapped",[402]],[[402,402],"valid"],[[403,403],"mapped",[608]],[[404,404],"mapped",[611]],[[405,405],"valid"],[[406,406],"mapped",[617]],[[407,407],"mapped",[616]],[[408,408],"mapped",[409]],[[409,411],"valid"],[[412,412],"mapped",[623]],[[413,413],"mapped",[626]],[[414,414],"valid"],[[415,415],"mapped",[629]],[[416,416],"mapped",[417]],[[417,417],"valid"],[[418,418],"mapped",[419]],[[419,419],"valid"],[[420,420],"mapped",[421]],[[421,421],"valid"],[[422,422],"mapped",[640]],[[423,423],"mapped",[424]],[[424,424],"valid"],[[425,425],"mapped",[643]],[[426,427],"valid"],[[428,428],"mapped",[429]],[[429,429],"valid"],[[430,430],"mapped",[648]],[[431,431],"mapped",[432]],[[432,432],"valid"],[[433,433],"mapped",[650]],[[434,434],"mapped",[651]],[[435,435],"mapped",[436]],[[436,436],"valid"],[[437,437],"mapped",[438]],[[438,438],"valid"],[[439,439],"mapped",[658]],[[440,440],"mapped",[441]],[[441,443],"valid"],[[444,444],"mapped",[445]],[[445,451],"valid"],[[452,454],"mapped",[100,382]],[[455,457],"mapped",[108,106]],[[458,460],"mapped",[110,106]],[[461,461],"mapped",[462]],[[462,462],"valid"],[[463,463],"mapped",[464]],[[464,464],"valid"],[[465,465],"mapped",[466]],[[466,466],"valid"],[[467,467],"mapped",[468]],[[468,468],"valid"],[[469,469],"mapped",[470]],[[470,470],"valid"],[[471,471],"mapped",[472]],[[472,472],"valid"],[[473,473],"mapped",[474]],[[474,474],"valid"],[[475,475],"mapped",[476]],[[476,477],"valid"],[[478,478],"mapped",[479]],[[479,479],"valid"],[[480,480],"mapped",[481]],[[481,481],"valid"],[[482,482],"mapped",[483]],[[483,483],"valid"],[[484,484],"mapped",[485]],[[485,485],"valid"],[[486,486],"mapped",[487]],[[487,487],"valid"],[[488,488],"mapped",[489]],[[489,489],"valid"],[[490,490],"mapped",[491]],[[491,491],"valid"],[[492,492],"mapped",[493]],[[493,493],"valid"],[[494,494],"mapped",[495]],[[495,496],"valid"],[[497,499],"mapped",[100,122]],[[500,500],"mapped",[501]],[[501,501],"valid"],[[502,502],"mapped",[405]],[[503,503],"mapped",[447]],[[504,504],"mapped",[505]],[[505,505],"valid"],[[506,506],"mapped",[507]],[[507,507],"valid"],[[508,508],"mapped",[509]],[[509,509],"valid"],[[510,510],"mapped",[511]],[[511,511],"valid"],[[512,512],"mapped",[513]],[[513,513],"valid"],[[514,514],"mapped",[515]],[[515,515],"valid"],[[516,516],"mapped",[517]],[[517,517],"valid"],[[518,518],"mapped",[519]],[[519,519],"valid"],[[520,520],"mapped",[521]],[[521,521],"valid"],[[522,522],"mapped",[523]],[[523,523],"valid"],[[524,524],"mapped",[525]],[[525,525],"valid"],[[526,526],"mapped",[527]],[[527,527],"valid"],[[528,528],"mapped",[529]],[[529,529],"valid"],[[530,530],"mapped",[531]],[[531,531],"valid"],[[532,532],"mapped",[533]],[[533,533],"valid"],[[534,534],"mapped",[535]],[[535,535],"valid"],[[536,536],"mapped",[537]],[[537,537],"valid"],[[538,538],"mapped",[539]],[[539,539],"valid"],[[540,540],"mapped",[541]],[[541,541],"valid"],[[542,542],"mapped",[543]],[[543,543],"valid"],[[544,544],"mapped",[414]],[[545,545],"valid"],[[546,546],"mapped",[547]],[[547,547],"valid"],[[548,548],"mapped",[549]],[[549,549],"valid"],[[550,550],"mapped",[551]],[[551,551],"valid"],[[552,552],"mapped",[553]],[[553,553],"valid"],[[554,554],"mapped",[555]],[[555,555],"valid"],[[556,556],"mapped",[557]],[[557,557],"valid"],[[558,558],"mapped",[559]],[[559,559],"valid"],[[560,560],"mapped",[561]],[[561,561],"valid"],[[562,562],"mapped",[563]],[[563,563],"valid"],[[564,566],"valid"],[[567,569],"valid"],[[570,570],"mapped",[11365]],[[571,571],"mapped",[572]],[[572,572],"valid"],[[573,573],"mapped",[410]],[[574,574],"mapped",[11366]],[[575,576],"valid"],[[577,577],"mapped",[578]],[[578,578],"valid"],[[579,579],"mapped",[384]],[[580,580],"mapped",[649]],[[581,581],"mapped",[652]],[[582,582],"mapped",[583]],[[583,583],"valid"],[[584,584],"mapped",[585]],[[585,585],"valid"],[[586,586],"mapped",[587]],[[587,587],"valid"],[[588,588],"mapped",[589]],[[589,589],"valid"],[[590,590],"mapped",[591]],[[591,591],"valid"],[[592,680],"valid"],[[681,685],"valid"],[[686,687],"valid"],[[688,688],"mapped",[104]],[[689,689],"mapped",[614]],[[690,690],"mapped",[106]],[[691,691],"mapped",[114]],[[692,692],"mapped",[633]],[[693,693],"mapped",[635]],[[694,694],"mapped",[641]],[[695,695],"mapped",[119]],[[696,696],"mapped",[121]],[[697,705],"valid"],[[706,709],"valid",[],"NV8"],[[710,721],"valid"],[[722,727],"valid",[],"NV8"],[[728,728],"disallowed_STD3_mapped",[32,774]],[[729,729],"disallowed_STD3_mapped",[32,775]],[[730,730],"disallowed_STD3_mapped",[32,778]],[[731,731],"disallowed_STD3_mapped",[32,808]],[[732,732],"disallowed_STD3_mapped",[32,771]],[[733,733],"disallowed_STD3_mapped",[32,779]],[[734,734],"valid",[],"NV8"],[[735,735],"valid",[],"NV8"],[[736,736],"mapped",[611]],[[737,737],"mapped",[108]],[[738,738],"mapped",[115]],[[739,739],"mapped",[120]],[[740,740],"mapped",[661]],[[741,745],"valid",[],"NV8"],[[746,747],"valid",[],"NV8"],[[748,748],"valid"],[[749,749],"valid",[],"NV8"],[[750,750],"valid"],[[751,767],"valid",[],"NV8"],[[768,831],"valid"],[[832,832],"mapped",[768]],[[833,833],"mapped",[769]],[[834,834],"valid"],[[835,835],"mapped",[787]],[[836,836],"mapped",[776,769]],[[837,837],"mapped",[953]],[[838,846],"valid"],[[847,847],"ignored"],[[848,855],"valid"],[[856,860],"valid"],[[861,863],"valid"],[[864,865],"valid"],[[866,866],"valid"],[[867,879],"valid"],[[880,880],"mapped",[881]],[[881,881],"valid"],[[882,882],"mapped",[883]],[[883,883],"valid"],[[884,884],"mapped",[697]],[[885,885],"valid"],[[886,886],"mapped",[887]],[[887,887],"valid"],[[888,889],"disallowed"],[[890,890],"disallowed_STD3_mapped",[32,953]],[[891,893],"valid"],[[894,894],"disallowed_STD3_mapped",[59]],[[895,895],"mapped",[1011]],[[896,899],"disallowed"],[[900,900],"disallowed_STD3_mapped",[32,769]],[[901,901],"disallowed_STD3_mapped",[32,776,769]],[[902,902],"mapped",[940]],[[903,903],"mapped",[183]],[[904,904],"mapped",[941]],[[905,905],"mapped",[942]],[[906,906],"mapped",[943]],[[907,907],"disallowed"],[[908,908],"mapped",[972]],[[909,909],"disallowed"],[[910,910],"mapped",[973]],[[911,911],"mapped",[974]],[[912,912],"valid"],[[913,913],"mapped",[945]],[[914,914],"mapped",[946]],[[915,915],"mapped",[947]],[[916,916],"mapped",[948]],[[917,917],"mapped",[949]],[[918,918],"mapped",[950]],[[919,919],"mapped",[951]],[[920,920],"mapped",[952]],[[921,921],"mapped",[953]],[[922,922],"mapped",[954]],[[923,923],"mapped",[955]],[[924,924],"mapped",[956]],[[925,925],"mapped",[957]],[[926,926],"mapped",[958]],[[927,927],"mapped",[959]],[[928,928],"mapped",[960]],[[929,929],"mapped",[961]],[[930,930],"disallowed"],[[931,931],"mapped",[963]],[[932,932],"mapped",[964]],[[933,933],"mapped",[965]],[[934,934],"mapped",[966]],[[935,935],"mapped",[967]],[[936,936],"mapped",[968]],[[937,937],"mapped",[969]],[[938,938],"mapped",[970]],[[939,939],"mapped",[971]],[[940,961],"valid"],[[962,962],"deviation",[963]],[[963,974],"valid"],[[975,975],"mapped",[983]],[[976,976],"mapped",[946]],[[977,977],"mapped",[952]],[[978,978],"mapped",[965]],[[979,979],"mapped",[973]],[[980,980],"mapped",[971]],[[981,981],"mapped",[966]],[[982,982],"mapped",[960]],[[983,983],"valid"],[[984,984],"mapped",[985]],[[985,985],"valid"],[[986,986],"mapped",[987]],[[987,987],"valid"],[[988,988],"mapped",[989]],[[989,989],"valid"],[[990,990],"mapped",[991]],[[991,991],"valid"],[[992,992],"mapped",[993]],[[993,993],"valid"],[[994,994],"mapped",[995]],[[995,995],"valid"],[[996,996],"mapped",[997]],[[997,997],"valid"],[[998,998],"mapped",[999]],[[999,999],"valid"],[[1000,1000],"mapped",[1001]],[[1001,1001],"valid"],[[1002,1002],"mapped",[1003]],[[1003,1003],"valid"],[[1004,1004],"mapped",[1005]],[[1005,1005],"valid"],[[1006,1006],"mapped",[1007]],[[1007,1007],"valid"],[[1008,1008],"mapped",[954]],[[1009,1009],"mapped",[961]],[[1010,1010],"mapped",[963]],[[1011,1011],"valid"],[[1012,1012],"mapped",[952]],[[1013,1013],"mapped",[949]],[[1014,1014],"valid",[],"NV8"],[[1015,1015],"mapped",[1016]],[[1016,1016],"valid"],[[1017,1017],"mapped",[963]],[[1018,1018],"mapped",[1019]],[[1019,1019],"valid"],[[1020,1020],"valid"],[[1021,1021],"mapped",[891]],[[1022,1022],"mapped",[892]],[[1023,1023],"mapped",[893]],[[1024,1024],"mapped",[1104]],[[1025,1025],"mapped",[1105]],[[1026,1026],"mapped",[1106]],[[1027,1027],"mapped",[1107]],[[1028,1028],"mapped",[1108]],[[1029,1029],"mapped",[1109]],[[1030,1030],"mapped",[1110]],[[1031,1031],"mapped",[1111]],[[1032,1032],"mapped",[1112]],[[1033,1033],"mapped",[1113]],[[1034,1034],"mapped",[1114]],[[1035,1035],"mapped",[1115]],[[1036,1036],"mapped",[1116]],[[1037,1037],"mapped",[1117]],[[1038,1038],"mapped",[1118]],[[1039,1039],"mapped",[1119]],[[1040,1040],"mapped",[1072]],[[1041,1041],"mapped",[1073]],[[1042,1042],"mapped",[1074]],[[1043,1043],"mapped",[1075]],[[1044,1044],"mapped",[1076]],[[1045,1045],"mapped",[1077]],[[1046,1046],"mapped",[1078]],[[1047,1047],"mapped",[1079]],[[1048,1048],"mapped",[1080]],[[1049,1049],"mapped",[1081]],[[1050,1050],"mapped",[1082]],[[1051,1051],"mapped",[1083]],[[1052,1052],"mapped",[1084]],[[1053,1053],"mapped",[1085]],[[1054,1054],"mapped",[1086]],[[1055,1055],"mapped",[1087]],[[1056,1056],"mapped",[1088]],[[1057,1057],"mapped",[1089]],[[1058,1058],"mapped",[1090]],[[1059,1059],"mapped",[1091]],[[1060,1060],"mapped",[1092]],[[1061,1061],"mapped",[1093]],[[1062,1062],"mapped",[1094]],[[1063,1063],"mapped",[1095]],[[1064,1064],"mapped",[1096]],[[1065,1065],"mapped",[1097]],[[1066,1066],"mapped",[1098]],[[1067,1067],"mapped",[1099]],[[1068,1068],"mapped",[1100]],[[1069,1069],"mapped",[1101]],[[1070,1070],"mapped",[1102]],[[1071,1071],"mapped",[1103]],[[1072,1103],"valid"],[[1104,1104],"valid"],[[1105,1116],"valid"],[[1117,1117],"valid"],[[1118,1119],"valid"],[[1120,1120],"mapped",[1121]],[[1121,1121],"valid"],[[1122,1122],"mapped",[1123]],[[1123,1123],"valid"],[[1124,1124],"mapped",[1125]],[[1125,1125],"valid"],[[1126,1126],"mapped",[1127]],[[1127,1127],"valid"],[[1128,1128],"mapped",[1129]],[[1129,1129],"valid"],[[1130,1130],"mapped",[1131]],[[1131,1131],"valid"],[[1132,1132],"mapped",[1133]],[[1133,1133],"valid"],[[1134,1134],"mapped",[1135]],[[1135,1135],"valid"],[[1136,1136],"mapped",[1137]],[[1137,1137],"valid"],[[1138,1138],"mapped",[1139]],[[1139,1139],"valid"],[[1140,1140],"mapped",[1141]],[[1141,1141],"valid"],[[1142,1142],"mapped",[1143]],[[1143,1143],"valid"],[[1144,1144],"mapped",[1145]],[[1145,1145],"valid"],[[1146,1146],"mapped",[1147]],[[1147,1147],"valid"],[[1148,1148],"mapped",[1149]],[[1149,1149],"valid"],[[1150,1150],"mapped",[1151]],[[1151,1151],"valid"],[[1152,1152],"mapped",[1153]],[[1153,1153],"valid"],[[1154,1154],"valid",[],"NV8"],[[1155,1158],"valid"],[[1159,1159],"valid"],[[1160,1161],"valid",[],"NV8"],[[1162,1162],"mapped",[1163]],[[1163,1163],"valid"],[[1164,1164],"mapped",[1165]],[[1165,1165],"valid"],[[1166,1166],"mapped",[1167]],[[1167,1167],"valid"],[[1168,1168],"mapped",[1169]],[[1169,1169],"valid"],[[1170,1170],"mapped",[1171]],[[1171,1171],"valid"],[[1172,1172],"mapped",[1173]],[[1173,1173],"valid"],[[1174,1174],"mapped",[1175]],[[1175,1175],"valid"],[[1176,1176],"mapped",[1177]],[[1177,1177],"valid"],[[1178,1178],"mapped",[1179]],[[1179,1179],"valid"],[[1180,1180],"mapped",[1181]],[[1181,1181],"valid"],[[1182,1182],"mapped",[1183]],[[1183,1183],"valid"],[[1184,1184],"mapped",[1185]],[[1185,1185],"valid"],[[1186,1186],"mapped",[1187]],[[1187,1187],"valid"],[[1188,1188],"mapped",[1189]],[[1189,1189],"valid"],[[1190,1190],"mapped",[1191]],[[1191,1191],"valid"],[[1192,1192],"mapped",[1193]],[[1193,1193],"valid"],[[1194,1194],"mapped",[1195]],[[1195,1195],"valid"],[[1196,1196],"mapped",[1197]],[[1197,1197],"valid"],[[1198,1198],"mapped",[1199]],[[1199,1199],"valid"],[[1200,1200],"mapped",[1201]],[[1201,1201],"valid"],[[1202,1202],"mapped",[1203]],[[1203,1203],"valid"],[[1204,1204],"mapped",[1205]],[[1205,1205],"valid"],[[1206,1206],"mapped",[1207]],[[1207,1207],"valid"],[[1208,1208],"mapped",[1209]],[[1209,1209],"valid"],[[1210,1210],"mapped",[1211]],[[1211,1211],"valid"],[[1212,1212],"mapped",[1213]],[[1213,1213],"valid"],[[1214,1214],"mapped",[1215]],[[1215,1215],"valid"],[[1216,1216],"disallowed"],[[1217,1217],"mapped",[1218]],[[1218,1218],"valid"],[[1219,1219],"mapped",[1220]],[[1220,1220],"valid"],[[1221,1221],"mapped",[1222]],[[1222,1222],"valid"],[[1223,1223],"mapped",[1224]],[[1224,1224],"valid"],[[1225,1225],"mapped",[1226]],[[1226,1226],"valid"],[[1227,1227],"mapped",[1228]],[[1228,1228],"valid"],[[1229,1229],"mapped",[1230]],[[1230,1230],"valid"],[[1231,1231],"valid"],[[1232,1232],"mapped",[1233]],[[1233,1233],"valid"],[[1234,1234],"mapped",[1235]],[[1235,1235],"valid"],[[1236,1236],"mapped",[1237]],[[1237,1237],"valid"],[[1238,1238],"mapped",[1239]],[[1239,1239],"valid"],[[1240,1240],"mapped",[1241]],[[1241,1241],"valid"],[[1242,1242],"mapped",[1243]],[[1243,1243],"valid"],[[1244,1244],"mapped",[1245]],[[1245,1245],"valid"],[[1246,1246],"mapped",[1247]],[[1247,1247],"valid"],[[1248,1248],"mapped",[1249]],[[1249,1249],"valid"],[[1250,1250],"mapped",[1251]],[[1251,1251],"valid"],[[1252,1252],"mapped",[1253]],[[1253,1253],"valid"],[[1254,1254],"mapped",[1255]],[[1255,1255],"valid"],[[1256,1256],"mapped",[1257]],[[1257,1257],"valid"],[[1258,1258],"mapped",[1259]],[[1259,1259],"valid"],[[1260,1260],"mapped",[1261]],[[1261,1261],"valid"],[[1262,1262],"mapped",[1263]],[[1263,1263],"valid"],[[1264,1264],"mapped",[1265]],[[1265,1265],"valid"],[[1266,1266],"mapped",[1267]],[[1267,1267],"valid"],[[1268,1268],"mapped",[1269]],[[1269,1269],"valid"],[[1270,1270],"mapped",[1271]],[[1271,1271],"valid"],[[1272,1272],"mapped",[1273]],[[1273,1273],"valid"],[[1274,1274],"mapped",[1275]],[[1275,1275],"valid"],[[1276,1276],"mapped",[1277]],[[1277,1277],"valid"],[[1278,1278],"mapped",[1279]],[[1279,1279],"valid"],[[1280,1280],"mapped",[1281]],[[1281,1281],"valid"],[[1282,1282],"mapped",[1283]],[[1283,1283],"valid"],[[1284,1284],"mapped",[1285]],[[1285,1285],"valid"],[[1286,1286],"mapped",[1287]],[[1287,1287],"valid"],[[1288,1288],"mapped",[1289]],[[1289,1289],"valid"],[[1290,1290],"mapped",[1291]],[[1291,1291],"valid"],[[1292,1292],"mapped",[1293]],[[1293,1293],"valid"],[[1294,1294],"mapped",[1295]],[[1295,1295],"valid"],[[1296,1296],"mapped",[1297]],[[1297,1297],"valid"],[[1298,1298],"mapped",[1299]],[[1299,1299],"valid"],[[1300,1300],"mapped",[1301]],[[1301,1301],"valid"],[[1302,1302],"mapped",[1303]],[[1303,1303],"valid"],[[1304,1304],"mapped",[1305]],[[1305,1305],"valid"],[[1306,1306],"mapped",[1307]],[[1307,1307],"valid"],[[1308,1308],"mapped",[1309]],[[1309,1309],"valid"],[[1310,1310],"mapped",[1311]],[[1311,1311],"valid"],[[1312,1312],"mapped",[1313]],[[1313,1313],"valid"],[[1314,1314],"mapped",[1315]],[[1315,1315],"valid"],[[1316,1316],"mapped",[1317]],[[1317,1317],"valid"],[[1318,1318],"mapped",[1319]],[[1319,1319],"valid"],[[1320,1320],"mapped",[1321]],[[1321,1321],"valid"],[[1322,1322],"mapped",[1323]],[[1323,1323],"valid"],[[1324,1324],"mapped",[1325]],[[1325,1325],"valid"],[[1326,1326],"mapped",[1327]],[[1327,1327],"valid"],[[1328,1328],"disallowed"],[[1329,1329],"mapped",[1377]],[[1330,1330],"mapped",[1378]],[[1331,1331],"mapped",[1379]],[[1332,1332],"mapped",[1380]],[[1333,1333],"mapped",[1381]],[[1334,1334],"mapped",[1382]],[[1335,1335],"mapped",[1383]],[[1336,1336],"mapped",[1384]],[[1337,1337],"mapped",[1385]],[[1338,1338],"mapped",[1386]],[[1339,1339],"mapped",[1387]],[[1340,1340],"mapped",[1388]],[[1341,1341],"mapped",[1389]],[[1342,1342],"mapped",[1390]],[[1343,1343],"mapped",[1391]],[[1344,1344],"mapped",[1392]],[[1345,1345],"mapped",[1393]],[[1346,1346],"mapped",[1394]],[[1347,1347],"mapped",[1395]],[[1348,1348],"mapped",[1396]],[[1349,1349],"mapped",[1397]],[[1350,1350],"mapped",[1398]],[[1351,1351],"mapped",[1399]],[[1352,1352],"mapped",[1400]],[[1353,1353],"mapped",[1401]],[[1354,1354],"mapped",[1402]],[[1355,1355],"mapped",[1403]],[[1356,1356],"mapped",[1404]],[[1357,1357],"mapped",[1405]],[[1358,1358],"mapped",[1406]],[[1359,1359],"mapped",[1407]],[[1360,1360],"mapped",[1408]],[[1361,1361],"mapped",[1409]],[[1362,1362],"mapped",[1410]],[[1363,1363],"mapped",[1411]],[[1364,1364],"mapped",[1412]],[[1365,1365],"mapped",[1413]],[[1366,1366],"mapped",[1414]],[[1367,1368],"disallowed"],[[1369,1369],"valid"],[[1370,1375],"valid",[],"NV8"],[[1376,1376],"disallowed"],[[1377,1414],"valid"],[[1415,1415],"mapped",[1381,1410]],[[1416,1416],"disallowed"],[[1417,1417],"valid",[],"NV8"],[[1418,1418],"valid",[],"NV8"],[[1419,1420],"disallowed"],[[1421,1422],"valid",[],"NV8"],[[1423,1423],"valid",[],"NV8"],[[1424,1424],"disallowed"],[[1425,1441],"valid"],[[1442,1442],"valid"],[[1443,1455],"valid"],[[1456,1465],"valid"],[[1466,1466],"valid"],[[1467,1469],"valid"],[[1470,1470],"valid",[],"NV8"],[[1471,1471],"valid"],[[1472,1472],"valid",[],"NV8"],[[1473,1474],"valid"],[[1475,1475],"valid",[],"NV8"],[[1476,1476],"valid"],[[1477,1477],"valid"],[[1478,1478],"valid",[],"NV8"],[[1479,1479],"valid"],[[1480,1487],"disallowed"],[[1488,1514],"valid"],[[1515,1519],"disallowed"],[[1520,1524],"valid"],[[1525,1535],"disallowed"],[[1536,1539],"disallowed"],[[1540,1540],"disallowed"],[[1541,1541],"disallowed"],[[1542,1546],"valid",[],"NV8"],[[1547,1547],"valid",[],"NV8"],[[1548,1548],"valid",[],"NV8"],[[1549,1551],"valid",[],"NV8"],[[1552,1557],"valid"],[[1558,1562],"valid"],[[1563,1563],"valid",[],"NV8"],[[1564,1564],"disallowed"],[[1565,1565],"disallowed"],[[1566,1566],"valid",[],"NV8"],[[1567,1567],"valid",[],"NV8"],[[1568,1568],"valid"],[[1569,1594],"valid"],[[1595,1599],"valid"],[[1600,1600],"valid",[],"NV8"],[[1601,1618],"valid"],[[1619,1621],"valid"],[[1622,1624],"valid"],[[1625,1630],"valid"],[[1631,1631],"valid"],[[1632,1641],"valid"],[[1642,1645],"valid",[],"NV8"],[[1646,1647],"valid"],[[1648,1652],"valid"],[[1653,1653],"mapped",[1575,1652]],[[1654,1654],"mapped",[1608,1652]],[[1655,1655],"mapped",[1735,1652]],[[1656,1656],"mapped",[1610,1652]],[[1657,1719],"valid"],[[1720,1721],"valid"],[[1722,1726],"valid"],[[1727,1727],"valid"],[[1728,1742],"valid"],[[1743,1743],"valid"],[[1744,1747],"valid"],[[1748,1748],"valid",[],"NV8"],[[1749,1756],"valid"],[[1757,1757],"disallowed"],[[1758,1758],"valid",[],"NV8"],[[1759,1768],"valid"],[[1769,1769],"valid",[],"NV8"],[[1770,1773],"valid"],[[1774,1775],"valid"],[[1776,1785],"valid"],[[1786,1790],"valid"],[[1791,1791],"valid"],[[1792,1805],"valid",[],"NV8"],[[1806,1806],"disallowed"],[[1807,1807],"disallowed"],[[1808,1836],"valid"],[[1837,1839],"valid"],[[1840,1866],"valid"],[[1867,1868],"disallowed"],[[1869,1871],"valid"],[[1872,1901],"valid"],[[1902,1919],"valid"],[[1920,1968],"valid"],[[1969,1969],"valid"],[[1970,1983],"disallowed"],[[1984,2037],"valid"],[[2038,2042],"valid",[],"NV8"],[[2043,2047],"disallowed"],[[2048,2093],"valid"],[[2094,2095],"disallowed"],[[2096,2110],"valid",[],"NV8"],[[2111,2111],"disallowed"],[[2112,2139],"valid"],[[2140,2141],"disallowed"],[[2142,2142],"valid",[],"NV8"],[[2143,2207],"disallowed"],[[2208,2208],"valid"],[[2209,2209],"valid"],[[2210,2220],"valid"],[[2221,2226],"valid"],[[2227,2228],"valid"],[[2229,2274],"disallowed"],[[2275,2275],"valid"],[[2276,2302],"valid"],[[2303,2303],"valid"],[[2304,2304],"valid"],[[2305,2307],"valid"],[[2308,2308],"valid"],[[2309,2361],"valid"],[[2362,2363],"valid"],[[2364,2381],"valid"],[[2382,2382],"valid"],[[2383,2383],"valid"],[[2384,2388],"valid"],[[2389,2389],"valid"],[[2390,2391],"valid"],[[2392,2392],"mapped",[2325,2364]],[[2393,2393],"mapped",[2326,2364]],[[2394,2394],"mapped",[2327,2364]],[[2395,2395],"mapped",[2332,2364]],[[2396,2396],"mapped",[2337,2364]],[[2397,2397],"mapped",[2338,2364]],[[2398,2398],"mapped",[2347,2364]],[[2399,2399],"mapped",[2351,2364]],[[2400,2403],"valid"],[[2404,2405],"valid",[],"NV8"],[[2406,2415],"valid"],[[2416,2416],"valid",[],"NV8"],[[2417,2418],"valid"],[[2419,2423],"valid"],[[2424,2424],"valid"],[[2425,2426],"valid"],[[2427,2428],"valid"],[[2429,2429],"valid"],[[2430,2431],"valid"],[[2432,2432],"valid"],[[2433,2435],"valid"],[[2436,2436],"disallowed"],[[2437,2444],"valid"],[[2445,2446],"disallowed"],[[2447,2448],"valid"],[[2449,2450],"disallowed"],[[2451,2472],"valid"],[[2473,2473],"disallowed"],[[2474,2480],"valid"],[[2481,2481],"disallowed"],[[2482,2482],"valid"],[[2483,2485],"disallowed"],[[2486,2489],"valid"],[[2490,2491],"disallowed"],[[2492,2492],"valid"],[[2493,2493],"valid"],[[2494,2500],"valid"],[[2501,2502],"disallowed"],[[2503,2504],"valid"],[[2505,2506],"disallowed"],[[2507,2509],"valid"],[[2510,2510],"valid"],[[2511,2518],"disallowed"],[[2519,2519],"valid"],[[2520,2523],"disallowed"],[[2524,2524],"mapped",[2465,2492]],[[2525,2525],"mapped",[2466,2492]],[[2526,2526],"disallowed"],[[2527,2527],"mapped",[2479,2492]],[[2528,2531],"valid"],[[2532,2533],"disallowed"],[[2534,2545],"valid"],[[2546,2554],"valid",[],"NV8"],[[2555,2555],"valid",[],"NV8"],[[2556,2560],"disallowed"],[[2561,2561],"valid"],[[2562,2562],"valid"],[[2563,2563],"valid"],[[2564,2564],"disallowed"],[[2565,2570],"valid"],[[2571,2574],"disallowed"],[[2575,2576],"valid"],[[2577,2578],"disallowed"],[[2579,2600],"valid"],[[2601,2601],"disallowed"],[[2602,2608],"valid"],[[2609,2609],"disallowed"],[[2610,2610],"valid"],[[2611,2611],"mapped",[2610,2620]],[[2612,2612],"disallowed"],[[2613,2613],"valid"],[[2614,2614],"mapped",[2616,2620]],[[2615,2615],"disallowed"],[[2616,2617],"valid"],[[2618,2619],"disallowed"],[[2620,2620],"valid"],[[2621,2621],"disallowed"],[[2622,2626],"valid"],[[2627,2630],"disallowed"],[[2631,2632],"valid"],[[2633,2634],"disallowed"],[[2635,2637],"valid"],[[2638,2640],"disallowed"],[[2641,2641],"valid"],[[2642,2648],"disallowed"],[[2649,2649],"mapped",[2582,2620]],[[2650,2650],"mapped",[2583,2620]],[[2651,2651],"mapped",[2588,2620]],[[2652,2652],"valid"],[[2653,2653],"disallowed"],[[2654,2654],"mapped",[2603,2620]],[[2655,2661],"disallowed"],[[2662,2676],"valid"],[[2677,2677],"valid"],[[2678,2688],"disallowed"],[[2689,2691],"valid"],[[2692,2692],"disallowed"],[[2693,2699],"valid"],[[2700,2700],"valid"],[[2701,2701],"valid"],[[2702,2702],"disallowed"],[[2703,2705],"valid"],[[2706,2706],"disallowed"],[[2707,2728],"valid"],[[2729,2729],"disallowed"],[[2730,2736],"valid"],[[2737,2737],"disallowed"],[[2738,2739],"valid"],[[2740,2740],"disallowed"],[[2741,2745],"valid"],[[2746,2747],"disallowed"],[[2748,2757],"valid"],[[2758,2758],"disallowed"],[[2759,2761],"valid"],[[2762,2762],"disallowed"],[[2763,2765],"valid"],[[2766,2767],"disallowed"],[[2768,2768],"valid"],[[2769,2783],"disallowed"],[[2784,2784],"valid"],[[2785,2787],"valid"],[[2788,2789],"disallowed"],[[2790,2799],"valid"],[[2800,2800],"valid",[],"NV8"],[[2801,2801],"valid",[],"NV8"],[[2802,2808],"disallowed"],[[2809,2809],"valid"],[[2810,2816],"disallowed"],[[2817,2819],"valid"],[[2820,2820],"disallowed"],[[2821,2828],"valid"],[[2829,2830],"disallowed"],[[2831,2832],"valid"],[[2833,2834],"disallowed"],[[2835,2856],"valid"],[[2857,2857],"disallowed"],[[2858,2864],"valid"],[[2865,2865],"disallowed"],[[2866,2867],"valid"],[[2868,2868],"disallowed"],[[2869,2869],"valid"],[[2870,2873],"valid"],[[2874,2875],"disallowed"],[[2876,2883],"valid"],[[2884,2884],"valid"],[[2885,2886],"disallowed"],[[2887,2888],"valid"],[[2889,2890],"disallowed"],[[2891,2893],"valid"],[[2894,2901],"disallowed"],[[2902,2903],"valid"],[[2904,2907],"disallowed"],[[2908,2908],"mapped",[2849,2876]],[[2909,2909],"mapped",[2850,2876]],[[2910,2910],"disallowed"],[[2911,2913],"valid"],[[2914,2915],"valid"],[[2916,2917],"disallowed"],[[2918,2927],"valid"],[[2928,2928],"valid",[],"NV8"],[[2929,2929],"valid"],[[2930,2935],"valid",[],"NV8"],[[2936,2945],"disallowed"],[[2946,2947],"valid"],[[2948,2948],"disallowed"],[[2949,2954],"valid"],[[2955,2957],"disallowed"],[[2958,2960],"valid"],[[2961,2961],"disallowed"],[[2962,2965],"valid"],[[2966,2968],"disallowed"],[[2969,2970],"valid"],[[2971,2971],"disallowed"],[[2972,2972],"valid"],[[2973,2973],"disallowed"],[[2974,2975],"valid"],[[2976,2978],"disallowed"],[[2979,2980],"valid"],[[2981,2983],"disallowed"],[[2984,2986],"valid"],[[2987,2989],"disallowed"],[[2990,2997],"valid"],[[2998,2998],"valid"],[[2999,3001],"valid"],[[3002,3005],"disallowed"],[[3006,3010],"valid"],[[3011,3013],"disallowed"],[[3014,3016],"valid"],[[3017,3017],"disallowed"],[[3018,3021],"valid"],[[3022,3023],"disallowed"],[[3024,3024],"valid"],[[3025,3030],"disallowed"],[[3031,3031],"valid"],[[3032,3045],"disallowed"],[[3046,3046],"valid"],[[3047,3055],"valid"],[[3056,3058],"valid",[],"NV8"],[[3059,3066],"valid",[],"NV8"],[[3067,3071],"disallowed"],[[3072,3072],"valid"],[[3073,3075],"valid"],[[3076,3076],"disallowed"],[[3077,3084],"valid"],[[3085,3085],"disallowed"],[[3086,3088],"valid"],[[3089,3089],"disallowed"],[[3090,3112],"valid"],[[3113,3113],"disallowed"],[[3114,3123],"valid"],[[3124,3124],"valid"],[[3125,3129],"valid"],[[3130,3132],"disallowed"],[[3133,3133],"valid"],[[3134,3140],"valid"],[[3141,3141],"disallowed"],[[3142,3144],"valid"],[[3145,3145],"disallowed"],[[3146,3149],"valid"],[[3150,3156],"disallowed"],[[3157,3158],"valid"],[[3159,3159],"disallowed"],[[3160,3161],"valid"],[[3162,3162],"valid"],[[3163,3167],"disallowed"],[[3168,3169],"valid"],[[3170,3171],"valid"],[[3172,3173],"disallowed"],[[3174,3183],"valid"],[[3184,3191],"disallowed"],[[3192,3199],"valid",[],"NV8"],[[3200,3200],"disallowed"],[[3201,3201],"valid"],[[3202,3203],"valid"],[[3204,3204],"disallowed"],[[3205,3212],"valid"],[[3213,3213],"disallowed"],[[3214,3216],"valid"],[[3217,3217],"disallowed"],[[3218,3240],"valid"],[[3241,3241],"disallowed"],[[3242,3251],"valid"],[[3252,3252],"disallowed"],[[3253,3257],"valid"],[[3258,3259],"disallowed"],[[3260,3261],"valid"],[[3262,3268],"valid"],[[3269,3269],"disallowed"],[[3270,3272],"valid"],[[3273,3273],"disallowed"],[[3274,3277],"valid"],[[3278,3284],"disallowed"],[[3285,3286],"valid"],[[3287,3293],"disallowed"],[[3294,3294],"valid"],[[3295,3295],"disallowed"],[[3296,3297],"valid"],[[3298,3299],"valid"],[[3300,3301],"disallowed"],[[3302,3311],"valid"],[[3312,3312],"disallowed"],[[3313,3314],"valid"],[[3315,3328],"disallowed"],[[3329,3329],"valid"],[[3330,3331],"valid"],[[3332,3332],"disallowed"],[[3333,3340],"valid"],[[3341,3341],"disallowed"],[[3342,3344],"valid"],[[3345,3345],"disallowed"],[[3346,3368],"valid"],[[3369,3369],"valid"],[[3370,3385],"valid"],[[3386,3386],"valid"],[[3387,3388],"disallowed"],[[3389,3389],"valid"],[[3390,3395],"valid"],[[3396,3396],"valid"],[[3397,3397],"disallowed"],[[3398,3400],"valid"],[[3401,3401],"disallowed"],[[3402,3405],"valid"],[[3406,3406],"valid"],[[3407,3414],"disallowed"],[[3415,3415],"valid"],[[3416,3422],"disallowed"],[[3423,3423],"valid"],[[3424,3425],"valid"],[[3426,3427],"valid"],[[3428,3429],"disallowed"],[[3430,3439],"valid"],[[3440,3445],"valid",[],"NV8"],[[3446,3448],"disallowed"],[[3449,3449],"valid",[],"NV8"],[[3450,3455],"valid"],[[3456,3457],"disallowed"],[[3458,3459],"valid"],[[3460,3460],"disallowed"],[[3461,3478],"valid"],[[3479,3481],"disallowed"],[[3482,3505],"valid"],[[3506,3506],"disallowed"],[[3507,3515],"valid"],[[3516,3516],"disallowed"],[[3517,3517],"valid"],[[3518,3519],"disallowed"],[[3520,3526],"valid"],[[3527,3529],"disallowed"],[[3530,3530],"valid"],[[3531,3534],"disallowed"],[[3535,3540],"valid"],[[3541,3541],"disallowed"],[[3542,3542],"valid"],[[3543,3543],"disallowed"],[[3544,3551],"valid"],[[3552,3557],"disallowed"],[[3558,3567],"valid"],[[3568,3569],"disallowed"],[[3570,3571],"valid"],[[3572,3572],"valid",[],"NV8"],[[3573,3584],"disallowed"],[[3585,3634],"valid"],[[3635,3635],"mapped",[3661,3634]],[[3636,3642],"valid"],[[3643,3646],"disallowed"],[[3647,3647],"valid",[],"NV8"],[[3648,3662],"valid"],[[3663,3663],"valid",[],"NV8"],[[3664,3673],"valid"],[[3674,3675],"valid",[],"NV8"],[[3676,3712],"disallowed"],[[3713,3714],"valid"],[[3715,3715],"disallowed"],[[3716,3716],"valid"],[[3717,3718],"disallowed"],[[3719,3720],"valid"],[[3721,3721],"disallowed"],[[3722,3722],"valid"],[[3723,3724],"disallowed"],[[3725,3725],"valid"],[[3726,3731],"disallowed"],[[3732,3735],"valid"],[[3736,3736],"disallowed"],[[3737,3743],"valid"],[[3744,3744],"disallowed"],[[3745,3747],"valid"],[[3748,3748],"disallowed"],[[3749,3749],"valid"],[[3750,3750],"disallowed"],[[3751,3751],"valid"],[[3752,3753],"disallowed"],[[3754,3755],"valid"],[[3756,3756],"disallowed"],[[3757,3762],"valid"],[[3763,3763],"mapped",[3789,3762]],[[3764,3769],"valid"],[[3770,3770],"disallowed"],[[3771,3773],"valid"],[[3774,3775],"disallowed"],[[3776,3780],"valid"],[[3781,3781],"disallowed"],[[3782,3782],"valid"],[[3783,3783],"disallowed"],[[3784,3789],"valid"],[[3790,3791],"disallowed"],[[3792,3801],"valid"],[[3802,3803],"disallowed"],[[3804,3804],"mapped",[3755,3737]],[[3805,3805],"mapped",[3755,3745]],[[3806,3807],"valid"],[[3808,3839],"disallowed"],[[3840,3840],"valid"],[[3841,3850],"valid",[],"NV8"],[[3851,3851],"valid"],[[3852,3852],"mapped",[3851]],[[3853,3863],"valid",[],"NV8"],[[3864,3865],"valid"],[[3866,3871],"valid",[],"NV8"],[[3872,3881],"valid"],[[3882,3892],"valid",[],"NV8"],[[3893,3893],"valid"],[[3894,3894],"valid",[],"NV8"],[[3895,3895],"valid"],[[3896,3896],"valid",[],"NV8"],[[3897,3897],"valid"],[[3898,3901],"valid",[],"NV8"],[[3902,3906],"valid"],[[3907,3907],"mapped",[3906,4023]],[[3908,3911],"valid"],[[3912,3912],"disallowed"],[[3913,3916],"valid"],[[3917,3917],"mapped",[3916,4023]],[[3918,3921],"valid"],[[3922,3922],"mapped",[3921,4023]],[[3923,3926],"valid"],[[3927,3927],"mapped",[3926,4023]],[[3928,3931],"valid"],[[3932,3932],"mapped",[3931,4023]],[[3933,3944],"valid"],[[3945,3945],"mapped",[3904,4021]],[[3946,3946],"valid"],[[3947,3948],"valid"],[[3949,3952],"disallowed"],[[3953,3954],"valid"],[[3955,3955],"mapped",[3953,3954]],[[3956,3956],"valid"],[[3957,3957],"mapped",[3953,3956]],[[3958,3958],"mapped",[4018,3968]],[[3959,3959],"mapped",[4018,3953,3968]],[[3960,3960],"mapped",[4019,3968]],[[3961,3961],"mapped",[4019,3953,3968]],[[3962,3968],"valid"],[[3969,3969],"mapped",[3953,3968]],[[3970,3972],"valid"],[[3973,3973],"valid",[],"NV8"],[[3974,3979],"valid"],[[3980,3983],"valid"],[[3984,3986],"valid"],[[3987,3987],"mapped",[3986,4023]],[[3988,3989],"valid"],[[3990,3990],"valid"],[[3991,3991],"valid"],[[3992,3992],"disallowed"],[[3993,3996],"valid"],[[3997,3997],"mapped",[3996,4023]],[[3998,4001],"valid"],[[4002,4002],"mapped",[4001,4023]],[[4003,4006],"valid"],[[4007,4007],"mapped",[4006,4023]],[[4008,4011],"valid"],[[4012,4012],"mapped",[4011,4023]],[[4013,4013],"valid"],[[4014,4016],"valid"],[[4017,4023],"valid"],[[4024,4024],"valid"],[[4025,4025],"mapped",[3984,4021]],[[4026,4028],"valid"],[[4029,4029],"disallowed"],[[4030,4037],"valid",[],"NV8"],[[4038,4038],"valid"],[[4039,4044],"valid",[],"NV8"],[[4045,4045],"disallowed"],[[4046,4046],"valid",[],"NV8"],[[4047,4047],"valid",[],"NV8"],[[4048,4049],"valid",[],"NV8"],[[4050,4052],"valid",[],"NV8"],[[4053,4056],"valid",[],"NV8"],[[4057,4058],"valid",[],"NV8"],[[4059,4095],"disallowed"],[[4096,4129],"valid"],[[4130,4130],"valid"],[[4131,4135],"valid"],[[4136,4136],"valid"],[[4137,4138],"valid"],[[4139,4139],"valid"],[[4140,4146],"valid"],[[4147,4149],"valid"],[[4150,4153],"valid"],[[4154,4159],"valid"],[[4160,4169],"valid"],[[4170,4175],"valid",[],"NV8"],[[4176,4185],"valid"],[[4186,4249],"valid"],[[4250,4253],"valid"],[[4254,4255],"valid",[],"NV8"],[[4256,4293],"disallowed"],[[4294,4294],"disallowed"],[[4295,4295],"mapped",[11559]],[[4296,4300],"disallowed"],[[4301,4301],"mapped",[11565]],[[4302,4303],"disallowed"],[[4304,4342],"valid"],[[4343,4344],"valid"],[[4345,4346],"valid"],[[4347,4347],"valid",[],"NV8"],[[4348,4348],"mapped",[4316]],[[4349,4351],"valid"],[[4352,4441],"valid",[],"NV8"],[[4442,4446],"valid",[],"NV8"],[[4447,4448],"disallowed"],[[4449,4514],"valid",[],"NV8"],[[4515,4519],"valid",[],"NV8"],[[4520,4601],"valid",[],"NV8"],[[4602,4607],"valid",[],"NV8"],[[4608,4614],"valid"],[[4615,4615],"valid"],[[4616,4678],"valid"],[[4679,4679],"valid"],[[4680,4680],"valid"],[[4681,4681],"disallowed"],[[4682,4685],"valid"],[[4686,4687],"disallowed"],[[4688,4694],"valid"],[[4695,4695],"disallowed"],[[4696,4696],"valid"],[[4697,4697],"disallowed"],[[4698,4701],"valid"],[[4702,4703],"disallowed"],[[4704,4742],"valid"],[[4743,4743],"valid"],[[4744,4744],"valid"],[[4745,4745],"disallowed"],[[4746,4749],"valid"],[[4750,4751],"disallowed"],[[4752,4782],"valid"],[[4783,4783],"valid"],[[4784,4784],"valid"],[[4785,4785],"disallowed"],[[4786,4789],"valid"],[[4790,4791],"disallowed"],[[4792,4798],"valid"],[[4799,4799],"disallowed"],[[4800,4800],"valid"],[[4801,4801],"disallowed"],[[4802,4805],"valid"],[[4806,4807],"disallowed"],[[4808,4814],"valid"],[[4815,4815],"valid"],[[4816,4822],"valid"],[[4823,4823],"disallowed"],[[4824,4846],"valid"],[[4847,4847],"valid"],[[4848,4878],"valid"],[[4879,4879],"valid"],[[4880,4880],"valid"],[[4881,4881],"disallowed"],[[4882,4885],"valid"],[[4886,4887],"disallowed"],[[4888,4894],"valid"],[[4895,4895],"valid"],[[4896,4934],"valid"],[[4935,4935],"valid"],[[4936,4954],"valid"],[[4955,4956],"disallowed"],[[4957,4958],"valid"],[[4959,4959],"valid"],[[4960,4960],"valid",[],"NV8"],[[4961,4988],"valid",[],"NV8"],[[4989,4991],"disallowed"],[[4992,5007],"valid"],[[5008,5017],"valid",[],"NV8"],[[5018,5023],"disallowed"],[[5024,5108],"valid"],[[5109,5109],"valid"],[[5110,5111],"disallowed"],[[5112,5112],"mapped",[5104]],[[5113,5113],"mapped",[5105]],[[5114,5114],"mapped",[5106]],[[5115,5115],"mapped",[5107]],[[5116,5116],"mapped",[5108]],[[5117,5117],"mapped",[5109]],[[5118,5119],"disallowed"],[[5120,5120],"valid",[],"NV8"],[[5121,5740],"valid"],[[5741,5742],"valid",[],"NV8"],[[5743,5750],"valid"],[[5751,5759],"valid"],[[5760,5760],"disallowed"],[[5761,5786],"valid"],[[5787,5788],"valid",[],"NV8"],[[5789,5791],"disallowed"],[[5792,5866],"valid"],[[5867,5872],"valid",[],"NV8"],[[5873,5880],"valid"],[[5881,5887],"disallowed"],[[5888,5900],"valid"],[[5901,5901],"disallowed"],[[5902,5908],"valid"],[[5909,5919],"disallowed"],[[5920,5940],"valid"],[[5941,5942],"valid",[],"NV8"],[[5943,5951],"disallowed"],[[5952,5971],"valid"],[[5972,5983],"disallowed"],[[5984,5996],"valid"],[[5997,5997],"disallowed"],[[5998,6000],"valid"],[[6001,6001],"disallowed"],[[6002,6003],"valid"],[[6004,6015],"disallowed"],[[6016,6067],"valid"],[[6068,6069],"disallowed"],[[6070,6099],"valid"],[[6100,6102],"valid",[],"NV8"],[[6103,6103],"valid"],[[6104,6107],"valid",[],"NV8"],[[6108,6108],"valid"],[[6109,6109],"valid"],[[6110,6111],"disallowed"],[[6112,6121],"valid"],[[6122,6127],"disallowed"],[[6128,6137],"valid",[],"NV8"],[[6138,6143],"disallowed"],[[6144,6149],"valid",[],"NV8"],[[6150,6150],"disallowed"],[[6151,6154],"valid",[],"NV8"],[[6155,6157],"ignored"],[[6158,6158],"disallowed"],[[6159,6159],"disallowed"],[[6160,6169],"valid"],[[6170,6175],"disallowed"],[[6176,6263],"valid"],[[6264,6271],"disallowed"],[[6272,6313],"valid"],[[6314,6314],"valid"],[[6315,6319],"disallowed"],[[6320,6389],"valid"],[[6390,6399],"disallowed"],[[6400,6428],"valid"],[[6429,6430],"valid"],[[6431,6431],"disallowed"],[[6432,6443],"valid"],[[6444,6447],"disallowed"],[[6448,6459],"valid"],[[6460,6463],"disallowed"],[[6464,6464],"valid",[],"NV8"],[[6465,6467],"disallowed"],[[6468,6469],"valid",[],"NV8"],[[6470,6509],"valid"],[[6510,6511],"disallowed"],[[6512,6516],"valid"],[[6517,6527],"disallowed"],[[6528,6569],"valid"],[[6570,6571],"valid"],[[6572,6575],"disallowed"],[[6576,6601],"valid"],[[6602,6607],"disallowed"],[[6608,6617],"valid"],[[6618,6618],"valid",[],"XV8"],[[6619,6621],"disallowed"],[[6622,6623],"valid",[],"NV8"],[[6624,6655],"valid",[],"NV8"],[[6656,6683],"valid"],[[6684,6685],"disallowed"],[[6686,6687],"valid",[],"NV8"],[[6688,6750],"valid"],[[6751,6751],"disallowed"],[[6752,6780],"valid"],[[6781,6782],"disallowed"],[[6783,6793],"valid"],[[6794,6799],"disallowed"],[[6800,6809],"valid"],[[6810,6815],"disallowed"],[[6816,6822],"valid",[],"NV8"],[[6823,6823],"valid"],[[6824,6829],"valid",[],"NV8"],[[6830,6831],"disallowed"],[[6832,6845],"valid"],[[6846,6846],"valid",[],"NV8"],[[6847,6911],"disallowed"],[[6912,6987],"valid"],[[6988,6991],"disallowed"],[[6992,7001],"valid"],[[7002,7018],"valid",[],"NV8"],[[7019,7027],"valid"],[[7028,7036],"valid",[],"NV8"],[[7037,7039],"disallowed"],[[7040,7082],"valid"],[[7083,7085],"valid"],[[7086,7097],"valid"],[[7098,7103],"valid"],[[7104,7155],"valid"],[[7156,7163],"disallowed"],[[7164,7167],"valid",[],"NV8"],[[7168,7223],"valid"],[[7224,7226],"disallowed"],[[7227,7231],"valid",[],"NV8"],[[7232,7241],"valid"],[[7242,7244],"disallowed"],[[7245,7293],"valid"],[[7294,7295],"valid",[],"NV8"],[[7296,7359],"disallowed"],[[7360,7367],"valid",[],"NV8"],[[7368,7375],"disallowed"],[[7376,7378],"valid"],[[7379,7379],"valid",[],"NV8"],[[7380,7410],"valid"],[[7411,7414],"valid"],[[7415,7415],"disallowed"],[[7416,7417],"valid"],[[7418,7423],"disallowed"],[[7424,7467],"valid"],[[7468,7468],"mapped",[97]],[[7469,7469],"mapped",[230]],[[7470,7470],"mapped",[98]],[[7471,7471],"valid"],[[7472,7472],"mapped",[100]],[[7473,7473],"mapped",[101]],[[7474,7474],"mapped",[477]],[[7475,7475],"mapped",[103]],[[7476,7476],"mapped",[104]],[[7477,7477],"mapped",[105]],[[7478,7478],"mapped",[106]],[[7479,7479],"mapped",[107]],[[7480,7480],"mapped",[108]],[[7481,7481],"mapped",[109]],[[7482,7482],"mapped",[110]],[[7483,7483],"valid"],[[7484,7484],"mapped",[111]],[[7485,7485],"mapped",[547]],[[7486,7486],"mapped",[112]],[[7487,7487],"mapped",[114]],[[7488,7488],"mapped",[116]],[[7489,7489],"mapped",[117]],[[7490,7490],"mapped",[119]],[[7491,7491],"mapped",[97]],[[7492,7492],"mapped",[592]],[[7493,7493],"mapped",[593]],[[7494,7494],"mapped",[7426]],[[7495,7495],"mapped",[98]],[[7496,7496],"mapped",[100]],[[7497,7497],"mapped",[101]],[[7498,7498],"mapped",[601]],[[7499,7499],"mapped",[603]],[[7500,7500],"mapped",[604]],[[7501,7501],"mapped",[103]],[[7502,7502],"valid"],[[7503,7503],"mapped",[107]],[[7504,7504],"mapped",[109]],[[7505,7505],"mapped",[331]],[[7506,7506],"mapped",[111]],[[7507,7507],"mapped",[596]],[[7508,7508],"mapped",[7446]],[[7509,7509],"mapped",[7447]],[[7510,7510],"mapped",[112]],[[7511,7511],"mapped",[116]],[[7512,7512],"mapped",[117]],[[7513,7513],"mapped",[7453]],[[7514,7514],"mapped",[623]],[[7515,7515],"mapped",[118]],[[7516,7516],"mapped",[7461]],[[7517,7517],"mapped",[946]],[[7518,7518],"mapped",[947]],[[7519,7519],"mapped",[948]],[[7520,7520],"mapped",[966]],[[7521,7521],"mapped",[967]],[[7522,7522],"mapped",[105]],[[7523,7523],"mapped",[114]],[[7524,7524],"mapped",[117]],[[7525,7525],"mapped",[118]],[[7526,7526],"mapped",[946]],[[7527,7527],"mapped",[947]],[[7528,7528],"mapped",[961]],[[7529,7529],"mapped",[966]],[[7530,7530],"mapped",[967]],[[7531,7531],"valid"],[[7532,7543],"valid"],[[7544,7544],"mapped",[1085]],[[7545,7578],"valid"],[[7579,7579],"mapped",[594]],[[7580,7580],"mapped",[99]],[[7581,7581],"mapped",[597]],[[7582,7582],"mapped",[240]],[[7583,7583],"mapped",[604]],[[7584,7584],"mapped",[102]],[[7585,7585],"mapped",[607]],[[7586,7586],"mapped",[609]],[[7587,7587],"mapped",[613]],[[7588,7588],"mapped",[616]],[[7589,7589],"mapped",[617]],[[7590,7590],"mapped",[618]],[[7591,7591],"mapped",[7547]],[[7592,7592],"mapped",[669]],[[7593,7593],"mapped",[621]],[[7594,7594],"mapped",[7557]],[[7595,7595],"mapped",[671]],[[7596,7596],"mapped",[625]],[[7597,7597],"mapped",[624]],[[7598,7598],"mapped",[626]],[[7599,7599],"mapped",[627]],[[7600,7600],"mapped",[628]],[[7601,7601],"mapped",[629]],[[7602,7602],"mapped",[632]],[[7603,7603],"mapped",[642]],[[7604,7604],"mapped",[643]],[[7605,7605],"mapped",[427]],[[7606,7606],"mapped",[649]],[[7607,7607],"mapped",[650]],[[7608,7608],"mapped",[7452]],[[7609,7609],"mapped",[651]],[[7610,7610],"mapped",[652]],[[7611,7611],"mapped",[122]],[[7612,7612],"mapped",[656]],[[7613,7613],"mapped",[657]],[[7614,7614],"mapped",[658]],[[7615,7615],"mapped",[952]],[[7616,7619],"valid"],[[7620,7626],"valid"],[[7627,7654],"valid"],[[7655,7669],"valid"],[[7670,7675],"disallowed"],[[7676,7676],"valid"],[[7677,7677],"valid"],[[7678,7679],"valid"],[[7680,7680],"mapped",[7681]],[[7681,7681],"valid"],[[7682,7682],"mapped",[7683]],[[7683,7683],"valid"],[[7684,7684],"mapped",[7685]],[[7685,7685],"valid"],[[7686,7686],"mapped",[7687]],[[7687,7687],"valid"],[[7688,7688],"mapped",[7689]],[[7689,7689],"valid"],[[7690,7690],"mapped",[7691]],[[7691,7691],"valid"],[[7692,7692],"mapped",[7693]],[[7693,7693],"valid"],[[7694,7694],"mapped",[7695]],[[7695,7695],"valid"],[[7696,7696],"mapped",[7697]],[[7697,7697],"valid"],[[7698,7698],"mapped",[7699]],[[7699,7699],"valid"],[[7700,7700],"mapped",[7701]],[[7701,7701],"valid"],[[7702,7702],"mapped",[7703]],[[7703,7703],"valid"],[[7704,7704],"mapped",[7705]],[[7705,7705],"valid"],[[7706,7706],"mapped",[7707]],[[7707,7707],"valid"],[[7708,7708],"mapped",[7709]],[[7709,7709],"valid"],[[7710,7710],"mapped",[7711]],[[7711,7711],"valid"],[[7712,7712],"mapped",[7713]],[[7713,7713],"valid"],[[7714,7714],"mapped",[7715]],[[7715,7715],"valid"],[[7716,7716],"mapped",[7717]],[[7717,7717],"valid"],[[7718,7718],"mapped",[7719]],[[7719,7719],"valid"],[[7720,7720],"mapped",[7721]],[[7721,7721],"valid"],[[7722,7722],"mapped",[7723]],[[7723,7723],"valid"],[[7724,7724],"mapped",[7725]],[[7725,7725],"valid"],[[7726,7726],"mapped",[7727]],[[7727,7727],"valid"],[[7728,7728],"mapped",[7729]],[[7729,7729],"valid"],[[7730,7730],"mapped",[7731]],[[7731,7731],"valid"],[[7732,7732],"mapped",[7733]],[[7733,7733],"valid"],[[7734,7734],"mapped",[7735]],[[7735,7735],"valid"],[[7736,7736],"mapped",[7737]],[[7737,7737],"valid"],[[7738,7738],"mapped",[7739]],[[7739,7739],"valid"],[[7740,7740],"mapped",[7741]],[[7741,7741],"valid"],[[7742,7742],"mapped",[7743]],[[7743,7743],"valid"],[[7744,7744],"mapped",[7745]],[[7745,7745],"valid"],[[7746,7746],"mapped",[7747]],[[7747,7747],"valid"],[[7748,7748],"mapped",[7749]],[[7749,7749],"valid"],[[7750,7750],"mapped",[7751]],[[7751,7751],"valid"],[[7752,7752],"mapped",[7753]],[[7753,7753],"valid"],[[7754,7754],"mapped",[7755]],[[7755,7755],"valid"],[[7756,7756],"mapped",[7757]],[[7757,7757],"valid"],[[7758,7758],"mapped",[7759]],[[7759,7759],"valid"],[[7760,7760],"mapped",[7761]],[[7761,7761],"valid"],[[7762,7762],"mapped",[7763]],[[7763,7763],"valid"],[[7764,7764],"mapped",[7765]],[[7765,7765],"valid"],[[7766,7766],"mapped",[7767]],[[7767,7767],"valid"],[[7768,7768],"mapped",[7769]],[[7769,7769],"valid"],[[7770,7770],"mapped",[7771]],[[7771,7771],"valid"],[[7772,7772],"mapped",[7773]],[[7773,7773],"valid"],[[7774,7774],"mapped",[7775]],[[7775,7775],"valid"],[[7776,7776],"mapped",[7777]],[[7777,7777],"valid"],[[7778,7778],"mapped",[7779]],[[7779,7779],"valid"],[[7780,7780],"mapped",[7781]],[[7781,7781],"valid"],[[7782,7782],"mapped",[7783]],[[7783,7783],"valid"],[[7784,7784],"mapped",[7785]],[[7785,7785],"valid"],[[7786,7786],"mapped",[7787]],[[7787,7787],"valid"],[[7788,7788],"mapped",[7789]],[[7789,7789],"valid"],[[7790,7790],"mapped",[7791]],[[7791,7791],"valid"],[[7792,7792],"mapped",[7793]],[[7793,7793],"valid"],[[7794,7794],"mapped",[7795]],[[7795,7795],"valid"],[[7796,7796],"mapped",[7797]],[[7797,7797],"valid"],[[7798,7798],"mapped",[7799]],[[7799,7799],"valid"],[[7800,7800],"mapped",[7801]],[[7801,7801],"valid"],[[7802,7802],"mapped",[7803]],[[7803,7803],"valid"],[[7804,7804],"mapped",[7805]],[[7805,7805],"valid"],[[7806,7806],"mapped",[7807]],[[7807,7807],"valid"],[[7808,7808],"mapped",[7809]],[[7809,7809],"valid"],[[7810,7810],"mapped",[7811]],[[7811,7811],"valid"],[[7812,7812],"mapped",[7813]],[[7813,7813],"valid"],[[7814,7814],"mapped",[7815]],[[7815,7815],"valid"],[[7816,7816],"mapped",[7817]],[[7817,7817],"valid"],[[7818,7818],"mapped",[7819]],[[7819,7819],"valid"],[[7820,7820],"mapped",[7821]],[[7821,7821],"valid"],[[7822,7822],"mapped",[7823]],[[7823,7823],"valid"],[[7824,7824],"mapped",[7825]],[[7825,7825],"valid"],[[7826,7826],"mapped",[7827]],[[7827,7827],"valid"],[[7828,7828],"mapped",[7829]],[[7829,7833],"valid"],[[7834,7834],"mapped",[97,702]],[[7835,7835],"mapped",[7777]],[[7836,7837],"valid"],[[7838,7838],"mapped",[115,115]],[[7839,7839],"valid"],[[7840,7840],"mapped",[7841]],[[7841,7841],"valid"],[[7842,7842],"mapped",[7843]],[[7843,7843],"valid"],[[7844,7844],"mapped",[7845]],[[7845,7845],"valid"],[[7846,7846],"mapped",[7847]],[[7847,7847],"valid"],[[7848,7848],"mapped",[7849]],[[7849,7849],"valid"],[[7850,7850],"mapped",[7851]],[[7851,7851],"valid"],[[7852,7852],"mapped",[7853]],[[7853,7853],"valid"],[[7854,7854],"mapped",[7855]],[[7855,7855],"valid"],[[7856,7856],"mapped",[7857]],[[7857,7857],"valid"],[[7858,7858],"mapped",[7859]],[[7859,7859],"valid"],[[7860,7860],"mapped",[7861]],[[7861,7861],"valid"],[[7862,7862],"mapped",[7863]],[[7863,7863],"valid"],[[7864,7864],"mapped",[7865]],[[7865,7865],"valid"],[[7866,7866],"mapped",[7867]],[[7867,7867],"valid"],[[7868,7868],"mapped",[7869]],[[7869,7869],"valid"],[[7870,7870],"mapped",[7871]],[[7871,7871],"valid"],[[7872,7872],"mapped",[7873]],[[7873,7873],"valid"],[[7874,7874],"mapped",[7875]],[[7875,7875],"valid"],[[7876,7876],"mapped",[7877]],[[7877,7877],"valid"],[[7878,7878],"mapped",[7879]],[[7879,7879],"valid"],[[7880,7880],"mapped",[7881]],[[7881,7881],"valid"],[[7882,7882],"mapped",[7883]],[[7883,7883],"valid"],[[7884,7884],"mapped",[7885]],[[7885,7885],"valid"],[[7886,7886],"mapped",[7887]],[[7887,7887],"valid"],[[7888,7888],"mapped",[7889]],[[7889,7889],"valid"],[[7890,7890],"mapped",[7891]],[[7891,7891],"valid"],[[7892,7892],"mapped",[7893]],[[7893,7893],"valid"],[[7894,7894],"mapped",[7895]],[[7895,7895],"valid"],[[7896,7896],"mapped",[7897]],[[7897,7897],"valid"],[[7898,7898],"mapped",[7899]],[[7899,7899],"valid"],[[7900,7900],"mapped",[7901]],[[7901,7901],"valid"],[[7902,7902],"mapped",[7903]],[[7903,7903],"valid"],[[7904,7904],"mapped",[7905]],[[7905,7905],"valid"],[[7906,7906],"mapped",[7907]],[[7907,7907],"valid"],[[7908,7908],"mapped",[7909]],[[7909,7909],"valid"],[[7910,7910],"mapped",[7911]],[[7911,7911],"valid"],[[7912,7912],"mapped",[7913]],[[7913,7913],"valid"],[[7914,7914],"mapped",[7915]],[[7915,7915],"valid"],[[7916,7916],"mapped",[7917]],[[7917,7917],"valid"],[[7918,7918],"mapped",[7919]],[[7919,7919],"valid"],[[7920,7920],"mapped",[7921]],[[7921,7921],"valid"],[[7922,7922],"mapped",[7923]],[[7923,7923],"valid"],[[7924,7924],"mapped",[7925]],[[7925,7925],"valid"],[[7926,7926],"mapped",[7927]],[[7927,7927],"valid"],[[7928,7928],"mapped",[7929]],[[7929,7929],"valid"],[[7930,7930],"mapped",[7931]],[[7931,7931],"valid"],[[7932,7932],"mapped",[7933]],[[7933,7933],"valid"],[[7934,7934],"mapped",[7935]],[[7935,7935],"valid"],[[7936,7943],"valid"],[[7944,7944],"mapped",[7936]],[[7945,7945],"mapped",[7937]],[[7946,7946],"mapped",[7938]],[[7947,7947],"mapped",[7939]],[[7948,7948],"mapped",[7940]],[[7949,7949],"mapped",[7941]],[[7950,7950],"mapped",[7942]],[[7951,7951],"mapped",[7943]],[[7952,7957],"valid"],[[7958,7959],"disallowed"],[[7960,7960],"mapped",[7952]],[[7961,7961],"mapped",[7953]],[[7962,7962],"mapped",[7954]],[[7963,7963],"mapped",[7955]],[[7964,7964],"mapped",[7956]],[[7965,7965],"mapped",[7957]],[[7966,7967],"disallowed"],[[7968,7975],"valid"],[[7976,7976],"mapped",[7968]],[[7977,7977],"mapped",[7969]],[[7978,7978],"mapped",[7970]],[[7979,7979],"mapped",[7971]],[[7980,7980],"mapped",[7972]],[[7981,7981],"mapped",[7973]],[[7982,7982],"mapped",[7974]],[[7983,7983],"mapped",[7975]],[[7984,7991],"valid"],[[7992,7992],"mapped",[7984]],[[7993,7993],"mapped",[7985]],[[7994,7994],"mapped",[7986]],[[7995,7995],"mapped",[7987]],[[7996,7996],"mapped",[7988]],[[7997,7997],"mapped",[7989]],[[7998,7998],"mapped",[7990]],[[7999,7999],"mapped",[7991]],[[8000,8005],"valid"],[[8006,8007],"disallowed"],[[8008,8008],"mapped",[8000]],[[8009,8009],"mapped",[8001]],[[8010,8010],"mapped",[8002]],[[8011,8011],"mapped",[8003]],[[8012,8012],"mapped",[8004]],[[8013,8013],"mapped",[8005]],[[8014,8015],"disallowed"],[[8016,8023],"valid"],[[8024,8024],"disallowed"],[[8025,8025],"mapped",[8017]],[[8026,8026],"disallowed"],[[8027,8027],"mapped",[8019]],[[8028,8028],"disallowed"],[[8029,8029],"mapped",[8021]],[[8030,8030],"disallowed"],[[8031,8031],"mapped",[8023]],[[8032,8039],"valid"],[[8040,8040],"mapped",[8032]],[[8041,8041],"mapped",[8033]],[[8042,8042],"mapped",[8034]],[[8043,8043],"mapped",[8035]],[[8044,8044],"mapped",[8036]],[[8045,8045],"mapped",[8037]],[[8046,8046],"mapped",[8038]],[[8047,8047],"mapped",[8039]],[[8048,8048],"valid"],[[8049,8049],"mapped",[940]],[[8050,8050],"valid"],[[8051,8051],"mapped",[941]],[[8052,8052],"valid"],[[8053,8053],"mapped",[942]],[[8054,8054],"valid"],[[8055,8055],"mapped",[943]],[[8056,8056],"valid"],[[8057,8057],"mapped",[972]],[[8058,8058],"valid"],[[8059,8059],"mapped",[973]],[[8060,8060],"valid"],[[8061,8061],"mapped",[974]],[[8062,8063],"disallowed"],[[8064,8064],"mapped",[7936,953]],[[8065,8065],"mapped",[7937,953]],[[8066,8066],"mapped",[7938,953]],[[8067,8067],"mapped",[7939,953]],[[8068,8068],"mapped",[7940,953]],[[8069,8069],"mapped",[7941,953]],[[8070,8070],"mapped",[7942,953]],[[8071,8071],"mapped",[7943,953]],[[8072,8072],"mapped",[7936,953]],[[8073,8073],"mapped",[7937,953]],[[8074,8074],"mapped",[7938,953]],[[8075,8075],"mapped",[7939,953]],[[8076,8076],"mapped",[7940,953]],[[8077,8077],"mapped",[7941,953]],[[8078,8078],"mapped",[7942,953]],[[8079,8079],"mapped",[7943,953]],[[8080,8080],"mapped",[7968,953]],[[8081,8081],"mapped",[7969,953]],[[8082,8082],"mapped",[7970,953]],[[8083,8083],"mapped",[7971,953]],[[8084,8084],"mapped",[7972,953]],[[8085,8085],"mapped",[7973,953]],[[8086,8086],"mapped",[7974,953]],[[8087,8087],"mapped",[7975,953]],[[8088,8088],"mapped",[7968,953]],[[8089,8089],"mapped",[7969,953]],[[8090,8090],"mapped",[7970,953]],[[8091,8091],"mapped",[7971,953]],[[8092,8092],"mapped",[7972,953]],[[8093,8093],"mapped",[7973,953]],[[8094,8094],"mapped",[7974,953]],[[8095,8095],"mapped",[7975,953]],[[8096,8096],"mapped",[8032,953]],[[8097,8097],"mapped",[8033,953]],[[8098,8098],"mapped",[8034,953]],[[8099,8099],"mapped",[8035,953]],[[8100,8100],"mapped",[8036,953]],[[8101,8101],"mapped",[8037,953]],[[8102,8102],"mapped",[8038,953]],[[8103,8103],"mapped",[8039,953]],[[8104,8104],"mapped",[8032,953]],[[8105,8105],"mapped",[8033,953]],[[8106,8106],"mapped",[8034,953]],[[8107,8107],"mapped",[8035,953]],[[8108,8108],"mapped",[8036,953]],[[8109,8109],"mapped",[8037,953]],[[8110,8110],"mapped",[8038,953]],[[8111,8111],"mapped",[8039,953]],[[8112,8113],"valid"],[[8114,8114],"mapped",[8048,953]],[[8115,8115],"mapped",[945,953]],[[8116,8116],"mapped",[940,953]],[[8117,8117],"disallowed"],[[8118,8118],"valid"],[[8119,8119],"mapped",[8118,953]],[[8120,8120],"mapped",[8112]],[[8121,8121],"mapped",[8113]],[[8122,8122],"mapped",[8048]],[[8123,8123],"mapped",[940]],[[8124,8124],"mapped",[945,953]],[[8125,8125],"disallowed_STD3_mapped",[32,787]],[[8126,8126],"mapped",[953]],[[8127,8127],"disallowed_STD3_mapped",[32,787]],[[8128,8128],"disallowed_STD3_mapped",[32,834]],[[8129,8129],"disallowed_STD3_mapped",[32,776,834]],[[8130,8130],"mapped",[8052,953]],[[8131,8131],"mapped",[951,953]],[[8132,8132],"mapped",[942,953]],[[8133,8133],"disallowed"],[[8134,8134],"valid"],[[8135,8135],"mapped",[8134,953]],[[8136,8136],"mapped",[8050]],[[8137,8137],"mapped",[941]],[[8138,8138],"mapped",[8052]],[[8139,8139],"mapped",[942]],[[8140,8140],"mapped",[951,953]],[[8141,8141],"disallowed_STD3_mapped",[32,787,768]],[[8142,8142],"disallowed_STD3_mapped",[32,787,769]],[[8143,8143],"disallowed_STD3_mapped",[32,787,834]],[[8144,8146],"valid"],[[8147,8147],"mapped",[912]],[[8148,8149],"disallowed"],[[8150,8151],"valid"],[[8152,8152],"mapped",[8144]],[[8153,8153],"mapped",[8145]],[[8154,8154],"mapped",[8054]],[[8155,8155],"mapped",[943]],[[8156,8156],"disallowed"],[[8157,8157],"disallowed_STD3_mapped",[32,788,768]],[[8158,8158],"disallowed_STD3_mapped",[32,788,769]],[[8159,8159],"disallowed_STD3_mapped",[32,788,834]],[[8160,8162],"valid"],[[8163,8163],"mapped",[944]],[[8164,8167],"valid"],[[8168,8168],"mapped",[8160]],[[8169,8169],"mapped",[8161]],[[8170,8170],"mapped",[8058]],[[8171,8171],"mapped",[973]],[[8172,8172],"mapped",[8165]],[[8173,8173],"disallowed_STD3_mapped",[32,776,768]],[[8174,8174],"disallowed_STD3_mapped",[32,776,769]],[[8175,8175],"disallowed_STD3_mapped",[96]],[[8176,8177],"disallowed"],[[8178,8178],"mapped",[8060,953]],[[8179,8179],"mapped",[969,953]],[[8180,8180],"mapped",[974,953]],[[8181,8181],"disallowed"],[[8182,8182],"valid"],[[8183,8183],"mapped",[8182,953]],[[8184,8184],"mapped",[8056]],[[8185,8185],"mapped",[972]],[[8186,8186],"mapped",[8060]],[[8187,8187],"mapped",[974]],[[8188,8188],"mapped",[969,953]],[[8189,8189],"disallowed_STD3_mapped",[32,769]],[[8190,8190],"disallowed_STD3_mapped",[32,788]],[[8191,8191],"disallowed"],[[8192,8202],"disallowed_STD3_mapped",[32]],[[8203,8203],"ignored"],[[8204,8205],"deviation",[]],[[8206,8207],"disallowed"],[[8208,8208],"valid",[],"NV8"],[[8209,8209],"mapped",[8208]],[[8210,8214],"valid",[],"NV8"],[[8215,8215],"disallowed_STD3_mapped",[32,819]],[[8216,8227],"valid",[],"NV8"],[[8228,8230],"disallowed"],[[8231,8231],"valid",[],"NV8"],[[8232,8238],"disallowed"],[[8239,8239],"disallowed_STD3_mapped",[32]],[[8240,8242],"valid",[],"NV8"],[[8243,8243],"mapped",[8242,8242]],[[8244,8244],"mapped",[8242,8242,8242]],[[8245,8245],"valid",[],"NV8"],[[8246,8246],"mapped",[8245,8245]],[[8247,8247],"mapped",[8245,8245,8245]],[[8248,8251],"valid",[],"NV8"],[[8252,8252],"disallowed_STD3_mapped",[33,33]],[[8253,8253],"valid",[],"NV8"],[[8254,8254],"disallowed_STD3_mapped",[32,773]],[[8255,8262],"valid",[],"NV8"],[[8263,8263],"disallowed_STD3_mapped",[63,63]],[[8264,8264],"disallowed_STD3_mapped",[63,33]],[[8265,8265],"disallowed_STD3_mapped",[33,63]],[[8266,8269],"valid",[],"NV8"],[[8270,8274],"valid",[],"NV8"],[[8275,8276],"valid",[],"NV8"],[[8277,8278],"valid",[],"NV8"],[[8279,8279],"mapped",[8242,8242,8242,8242]],[[8280,8286],"valid",[],"NV8"],[[8287,8287],"disallowed_STD3_mapped",[32]],[[8288,8288],"ignored"],[[8289,8291],"disallowed"],[[8292,8292],"ignored"],[[8293,8293],"disallowed"],[[8294,8297],"disallowed"],[[8298,8303],"disallowed"],[[8304,8304],"mapped",[48]],[[8305,8305],"mapped",[105]],[[8306,8307],"disallowed"],[[8308,8308],"mapped",[52]],[[8309,8309],"mapped",[53]],[[8310,8310],"mapped",[54]],[[8311,8311],"mapped",[55]],[[8312,8312],"mapped",[56]],[[8313,8313],"mapped",[57]],[[8314,8314],"disallowed_STD3_mapped",[43]],[[8315,8315],"mapped",[8722]],[[8316,8316],"disallowed_STD3_mapped",[61]],[[8317,8317],"disallowed_STD3_mapped",[40]],[[8318,8318],"disallowed_STD3_mapped",[41]],[[8319,8319],"mapped",[110]],[[8320,8320],"mapped",[48]],[[8321,8321],"mapped",[49]],[[8322,8322],"mapped",[50]],[[8323,8323],"mapped",[51]],[[8324,8324],"mapped",[52]],[[8325,8325],"mapped",[53]],[[8326,8326],"mapped",[54]],[[8327,8327],"mapped",[55]],[[8328,8328],"mapped",[56]],[[8329,8329],"mapped",[57]],[[8330,8330],"disallowed_STD3_mapped",[43]],[[8331,8331],"mapped",[8722]],[[8332,8332],"disallowed_STD3_mapped",[61]],[[8333,8333],"disallowed_STD3_mapped",[40]],[[8334,8334],"disallowed_STD3_mapped",[41]],[[8335,8335],"disallowed"],[[8336,8336],"mapped",[97]],[[8337,8337],"mapped",[101]],[[8338,8338],"mapped",[111]],[[8339,8339],"mapped",[120]],[[8340,8340],"mapped",[601]],[[8341,8341],"mapped",[104]],[[8342,8342],"mapped",[107]],[[8343,8343],"mapped",[108]],[[8344,8344],"mapped",[109]],[[8345,8345],"mapped",[110]],[[8346,8346],"mapped",[112]],[[8347,8347],"mapped",[115]],[[8348,8348],"mapped",[116]],[[8349,8351],"disallowed"],[[8352,8359],"valid",[],"NV8"],[[8360,8360],"mapped",[114,115]],[[8361,8362],"valid",[],"NV8"],[[8363,8363],"valid",[],"NV8"],[[8364,8364],"valid",[],"NV8"],[[8365,8367],"valid",[],"NV8"],[[8368,8369],"valid",[],"NV8"],[[8370,8373],"valid",[],"NV8"],[[8374,8376],"valid",[],"NV8"],[[8377,8377],"valid",[],"NV8"],[[8378,8378],"valid",[],"NV8"],[[8379,8381],"valid",[],"NV8"],[[8382,8382],"valid",[],"NV8"],[[8383,8399],"disallowed"],[[8400,8417],"valid",[],"NV8"],[[8418,8419],"valid",[],"NV8"],[[8420,8426],"valid",[],"NV8"],[[8427,8427],"valid",[],"NV8"],[[8428,8431],"valid",[],"NV8"],[[8432,8432],"valid",[],"NV8"],[[8433,8447],"disallowed"],[[8448,8448],"disallowed_STD3_mapped",[97,47,99]],[[8449,8449],"disallowed_STD3_mapped",[97,47,115]],[[8450,8450],"mapped",[99]],[[8451,8451],"mapped",[176,99]],[[8452,8452],"valid",[],"NV8"],[[8453,8453],"disallowed_STD3_mapped",[99,47,111]],[[8454,8454],"disallowed_STD3_mapped",[99,47,117]],[[8455,8455],"mapped",[603]],[[8456,8456],"valid",[],"NV8"],[[8457,8457],"mapped",[176,102]],[[8458,8458],"mapped",[103]],[[8459,8462],"mapped",[104]],[[8463,8463],"mapped",[295]],[[8464,8465],"mapped",[105]],[[8466,8467],"mapped",[108]],[[8468,8468],"valid",[],"NV8"],[[8469,8469],"mapped",[110]],[[8470,8470],"mapped",[110,111]],[[8471,8472],"valid",[],"NV8"],[[8473,8473],"mapped",[112]],[[8474,8474],"mapped",[113]],[[8475,8477],"mapped",[114]],[[8478,8479],"valid",[],"NV8"],[[8480,8480],"mapped",[115,109]],[[8481,8481],"mapped",[116,101,108]],[[8482,8482],"mapped",[116,109]],[[8483,8483],"valid",[],"NV8"],[[8484,8484],"mapped",[122]],[[8485,8485],"valid",[],"NV8"],[[8486,8486],"mapped",[969]],[[8487,8487],"valid",[],"NV8"],[[8488,8488],"mapped",[122]],[[8489,8489],"valid",[],"NV8"],[[8490,8490],"mapped",[107]],[[8491,8491],"mapped",[229]],[[8492,8492],"mapped",[98]],[[8493,8493],"mapped",[99]],[[8494,8494],"valid",[],"NV8"],[[8495,8496],"mapped",[101]],[[8497,8497],"mapped",[102]],[[8498,8498],"disallowed"],[[8499,8499],"mapped",[109]],[[8500,8500],"mapped",[111]],[[8501,8501],"mapped",[1488]],[[8502,8502],"mapped",[1489]],[[8503,8503],"mapped",[1490]],[[8504,8504],"mapped",[1491]],[[8505,8505],"mapped",[105]],[[8506,8506],"valid",[],"NV8"],[[8507,8507],"mapped",[102,97,120]],[[8508,8508],"mapped",[960]],[[8509,8510],"mapped",[947]],[[8511,8511],"mapped",[960]],[[8512,8512],"mapped",[8721]],[[8513,8516],"valid",[],"NV8"],[[8517,8518],"mapped",[100]],[[8519,8519],"mapped",[101]],[[8520,8520],"mapped",[105]],[[8521,8521],"mapped",[106]],[[8522,8523],"valid",[],"NV8"],[[8524,8524],"valid",[],"NV8"],[[8525,8525],"valid",[],"NV8"],[[8526,8526],"valid"],[[8527,8527],"valid",[],"NV8"],[[8528,8528],"mapped",[49,8260,55]],[[8529,8529],"mapped",[49,8260,57]],[[8530,8530],"mapped",[49,8260,49,48]],[[8531,8531],"mapped",[49,8260,51]],[[8532,8532],"mapped",[50,8260,51]],[[8533,8533],"mapped",[49,8260,53]],[[8534,8534],"mapped",[50,8260,53]],[[8535,8535],"mapped",[51,8260,53]],[[8536,8536],"mapped",[52,8260,53]],[[8537,8537],"mapped",[49,8260,54]],[[8538,8538],"mapped",[53,8260,54]],[[8539,8539],"mapped",[49,8260,56]],[[8540,8540],"mapped",[51,8260,56]],[[8541,8541],"mapped",[53,8260,56]],[[8542,8542],"mapped",[55,8260,56]],[[8543,8543],"mapped",[49,8260]],[[8544,8544],"mapped",[105]],[[8545,8545],"mapped",[105,105]],[[8546,8546],"mapped",[105,105,105]],[[8547,8547],"mapped",[105,118]],[[8548,8548],"mapped",[118]],[[8549,8549],"mapped",[118,105]],[[8550,8550],"mapped",[118,105,105]],[[8551,8551],"mapped",[118,105,105,105]],[[8552,8552],"mapped",[105,120]],[[8553,8553],"mapped",[120]],[[8554,8554],"mapped",[120,105]],[[8555,8555],"mapped",[120,105,105]],[[8556,8556],"mapped",[108]],[[8557,8557],"mapped",[99]],[[8558,8558],"mapped",[100]],[[8559,8559],"mapped",[109]],[[8560,8560],"mapped",[105]],[[8561,8561],"mapped",[105,105]],[[8562,8562],"mapped",[105,105,105]],[[8563,8563],"mapped",[105,118]],[[8564,8564],"mapped",[118]],[[8565,8565],"mapped",[118,105]],[[8566,8566],"mapped",[118,105,105]],[[8567,8567],"mapped",[118,105,105,105]],[[8568,8568],"mapped",[105,120]],[[8569,8569],"mapped",[120]],[[8570,8570],"mapped",[120,105]],[[8571,8571],"mapped",[120,105,105]],[[8572,8572],"mapped",[108]],[[8573,8573],"mapped",[99]],[[8574,8574],"mapped",[100]],[[8575,8575],"mapped",[109]],[[8576,8578],"valid",[],"NV8"],[[8579,8579],"disallowed"],[[8580,8580],"valid"],[[8581,8584],"valid",[],"NV8"],[[8585,8585],"mapped",[48,8260,51]],[[8586,8587],"valid",[],"NV8"],[[8588,8591],"disallowed"],[[8592,8682],"valid",[],"NV8"],[[8683,8691],"valid",[],"NV8"],[[8692,8703],"valid",[],"NV8"],[[8704,8747],"valid",[],"NV8"],[[8748,8748],"mapped",[8747,8747]],[[8749,8749],"mapped",[8747,8747,8747]],[[8750,8750],"valid",[],"NV8"],[[8751,8751],"mapped",[8750,8750]],[[8752,8752],"mapped",[8750,8750,8750]],[[8753,8799],"valid",[],"NV8"],[[8800,8800],"disallowed_STD3_valid"],[[8801,8813],"valid",[],"NV8"],[[8814,8815],"disallowed_STD3_valid"],[[8816,8945],"valid",[],"NV8"],[[8946,8959],"valid",[],"NV8"],[[8960,8960],"valid",[],"NV8"],[[8961,8961],"valid",[],"NV8"],[[8962,9000],"valid",[],"NV8"],[[9001,9001],"mapped",[12296]],[[9002,9002],"mapped",[12297]],[[9003,9082],"valid",[],"NV8"],[[9083,9083],"valid",[],"NV8"],[[9084,9084],"valid",[],"NV8"],[[9085,9114],"valid",[],"NV8"],[[9115,9166],"valid",[],"NV8"],[[9167,9168],"valid",[],"NV8"],[[9169,9179],"valid",[],"NV8"],[[9180,9191],"valid",[],"NV8"],[[9192,9192],"valid",[],"NV8"],[[9193,9203],"valid",[],"NV8"],[[9204,9210],"valid",[],"NV8"],[[9211,9215],"disallowed"],[[9216,9252],"valid",[],"NV8"],[[9253,9254],"valid",[],"NV8"],[[9255,9279],"disallowed"],[[9280,9290],"valid",[],"NV8"],[[9291,9311],"disallowed"],[[9312,9312],"mapped",[49]],[[9313,9313],"mapped",[50]],[[9314,9314],"mapped",[51]],[[9315,9315],"mapped",[52]],[[9316,9316],"mapped",[53]],[[9317,9317],"mapped",[54]],[[9318,9318],"mapped",[55]],[[9319,9319],"mapped",[56]],[[9320,9320],"mapped",[57]],[[9321,9321],"mapped",[49,48]],[[9322,9322],"mapped",[49,49]],[[9323,9323],"mapped",[49,50]],[[9324,9324],"mapped",[49,51]],[[9325,9325],"mapped",[49,52]],[[9326,9326],"mapped",[49,53]],[[9327,9327],"mapped",[49,54]],[[9328,9328],"mapped",[49,55]],[[9329,9329],"mapped",[49,56]],[[9330,9330],"mapped",[49,57]],[[9331,9331],"mapped",[50,48]],[[9332,9332],"disallowed_STD3_mapped",[40,49,41]],[[9333,9333],"disallowed_STD3_mapped",[40,50,41]],[[9334,9334],"disallowed_STD3_mapped",[40,51,41]],[[9335,9335],"disallowed_STD3_mapped",[40,52,41]],[[9336,9336],"disallowed_STD3_mapped",[40,53,41]],[[9337,9337],"disallowed_STD3_mapped",[40,54,41]],[[9338,9338],"disallowed_STD3_mapped",[40,55,41]],[[9339,9339],"disallowed_STD3_mapped",[40,56,41]],[[9340,9340],"disallowed_STD3_mapped",[40,57,41]],[[9341,9341],"disallowed_STD3_mapped",[40,49,48,41]],[[9342,9342],"disallowed_STD3_mapped",[40,49,49,41]],[[9343,9343],"disallowed_STD3_mapped",[40,49,50,41]],[[9344,9344],"disallowed_STD3_mapped",[40,49,51,41]],[[9345,9345],"disallowed_STD3_mapped",[40,49,52,41]],[[9346,9346],"disallowed_STD3_mapped",[40,49,53,41]],[[9347,9347],"disallowed_STD3_mapped",[40,49,54,41]],[[9348,9348],"disallowed_STD3_mapped",[40,49,55,41]],[[9349,9349],"disallowed_STD3_mapped",[40,49,56,41]],[[9350,9350],"disallowed_STD3_mapped",[40,49,57,41]],[[9351,9351],"disallowed_STD3_mapped",[40,50,48,41]],[[9352,9371],"disallowed"],[[9372,9372],"disallowed_STD3_mapped",[40,97,41]],[[9373,9373],"disallowed_STD3_mapped",[40,98,41]],[[9374,9374],"disallowed_STD3_mapped",[40,99,41]],[[9375,9375],"disallowed_STD3_mapped",[40,100,41]],[[9376,9376],"disallowed_STD3_mapped",[40,101,41]],[[9377,9377],"disallowed_STD3_mapped",[40,102,41]],[[9378,9378],"disallowed_STD3_mapped",[40,103,41]],[[9379,9379],"disallowed_STD3_mapped",[40,104,41]],[[9380,9380],"disallowed_STD3_mapped",[40,105,41]],[[9381,9381],"disallowed_STD3_mapped",[40,106,41]],[[9382,9382],"disallowed_STD3_mapped",[40,107,41]],[[9383,9383],"disallowed_STD3_mapped",[40,108,41]],[[9384,9384],"disallowed_STD3_mapped",[40,109,41]],[[9385,9385],"disallowed_STD3_mapped",[40,110,41]],[[9386,9386],"disallowed_STD3_mapped",[40,111,41]],[[9387,9387],"disallowed_STD3_mapped",[40,112,41]],[[9388,9388],"disallowed_STD3_mapped",[40,113,41]],[[9389,9389],"disallowed_STD3_mapped",[40,114,41]],[[9390,9390],"disallowed_STD3_mapped",[40,115,41]],[[9391,9391],"disallowed_STD3_mapped",[40,116,41]],[[9392,9392],"disallowed_STD3_mapped",[40,117,41]],[[9393,9393],"disallowed_STD3_mapped",[40,118,41]],[[9394,9394],"disallowed_STD3_mapped",[40,119,41]],[[9395,9395],"disallowed_STD3_mapped",[40,120,41]],[[9396,9396],"disallowed_STD3_mapped",[40,121,41]],[[9397,9397],"disallowed_STD3_mapped",[40,122,41]],[[9398,9398],"mapped",[97]],[[9399,9399],"mapped",[98]],[[9400,9400],"mapped",[99]],[[9401,9401],"mapped",[100]],[[9402,9402],"mapped",[101]],[[9403,9403],"mapped",[102]],[[9404,9404],"mapped",[103]],[[9405,9405],"mapped",[104]],[[9406,9406],"mapped",[105]],[[9407,9407],"mapped",[106]],[[9408,9408],"mapped",[107]],[[9409,9409],"mapped",[108]],[[9410,9410],"mapped",[109]],[[9411,9411],"mapped",[110]],[[9412,9412],"mapped",[111]],[[9413,9413],"mapped",[112]],[[9414,9414],"mapped",[113]],[[9415,9415],"mapped",[114]],[[9416,9416],"mapped",[115]],[[9417,9417],"mapped",[116]],[[9418,9418],"mapped",[117]],[[9419,9419],"mapped",[118]],[[9420,9420],"mapped",[119]],[[9421,9421],"mapped",[120]],[[9422,9422],"mapped",[121]],[[9423,9423],"mapped",[122]],[[9424,9424],"mapped",[97]],[[9425,9425],"mapped",[98]],[[9426,9426],"mapped",[99]],[[9427,9427],"mapped",[100]],[[9428,9428],"mapped",[101]],[[9429,9429],"mapped",[102]],[[9430,9430],"mapped",[103]],[[9431,9431],"mapped",[104]],[[9432,9432],"mapped",[105]],[[9433,9433],"mapped",[106]],[[9434,9434],"mapped",[107]],[[9435,9435],"mapped",[108]],[[9436,9436],"mapped",[109]],[[9437,9437],"mapped",[110]],[[9438,9438],"mapped",[111]],[[9439,9439],"mapped",[112]],[[9440,9440],"mapped",[113]],[[9441,9441],"mapped",[114]],[[9442,9442],"mapped",[115]],[[9443,9443],"mapped",[116]],[[9444,9444],"mapped",[117]],[[9445,9445],"mapped",[118]],[[9446,9446],"mapped",[119]],[[9447,9447],"mapped",[120]],[[9448,9448],"mapped",[121]],[[9449,9449],"mapped",[122]],[[9450,9450],"mapped",[48]],[[9451,9470],"valid",[],"NV8"],[[9471,9471],"valid",[],"NV8"],[[9472,9621],"valid",[],"NV8"],[[9622,9631],"valid",[],"NV8"],[[9632,9711],"valid",[],"NV8"],[[9712,9719],"valid",[],"NV8"],[[9720,9727],"valid",[],"NV8"],[[9728,9747],"valid",[],"NV8"],[[9748,9749],"valid",[],"NV8"],[[9750,9751],"valid",[],"NV8"],[[9752,9752],"valid",[],"NV8"],[[9753,9753],"valid",[],"NV8"],[[9754,9839],"valid",[],"NV8"],[[9840,9841],"valid",[],"NV8"],[[9842,9853],"valid",[],"NV8"],[[9854,9855],"valid",[],"NV8"],[[9856,9865],"valid",[],"NV8"],[[9866,9873],"valid",[],"NV8"],[[9874,9884],"valid",[],"NV8"],[[9885,9885],"valid",[],"NV8"],[[9886,9887],"valid",[],"NV8"],[[9888,9889],"valid",[],"NV8"],[[9890,9905],"valid",[],"NV8"],[[9906,9906],"valid",[],"NV8"],[[9907,9916],"valid",[],"NV8"],[[9917,9919],"valid",[],"NV8"],[[9920,9923],"valid",[],"NV8"],[[9924,9933],"valid",[],"NV8"],[[9934,9934],"valid",[],"NV8"],[[9935,9953],"valid",[],"NV8"],[[9954,9954],"valid",[],"NV8"],[[9955,9955],"valid",[],"NV8"],[[9956,9959],"valid",[],"NV8"],[[9960,9983],"valid",[],"NV8"],[[9984,9984],"valid",[],"NV8"],[[9985,9988],"valid",[],"NV8"],[[9989,9989],"valid",[],"NV8"],[[9990,9993],"valid",[],"NV8"],[[9994,9995],"valid",[],"NV8"],[[9996,10023],"valid",[],"NV8"],[[10024,10024],"valid",[],"NV8"],[[10025,10059],"valid",[],"NV8"],[[10060,10060],"valid",[],"NV8"],[[10061,10061],"valid",[],"NV8"],[[10062,10062],"valid",[],"NV8"],[[10063,10066],"valid",[],"NV8"],[[10067,10069],"valid",[],"NV8"],[[10070,10070],"valid",[],"NV8"],[[10071,10071],"valid",[],"NV8"],[[10072,10078],"valid",[],"NV8"],[[10079,10080],"valid",[],"NV8"],[[10081,10087],"valid",[],"NV8"],[[10088,10101],"valid",[],"NV8"],[[10102,10132],"valid",[],"NV8"],[[10133,10135],"valid",[],"NV8"],[[10136,10159],"valid",[],"NV8"],[[10160,10160],"valid",[],"NV8"],[[10161,10174],"valid",[],"NV8"],[[10175,10175],"valid",[],"NV8"],[[10176,10182],"valid",[],"NV8"],[[10183,10186],"valid",[],"NV8"],[[10187,10187],"valid",[],"NV8"],[[10188,10188],"valid",[],"NV8"],[[10189,10189],"valid",[],"NV8"],[[10190,10191],"valid",[],"NV8"],[[10192,10219],"valid",[],"NV8"],[[10220,10223],"valid",[],"NV8"],[[10224,10239],"valid",[],"NV8"],[[10240,10495],"valid",[],"NV8"],[[10496,10763],"valid",[],"NV8"],[[10764,10764],"mapped",[8747,8747,8747,8747]],[[10765,10867],"valid",[],"NV8"],[[10868,10868],"disallowed_STD3_mapped",[58,58,61]],[[10869,10869],"disallowed_STD3_mapped",[61,61]],[[10870,10870],"disallowed_STD3_mapped",[61,61,61]],[[10871,10971],"valid",[],"NV8"],[[10972,10972],"mapped",[10973,824]],[[10973,11007],"valid",[],"NV8"],[[11008,11021],"valid",[],"NV8"],[[11022,11027],"valid",[],"NV8"],[[11028,11034],"valid",[],"NV8"],[[11035,11039],"valid",[],"NV8"],[[11040,11043],"valid",[],"NV8"],[[11044,11084],"valid",[],"NV8"],[[11085,11087],"valid",[],"NV8"],[[11088,11092],"valid",[],"NV8"],[[11093,11097],"valid",[],"NV8"],[[11098,11123],"valid",[],"NV8"],[[11124,11125],"disallowed"],[[11126,11157],"valid",[],"NV8"],[[11158,11159],"disallowed"],[[11160,11193],"valid",[],"NV8"],[[11194,11196],"disallowed"],[[11197,11208],"valid",[],"NV8"],[[11209,11209],"disallowed"],[[11210,11217],"valid",[],"NV8"],[[11218,11243],"disallowed"],[[11244,11247],"valid",[],"NV8"],[[11248,11263],"disallowed"],[[11264,11264],"mapped",[11312]],[[11265,11265],"mapped",[11313]],[[11266,11266],"mapped",[11314]],[[11267,11267],"mapped",[11315]],[[11268,11268],"mapped",[11316]],[[11269,11269],"mapped",[11317]],[[11270,11270],"mapped",[11318]],[[11271,11271],"mapped",[11319]],[[11272,11272],"mapped",[11320]],[[11273,11273],"mapped",[11321]],[[11274,11274],"mapped",[11322]],[[11275,11275],"mapped",[11323]],[[11276,11276],"mapped",[11324]],[[11277,11277],"mapped",[11325]],[[11278,11278],"mapped",[11326]],[[11279,11279],"mapped",[11327]],[[11280,11280],"mapped",[11328]],[[11281,11281],"mapped",[11329]],[[11282,11282],"mapped",[11330]],[[11283,11283],"mapped",[11331]],[[11284,11284],"mapped",[11332]],[[11285,11285],"mapped",[11333]],[[11286,11286],"mapped",[11334]],[[11287,11287],"mapped",[11335]],[[11288,11288],"mapped",[11336]],[[11289,11289],"mapped",[11337]],[[11290,11290],"mapped",[11338]],[[11291,11291],"mapped",[11339]],[[11292,11292],"mapped",[11340]],[[11293,11293],"mapped",[11341]],[[11294,11294],"mapped",[11342]],[[11295,11295],"mapped",[11343]],[[11296,11296],"mapped",[11344]],[[11297,11297],"mapped",[11345]],[[11298,11298],"mapped",[11346]],[[11299,11299],"mapped",[11347]],[[11300,11300],"mapped",[11348]],[[11301,11301],"mapped",[11349]],[[11302,11302],"mapped",[11350]],[[11303,11303],"mapped",[11351]],[[11304,11304],"mapped",[11352]],[[11305,11305],"mapped",[11353]],[[11306,11306],"mapped",[11354]],[[11307,11307],"mapped",[11355]],[[11308,11308],"mapped",[11356]],[[11309,11309],"mapped",[11357]],[[11310,11310],"mapped",[11358]],[[11311,11311],"disallowed"],[[11312,11358],"valid"],[[11359,11359],"disallowed"],[[11360,11360],"mapped",[11361]],[[11361,11361],"valid"],[[11362,11362],"mapped",[619]],[[11363,11363],"mapped",[7549]],[[11364,11364],"mapped",[637]],[[11365,11366],"valid"],[[11367,11367],"mapped",[11368]],[[11368,11368],"valid"],[[11369,11369],"mapped",[11370]],[[11370,11370],"valid"],[[11371,11371],"mapped",[11372]],[[11372,11372],"valid"],[[11373,11373],"mapped",[593]],[[11374,11374],"mapped",[625]],[[11375,11375],"mapped",[592]],[[11376,11376],"mapped",[594]],[[11377,11377],"valid"],[[11378,11378],"mapped",[11379]],[[11379,11379],"valid"],[[11380,11380],"valid"],[[11381,11381],"mapped",[11382]],[[11382,11383],"valid"],[[11384,11387],"valid"],[[11388,11388],"mapped",[106]],[[11389,11389],"mapped",[118]],[[11390,11390],"mapped",[575]],[[11391,11391],"mapped",[576]],[[11392,11392],"mapped",[11393]],[[11393,11393],"valid"],[[11394,11394],"mapped",[11395]],[[11395,11395],"valid"],[[11396,11396],"mapped",[11397]],[[11397,11397],"valid"],[[11398,11398],"mapped",[11399]],[[11399,11399],"valid"],[[11400,11400],"mapped",[11401]],[[11401,11401],"valid"],[[11402,11402],"mapped",[11403]],[[11403,11403],"valid"],[[11404,11404],"mapped",[11405]],[[11405,11405],"valid"],[[11406,11406],"mapped",[11407]],[[11407,11407],"valid"],[[11408,11408],"mapped",[11409]],[[11409,11409],"valid"],[[11410,11410],"mapped",[11411]],[[11411,11411],"valid"],[[11412,11412],"mapped",[11413]],[[11413,11413],"valid"],[[11414,11414],"mapped",[11415]],[[11415,11415],"valid"],[[11416,11416],"mapped",[11417]],[[11417,11417],"valid"],[[11418,11418],"mapped",[11419]],[[11419,11419],"valid"],[[11420,11420],"mapped",[11421]],[[11421,11421],"valid"],[[11422,11422],"mapped",[11423]],[[11423,11423],"valid"],[[11424,11424],"mapped",[11425]],[[11425,11425],"valid"],[[11426,11426],"mapped",[11427]],[[11427,11427],"valid"],[[11428,11428],"mapped",[11429]],[[11429,11429],"valid"],[[11430,11430],"mapped",[11431]],[[11431,11431],"valid"],[[11432,11432],"mapped",[11433]],[[11433,11433],"valid"],[[11434,11434],"mapped",[11435]],[[11435,11435],"valid"],[[11436,11436],"mapped",[11437]],[[11437,11437],"valid"],[[11438,11438],"mapped",[11439]],[[11439,11439],"valid"],[[11440,11440],"mapped",[11441]],[[11441,11441],"valid"],[[11442,11442],"mapped",[11443]],[[11443,11443],"valid"],[[11444,11444],"mapped",[11445]],[[11445,11445],"valid"],[[11446,11446],"mapped",[11447]],[[11447,11447],"valid"],[[11448,11448],"mapped",[11449]],[[11449,11449],"valid"],[[11450,11450],"mapped",[11451]],[[11451,11451],"valid"],[[11452,11452],"mapped",[11453]],[[11453,11453],"valid"],[[11454,11454],"mapped",[11455]],[[11455,11455],"valid"],[[11456,11456],"mapped",[11457]],[[11457,11457],"valid"],[[11458,11458],"mapped",[11459]],[[11459,11459],"valid"],[[11460,11460],"mapped",[11461]],[[11461,11461],"valid"],[[11462,11462],"mapped",[11463]],[[11463,11463],"valid"],[[11464,11464],"mapped",[11465]],[[11465,11465],"valid"],[[11466,11466],"mapped",[11467]],[[11467,11467],"valid"],[[11468,11468],"mapped",[11469]],[[11469,11469],"valid"],[[11470,11470],"mapped",[11471]],[[11471,11471],"valid"],[[11472,11472],"mapped",[11473]],[[11473,11473],"valid"],[[11474,11474],"mapped",[11475]],[[11475,11475],"valid"],[[11476,11476],"mapped",[11477]],[[11477,11477],"valid"],[[11478,11478],"mapped",[11479]],[[11479,11479],"valid"],[[11480,11480],"mapped",[11481]],[[11481,11481],"valid"],[[11482,11482],"mapped",[11483]],[[11483,11483],"valid"],[[11484,11484],"mapped",[11485]],[[11485,11485],"valid"],[[11486,11486],"mapped",[11487]],[[11487,11487],"valid"],[[11488,11488],"mapped",[11489]],[[11489,11489],"valid"],[[11490,11490],"mapped",[11491]],[[11491,11492],"valid"],[[11493,11498],"valid",[],"NV8"],[[11499,11499],"mapped",[11500]],[[11500,11500],"valid"],[[11501,11501],"mapped",[11502]],[[11502,11505],"valid"],[[11506,11506],"mapped",[11507]],[[11507,11507],"valid"],[[11508,11512],"disallowed"],[[11513,11519],"valid",[],"NV8"],[[11520,11557],"valid"],[[11558,11558],"disallowed"],[[11559,11559],"valid"],[[11560,11564],"disallowed"],[[11565,11565],"valid"],[[11566,11567],"disallowed"],[[11568,11621],"valid"],[[11622,11623],"valid"],[[11624,11630],"disallowed"],[[11631,11631],"mapped",[11617]],[[11632,11632],"valid",[],"NV8"],[[11633,11646],"disallowed"],[[11647,11647],"valid"],[[11648,11670],"valid"],[[11671,11679],"disallowed"],[[11680,11686],"valid"],[[11687,11687],"disallowed"],[[11688,11694],"valid"],[[11695,11695],"disallowed"],[[11696,11702],"valid"],[[11703,11703],"disallowed"],[[11704,11710],"valid"],[[11711,11711],"disallowed"],[[11712,11718],"valid"],[[11719,11719],"disallowed"],[[11720,11726],"valid"],[[11727,11727],"disallowed"],[[11728,11734],"valid"],[[11735,11735],"disallowed"],[[11736,11742],"valid"],[[11743,11743],"disallowed"],[[11744,11775],"valid"],[[11776,11799],"valid",[],"NV8"],[[11800,11803],"valid",[],"NV8"],[[11804,11805],"valid",[],"NV8"],[[11806,11822],"valid",[],"NV8"],[[11823,11823],"valid"],[[11824,11824],"valid",[],"NV8"],[[11825,11825],"valid",[],"NV8"],[[11826,11835],"valid",[],"NV8"],[[11836,11842],"valid",[],"NV8"],[[11843,11903],"disallowed"],[[11904,11929],"valid",[],"NV8"],[[11930,11930],"disallowed"],[[11931,11934],"valid",[],"NV8"],[[11935,11935],"mapped",[27597]],[[11936,12018],"valid",[],"NV8"],[[12019,12019],"mapped",[40863]],[[12020,12031],"disallowed"],[[12032,12032],"mapped",[19968]],[[12033,12033],"mapped",[20008]],[[12034,12034],"mapped",[20022]],[[12035,12035],"mapped",[20031]],[[12036,12036],"mapped",[20057]],[[12037,12037],"mapped",[20101]],[[12038,12038],"mapped",[20108]],[[12039,12039],"mapped",[20128]],[[12040,12040],"mapped",[20154]],[[12041,12041],"mapped",[20799]],[[12042,12042],"mapped",[20837]],[[12043,12043],"mapped",[20843]],[[12044,12044],"mapped",[20866]],[[12045,12045],"mapped",[20886]],[[12046,12046],"mapped",[20907]],[[12047,12047],"mapped",[20960]],[[12048,12048],"mapped",[20981]],[[12049,12049],"mapped",[20992]],[[12050,12050],"mapped",[21147]],[[12051,12051],"mapped",[21241]],[[12052,12052],"mapped",[21269]],[[12053,12053],"mapped",[21274]],[[12054,12054],"mapped",[21304]],[[12055,12055],"mapped",[21313]],[[12056,12056],"mapped",[21340]],[[12057,12057],"mapped",[21353]],[[12058,12058],"mapped",[21378]],[[12059,12059],"mapped",[21430]],[[12060,12060],"mapped",[21448]],[[12061,12061],"mapped",[21475]],[[12062,12062],"mapped",[22231]],[[12063,12063],"mapped",[22303]],[[12064,12064],"mapped",[22763]],[[12065,12065],"mapped",[22786]],[[12066,12066],"mapped",[22794]],[[12067,12067],"mapped",[22805]],[[12068,12068],"mapped",[22823]],[[12069,12069],"mapped",[22899]],[[12070,12070],"mapped",[23376]],[[12071,12071],"mapped",[23424]],[[12072,12072],"mapped",[23544]],[[12073,12073],"mapped",[23567]],[[12074,12074],"mapped",[23586]],[[12075,12075],"mapped",[23608]],[[12076,12076],"mapped",[23662]],[[12077,12077],"mapped",[23665]],[[12078,12078],"mapped",[24027]],[[12079,12079],"mapped",[24037]],[[12080,12080],"mapped",[24049]],[[12081,12081],"mapped",[24062]],[[12082,12082],"mapped",[24178]],[[12083,12083],"mapped",[24186]],[[12084,12084],"mapped",[24191]],[[12085,12085],"mapped",[24308]],[[12086,12086],"mapped",[24318]],[[12087,12087],"mapped",[24331]],[[12088,12088],"mapped",[24339]],[[12089,12089],"mapped",[24400]],[[12090,12090],"mapped",[24417]],[[12091,12091],"mapped",[24435]],[[12092,12092],"mapped",[24515]],[[12093,12093],"mapped",[25096]],[[12094,12094],"mapped",[25142]],[[12095,12095],"mapped",[25163]],[[12096,12096],"mapped",[25903]],[[12097,12097],"mapped",[25908]],[[12098,12098],"mapped",[25991]],[[12099,12099],"mapped",[26007]],[[12100,12100],"mapped",[26020]],[[12101,12101],"mapped",[26041]],[[12102,12102],"mapped",[26080]],[[12103,12103],"mapped",[26085]],[[12104,12104],"mapped",[26352]],[[12105,12105],"mapped",[26376]],[[12106,12106],"mapped",[26408]],[[12107,12107],"mapped",[27424]],[[12108,12108],"mapped",[27490]],[[12109,12109],"mapped",[27513]],[[12110,12110],"mapped",[27571]],[[12111,12111],"mapped",[27595]],[[12112,12112],"mapped",[27604]],[[12113,12113],"mapped",[27611]],[[12114,12114],"mapped",[27663]],[[12115,12115],"mapped",[27668]],[[12116,12116],"mapped",[27700]],[[12117,12117],"mapped",[28779]],[[12118,12118],"mapped",[29226]],[[12119,12119],"mapped",[29238]],[[12120,12120],"mapped",[29243]],[[12121,12121],"mapped",[29247]],[[12122,12122],"mapped",[29255]],[[12123,12123],"mapped",[29273]],[[12124,12124],"mapped",[29275]],[[12125,12125],"mapped",[29356]],[[12126,12126],"mapped",[29572]],[[12127,12127],"mapped",[29577]],[[12128,12128],"mapped",[29916]],[[12129,12129],"mapped",[29926]],[[12130,12130],"mapped",[29976]],[[12131,12131],"mapped",[29983]],[[12132,12132],"mapped",[29992]],[[12133,12133],"mapped",[30000]],[[12134,12134],"mapped",[30091]],[[12135,12135],"mapped",[30098]],[[12136,12136],"mapped",[30326]],[[12137,12137],"mapped",[30333]],[[12138,12138],"mapped",[30382]],[[12139,12139],"mapped",[30399]],[[12140,12140],"mapped",[30446]],[[12141,12141],"mapped",[30683]],[[12142,12142],"mapped",[30690]],[[12143,12143],"mapped",[30707]],[[12144,12144],"mapped",[31034]],[[12145,12145],"mapped",[31160]],[[12146,12146],"mapped",[31166]],[[12147,12147],"mapped",[31348]],[[12148,12148],"mapped",[31435]],[[12149,12149],"mapped",[31481]],[[12150,12150],"mapped",[31859]],[[12151,12151],"mapped",[31992]],[[12152,12152],"mapped",[32566]],[[12153,12153],"mapped",[32593]],[[12154,12154],"mapped",[32650]],[[12155,12155],"mapped",[32701]],[[12156,12156],"mapped",[32769]],[[12157,12157],"mapped",[32780]],[[12158,12158],"mapped",[32786]],[[12159,12159],"mapped",[32819]],[[12160,12160],"mapped",[32895]],[[12161,12161],"mapped",[32905]],[[12162,12162],"mapped",[33251]],[[12163,12163],"mapped",[33258]],[[12164,12164],"mapped",[33267]],[[12165,12165],"mapped",[33276]],[[12166,12166],"mapped",[33292]],[[12167,12167],"mapped",[33307]],[[12168,12168],"mapped",[33311]],[[12169,12169],"mapped",[33390]],[[12170,12170],"mapped",[33394]],[[12171,12171],"mapped",[33400]],[[12172,12172],"mapped",[34381]],[[12173,12173],"mapped",[34411]],[[12174,12174],"mapped",[34880]],[[12175,12175],"mapped",[34892]],[[12176,12176],"mapped",[34915]],[[12177,12177],"mapped",[35198]],[[12178,12178],"mapped",[35211]],[[12179,12179],"mapped",[35282]],[[12180,12180],"mapped",[35328]],[[12181,12181],"mapped",[35895]],[[12182,12182],"mapped",[35910]],[[12183,12183],"mapped",[35925]],[[12184,12184],"mapped",[35960]],[[12185,12185],"mapped",[35997]],[[12186,12186],"mapped",[36196]],[[12187,12187],"mapped",[36208]],[[12188,12188],"mapped",[36275]],[[12189,12189],"mapped",[36523]],[[12190,12190],"mapped",[36554]],[[12191,12191],"mapped",[36763]],[[12192,12192],"mapped",[36784]],[[12193,12193],"mapped",[36789]],[[12194,12194],"mapped",[37009]],[[12195,12195],"mapped",[37193]],[[12196,12196],"mapped",[37318]],[[12197,12197],"mapped",[37324]],[[12198,12198],"mapped",[37329]],[[12199,12199],"mapped",[38263]],[[12200,12200],"mapped",[38272]],[[12201,12201],"mapped",[38428]],[[12202,12202],"mapped",[38582]],[[12203,12203],"mapped",[38585]],[[12204,12204],"mapped",[38632]],[[12205,12205],"mapped",[38737]],[[12206,12206],"mapped",[38750]],[[12207,12207],"mapped",[38754]],[[12208,12208],"mapped",[38761]],[[12209,12209],"mapped",[38859]],[[12210,12210],"mapped",[38893]],[[12211,12211],"mapped",[38899]],[[12212,12212],"mapped",[38913]],[[12213,12213],"mapped",[39080]],[[12214,12214],"mapped",[39131]],[[12215,12215],"mapped",[39135]],[[12216,12216],"mapped",[39318]],[[12217,12217],"mapped",[39321]],[[12218,12218],"mapped",[39340]],[[12219,12219],"mapped",[39592]],[[12220,12220],"mapped",[39640]],[[12221,12221],"mapped",[39647]],[[12222,12222],"mapped",[39717]],[[12223,12223],"mapped",[39727]],[[12224,12224],"mapped",[39730]],[[12225,12225],"mapped",[39740]],[[12226,12226],"mapped",[39770]],[[12227,12227],"mapped",[40165]],[[12228,12228],"mapped",[40565]],[[12229,12229],"mapped",[40575]],[[12230,12230],"mapped",[40613]],[[12231,12231],"mapped",[40635]],[[12232,12232],"mapped",[40643]],[[12233,12233],"mapped",[40653]],[[12234,12234],"mapped",[40657]],[[12235,12235],"mapped",[40697]],[[12236,12236],"mapped",[40701]],[[12237,12237],"mapped",[40718]],[[12238,12238],"mapped",[40723]],[[12239,12239],"mapped",[40736]],[[12240,12240],"mapped",[40763]],[[12241,12241],"mapped",[40778]],[[12242,12242],"mapped",[40786]],[[12243,12243],"mapped",[40845]],[[12244,12244],"mapped",[40860]],[[12245,12245],"mapped",[40864]],[[12246,12271],"disallowed"],[[12272,12283],"disallowed"],[[12284,12287],"disallowed"],[[12288,12288],"disallowed_STD3_mapped",[32]],[[12289,12289],"valid",[],"NV8"],[[12290,12290],"mapped",[46]],[[12291,12292],"valid",[],"NV8"],[[12293,12295],"valid"],[[12296,12329],"valid",[],"NV8"],[[12330,12333],"valid"],[[12334,12341],"valid",[],"NV8"],[[12342,12342],"mapped",[12306]],[[12343,12343],"valid",[],"NV8"],[[12344,12344],"mapped",[21313]],[[12345,12345],"mapped",[21316]],[[12346,12346],"mapped",[21317]],[[12347,12347],"valid",[],"NV8"],[[12348,12348],"valid"],[[12349,12349],"valid",[],"NV8"],[[12350,12350],"valid",[],"NV8"],[[12351,12351],"valid",[],"NV8"],[[12352,12352],"disallowed"],[[12353,12436],"valid"],[[12437,12438],"valid"],[[12439,12440],"disallowed"],[[12441,12442],"valid"],[[12443,12443],"disallowed_STD3_mapped",[32,12441]],[[12444,12444],"disallowed_STD3_mapped",[32,12442]],[[12445,12446],"valid"],[[12447,12447],"mapped",[12424,12426]],[[12448,12448],"valid",[],"NV8"],[[12449,12542],"valid"],[[12543,12543],"mapped",[12467,12488]],[[12544,12548],"disallowed"],[[12549,12588],"valid"],[[12589,12589],"valid"],[[12590,12592],"disallowed"],[[12593,12593],"mapped",[4352]],[[12594,12594],"mapped",[4353]],[[12595,12595],"mapped",[4522]],[[12596,12596],"mapped",[4354]],[[12597,12597],"mapped",[4524]],[[12598,12598],"mapped",[4525]],[[12599,12599],"mapped",[4355]],[[12600,12600],"mapped",[4356]],[[12601,12601],"mapped",[4357]],[[12602,12602],"mapped",[4528]],[[12603,12603],"mapped",[4529]],[[12604,12604],"mapped",[4530]],[[12605,12605],"mapped",[4531]],[[12606,12606],"mapped",[4532]],[[12607,12607],"mapped",[4533]],[[12608,12608],"mapped",[4378]],[[12609,12609],"mapped",[4358]],[[12610,12610],"mapped",[4359]],[[12611,12611],"mapped",[4360]],[[12612,12612],"mapped",[4385]],[[12613,12613],"mapped",[4361]],[[12614,12614],"mapped",[4362]],[[12615,12615],"mapped",[4363]],[[12616,12616],"mapped",[4364]],[[12617,12617],"mapped",[4365]],[[12618,12618],"mapped",[4366]],[[12619,12619],"mapped",[4367]],[[12620,12620],"mapped",[4368]],[[12621,12621],"mapped",[4369]],[[12622,12622],"mapped",[4370]],[[12623,12623],"mapped",[4449]],[[12624,12624],"mapped",[4450]],[[12625,12625],"mapped",[4451]],[[12626,12626],"mapped",[4452]],[[12627,12627],"mapped",[4453]],[[12628,12628],"mapped",[4454]],[[12629,12629],"mapped",[4455]],[[12630,12630],"mapped",[4456]],[[12631,12631],"mapped",[4457]],[[12632,12632],"mapped",[4458]],[[12633,12633],"mapped",[4459]],[[12634,12634],"mapped",[4460]],[[12635,12635],"mapped",[4461]],[[12636,12636],"mapped",[4462]],[[12637,12637],"mapped",[4463]],[[12638,12638],"mapped",[4464]],[[12639,12639],"mapped",[4465]],[[12640,12640],"mapped",[4466]],[[12641,12641],"mapped",[4467]],[[12642,12642],"mapped",[4468]],[[12643,12643],"mapped",[4469]],[[12644,12644],"disallowed"],[[12645,12645],"mapped",[4372]],[[12646,12646],"mapped",[4373]],[[12647,12647],"mapped",[4551]],[[12648,12648],"mapped",[4552]],[[12649,12649],"mapped",[4556]],[[12650,12650],"mapped",[4558]],[[12651,12651],"mapped",[4563]],[[12652,12652],"mapped",[4567]],[[12653,12653],"mapped",[4569]],[[12654,12654],"mapped",[4380]],[[12655,12655],"mapped",[4573]],[[12656,12656],"mapped",[4575]],[[12657,12657],"mapped",[4381]],[[12658,12658],"mapped",[4382]],[[12659,12659],"mapped",[4384]],[[12660,12660],"mapped",[4386]],[[12661,12661],"mapped",[4387]],[[12662,12662],"mapped",[4391]],[[12663,12663],"mapped",[4393]],[[12664,12664],"mapped",[4395]],[[12665,12665],"mapped",[4396]],[[12666,12666],"mapped",[4397]],[[12667,12667],"mapped",[4398]],[[12668,12668],"mapped",[4399]],[[12669,12669],"mapped",[4402]],[[12670,12670],"mapped",[4406]],[[12671,12671],"mapped",[4416]],[[12672,12672],"mapped",[4423]],[[12673,12673],"mapped",[4428]],[[12674,12674],"mapped",[4593]],[[12675,12675],"mapped",[4594]],[[12676,12676],"mapped",[4439]],[[12677,12677],"mapped",[4440]],[[12678,12678],"mapped",[4441]],[[12679,12679],"mapped",[4484]],[[12680,12680],"mapped",[4485]],[[12681,12681],"mapped",[4488]],[[12682,12682],"mapped",[4497]],[[12683,12683],"mapped",[4498]],[[12684,12684],"mapped",[4500]],[[12685,12685],"mapped",[4510]],[[12686,12686],"mapped",[4513]],[[12687,12687],"disallowed"],[[12688,12689],"valid",[],"NV8"],[[12690,12690],"mapped",[19968]],[[12691,12691],"mapped",[20108]],[[12692,12692],"mapped",[19977]],[[12693,12693],"mapped",[22235]],[[12694,12694],"mapped",[19978]],[[12695,12695],"mapped",[20013]],[[12696,12696],"mapped",[19979]],[[12697,12697],"mapped",[30002]],[[12698,12698],"mapped",[20057]],[[12699,12699],"mapped",[19993]],[[12700,12700],"mapped",[19969]],[[12701,12701],"mapped",[22825]],[[12702,12702],"mapped",[22320]],[[12703,12703],"mapped",[20154]],[[12704,12727],"valid"],[[12728,12730],"valid"],[[12731,12735],"disallowed"],[[12736,12751],"valid",[],"NV8"],[[12752,12771],"valid",[],"NV8"],[[12772,12783],"disallowed"],[[12784,12799],"valid"],[[12800,12800],"disallowed_STD3_mapped",[40,4352,41]],[[12801,12801],"disallowed_STD3_mapped",[40,4354,41]],[[12802,12802],"disallowed_STD3_mapped",[40,4355,41]],[[12803,12803],"disallowed_STD3_mapped",[40,4357,41]],[[12804,12804],"disallowed_STD3_mapped",[40,4358,41]],[[12805,12805],"disallowed_STD3_mapped",[40,4359,41]],[[12806,12806],"disallowed_STD3_mapped",[40,4361,41]],[[12807,12807],"disallowed_STD3_mapped",[40,4363,41]],[[12808,12808],"disallowed_STD3_mapped",[40,4364,41]],[[12809,12809],"disallowed_STD3_mapped",[40,4366,41]],[[12810,12810],"disallowed_STD3_mapped",[40,4367,41]],[[12811,12811],"disallowed_STD3_mapped",[40,4368,41]],[[12812,12812],"disallowed_STD3_mapped",[40,4369,41]],[[12813,12813],"disallowed_STD3_mapped",[40,4370,41]],[[12814,12814],"disallowed_STD3_mapped",[40,44032,41]],[[12815,12815],"disallowed_STD3_mapped",[40,45208,41]],[[12816,12816],"disallowed_STD3_mapped",[40,45796,41]],[[12817,12817],"disallowed_STD3_mapped",[40,46972,41]],[[12818,12818],"disallowed_STD3_mapped",[40,47560,41]],[[12819,12819],"disallowed_STD3_mapped",[40,48148,41]],[[12820,12820],"disallowed_STD3_mapped",[40,49324,41]],[[12821,12821],"disallowed_STD3_mapped",[40,50500,41]],[[12822,12822],"disallowed_STD3_mapped",[40,51088,41]],[[12823,12823],"disallowed_STD3_mapped",[40,52264,41]],[[12824,12824],"disallowed_STD3_mapped",[40,52852,41]],[[12825,12825],"disallowed_STD3_mapped",[40,53440,41]],[[12826,12826],"disallowed_STD3_mapped",[40,54028,41]],[[12827,12827],"disallowed_STD3_mapped",[40,54616,41]],[[12828,12828],"disallowed_STD3_mapped",[40,51452,41]],[[12829,12829],"disallowed_STD3_mapped",[40,50724,51204,41]],[[12830,12830],"disallowed_STD3_mapped",[40,50724,54980,41]],[[12831,12831],"disallowed"],[[12832,12832],"disallowed_STD3_mapped",[40,19968,41]],[[12833,12833],"disallowed_STD3_mapped",[40,20108,41]],[[12834,12834],"disallowed_STD3_mapped",[40,19977,41]],[[12835,12835],"disallowed_STD3_mapped",[40,22235,41]],[[12836,12836],"disallowed_STD3_mapped",[40,20116,41]],[[12837,12837],"disallowed_STD3_mapped",[40,20845,41]],[[12838,12838],"disallowed_STD3_mapped",[40,19971,41]],[[12839,12839],"disallowed_STD3_mapped",[40,20843,41]],[[12840,12840],"disallowed_STD3_mapped",[40,20061,41]],[[12841,12841],"disallowed_STD3_mapped",[40,21313,41]],[[12842,12842],"disallowed_STD3_mapped",[40,26376,41]],[[12843,12843],"disallowed_STD3_mapped",[40,28779,41]],[[12844,12844],"disallowed_STD3_mapped",[40,27700,41]],[[12845,12845],"disallowed_STD3_mapped",[40,26408,41]],[[12846,12846],"disallowed_STD3_mapped",[40,37329,41]],[[12847,12847],"disallowed_STD3_mapped",[40,22303,41]],[[12848,12848],"disallowed_STD3_mapped",[40,26085,41]],[[12849,12849],"disallowed_STD3_mapped",[40,26666,41]],[[12850,12850],"disallowed_STD3_mapped",[40,26377,41]],[[12851,12851],"disallowed_STD3_mapped",[40,31038,41]],[[12852,12852],"disallowed_STD3_mapped",[40,21517,41]],[[12853,12853],"disallowed_STD3_mapped",[40,29305,41]],[[12854,12854],"disallowed_STD3_mapped",[40,36001,41]],[[12855,12855],"disallowed_STD3_mapped",[40,31069,41]],[[12856,12856],"disallowed_STD3_mapped",[40,21172,41]],[[12857,12857],"disallowed_STD3_mapped",[40,20195,41]],[[12858,12858],"disallowed_STD3_mapped",[40,21628,41]],[[12859,12859],"disallowed_STD3_mapped",[40,23398,41]],[[12860,12860],"disallowed_STD3_mapped",[40,30435,41]],[[12861,12861],"disallowed_STD3_mapped",[40,20225,41]],[[12862,12862],"disallowed_STD3_mapped",[40,36039,41]],[[12863,12863],"disallowed_STD3_mapped",[40,21332,41]],[[12864,12864],"disallowed_STD3_mapped",[40,31085,41]],[[12865,12865],"disallowed_STD3_mapped",[40,20241,41]],[[12866,12866],"disallowed_STD3_mapped",[40,33258,41]],[[12867,12867],"disallowed_STD3_mapped",[40,33267,41]],[[12868,12868],"mapped",[21839]],[[12869,12869],"mapped",[24188]],[[12870,12870],"mapped",[25991]],[[12871,12871],"mapped",[31631]],[[12872,12879],"valid",[],"NV8"],[[12880,12880],"mapped",[112,116,101]],[[12881,12881],"mapped",[50,49]],[[12882,12882],"mapped",[50,50]],[[12883,12883],"mapped",[50,51]],[[12884,12884],"mapped",[50,52]],[[12885,12885],"mapped",[50,53]],[[12886,12886],"mapped",[50,54]],[[12887,12887],"mapped",[50,55]],[[12888,12888],"mapped",[50,56]],[[12889,12889],"mapped",[50,57]],[[12890,12890],"mapped",[51,48]],[[12891,12891],"mapped",[51,49]],[[12892,12892],"mapped",[51,50]],[[12893,12893],"mapped",[51,51]],[[12894,12894],"mapped",[51,52]],[[12895,12895],"mapped",[51,53]],[[12896,12896],"mapped",[4352]],[[12897,12897],"mapped",[4354]],[[12898,12898],"mapped",[4355]],[[12899,12899],"mapped",[4357]],[[12900,12900],"mapped",[4358]],[[12901,12901],"mapped",[4359]],[[12902,12902],"mapped",[4361]],[[12903,12903],"mapped",[4363]],[[12904,12904],"mapped",[4364]],[[12905,12905],"mapped",[4366]],[[12906,12906],"mapped",[4367]],[[12907,12907],"mapped",[4368]],[[12908,12908],"mapped",[4369]],[[12909,12909],"mapped",[4370]],[[12910,12910],"mapped",[44032]],[[12911,12911],"mapped",[45208]],[[12912,12912],"mapped",[45796]],[[12913,12913],"mapped",[46972]],[[12914,12914],"mapped",[47560]],[[12915,12915],"mapped",[48148]],[[12916,12916],"mapped",[49324]],[[12917,12917],"mapped",[50500]],[[12918,12918],"mapped",[51088]],[[12919,12919],"mapped",[52264]],[[12920,12920],"mapped",[52852]],[[12921,12921],"mapped",[53440]],[[12922,12922],"mapped",[54028]],[[12923,12923],"mapped",[54616]],[[12924,12924],"mapped",[52280,44256]],[[12925,12925],"mapped",[51452,51032]],[[12926,12926],"mapped",[50864]],[[12927,12927],"valid",[],"NV8"],[[12928,12928],"mapped",[19968]],[[12929,12929],"mapped",[20108]],[[12930,12930],"mapped",[19977]],[[12931,12931],"mapped",[22235]],[[12932,12932],"mapped",[20116]],[[12933,12933],"mapped",[20845]],[[12934,12934],"mapped",[19971]],[[12935,12935],"mapped",[20843]],[[12936,12936],"mapped",[20061]],[[12937,12937],"mapped",[21313]],[[12938,12938],"mapped",[26376]],[[12939,12939],"mapped",[28779]],[[12940,12940],"mapped",[27700]],[[12941,12941],"mapped",[26408]],[[12942,12942],"mapped",[37329]],[[12943,12943],"mapped",[22303]],[[12944,12944],"mapped",[26085]],[[12945,12945],"mapped",[26666]],[[12946,12946],"mapped",[26377]],[[12947,12947],"mapped",[31038]],[[12948,12948],"mapped",[21517]],[[12949,12949],"mapped",[29305]],[[12950,12950],"mapped",[36001]],[[12951,12951],"mapped",[31069]],[[12952,12952],"mapped",[21172]],[[12953,12953],"mapped",[31192]],[[12954,12954],"mapped",[30007]],[[12955,12955],"mapped",[22899]],[[12956,12956],"mapped",[36969]],[[12957,12957],"mapped",[20778]],[[12958,12958],"mapped",[21360]],[[12959,12959],"mapped",[27880]],[[12960,12960],"mapped",[38917]],[[12961,12961],"mapped",[20241]],[[12962,12962],"mapped",[20889]],[[12963,12963],"mapped",[27491]],[[12964,12964],"mapped",[19978]],[[12965,12965],"mapped",[20013]],[[12966,12966],"mapped",[19979]],[[12967,12967],"mapped",[24038]],[[12968,12968],"mapped",[21491]],[[12969,12969],"mapped",[21307]],[[12970,12970],"mapped",[23447]],[[12971,12971],"mapped",[23398]],[[12972,12972],"mapped",[30435]],[[12973,12973],"mapped",[20225]],[[12974,12974],"mapped",[36039]],[[12975,12975],"mapped",[21332]],[[12976,12976],"mapped",[22812]],[[12977,12977],"mapped",[51,54]],[[12978,12978],"mapped",[51,55]],[[12979,12979],"mapped",[51,56]],[[12980,12980],"mapped",[51,57]],[[12981,12981],"mapped",[52,48]],[[12982,12982],"mapped",[52,49]],[[12983,12983],"mapped",[52,50]],[[12984,12984],"mapped",[52,51]],[[12985,12985],"mapped",[52,52]],[[12986,12986],"mapped",[52,53]],[[12987,12987],"mapped",[52,54]],[[12988,12988],"mapped",[52,55]],[[12989,12989],"mapped",[52,56]],[[12990,12990],"mapped",[52,57]],[[12991,12991],"mapped",[53,48]],[[12992,12992],"mapped",[49,26376]],[[12993,12993],"mapped",[50,26376]],[[12994,12994],"mapped",[51,26376]],[[12995,12995],"mapped",[52,26376]],[[12996,12996],"mapped",[53,26376]],[[12997,12997],"mapped",[54,26376]],[[12998,12998],"mapped",[55,26376]],[[12999,12999],"mapped",[56,26376]],[[13000,13000],"mapped",[57,26376]],[[13001,13001],"mapped",[49,48,26376]],[[13002,13002],"mapped",[49,49,26376]],[[13003,13003],"mapped",[49,50,26376]],[[13004,13004],"mapped",[104,103]],[[13005,13005],"mapped",[101,114,103]],[[13006,13006],"mapped",[101,118]],[[13007,13007],"mapped",[108,116,100]],[[13008,13008],"mapped",[12450]],[[13009,13009],"mapped",[12452]],[[13010,13010],"mapped",[12454]],[[13011,13011],"mapped",[12456]],[[13012,13012],"mapped",[12458]],[[13013,13013],"mapped",[12459]],[[13014,13014],"mapped",[12461]],[[13015,13015],"mapped",[12463]],[[13016,13016],"mapped",[12465]],[[13017,13017],"mapped",[12467]],[[13018,13018],"mapped",[12469]],[[13019,13019],"mapped",[12471]],[[13020,13020],"mapped",[12473]],[[13021,13021],"mapped",[12475]],[[13022,13022],"mapped",[12477]],[[13023,13023],"mapped",[12479]],[[13024,13024],"mapped",[12481]],[[13025,13025],"mapped",[12484]],[[13026,13026],"mapped",[12486]],[[13027,13027],"mapped",[12488]],[[13028,13028],"mapped",[12490]],[[13029,13029],"mapped",[12491]],[[13030,13030],"mapped",[12492]],[[13031,13031],"mapped",[12493]],[[13032,13032],"mapped",[12494]],[[13033,13033],"mapped",[12495]],[[13034,13034],"mapped",[12498]],[[13035,13035],"mapped",[12501]],[[13036,13036],"mapped",[12504]],[[13037,13037],"mapped",[12507]],[[13038,13038],"mapped",[12510]],[[13039,13039],"mapped",[12511]],[[13040,13040],"mapped",[12512]],[[13041,13041],"mapped",[12513]],[[13042,13042],"mapped",[12514]],[[13043,13043],"mapped",[12516]],[[13044,13044],"mapped",[12518]],[[13045,13045],"mapped",[12520]],[[13046,13046],"mapped",[12521]],[[13047,13047],"mapped",[12522]],[[13048,13048],"mapped",[12523]],[[13049,13049],"mapped",[12524]],[[13050,13050],"mapped",[12525]],[[13051,13051],"mapped",[12527]],[[13052,13052],"mapped",[12528]],[[13053,13053],"mapped",[12529]],[[13054,13054],"mapped",[12530]],[[13055,13055],"disallowed"],[[13056,13056],"mapped",[12450,12497,12540,12488]],[[13057,13057],"mapped",[12450,12523,12501,12449]],[[13058,13058],"mapped",[12450,12531,12506,12450]],[[13059,13059],"mapped",[12450,12540,12523]],[[13060,13060],"mapped",[12452,12491,12531,12464]],[[13061,13061],"mapped",[12452,12531,12481]],[[13062,13062],"mapped",[12454,12457,12531]],[[13063,13063],"mapped",[12456,12473,12463,12540,12489]],[[13064,13064],"mapped",[12456,12540,12459,12540]],[[13065,13065],"mapped",[12458,12531,12473]],[[13066,13066],"mapped",[12458,12540,12512]],[[13067,13067],"mapped",[12459,12452,12522]],[[13068,13068],"mapped",[12459,12521,12483,12488]],[[13069,13069],"mapped",[12459,12525,12522,12540]],[[13070,13070],"mapped",[12460,12525,12531]],[[13071,13071],"mapped",[12460,12531,12510]],[[13072,13072],"mapped",[12462,12460]],[[13073,13073],"mapped",[12462,12491,12540]],[[13074,13074],"mapped",[12461,12517,12522,12540]],[[13075,13075],"mapped",[12462,12523,12480,12540]],[[13076,13076],"mapped",[12461,12525]],[[13077,13077],"mapped",[12461,12525,12464,12521,12512]],[[13078,13078],"mapped",[12461,12525,12513,12540,12488,12523]],[[13079,13079],"mapped",[12461,12525,12527,12483,12488]],[[13080,13080],"mapped",[12464,12521,12512]],[[13081,13081],"mapped",[12464,12521,12512,12488,12531]],[[13082,13082],"mapped",[12463,12523,12476,12452,12525]],[[13083,13083],"mapped",[12463,12525,12540,12493]],[[13084,13084],"mapped",[12465,12540,12473]],[[13085,13085],"mapped",[12467,12523,12490]],[[13086,13086],"mapped",[12467,12540,12509]],[[13087,13087],"mapped",[12469,12452,12463,12523]],[[13088,13088],"mapped",[12469,12531,12481,12540,12512]],[[13089,13089],"mapped",[12471,12522,12531,12464]],[[13090,13090],"mapped",[12475,12531,12481]],[[13091,13091],"mapped",[12475,12531,12488]],[[13092,13092],"mapped",[12480,12540,12473]],[[13093,13093],"mapped",[12487,12471]],[[13094,13094],"mapped",[12489,12523]],[[13095,13095],"mapped",[12488,12531]],[[13096,13096],"mapped",[12490,12494]],[[13097,13097],"mapped",[12494,12483,12488]],[[13098,13098],"mapped",[12495,12452,12484]],[[13099,13099],"mapped",[12497,12540,12475,12531,12488]],[[13100,13100],"mapped",[12497,12540,12484]],[[13101,13101],"mapped",[12496,12540,12524,12523]],[[13102,13102],"mapped",[12500,12450,12473,12488,12523]],[[13103,13103],"mapped",[12500,12463,12523]],[[13104,13104],"mapped",[12500,12467]],[[13105,13105],"mapped",[12499,12523]],[[13106,13106],"mapped",[12501,12449,12521,12483,12489]],[[13107,13107],"mapped",[12501,12451,12540,12488]],[[13108,13108],"mapped",[12502,12483,12471,12455,12523]],[[13109,13109],"mapped",[12501,12521,12531]],[[13110,13110],"mapped",[12504,12463,12479,12540,12523]],[[13111,13111],"mapped",[12506,12477]],[[13112,13112],"mapped",[12506,12491,12498]],[[13113,13113],"mapped",[12504,12523,12484]],[[13114,13114],"mapped",[12506,12531,12473]],[[13115,13115],"mapped",[12506,12540,12472]],[[13116,13116],"mapped",[12505,12540,12479]],[[13117,13117],"mapped",[12509,12452,12531,12488]],[[13118,13118],"mapped",[12508,12523,12488]],[[13119,13119],"mapped",[12507,12531]],[[13120,13120],"mapped",[12509,12531,12489]],[[13121,13121],"mapped",[12507,12540,12523]],[[13122,13122],"mapped",[12507,12540,12531]],[[13123,13123],"mapped",[12510,12452,12463,12525]],[[13124,13124],"mapped",[12510,12452,12523]],[[13125,13125],"mapped",[12510,12483,12495]],[[13126,13126],"mapped",[12510,12523,12463]],[[13127,13127],"mapped",[12510,12531,12471,12519,12531]],[[13128,13128],"mapped",[12511,12463,12525,12531]],[[13129,13129],"mapped",[12511,12522]],[[13130,13130],"mapped",[12511,12522,12496,12540,12523]],[[13131,13131],"mapped",[12513,12460]],[[13132,13132],"mapped",[12513,12460,12488,12531]],[[13133,13133],"mapped",[12513,12540,12488,12523]],[[13134,13134],"mapped",[12516,12540,12489]],[[13135,13135],"mapped",[12516,12540,12523]],[[13136,13136],"mapped",[12518,12450,12531]],[[13137,13137],"mapped",[12522,12483,12488,12523]],[[13138,13138],"mapped",[12522,12521]],[[13139,13139],"mapped",[12523,12500,12540]],[[13140,13140],"mapped",[12523,12540,12502,12523]],[[13141,13141],"mapped",[12524,12512]],[[13142,13142],"mapped",[12524,12531,12488,12466,12531]],[[13143,13143],"mapped",[12527,12483,12488]],[[13144,13144],"mapped",[48,28857]],[[13145,13145],"mapped",[49,28857]],[[13146,13146],"mapped",[50,28857]],[[13147,13147],"mapped",[51,28857]],[[13148,13148],"mapped",[52,28857]],[[13149,13149],"mapped",[53,28857]],[[13150,13150],"mapped",[54,28857]],[[13151,13151],"mapped",[55,28857]],[[13152,13152],"mapped",[56,28857]],[[13153,13153],"mapped",[57,28857]],[[13154,13154],"mapped",[49,48,28857]],[[13155,13155],"mapped",[49,49,28857]],[[13156,13156],"mapped",[49,50,28857]],[[13157,13157],"mapped",[49,51,28857]],[[13158,13158],"mapped",[49,52,28857]],[[13159,13159],"mapped",[49,53,28857]],[[13160,13160],"mapped",[49,54,28857]],[[13161,13161],"mapped",[49,55,28857]],[[13162,13162],"mapped",[49,56,28857]],[[13163,13163],"mapped",[49,57,28857]],[[13164,13164],"mapped",[50,48,28857]],[[13165,13165],"mapped",[50,49,28857]],[[13166,13166],"mapped",[50,50,28857]],[[13167,13167],"mapped",[50,51,28857]],[[13168,13168],"mapped",[50,52,28857]],[[13169,13169],"mapped",[104,112,97]],[[13170,13170],"mapped",[100,97]],[[13171,13171],"mapped",[97,117]],[[13172,13172],"mapped",[98,97,114]],[[13173,13173],"mapped",[111,118]],[[13174,13174],"mapped",[112,99]],[[13175,13175],"mapped",[100,109]],[[13176,13176],"mapped",[100,109,50]],[[13177,13177],"mapped",[100,109,51]],[[13178,13178],"mapped",[105,117]],[[13179,13179],"mapped",[24179,25104]],[[13180,13180],"mapped",[26157,21644]],[[13181,13181],"mapped",[22823,27491]],[[13182,13182],"mapped",[26126,27835]],[[13183,13183],"mapped",[26666,24335,20250,31038]],[[13184,13184],"mapped",[112,97]],[[13185,13185],"mapped",[110,97]],[[13186,13186],"mapped",[956,97]],[[13187,13187],"mapped",[109,97]],[[13188,13188],"mapped",[107,97]],[[13189,13189],"mapped",[107,98]],[[13190,13190],"mapped",[109,98]],[[13191,13191],"mapped",[103,98]],[[13192,13192],"mapped",[99,97,108]],[[13193,13193],"mapped",[107,99,97,108]],[[13194,13194],"mapped",[112,102]],[[13195,13195],"mapped",[110,102]],[[13196,13196],"mapped",[956,102]],[[13197,13197],"mapped",[956,103]],[[13198,13198],"mapped",[109,103]],[[13199,13199],"mapped",[107,103]],[[13200,13200],"mapped",[104,122]],[[13201,13201],"mapped",[107,104,122]],[[13202,13202],"mapped",[109,104,122]],[[13203,13203],"mapped",[103,104,122]],[[13204,13204],"mapped",[116,104,122]],[[13205,13205],"mapped",[956,108]],[[13206,13206],"mapped",[109,108]],[[13207,13207],"mapped",[100,108]],[[13208,13208],"mapped",[107,108]],[[13209,13209],"mapped",[102,109]],[[13210,13210],"mapped",[110,109]],[[13211,13211],"mapped",[956,109]],[[13212,13212],"mapped",[109,109]],[[13213,13213],"mapped",[99,109]],[[13214,13214],"mapped",[107,109]],[[13215,13215],"mapped",[109,109,50]],[[13216,13216],"mapped",[99,109,50]],[[13217,13217],"mapped",[109,50]],[[13218,13218],"mapped",[107,109,50]],[[13219,13219],"mapped",[109,109,51]],[[13220,13220],"mapped",[99,109,51]],[[13221,13221],"mapped",[109,51]],[[13222,13222],"mapped",[107,109,51]],[[13223,13223],"mapped",[109,8725,115]],[[13224,13224],"mapped",[109,8725,115,50]],[[13225,13225],"mapped",[112,97]],[[13226,13226],"mapped",[107,112,97]],[[13227,13227],"mapped",[109,112,97]],[[13228,13228],"mapped",[103,112,97]],[[13229,13229],"mapped",[114,97,100]],[[13230,13230],"mapped",[114,97,100,8725,115]],[[13231,13231],"mapped",[114,97,100,8725,115,50]],[[13232,13232],"mapped",[112,115]],[[13233,13233],"mapped",[110,115]],[[13234,13234],"mapped",[956,115]],[[13235,13235],"mapped",[109,115]],[[13236,13236],"mapped",[112,118]],[[13237,13237],"mapped",[110,118]],[[13238,13238],"mapped",[956,118]],[[13239,13239],"mapped",[109,118]],[[13240,13240],"mapped",[107,118]],[[13241,13241],"mapped",[109,118]],[[13242,13242],"mapped",[112,119]],[[13243,13243],"mapped",[110,119]],[[13244,13244],"mapped",[956,119]],[[13245,13245],"mapped",[109,119]],[[13246,13246],"mapped",[107,119]],[[13247,13247],"mapped",[109,119]],[[13248,13248],"mapped",[107,969]],[[13249,13249],"mapped",[109,969]],[[13250,13250],"disallowed"],[[13251,13251],"mapped",[98,113]],[[13252,13252],"mapped",[99,99]],[[13253,13253],"mapped",[99,100]],[[13254,13254],"mapped",[99,8725,107,103]],[[13255,13255],"disallowed"],[[13256,13256],"mapped",[100,98]],[[13257,13257],"mapped",[103,121]],[[13258,13258],"mapped",[104,97]],[[13259,13259],"mapped",[104,112]],[[13260,13260],"mapped",[105,110]],[[13261,13261],"mapped",[107,107]],[[13262,13262],"mapped",[107,109]],[[13263,13263],"mapped",[107,116]],[[13264,13264],"mapped",[108,109]],[[13265,13265],"mapped",[108,110]],[[13266,13266],"mapped",[108,111,103]],[[13267,13267],"mapped",[108,120]],[[13268,13268],"mapped",[109,98]],[[13269,13269],"mapped",[109,105,108]],[[13270,13270],"mapped",[109,111,108]],[[13271,13271],"mapped",[112,104]],[[13272,13272],"disallowed"],[[13273,13273],"mapped",[112,112,109]],[[13274,13274],"mapped",[112,114]],[[13275,13275],"mapped",[115,114]],[[13276,13276],"mapped",[115,118]],[[13277,13277],"mapped",[119,98]],[[13278,13278],"mapped",[118,8725,109]],[[13279,13279],"mapped",[97,8725,109]],[[13280,13280],"mapped",[49,26085]],[[13281,13281],"mapped",[50,26085]],[[13282,13282],"mapped",[51,26085]],[[13283,13283],"mapped",[52,26085]],[[13284,13284],"mapped",[53,26085]],[[13285,13285],"mapped",[54,26085]],[[13286,13286],"mapped",[55,26085]],[[13287,13287],"mapped",[56,26085]],[[13288,13288],"mapped",[57,26085]],[[13289,13289],"mapped",[49,48,26085]],[[13290,13290],"mapped",[49,49,26085]],[[13291,13291],"mapped",[49,50,26085]],[[13292,13292],"mapped",[49,51,26085]],[[13293,13293],"mapped",[49,52,26085]],[[13294,13294],"mapped",[49,53,26085]],[[13295,13295],"mapped",[49,54,26085]],[[13296,13296],"mapped",[49,55,26085]],[[13297,13297],"mapped",[49,56,26085]],[[13298,13298],"mapped",[49,57,26085]],[[13299,13299],"mapped",[50,48,26085]],[[13300,13300],"mapped",[50,49,26085]],[[13301,13301],"mapped",[50,50,26085]],[[13302,13302],"mapped",[50,51,26085]],[[13303,13303],"mapped",[50,52,26085]],[[13304,13304],"mapped",[50,53,26085]],[[13305,13305],"mapped",[50,54,26085]],[[13306,13306],"mapped",[50,55,26085]],[[13307,13307],"mapped",[50,56,26085]],[[13308,13308],"mapped",[50,57,26085]],[[13309,13309],"mapped",[51,48,26085]],[[13310,13310],"mapped",[51,49,26085]],[[13311,13311],"mapped",[103,97,108]],[[13312,19893],"valid"],[[19894,19903],"disallowed"],[[19904,19967],"valid",[],"NV8"],[[19968,40869],"valid"],[[40870,40891],"valid"],[[40892,40899],"valid"],[[40900,40907],"valid"],[[40908,40908],"valid"],[[40909,40917],"valid"],[[40918,40959],"disallowed"],[[40960,42124],"valid"],[[42125,42127],"disallowed"],[[42128,42145],"valid",[],"NV8"],[[42146,42147],"valid",[],"NV8"],[[42148,42163],"valid",[],"NV8"],[[42164,42164],"valid",[],"NV8"],[[42165,42176],"valid",[],"NV8"],[[42177,42177],"valid",[],"NV8"],[[42178,42180],"valid",[],"NV8"],[[42181,42181],"valid",[],"NV8"],[[42182,42182],"valid",[],"NV8"],[[42183,42191],"disallowed"],[[42192,42237],"valid"],[[42238,42239],"valid",[],"NV8"],[[42240,42508],"valid"],[[42509,42511],"valid",[],"NV8"],[[42512,42539],"valid"],[[42540,42559],"disallowed"],[[42560,42560],"mapped",[42561]],[[42561,42561],"valid"],[[42562,42562],"mapped",[42563]],[[42563,42563],"valid"],[[42564,42564],"mapped",[42565]],[[42565,42565],"valid"],[[42566,42566],"mapped",[42567]],[[42567,42567],"valid"],[[42568,42568],"mapped",[42569]],[[42569,42569],"valid"],[[42570,42570],"mapped",[42571]],[[42571,42571],"valid"],[[42572,42572],"mapped",[42573]],[[42573,42573],"valid"],[[42574,42574],"mapped",[42575]],[[42575,42575],"valid"],[[42576,42576],"mapped",[42577]],[[42577,42577],"valid"],[[42578,42578],"mapped",[42579]],[[42579,42579],"valid"],[[42580,42580],"mapped",[42581]],[[42581,42581],"valid"],[[42582,42582],"mapped",[42583]],[[42583,42583],"valid"],[[42584,42584],"mapped",[42585]],[[42585,42585],"valid"],[[42586,42586],"mapped",[42587]],[[42587,42587],"valid"],[[42588,42588],"mapped",[42589]],[[42589,42589],"valid"],[[42590,42590],"mapped",[42591]],[[42591,42591],"valid"],[[42592,42592],"mapped",[42593]],[[42593,42593],"valid"],[[42594,42594],"mapped",[42595]],[[42595,42595],"valid"],[[42596,42596],"mapped",[42597]],[[42597,42597],"valid"],[[42598,42598],"mapped",[42599]],[[42599,42599],"valid"],[[42600,42600],"mapped",[42601]],[[42601,42601],"valid"],[[42602,42602],"mapped",[42603]],[[42603,42603],"valid"],[[42604,42604],"mapped",[42605]],[[42605,42607],"valid"],[[42608,42611],"valid",[],"NV8"],[[42612,42619],"valid"],[[42620,42621],"valid"],[[42622,42622],"valid",[],"NV8"],[[42623,42623],"valid"],[[42624,42624],"mapped",[42625]],[[42625,42625],"valid"],[[42626,42626],"mapped",[42627]],[[42627,42627],"valid"],[[42628,42628],"mapped",[42629]],[[42629,42629],"valid"],[[42630,42630],"mapped",[42631]],[[42631,42631],"valid"],[[42632,42632],"mapped",[42633]],[[42633,42633],"valid"],[[42634,42634],"mapped",[42635]],[[42635,42635],"valid"],[[42636,42636],"mapped",[42637]],[[42637,42637],"valid"],[[42638,42638],"mapped",[42639]],[[42639,42639],"valid"],[[42640,42640],"mapped",[42641]],[[42641,42641],"valid"],[[42642,42642],"mapped",[42643]],[[42643,42643],"valid"],[[42644,42644],"mapped",[42645]],[[42645,42645],"valid"],[[42646,42646],"mapped",[42647]],[[42647,42647],"valid"],[[42648,42648],"mapped",[42649]],[[42649,42649],"valid"],[[42650,42650],"mapped",[42651]],[[42651,42651],"valid"],[[42652,42652],"mapped",[1098]],[[42653,42653],"mapped",[1100]],[[42654,42654],"valid"],[[42655,42655],"valid"],[[42656,42725],"valid"],[[42726,42735],"valid",[],"NV8"],[[42736,42737],"valid"],[[42738,42743],"valid",[],"NV8"],[[42744,42751],"disallowed"],[[42752,42774],"valid",[],"NV8"],[[42775,42778],"valid"],[[42779,42783],"valid"],[[42784,42785],"valid",[],"NV8"],[[42786,42786],"mapped",[42787]],[[42787,42787],"valid"],[[42788,42788],"mapped",[42789]],[[42789,42789],"valid"],[[42790,42790],"mapped",[42791]],[[42791,42791],"valid"],[[42792,42792],"mapped",[42793]],[[42793,42793],"valid"],[[42794,42794],"mapped",[42795]],[[42795,42795],"valid"],[[42796,42796],"mapped",[42797]],[[42797,42797],"valid"],[[42798,42798],"mapped",[42799]],[[42799,42801],"valid"],[[42802,42802],"mapped",[42803]],[[42803,42803],"valid"],[[42804,42804],"mapped",[42805]],[[42805,42805],"valid"],[[42806,42806],"mapped",[42807]],[[42807,42807],"valid"],[[42808,42808],"mapped",[42809]],[[42809,42809],"valid"],[[42810,42810],"mapped",[42811]],[[42811,42811],"valid"],[[42812,42812],"mapped",[42813]],[[42813,42813],"valid"],[[42814,42814],"mapped",[42815]],[[42815,42815],"valid"],[[42816,42816],"mapped",[42817]],[[42817,42817],"valid"],[[42818,42818],"mapped",[42819]],[[42819,42819],"valid"],[[42820,42820],"mapped",[42821]],[[42821,42821],"valid"],[[42822,42822],"mapped",[42823]],[[42823,42823],"valid"],[[42824,42824],"mapped",[42825]],[[42825,42825],"valid"],[[42826,42826],"mapped",[42827]],[[42827,42827],"valid"],[[42828,42828],"mapped",[42829]],[[42829,42829],"valid"],[[42830,42830],"mapped",[42831]],[[42831,42831],"valid"],[[42832,42832],"mapped",[42833]],[[42833,42833],"valid"],[[42834,42834],"mapped",[42835]],[[42835,42835],"valid"],[[42836,42836],"mapped",[42837]],[[42837,42837],"valid"],[[42838,42838],"mapped",[42839]],[[42839,42839],"valid"],[[42840,42840],"mapped",[42841]],[[42841,42841],"valid"],[[42842,42842],"mapped",[42843]],[[42843,42843],"valid"],[[42844,42844],"mapped",[42845]],[[42845,42845],"valid"],[[42846,42846],"mapped",[42847]],[[42847,42847],"valid"],[[42848,42848],"mapped",[42849]],[[42849,42849],"valid"],[[42850,42850],"mapped",[42851]],[[42851,42851],"valid"],[[42852,42852],"mapped",[42853]],[[42853,42853],"valid"],[[42854,42854],"mapped",[42855]],[[42855,42855],"valid"],[[42856,42856],"mapped",[42857]],[[42857,42857],"valid"],[[42858,42858],"mapped",[42859]],[[42859,42859],"valid"],[[42860,42860],"mapped",[42861]],[[42861,42861],"valid"],[[42862,42862],"mapped",[42863]],[[42863,42863],"valid"],[[42864,42864],"mapped",[42863]],[[42865,42872],"valid"],[[42873,42873],"mapped",[42874]],[[42874,42874],"valid"],[[42875,42875],"mapped",[42876]],[[42876,42876],"valid"],[[42877,42877],"mapped",[7545]],[[42878,42878],"mapped",[42879]],[[42879,42879],"valid"],[[42880,42880],"mapped",[42881]],[[42881,42881],"valid"],[[42882,42882],"mapped",[42883]],[[42883,42883],"valid"],[[42884,42884],"mapped",[42885]],[[42885,42885],"valid"],[[42886,42886],"mapped",[42887]],[[42887,42888],"valid"],[[42889,42890],"valid",[],"NV8"],[[42891,42891],"mapped",[42892]],[[42892,42892],"valid"],[[42893,42893],"mapped",[613]],[[42894,42894],"valid"],[[42895,42895],"valid"],[[42896,42896],"mapped",[42897]],[[42897,42897],"valid"],[[42898,42898],"mapped",[42899]],[[42899,42899],"valid"],[[42900,42901],"valid"],[[42902,42902],"mapped",[42903]],[[42903,42903],"valid"],[[42904,42904],"mapped",[42905]],[[42905,42905],"valid"],[[42906,42906],"mapped",[42907]],[[42907,42907],"valid"],[[42908,42908],"mapped",[42909]],[[42909,42909],"valid"],[[42910,42910],"mapped",[42911]],[[42911,42911],"valid"],[[42912,42912],"mapped",[42913]],[[42913,42913],"valid"],[[42914,42914],"mapped",[42915]],[[42915,42915],"valid"],[[42916,42916],"mapped",[42917]],[[42917,42917],"valid"],[[42918,42918],"mapped",[42919]],[[42919,42919],"valid"],[[42920,42920],"mapped",[42921]],[[42921,42921],"valid"],[[42922,42922],"mapped",[614]],[[42923,42923],"mapped",[604]],[[42924,42924],"mapped",[609]],[[42925,42925],"mapped",[620]],[[42926,42927],"disallowed"],[[42928,42928],"mapped",[670]],[[42929,42929],"mapped",[647]],[[42930,42930],"mapped",[669]],[[42931,42931],"mapped",[43859]],[[42932,42932],"mapped",[42933]],[[42933,42933],"valid"],[[42934,42934],"mapped",[42935]],[[42935,42935],"valid"],[[42936,42998],"disallowed"],[[42999,42999],"valid"],[[43000,43000],"mapped",[295]],[[43001,43001],"mapped",[339]],[[43002,43002],"valid"],[[43003,43007],"valid"],[[43008,43047],"valid"],[[43048,43051],"valid",[],"NV8"],[[43052,43055],"disallowed"],[[43056,43065],"valid",[],"NV8"],[[43066,43071],"disallowed"],[[43072,43123],"valid"],[[43124,43127],"valid",[],"NV8"],[[43128,43135],"disallowed"],[[43136,43204],"valid"],[[43205,43213],"disallowed"],[[43214,43215],"valid",[],"NV8"],[[43216,43225],"valid"],[[43226,43231],"disallowed"],[[43232,43255],"valid"],[[43256,43258],"valid",[],"NV8"],[[43259,43259],"valid"],[[43260,43260],"valid",[],"NV8"],[[43261,43261],"valid"],[[43262,43263],"disallowed"],[[43264,43309],"valid"],[[43310,43311],"valid",[],"NV8"],[[43312,43347],"valid"],[[43348,43358],"disallowed"],[[43359,43359],"valid",[],"NV8"],[[43360,43388],"valid",[],"NV8"],[[43389,43391],"disallowed"],[[43392,43456],"valid"],[[43457,43469],"valid",[],"NV8"],[[43470,43470],"disallowed"],[[43471,43481],"valid"],[[43482,43485],"disallowed"],[[43486,43487],"valid",[],"NV8"],[[43488,43518],"valid"],[[43519,43519],"disallowed"],[[43520,43574],"valid"],[[43575,43583],"disallowed"],[[43584,43597],"valid"],[[43598,43599],"disallowed"],[[43600,43609],"valid"],[[43610,43611],"disallowed"],[[43612,43615],"valid",[],"NV8"],[[43616,43638],"valid"],[[43639,43641],"valid",[],"NV8"],[[43642,43643],"valid"],[[43644,43647],"valid"],[[43648,43714],"valid"],[[43715,43738],"disallowed"],[[43739,43741],"valid"],[[43742,43743],"valid",[],"NV8"],[[43744,43759],"valid"],[[43760,43761],"valid",[],"NV8"],[[43762,43766],"valid"],[[43767,43776],"disallowed"],[[43777,43782],"valid"],[[43783,43784],"disallowed"],[[43785,43790],"valid"],[[43791,43792],"disallowed"],[[43793,43798],"valid"],[[43799,43807],"disallowed"],[[43808,43814],"valid"],[[43815,43815],"disallowed"],[[43816,43822],"valid"],[[43823,43823],"disallowed"],[[43824,43866],"valid"],[[43867,43867],"valid",[],"NV8"],[[43868,43868],"mapped",[42791]],[[43869,43869],"mapped",[43831]],[[43870,43870],"mapped",[619]],[[43871,43871],"mapped",[43858]],[[43872,43875],"valid"],[[43876,43877],"valid"],[[43878,43887],"disallowed"],[[43888,43888],"mapped",[5024]],[[43889,43889],"mapped",[5025]],[[43890,43890],"mapped",[5026]],[[43891,43891],"mapped",[5027]],[[43892,43892],"mapped",[5028]],[[43893,43893],"mapped",[5029]],[[43894,43894],"mapped",[5030]],[[43895,43895],"mapped",[5031]],[[43896,43896],"mapped",[5032]],[[43897,43897],"mapped",[5033]],[[43898,43898],"mapped",[5034]],[[43899,43899],"mapped",[5035]],[[43900,43900],"mapped",[5036]],[[43901,43901],"mapped",[5037]],[[43902,43902],"mapped",[5038]],[[43903,43903],"mapped",[5039]],[[43904,43904],"mapped",[5040]],[[43905,43905],"mapped",[5041]],[[43906,43906],"mapped",[5042]],[[43907,43907],"mapped",[5043]],[[43908,43908],"mapped",[5044]],[[43909,43909],"mapped",[5045]],[[43910,43910],"mapped",[5046]],[[43911,43911],"mapped",[5047]],[[43912,43912],"mapped",[5048]],[[43913,43913],"mapped",[5049]],[[43914,43914],"mapped",[5050]],[[43915,43915],"mapped",[5051]],[[43916,43916],"mapped",[5052]],[[43917,43917],"mapped",[5053]],[[43918,43918],"mapped",[5054]],[[43919,43919],"mapped",[5055]],[[43920,43920],"mapped",[5056]],[[43921,43921],"mapped",[5057]],[[43922,43922],"mapped",[5058]],[[43923,43923],"mapped",[5059]],[[43924,43924],"mapped",[5060]],[[43925,43925],"mapped",[5061]],[[43926,43926],"mapped",[5062]],[[43927,43927],"mapped",[5063]],[[43928,43928],"mapped",[5064]],[[43929,43929],"mapped",[5065]],[[43930,43930],"mapped",[5066]],[[43931,43931],"mapped",[5067]],[[43932,43932],"mapped",[5068]],[[43933,43933],"mapped",[5069]],[[43934,43934],"mapped",[5070]],[[43935,43935],"mapped",[5071]],[[43936,43936],"mapped",[5072]],[[43937,43937],"mapped",[5073]],[[43938,43938],"mapped",[5074]],[[43939,43939],"mapped",[5075]],[[43940,43940],"mapped",[5076]],[[43941,43941],"mapped",[5077]],[[43942,43942],"mapped",[5078]],[[43943,43943],"mapped",[5079]],[[43944,43944],"mapped",[5080]],[[43945,43945],"mapped",[5081]],[[43946,43946],"mapped",[5082]],[[43947,43947],"mapped",[5083]],[[43948,43948],"mapped",[5084]],[[43949,43949],"mapped",[5085]],[[43950,43950],"mapped",[5086]],[[43951,43951],"mapped",[5087]],[[43952,43952],"mapped",[5088]],[[43953,43953],"mapped",[5089]],[[43954,43954],"mapped",[5090]],[[43955,43955],"mapped",[5091]],[[43956,43956],"mapped",[5092]],[[43957,43957],"mapped",[5093]],[[43958,43958],"mapped",[5094]],[[43959,43959],"mapped",[5095]],[[43960,43960],"mapped",[5096]],[[43961,43961],"mapped",[5097]],[[43962,43962],"mapped",[5098]],[[43963,43963],"mapped",[5099]],[[43964,43964],"mapped",[5100]],[[43965,43965],"mapped",[5101]],[[43966,43966],"mapped",[5102]],[[43967,43967],"mapped",[5103]],[[43968,44010],"valid"],[[44011,44011],"valid",[],"NV8"],[[44012,44013],"valid"],[[44014,44015],"disallowed"],[[44016,44025],"valid"],[[44026,44031],"disallowed"],[[44032,55203],"valid"],[[55204,55215],"disallowed"],[[55216,55238],"valid",[],"NV8"],[[55239,55242],"disallowed"],[[55243,55291],"valid",[],"NV8"],[[55292,55295],"disallowed"],[[55296,57343],"disallowed"],[[57344,63743],"disallowed"],[[63744,63744],"mapped",[35912]],[[63745,63745],"mapped",[26356]],[[63746,63746],"mapped",[36554]],[[63747,63747],"mapped",[36040]],[[63748,63748],"mapped",[28369]],[[63749,63749],"mapped",[20018]],[[63750,63750],"mapped",[21477]],[[63751,63752],"mapped",[40860]],[[63753,63753],"mapped",[22865]],[[63754,63754],"mapped",[37329]],[[63755,63755],"mapped",[21895]],[[63756,63756],"mapped",[22856]],[[63757,63757],"mapped",[25078]],[[63758,63758],"mapped",[30313]],[[63759,63759],"mapped",[32645]],[[63760,63760],"mapped",[34367]],[[63761,63761],"mapped",[34746]],[[63762,63762],"mapped",[35064]],[[63763,63763],"mapped",[37007]],[[63764,63764],"mapped",[27138]],[[63765,63765],"mapped",[27931]],[[63766,63766],"mapped",[28889]],[[63767,63767],"mapped",[29662]],[[63768,63768],"mapped",[33853]],[[63769,63769],"mapped",[37226]],[[63770,63770],"mapped",[39409]],[[63771,63771],"mapped",[20098]],[[63772,63772],"mapped",[21365]],[[63773,63773],"mapped",[27396]],[[63774,63774],"mapped",[29211]],[[63775,63775],"mapped",[34349]],[[63776,63776],"mapped",[40478]],[[63777,63777],"mapped",[23888]],[[63778,63778],"mapped",[28651]],[[63779,63779],"mapped",[34253]],[[63780,63780],"mapped",[35172]],[[63781,63781],"mapped",[25289]],[[63782,63782],"mapped",[33240]],[[63783,63783],"mapped",[34847]],[[63784,63784],"mapped",[24266]],[[63785,63785],"mapped",[26391]],[[63786,63786],"mapped",[28010]],[[63787,63787],"mapped",[29436]],[[63788,63788],"mapped",[37070]],[[63789,63789],"mapped",[20358]],[[63790,63790],"mapped",[20919]],[[63791,63791],"mapped",[21214]],[[63792,63792],"mapped",[25796]],[[63793,63793],"mapped",[27347]],[[63794,63794],"mapped",[29200]],[[63795,63795],"mapped",[30439]],[[63796,63796],"mapped",[32769]],[[63797,63797],"mapped",[34310]],[[63798,63798],"mapped",[34396]],[[63799,63799],"mapped",[36335]],[[63800,63800],"mapped",[38706]],[[63801,63801],"mapped",[39791]],[[63802,63802],"mapped",[40442]],[[63803,63803],"mapped",[30860]],[[63804,63804],"mapped",[31103]],[[63805,63805],"mapped",[32160]],[[63806,63806],"mapped",[33737]],[[63807,63807],"mapped",[37636]],[[63808,63808],"mapped",[40575]],[[63809,63809],"mapped",[35542]],[[63810,63810],"mapped",[22751]],[[63811,63811],"mapped",[24324]],[[63812,63812],"mapped",[31840]],[[63813,63813],"mapped",[32894]],[[63814,63814],"mapped",[29282]],[[63815,63815],"mapped",[30922]],[[63816,63816],"mapped",[36034]],[[63817,63817],"mapped",[38647]],[[63818,63818],"mapped",[22744]],[[63819,63819],"mapped",[23650]],[[63820,63820],"mapped",[27155]],[[63821,63821],"mapped",[28122]],[[63822,63822],"mapped",[28431]],[[63823,63823],"mapped",[32047]],[[63824,63824],"mapped",[32311]],[[63825,63825],"mapped",[38475]],[[63826,63826],"mapped",[21202]],[[63827,63827],"mapped",[32907]],[[63828,63828],"mapped",[20956]],[[63829,63829],"mapped",[20940]],[[63830,63830],"mapped",[31260]],[[63831,63831],"mapped",[32190]],[[63832,63832],"mapped",[33777]],[[63833,63833],"mapped",[38517]],[[63834,63834],"mapped",[35712]],[[63835,63835],"mapped",[25295]],[[63836,63836],"mapped",[27138]],[[63837,63837],"mapped",[35582]],[[63838,63838],"mapped",[20025]],[[63839,63839],"mapped",[23527]],[[63840,63840],"mapped",[24594]],[[63841,63841],"mapped",[29575]],[[63842,63842],"mapped",[30064]],[[63843,63843],"mapped",[21271]],[[63844,63844],"mapped",[30971]],[[63845,63845],"mapped",[20415]],[[63846,63846],"mapped",[24489]],[[63847,63847],"mapped",[19981]],[[63848,63848],"mapped",[27852]],[[63849,63849],"mapped",[25976]],[[63850,63850],"mapped",[32034]],[[63851,63851],"mapped",[21443]],[[63852,63852],"mapped",[22622]],[[63853,63853],"mapped",[30465]],[[63854,63854],"mapped",[33865]],[[63855,63855],"mapped",[35498]],[[63856,63856],"mapped",[27578]],[[63857,63857],"mapped",[36784]],[[63858,63858],"mapped",[27784]],[[63859,63859],"mapped",[25342]],[[63860,63860],"mapped",[33509]],[[63861,63861],"mapped",[25504]],[[63862,63862],"mapped",[30053]],[[63863,63863],"mapped",[20142]],[[63864,63864],"mapped",[20841]],[[63865,63865],"mapped",[20937]],[[63866,63866],"mapped",[26753]],[[63867,63867],"mapped",[31975]],[[63868,63868],"mapped",[33391]],[[63869,63869],"mapped",[35538]],[[63870,63870],"mapped",[37327]],[[63871,63871],"mapped",[21237]],[[63872,63872],"mapped",[21570]],[[63873,63873],"mapped",[22899]],[[63874,63874],"mapped",[24300]],[[63875,63875],"mapped",[26053]],[[63876,63876],"mapped",[28670]],[[63877,63877],"mapped",[31018]],[[63878,63878],"mapped",[38317]],[[63879,63879],"mapped",[39530]],[[63880,63880],"mapped",[40599]],[[63881,63881],"mapped",[40654]],[[63882,63882],"mapped",[21147]],[[63883,63883],"mapped",[26310]],[[63884,63884],"mapped",[27511]],[[63885,63885],"mapped",[36706]],[[63886,63886],"mapped",[24180]],[[63887,63887],"mapped",[24976]],[[63888,63888],"mapped",[25088]],[[63889,63889],"mapped",[25754]],[[63890,63890],"mapped",[28451]],[[63891,63891],"mapped",[29001]],[[63892,63892],"mapped",[29833]],[[63893,63893],"mapped",[31178]],[[63894,63894],"mapped",[32244]],[[63895,63895],"mapped",[32879]],[[63896,63896],"mapped",[36646]],[[63897,63897],"mapped",[34030]],[[63898,63898],"mapped",[36899]],[[63899,63899],"mapped",[37706]],[[63900,63900],"mapped",[21015]],[[63901,63901],"mapped",[21155]],[[63902,63902],"mapped",[21693]],[[63903,63903],"mapped",[28872]],[[63904,63904],"mapped",[35010]],[[63905,63905],"mapped",[35498]],[[63906,63906],"mapped",[24265]],[[63907,63907],"mapped",[24565]],[[63908,63908],"mapped",[25467]],[[63909,63909],"mapped",[27566]],[[63910,63910],"mapped",[31806]],[[63911,63911],"mapped",[29557]],[[63912,63912],"mapped",[20196]],[[63913,63913],"mapped",[22265]],[[63914,63914],"mapped",[23527]],[[63915,63915],"mapped",[23994]],[[63916,63916],"mapped",[24604]],[[63917,63917],"mapped",[29618]],[[63918,63918],"mapped",[29801]],[[63919,63919],"mapped",[32666]],[[63920,63920],"mapped",[32838]],[[63921,63921],"mapped",[37428]],[[63922,63922],"mapped",[38646]],[[63923,63923],"mapped",[38728]],[[63924,63924],"mapped",[38936]],[[63925,63925],"mapped",[20363]],[[63926,63926],"mapped",[31150]],[[63927,63927],"mapped",[37300]],[[63928,63928],"mapped",[38584]],[[63929,63929],"mapped",[24801]],[[63930,63930],"mapped",[20102]],[[63931,63931],"mapped",[20698]],[[63932,63932],"mapped",[23534]],[[63933,63933],"mapped",[23615]],[[63934,63934],"mapped",[26009]],[[63935,63935],"mapped",[27138]],[[63936,63936],"mapped",[29134]],[[63937,63937],"mapped",[30274]],[[63938,63938],"mapped",[34044]],[[63939,63939],"mapped",[36988]],[[63940,63940],"mapped",[40845]],[[63941,63941],"mapped",[26248]],[[63942,63942],"mapped",[38446]],[[63943,63943],"mapped",[21129]],[[63944,63944],"mapped",[26491]],[[63945,63945],"mapped",[26611]],[[63946,63946],"mapped",[27969]],[[63947,63947],"mapped",[28316]],[[63948,63948],"mapped",[29705]],[[63949,63949],"mapped",[30041]],[[63950,63950],"mapped",[30827]],[[63951,63951],"mapped",[32016]],[[63952,63952],"mapped",[39006]],[[63953,63953],"mapped",[20845]],[[63954,63954],"mapped",[25134]],[[63955,63955],"mapped",[38520]],[[63956,63956],"mapped",[20523]],[[63957,63957],"mapped",[23833]],[[63958,63958],"mapped",[28138]],[[63959,63959],"mapped",[36650]],[[63960,63960],"mapped",[24459]],[[63961,63961],"mapped",[24900]],[[63962,63962],"mapped",[26647]],[[63963,63963],"mapped",[29575]],[[63964,63964],"mapped",[38534]],[[63965,63965],"mapped",[21033]],[[63966,63966],"mapped",[21519]],[[63967,63967],"mapped",[23653]],[[63968,63968],"mapped",[26131]],[[63969,63969],"mapped",[26446]],[[63970,63970],"mapped",[26792]],[[63971,63971],"mapped",[27877]],[[63972,63972],"mapped",[29702]],[[63973,63973],"mapped",[30178]],[[63974,63974],"mapped",[32633]],[[63975,63975],"mapped",[35023]],[[63976,63976],"mapped",[35041]],[[63977,63977],"mapped",[37324]],[[63978,63978],"mapped",[38626]],[[63979,63979],"mapped",[21311]],[[63980,63980],"mapped",[28346]],[[63981,63981],"mapped",[21533]],[[63982,63982],"mapped",[29136]],[[63983,63983],"mapped",[29848]],[[63984,63984],"mapped",[34298]],[[63985,63985],"mapped",[38563]],[[63986,63986],"mapped",[40023]],[[63987,63987],"mapped",[40607]],[[63988,63988],"mapped",[26519]],[[63989,63989],"mapped",[28107]],[[63990,63990],"mapped",[33256]],[[63991,63991],"mapped",[31435]],[[63992,63992],"mapped",[31520]],[[63993,63993],"mapped",[31890]],[[63994,63994],"mapped",[29376]],[[63995,63995],"mapped",[28825]],[[63996,63996],"mapped",[35672]],[[63997,63997],"mapped",[20160]],[[63998,63998],"mapped",[33590]],[[63999,63999],"mapped",[21050]],[[64000,64000],"mapped",[20999]],[[64001,64001],"mapped",[24230]],[[64002,64002],"mapped",[25299]],[[64003,64003],"mapped",[31958]],[[64004,64004],"mapped",[23429]],[[64005,64005],"mapped",[27934]],[[64006,64006],"mapped",[26292]],[[64007,64007],"mapped",[36667]],[[64008,64008],"mapped",[34892]],[[64009,64009],"mapped",[38477]],[[64010,64010],"mapped",[35211]],[[64011,64011],"mapped",[24275]],[[64012,64012],"mapped",[20800]],[[64013,64013],"mapped",[21952]],[[64014,64015],"valid"],[[64016,64016],"mapped",[22618]],[[64017,64017],"valid"],[[64018,64018],"mapped",[26228]],[[64019,64020],"valid"],[[64021,64021],"mapped",[20958]],[[64022,64022],"mapped",[29482]],[[64023,64023],"mapped",[30410]],[[64024,64024],"mapped",[31036]],[[64025,64025],"mapped",[31070]],[[64026,64026],"mapped",[31077]],[[64027,64027],"mapped",[31119]],[[64028,64028],"mapped",[38742]],[[64029,64029],"mapped",[31934]],[[64030,64030],"mapped",[32701]],[[64031,64031],"valid"],[[64032,64032],"mapped",[34322]],[[64033,64033],"valid"],[[64034,64034],"mapped",[35576]],[[64035,64036],"valid"],[[64037,64037],"mapped",[36920]],[[64038,64038],"mapped",[37117]],[[64039,64041],"valid"],[[64042,64042],"mapped",[39151]],[[64043,64043],"mapped",[39164]],[[64044,64044],"mapped",[39208]],[[64045,64045],"mapped",[40372]],[[64046,64046],"mapped",[37086]],[[64047,64047],"mapped",[38583]],[[64048,64048],"mapped",[20398]],[[64049,64049],"mapped",[20711]],[[64050,64050],"mapped",[20813]],[[64051,64051],"mapped",[21193]],[[64052,64052],"mapped",[21220]],[[64053,64053],"mapped",[21329]],[[64054,64054],"mapped",[21917]],[[64055,64055],"mapped",[22022]],[[64056,64056],"mapped",[22120]],[[64057,64057],"mapped",[22592]],[[64058,64058],"mapped",[22696]],[[64059,64059],"mapped",[23652]],[[64060,64060],"mapped",[23662]],[[64061,64061],"mapped",[24724]],[[64062,64062],"mapped",[24936]],[[64063,64063],"mapped",[24974]],[[64064,64064],"mapped",[25074]],[[64065,64065],"mapped",[25935]],[[64066,64066],"mapped",[26082]],[[64067,64067],"mapped",[26257]],[[64068,64068],"mapped",[26757]],[[64069,64069],"mapped",[28023]],[[64070,64070],"mapped",[28186]],[[64071,64071],"mapped",[28450]],[[64072,64072],"mapped",[29038]],[[64073,64073],"mapped",[29227]],[[64074,64074],"mapped",[29730]],[[64075,64075],"mapped",[30865]],[[64076,64076],"mapped",[31038]],[[64077,64077],"mapped",[31049]],[[64078,64078],"mapped",[31048]],[[64079,64079],"mapped",[31056]],[[64080,64080],"mapped",[31062]],[[64081,64081],"mapped",[31069]],[[64082,64082],"mapped",[31117]],[[64083,64083],"mapped",[31118]],[[64084,64084],"mapped",[31296]],[[64085,64085],"mapped",[31361]],[[64086,64086],"mapped",[31680]],[[64087,64087],"mapped",[32244]],[[64088,64088],"mapped",[32265]],[[64089,64089],"mapped",[32321]],[[64090,64090],"mapped",[32626]],[[64091,64091],"mapped",[32773]],[[64092,64092],"mapped",[33261]],[[64093,64094],"mapped",[33401]],[[64095,64095],"mapped",[33879]],[[64096,64096],"mapped",[35088]],[[64097,64097],"mapped",[35222]],[[64098,64098],"mapped",[35585]],[[64099,64099],"mapped",[35641]],[[64100,64100],"mapped",[36051]],[[64101,64101],"mapped",[36104]],[[64102,64102],"mapped",[36790]],[[64103,64103],"mapped",[36920]],[[64104,64104],"mapped",[38627]],[[64105,64105],"mapped",[38911]],[[64106,64106],"mapped",[38971]],[[64107,64107],"mapped",[24693]],[[64108,64108],"mapped",[148206]],[[64109,64109],"mapped",[33304]],[[64110,64111],"disallowed"],[[64112,64112],"mapped",[20006]],[[64113,64113],"mapped",[20917]],[[64114,64114],"mapped",[20840]],[[64115,64115],"mapped",[20352]],[[64116,64116],"mapped",[20805]],[[64117,64117],"mapped",[20864]],[[64118,64118],"mapped",[21191]],[[64119,64119],"mapped",[21242]],[[64120,64120],"mapped",[21917]],[[64121,64121],"mapped",[21845]],[[64122,64122],"mapped",[21913]],[[64123,64123],"mapped",[21986]],[[64124,64124],"mapped",[22618]],[[64125,64125],"mapped",[22707]],[[64126,64126],"mapped",[22852]],[[64127,64127],"mapped",[22868]],[[64128,64128],"mapped",[23138]],[[64129,64129],"mapped",[23336]],[[64130,64130],"mapped",[24274]],[[64131,64131],"mapped",[24281]],[[64132,64132],"mapped",[24425]],[[64133,64133],"mapped",[24493]],[[64134,64134],"mapped",[24792]],[[64135,64135],"mapped",[24910]],[[64136,64136],"mapped",[24840]],[[64137,64137],"mapped",[24974]],[[64138,64138],"mapped",[24928]],[[64139,64139],"mapped",[25074]],[[64140,64140],"mapped",[25140]],[[64141,64141],"mapped",[25540]],[[64142,64142],"mapped",[25628]],[[64143,64143],"mapped",[25682]],[[64144,64144],"mapped",[25942]],[[64145,64145],"mapped",[26228]],[[64146,64146],"mapped",[26391]],[[64147,64147],"mapped",[26395]],[[64148,64148],"mapped",[26454]],[[64149,64149],"mapped",[27513]],[[64150,64150],"mapped",[27578]],[[64151,64151],"mapped",[27969]],[[64152,64152],"mapped",[28379]],[[64153,64153],"mapped",[28363]],[[64154,64154],"mapped",[28450]],[[64155,64155],"mapped",[28702]],[[64156,64156],"mapped",[29038]],[[64157,64157],"mapped",[30631]],[[64158,64158],"mapped",[29237]],[[64159,64159],"mapped",[29359]],[[64160,64160],"mapped",[29482]],[[64161,64161],"mapped",[29809]],[[64162,64162],"mapped",[29958]],[[64163,64163],"mapped",[30011]],[[64164,64164],"mapped",[30237]],[[64165,64165],"mapped",[30239]],[[64166,64166],"mapped",[30410]],[[64167,64167],"mapped",[30427]],[[64168,64168],"mapped",[30452]],[[64169,64169],"mapped",[30538]],[[64170,64170],"mapped",[30528]],[[64171,64171],"mapped",[30924]],[[64172,64172],"mapped",[31409]],[[64173,64173],"mapped",[31680]],[[64174,64174],"mapped",[31867]],[[64175,64175],"mapped",[32091]],[[64176,64176],"mapped",[32244]],[[64177,64177],"mapped",[32574]],[[64178,64178],"mapped",[32773]],[[64179,64179],"mapped",[33618]],[[64180,64180],"mapped",[33775]],[[64181,64181],"mapped",[34681]],[[64182,64182],"mapped",[35137]],[[64183,64183],"mapped",[35206]],[[64184,64184],"mapped",[35222]],[[64185,64185],"mapped",[35519]],[[64186,64186],"mapped",[35576]],[[64187,64187],"mapped",[35531]],[[64188,64188],"mapped",[35585]],[[64189,64189],"mapped",[35582]],[[64190,64190],"mapped",[35565]],[[64191,64191],"mapped",[35641]],[[64192,64192],"mapped",[35722]],[[64193,64193],"mapped",[36104]],[[64194,64194],"mapped",[36664]],[[64195,64195],"mapped",[36978]],[[64196,64196],"mapped",[37273]],[[64197,64197],"mapped",[37494]],[[64198,64198],"mapped",[38524]],[[64199,64199],"mapped",[38627]],[[64200,64200],"mapped",[38742]],[[64201,64201],"mapped",[38875]],[[64202,64202],"mapped",[38911]],[[64203,64203],"mapped",[38923]],[[64204,64204],"mapped",[38971]],[[64205,64205],"mapped",[39698]],[[64206,64206],"mapped",[40860]],[[64207,64207],"mapped",[141386]],[[64208,64208],"mapped",[141380]],[[64209,64209],"mapped",[144341]],[[64210,64210],"mapped",[15261]],[[64211,64211],"mapped",[16408]],[[64212,64212],"mapped",[16441]],[[64213,64213],"mapped",[152137]],[[64214,64214],"mapped",[154832]],[[64215,64215],"mapped",[163539]],[[64216,64216],"mapped",[40771]],[[64217,64217],"mapped",[40846]],[[64218,64255],"disallowed"],[[64256,64256],"mapped",[102,102]],[[64257,64257],"mapped",[102,105]],[[64258,64258],"mapped",[102,108]],[[64259,64259],"mapped",[102,102,105]],[[64260,64260],"mapped",[102,102,108]],[[64261,64262],"mapped",[115,116]],[[64263,64274],"disallowed"],[[64275,64275],"mapped",[1396,1398]],[[64276,64276],"mapped",[1396,1381]],[[64277,64277],"mapped",[1396,1387]],[[64278,64278],"mapped",[1406,1398]],[[64279,64279],"mapped",[1396,1389]],[[64280,64284],"disallowed"],[[64285,64285],"mapped",[1497,1460]],[[64286,64286],"valid"],[[64287,64287],"mapped",[1522,1463]],[[64288,64288],"mapped",[1506]],[[64289,64289],"mapped",[1488]],[[64290,64290],"mapped",[1491]],[[64291,64291],"mapped",[1492]],[[64292,64292],"mapped",[1499]],[[64293,64293],"mapped",[1500]],[[64294,64294],"mapped",[1501]],[[64295,64295],"mapped",[1512]],[[64296,64296],"mapped",[1514]],[[64297,64297],"disallowed_STD3_mapped",[43]],[[64298,64298],"mapped",[1513,1473]],[[64299,64299],"mapped",[1513,1474]],[[64300,64300],"mapped",[1513,1468,1473]],[[64301,64301],"mapped",[1513,1468,1474]],[[64302,64302],"mapped",[1488,1463]],[[64303,64303],"mapped",[1488,1464]],[[64304,64304],"mapped",[1488,1468]],[[64305,64305],"mapped",[1489,1468]],[[64306,64306],"mapped",[1490,1468]],[[64307,64307],"mapped",[1491,1468]],[[64308,64308],"mapped",[1492,1468]],[[64309,64309],"mapped",[1493,1468]],[[64310,64310],"mapped",[1494,1468]],[[64311,64311],"disallowed"],[[64312,64312],"mapped",[1496,1468]],[[64313,64313],"mapped",[1497,1468]],[[64314,64314],"mapped",[1498,1468]],[[64315,64315],"mapped",[1499,1468]],[[64316,64316],"mapped",[1500,1468]],[[64317,64317],"disallowed"],[[64318,64318],"mapped",[1502,1468]],[[64319,64319],"disallowed"],[[64320,64320],"mapped",[1504,1468]],[[64321,64321],"mapped",[1505,1468]],[[64322,64322],"disallowed"],[[64323,64323],"mapped",[1507,1468]],[[64324,64324],"mapped",[1508,1468]],[[64325,64325],"disallowed"],[[64326,64326],"mapped",[1510,1468]],[[64327,64327],"mapped",[1511,1468]],[[64328,64328],"mapped",[1512,1468]],[[64329,64329],"mapped",[1513,1468]],[[64330,64330],"mapped",[1514,1468]],[[64331,64331],"mapped",[1493,1465]],[[64332,64332],"mapped",[1489,1471]],[[64333,64333],"mapped",[1499,1471]],[[64334,64334],"mapped",[1508,1471]],[[64335,64335],"mapped",[1488,1500]],[[64336,64337],"mapped",[1649]],[[64338,64341],"mapped",[1659]],[[64342,64345],"mapped",[1662]],[[64346,64349],"mapped",[1664]],[[64350,64353],"mapped",[1658]],[[64354,64357],"mapped",[1663]],[[64358,64361],"mapped",[1657]],[[64362,64365],"mapped",[1700]],[[64366,64369],"mapped",[1702]],[[64370,64373],"mapped",[1668]],[[64374,64377],"mapped",[1667]],[[64378,64381],"mapped",[1670]],[[64382,64385],"mapped",[1671]],[[64386,64387],"mapped",[1677]],[[64388,64389],"mapped",[1676]],[[64390,64391],"mapped",[1678]],[[64392,64393],"mapped",[1672]],[[64394,64395],"mapped",[1688]],[[64396,64397],"mapped",[1681]],[[64398,64401],"mapped",[1705]],[[64402,64405],"mapped",[1711]],[[64406,64409],"mapped",[1715]],[[64410,64413],"mapped",[1713]],[[64414,64415],"mapped",[1722]],[[64416,64419],"mapped",[1723]],[[64420,64421],"mapped",[1728]],[[64422,64425],"mapped",[1729]],[[64426,64429],"mapped",[1726]],[[64430,64431],"mapped",[1746]],[[64432,64433],"mapped",[1747]],[[64434,64449],"valid",[],"NV8"],[[64450,64466],"disallowed"],[[64467,64470],"mapped",[1709]],[[64471,64472],"mapped",[1735]],[[64473,64474],"mapped",[1734]],[[64475,64476],"mapped",[1736]],[[64477,64477],"mapped",[1735,1652]],[[64478,64479],"mapped",[1739]],[[64480,64481],"mapped",[1733]],[[64482,64483],"mapped",[1737]],[[64484,64487],"mapped",[1744]],[[64488,64489],"mapped",[1609]],[[64490,64491],"mapped",[1574,1575]],[[64492,64493],"mapped",[1574,1749]],[[64494,64495],"mapped",[1574,1608]],[[64496,64497],"mapped",[1574,1735]],[[64498,64499],"mapped",[1574,1734]],[[64500,64501],"mapped",[1574,1736]],[[64502,64504],"mapped",[1574,1744]],[[64505,64507],"mapped",[1574,1609]],[[64508,64511],"mapped",[1740]],[[64512,64512],"mapped",[1574,1580]],[[64513,64513],"mapped",[1574,1581]],[[64514,64514],"mapped",[1574,1605]],[[64515,64515],"mapped",[1574,1609]],[[64516,64516],"mapped",[1574,1610]],[[64517,64517],"mapped",[1576,1580]],[[64518,64518],"mapped",[1576,1581]],[[64519,64519],"mapped",[1576,1582]],[[64520,64520],"mapped",[1576,1605]],[[64521,64521],"mapped",[1576,1609]],[[64522,64522],"mapped",[1576,1610]],[[64523,64523],"mapped",[1578,1580]],[[64524,64524],"mapped",[1578,1581]],[[64525,64525],"mapped",[1578,1582]],[[64526,64526],"mapped",[1578,1605]],[[64527,64527],"mapped",[1578,1609]],[[64528,64528],"mapped",[1578,1610]],[[64529,64529],"mapped",[1579,1580]],[[64530,64530],"mapped",[1579,1605]],[[64531,64531],"mapped",[1579,1609]],[[64532,64532],"mapped",[1579,1610]],[[64533,64533],"mapped",[1580,1581]],[[64534,64534],"mapped",[1580,1605]],[[64535,64535],"mapped",[1581,1580]],[[64536,64536],"mapped",[1581,1605]],[[64537,64537],"mapped",[1582,1580]],[[64538,64538],"mapped",[1582,1581]],[[64539,64539],"mapped",[1582,1605]],[[64540,64540],"mapped",[1587,1580]],[[64541,64541],"mapped",[1587,1581]],[[64542,64542],"mapped",[1587,1582]],[[64543,64543],"mapped",[1587,1605]],[[64544,64544],"mapped",[1589,1581]],[[64545,64545],"mapped",[1589,1605]],[[64546,64546],"mapped",[1590,1580]],[[64547,64547],"mapped",[1590,1581]],[[64548,64548],"mapped",[1590,1582]],[[64549,64549],"mapped",[1590,1605]],[[64550,64550],"mapped",[1591,1581]],[[64551,64551],"mapped",[1591,1605]],[[64552,64552],"mapped",[1592,1605]],[[64553,64553],"mapped",[1593,1580]],[[64554,64554],"mapped",[1593,1605]],[[64555,64555],"mapped",[1594,1580]],[[64556,64556],"mapped",[1594,1605]],[[64557,64557],"mapped",[1601,1580]],[[64558,64558],"mapped",[1601,1581]],[[64559,64559],"mapped",[1601,1582]],[[64560,64560],"mapped",[1601,1605]],[[64561,64561],"mapped",[1601,1609]],[[64562,64562],"mapped",[1601,1610]],[[64563,64563],"mapped",[1602,1581]],[[64564,64564],"mapped",[1602,1605]],[[64565,64565],"mapped",[1602,1609]],[[64566,64566],"mapped",[1602,1610]],[[64567,64567],"mapped",[1603,1575]],[[64568,64568],"mapped",[1603,1580]],[[64569,64569],"mapped",[1603,1581]],[[64570,64570],"mapped",[1603,1582]],[[64571,64571],"mapped",[1603,1604]],[[64572,64572],"mapped",[1603,1605]],[[64573,64573],"mapped",[1603,1609]],[[64574,64574],"mapped",[1603,1610]],[[64575,64575],"mapped",[1604,1580]],[[64576,64576],"mapped",[1604,1581]],[[64577,64577],"mapped",[1604,1582]],[[64578,64578],"mapped",[1604,1605]],[[64579,64579],"mapped",[1604,1609]],[[64580,64580],"mapped",[1604,1610]],[[64581,64581],"mapped",[1605,1580]],[[64582,64582],"mapped",[1605,1581]],[[64583,64583],"mapped",[1605,1582]],[[64584,64584],"mapped",[1605,1605]],[[64585,64585],"mapped",[1605,1609]],[[64586,64586],"mapped",[1605,1610]],[[64587,64587],"mapped",[1606,1580]],[[64588,64588],"mapped",[1606,1581]],[[64589,64589],"mapped",[1606,1582]],[[64590,64590],"mapped",[1606,1605]],[[64591,64591],"mapped",[1606,1609]],[[64592,64592],"mapped",[1606,1610]],[[64593,64593],"mapped",[1607,1580]],[[64594,64594],"mapped",[1607,1605]],[[64595,64595],"mapped",[1607,1609]],[[64596,64596],"mapped",[1607,1610]],[[64597,64597],"mapped",[1610,1580]],[[64598,64598],"mapped",[1610,1581]],[[64599,64599],"mapped",[1610,1582]],[[64600,64600],"mapped",[1610,1605]],[[64601,64601],"mapped",[1610,1609]],[[64602,64602],"mapped",[1610,1610]],[[64603,64603],"mapped",[1584,1648]],[[64604,64604],"mapped",[1585,1648]],[[64605,64605],"mapped",[1609,1648]],[[64606,64606],"disallowed_STD3_mapped",[32,1612,1617]],[[64607,64607],"disallowed_STD3_mapped",[32,1613,1617]],[[64608,64608],"disallowed_STD3_mapped",[32,1614,1617]],[[64609,64609],"disallowed_STD3_mapped",[32,1615,1617]],[[64610,64610],"disallowed_STD3_mapped",[32,1616,1617]],[[64611,64611],"disallowed_STD3_mapped",[32,1617,1648]],[[64612,64612],"mapped",[1574,1585]],[[64613,64613],"mapped",[1574,1586]],[[64614,64614],"mapped",[1574,1605]],[[64615,64615],"mapped",[1574,1606]],[[64616,64616],"mapped",[1574,1609]],[[64617,64617],"mapped",[1574,1610]],[[64618,64618],"mapped",[1576,1585]],[[64619,64619],"mapped",[1576,1586]],[[64620,64620],"mapped",[1576,1605]],[[64621,64621],"mapped",[1576,1606]],[[64622,64622],"mapped",[1576,1609]],[[64623,64623],"mapped",[1576,1610]],[[64624,64624],"mapped",[1578,1585]],[[64625,64625],"mapped",[1578,1586]],[[64626,64626],"mapped",[1578,1605]],[[64627,64627],"mapped",[1578,1606]],[[64628,64628],"mapped",[1578,1609]],[[64629,64629],"mapped",[1578,1610]],[[64630,64630],"mapped",[1579,1585]],[[64631,64631],"mapped",[1579,1586]],[[64632,64632],"mapped",[1579,1605]],[[64633,64633],"mapped",[1579,1606]],[[64634,64634],"mapped",[1579,1609]],[[64635,64635],"mapped",[1579,1610]],[[64636,64636],"mapped",[1601,1609]],[[64637,64637],"mapped",[1601,1610]],[[64638,64638],"mapped",[1602,1609]],[[64639,64639],"mapped",[1602,1610]],[[64640,64640],"mapped",[1603,1575]],[[64641,64641],"mapped",[1603,1604]],[[64642,64642],"mapped",[1603,1605]],[[64643,64643],"mapped",[1603,1609]],[[64644,64644],"mapped",[1603,1610]],[[64645,64645],"mapped",[1604,1605]],[[64646,64646],"mapped",[1604,1609]],[[64647,64647],"mapped",[1604,1610]],[[64648,64648],"mapped",[1605,1575]],[[64649,64649],"mapped",[1605,1605]],[[64650,64650],"mapped",[1606,1585]],[[64651,64651],"mapped",[1606,1586]],[[64652,64652],"mapped",[1606,1605]],[[64653,64653],"mapped",[1606,1606]],[[64654,64654],"mapped",[1606,1609]],[[64655,64655],"mapped",[1606,1610]],[[64656,64656],"mapped",[1609,1648]],[[64657,64657],"mapped",[1610,1585]],[[64658,64658],"mapped",[1610,1586]],[[64659,64659],"mapped",[1610,1605]],[[64660,64660],"mapped",[1610,1606]],[[64661,64661],"mapped",[1610,1609]],[[64662,64662],"mapped",[1610,1610]],[[64663,64663],"mapped",[1574,1580]],[[64664,64664],"mapped",[1574,1581]],[[64665,64665],"mapped",[1574,1582]],[[64666,64666],"mapped",[1574,1605]],[[64667,64667],"mapped",[1574,1607]],[[64668,64668],"mapped",[1576,1580]],[[64669,64669],"mapped",[1576,1581]],[[64670,64670],"mapped",[1576,1582]],[[64671,64671],"mapped",[1576,1605]],[[64672,64672],"mapped",[1576,1607]],[[64673,64673],"mapped",[1578,1580]],[[64674,64674],"mapped",[1578,1581]],[[64675,64675],"mapped",[1578,1582]],[[64676,64676],"mapped",[1578,1605]],[[64677,64677],"mapped",[1578,1607]],[[64678,64678],"mapped",[1579,1605]],[[64679,64679],"mapped",[1580,1581]],[[64680,64680],"mapped",[1580,1605]],[[64681,64681],"mapped",[1581,1580]],[[64682,64682],"mapped",[1581,1605]],[[64683,64683],"mapped",[1582,1580]],[[64684,64684],"mapped",[1582,1605]],[[64685,64685],"mapped",[1587,1580]],[[64686,64686],"mapped",[1587,1581]],[[64687,64687],"mapped",[1587,1582]],[[64688,64688],"mapped",[1587,1605]],[[64689,64689],"mapped",[1589,1581]],[[64690,64690],"mapped",[1589,1582]],[[64691,64691],"mapped",[1589,1605]],[[64692,64692],"mapped",[1590,1580]],[[64693,64693],"mapped",[1590,1581]],[[64694,64694],"mapped",[1590,1582]],[[64695,64695],"mapped",[1590,1605]],[[64696,64696],"mapped",[1591,1581]],[[64697,64697],"mapped",[1592,1605]],[[64698,64698],"mapped",[1593,1580]],[[64699,64699],"mapped",[1593,1605]],[[64700,64700],"mapped",[1594,1580]],[[64701,64701],"mapped",[1594,1605]],[[64702,64702],"mapped",[1601,1580]],[[64703,64703],"mapped",[1601,1581]],[[64704,64704],"mapped",[1601,1582]],[[64705,64705],"mapped",[1601,1605]],[[64706,64706],"mapped",[1602,1581]],[[64707,64707],"mapped",[1602,1605]],[[64708,64708],"mapped",[1603,1580]],[[64709,64709],"mapped",[1603,1581]],[[64710,64710],"mapped",[1603,1582]],[[64711,64711],"mapped",[1603,1604]],[[64712,64712],"mapped",[1603,1605]],[[64713,64713],"mapped",[1604,1580]],[[64714,64714],"mapped",[1604,1581]],[[64715,64715],"mapped",[1604,1582]],[[64716,64716],"mapped",[1604,1605]],[[64717,64717],"mapped",[1604,1607]],[[64718,64718],"mapped",[1605,1580]],[[64719,64719],"mapped",[1605,1581]],[[64720,64720],"mapped",[1605,1582]],[[64721,64721],"mapped",[1605,1605]],[[64722,64722],"mapped",[1606,1580]],[[64723,64723],"mapped",[1606,1581]],[[64724,64724],"mapped",[1606,1582]],[[64725,64725],"mapped",[1606,1605]],[[64726,64726],"mapped",[1606,1607]],[[64727,64727],"mapped",[1607,1580]],[[64728,64728],"mapped",[1607,1605]],[[64729,64729],"mapped",[1607,1648]],[[64730,64730],"mapped",[1610,1580]],[[64731,64731],"mapped",[1610,1581]],[[64732,64732],"mapped",[1610,1582]],[[64733,64733],"mapped",[1610,1605]],[[64734,64734],"mapped",[1610,1607]],[[64735,64735],"mapped",[1574,1605]],[[64736,64736],"mapped",[1574,1607]],[[64737,64737],"mapped",[1576,1605]],[[64738,64738],"mapped",[1576,1607]],[[64739,64739],"mapped",[1578,1605]],[[64740,64740],"mapped",[1578,1607]],[[64741,64741],"mapped",[1579,1605]],[[64742,64742],"mapped",[1579,1607]],[[64743,64743],"mapped",[1587,1605]],[[64744,64744],"mapped",[1587,1607]],[[64745,64745],"mapped",[1588,1605]],[[64746,64746],"mapped",[1588,1607]],[[64747,64747],"mapped",[1603,1604]],[[64748,64748],"mapped",[1603,1605]],[[64749,64749],"mapped",[1604,1605]],[[64750,64750],"mapped",[1606,1605]],[[64751,64751],"mapped",[1606,1607]],[[64752,64752],"mapped",[1610,1605]],[[64753,64753],"mapped",[1610,1607]],[[64754,64754],"mapped",[1600,1614,1617]],[[64755,64755],"mapped",[1600,1615,1617]],[[64756,64756],"mapped",[1600,1616,1617]],[[64757,64757],"mapped",[1591,1609]],[[64758,64758],"mapped",[1591,1610]],[[64759,64759],"mapped",[1593,1609]],[[64760,64760],"mapped",[1593,1610]],[[64761,64761],"mapped",[1594,1609]],[[64762,64762],"mapped",[1594,1610]],[[64763,64763],"mapped",[1587,1609]],[[64764,64764],"mapped",[1587,1610]],[[64765,64765],"mapped",[1588,1609]],[[64766,64766],"mapped",[1588,1610]],[[64767,64767],"mapped",[1581,1609]],[[64768,64768],"mapped",[1581,1610]],[[64769,64769],"mapped",[1580,1609]],[[64770,64770],"mapped",[1580,1610]],[[64771,64771],"mapped",[1582,1609]],[[64772,64772],"mapped",[1582,1610]],[[64773,64773],"mapped",[1589,1609]],[[64774,64774],"mapped",[1589,1610]],[[64775,64775],"mapped",[1590,1609]],[[64776,64776],"mapped",[1590,1610]],[[64777,64777],"mapped",[1588,1580]],[[64778,64778],"mapped",[1588,1581]],[[64779,64779],"mapped",[1588,1582]],[[64780,64780],"mapped",[1588,1605]],[[64781,64781],"mapped",[1588,1585]],[[64782,64782],"mapped",[1587,1585]],[[64783,64783],"mapped",[1589,1585]],[[64784,64784],"mapped",[1590,1585]],[[64785,64785],"mapped",[1591,1609]],[[64786,64786],"mapped",[1591,1610]],[[64787,64787],"mapped",[1593,1609]],[[64788,64788],"mapped",[1593,1610]],[[64789,64789],"mapped",[1594,1609]],[[64790,64790],"mapped",[1594,1610]],[[64791,64791],"mapped",[1587,1609]],[[64792,64792],"mapped",[1587,1610]],[[64793,64793],"mapped",[1588,1609]],[[64794,64794],"mapped",[1588,1610]],[[64795,64795],"mapped",[1581,1609]],[[64796,64796],"mapped",[1581,1610]],[[64797,64797],"mapped",[1580,1609]],[[64798,64798],"mapped",[1580,1610]],[[64799,64799],"mapped",[1582,1609]],[[64800,64800],"mapped",[1582,1610]],[[64801,64801],"mapped",[1589,1609]],[[64802,64802],"mapped",[1589,1610]],[[64803,64803],"mapped",[1590,1609]],[[64804,64804],"mapped",[1590,1610]],[[64805,64805],"mapped",[1588,1580]],[[64806,64806],"mapped",[1588,1581]],[[64807,64807],"mapped",[1588,1582]],[[64808,64808],"mapped",[1588,1605]],[[64809,64809],"mapped",[1588,1585]],[[64810,64810],"mapped",[1587,1585]],[[64811,64811],"mapped",[1589,1585]],[[64812,64812],"mapped",[1590,1585]],[[64813,64813],"mapped",[1588,1580]],[[64814,64814],"mapped",[1588,1581]],[[64815,64815],"mapped",[1588,1582]],[[64816,64816],"mapped",[1588,1605]],[[64817,64817],"mapped",[1587,1607]],[[64818,64818],"mapped",[1588,1607]],[[64819,64819],"mapped",[1591,1605]],[[64820,64820],"mapped",[1587,1580]],[[64821,64821],"mapped",[1587,1581]],[[64822,64822],"mapped",[1587,1582]],[[64823,64823],"mapped",[1588,1580]],[[64824,64824],"mapped",[1588,1581]],[[64825,64825],"mapped",[1588,1582]],[[64826,64826],"mapped",[1591,1605]],[[64827,64827],"mapped",[1592,1605]],[[64828,64829],"mapped",[1575,1611]],[[64830,64831],"valid",[],"NV8"],[[64832,64847],"disallowed"],[[64848,64848],"mapped",[1578,1580,1605]],[[64849,64850],"mapped",[1578,1581,1580]],[[64851,64851],"mapped",[1578,1581,1605]],[[64852,64852],"mapped",[1578,1582,1605]],[[64853,64853],"mapped",[1578,1605,1580]],[[64854,64854],"mapped",[1578,1605,1581]],[[64855,64855],"mapped",[1578,1605,1582]],[[64856,64857],"mapped",[1580,1605,1581]],[[64858,64858],"mapped",[1581,1605,1610]],[[64859,64859],"mapped",[1581,1605,1609]],[[64860,64860],"mapped",[1587,1581,1580]],[[64861,64861],"mapped",[1587,1580,1581]],[[64862,64862],"mapped",[1587,1580,1609]],[[64863,64864],"mapped",[1587,1605,1581]],[[64865,64865],"mapped",[1587,1605,1580]],[[64866,64867],"mapped",[1587,1605,1605]],[[64868,64869],"mapped",[1589,1581,1581]],[[64870,64870],"mapped",[1589,1605,1605]],[[64871,64872],"mapped",[1588,1581,1605]],[[64873,64873],"mapped",[1588,1580,1610]],[[64874,64875],"mapped",[1588,1605,1582]],[[64876,64877],"mapped",[1588,1605,1605]],[[64878,64878],"mapped",[1590,1581,1609]],[[64879,64880],"mapped",[1590,1582,1605]],[[64881,64882],"mapped",[1591,1605,1581]],[[64883,64883],"mapped",[1591,1605,1605]],[[64884,64884],"mapped",[1591,1605,1610]],[[64885,64885],"mapped",[1593,1580,1605]],[[64886,64887],"mapped",[1593,1605,1605]],[[64888,64888],"mapped",[1593,1605,1609]],[[64889,64889],"mapped",[1594,1605,1605]],[[64890,64890],"mapped",[1594,1605,1610]],[[64891,64891],"mapped",[1594,1605,1609]],[[64892,64893],"mapped",[1601,1582,1605]],[[64894,64894],"mapped",[1602,1605,1581]],[[64895,64895],"mapped",[1602,1605,1605]],[[64896,64896],"mapped",[1604,1581,1605]],[[64897,64897],"mapped",[1604,1581,1610]],[[64898,64898],"mapped",[1604,1581,1609]],[[64899,64900],"mapped",[1604,1580,1580]],[[64901,64902],"mapped",[1604,1582,1605]],[[64903,64904],"mapped",[1604,1605,1581]],[[64905,64905],"mapped",[1605,1581,1580]],[[64906,64906],"mapped",[1605,1581,1605]],[[64907,64907],"mapped",[1605,1581,1610]],[[64908,64908],"mapped",[1605,1580,1581]],[[64909,64909],"mapped",[1605,1580,1605]],[[64910,64910],"mapped",[1605,1582,1580]],[[64911,64911],"mapped",[1605,1582,1605]],[[64912,64913],"disallowed"],[[64914,64914],"mapped",[1605,1580,1582]],[[64915,64915],"mapped",[1607,1605,1580]],[[64916,64916],"mapped",[1607,1605,1605]],[[64917,64917],"mapped",[1606,1581,1605]],[[64918,64918],"mapped",[1606,1581,1609]],[[64919,64920],"mapped",[1606,1580,1605]],[[64921,64921],"mapped",[1606,1580,1609]],[[64922,64922],"mapped",[1606,1605,1610]],[[64923,64923],"mapped",[1606,1605,1609]],[[64924,64925],"mapped",[1610,1605,1605]],[[64926,64926],"mapped",[1576,1582,1610]],[[64927,64927],"mapped",[1578,1580,1610]],[[64928,64928],"mapped",[1578,1580,1609]],[[64929,64929],"mapped",[1578,1582,1610]],[[64930,64930],"mapped",[1578,1582,1609]],[[64931,64931],"mapped",[1578,1605,1610]],[[64932,64932],"mapped",[1578,1605,1609]],[[64933,64933],"mapped",[1580,1605,1610]],[[64934,64934],"mapped",[1580,1581,1609]],[[64935,64935],"mapped",[1580,1605,1609]],[[64936,64936],"mapped",[1587,1582,1609]],[[64937,64937],"mapped",[1589,1581,1610]],[[64938,64938],"mapped",[1588,1581,1610]],[[64939,64939],"mapped",[1590,1581,1610]],[[64940,64940],"mapped",[1604,1580,1610]],[[64941,64941],"mapped",[1604,1605,1610]],[[64942,64942],"mapped",[1610,1581,1610]],[[64943,64943],"mapped",[1610,1580,1610]],[[64944,64944],"mapped",[1610,1605,1610]],[[64945,64945],"mapped",[1605,1605,1610]],[[64946,64946],"mapped",[1602,1605,1610]],[[64947,64947],"mapped",[1606,1581,1610]],[[64948,64948],"mapped",[1602,1605,1581]],[[64949,64949],"mapped",[1604,1581,1605]],[[64950,64950],"mapped",[1593,1605,1610]],[[64951,64951],"mapped",[1603,1605,1610]],[[64952,64952],"mapped",[1606,1580,1581]],[[64953,64953],"mapped",[1605,1582,1610]],[[64954,64954],"mapped",[1604,1580,1605]],[[64955,64955],"mapped",[1603,1605,1605]],[[64956,64956],"mapped",[1604,1580,1605]],[[64957,64957],"mapped",[1606,1580,1581]],[[64958,64958],"mapped",[1580,1581,1610]],[[64959,64959],"mapped",[1581,1580,1610]],[[64960,64960],"mapped",[1605,1580,1610]],[[64961,64961],"mapped",[1601,1605,1610]],[[64962,64962],"mapped",[1576,1581,1610]],[[64963,64963],"mapped",[1603,1605,1605]],[[64964,64964],"mapped",[1593,1580,1605]],[[64965,64965],"mapped",[1589,1605,1605]],[[64966,64966],"mapped",[1587,1582,1610]],[[64967,64967],"mapped",[1606,1580,1610]],[[64968,64975],"disallowed"],[[64976,65007],"disallowed"],[[65008,65008],"mapped",[1589,1604,1746]],[[65009,65009],"mapped",[1602,1604,1746]],[[65010,65010],"mapped",[1575,1604,1604,1607]],[[65011,65011],"mapped",[1575,1603,1576,1585]],[[65012,65012],"mapped",[1605,1581,1605,1583]],[[65013,65013],"mapped",[1589,1604,1593,1605]],[[65014,65014],"mapped",[1585,1587,1608,1604]],[[65015,65015],"mapped",[1593,1604,1610,1607]],[[65016,65016],"mapped",[1608,1587,1604,1605]],[[65017,65017],"mapped",[1589,1604,1609]],[[65018,65018],"disallowed_STD3_mapped",[1589,1604,1609,32,1575,1604,1604,1607,32,1593,1604,1610,1607,32,1608,1587,1604,1605]],[[65019,65019],"disallowed_STD3_mapped",[1580,1604,32,1580,1604,1575,1604,1607]],[[65020,65020],"mapped",[1585,1740,1575,1604]],[[65021,65021],"valid",[],"NV8"],[[65022,65023],"disallowed"],[[65024,65039],"ignored"],[[65040,65040],"disallowed_STD3_mapped",[44]],[[65041,65041],"mapped",[12289]],[[65042,65042],"disallowed"],[[65043,65043],"disallowed_STD3_mapped",[58]],[[65044,65044],"disallowed_STD3_mapped",[59]],[[65045,65045],"disallowed_STD3_mapped",[33]],[[65046,65046],"disallowed_STD3_mapped",[63]],[[65047,65047],"mapped",[12310]],[[65048,65048],"mapped",[12311]],[[65049,65049],"disallowed"],[[65050,65055],"disallowed"],[[65056,65059],"valid"],[[65060,65062],"valid"],[[65063,65069],"valid"],[[65070,65071],"valid"],[[65072,65072],"disallowed"],[[65073,65073],"mapped",[8212]],[[65074,65074],"mapped",[8211]],[[65075,65076],"disallowed_STD3_mapped",[95]],[[65077,65077],"disallowed_STD3_mapped",[40]],[[65078,65078],"disallowed_STD3_mapped",[41]],[[65079,65079],"disallowed_STD3_mapped",[123]],[[65080,65080],"disallowed_STD3_mapped",[125]],[[65081,65081],"mapped",[12308]],[[65082,65082],"mapped",[12309]],[[65083,65083],"mapped",[12304]],[[65084,65084],"mapped",[12305]],[[65085,65085],"mapped",[12298]],[[65086,65086],"mapped",[12299]],[[65087,65087],"mapped",[12296]],[[65088,65088],"mapped",[12297]],[[65089,65089],"mapped",[12300]],[[65090,65090],"mapped",[12301]],[[65091,65091],"mapped",[12302]],[[65092,65092],"mapped",[12303]],[[65093,65094],"valid",[],"NV8"],[[65095,65095],"disallowed_STD3_mapped",[91]],[[65096,65096],"disallowed_STD3_mapped",[93]],[[65097,65100],"disallowed_STD3_mapped",[32,773]],[[65101,65103],"disallowed_STD3_mapped",[95]],[[65104,65104],"disallowed_STD3_mapped",[44]],[[65105,65105],"mapped",[12289]],[[65106,65106],"disallowed"],[[65107,65107],"disallowed"],[[65108,65108],"disallowed_STD3_mapped",[59]],[[65109,65109],"disallowed_STD3_mapped",[58]],[[65110,65110],"disallowed_STD3_mapped",[63]],[[65111,65111],"disallowed_STD3_mapped",[33]],[[65112,65112],"mapped",[8212]],[[65113,65113],"disallowed_STD3_mapped",[40]],[[65114,65114],"disallowed_STD3_mapped",[41]],[[65115,65115],"disallowed_STD3_mapped",[123]],[[65116,65116],"disallowed_STD3_mapped",[125]],[[65117,65117],"mapped",[12308]],[[65118,65118],"mapped",[12309]],[[65119,65119],"disallowed_STD3_mapped",[35]],[[65120,65120],"disallowed_STD3_mapped",[38]],[[65121,65121],"disallowed_STD3_mapped",[42]],[[65122,65122],"disallowed_STD3_mapped",[43]],[[65123,65123],"mapped",[45]],[[65124,65124],"disallowed_STD3_mapped",[60]],[[65125,65125],"disallowed_STD3_mapped",[62]],[[65126,65126],"disallowed_STD3_mapped",[61]],[[65127,65127],"disallowed"],[[65128,65128],"disallowed_STD3_mapped",[92]],[[65129,65129],"disallowed_STD3_mapped",[36]],[[65130,65130],"disallowed_STD3_mapped",[37]],[[65131,65131],"disallowed_STD3_mapped",[64]],[[65132,65135],"disallowed"],[[65136,65136],"disallowed_STD3_mapped",[32,1611]],[[65137,65137],"mapped",[1600,1611]],[[65138,65138],"disallowed_STD3_mapped",[32,1612]],[[65139,65139],"valid"],[[65140,65140],"disallowed_STD3_mapped",[32,1613]],[[65141,65141],"disallowed"],[[65142,65142],"disallowed_STD3_mapped",[32,1614]],[[65143,65143],"mapped",[1600,1614]],[[65144,65144],"disallowed_STD3_mapped",[32,1615]],[[65145,65145],"mapped",[1600,1615]],[[65146,65146],"disallowed_STD3_mapped",[32,1616]],[[65147,65147],"mapped",[1600,1616]],[[65148,65148],"disallowed_STD3_mapped",[32,1617]],[[65149,65149],"mapped",[1600,1617]],[[65150,65150],"disallowed_STD3_mapped",[32,1618]],[[65151,65151],"mapped",[1600,1618]],[[65152,65152],"mapped",[1569]],[[65153,65154],"mapped",[1570]],[[65155,65156],"mapped",[1571]],[[65157,65158],"mapped",[1572]],[[65159,65160],"mapped",[1573]],[[65161,65164],"mapped",[1574]],[[65165,65166],"mapped",[1575]],[[65167,65170],"mapped",[1576]],[[65171,65172],"mapped",[1577]],[[65173,65176],"mapped",[1578]],[[65177,65180],"mapped",[1579]],[[65181,65184],"mapped",[1580]],[[65185,65188],"mapped",[1581]],[[65189,65192],"mapped",[1582]],[[65193,65194],"mapped",[1583]],[[65195,65196],"mapped",[1584]],[[65197,65198],"mapped",[1585]],[[65199,65200],"mapped",[1586]],[[65201,65204],"mapped",[1587]],[[65205,65208],"mapped",[1588]],[[65209,65212],"mapped",[1589]],[[65213,65216],"mapped",[1590]],[[65217,65220],"mapped",[1591]],[[65221,65224],"mapped",[1592]],[[65225,65228],"mapped",[1593]],[[65229,65232],"mapped",[1594]],[[65233,65236],"mapped",[1601]],[[65237,65240],"mapped",[1602]],[[65241,65244],"mapped",[1603]],[[65245,65248],"mapped",[1604]],[[65249,65252],"mapped",[1605]],[[65253,65256],"mapped",[1606]],[[65257,65260],"mapped",[1607]],[[65261,65262],"mapped",[1608]],[[65263,65264],"mapped",[1609]],[[65265,65268],"mapped",[1610]],[[65269,65270],"mapped",[1604,1570]],[[65271,65272],"mapped",[1604,1571]],[[65273,65274],"mapped",[1604,1573]],[[65275,65276],"mapped",[1604,1575]],[[65277,65278],"disallowed"],[[65279,65279],"ignored"],[[65280,65280],"disallowed"],[[65281,65281],"disallowed_STD3_mapped",[33]],[[65282,65282],"disallowed_STD3_mapped",[34]],[[65283,65283],"disallowed_STD3_mapped",[35]],[[65284,65284],"disallowed_STD3_mapped",[36]],[[65285,65285],"disallowed_STD3_mapped",[37]],[[65286,65286],"disallowed_STD3_mapped",[38]],[[65287,65287],"disallowed_STD3_mapped",[39]],[[65288,65288],"disallowed_STD3_mapped",[40]],[[65289,65289],"disallowed_STD3_mapped",[41]],[[65290,65290],"disallowed_STD3_mapped",[42]],[[65291,65291],"disallowed_STD3_mapped",[43]],[[65292,65292],"disallowed_STD3_mapped",[44]],[[65293,65293],"mapped",[45]],[[65294,65294],"mapped",[46]],[[65295,65295],"disallowed_STD3_mapped",[47]],[[65296,65296],"mapped",[48]],[[65297,65297],"mapped",[49]],[[65298,65298],"mapped",[50]],[[65299,65299],"mapped",[51]],[[65300,65300],"mapped",[52]],[[65301,65301],"mapped",[53]],[[65302,65302],"mapped",[54]],[[65303,65303],"mapped",[55]],[[65304,65304],"mapped",[56]],[[65305,65305],"mapped",[57]],[[65306,65306],"disallowed_STD3_mapped",[58]],[[65307,65307],"disallowed_STD3_mapped",[59]],[[65308,65308],"disallowed_STD3_mapped",[60]],[[65309,65309],"disallowed_STD3_mapped",[61]],[[65310,65310],"disallowed_STD3_mapped",[62]],[[65311,65311],"disallowed_STD3_mapped",[63]],[[65312,65312],"disallowed_STD3_mapped",[64]],[[65313,65313],"mapped",[97]],[[65314,65314],"mapped",[98]],[[65315,65315],"mapped",[99]],[[65316,65316],"mapped",[100]],[[65317,65317],"mapped",[101]],[[65318,65318],"mapped",[102]],[[65319,65319],"mapped",[103]],[[65320,65320],"mapped",[104]],[[65321,65321],"mapped",[105]],[[65322,65322],"mapped",[106]],[[65323,65323],"mapped",[107]],[[65324,65324],"mapped",[108]],[[65325,65325],"mapped",[109]],[[65326,65326],"mapped",[110]],[[65327,65327],"mapped",[111]],[[65328,65328],"mapped",[112]],[[65329,65329],"mapped",[113]],[[65330,65330],"mapped",[114]],[[65331,65331],"mapped",[115]],[[65332,65332],"mapped",[116]],[[65333,65333],"mapped",[117]],[[65334,65334],"mapped",[118]],[[65335,65335],"mapped",[119]],[[65336,65336],"mapped",[120]],[[65337,65337],"mapped",[121]],[[65338,65338],"mapped",[122]],[[65339,65339],"disallowed_STD3_mapped",[91]],[[65340,65340],"disallowed_STD3_mapped",[92]],[[65341,65341],"disallowed_STD3_mapped",[93]],[[65342,65342],"disallowed_STD3_mapped",[94]],[[65343,65343],"disallowed_STD3_mapped",[95]],[[65344,65344],"disallowed_STD3_mapped",[96]],[[65345,65345],"mapped",[97]],[[65346,65346],"mapped",[98]],[[65347,65347],"mapped",[99]],[[65348,65348],"mapped",[100]],[[65349,65349],"mapped",[101]],[[65350,65350],"mapped",[102]],[[65351,65351],"mapped",[103]],[[65352,65352],"mapped",[104]],[[65353,65353],"mapped",[105]],[[65354,65354],"mapped",[106]],[[65355,65355],"mapped",[107]],[[65356,65356],"mapped",[108]],[[65357,65357],"mapped",[109]],[[65358,65358],"mapped",[110]],[[65359,65359],"mapped",[111]],[[65360,65360],"mapped",[112]],[[65361,65361],"mapped",[113]],[[65362,65362],"mapped",[114]],[[65363,65363],"mapped",[115]],[[65364,65364],"mapped",[116]],[[65365,65365],"mapped",[117]],[[65366,65366],"mapped",[118]],[[65367,65367],"mapped",[119]],[[65368,65368],"mapped",[120]],[[65369,65369],"mapped",[121]],[[65370,65370],"mapped",[122]],[[65371,65371],"disallowed_STD3_mapped",[123]],[[65372,65372],"disallowed_STD3_mapped",[124]],[[65373,65373],"disallowed_STD3_mapped",[125]],[[65374,65374],"disallowed_STD3_mapped",[126]],[[65375,65375],"mapped",[10629]],[[65376,65376],"mapped",[10630]],[[65377,65377],"mapped",[46]],[[65378,65378],"mapped",[12300]],[[65379,65379],"mapped",[12301]],[[65380,65380],"mapped",[12289]],[[65381,65381],"mapped",[12539]],[[65382,65382],"mapped",[12530]],[[65383,65383],"mapped",[12449]],[[65384,65384],"mapped",[12451]],[[65385,65385],"mapped",[12453]],[[65386,65386],"mapped",[12455]],[[65387,65387],"mapped",[12457]],[[65388,65388],"mapped",[12515]],[[65389,65389],"mapped",[12517]],[[65390,65390],"mapped",[12519]],[[65391,65391],"mapped",[12483]],[[65392,65392],"mapped",[12540]],[[65393,65393],"mapped",[12450]],[[65394,65394],"mapped",[12452]],[[65395,65395],"mapped",[12454]],[[65396,65396],"mapped",[12456]],[[65397,65397],"mapped",[12458]],[[65398,65398],"mapped",[12459]],[[65399,65399],"mapped",[12461]],[[65400,65400],"mapped",[12463]],[[65401,65401],"mapped",[12465]],[[65402,65402],"mapped",[12467]],[[65403,65403],"mapped",[12469]],[[65404,65404],"mapped",[12471]],[[65405,65405],"mapped",[12473]],[[65406,65406],"mapped",[12475]],[[65407,65407],"mapped",[12477]],[[65408,65408],"mapped",[12479]],[[65409,65409],"mapped",[12481]],[[65410,65410],"mapped",[12484]],[[65411,65411],"mapped",[12486]],[[65412,65412],"mapped",[12488]],[[65413,65413],"mapped",[12490]],[[65414,65414],"mapped",[12491]],[[65415,65415],"mapped",[12492]],[[65416,65416],"mapped",[12493]],[[65417,65417],"mapped",[12494]],[[65418,65418],"mapped",[12495]],[[65419,65419],"mapped",[12498]],[[65420,65420],"mapped",[12501]],[[65421,65421],"mapped",[12504]],[[65422,65422],"mapped",[12507]],[[65423,65423],"mapped",[12510]],[[65424,65424],"mapped",[12511]],[[65425,65425],"mapped",[12512]],[[65426,65426],"mapped",[12513]],[[65427,65427],"mapped",[12514]],[[65428,65428],"mapped",[12516]],[[65429,65429],"mapped",[12518]],[[65430,65430],"mapped",[12520]],[[65431,65431],"mapped",[12521]],[[65432,65432],"mapped",[12522]],[[65433,65433],"mapped",[12523]],[[65434,65434],"mapped",[12524]],[[65435,65435],"mapped",[12525]],[[65436,65436],"mapped",[12527]],[[65437,65437],"mapped",[12531]],[[65438,65438],"mapped",[12441]],[[65439,65439],"mapped",[12442]],[[65440,65440],"disallowed"],[[65441,65441],"mapped",[4352]],[[65442,65442],"mapped",[4353]],[[65443,65443],"mapped",[4522]],[[65444,65444],"mapped",[4354]],[[65445,65445],"mapped",[4524]],[[65446,65446],"mapped",[4525]],[[65447,65447],"mapped",[4355]],[[65448,65448],"mapped",[4356]],[[65449,65449],"mapped",[4357]],[[65450,65450],"mapped",[4528]],[[65451,65451],"mapped",[4529]],[[65452,65452],"mapped",[4530]],[[65453,65453],"mapped",[4531]],[[65454,65454],"mapped",[4532]],[[65455,65455],"mapped",[4533]],[[65456,65456],"mapped",[4378]],[[65457,65457],"mapped",[4358]],[[65458,65458],"mapped",[4359]],[[65459,65459],"mapped",[4360]],[[65460,65460],"mapped",[4385]],[[65461,65461],"mapped",[4361]],[[65462,65462],"mapped",[4362]],[[65463,65463],"mapped",[4363]],[[65464,65464],"mapped",[4364]],[[65465,65465],"mapped",[4365]],[[65466,65466],"mapped",[4366]],[[65467,65467],"mapped",[4367]],[[65468,65468],"mapped",[4368]],[[65469,65469],"mapped",[4369]],[[65470,65470],"mapped",[4370]],[[65471,65473],"disallowed"],[[65474,65474],"mapped",[4449]],[[65475,65475],"mapped",[4450]],[[65476,65476],"mapped",[4451]],[[65477,65477],"mapped",[4452]],[[65478,65478],"mapped",[4453]],[[65479,65479],"mapped",[4454]],[[65480,65481],"disallowed"],[[65482,65482],"mapped",[4455]],[[65483,65483],"mapped",[4456]],[[65484,65484],"mapped",[4457]],[[65485,65485],"mapped",[4458]],[[65486,65486],"mapped",[4459]],[[65487,65487],"mapped",[4460]],[[65488,65489],"disallowed"],[[65490,65490],"mapped",[4461]],[[65491,65491],"mapped",[4462]],[[65492,65492],"mapped",[4463]],[[65493,65493],"mapped",[4464]],[[65494,65494],"mapped",[4465]],[[65495,65495],"mapped",[4466]],[[65496,65497],"disallowed"],[[65498,65498],"mapped",[4467]],[[65499,65499],"mapped",[4468]],[[65500,65500],"mapped",[4469]],[[65501,65503],"disallowed"],[[65504,65504],"mapped",[162]],[[65505,65505],"mapped",[163]],[[65506,65506],"mapped",[172]],[[65507,65507],"disallowed_STD3_mapped",[32,772]],[[65508,65508],"mapped",[166]],[[65509,65509],"mapped",[165]],[[65510,65510],"mapped",[8361]],[[65511,65511],"disallowed"],[[65512,65512],"mapped",[9474]],[[65513,65513],"mapped",[8592]],[[65514,65514],"mapped",[8593]],[[65515,65515],"mapped",[8594]],[[65516,65516],"mapped",[8595]],[[65517,65517],"mapped",[9632]],[[65518,65518],"mapped",[9675]],[[65519,65528],"disallowed"],[[65529,65531],"disallowed"],[[65532,65532],"disallowed"],[[65533,65533],"disallowed"],[[65534,65535],"disallowed"],[[65536,65547],"valid"],[[65548,65548],"disallowed"],[[65549,65574],"valid"],[[65575,65575],"disallowed"],[[65576,65594],"valid"],[[65595,65595],"disallowed"],[[65596,65597],"valid"],[[65598,65598],"disallowed"],[[65599,65613],"valid"],[[65614,65615],"disallowed"],[[65616,65629],"valid"],[[65630,65663],"disallowed"],[[65664,65786],"valid"],[[65787,65791],"disallowed"],[[65792,65794],"valid",[],"NV8"],[[65795,65798],"disallowed"],[[65799,65843],"valid",[],"NV8"],[[65844,65846],"disallowed"],[[65847,65855],"valid",[],"NV8"],[[65856,65930],"valid",[],"NV8"],[[65931,65932],"valid",[],"NV8"],[[65933,65935],"disallowed"],[[65936,65947],"valid",[],"NV8"],[[65948,65951],"disallowed"],[[65952,65952],"valid",[],"NV8"],[[65953,65999],"disallowed"],[[66000,66044],"valid",[],"NV8"],[[66045,66045],"valid"],[[66046,66175],"disallowed"],[[66176,66204],"valid"],[[66205,66207],"disallowed"],[[66208,66256],"valid"],[[66257,66271],"disallowed"],[[66272,66272],"valid"],[[66273,66299],"valid",[],"NV8"],[[66300,66303],"disallowed"],[[66304,66334],"valid"],[[66335,66335],"valid"],[[66336,66339],"valid",[],"NV8"],[[66340,66351],"disallowed"],[[66352,66368],"valid"],[[66369,66369],"valid",[],"NV8"],[[66370,66377],"valid"],[[66378,66378],"valid",[],"NV8"],[[66379,66383],"disallowed"],[[66384,66426],"valid"],[[66427,66431],"disallowed"],[[66432,66461],"valid"],[[66462,66462],"disallowed"],[[66463,66463],"valid",[],"NV8"],[[66464,66499],"valid"],[[66500,66503],"disallowed"],[[66504,66511],"valid"],[[66512,66517],"valid",[],"NV8"],[[66518,66559],"disallowed"],[[66560,66560],"mapped",[66600]],[[66561,66561],"mapped",[66601]],[[66562,66562],"mapped",[66602]],[[66563,66563],"mapped",[66603]],[[66564,66564],"mapped",[66604]],[[66565,66565],"mapped",[66605]],[[66566,66566],"mapped",[66606]],[[66567,66567],"mapped",[66607]],[[66568,66568],"mapped",[66608]],[[66569,66569],"mapped",[66609]],[[66570,66570],"mapped",[66610]],[[66571,66571],"mapped",[66611]],[[66572,66572],"mapped",[66612]],[[66573,66573],"mapped",[66613]],[[66574,66574],"mapped",[66614]],[[66575,66575],"mapped",[66615]],[[66576,66576],"mapped",[66616]],[[66577,66577],"mapped",[66617]],[[66578,66578],"mapped",[66618]],[[66579,66579],"mapped",[66619]],[[66580,66580],"mapped",[66620]],[[66581,66581],"mapped",[66621]],[[66582,66582],"mapped",[66622]],[[66583,66583],"mapped",[66623]],[[66584,66584],"mapped",[66624]],[[66585,66585],"mapped",[66625]],[[66586,66586],"mapped",[66626]],[[66587,66587],"mapped",[66627]],[[66588,66588],"mapped",[66628]],[[66589,66589],"mapped",[66629]],[[66590,66590],"mapped",[66630]],[[66591,66591],"mapped",[66631]],[[66592,66592],"mapped",[66632]],[[66593,66593],"mapped",[66633]],[[66594,66594],"mapped",[66634]],[[66595,66595],"mapped",[66635]],[[66596,66596],"mapped",[66636]],[[66597,66597],"mapped",[66637]],[[66598,66598],"mapped",[66638]],[[66599,66599],"mapped",[66639]],[[66600,66637],"valid"],[[66638,66717],"valid"],[[66718,66719],"disallowed"],[[66720,66729],"valid"],[[66730,66815],"disallowed"],[[66816,66855],"valid"],[[66856,66863],"disallowed"],[[66864,66915],"valid"],[[66916,66926],"disallowed"],[[66927,66927],"valid",[],"NV8"],[[66928,67071],"disallowed"],[[67072,67382],"valid"],[[67383,67391],"disallowed"],[[67392,67413],"valid"],[[67414,67423],"disallowed"],[[67424,67431],"valid"],[[67432,67583],"disallowed"],[[67584,67589],"valid"],[[67590,67591],"disallowed"],[[67592,67592],"valid"],[[67593,67593],"disallowed"],[[67594,67637],"valid"],[[67638,67638],"disallowed"],[[67639,67640],"valid"],[[67641,67643],"disallowed"],[[67644,67644],"valid"],[[67645,67646],"disallowed"],[[67647,67647],"valid"],[[67648,67669],"valid"],[[67670,67670],"disallowed"],[[67671,67679],"valid",[],"NV8"],[[67680,67702],"valid"],[[67703,67711],"valid",[],"NV8"],[[67712,67742],"valid"],[[67743,67750],"disallowed"],[[67751,67759],"valid",[],"NV8"],[[67760,67807],"disallowed"],[[67808,67826],"valid"],[[67827,67827],"disallowed"],[[67828,67829],"valid"],[[67830,67834],"disallowed"],[[67835,67839],"valid",[],"NV8"],[[67840,67861],"valid"],[[67862,67865],"valid",[],"NV8"],[[67866,67867],"valid",[],"NV8"],[[67868,67870],"disallowed"],[[67871,67871],"valid",[],"NV8"],[[67872,67897],"valid"],[[67898,67902],"disallowed"],[[67903,67903],"valid",[],"NV8"],[[67904,67967],"disallowed"],[[67968,68023],"valid"],[[68024,68027],"disallowed"],[[68028,68029],"valid",[],"NV8"],[[68030,68031],"valid"],[[68032,68047],"valid",[],"NV8"],[[68048,68049],"disallowed"],[[68050,68095],"valid",[],"NV8"],[[68096,68099],"valid"],[[68100,68100],"disallowed"],[[68101,68102],"valid"],[[68103,68107],"disallowed"],[[68108,68115],"valid"],[[68116,68116],"disallowed"],[[68117,68119],"valid"],[[68120,68120],"disallowed"],[[68121,68147],"valid"],[[68148,68151],"disallowed"],[[68152,68154],"valid"],[[68155,68158],"disallowed"],[[68159,68159],"valid"],[[68160,68167],"valid",[],"NV8"],[[68168,68175],"disallowed"],[[68176,68184],"valid",[],"NV8"],[[68185,68191],"disallowed"],[[68192,68220],"valid"],[[68221,68223],"valid",[],"NV8"],[[68224,68252],"valid"],[[68253,68255],"valid",[],"NV8"],[[68256,68287],"disallowed"],[[68288,68295],"valid"],[[68296,68296],"valid",[],"NV8"],[[68297,68326],"valid"],[[68327,68330],"disallowed"],[[68331,68342],"valid",[],"NV8"],[[68343,68351],"disallowed"],[[68352,68405],"valid"],[[68406,68408],"disallowed"],[[68409,68415],"valid",[],"NV8"],[[68416,68437],"valid"],[[68438,68439],"disallowed"],[[68440,68447],"valid",[],"NV8"],[[68448,68466],"valid"],[[68467,68471],"disallowed"],[[68472,68479],"valid",[],"NV8"],[[68480,68497],"valid"],[[68498,68504],"disallowed"],[[68505,68508],"valid",[],"NV8"],[[68509,68520],"disallowed"],[[68521,68527],"valid",[],"NV8"],[[68528,68607],"disallowed"],[[68608,68680],"valid"],[[68681,68735],"disallowed"],[[68736,68736],"mapped",[68800]],[[68737,68737],"mapped",[68801]],[[68738,68738],"mapped",[68802]],[[68739,68739],"mapped",[68803]],[[68740,68740],"mapped",[68804]],[[68741,68741],"mapped",[68805]],[[68742,68742],"mapped",[68806]],[[68743,68743],"mapped",[68807]],[[68744,68744],"mapped",[68808]],[[68745,68745],"mapped",[68809]],[[68746,68746],"mapped",[68810]],[[68747,68747],"mapped",[68811]],[[68748,68748],"mapped",[68812]],[[68749,68749],"mapped",[68813]],[[68750,68750],"mapped",[68814]],[[68751,68751],"mapped",[68815]],[[68752,68752],"mapped",[68816]],[[68753,68753],"mapped",[68817]],[[68754,68754],"mapped",[68818]],[[68755,68755],"mapped",[68819]],[[68756,68756],"mapped",[68820]],[[68757,68757],"mapped",[68821]],[[68758,68758],"mapped",[68822]],[[68759,68759],"mapped",[68823]],[[68760,68760],"mapped",[68824]],[[68761,68761],"mapped",[68825]],[[68762,68762],"mapped",[68826]],[[68763,68763],"mapped",[68827]],[[68764,68764],"mapped",[68828]],[[68765,68765],"mapped",[68829]],[[68766,68766],"mapped",[68830]],[[68767,68767],"mapped",[68831]],[[68768,68768],"mapped",[68832]],[[68769,68769],"mapped",[68833]],[[68770,68770],"mapped",[68834]],[[68771,68771],"mapped",[68835]],[[68772,68772],"mapped",[68836]],[[68773,68773],"mapped",[68837]],[[68774,68774],"mapped",[68838]],[[68775,68775],"mapped",[68839]],[[68776,68776],"mapped",[68840]],[[68777,68777],"mapped",[68841]],[[68778,68778],"mapped",[68842]],[[68779,68779],"mapped",[68843]],[[68780,68780],"mapped",[68844]],[[68781,68781],"mapped",[68845]],[[68782,68782],"mapped",[68846]],[[68783,68783],"mapped",[68847]],[[68784,68784],"mapped",[68848]],[[68785,68785],"mapped",[68849]],[[68786,68786],"mapped",[68850]],[[68787,68799],"disallowed"],[[68800,68850],"valid"],[[68851,68857],"disallowed"],[[68858,68863],"valid",[],"NV8"],[[68864,69215],"disallowed"],[[69216,69246],"valid",[],"NV8"],[[69247,69631],"disallowed"],[[69632,69702],"valid"],[[69703,69709],"valid",[],"NV8"],[[69710,69713],"disallowed"],[[69714,69733],"valid",[],"NV8"],[[69734,69743],"valid"],[[69744,69758],"disallowed"],[[69759,69759],"valid"],[[69760,69818],"valid"],[[69819,69820],"valid",[],"NV8"],[[69821,69821],"disallowed"],[[69822,69825],"valid",[],"NV8"],[[69826,69839],"disallowed"],[[69840,69864],"valid"],[[69865,69871],"disallowed"],[[69872,69881],"valid"],[[69882,69887],"disallowed"],[[69888,69940],"valid"],[[69941,69941],"disallowed"],[[69942,69951],"valid"],[[69952,69955],"valid",[],"NV8"],[[69956,69967],"disallowed"],[[69968,70003],"valid"],[[70004,70005],"valid",[],"NV8"],[[70006,70006],"valid"],[[70007,70015],"disallowed"],[[70016,70084],"valid"],[[70085,70088],"valid",[],"NV8"],[[70089,70089],"valid",[],"NV8"],[[70090,70092],"valid"],[[70093,70093],"valid",[],"NV8"],[[70094,70095],"disallowed"],[[70096,70105],"valid"],[[70106,70106],"valid"],[[70107,70107],"valid",[],"NV8"],[[70108,70108],"valid"],[[70109,70111],"valid",[],"NV8"],[[70112,70112],"disallowed"],[[70113,70132],"valid",[],"NV8"],[[70133,70143],"disallowed"],[[70144,70161],"valid"],[[70162,70162],"disallowed"],[[70163,70199],"valid"],[[70200,70205],"valid",[],"NV8"],[[70206,70271],"disallowed"],[[70272,70278],"valid"],[[70279,70279],"disallowed"],[[70280,70280],"valid"],[[70281,70281],"disallowed"],[[70282,70285],"valid"],[[70286,70286],"disallowed"],[[70287,70301],"valid"],[[70302,70302],"disallowed"],[[70303,70312],"valid"],[[70313,70313],"valid",[],"NV8"],[[70314,70319],"disallowed"],[[70320,70378],"valid"],[[70379,70383],"disallowed"],[[70384,70393],"valid"],[[70394,70399],"disallowed"],[[70400,70400],"valid"],[[70401,70403],"valid"],[[70404,70404],"disallowed"],[[70405,70412],"valid"],[[70413,70414],"disallowed"],[[70415,70416],"valid"],[[70417,70418],"disallowed"],[[70419,70440],"valid"],[[70441,70441],"disallowed"],[[70442,70448],"valid"],[[70449,70449],"disallowed"],[[70450,70451],"valid"],[[70452,70452],"disallowed"],[[70453,70457],"valid"],[[70458,70459],"disallowed"],[[70460,70468],"valid"],[[70469,70470],"disallowed"],[[70471,70472],"valid"],[[70473,70474],"disallowed"],[[70475,70477],"valid"],[[70478,70479],"disallowed"],[[70480,70480],"valid"],[[70481,70486],"disallowed"],[[70487,70487],"valid"],[[70488,70492],"disallowed"],[[70493,70499],"valid"],[[70500,70501],"disallowed"],[[70502,70508],"valid"],[[70509,70511],"disallowed"],[[70512,70516],"valid"],[[70517,70783],"disallowed"],[[70784,70853],"valid"],[[70854,70854],"valid",[],"NV8"],[[70855,70855],"valid"],[[70856,70863],"disallowed"],[[70864,70873],"valid"],[[70874,71039],"disallowed"],[[71040,71093],"valid"],[[71094,71095],"disallowed"],[[71096,71104],"valid"],[[71105,71113],"valid",[],"NV8"],[[71114,71127],"valid",[],"NV8"],[[71128,71133],"valid"],[[71134,71167],"disallowed"],[[71168,71232],"valid"],[[71233,71235],"valid",[],"NV8"],[[71236,71236],"valid"],[[71237,71247],"disallowed"],[[71248,71257],"valid"],[[71258,71295],"disallowed"],[[71296,71351],"valid"],[[71352,71359],"disallowed"],[[71360,71369],"valid"],[[71370,71423],"disallowed"],[[71424,71449],"valid"],[[71450,71452],"disallowed"],[[71453,71467],"valid"],[[71468,71471],"disallowed"],[[71472,71481],"valid"],[[71482,71487],"valid",[],"NV8"],[[71488,71839],"disallowed"],[[71840,71840],"mapped",[71872]],[[71841,71841],"mapped",[71873]],[[71842,71842],"mapped",[71874]],[[71843,71843],"mapped",[71875]],[[71844,71844],"mapped",[71876]],[[71845,71845],"mapped",[71877]],[[71846,71846],"mapped",[71878]],[[71847,71847],"mapped",[71879]],[[71848,71848],"mapped",[71880]],[[71849,71849],"mapped",[71881]],[[71850,71850],"mapped",[71882]],[[71851,71851],"mapped",[71883]],[[71852,71852],"mapped",[71884]],[[71853,71853],"mapped",[71885]],[[71854,71854],"mapped",[71886]],[[71855,71855],"mapped",[71887]],[[71856,71856],"mapped",[71888]],[[71857,71857],"mapped",[71889]],[[71858,71858],"mapped",[71890]],[[71859,71859],"mapped",[71891]],[[71860,71860],"mapped",[71892]],[[71861,71861],"mapped",[71893]],[[71862,71862],"mapped",[71894]],[[71863,71863],"mapped",[71895]],[[71864,71864],"mapped",[71896]],[[71865,71865],"mapped",[71897]],[[71866,71866],"mapped",[71898]],[[71867,71867],"mapped",[71899]],[[71868,71868],"mapped",[71900]],[[71869,71869],"mapped",[71901]],[[71870,71870],"mapped",[71902]],[[71871,71871],"mapped",[71903]],[[71872,71913],"valid"],[[71914,71922],"valid",[],"NV8"],[[71923,71934],"disallowed"],[[71935,71935],"valid"],[[71936,72383],"disallowed"],[[72384,72440],"valid"],[[72441,73727],"disallowed"],[[73728,74606],"valid"],[[74607,74648],"valid"],[[74649,74649],"valid"],[[74650,74751],"disallowed"],[[74752,74850],"valid",[],"NV8"],[[74851,74862],"valid",[],"NV8"],[[74863,74863],"disallowed"],[[74864,74867],"valid",[],"NV8"],[[74868,74868],"valid",[],"NV8"],[[74869,74879],"disallowed"],[[74880,75075],"valid"],[[75076,77823],"disallowed"],[[77824,78894],"valid"],[[78895,82943],"disallowed"],[[82944,83526],"valid"],[[83527,92159],"disallowed"],[[92160,92728],"valid"],[[92729,92735],"disallowed"],[[92736,92766],"valid"],[[92767,92767],"disallowed"],[[92768,92777],"valid"],[[92778,92781],"disallowed"],[[92782,92783],"valid",[],"NV8"],[[92784,92879],"disallowed"],[[92880,92909],"valid"],[[92910,92911],"disallowed"],[[92912,92916],"valid"],[[92917,92917],"valid",[],"NV8"],[[92918,92927],"disallowed"],[[92928,92982],"valid"],[[92983,92991],"valid",[],"NV8"],[[92992,92995],"valid"],[[92996,92997],"valid",[],"NV8"],[[92998,93007],"disallowed"],[[93008,93017],"valid"],[[93018,93018],"disallowed"],[[93019,93025],"valid",[],"NV8"],[[93026,93026],"disallowed"],[[93027,93047],"valid"],[[93048,93052],"disallowed"],[[93053,93071],"valid"],[[93072,93951],"disallowed"],[[93952,94020],"valid"],[[94021,94031],"disallowed"],[[94032,94078],"valid"],[[94079,94094],"disallowed"],[[94095,94111],"valid"],[[94112,110591],"disallowed"],[[110592,110593],"valid"],[[110594,113663],"disallowed"],[[113664,113770],"valid"],[[113771,113775],"disallowed"],[[113776,113788],"valid"],[[113789,113791],"disallowed"],[[113792,113800],"valid"],[[113801,113807],"disallowed"],[[113808,113817],"valid"],[[113818,113819],"disallowed"],[[113820,113820],"valid",[],"NV8"],[[113821,113822],"valid"],[[113823,113823],"valid",[],"NV8"],[[113824,113827],"ignored"],[[113828,118783],"disallowed"],[[118784,119029],"valid",[],"NV8"],[[119030,119039],"disallowed"],[[119040,119078],"valid",[],"NV8"],[[119079,119080],"disallowed"],[[119081,119081],"valid",[],"NV8"],[[119082,119133],"valid",[],"NV8"],[[119134,119134],"mapped",[119127,119141]],[[119135,119135],"mapped",[119128,119141]],[[119136,119136],"mapped",[119128,119141,119150]],[[119137,119137],"mapped",[119128,119141,119151]],[[119138,119138],"mapped",[119128,119141,119152]],[[119139,119139],"mapped",[119128,119141,119153]],[[119140,119140],"mapped",[119128,119141,119154]],[[119141,119154],"valid",[],"NV8"],[[119155,119162],"disallowed"],[[119163,119226],"valid",[],"NV8"],[[119227,119227],"mapped",[119225,119141]],[[119228,119228],"mapped",[119226,119141]],[[119229,119229],"mapped",[119225,119141,119150]],[[119230,119230],"mapped",[119226,119141,119150]],[[119231,119231],"mapped",[119225,119141,119151]],[[119232,119232],"mapped",[119226,119141,119151]],[[119233,119261],"valid",[],"NV8"],[[119262,119272],"valid",[],"NV8"],[[119273,119295],"disallowed"],[[119296,119365],"valid",[],"NV8"],[[119366,119551],"disallowed"],[[119552,119638],"valid",[],"NV8"],[[119639,119647],"disallowed"],[[119648,119665],"valid",[],"NV8"],[[119666,119807],"disallowed"],[[119808,119808],"mapped",[97]],[[119809,119809],"mapped",[98]],[[119810,119810],"mapped",[99]],[[119811,119811],"mapped",[100]],[[119812,119812],"mapped",[101]],[[119813,119813],"mapped",[102]],[[119814,119814],"mapped",[103]],[[119815,119815],"mapped",[104]],[[119816,119816],"mapped",[105]],[[119817,119817],"mapped",[106]],[[119818,119818],"mapped",[107]],[[119819,119819],"mapped",[108]],[[119820,119820],"mapped",[109]],[[119821,119821],"mapped",[110]],[[119822,119822],"mapped",[111]],[[119823,119823],"mapped",[112]],[[119824,119824],"mapped",[113]],[[119825,119825],"mapped",[114]],[[119826,119826],"mapped",[115]],[[119827,119827],"mapped",[116]],[[119828,119828],"mapped",[117]],[[119829,119829],"mapped",[118]],[[119830,119830],"mapped",[119]],[[119831,119831],"mapped",[120]],[[119832,119832],"mapped",[121]],[[119833,119833],"mapped",[122]],[[119834,119834],"mapped",[97]],[[119835,119835],"mapped",[98]],[[119836,119836],"mapped",[99]],[[119837,119837],"mapped",[100]],[[119838,119838],"mapped",[101]],[[119839,119839],"mapped",[102]],[[119840,119840],"mapped",[103]],[[119841,119841],"mapped",[104]],[[119842,119842],"mapped",[105]],[[119843,119843],"mapped",[106]],[[119844,119844],"mapped",[107]],[[119845,119845],"mapped",[108]],[[119846,119846],"mapped",[109]],[[119847,119847],"mapped",[110]],[[119848,119848],"mapped",[111]],[[119849,119849],"mapped",[112]],[[119850,119850],"mapped",[113]],[[119851,119851],"mapped",[114]],[[119852,119852],"mapped",[115]],[[119853,119853],"mapped",[116]],[[119854,119854],"mapped",[117]],[[119855,119855],"mapped",[118]],[[119856,119856],"mapped",[119]],[[119857,119857],"mapped",[120]],[[119858,119858],"mapped",[121]],[[119859,119859],"mapped",[122]],[[119860,119860],"mapped",[97]],[[119861,119861],"mapped",[98]],[[119862,119862],"mapped",[99]],[[119863,119863],"mapped",[100]],[[119864,119864],"mapped",[101]],[[119865,119865],"mapped",[102]],[[119866,119866],"mapped",[103]],[[119867,119867],"mapped",[104]],[[119868,119868],"mapped",[105]],[[119869,119869],"mapped",[106]],[[119870,119870],"mapped",[107]],[[119871,119871],"mapped",[108]],[[119872,119872],"mapped",[109]],[[119873,119873],"mapped",[110]],[[119874,119874],"mapped",[111]],[[119875,119875],"mapped",[112]],[[119876,119876],"mapped",[113]],[[119877,119877],"mapped",[114]],[[119878,119878],"mapped",[115]],[[119879,119879],"mapped",[116]],[[119880,119880],"mapped",[117]],[[119881,119881],"mapped",[118]],[[119882,119882],"mapped",[119]],[[119883,119883],"mapped",[120]],[[119884,119884],"mapped",[121]],[[119885,119885],"mapped",[122]],[[119886,119886],"mapped",[97]],[[119887,119887],"mapped",[98]],[[119888,119888],"mapped",[99]],[[119889,119889],"mapped",[100]],[[119890,119890],"mapped",[101]],[[119891,119891],"mapped",[102]],[[119892,119892],"mapped",[103]],[[119893,119893],"disallowed"],[[119894,119894],"mapped",[105]],[[119895,119895],"mapped",[106]],[[119896,119896],"mapped",[107]],[[119897,119897],"mapped",[108]],[[119898,119898],"mapped",[109]],[[119899,119899],"mapped",[110]],[[119900,119900],"mapped",[111]],[[119901,119901],"mapped",[112]],[[119902,119902],"mapped",[113]],[[119903,119903],"mapped",[114]],[[119904,119904],"mapped",[115]],[[119905,119905],"mapped",[116]],[[119906,119906],"mapped",[117]],[[119907,119907],"mapped",[118]],[[119908,119908],"mapped",[119]],[[119909,119909],"mapped",[120]],[[119910,119910],"mapped",[121]],[[119911,119911],"mapped",[122]],[[119912,119912],"mapped",[97]],[[119913,119913],"mapped",[98]],[[119914,119914],"mapped",[99]],[[119915,119915],"mapped",[100]],[[119916,119916],"mapped",[101]],[[119917,119917],"mapped",[102]],[[119918,119918],"mapped",[103]],[[119919,119919],"mapped",[104]],[[119920,119920],"mapped",[105]],[[119921,119921],"mapped",[106]],[[119922,119922],"mapped",[107]],[[119923,119923],"mapped",[108]],[[119924,119924],"mapped",[109]],[[119925,119925],"mapped",[110]],[[119926,119926],"mapped",[111]],[[119927,119927],"mapped",[112]],[[119928,119928],"mapped",[113]],[[119929,119929],"mapped",[114]],[[119930,119930],"mapped",[115]],[[119931,119931],"mapped",[116]],[[119932,119932],"mapped",[117]],[[119933,119933],"mapped",[118]],[[119934,119934],"mapped",[119]],[[119935,119935],"mapped",[120]],[[119936,119936],"mapped",[121]],[[119937,119937],"mapped",[122]],[[119938,119938],"mapped",[97]],[[119939,119939],"mapped",[98]],[[119940,119940],"mapped",[99]],[[119941,119941],"mapped",[100]],[[119942,119942],"mapped",[101]],[[119943,119943],"mapped",[102]],[[119944,119944],"mapped",[103]],[[119945,119945],"mapped",[104]],[[119946,119946],"mapped",[105]],[[119947,119947],"mapped",[106]],[[119948,119948],"mapped",[107]],[[119949,119949],"mapped",[108]],[[119950,119950],"mapped",[109]],[[119951,119951],"mapped",[110]],[[119952,119952],"mapped",[111]],[[119953,119953],"mapped",[112]],[[119954,119954],"mapped",[113]],[[119955,119955],"mapped",[114]],[[119956,119956],"mapped",[115]],[[119957,119957],"mapped",[116]],[[119958,119958],"mapped",[117]],[[119959,119959],"mapped",[118]],[[119960,119960],"mapped",[119]],[[119961,119961],"mapped",[120]],[[119962,119962],"mapped",[121]],[[119963,119963],"mapped",[122]],[[119964,119964],"mapped",[97]],[[119965,119965],"disallowed"],[[119966,119966],"mapped",[99]],[[119967,119967],"mapped",[100]],[[119968,119969],"disallowed"],[[119970,119970],"mapped",[103]],[[119971,119972],"disallowed"],[[119973,119973],"mapped",[106]],[[119974,119974],"mapped",[107]],[[119975,119976],"disallowed"],[[119977,119977],"mapped",[110]],[[119978,119978],"mapped",[111]],[[119979,119979],"mapped",[112]],[[119980,119980],"mapped",[113]],[[119981,119981],"disallowed"],[[119982,119982],"mapped",[115]],[[119983,119983],"mapped",[116]],[[119984,119984],"mapped",[117]],[[119985,119985],"mapped",[118]],[[119986,119986],"mapped",[119]],[[119987,119987],"mapped",[120]],[[119988,119988],"mapped",[121]],[[119989,119989],"mapped",[122]],[[119990,119990],"mapped",[97]],[[119991,119991],"mapped",[98]],[[119992,119992],"mapped",[99]],[[119993,119993],"mapped",[100]],[[119994,119994],"disallowed"],[[119995,119995],"mapped",[102]],[[119996,119996],"disallowed"],[[119997,119997],"mapped",[104]],[[119998,119998],"mapped",[105]],[[119999,119999],"mapped",[106]],[[120000,120000],"mapped",[107]],[[120001,120001],"mapped",[108]],[[120002,120002],"mapped",[109]],[[120003,120003],"mapped",[110]],[[120004,120004],"disallowed"],[[120005,120005],"mapped",[112]],[[120006,120006],"mapped",[113]],[[120007,120007],"mapped",[114]],[[120008,120008],"mapped",[115]],[[120009,120009],"mapped",[116]],[[120010,120010],"mapped",[117]],[[120011,120011],"mapped",[118]],[[120012,120012],"mapped",[119]],[[120013,120013],"mapped",[120]],[[120014,120014],"mapped",[121]],[[120015,120015],"mapped",[122]],[[120016,120016],"mapped",[97]],[[120017,120017],"mapped",[98]],[[120018,120018],"mapped",[99]],[[120019,120019],"mapped",[100]],[[120020,120020],"mapped",[101]],[[120021,120021],"mapped",[102]],[[120022,120022],"mapped",[103]],[[120023,120023],"mapped",[104]],[[120024,120024],"mapped",[105]],[[120025,120025],"mapped",[106]],[[120026,120026],"mapped",[107]],[[120027,120027],"mapped",[108]],[[120028,120028],"mapped",[109]],[[120029,120029],"mapped",[110]],[[120030,120030],"mapped",[111]],[[120031,120031],"mapped",[112]],[[120032,120032],"mapped",[113]],[[120033,120033],"mapped",[114]],[[120034,120034],"mapped",[115]],[[120035,120035],"mapped",[116]],[[120036,120036],"mapped",[117]],[[120037,120037],"mapped",[118]],[[120038,120038],"mapped",[119]],[[120039,120039],"mapped",[120]],[[120040,120040],"mapped",[121]],[[120041,120041],"mapped",[122]],[[120042,120042],"mapped",[97]],[[120043,120043],"mapped",[98]],[[120044,120044],"mapped",[99]],[[120045,120045],"mapped",[100]],[[120046,120046],"mapped",[101]],[[120047,120047],"mapped",[102]],[[120048,120048],"mapped",[103]],[[120049,120049],"mapped",[104]],[[120050,120050],"mapped",[105]],[[120051,120051],"mapped",[106]],[[120052,120052],"mapped",[107]],[[120053,120053],"mapped",[108]],[[120054,120054],"mapped",[109]],[[120055,120055],"mapped",[110]],[[120056,120056],"mapped",[111]],[[120057,120057],"mapped",[112]],[[120058,120058],"mapped",[113]],[[120059,120059],"mapped",[114]],[[120060,120060],"mapped",[115]],[[120061,120061],"mapped",[116]],[[120062,120062],"mapped",[117]],[[120063,120063],"mapped",[118]],[[120064,120064],"mapped",[119]],[[120065,120065],"mapped",[120]],[[120066,120066],"mapped",[121]],[[120067,120067],"mapped",[122]],[[120068,120068],"mapped",[97]],[[120069,120069],"mapped",[98]],[[120070,120070],"disallowed"],[[120071,120071],"mapped",[100]],[[120072,120072],"mapped",[101]],[[120073,120073],"mapped",[102]],[[120074,120074],"mapped",[103]],[[120075,120076],"disallowed"],[[120077,120077],"mapped",[106]],[[120078,120078],"mapped",[107]],[[120079,120079],"mapped",[108]],[[120080,120080],"mapped",[109]],[[120081,120081],"mapped",[110]],[[120082,120082],"mapped",[111]],[[120083,120083],"mapped",[112]],[[120084,120084],"mapped",[113]],[[120085,120085],"disallowed"],[[120086,120086],"mapped",[115]],[[120087,120087],"mapped",[116]],[[120088,120088],"mapped",[117]],[[120089,120089],"mapped",[118]],[[120090,120090],"mapped",[119]],[[120091,120091],"mapped",[120]],[[120092,120092],"mapped",[121]],[[120093,120093],"disallowed"],[[120094,120094],"mapped",[97]],[[120095,120095],"mapped",[98]],[[120096,120096],"mapped",[99]],[[120097,120097],"mapped",[100]],[[120098,120098],"mapped",[101]],[[120099,120099],"mapped",[102]],[[120100,120100],"mapped",[103]],[[120101,120101],"mapped",[104]],[[120102,120102],"mapped",[105]],[[120103,120103],"mapped",[106]],[[120104,120104],"mapped",[107]],[[120105,120105],"mapped",[108]],[[120106,120106],"mapped",[109]],[[120107,120107],"mapped",[110]],[[120108,120108],"mapped",[111]],[[120109,120109],"mapped",[112]],[[120110,120110],"mapped",[113]],[[120111,120111],"mapped",[114]],[[120112,120112],"mapped",[115]],[[120113,120113],"mapped",[116]],[[120114,120114],"mapped",[117]],[[120115,120115],"mapped",[118]],[[120116,120116],"mapped",[119]],[[120117,120117],"mapped",[120]],[[120118,120118],"mapped",[121]],[[120119,120119],"mapped",[122]],[[120120,120120],"mapped",[97]],[[120121,120121],"mapped",[98]],[[120122,120122],"disallowed"],[[120123,120123],"mapped",[100]],[[120124,120124],"mapped",[101]],[[120125,120125],"mapped",[102]],[[120126,120126],"mapped",[103]],[[120127,120127],"disallowed"],[[120128,120128],"mapped",[105]],[[120129,120129],"mapped",[106]],[[120130,120130],"mapped",[107]],[[120131,120131],"mapped",[108]],[[120132,120132],"mapped",[109]],[[120133,120133],"disallowed"],[[120134,120134],"mapped",[111]],[[120135,120137],"disallowed"],[[120138,120138],"mapped",[115]],[[120139,120139],"mapped",[116]],[[120140,120140],"mapped",[117]],[[120141,120141],"mapped",[118]],[[120142,120142],"mapped",[119]],[[120143,120143],"mapped",[120]],[[120144,120144],"mapped",[121]],[[120145,120145],"disallowed"],[[120146,120146],"mapped",[97]],[[120147,120147],"mapped",[98]],[[120148,120148],"mapped",[99]],[[120149,120149],"mapped",[100]],[[120150,120150],"mapped",[101]],[[120151,120151],"mapped",[102]],[[120152,120152],"mapped",[103]],[[120153,120153],"mapped",[104]],[[120154,120154],"mapped",[105]],[[120155,120155],"mapped",[106]],[[120156,120156],"mapped",[107]],[[120157,120157],"mapped",[108]],[[120158,120158],"mapped",[109]],[[120159,120159],"mapped",[110]],[[120160,120160],"mapped",[111]],[[120161,120161],"mapped",[112]],[[120162,120162],"mapped",[113]],[[120163,120163],"mapped",[114]],[[120164,120164],"mapped",[115]],[[120165,120165],"mapped",[116]],[[120166,120166],"mapped",[117]],[[120167,120167],"mapped",[118]],[[120168,120168],"mapped",[119]],[[120169,120169],"mapped",[120]],[[120170,120170],"mapped",[121]],[[120171,120171],"mapped",[122]],[[120172,120172],"mapped",[97]],[[120173,120173],"mapped",[98]],[[120174,120174],"mapped",[99]],[[120175,120175],"mapped",[100]],[[120176,120176],"mapped",[101]],[[120177,120177],"mapped",[102]],[[120178,120178],"mapped",[103]],[[120179,120179],"mapped",[104]],[[120180,120180],"mapped",[105]],[[120181,120181],"mapped",[106]],[[120182,120182],"mapped",[107]],[[120183,120183],"mapped",[108]],[[120184,120184],"mapped",[109]],[[120185,120185],"mapped",[110]],[[120186,120186],"mapped",[111]],[[120187,120187],"mapped",[112]],[[120188,120188],"mapped",[113]],[[120189,120189],"mapped",[114]],[[120190,120190],"mapped",[115]],[[120191,120191],"mapped",[116]],[[120192,120192],"mapped",[117]],[[120193,120193],"mapped",[118]],[[120194,120194],"mapped",[119]],[[120195,120195],"mapped",[120]],[[120196,120196],"mapped",[121]],[[120197,120197],"mapped",[122]],[[120198,120198],"mapped",[97]],[[120199,120199],"mapped",[98]],[[120200,120200],"mapped",[99]],[[120201,120201],"mapped",[100]],[[120202,120202],"mapped",[101]],[[120203,120203],"mapped",[102]],[[120204,120204],"mapped",[103]],[[120205,120205],"mapped",[104]],[[120206,120206],"mapped",[105]],[[120207,120207],"mapped",[106]],[[120208,120208],"mapped",[107]],[[120209,120209],"mapped",[108]],[[120210,120210],"mapped",[109]],[[120211,120211],"mapped",[110]],[[120212,120212],"mapped",[111]],[[120213,120213],"mapped",[112]],[[120214,120214],"mapped",[113]],[[120215,120215],"mapped",[114]],[[120216,120216],"mapped",[115]],[[120217,120217],"mapped",[116]],[[120218,120218],"mapped",[117]],[[120219,120219],"mapped",[118]],[[120220,120220],"mapped",[119]],[[120221,120221],"mapped",[120]],[[120222,120222],"mapped",[121]],[[120223,120223],"mapped",[122]],[[120224,120224],"mapped",[97]],[[120225,120225],"mapped",[98]],[[120226,120226],"mapped",[99]],[[120227,120227],"mapped",[100]],[[120228,120228],"mapped",[101]],[[120229,120229],"mapped",[102]],[[120230,120230],"mapped",[103]],[[120231,120231],"mapped",[104]],[[120232,120232],"mapped",[105]],[[120233,120233],"mapped",[106]],[[120234,120234],"mapped",[107]],[[120235,120235],"mapped",[108]],[[120236,120236],"mapped",[109]],[[120237,120237],"mapped",[110]],[[120238,120238],"mapped",[111]],[[120239,120239],"mapped",[112]],[[120240,120240],"mapped",[113]],[[120241,120241],"mapped",[114]],[[120242,120242],"mapped",[115]],[[120243,120243],"mapped",[116]],[[120244,120244],"mapped",[117]],[[120245,120245],"mapped",[118]],[[120246,120246],"mapped",[119]],[[120247,120247],"mapped",[120]],[[120248,120248],"mapped",[121]],[[120249,120249],"mapped",[122]],[[120250,120250],"mapped",[97]],[[120251,120251],"mapped",[98]],[[120252,120252],"mapped",[99]],[[120253,120253],"mapped",[100]],[[120254,120254],"mapped",[101]],[[120255,120255],"mapped",[102]],[[120256,120256],"mapped",[103]],[[120257,120257],"mapped",[104]],[[120258,120258],"mapped",[105]],[[120259,120259],"mapped",[106]],[[120260,120260],"mapped",[107]],[[120261,120261],"mapped",[108]],[[120262,120262],"mapped",[109]],[[120263,120263],"mapped",[110]],[[120264,120264],"mapped",[111]],[[120265,120265],"mapped",[112]],[[120266,120266],"mapped",[113]],[[120267,120267],"mapped",[114]],[[120268,120268],"mapped",[115]],[[120269,120269],"mapped",[116]],[[120270,120270],"mapped",[117]],[[120271,120271],"mapped",[118]],[[120272,120272],"mapped",[119]],[[120273,120273],"mapped",[120]],[[120274,120274],"mapped",[121]],[[120275,120275],"mapped",[122]],[[120276,120276],"mapped",[97]],[[120277,120277],"mapped",[98]],[[120278,120278],"mapped",[99]],[[120279,120279],"mapped",[100]],[[120280,120280],"mapped",[101]],[[120281,120281],"mapped",[102]],[[120282,120282],"mapped",[103]],[[120283,120283],"mapped",[104]],[[120284,120284],"mapped",[105]],[[120285,120285],"mapped",[106]],[[120286,120286],"mapped",[107]],[[120287,120287],"mapped",[108]],[[120288,120288],"mapped",[109]],[[120289,120289],"mapped",[110]],[[120290,120290],"mapped",[111]],[[120291,120291],"mapped",[112]],[[120292,120292],"mapped",[113]],[[120293,120293],"mapped",[114]],[[120294,120294],"mapped",[115]],[[120295,120295],"mapped",[116]],[[120296,120296],"mapped",[117]],[[120297,120297],"mapped",[118]],[[120298,120298],"mapped",[119]],[[120299,120299],"mapped",[120]],[[120300,120300],"mapped",[121]],[[120301,120301],"mapped",[122]],[[120302,120302],"mapped",[97]],[[120303,120303],"mapped",[98]],[[120304,120304],"mapped",[99]],[[120305,120305],"mapped",[100]],[[120306,120306],"mapped",[101]],[[120307,120307],"mapped",[102]],[[120308,120308],"mapped",[103]],[[120309,120309],"mapped",[104]],[[120310,120310],"mapped",[105]],[[120311,120311],"mapped",[106]],[[120312,120312],"mapped",[107]],[[120313,120313],"mapped",[108]],[[120314,120314],"mapped",[109]],[[120315,120315],"mapped",[110]],[[120316,120316],"mapped",[111]],[[120317,120317],"mapped",[112]],[[120318,120318],"mapped",[113]],[[120319,120319],"mapped",[114]],[[120320,120320],"mapped",[115]],[[120321,120321],"mapped",[116]],[[120322,120322],"mapped",[117]],[[120323,120323],"mapped",[118]],[[120324,120324],"mapped",[119]],[[120325,120325],"mapped",[120]],[[120326,120326],"mapped",[121]],[[120327,120327],"mapped",[122]],[[120328,120328],"mapped",[97]],[[120329,120329],"mapped",[98]],[[120330,120330],"mapped",[99]],[[120331,120331],"mapped",[100]],[[120332,120332],"mapped",[101]],[[120333,120333],"mapped",[102]],[[120334,120334],"mapped",[103]],[[120335,120335],"mapped",[104]],[[120336,120336],"mapped",[105]],[[120337,120337],"mapped",[106]],[[120338,120338],"mapped",[107]],[[120339,120339],"mapped",[108]],[[120340,120340],"mapped",[109]],[[120341,120341],"mapped",[110]],[[120342,120342],"mapped",[111]],[[120343,120343],"mapped",[112]],[[120344,120344],"mapped",[113]],[[120345,120345],"mapped",[114]],[[120346,120346],"mapped",[115]],[[120347,120347],"mapped",[116]],[[120348,120348],"mapped",[117]],[[120349,120349],"mapped",[118]],[[120350,120350],"mapped",[119]],[[120351,120351],"mapped",[120]],[[120352,120352],"mapped",[121]],[[120353,120353],"mapped",[122]],[[120354,120354],"mapped",[97]],[[120355,120355],"mapped",[98]],[[120356,120356],"mapped",[99]],[[120357,120357],"mapped",[100]],[[120358,120358],"mapped",[101]],[[120359,120359],"mapped",[102]],[[120360,120360],"mapped",[103]],[[120361,120361],"mapped",[104]],[[120362,120362],"mapped",[105]],[[120363,120363],"mapped",[106]],[[120364,120364],"mapped",[107]],[[120365,120365],"mapped",[108]],[[120366,120366],"mapped",[109]],[[120367,120367],"mapped",[110]],[[120368,120368],"mapped",[111]],[[120369,120369],"mapped",[112]],[[120370,120370],"mapped",[113]],[[120371,120371],"mapped",[114]],[[120372,120372],"mapped",[115]],[[120373,120373],"mapped",[116]],[[120374,120374],"mapped",[117]],[[120375,120375],"mapped",[118]],[[120376,120376],"mapped",[119]],[[120377,120377],"mapped",[120]],[[120378,120378],"mapped",[121]],[[120379,120379],"mapped",[122]],[[120380,120380],"mapped",[97]],[[120381,120381],"mapped",[98]],[[120382,120382],"mapped",[99]],[[120383,120383],"mapped",[100]],[[120384,120384],"mapped",[101]],[[120385,120385],"mapped",[102]],[[120386,120386],"mapped",[103]],[[120387,120387],"mapped",[104]],[[120388,120388],"mapped",[105]],[[120389,120389],"mapped",[106]],[[120390,120390],"mapped",[107]],[[120391,120391],"mapped",[108]],[[120392,120392],"mapped",[109]],[[120393,120393],"mapped",[110]],[[120394,120394],"mapped",[111]],[[120395,120395],"mapped",[112]],[[120396,120396],"mapped",[113]],[[120397,120397],"mapped",[114]],[[120398,120398],"mapped",[115]],[[120399,120399],"mapped",[116]],[[120400,120400],"mapped",[117]],[[120401,120401],"mapped",[118]],[[120402,120402],"mapped",[119]],[[120403,120403],"mapped",[120]],[[120404,120404],"mapped",[121]],[[120405,120405],"mapped",[122]],[[120406,120406],"mapped",[97]],[[120407,120407],"mapped",[98]],[[120408,120408],"mapped",[99]],[[120409,120409],"mapped",[100]],[[120410,120410],"mapped",[101]],[[120411,120411],"mapped",[102]],[[120412,120412],"mapped",[103]],[[120413,120413],"mapped",[104]],[[120414,120414],"mapped",[105]],[[120415,120415],"mapped",[106]],[[120416,120416],"mapped",[107]],[[120417,120417],"mapped",[108]],[[120418,120418],"mapped",[109]],[[120419,120419],"mapped",[110]],[[120420,120420],"mapped",[111]],[[120421,120421],"mapped",[112]],[[120422,120422],"mapped",[113]],[[120423,120423],"mapped",[114]],[[120424,120424],"mapped",[115]],[[120425,120425],"mapped",[116]],[[120426,120426],"mapped",[117]],[[120427,120427],"mapped",[118]],[[120428,120428],"mapped",[119]],[[120429,120429],"mapped",[120]],[[120430,120430],"mapped",[121]],[[120431,120431],"mapped",[122]],[[120432,120432],"mapped",[97]],[[120433,120433],"mapped",[98]],[[120434,120434],"mapped",[99]],[[120435,120435],"mapped",[100]],[[120436,120436],"mapped",[101]],[[120437,120437],"mapped",[102]],[[120438,120438],"mapped",[103]],[[120439,120439],"mapped",[104]],[[120440,120440],"mapped",[105]],[[120441,120441],"mapped",[106]],[[120442,120442],"mapped",[107]],[[120443,120443],"mapped",[108]],[[120444,120444],"mapped",[109]],[[120445,120445],"mapped",[110]],[[120446,120446],"mapped",[111]],[[120447,120447],"mapped",[112]],[[120448,120448],"mapped",[113]],[[120449,120449],"mapped",[114]],[[120450,120450],"mapped",[115]],[[120451,120451],"mapped",[116]],[[120452,120452],"mapped",[117]],[[120453,120453],"mapped",[118]],[[120454,120454],"mapped",[119]],[[120455,120455],"mapped",[120]],[[120456,120456],"mapped",[121]],[[120457,120457],"mapped",[122]],[[120458,120458],"mapped",[97]],[[120459,120459],"mapped",[98]],[[120460,120460],"mapped",[99]],[[120461,120461],"mapped",[100]],[[120462,120462],"mapped",[101]],[[120463,120463],"mapped",[102]],[[120464,120464],"mapped",[103]],[[120465,120465],"mapped",[104]],[[120466,120466],"mapped",[105]],[[120467,120467],"mapped",[106]],[[120468,120468],"mapped",[107]],[[120469,120469],"mapped",[108]],[[120470,120470],"mapped",[109]],[[120471,120471],"mapped",[110]],[[120472,120472],"mapped",[111]],[[120473,120473],"mapped",[112]],[[120474,120474],"mapped",[113]],[[120475,120475],"mapped",[114]],[[120476,120476],"mapped",[115]],[[120477,120477],"mapped",[116]],[[120478,120478],"mapped",[117]],[[120479,120479],"mapped",[118]],[[120480,120480],"mapped",[119]],[[120481,120481],"mapped",[120]],[[120482,120482],"mapped",[121]],[[120483,120483],"mapped",[122]],[[120484,120484],"mapped",[305]],[[120485,120485],"mapped",[567]],[[120486,120487],"disallowed"],[[120488,120488],"mapped",[945]],[[120489,120489],"mapped",[946]],[[120490,120490],"mapped",[947]],[[120491,120491],"mapped",[948]],[[120492,120492],"mapped",[949]],[[120493,120493],"mapped",[950]],[[120494,120494],"mapped",[951]],[[120495,120495],"mapped",[952]],[[120496,120496],"mapped",[953]],[[120497,120497],"mapped",[954]],[[120498,120498],"mapped",[955]],[[120499,120499],"mapped",[956]],[[120500,120500],"mapped",[957]],[[120501,120501],"mapped",[958]],[[120502,120502],"mapped",[959]],[[120503,120503],"mapped",[960]],[[120504,120504],"mapped",[961]],[[120505,120505],"mapped",[952]],[[120506,120506],"mapped",[963]],[[120507,120507],"mapped",[964]],[[120508,120508],"mapped",[965]],[[120509,120509],"mapped",[966]],[[120510,120510],"mapped",[967]],[[120511,120511],"mapped",[968]],[[120512,120512],"mapped",[969]],[[120513,120513],"mapped",[8711]],[[120514,120514],"mapped",[945]],[[120515,120515],"mapped",[946]],[[120516,120516],"mapped",[947]],[[120517,120517],"mapped",[948]],[[120518,120518],"mapped",[949]],[[120519,120519],"mapped",[950]],[[120520,120520],"mapped",[951]],[[120521,120521],"mapped",[952]],[[120522,120522],"mapped",[953]],[[120523,120523],"mapped",[954]],[[120524,120524],"mapped",[955]],[[120525,120525],"mapped",[956]],[[120526,120526],"mapped",[957]],[[120527,120527],"mapped",[958]],[[120528,120528],"mapped",[959]],[[120529,120529],"mapped",[960]],[[120530,120530],"mapped",[961]],[[120531,120532],"mapped",[963]],[[120533,120533],"mapped",[964]],[[120534,120534],"mapped",[965]],[[120535,120535],"mapped",[966]],[[120536,120536],"mapped",[967]],[[120537,120537],"mapped",[968]],[[120538,120538],"mapped",[969]],[[120539,120539],"mapped",[8706]],[[120540,120540],"mapped",[949]],[[120541,120541],"mapped",[952]],[[120542,120542],"mapped",[954]],[[120543,120543],"mapped",[966]],[[120544,120544],"mapped",[961]],[[120545,120545],"mapped",[960]],[[120546,120546],"mapped",[945]],[[120547,120547],"mapped",[946]],[[120548,120548],"mapped",[947]],[[120549,120549],"mapped",[948]],[[120550,120550],"mapped",[949]],[[120551,120551],"mapped",[950]],[[120552,120552],"mapped",[951]],[[120553,120553],"mapped",[952]],[[120554,120554],"mapped",[953]],[[120555,120555],"mapped",[954]],[[120556,120556],"mapped",[955]],[[120557,120557],"mapped",[956]],[[120558,120558],"mapped",[957]],[[120559,120559],"mapped",[958]],[[120560,120560],"mapped",[959]],[[120561,120561],"mapped",[960]],[[120562,120562],"mapped",[961]],[[120563,120563],"mapped",[952]],[[120564,120564],"mapped",[963]],[[120565,120565],"mapped",[964]],[[120566,120566],"mapped",[965]],[[120567,120567],"mapped",[966]],[[120568,120568],"mapped",[967]],[[120569,120569],"mapped",[968]],[[120570,120570],"mapped",[969]],[[120571,120571],"mapped",[8711]],[[120572,120572],"mapped",[945]],[[120573,120573],"mapped",[946]],[[120574,120574],"mapped",[947]],[[120575,120575],"mapped",[948]],[[120576,120576],"mapped",[949]],[[120577,120577],"mapped",[950]],[[120578,120578],"mapped",[951]],[[120579,120579],"mapped",[952]],[[120580,120580],"mapped",[953]],[[120581,120581],"mapped",[954]],[[120582,120582],"mapped",[955]],[[120583,120583],"mapped",[956]],[[120584,120584],"mapped",[957]],[[120585,120585],"mapped",[958]],[[120586,120586],"mapped",[959]],[[120587,120587],"mapped",[960]],[[120588,120588],"mapped",[961]],[[120589,120590],"mapped",[963]],[[120591,120591],"mapped",[964]],[[120592,120592],"mapped",[965]],[[120593,120593],"mapped",[966]],[[120594,120594],"mapped",[967]],[[120595,120595],"mapped",[968]],[[120596,120596],"mapped",[969]],[[120597,120597],"mapped",[8706]],[[120598,120598],"mapped",[949]],[[120599,120599],"mapped",[952]],[[120600,120600],"mapped",[954]],[[120601,120601],"mapped",[966]],[[120602,120602],"mapped",[961]],[[120603,120603],"mapped",[960]],[[120604,120604],"mapped",[945]],[[120605,120605],"mapped",[946]],[[120606,120606],"mapped",[947]],[[120607,120607],"mapped",[948]],[[120608,120608],"mapped",[949]],[[120609,120609],"mapped",[950]],[[120610,120610],"mapped",[951]],[[120611,120611],"mapped",[952]],[[120612,120612],"mapped",[953]],[[120613,120613],"mapped",[954]],[[120614,120614],"mapped",[955]],[[120615,120615],"mapped",[956]],[[120616,120616],"mapped",[957]],[[120617,120617],"mapped",[958]],[[120618,120618],"mapped",[959]],[[120619,120619],"mapped",[960]],[[120620,120620],"mapped",[961]],[[120621,120621],"mapped",[952]],[[120622,120622],"mapped",[963]],[[120623,120623],"mapped",[964]],[[120624,120624],"mapped",[965]],[[120625,120625],"mapped",[966]],[[120626,120626],"mapped",[967]],[[120627,120627],"mapped",[968]],[[120628,120628],"mapped",[969]],[[120629,120629],"mapped",[8711]],[[120630,120630],"mapped",[945]],[[120631,120631],"mapped",[946]],[[120632,120632],"mapped",[947]],[[120633,120633],"mapped",[948]],[[120634,120634],"mapped",[949]],[[120635,120635],"mapped",[950]],[[120636,120636],"mapped",[951]],[[120637,120637],"mapped",[952]],[[120638,120638],"mapped",[953]],[[120639,120639],"mapped",[954]],[[120640,120640],"mapped",[955]],[[120641,120641],"mapped",[956]],[[120642,120642],"mapped",[957]],[[120643,120643],"mapped",[958]],[[120644,120644],"mapped",[959]],[[120645,120645],"mapped",[960]],[[120646,120646],"mapped",[961]],[[120647,120648],"mapped",[963]],[[120649,120649],"mapped",[964]],[[120650,120650],"mapped",[965]],[[120651,120651],"mapped",[966]],[[120652,120652],"mapped",[967]],[[120653,120653],"mapped",[968]],[[120654,120654],"mapped",[969]],[[120655,120655],"mapped",[8706]],[[120656,120656],"mapped",[949]],[[120657,120657],"mapped",[952]],[[120658,120658],"mapped",[954]],[[120659,120659],"mapped",[966]],[[120660,120660],"mapped",[961]],[[120661,120661],"mapped",[960]],[[120662,120662],"mapped",[945]],[[120663,120663],"mapped",[946]],[[120664,120664],"mapped",[947]],[[120665,120665],"mapped",[948]],[[120666,120666],"mapped",[949]],[[120667,120667],"mapped",[950]],[[120668,120668],"mapped",[951]],[[120669,120669],"mapped",[952]],[[120670,120670],"mapped",[953]],[[120671,120671],"mapped",[954]],[[120672,120672],"mapped",[955]],[[120673,120673],"mapped",[956]],[[120674,120674],"mapped",[957]],[[120675,120675],"mapped",[958]],[[120676,120676],"mapped",[959]],[[120677,120677],"mapped",[960]],[[120678,120678],"mapped",[961]],[[120679,120679],"mapped",[952]],[[120680,120680],"mapped",[963]],[[120681,120681],"mapped",[964]],[[120682,120682],"mapped",[965]],[[120683,120683],"mapped",[966]],[[120684,120684],"mapped",[967]],[[120685,120685],"mapped",[968]],[[120686,120686],"mapped",[969]],[[120687,120687],"mapped",[8711]],[[120688,120688],"mapped",[945]],[[120689,120689],"mapped",[946]],[[120690,120690],"mapped",[947]],[[120691,120691],"mapped",[948]],[[120692,120692],"mapped",[949]],[[120693,120693],"mapped",[950]],[[120694,120694],"mapped",[951]],[[120695,120695],"mapped",[952]],[[120696,120696],"mapped",[953]],[[120697,120697],"mapped",[954]],[[120698,120698],"mapped",[955]],[[120699,120699],"mapped",[956]],[[120700,120700],"mapped",[957]],[[120701,120701],"mapped",[958]],[[120702,120702],"mapped",[959]],[[120703,120703],"mapped",[960]],[[120704,120704],"mapped",[961]],[[120705,120706],"mapped",[963]],[[120707,120707],"mapped",[964]],[[120708,120708],"mapped",[965]],[[120709,120709],"mapped",[966]],[[120710,120710],"mapped",[967]],[[120711,120711],"mapped",[968]],[[120712,120712],"mapped",[969]],[[120713,120713],"mapped",[8706]],[[120714,120714],"mapped",[949]],[[120715,120715],"mapped",[952]],[[120716,120716],"mapped",[954]],[[120717,120717],"mapped",[966]],[[120718,120718],"mapped",[961]],[[120719,120719],"mapped",[960]],[[120720,120720],"mapped",[945]],[[120721,120721],"mapped",[946]],[[120722,120722],"mapped",[947]],[[120723,120723],"mapped",[948]],[[120724,120724],"mapped",[949]],[[120725,120725],"mapped",[950]],[[120726,120726],"mapped",[951]],[[120727,120727],"mapped",[952]],[[120728,120728],"mapped",[953]],[[120729,120729],"mapped",[954]],[[120730,120730],"mapped",[955]],[[120731,120731],"mapped",[956]],[[120732,120732],"mapped",[957]],[[120733,120733],"mapped",[958]],[[120734,120734],"mapped",[959]],[[120735,120735],"mapped",[960]],[[120736,120736],"mapped",[961]],[[120737,120737],"mapped",[952]],[[120738,120738],"mapped",[963]],[[120739,120739],"mapped",[964]],[[120740,120740],"mapped",[965]],[[120741,120741],"mapped",[966]],[[120742,120742],"mapped",[967]],[[120743,120743],"mapped",[968]],[[120744,120744],"mapped",[969]],[[120745,120745],"mapped",[8711]],[[120746,120746],"mapped",[945]],[[120747,120747],"mapped",[946]],[[120748,120748],"mapped",[947]],[[120749,120749],"mapped",[948]],[[120750,120750],"mapped",[949]],[[120751,120751],"mapped",[950]],[[120752,120752],"mapped",[951]],[[120753,120753],"mapped",[952]],[[120754,120754],"mapped",[953]],[[120755,120755],"mapped",[954]],[[120756,120756],"mapped",[955]],[[120757,120757],"mapped",[956]],[[120758,120758],"mapped",[957]],[[120759,120759],"mapped",[958]],[[120760,120760],"mapped",[959]],[[120761,120761],"mapped",[960]],[[120762,120762],"mapped",[961]],[[120763,120764],"mapped",[963]],[[120765,120765],"mapped",[964]],[[120766,120766],"mapped",[965]],[[120767,120767],"mapped",[966]],[[120768,120768],"mapped",[967]],[[120769,120769],"mapped",[968]],[[120770,120770],"mapped",[969]],[[120771,120771],"mapped",[8706]],[[120772,120772],"mapped",[949]],[[120773,120773],"mapped",[952]],[[120774,120774],"mapped",[954]],[[120775,120775],"mapped",[966]],[[120776,120776],"mapped",[961]],[[120777,120777],"mapped",[960]],[[120778,120779],"mapped",[989]],[[120780,120781],"disallowed"],[[120782,120782],"mapped",[48]],[[120783,120783],"mapped",[49]],[[120784,120784],"mapped",[50]],[[120785,120785],"mapped",[51]],[[120786,120786],"mapped",[52]],[[120787,120787],"mapped",[53]],[[120788,120788],"mapped",[54]],[[120789,120789],"mapped",[55]],[[120790,120790],"mapped",[56]],[[120791,120791],"mapped",[57]],[[120792,120792],"mapped",[48]],[[120793,120793],"mapped",[49]],[[120794,120794],"mapped",[50]],[[120795,120795],"mapped",[51]],[[120796,120796],"mapped",[52]],[[120797,120797],"mapped",[53]],[[120798,120798],"mapped",[54]],[[120799,120799],"mapped",[55]],[[120800,120800],"mapped",[56]],[[120801,120801],"mapped",[57]],[[120802,120802],"mapped",[48]],[[120803,120803],"mapped",[49]],[[120804,120804],"mapped",[50]],[[120805,120805],"mapped",[51]],[[120806,120806],"mapped",[52]],[[120807,120807],"mapped",[53]],[[120808,120808],"mapped",[54]],[[120809,120809],"mapped",[55]],[[120810,120810],"mapped",[56]],[[120811,120811],"mapped",[57]],[[120812,120812],"mapped",[48]],[[120813,120813],"mapped",[49]],[[120814,120814],"mapped",[50]],[[120815,120815],"mapped",[51]],[[120816,120816],"mapped",[52]],[[120817,120817],"mapped",[53]],[[120818,120818],"mapped",[54]],[[120819,120819],"mapped",[55]],[[120820,120820],"mapped",[56]],[[120821,120821],"mapped",[57]],[[120822,120822],"mapped",[48]],[[120823,120823],"mapped",[49]],[[120824,120824],"mapped",[50]],[[120825,120825],"mapped",[51]],[[120826,120826],"mapped",[52]],[[120827,120827],"mapped",[53]],[[120828,120828],"mapped",[54]],[[120829,120829],"mapped",[55]],[[120830,120830],"mapped",[56]],[[120831,120831],"mapped",[57]],[[120832,121343],"valid",[],"NV8"],[[121344,121398],"valid"],[[121399,121402],"valid",[],"NV8"],[[121403,121452],"valid"],[[121453,121460],"valid",[],"NV8"],[[121461,121461],"valid"],[[121462,121475],"valid",[],"NV8"],[[121476,121476],"valid"],[[121477,121483],"valid",[],"NV8"],[[121484,121498],"disallowed"],[[121499,121503],"valid"],[[121504,121504],"disallowed"],[[121505,121519],"valid"],[[121520,124927],"disallowed"],[[124928,125124],"valid"],[[125125,125126],"disallowed"],[[125127,125135],"valid",[],"NV8"],[[125136,125142],"valid"],[[125143,126463],"disallowed"],[[126464,126464],"mapped",[1575]],[[126465,126465],"mapped",[1576]],[[126466,126466],"mapped",[1580]],[[126467,126467],"mapped",[1583]],[[126468,126468],"disallowed"],[[126469,126469],"mapped",[1608]],[[126470,126470],"mapped",[1586]],[[126471,126471],"mapped",[1581]],[[126472,126472],"mapped",[1591]],[[126473,126473],"mapped",[1610]],[[126474,126474],"mapped",[1603]],[[126475,126475],"mapped",[1604]],[[126476,126476],"mapped",[1605]],[[126477,126477],"mapped",[1606]],[[126478,126478],"mapped",[1587]],[[126479,126479],"mapped",[1593]],[[126480,126480],"mapped",[1601]],[[126481,126481],"mapped",[1589]],[[126482,126482],"mapped",[1602]],[[126483,126483],"mapped",[1585]],[[126484,126484],"mapped",[1588]],[[126485,126485],"mapped",[1578]],[[126486,126486],"mapped",[1579]],[[126487,126487],"mapped",[1582]],[[126488,126488],"mapped",[1584]],[[126489,126489],"mapped",[1590]],[[126490,126490],"mapped",[1592]],[[126491,126491],"mapped",[1594]],[[126492,126492],"mapped",[1646]],[[126493,126493],"mapped",[1722]],[[126494,126494],"mapped",[1697]],[[126495,126495],"mapped",[1647]],[[126496,126496],"disallowed"],[[126497,126497],"mapped",[1576]],[[126498,126498],"mapped",[1580]],[[126499,126499],"disallowed"],[[126500,126500],"mapped",[1607]],[[126501,126502],"disallowed"],[[126503,126503],"mapped",[1581]],[[126504,126504],"disallowed"],[[126505,126505],"mapped",[1610]],[[126506,126506],"mapped",[1603]],[[126507,126507],"mapped",[1604]],[[126508,126508],"mapped",[1605]],[[126509,126509],"mapped",[1606]],[[126510,126510],"mapped",[1587]],[[126511,126511],"mapped",[1593]],[[126512,126512],"mapped",[1601]],[[126513,126513],"mapped",[1589]],[[126514,126514],"mapped",[1602]],[[126515,126515],"disallowed"],[[126516,126516],"mapped",[1588]],[[126517,126517],"mapped",[1578]],[[126518,126518],"mapped",[1579]],[[126519,126519],"mapped",[1582]],[[126520,126520],"disallowed"],[[126521,126521],"mapped",[1590]],[[126522,126522],"disallowed"],[[126523,126523],"mapped",[1594]],[[126524,126529],"disallowed"],[[126530,126530],"mapped",[1580]],[[126531,126534],"disallowed"],[[126535,126535],"mapped",[1581]],[[126536,126536],"disallowed"],[[126537,126537],"mapped",[1610]],[[126538,126538],"disallowed"],[[126539,126539],"mapped",[1604]],[[126540,126540],"disallowed"],[[126541,126541],"mapped",[1606]],[[126542,126542],"mapped",[1587]],[[126543,126543],"mapped",[1593]],[[126544,126544],"disallowed"],[[126545,126545],"mapped",[1589]],[[126546,126546],"mapped",[1602]],[[126547,126547],"disallowed"],[[126548,126548],"mapped",[1588]],[[126549,126550],"disallowed"],[[126551,126551],"mapped",[1582]],[[126552,126552],"disallowed"],[[126553,126553],"mapped",[1590]],[[126554,126554],"disallowed"],[[126555,126555],"mapped",[1594]],[[126556,126556],"disallowed"],[[126557,126557],"mapped",[1722]],[[126558,126558],"disallowed"],[[126559,126559],"mapped",[1647]],[[126560,126560],"disallowed"],[[126561,126561],"mapped",[1576]],[[126562,126562],"mapped",[1580]],[[126563,126563],"disallowed"],[[126564,126564],"mapped",[1607]],[[126565,126566],"disallowed"],[[126567,126567],"mapped",[1581]],[[126568,126568],"mapped",[1591]],[[126569,126569],"mapped",[1610]],[[126570,126570],"mapped",[1603]],[[126571,126571],"disallowed"],[[126572,126572],"mapped",[1605]],[[126573,126573],"mapped",[1606]],[[126574,126574],"mapped",[1587]],[[126575,126575],"mapped",[1593]],[[126576,126576],"mapped",[1601]],[[126577,126577],"mapped",[1589]],[[126578,126578],"mapped",[1602]],[[126579,126579],"disallowed"],[[126580,126580],"mapped",[1588]],[[126581,126581],"mapped",[1578]],[[126582,126582],"mapped",[1579]],[[126583,126583],"mapped",[1582]],[[126584,126584],"disallowed"],[[126585,126585],"mapped",[1590]],[[126586,126586],"mapped",[1592]],[[126587,126587],"mapped",[1594]],[[126588,126588],"mapped",[1646]],[[126589,126589],"disallowed"],[[126590,126590],"mapped",[1697]],[[126591,126591],"disallowed"],[[126592,126592],"mapped",[1575]],[[126593,126593],"mapped",[1576]],[[126594,126594],"mapped",[1580]],[[126595,126595],"mapped",[1583]],[[126596,126596],"mapped",[1607]],[[126597,126597],"mapped",[1608]],[[126598,126598],"mapped",[1586]],[[126599,126599],"mapped",[1581]],[[126600,126600],"mapped",[1591]],[[126601,126601],"mapped",[1610]],[[126602,126602],"disallowed"],[[126603,126603],"mapped",[1604]],[[126604,126604],"mapped",[1605]],[[126605,126605],"mapped",[1606]],[[126606,126606],"mapped",[1587]],[[126607,126607],"mapped",[1593]],[[126608,126608],"mapped",[1601]],[[126609,126609],"mapped",[1589]],[[126610,126610],"mapped",[1602]],[[126611,126611],"mapped",[1585]],[[126612,126612],"mapped",[1588]],[[126613,126613],"mapped",[1578]],[[126614,126614],"mapped",[1579]],[[126615,126615],"mapped",[1582]],[[126616,126616],"mapped",[1584]],[[126617,126617],"mapped",[1590]],[[126618,126618],"mapped",[1592]],[[126619,126619],"mapped",[1594]],[[126620,126624],"disallowed"],[[126625,126625],"mapped",[1576]],[[126626,126626],"mapped",[1580]],[[126627,126627],"mapped",[1583]],[[126628,126628],"disallowed"],[[126629,126629],"mapped",[1608]],[[126630,126630],"mapped",[1586]],[[126631,126631],"mapped",[1581]],[[126632,126632],"mapped",[1591]],[[126633,126633],"mapped",[1610]],[[126634,126634],"disallowed"],[[126635,126635],"mapped",[1604]],[[126636,126636],"mapped",[1605]],[[126637,126637],"mapped",[1606]],[[126638,126638],"mapped",[1587]],[[126639,126639],"mapped",[1593]],[[126640,126640],"mapped",[1601]],[[126641,126641],"mapped",[1589]],[[126642,126642],"mapped",[1602]],[[126643,126643],"mapped",[1585]],[[126644,126644],"mapped",[1588]],[[126645,126645],"mapped",[1578]],[[126646,126646],"mapped",[1579]],[[126647,126647],"mapped",[1582]],[[126648,126648],"mapped",[1584]],[[126649,126649],"mapped",[1590]],[[126650,126650],"mapped",[1592]],[[126651,126651],"mapped",[1594]],[[126652,126703],"disallowed"],[[126704,126705],"valid",[],"NV8"],[[126706,126975],"disallowed"],[[126976,127019],"valid",[],"NV8"],[[127020,127023],"disallowed"],[[127024,127123],"valid",[],"NV8"],[[127124,127135],"disallowed"],[[127136,127150],"valid",[],"NV8"],[[127151,127152],"disallowed"],[[127153,127166],"valid",[],"NV8"],[[127167,127167],"valid",[],"NV8"],[[127168,127168],"disallowed"],[[127169,127183],"valid",[],"NV8"],[[127184,127184],"disallowed"],[[127185,127199],"valid",[],"NV8"],[[127200,127221],"valid",[],"NV8"],[[127222,127231],"disallowed"],[[127232,127232],"disallowed"],[[127233,127233],"disallowed_STD3_mapped",[48,44]],[[127234,127234],"disallowed_STD3_mapped",[49,44]],[[127235,127235],"disallowed_STD3_mapped",[50,44]],[[127236,127236],"disallowed_STD3_mapped",[51,44]],[[127237,127237],"disallowed_STD3_mapped",[52,44]],[[127238,127238],"disallowed_STD3_mapped",[53,44]],[[127239,127239],"disallowed_STD3_mapped",[54,44]],[[127240,127240],"disallowed_STD3_mapped",[55,44]],[[127241,127241],"disallowed_STD3_mapped",[56,44]],[[127242,127242],"disallowed_STD3_mapped",[57,44]],[[127243,127244],"valid",[],"NV8"],[[127245,127247],"disallowed"],[[127248,127248],"disallowed_STD3_mapped",[40,97,41]],[[127249,127249],"disallowed_STD3_mapped",[40,98,41]],[[127250,127250],"disallowed_STD3_mapped",[40,99,41]],[[127251,127251],"disallowed_STD3_mapped",[40,100,41]],[[127252,127252],"disallowed_STD3_mapped",[40,101,41]],[[127253,127253],"disallowed_STD3_mapped",[40,102,41]],[[127254,127254],"disallowed_STD3_mapped",[40,103,41]],[[127255,127255],"disallowed_STD3_mapped",[40,104,41]],[[127256,127256],"disallowed_STD3_mapped",[40,105,41]],[[127257,127257],"disallowed_STD3_mapped",[40,106,41]],[[127258,127258],"disallowed_STD3_mapped",[40,107,41]],[[127259,127259],"disallowed_STD3_mapped",[40,108,41]],[[127260,127260],"disallowed_STD3_mapped",[40,109,41]],[[127261,127261],"disallowed_STD3_mapped",[40,110,41]],[[127262,127262],"disallowed_STD3_mapped",[40,111,41]],[[127263,127263],"disallowed_STD3_mapped",[40,112,41]],[[127264,127264],"disallowed_STD3_mapped",[40,113,41]],[[127265,127265],"disallowed_STD3_mapped",[40,114,41]],[[127266,127266],"disallowed_STD3_mapped",[40,115,41]],[[127267,127267],"disallowed_STD3_mapped",[40,116,41]],[[127268,127268],"disallowed_STD3_mapped",[40,117,41]],[[127269,127269],"disallowed_STD3_mapped",[40,118,41]],[[127270,127270],"disallowed_STD3_mapped",[40,119,41]],[[127271,127271],"disallowed_STD3_mapped",[40,120,41]],[[127272,127272],"disallowed_STD3_mapped",[40,121,41]],[[127273,127273],"disallowed_STD3_mapped",[40,122,41]],[[127274,127274],"mapped",[12308,115,12309]],[[127275,127275],"mapped",[99]],[[127276,127276],"mapped",[114]],[[127277,127277],"mapped",[99,100]],[[127278,127278],"mapped",[119,122]],[[127279,127279],"disallowed"],[[127280,127280],"mapped",[97]],[[127281,127281],"mapped",[98]],[[127282,127282],"mapped",[99]],[[127283,127283],"mapped",[100]],[[127284,127284],"mapped",[101]],[[127285,127285],"mapped",[102]],[[127286,127286],"mapped",[103]],[[127287,127287],"mapped",[104]],[[127288,127288],"mapped",[105]],[[127289,127289],"mapped",[106]],[[127290,127290],"mapped",[107]],[[127291,127291],"mapped",[108]],[[127292,127292],"mapped",[109]],[[127293,127293],"mapped",[110]],[[127294,127294],"mapped",[111]],[[127295,127295],"mapped",[112]],[[127296,127296],"mapped",[113]],[[127297,127297],"mapped",[114]],[[127298,127298],"mapped",[115]],[[127299,127299],"mapped",[116]],[[127300,127300],"mapped",[117]],[[127301,127301],"mapped",[118]],[[127302,127302],"mapped",[119]],[[127303,127303],"mapped",[120]],[[127304,127304],"mapped",[121]],[[127305,127305],"mapped",[122]],[[127306,127306],"mapped",[104,118]],[[127307,127307],"mapped",[109,118]],[[127308,127308],"mapped",[115,100]],[[127309,127309],"mapped",[115,115]],[[127310,127310],"mapped",[112,112,118]],[[127311,127311],"mapped",[119,99]],[[127312,127318],"valid",[],"NV8"],[[127319,127319],"valid",[],"NV8"],[[127320,127326],"valid",[],"NV8"],[[127327,127327],"valid",[],"NV8"],[[127328,127337],"valid",[],"NV8"],[[127338,127338],"mapped",[109,99]],[[127339,127339],"mapped",[109,100]],[[127340,127343],"disallowed"],[[127344,127352],"valid",[],"NV8"],[[127353,127353],"valid",[],"NV8"],[[127354,127354],"valid",[],"NV8"],[[127355,127356],"valid",[],"NV8"],[[127357,127358],"valid",[],"NV8"],[[127359,127359],"valid",[],"NV8"],[[127360,127369],"valid",[],"NV8"],[[127370,127373],"valid",[],"NV8"],[[127374,127375],"valid",[],"NV8"],[[127376,127376],"mapped",[100,106]],[[127377,127386],"valid",[],"NV8"],[[127387,127461],"disallowed"],[[127462,127487],"valid",[],"NV8"],[[127488,127488],"mapped",[12411,12363]],[[127489,127489],"mapped",[12467,12467]],[[127490,127490],"mapped",[12469]],[[127491,127503],"disallowed"],[[127504,127504],"mapped",[25163]],[[127505,127505],"mapped",[23383]],[[127506,127506],"mapped",[21452]],[[127507,127507],"mapped",[12487]],[[127508,127508],"mapped",[20108]],[[127509,127509],"mapped",[22810]],[[127510,127510],"mapped",[35299]],[[127511,127511],"mapped",[22825]],[[127512,127512],"mapped",[20132]],[[127513,127513],"mapped",[26144]],[[127514,127514],"mapped",[28961]],[[127515,127515],"mapped",[26009]],[[127516,127516],"mapped",[21069]],[[127517,127517],"mapped",[24460]],[[127518,127518],"mapped",[20877]],[[127519,127519],"mapped",[26032]],[[127520,127520],"mapped",[21021]],[[127521,127521],"mapped",[32066]],[[127522,127522],"mapped",[29983]],[[127523,127523],"mapped",[36009]],[[127524,127524],"mapped",[22768]],[[127525,127525],"mapped",[21561]],[[127526,127526],"mapped",[28436]],[[127527,127527],"mapped",[25237]],[[127528,127528],"mapped",[25429]],[[127529,127529],"mapped",[19968]],[[127530,127530],"mapped",[19977]],[[127531,127531],"mapped",[36938]],[[127532,127532],"mapped",[24038]],[[127533,127533],"mapped",[20013]],[[127534,127534],"mapped",[21491]],[[127535,127535],"mapped",[25351]],[[127536,127536],"mapped",[36208]],[[127537,127537],"mapped",[25171]],[[127538,127538],"mapped",[31105]],[[127539,127539],"mapped",[31354]],[[127540,127540],"mapped",[21512]],[[127541,127541],"mapped",[28288]],[[127542,127542],"mapped",[26377]],[[127543,127543],"mapped",[26376]],[[127544,127544],"mapped",[30003]],[[127545,127545],"mapped",[21106]],[[127546,127546],"mapped",[21942]],[[127547,127551],"disallowed"],[[127552,127552],"mapped",[12308,26412,12309]],[[127553,127553],"mapped",[12308,19977,12309]],[[127554,127554],"mapped",[12308,20108,12309]],[[127555,127555],"mapped",[12308,23433,12309]],[[127556,127556],"mapped",[12308,28857,12309]],[[127557,127557],"mapped",[12308,25171,12309]],[[127558,127558],"mapped",[12308,30423,12309]],[[127559,127559],"mapped",[12308,21213,12309]],[[127560,127560],"mapped",[12308,25943,12309]],[[127561,127567],"disallowed"],[[127568,127568],"mapped",[24471]],[[127569,127569],"mapped",[21487]],[[127570,127743],"disallowed"],[[127744,127776],"valid",[],"NV8"],[[127777,127788],"valid",[],"NV8"],[[127789,127791],"valid",[],"NV8"],[[127792,127797],"valid",[],"NV8"],[[127798,127798],"valid",[],"NV8"],[[127799,127868],"valid",[],"NV8"],[[127869,127869],"valid",[],"NV8"],[[127870,127871],"valid",[],"NV8"],[[127872,127891],"valid",[],"NV8"],[[127892,127903],"valid",[],"NV8"],[[127904,127940],"valid",[],"NV8"],[[127941,127941],"valid",[],"NV8"],[[127942,127946],"valid",[],"NV8"],[[127947,127950],"valid",[],"NV8"],[[127951,127955],"valid",[],"NV8"],[[127956,127967],"valid",[],"NV8"],[[127968,127984],"valid",[],"NV8"],[[127985,127991],"valid",[],"NV8"],[[127992,127999],"valid",[],"NV8"],[[128000,128062],"valid",[],"NV8"],[[128063,128063],"valid",[],"NV8"],[[128064,128064],"valid",[],"NV8"],[[128065,128065],"valid",[],"NV8"],[[128066,128247],"valid",[],"NV8"],[[128248,128248],"valid",[],"NV8"],[[128249,128252],"valid",[],"NV8"],[[128253,128254],"valid",[],"NV8"],[[128255,128255],"valid",[],"NV8"],[[128256,128317],"valid",[],"NV8"],[[128318,128319],"valid",[],"NV8"],[[128320,128323],"valid",[],"NV8"],[[128324,128330],"valid",[],"NV8"],[[128331,128335],"valid",[],"NV8"],[[128336,128359],"valid",[],"NV8"],[[128360,128377],"valid",[],"NV8"],[[128378,128378],"disallowed"],[[128379,128419],"valid",[],"NV8"],[[128420,128420],"disallowed"],[[128421,128506],"valid",[],"NV8"],[[128507,128511],"valid",[],"NV8"],[[128512,128512],"valid",[],"NV8"],[[128513,128528],"valid",[],"NV8"],[[128529,128529],"valid",[],"NV8"],[[128530,128532],"valid",[],"NV8"],[[128533,128533],"valid",[],"NV8"],[[128534,128534],"valid",[],"NV8"],[[128535,128535],"valid",[],"NV8"],[[128536,128536],"valid",[],"NV8"],[[128537,128537],"valid",[],"NV8"],[[128538,128538],"valid",[],"NV8"],[[128539,128539],"valid",[],"NV8"],[[128540,128542],"valid",[],"NV8"],[[128543,128543],"valid",[],"NV8"],[[128544,128549],"valid",[],"NV8"],[[128550,128551],"valid",[],"NV8"],[[128552,128555],"valid",[],"NV8"],[[128556,128556],"valid",[],"NV8"],[[128557,128557],"valid",[],"NV8"],[[128558,128559],"valid",[],"NV8"],[[128560,128563],"valid",[],"NV8"],[[128564,128564],"valid",[],"NV8"],[[128565,128576],"valid",[],"NV8"],[[128577,128578],"valid",[],"NV8"],[[128579,128580],"valid",[],"NV8"],[[128581,128591],"valid",[],"NV8"],[[128592,128639],"valid",[],"NV8"],[[128640,128709],"valid",[],"NV8"],[[128710,128719],"valid",[],"NV8"],[[128720,128720],"valid",[],"NV8"],[[128721,128735],"disallowed"],[[128736,128748],"valid",[],"NV8"],[[128749,128751],"disallowed"],[[128752,128755],"valid",[],"NV8"],[[128756,128767],"disallowed"],[[128768,128883],"valid",[],"NV8"],[[128884,128895],"disallowed"],[[128896,128980],"valid",[],"NV8"],[[128981,129023],"disallowed"],[[129024,129035],"valid",[],"NV8"],[[129036,129039],"disallowed"],[[129040,129095],"valid",[],"NV8"],[[129096,129103],"disallowed"],[[129104,129113],"valid",[],"NV8"],[[129114,129119],"disallowed"],[[129120,129159],"valid",[],"NV8"],[[129160,129167],"disallowed"],[[129168,129197],"valid",[],"NV8"],[[129198,129295],"disallowed"],[[129296,129304],"valid",[],"NV8"],[[129305,129407],"disallowed"],[[129408,129412],"valid",[],"NV8"],[[129413,129471],"disallowed"],[[129472,129472],"valid",[],"NV8"],[[129473,131069],"disallowed"],[[131070,131071],"disallowed"],[[131072,173782],"valid"],[[173783,173823],"disallowed"],[[173824,177972],"valid"],[[177973,177983],"disallowed"],[[177984,178205],"valid"],[[178206,178207],"disallowed"],[[178208,183969],"valid"],[[183970,194559],"disallowed"],[[194560,194560],"mapped",[20029]],[[194561,194561],"mapped",[20024]],[[194562,194562],"mapped",[20033]],[[194563,194563],"mapped",[131362]],[[194564,194564],"mapped",[20320]],[[194565,194565],"mapped",[20398]],[[194566,194566],"mapped",[20411]],[[194567,194567],"mapped",[20482]],[[194568,194568],"mapped",[20602]],[[194569,194569],"mapped",[20633]],[[194570,194570],"mapped",[20711]],[[194571,194571],"mapped",[20687]],[[194572,194572],"mapped",[13470]],[[194573,194573],"mapped",[132666]],[[194574,194574],"mapped",[20813]],[[194575,194575],"mapped",[20820]],[[194576,194576],"mapped",[20836]],[[194577,194577],"mapped",[20855]],[[194578,194578],"mapped",[132380]],[[194579,194579],"mapped",[13497]],[[194580,194580],"mapped",[20839]],[[194581,194581],"mapped",[20877]],[[194582,194582],"mapped",[132427]],[[194583,194583],"mapped",[20887]],[[194584,194584],"mapped",[20900]],[[194585,194585],"mapped",[20172]],[[194586,194586],"mapped",[20908]],[[194587,194587],"mapped",[20917]],[[194588,194588],"mapped",[168415]],[[194589,194589],"mapped",[20981]],[[194590,194590],"mapped",[20995]],[[194591,194591],"mapped",[13535]],[[194592,194592],"mapped",[21051]],[[194593,194593],"mapped",[21062]],[[194594,194594],"mapped",[21106]],[[194595,194595],"mapped",[21111]],[[194596,194596],"mapped",[13589]],[[194597,194597],"mapped",[21191]],[[194598,194598],"mapped",[21193]],[[194599,194599],"mapped",[21220]],[[194600,194600],"mapped",[21242]],[[194601,194601],"mapped",[21253]],[[194602,194602],"mapped",[21254]],[[194603,194603],"mapped",[21271]],[[194604,194604],"mapped",[21321]],[[194605,194605],"mapped",[21329]],[[194606,194606],"mapped",[21338]],[[194607,194607],"mapped",[21363]],[[194608,194608],"mapped",[21373]],[[194609,194611],"mapped",[21375]],[[194612,194612],"mapped",[133676]],[[194613,194613],"mapped",[28784]],[[194614,194614],"mapped",[21450]],[[194615,194615],"mapped",[21471]],[[194616,194616],"mapped",[133987]],[[194617,194617],"mapped",[21483]],[[194618,194618],"mapped",[21489]],[[194619,194619],"mapped",[21510]],[[194620,194620],"mapped",[21662]],[[194621,194621],"mapped",[21560]],[[194622,194622],"mapped",[21576]],[[194623,194623],"mapped",[21608]],[[194624,194624],"mapped",[21666]],[[194625,194625],"mapped",[21750]],[[194626,194626],"mapped",[21776]],[[194627,194627],"mapped",[21843]],[[194628,194628],"mapped",[21859]],[[194629,194630],"mapped",[21892]],[[194631,194631],"mapped",[21913]],[[194632,194632],"mapped",[21931]],[[194633,194633],"mapped",[21939]],[[194634,194634],"mapped",[21954]],[[194635,194635],"mapped",[22294]],[[194636,194636],"mapped",[22022]],[[194637,194637],"mapped",[22295]],[[194638,194638],"mapped",[22097]],[[194639,194639],"mapped",[22132]],[[194640,194640],"mapped",[20999]],[[194641,194641],"mapped",[22766]],[[194642,194642],"mapped",[22478]],[[194643,194643],"mapped",[22516]],[[194644,194644],"mapped",[22541]],[[194645,194645],"mapped",[22411]],[[194646,194646],"mapped",[22578]],[[194647,194647],"mapped",[22577]],[[194648,194648],"mapped",[22700]],[[194649,194649],"mapped",[136420]],[[194650,194650],"mapped",[22770]],[[194651,194651],"mapped",[22775]],[[194652,194652],"mapped",[22790]],[[194653,194653],"mapped",[22810]],[[194654,194654],"mapped",[22818]],[[194655,194655],"mapped",[22882]],[[194656,194656],"mapped",[136872]],[[194657,194657],"mapped",[136938]],[[194658,194658],"mapped",[23020]],[[194659,194659],"mapped",[23067]],[[194660,194660],"mapped",[23079]],[[194661,194661],"mapped",[23000]],[[194662,194662],"mapped",[23142]],[[194663,194663],"mapped",[14062]],[[194664,194664],"disallowed"],[[194665,194665],"mapped",[23304]],[[194666,194667],"mapped",[23358]],[[194668,194668],"mapped",[137672]],[[194669,194669],"mapped",[23491]],[[194670,194670],"mapped",[23512]],[[194671,194671],"mapped",[23527]],[[194672,194672],"mapped",[23539]],[[194673,194673],"mapped",[138008]],[[194674,194674],"mapped",[23551]],[[194675,194675],"mapped",[23558]],[[194676,194676],"disallowed"],[[194677,194677],"mapped",[23586]],[[194678,194678],"mapped",[14209]],[[194679,194679],"mapped",[23648]],[[194680,194680],"mapped",[23662]],[[194681,194681],"mapped",[23744]],[[194682,194682],"mapped",[23693]],[[194683,194683],"mapped",[138724]],[[194684,194684],"mapped",[23875]],[[194685,194685],"mapped",[138726]],[[194686,194686],"mapped",[23918]],[[194687,194687],"mapped",[23915]],[[194688,194688],"mapped",[23932]],[[194689,194689],"mapped",[24033]],[[194690,194690],"mapped",[24034]],[[194691,194691],"mapped",[14383]],[[194692,194692],"mapped",[24061]],[[194693,194693],"mapped",[24104]],[[194694,194694],"mapped",[24125]],[[194695,194695],"mapped",[24169]],[[194696,194696],"mapped",[14434]],[[194697,194697],"mapped",[139651]],[[194698,194698],"mapped",[14460]],[[194699,194699],"mapped",[24240]],[[194700,194700],"mapped",[24243]],[[194701,194701],"mapped",[24246]],[[194702,194702],"mapped",[24266]],[[194703,194703],"mapped",[172946]],[[194704,194704],"mapped",[24318]],[[194705,194706],"mapped",[140081]],[[194707,194707],"mapped",[33281]],[[194708,194709],"mapped",[24354]],[[194710,194710],"mapped",[14535]],[[194711,194711],"mapped",[144056]],[[194712,194712],"mapped",[156122]],[[194713,194713],"mapped",[24418]],[[194714,194714],"mapped",[24427]],[[194715,194715],"mapped",[14563]],[[194716,194716],"mapped",[24474]],[[194717,194717],"mapped",[24525]],[[194718,194718],"mapped",[24535]],[[194719,194719],"mapped",[24569]],[[194720,194720],"mapped",[24705]],[[194721,194721],"mapped",[14650]],[[194722,194722],"mapped",[14620]],[[194723,194723],"mapped",[24724]],[[194724,194724],"mapped",[141012]],[[194725,194725],"mapped",[24775]],[[194726,194726],"mapped",[24904]],[[194727,194727],"mapped",[24908]],[[194728,194728],"mapped",[24910]],[[194729,194729],"mapped",[24908]],[[194730,194730],"mapped",[24954]],[[194731,194731],"mapped",[24974]],[[194732,194732],"mapped",[25010]],[[194733,194733],"mapped",[24996]],[[194734,194734],"mapped",[25007]],[[194735,194735],"mapped",[25054]],[[194736,194736],"mapped",[25074]],[[194737,194737],"mapped",[25078]],[[194738,194738],"mapped",[25104]],[[194739,194739],"mapped",[25115]],[[194740,194740],"mapped",[25181]],[[194741,194741],"mapped",[25265]],[[194742,194742],"mapped",[25300]],[[194743,194743],"mapped",[25424]],[[194744,194744],"mapped",[142092]],[[194745,194745],"mapped",[25405]],[[194746,194746],"mapped",[25340]],[[194747,194747],"mapped",[25448]],[[194748,194748],"mapped",[25475]],[[194749,194749],"mapped",[25572]],[[194750,194750],"mapped",[142321]],[[194751,194751],"mapped",[25634]],[[194752,194752],"mapped",[25541]],[[194753,194753],"mapped",[25513]],[[194754,194754],"mapped",[14894]],[[194755,194755],"mapped",[25705]],[[194756,194756],"mapped",[25726]],[[194757,194757],"mapped",[25757]],[[194758,194758],"mapped",[25719]],[[194759,194759],"mapped",[14956]],[[194760,194760],"mapped",[25935]],[[194761,194761],"mapped",[25964]],[[194762,194762],"mapped",[143370]],[[194763,194763],"mapped",[26083]],[[194764,194764],"mapped",[26360]],[[194765,194765],"mapped",[26185]],[[194766,194766],"mapped",[15129]],[[194767,194767],"mapped",[26257]],[[194768,194768],"mapped",[15112]],[[194769,194769],"mapped",[15076]],[[194770,194770],"mapped",[20882]],[[194771,194771],"mapped",[20885]],[[194772,194772],"mapped",[26368]],[[194773,194773],"mapped",[26268]],[[194774,194774],"mapped",[32941]],[[194775,194775],"mapped",[17369]],[[194776,194776],"mapped",[26391]],[[194777,194777],"mapped",[26395]],[[194778,194778],"mapped",[26401]],[[194779,194779],"mapped",[26462]],[[194780,194780],"mapped",[26451]],[[194781,194781],"mapped",[144323]],[[194782,194782],"mapped",[15177]],[[194783,194783],"mapped",[26618]],[[194784,194784],"mapped",[26501]],[[194785,194785],"mapped",[26706]],[[194786,194786],"mapped",[26757]],[[194787,194787],"mapped",[144493]],[[194788,194788],"mapped",[26766]],[[194789,194789],"mapped",[26655]],[[194790,194790],"mapped",[26900]],[[194791,194791],"mapped",[15261]],[[194792,194792],"mapped",[26946]],[[194793,194793],"mapped",[27043]],[[194794,194794],"mapped",[27114]],[[194795,194795],"mapped",[27304]],[[194796,194796],"mapped",[145059]],[[194797,194797],"mapped",[27355]],[[194798,194798],"mapped",[15384]],[[194799,194799],"mapped",[27425]],[[194800,194800],"mapped",[145575]],[[194801,194801],"mapped",[27476]],[[194802,194802],"mapped",[15438]],[[194803,194803],"mapped",[27506]],[[194804,194804],"mapped",[27551]],[[194805,194805],"mapped",[27578]],[[194806,194806],"mapped",[27579]],[[194807,194807],"mapped",[146061]],[[194808,194808],"mapped",[138507]],[[194809,194809],"mapped",[146170]],[[194810,194810],"mapped",[27726]],[[194811,194811],"mapped",[146620]],[[194812,194812],"mapped",[27839]],[[194813,194813],"mapped",[27853]],[[194814,194814],"mapped",[27751]],[[194815,194815],"mapped",[27926]],[[194816,194816],"mapped",[27966]],[[194817,194817],"mapped",[28023]],[[194818,194818],"mapped",[27969]],[[194819,194819],"mapped",[28009]],[[194820,194820],"mapped",[28024]],[[194821,194821],"mapped",[28037]],[[194822,194822],"mapped",[146718]],[[194823,194823],"mapped",[27956]],[[194824,194824],"mapped",[28207]],[[194825,194825],"mapped",[28270]],[[194826,194826],"mapped",[15667]],[[194827,194827],"mapped",[28363]],[[194828,194828],"mapped",[28359]],[[194829,194829],"mapped",[147153]],[[194830,194830],"mapped",[28153]],[[194831,194831],"mapped",[28526]],[[194832,194832],"mapped",[147294]],[[194833,194833],"mapped",[147342]],[[194834,194834],"mapped",[28614]],[[194835,194835],"mapped",[28729]],[[194836,194836],"mapped",[28702]],[[194837,194837],"mapped",[28699]],[[194838,194838],"mapped",[15766]],[[194839,194839],"mapped",[28746]],[[194840,194840],"mapped",[28797]],[[194841,194841],"mapped",[28791]],[[194842,194842],"mapped",[28845]],[[194843,194843],"mapped",[132389]],[[194844,194844],"mapped",[28997]],[[194845,194845],"mapped",[148067]],[[194846,194846],"mapped",[29084]],[[194847,194847],"disallowed"],[[194848,194848],"mapped",[29224]],[[194849,194849],"mapped",[29237]],[[194850,194850],"mapped",[29264]],[[194851,194851],"mapped",[149000]],[[194852,194852],"mapped",[29312]],[[194853,194853],"mapped",[29333]],[[194854,194854],"mapped",[149301]],[[194855,194855],"mapped",[149524]],[[194856,194856],"mapped",[29562]],[[194857,194857],"mapped",[29579]],[[194858,194858],"mapped",[16044]],[[194859,194859],"mapped",[29605]],[[194860,194861],"mapped",[16056]],[[194862,194862],"mapped",[29767]],[[194863,194863],"mapped",[29788]],[[194864,194864],"mapped",[29809]],[[194865,194865],"mapped",[29829]],[[194866,194866],"mapped",[29898]],[[194867,194867],"mapped",[16155]],[[194868,194868],"mapped",[29988]],[[194869,194869],"mapped",[150582]],[[194870,194870],"mapped",[30014]],[[194871,194871],"mapped",[150674]],[[194872,194872],"mapped",[30064]],[[194873,194873],"mapped",[139679]],[[194874,194874],"mapped",[30224]],[[194875,194875],"mapped",[151457]],[[194876,194876],"mapped",[151480]],[[194877,194877],"mapped",[151620]],[[194878,194878],"mapped",[16380]],[[194879,194879],"mapped",[16392]],[[194880,194880],"mapped",[30452]],[[194881,194881],"mapped",[151795]],[[194882,194882],"mapped",[151794]],[[194883,194883],"mapped",[151833]],[[194884,194884],"mapped",[151859]],[[194885,194885],"mapped",[30494]],[[194886,194887],"mapped",[30495]],[[194888,194888],"mapped",[30538]],[[194889,194889],"mapped",[16441]],[[194890,194890],"mapped",[30603]],[[194891,194891],"mapped",[16454]],[[194892,194892],"mapped",[16534]],[[194893,194893],"mapped",[152605]],[[194894,194894],"mapped",[30798]],[[194895,194895],"mapped",[30860]],[[194896,194896],"mapped",[30924]],[[194897,194897],"mapped",[16611]],[[194898,194898],"mapped",[153126]],[[194899,194899],"mapped",[31062]],[[194900,194900],"mapped",[153242]],[[194901,194901],"mapped",[153285]],[[194902,194902],"mapped",[31119]],[[194903,194903],"mapped",[31211]],[[194904,194904],"mapped",[16687]],[[194905,194905],"mapped",[31296]],[[194906,194906],"mapped",[31306]],[[194907,194907],"mapped",[31311]],[[194908,194908],"mapped",[153980]],[[194909,194910],"mapped",[154279]],[[194911,194911],"disallowed"],[[194912,194912],"mapped",[16898]],[[194913,194913],"mapped",[154539]],[[194914,194914],"mapped",[31686]],[[194915,194915],"mapped",[31689]],[[194916,194916],"mapped",[16935]],[[194917,194917],"mapped",[154752]],[[194918,194918],"mapped",[31954]],[[194919,194919],"mapped",[17056]],[[194920,194920],"mapped",[31976]],[[194921,194921],"mapped",[31971]],[[194922,194922],"mapped",[32000]],[[194923,194923],"mapped",[155526]],[[194924,194924],"mapped",[32099]],[[194925,194925],"mapped",[17153]],[[194926,194926],"mapped",[32199]],[[194927,194927],"mapped",[32258]],[[194928,194928],"mapped",[32325]],[[194929,194929],"mapped",[17204]],[[194930,194930],"mapped",[156200]],[[194931,194931],"mapped",[156231]],[[194932,194932],"mapped",[17241]],[[194933,194933],"mapped",[156377]],[[194934,194934],"mapped",[32634]],[[194935,194935],"mapped",[156478]],[[194936,194936],"mapped",[32661]],[[194937,194937],"mapped",[32762]],[[194938,194938],"mapped",[32773]],[[194939,194939],"mapped",[156890]],[[194940,194940],"mapped",[156963]],[[194941,194941],"mapped",[32864]],[[194942,194942],"mapped",[157096]],[[194943,194943],"mapped",[32880]],[[194944,194944],"mapped",[144223]],[[194945,194945],"mapped",[17365]],[[194946,194946],"mapped",[32946]],[[194947,194947],"mapped",[33027]],[[194948,194948],"mapped",[17419]],[[194949,194949],"mapped",[33086]],[[194950,194950],"mapped",[23221]],[[194951,194951],"mapped",[157607]],[[194952,194952],"mapped",[157621]],[[194953,194953],"mapped",[144275]],[[194954,194954],"mapped",[144284]],[[194955,194955],"mapped",[33281]],[[194956,194956],"mapped",[33284]],[[194957,194957],"mapped",[36766]],[[194958,194958],"mapped",[17515]],[[194959,194959],"mapped",[33425]],[[194960,194960],"mapped",[33419]],[[194961,194961],"mapped",[33437]],[[194962,194962],"mapped",[21171]],[[194963,194963],"mapped",[33457]],[[194964,194964],"mapped",[33459]],[[194965,194965],"mapped",[33469]],[[194966,194966],"mapped",[33510]],[[194967,194967],"mapped",[158524]],[[194968,194968],"mapped",[33509]],[[194969,194969],"mapped",[33565]],[[194970,194970],"mapped",[33635]],[[194971,194971],"mapped",[33709]],[[194972,194972],"mapped",[33571]],[[194973,194973],"mapped",[33725]],[[194974,194974],"mapped",[33767]],[[194975,194975],"mapped",[33879]],[[194976,194976],"mapped",[33619]],[[194977,194977],"mapped",[33738]],[[194978,194978],"mapped",[33740]],[[194979,194979],"mapped",[33756]],[[194980,194980],"mapped",[158774]],[[194981,194981],"mapped",[159083]],[[194982,194982],"mapped",[158933]],[[194983,194983],"mapped",[17707]],[[194984,194984],"mapped",[34033]],[[194985,194985],"mapped",[34035]],[[194986,194986],"mapped",[34070]],[[194987,194987],"mapped",[160714]],[[194988,194988],"mapped",[34148]],[[194989,194989],"mapped",[159532]],[[194990,194990],"mapped",[17757]],[[194991,194991],"mapped",[17761]],[[194992,194992],"mapped",[159665]],[[194993,194993],"mapped",[159954]],[[194994,194994],"mapped",[17771]],[[194995,194995],"mapped",[34384]],[[194996,194996],"mapped",[34396]],[[194997,194997],"mapped",[34407]],[[194998,194998],"mapped",[34409]],[[194999,194999],"mapped",[34473]],[[195000,195000],"mapped",[34440]],[[195001,195001],"mapped",[34574]],[[195002,195002],"mapped",[34530]],[[195003,195003],"mapped",[34681]],[[195004,195004],"mapped",[34600]],[[195005,195005],"mapped",[34667]],[[195006,195006],"mapped",[34694]],[[195007,195007],"disallowed"],[[195008,195008],"mapped",[34785]],[[195009,195009],"mapped",[34817]],[[195010,195010],"mapped",[17913]],[[195011,195011],"mapped",[34912]],[[195012,195012],"mapped",[34915]],[[195013,195013],"mapped",[161383]],[[195014,195014],"mapped",[35031]],[[195015,195015],"mapped",[35038]],[[195016,195016],"mapped",[17973]],[[195017,195017],"mapped",[35066]],[[195018,195018],"mapped",[13499]],[[195019,195019],"mapped",[161966]],[[195020,195020],"mapped",[162150]],[[195021,195021],"mapped",[18110]],[[195022,195022],"mapped",[18119]],[[195023,195023],"mapped",[35488]],[[195024,195024],"mapped",[35565]],[[195025,195025],"mapped",[35722]],[[195026,195026],"mapped",[35925]],[[195027,195027],"mapped",[162984]],[[195028,195028],"mapped",[36011]],[[195029,195029],"mapped",[36033]],[[195030,195030],"mapped",[36123]],[[195031,195031],"mapped",[36215]],[[195032,195032],"mapped",[163631]],[[195033,195033],"mapped",[133124]],[[195034,195034],"mapped",[36299]],[[195035,195035],"mapped",[36284]],[[195036,195036],"mapped",[36336]],[[195037,195037],"mapped",[133342]],[[195038,195038],"mapped",[36564]],[[195039,195039],"mapped",[36664]],[[195040,195040],"mapped",[165330]],[[195041,195041],"mapped",[165357]],[[195042,195042],"mapped",[37012]],[[195043,195043],"mapped",[37105]],[[195044,195044],"mapped",[37137]],[[195045,195045],"mapped",[165678]],[[195046,195046],"mapped",[37147]],[[195047,195047],"mapped",[37432]],[[195048,195048],"mapped",[37591]],[[195049,195049],"mapped",[37592]],[[195050,195050],"mapped",[37500]],[[195051,195051],"mapped",[37881]],[[195052,195052],"mapped",[37909]],[[195053,195053],"mapped",[166906]],[[195054,195054],"mapped",[38283]],[[195055,195055],"mapped",[18837]],[[195056,195056],"mapped",[38327]],[[195057,195057],"mapped",[167287]],[[195058,195058],"mapped",[18918]],[[195059,195059],"mapped",[38595]],[[195060,195060],"mapped",[23986]],[[195061,195061],"mapped",[38691]],[[195062,195062],"mapped",[168261]],[[195063,195063],"mapped",[168474]],[[195064,195064],"mapped",[19054]],[[195065,195065],"mapped",[19062]],[[195066,195066],"mapped",[38880]],[[195067,195067],"mapped",[168970]],[[195068,195068],"mapped",[19122]],[[195069,195069],"mapped",[169110]],[[195070,195071],"mapped",[38923]],[[195072,195072],"mapped",[38953]],[[195073,195073],"mapped",[169398]],[[195074,195074],"mapped",[39138]],[[195075,195075],"mapped",[19251]],[[195076,195076],"mapped",[39209]],[[195077,195077],"mapped",[39335]],[[195078,195078],"mapped",[39362]],[[195079,195079],"mapped",[39422]],[[195080,195080],"mapped",[19406]],[[195081,195081],"mapped",[170800]],[[195082,195082],"mapped",[39698]],[[195083,195083],"mapped",[40000]],[[195084,195084],"mapped",[40189]],[[195085,195085],"mapped",[19662]],[[195086,195086],"mapped",[19693]],[[195087,195087],"mapped",[40295]],[[195088,195088],"mapped",[172238]],[[195089,195089],"mapped",[19704]],[[195090,195090],"mapped",[172293]],[[195091,195091],"mapped",[172558]],[[195092,195092],"mapped",[172689]],[[195093,195093],"mapped",[40635]],[[195094,195094],"mapped",[19798]],[[195095,195095],"mapped",[40697]],[[195096,195096],"mapped",[40702]],[[195097,195097],"mapped",[40709]],[[195098,195098],"mapped",[40719]],[[195099,195099],"mapped",[40726]],[[195100,195100],"mapped",[40763]],[[195101,195101],"mapped",[173568]],[[195102,196605],"disallowed"],[[196606,196607],"disallowed"],[[196608,262141],"disallowed"],[[262142,262143],"disallowed"],[[262144,327677],"disallowed"],[[327678,327679],"disallowed"],[[327680,393213],"disallowed"],[[393214,393215],"disallowed"],[[393216,458749],"disallowed"],[[458750,458751],"disallowed"],[[458752,524285],"disallowed"],[[524286,524287],"disallowed"],[[524288,589821],"disallowed"],[[589822,589823],"disallowed"],[[589824,655357],"disallowed"],[[655358,655359],"disallowed"],[[655360,720893],"disallowed"],[[720894,720895],"disallowed"],[[720896,786429],"disallowed"],[[786430,786431],"disallowed"],[[786432,851965],"disallowed"],[[851966,851967],"disallowed"],[[851968,917501],"disallowed"],[[917502,917503],"disallowed"],[[917504,917504],"disallowed"],[[917505,917505],"disallowed"],[[917506,917535],"disallowed"],[[917536,917631],"disallowed"],[[917632,917759],"disallowed"],[[917760,917999],"ignored"],[[918000,983037],"disallowed"],[[983038,983039],"disallowed"],[[983040,1048573],"disallowed"],[[1048574,1048575],"disallowed"],[[1048576,1114109],"disallowed"],[[1114110,1114111],"disallowed"]] \ No newline at end of file diff --git a/backend/node_modules/tr46/package.json b/backend/node_modules/tr46/package.json new file mode 100644 index 0000000000000000000000000000000000000000..b6826da1f7817f97ad6d307d698ad2004807c40a --- /dev/null +++ b/backend/node_modules/tr46/package.json @@ -0,0 +1,31 @@ +{ + "name": "tr46", + "version": "0.0.3", + "description": "An implementation of the Unicode TR46 spec", + "main": "index.js", + "scripts": { + "test": "mocha", + "pretest": "node scripts/getLatestUnicodeTests.js", + "prepublish": "node scripts/generateMappingTable.js" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/Sebmaster/tr46.js.git" + }, + "keywords": [ + "unicode", + "tr46", + "url", + "whatwg" + ], + "author": "Sebastian Mayr ", + "license": "MIT", + "bugs": { + "url": "https://github.com/Sebmaster/tr46.js/issues" + }, + "homepage": "https://github.com/Sebmaster/tr46.js#readme", + "devDependencies": { + "mocha": "^2.2.5", + "request": "^2.57.0" + } +} diff --git a/backend/node_modules/type-is/HISTORY.md b/backend/node_modules/type-is/HISTORY.md new file mode 100644 index 0000000000000000000000000000000000000000..8de21f7ae6f8de94d8c8b00fbf8c3017247077ff --- /dev/null +++ b/backend/node_modules/type-is/HISTORY.md @@ -0,0 +1,259 @@ +1.6.18 / 2019-04-26 +=================== + + * Fix regression passing request object to `typeis.is` + +1.6.17 / 2019-04-25 +=================== + + * deps: mime-types@~2.1.24 + - Add Apple file extensions from IANA + - Add extension `.csl` to `application/vnd.citationstyles.style+xml` + - Add extension `.es` to `application/ecmascript` + - Add extension `.nq` to `application/n-quads` + - Add extension `.nt` to `application/n-triples` + - Add extension `.owl` to `application/rdf+xml` + - Add extensions `.siv` and `.sieve` to `application/sieve` + - Add extensions from IANA for `image/*` types + - Add extensions from IANA for `model/*` types + - Add extensions to HEIC image types + - Add new mime types + - Add `text/mdx` with extension `.mdx` + * perf: prevent internal `throw` on invalid type + +1.6.16 / 2018-02-16 +=================== + + * deps: mime-types@~2.1.18 + - Add `application/raml+yaml` with extension `.raml` + - Add `application/wasm` with extension `.wasm` + - Add `text/shex` with extension `.shex` + - Add extensions for JPEG-2000 images + - Add extensions from IANA for `message/*` types + - Add extension `.mjs` to `application/javascript` + - Add extension `.wadl` to `application/vnd.sun.wadl+xml` + - Add extension `.gz` to `application/gzip` + - Add glTF types and extensions + - Add new mime types + - Update extensions `.md` and `.markdown` to be `text/markdown` + - Update font MIME types + - Update `text/hjson` to registered `application/hjson` + +1.6.15 / 2017-03-31 +=================== + + * deps: mime-types@~2.1.15 + - Add new mime types + +1.6.14 / 2016-11-18 +=================== + + * deps: mime-types@~2.1.13 + - Add new mime types + +1.6.13 / 2016-05-18 +=================== + + * deps: mime-types@~2.1.11 + - Add new mime types + +1.6.12 / 2016-02-28 +=================== + + * deps: mime-types@~2.1.10 + - Add new mime types + - Fix extension of `application/dash+xml` + - Update primary extension for `audio/mp4` + +1.6.11 / 2016-01-29 +=================== + + * deps: mime-types@~2.1.9 + - Add new mime types + +1.6.10 / 2015-12-01 +=================== + + * deps: mime-types@~2.1.8 + - Add new mime types + +1.6.9 / 2015-09-27 +================== + + * deps: mime-types@~2.1.7 + - Add new mime types + +1.6.8 / 2015-09-04 +================== + + * deps: mime-types@~2.1.6 + - Add new mime types + +1.6.7 / 2015-08-20 +================== + + * Fix type error when given invalid type to match against + * deps: mime-types@~2.1.5 + - Add new mime types + +1.6.6 / 2015-07-31 +================== + + * deps: mime-types@~2.1.4 + - Add new mime types + +1.6.5 / 2015-07-16 +================== + + * deps: mime-types@~2.1.3 + - Add new mime types + +1.6.4 / 2015-07-01 +================== + + * deps: mime-types@~2.1.2 + - Add new mime types + * perf: enable strict mode + * perf: remove argument reassignment + +1.6.3 / 2015-06-08 +================== + + * deps: mime-types@~2.1.1 + - Add new mime types + * perf: reduce try block size + * perf: remove bitwise operations + +1.6.2 / 2015-05-10 +================== + + * deps: mime-types@~2.0.11 + - Add new mime types + +1.6.1 / 2015-03-13 +================== + + * deps: mime-types@~2.0.10 + - Add new mime types + +1.6.0 / 2015-02-12 +================== + + * fix false-positives in `hasBody` `Transfer-Encoding` check + * support wildcard for both type and subtype (`*/*`) + +1.5.7 / 2015-02-09 +================== + + * fix argument reassignment + * deps: mime-types@~2.0.9 + - Add new mime types + +1.5.6 / 2015-01-29 +================== + + * deps: mime-types@~2.0.8 + - Add new mime types + +1.5.5 / 2014-12-30 +================== + + * deps: mime-types@~2.0.7 + - Add new mime types + - Fix missing extensions + - Fix various invalid MIME type entries + - Remove example template MIME types + - deps: mime-db@~1.5.0 + +1.5.4 / 2014-12-10 +================== + + * deps: mime-types@~2.0.4 + - Add new mime types + - deps: mime-db@~1.3.0 + +1.5.3 / 2014-11-09 +================== + + * deps: mime-types@~2.0.3 + - Add new mime types + - deps: mime-db@~1.2.0 + +1.5.2 / 2014-09-28 +================== + + * deps: mime-types@~2.0.2 + - Add new mime types + - deps: mime-db@~1.1.0 + +1.5.1 / 2014-09-07 +================== + + * Support Node.js 0.6 + * deps: media-typer@0.3.0 + * deps: mime-types@~2.0.1 + - Support Node.js 0.6 + +1.5.0 / 2014-09-05 +================== + + * fix `hasbody` to be true for `content-length: 0` + +1.4.0 / 2014-09-02 +================== + + * update mime-types + +1.3.2 / 2014-06-24 +================== + + * use `~` range on mime-types + +1.3.1 / 2014-06-19 +================== + + * fix global variable leak + +1.3.0 / 2014-06-19 +================== + + * improve type parsing + + - invalid media type never matches + - media type not case-sensitive + - extra LWS does not affect results + +1.2.2 / 2014-06-19 +================== + + * fix behavior on unknown type argument + +1.2.1 / 2014-06-03 +================== + + * switch dependency from `mime` to `mime-types@1.0.0` + +1.2.0 / 2014-05-11 +================== + + * support suffix matching: + + - `+json` matches `application/vnd+json` + - `*/vnd+json` matches `application/vnd+json` + - `application/*+json` matches `application/vnd+json` + +1.1.0 / 2014-04-12 +================== + + * add non-array values support + * expose internal utilities: + + - `.is()` + - `.hasBody()` + - `.normalize()` + - `.match()` + +1.0.1 / 2014-03-30 +================== + + * add `multipart` as a shorthand diff --git a/backend/node_modules/type-is/LICENSE b/backend/node_modules/type-is/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..386b7b6946e47bc46f8138791049b4e6a7cef889 --- /dev/null +++ b/backend/node_modules/type-is/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/backend/node_modules/type-is/README.md b/backend/node_modules/type-is/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b85ef8f78ff14113fe26b3a04bf82c3d07f88a73 --- /dev/null +++ b/backend/node_modules/type-is/README.md @@ -0,0 +1,170 @@ +# type-is + +[![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][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Infer the content-type of a request. + +### Install + +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 type-is +``` + +## API + +```js +var http = require('http') +var typeis = require('type-is') + +http.createServer(function (req, res) { + var istext = typeis(req, ['text/*']) + res.end('you ' + (istext ? 'sent' : 'did not send') + ' me text') +}) +``` + +### typeis(request, types) + +Checks if the `request` is one of the `types`. If the request has no body, +even if there is a `Content-Type` header, then `null` is returned. If the +`Content-Type` header is invalid or does not matches any of the `types`, then +`false` is returned. Otherwise, a string of the type that matched is returned. + +The `request` argument is expected to be a Node.js HTTP request. The `types` +argument is an array of type strings. + +Each type in the `types` array can be one of the following: + +- A file extension name such as `json`. This name will be returned if matched. +- A mime type such as `application/json`. +- A mime type with a wildcard such as `*/*` or `*/json` or `application/*`. + The full mime type will be returned if matched. +- A suffix such as `+json`. This can be combined with a wildcard such as + `*/vnd+json` or `application/*+json`. The full mime type will be returned + if matched. + +Some examples to illustrate the inputs and returned value: + + + +```js +// req.headers.content-type = 'application/json' + +typeis(req, ['json']) // => 'json' +typeis(req, ['html', 'json']) // => 'json' +typeis(req, ['application/*']) // => 'application/json' +typeis(req, ['application/json']) // => 'application/json' + +typeis(req, ['html']) // => false +``` + +### typeis.hasBody(request) + +Returns a Boolean if the given `request` has a body, regardless of the +`Content-Type` header. + +Having a body has no relation to how large the body is (it may be 0 bytes). +This is similar to how file existence works. If a body does exist, then this +indicates that there is data to read from the Node.js request stream. + + + +```js +if (typeis.hasBody(req)) { + // read the body, since there is one + + req.on('data', function (chunk) { + // ... + }) +} +``` + +### typeis.is(mediaType, types) + +Checks if the `mediaType` is one of the `types`. If the `mediaType` is invalid +or does not matches any of the `types`, then `false` is returned. Otherwise, a +string of the type that matched is returned. + +The `mediaType` argument is expected to be a +[media type](https://tools.ietf.org/html/rfc6838) string. The `types` argument +is an array of type strings. + +Each type in the `types` array can be one of the following: + +- A file extension name such as `json`. This name will be returned if matched. +- A mime type such as `application/json`. +- A mime type with a wildcard such as `*/*` or `*/json` or `application/*`. + The full mime type will be returned if matched. +- A suffix such as `+json`. This can be combined with a wildcard such as + `*/vnd+json` or `application/*+json`. The full mime type will be returned + if matched. + +Some examples to illustrate the inputs and returned value: + + + +```js +var mediaType = 'application/json' + +typeis.is(mediaType, ['json']) // => 'json' +typeis.is(mediaType, ['html', 'json']) // => 'json' +typeis.is(mediaType, ['application/*']) // => 'application/json' +typeis.is(mediaType, ['application/json']) // => 'application/json' + +typeis.is(mediaType, ['html']) // => false +``` + +## Examples + +### Example body parser + +```js +var express = require('express') +var typeis = require('type-is') + +var app = express() + +app.use(function bodyParser (req, res, next) { + if (!typeis.hasBody(req)) { + return next() + } + + switch (typeis(req, ['urlencoded', 'json', 'multipart'])) { + case 'urlencoded': + // parse urlencoded body + throw new Error('implement urlencoded body parsing') + case 'json': + // parse json body + throw new Error('implement json body parsing') + case 'multipart': + // parse multipart body + throw new Error('implement multipart body parsing') + default: + // 415 error code + res.statusCode = 415 + res.end() + break + } +}) +``` + +## License + +[MIT](LICENSE) + +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/type-is/master +[coveralls-url]: https://coveralls.io/r/jshttp/type-is?branch=master +[node-version-image]: https://badgen.net/npm/node/type-is +[node-version-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/type-is +[npm-url]: https://npmjs.org/package/type-is +[npm-version-image]: https://badgen.net/npm/v/type-is +[travis-image]: https://badgen.net/travis/jshttp/type-is/master +[travis-url]: https://travis-ci.org/jshttp/type-is diff --git a/backend/node_modules/type-is/index.js b/backend/node_modules/type-is/index.js new file mode 100644 index 0000000000000000000000000000000000000000..890ad76c7eb990c75e4601becab263df961318fb --- /dev/null +++ b/backend/node_modules/type-is/index.js @@ -0,0 +1,266 @@ +/*! + * type-is + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var typer = require('media-typer') +var mime = require('mime-types') + +/** + * Module exports. + * @public + */ + +module.exports = typeofrequest +module.exports.is = typeis +module.exports.hasBody = hasbody +module.exports.normalize = normalize +module.exports.match = mimeMatch + +/** + * Compare a `value` content-type with `types`. + * Each `type` can be an extension like `html`, + * a special shortcut like `multipart` or `urlencoded`, + * or a mime type. + * + * If no types match, `false` is returned. + * Otherwise, the first `type` that matches is returned. + * + * @param {String} value + * @param {Array} types + * @public + */ + +function typeis (value, types_) { + var i + var types = types_ + + // remove parameters and normalize + var val = tryNormalizeType(value) + + // no type or invalid + if (!val) { + return false + } + + // support flattened arguments + if (types && !Array.isArray(types)) { + types = new Array(arguments.length - 1) + for (i = 0; i < types.length; i++) { + types[i] = arguments[i + 1] + } + } + + // no types, return the content type + if (!types || !types.length) { + return val + } + + var type + for (i = 0; i < types.length; i++) { + if (mimeMatch(normalize(type = types[i]), val)) { + return type[0] === '+' || type.indexOf('*') !== -1 + ? val + : type + } + } + + // no matches + return false +} + +/** + * Check if a request has a request body. + * A request with a body __must__ either have `transfer-encoding` + * or `content-length` headers set. + * http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.3 + * + * @param {Object} request + * @return {Boolean} + * @public + */ + +function hasbody (req) { + return req.headers['transfer-encoding'] !== undefined || + !isNaN(req.headers['content-length']) +} + +/** + * Check if the incoming request contains the "Content-Type" + * header field, and it contains any of the give mime `type`s. + * If there is no request body, `null` is returned. + * If there is no content type, `false` is returned. + * Otherwise, it returns the first `type` that matches. + * + * Examples: + * + * // With Content-Type: text/html; charset=utf-8 + * this.is('html'); // => 'html' + * this.is('text/html'); // => 'text/html' + * this.is('text/*', 'application/json'); // => 'text/html' + * + * // When Content-Type is application/json + * this.is('json', 'urlencoded'); // => 'json' + * this.is('application/json'); // => 'application/json' + * this.is('html', 'application/*'); // => 'application/json' + * + * this.is('html'); // => false + * + * @param {String|Array} types... + * @return {String|false|null} + * @public + */ + +function typeofrequest (req, types_) { + var types = types_ + + // no body + if (!hasbody(req)) { + return null + } + + // support flattened arguments + if (arguments.length > 2) { + types = new Array(arguments.length - 1) + for (var i = 0; i < types.length; i++) { + types[i] = arguments[i + 1] + } + } + + // request content type + var value = req.headers['content-type'] + + return typeis(value, types) +} + +/** + * Normalize a mime type. + * If it's a shorthand, expand it to a valid mime type. + * + * In general, you probably want: + * + * var type = is(req, ['urlencoded', 'json', 'multipart']); + * + * Then use the appropriate body parsers. + * These three are the most common request body types + * and are thus ensured to work. + * + * @param {String} type + * @private + */ + +function normalize (type) { + if (typeof type !== 'string') { + // invalid type + return false + } + + switch (type) { + case 'urlencoded': + return 'application/x-www-form-urlencoded' + case 'multipart': + return 'multipart/*' + } + + if (type[0] === '+') { + // "+json" -> "*/*+json" expando + return '*/*' + type + } + + return type.indexOf('/') === -1 + ? mime.lookup(type) + : type +} + +/** + * Check if `expected` mime type + * matches `actual` mime type with + * wildcard and +suffix support. + * + * @param {String} expected + * @param {String} actual + * @return {Boolean} + * @private + */ + +function mimeMatch (expected, actual) { + // invalid type + if (expected === false) { + return false + } + + // split types + var actualParts = actual.split('/') + var expectedParts = expected.split('/') + + // invalid format + if (actualParts.length !== 2 || expectedParts.length !== 2) { + return false + } + + // validate type + if (expectedParts[0] !== '*' && expectedParts[0] !== actualParts[0]) { + return false + } + + // validate suffix wildcard + if (expectedParts[1].substr(0, 2) === '*+') { + return expectedParts[1].length <= actualParts[1].length + 1 && + expectedParts[1].substr(1) === actualParts[1].substr(1 - expectedParts[1].length) + } + + // validate subtype + if (expectedParts[1] !== '*' && expectedParts[1] !== actualParts[1]) { + return false + } + + return true +} + +/** + * Normalize a type and remove parameters. + * + * @param {string} value + * @return {string} + * @private + */ + +function normalizeType (value) { + // parse the type + var type = typer.parse(value) + + // remove the parameters + type.parameters = undefined + + // reformat it + return typer.format(type) +} + +/** + * Try to normalize a type and remove parameters. + * + * @param {string} value + * @return {string} + * @private + */ + +function tryNormalizeType (value) { + if (!value) { + return null + } + + try { + return normalizeType(value) + } catch (err) { + return null + } +} diff --git a/backend/node_modules/type-is/package.json b/backend/node_modules/type-is/package.json new file mode 100644 index 0000000000000000000000000000000000000000..97ba5f14b84f4ea397e9795636d2285e77ce18cb --- /dev/null +++ b/backend/node_modules/type-is/package.json @@ -0,0 +1,45 @@ +{ + "name": "type-is", + "description": "Infer the content-type of a request.", + "version": "1.6.18", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)" + ], + "license": "MIT", + "repository": "jshttp/type-is", + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + }, + "devDependencies": { + "eslint": "5.16.0", + "eslint-config-standard": "12.0.0", + "eslint-plugin-import": "2.17.2", + "eslint-plugin-markdown": "1.0.0", + "eslint-plugin-node": "8.0.1", + "eslint-plugin-promise": "4.1.1", + "eslint-plugin-standard": "4.0.0", + "mocha": "6.1.4", + "nyc": "14.0.0" + }, + "engines": { + "node": ">= 0.6" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "index.js" + ], + "scripts": { + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec --check-leaks --bail test/", + "test-cov": "nyc --reporter=html --reporter=text npm test", + "test-travis": "nyc --reporter=text npm test" + }, + "keywords": [ + "content", + "type", + "checking" + ] +} diff --git a/backend/node_modules/typedarray/.travis.yml b/backend/node_modules/typedarray/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..cc4dba29d959a2da7b97f9edd3c7c91384b2ee5b --- /dev/null +++ b/backend/node_modules/typedarray/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - "0.8" + - "0.10" diff --git a/backend/node_modules/typedarray/LICENSE b/backend/node_modules/typedarray/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..11adfaec9e7f95f3eab1ecdd6f1f8715fcdc4311 --- /dev/null +++ b/backend/node_modules/typedarray/LICENSE @@ -0,0 +1,35 @@ +/* + Copyright (c) 2010, Linden Research, Inc. + Copyright (c) 2012, Joshua Bell + + 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. + $/LicenseInfo$ + */ + +// Original can be found at: +// https://bitbucket.org/lindenlab/llsd +// Modifications by Joshua Bell inexorabletash@gmail.com +// https://github.com/inexorabletash/polyfill + +// ES3/ES5 implementation of the Krhonos Typed Array Specification +// Ref: http://www.khronos.org/registry/typedarray/specs/latest/ +// Date: 2011-02-01 +// +// Variations: +// * Allows typed_array.get/set() as alias for subscripts (typed_array[]) diff --git a/backend/node_modules/typedarray/example/tarray.js b/backend/node_modules/typedarray/example/tarray.js new file mode 100644 index 0000000000000000000000000000000000000000..8423d7c9b1c327e5c76744eccf7ec469b3ffdd79 --- /dev/null +++ b/backend/node_modules/typedarray/example/tarray.js @@ -0,0 +1,4 @@ +var Uint8Array = require('../').Uint8Array; +var ua = new Uint8Array(5); +ua[1] = 256 + 55; +console.log(ua[1]); diff --git a/backend/node_modules/typedarray/index.js b/backend/node_modules/typedarray/index.js new file mode 100644 index 0000000000000000000000000000000000000000..5e540841f432413f874b4c75ffc7280f114c37eb --- /dev/null +++ b/backend/node_modules/typedarray/index.js @@ -0,0 +1,630 @@ +var undefined = (void 0); // Paranoia + +// Beyond this value, index getters/setters (i.e. array[0], array[1]) are so slow to +// create, and consume so much memory, that the browser appears frozen. +var MAX_ARRAY_LENGTH = 1e5; + +// Approximations of internal ECMAScript conversion functions +var ECMAScript = (function() { + // Stash a copy in case other scripts modify these + var opts = Object.prototype.toString, + ophop = Object.prototype.hasOwnProperty; + + return { + // Class returns internal [[Class]] property, used to avoid cross-frame instanceof issues: + Class: function(v) { return opts.call(v).replace(/^\[object *|\]$/g, ''); }, + HasProperty: function(o, p) { return p in o; }, + HasOwnProperty: function(o, p) { return ophop.call(o, p); }, + IsCallable: function(o) { return typeof o === 'function'; }, + ToInt32: function(v) { return v >> 0; }, + ToUint32: function(v) { return v >>> 0; } + }; +}()); + +// Snapshot intrinsics +var LN2 = Math.LN2, + abs = Math.abs, + floor = Math.floor, + log = Math.log, + min = Math.min, + pow = Math.pow, + round = Math.round; + +// ES5: lock down object properties +function configureProperties(obj) { + if (getOwnPropNames && defineProp) { + var props = getOwnPropNames(obj), i; + for (i = 0; i < props.length; i += 1) { + defineProp(obj, props[i], { + value: obj[props[i]], + writable: false, + enumerable: false, + configurable: false + }); + } + } +} + +// emulate ES5 getter/setter API using legacy APIs +// http://blogs.msdn.com/b/ie/archive/2010/09/07/transitioning-existing-code-to-the-es5-getter-setter-apis.aspx +// (second clause tests for Object.defineProperty() in IE<9 that only supports extending DOM prototypes, but +// note that IE<9 does not support __defineGetter__ or __defineSetter__ so it just renders the method harmless) +var defineProp +if (Object.defineProperty && (function() { + try { + Object.defineProperty({}, 'x', {}); + return true; + } catch (e) { + return false; + } + })()) { + defineProp = Object.defineProperty; +} else { + defineProp = function(o, p, desc) { + if (!o === Object(o)) throw new TypeError("Object.defineProperty called on non-object"); + if (ECMAScript.HasProperty(desc, 'get') && Object.prototype.__defineGetter__) { Object.prototype.__defineGetter__.call(o, p, desc.get); } + if (ECMAScript.HasProperty(desc, 'set') && Object.prototype.__defineSetter__) { Object.prototype.__defineSetter__.call(o, p, desc.set); } + if (ECMAScript.HasProperty(desc, 'value')) { o[p] = desc.value; } + return o; + }; +} + +var getOwnPropNames = Object.getOwnPropertyNames || function (o) { + if (o !== Object(o)) throw new TypeError("Object.getOwnPropertyNames called on non-object"); + var props = [], p; + for (p in o) { + if (ECMAScript.HasOwnProperty(o, p)) { + props.push(p); + } + } + return props; +}; + +// ES5: Make obj[index] an alias for obj._getter(index)/obj._setter(index, value) +// for index in 0 ... obj.length +function makeArrayAccessors(obj) { + if (!defineProp) { return; } + + if (obj.length > MAX_ARRAY_LENGTH) throw new RangeError("Array too large for polyfill"); + + function makeArrayAccessor(index) { + defineProp(obj, index, { + 'get': function() { return obj._getter(index); }, + 'set': function(v) { obj._setter(index, v); }, + enumerable: true, + configurable: false + }); + } + + var i; + for (i = 0; i < obj.length; i += 1) { + makeArrayAccessor(i); + } +} + +// Internal conversion functions: +// pack() - take a number (interpreted as Type), output a byte array +// unpack() - take a byte array, output a Type-like number + +function as_signed(value, bits) { var s = 32 - bits; return (value << s) >> s; } +function as_unsigned(value, bits) { var s = 32 - bits; return (value << s) >>> s; } + +function packI8(n) { return [n & 0xff]; } +function unpackI8(bytes) { return as_signed(bytes[0], 8); } + +function packU8(n) { return [n & 0xff]; } +function unpackU8(bytes) { return as_unsigned(bytes[0], 8); } + +function packU8Clamped(n) { n = round(Number(n)); return [n < 0 ? 0 : n > 0xff ? 0xff : n & 0xff]; } + +function packI16(n) { return [(n >> 8) & 0xff, n & 0xff]; } +function unpackI16(bytes) { return as_signed(bytes[0] << 8 | bytes[1], 16); } + +function packU16(n) { return [(n >> 8) & 0xff, n & 0xff]; } +function unpackU16(bytes) { return as_unsigned(bytes[0] << 8 | bytes[1], 16); } + +function packI32(n) { return [(n >> 24) & 0xff, (n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff]; } +function unpackI32(bytes) { return as_signed(bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3], 32); } + +function packU32(n) { return [(n >> 24) & 0xff, (n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff]; } +function unpackU32(bytes) { return as_unsigned(bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3], 32); } + +function packIEEE754(v, ebits, fbits) { + + var bias = (1 << (ebits - 1)) - 1, + s, e, f, ln, + i, bits, str, bytes; + + function roundToEven(n) { + var w = floor(n), f = n - w; + if (f < 0.5) + return w; + if (f > 0.5) + return w + 1; + return w % 2 ? w + 1 : w; + } + + // Compute sign, exponent, fraction + if (v !== v) { + // NaN + // http://dev.w3.org/2006/webapi/WebIDL/#es-type-mapping + e = (1 << ebits) - 1; f = pow(2, fbits - 1); s = 0; + } else if (v === Infinity || v === -Infinity) { + e = (1 << ebits) - 1; f = 0; s = (v < 0) ? 1 : 0; + } else if (v === 0) { + e = 0; f = 0; s = (1 / v === -Infinity) ? 1 : 0; + } else { + s = v < 0; + v = abs(v); + + if (v >= pow(2, 1 - bias)) { + e = min(floor(log(v) / LN2), 1023); + f = roundToEven(v / pow(2, e) * pow(2, fbits)); + if (f / pow(2, fbits) >= 2) { + e = e + 1; + f = 1; + } + if (e > bias) { + // Overflow + e = (1 << ebits) - 1; + f = 0; + } else { + // Normalized + e = e + bias; + f = f - pow(2, fbits); + } + } else { + // Denormalized + e = 0; + f = roundToEven(v / pow(2, 1 - bias - fbits)); + } + } + + // Pack sign, exponent, fraction + bits = []; + for (i = fbits; i; i -= 1) { bits.push(f % 2 ? 1 : 0); f = floor(f / 2); } + for (i = ebits; i; i -= 1) { bits.push(e % 2 ? 1 : 0); e = floor(e / 2); } + bits.push(s ? 1 : 0); + bits.reverse(); + str = bits.join(''); + + // Bits to bytes + bytes = []; + while (str.length) { + bytes.push(parseInt(str.substring(0, 8), 2)); + str = str.substring(8); + } + return bytes; +} + +function unpackIEEE754(bytes, ebits, fbits) { + + // Bytes to bits + var bits = [], i, j, b, str, + bias, s, e, f; + + for (i = bytes.length; i; i -= 1) { + b = bytes[i - 1]; + for (j = 8; j; j -= 1) { + bits.push(b % 2 ? 1 : 0); b = b >> 1; + } + } + bits.reverse(); + str = bits.join(''); + + // Unpack sign, exponent, fraction + bias = (1 << (ebits - 1)) - 1; + s = parseInt(str.substring(0, 1), 2) ? -1 : 1; + e = parseInt(str.substring(1, 1 + ebits), 2); + f = parseInt(str.substring(1 + ebits), 2); + + // Produce number + if (e === (1 << ebits) - 1) { + return f !== 0 ? NaN : s * Infinity; + } else if (e > 0) { + // Normalized + return s * pow(2, e - bias) * (1 + f / pow(2, fbits)); + } else if (f !== 0) { + // Denormalized + return s * pow(2, -(bias - 1)) * (f / pow(2, fbits)); + } else { + return s < 0 ? -0 : 0; + } +} + +function unpackF64(b) { return unpackIEEE754(b, 11, 52); } +function packF64(v) { return packIEEE754(v, 11, 52); } +function unpackF32(b) { return unpackIEEE754(b, 8, 23); } +function packF32(v) { return packIEEE754(v, 8, 23); } + + +// +// 3 The ArrayBuffer Type +// + +(function() { + + /** @constructor */ + var ArrayBuffer = function ArrayBuffer(length) { + length = ECMAScript.ToInt32(length); + if (length < 0) throw new RangeError('ArrayBuffer size is not a small enough positive integer'); + + this.byteLength = length; + this._bytes = []; + this._bytes.length = length; + + var i; + for (i = 0; i < this.byteLength; i += 1) { + this._bytes[i] = 0; + } + + configureProperties(this); + }; + + exports.ArrayBuffer = exports.ArrayBuffer || ArrayBuffer; + + // + // 4 The ArrayBufferView Type + // + + // NOTE: this constructor is not exported + /** @constructor */ + var ArrayBufferView = function ArrayBufferView() { + //this.buffer = null; + //this.byteOffset = 0; + //this.byteLength = 0; + }; + + // + // 5 The Typed Array View Types + // + + function makeConstructor(bytesPerElement, pack, unpack) { + // Each TypedArray type requires a distinct constructor instance with + // identical logic, which this produces. + + var ctor; + ctor = function(buffer, byteOffset, length) { + var array, sequence, i, s; + + if (!arguments.length || typeof arguments[0] === 'number') { + // Constructor(unsigned long length) + this.length = ECMAScript.ToInt32(arguments[0]); + if (length < 0) throw new RangeError('ArrayBufferView size is not a small enough positive integer'); + + this.byteLength = this.length * this.BYTES_PER_ELEMENT; + this.buffer = new ArrayBuffer(this.byteLength); + this.byteOffset = 0; + } else if (typeof arguments[0] === 'object' && arguments[0].constructor === ctor) { + // Constructor(TypedArray array) + array = arguments[0]; + + this.length = array.length; + this.byteLength = this.length * this.BYTES_PER_ELEMENT; + this.buffer = new ArrayBuffer(this.byteLength); + this.byteOffset = 0; + + for (i = 0; i < this.length; i += 1) { + this._setter(i, array._getter(i)); + } + } else if (typeof arguments[0] === 'object' && + !(arguments[0] instanceof ArrayBuffer || ECMAScript.Class(arguments[0]) === 'ArrayBuffer')) { + // Constructor(sequence array) + sequence = arguments[0]; + + this.length = ECMAScript.ToUint32(sequence.length); + this.byteLength = this.length * this.BYTES_PER_ELEMENT; + this.buffer = new ArrayBuffer(this.byteLength); + this.byteOffset = 0; + + for (i = 0; i < this.length; i += 1) { + s = sequence[i]; + this._setter(i, Number(s)); + } + } else if (typeof arguments[0] === 'object' && + (arguments[0] instanceof ArrayBuffer || ECMAScript.Class(arguments[0]) === 'ArrayBuffer')) { + // Constructor(ArrayBuffer buffer, + // optional unsigned long byteOffset, optional unsigned long length) + this.buffer = buffer; + + this.byteOffset = ECMAScript.ToUint32(byteOffset); + if (this.byteOffset > this.buffer.byteLength) { + throw new RangeError("byteOffset out of range"); + } + + if (this.byteOffset % this.BYTES_PER_ELEMENT) { + // The given byteOffset must be a multiple of the element + // size of the specific type, otherwise an exception is raised. + throw new RangeError("ArrayBuffer length minus the byteOffset is not a multiple of the element size."); + } + + if (arguments.length < 3) { + this.byteLength = this.buffer.byteLength - this.byteOffset; + + if (this.byteLength % this.BYTES_PER_ELEMENT) { + throw new RangeError("length of buffer minus byteOffset not a multiple of the element size"); + } + this.length = this.byteLength / this.BYTES_PER_ELEMENT; + } else { + this.length = ECMAScript.ToUint32(length); + this.byteLength = this.length * this.BYTES_PER_ELEMENT; + } + + if ((this.byteOffset + this.byteLength) > this.buffer.byteLength) { + throw new RangeError("byteOffset and length reference an area beyond the end of the buffer"); + } + } else { + throw new TypeError("Unexpected argument type(s)"); + } + + this.constructor = ctor; + + configureProperties(this); + makeArrayAccessors(this); + }; + + ctor.prototype = new ArrayBufferView(); + ctor.prototype.BYTES_PER_ELEMENT = bytesPerElement; + ctor.prototype._pack = pack; + ctor.prototype._unpack = unpack; + ctor.BYTES_PER_ELEMENT = bytesPerElement; + + // getter type (unsigned long index); + ctor.prototype._getter = function(index) { + if (arguments.length < 1) throw new SyntaxError("Not enough arguments"); + + index = ECMAScript.ToUint32(index); + if (index >= this.length) { + return undefined; + } + + var bytes = [], i, o; + for (i = 0, o = this.byteOffset + index * this.BYTES_PER_ELEMENT; + i < this.BYTES_PER_ELEMENT; + i += 1, o += 1) { + bytes.push(this.buffer._bytes[o]); + } + return this._unpack(bytes); + }; + + // NONSTANDARD: convenience alias for getter: type get(unsigned long index); + ctor.prototype.get = ctor.prototype._getter; + + // setter void (unsigned long index, type value); + ctor.prototype._setter = function(index, value) { + if (arguments.length < 2) throw new SyntaxError("Not enough arguments"); + + index = ECMAScript.ToUint32(index); + if (index >= this.length) { + return undefined; + } + + var bytes = this._pack(value), i, o; + for (i = 0, o = this.byteOffset + index * this.BYTES_PER_ELEMENT; + i < this.BYTES_PER_ELEMENT; + i += 1, o += 1) { + this.buffer._bytes[o] = bytes[i]; + } + }; + + // void set(TypedArray array, optional unsigned long offset); + // void set(sequence array, optional unsigned long offset); + ctor.prototype.set = function(index, value) { + if (arguments.length < 1) throw new SyntaxError("Not enough arguments"); + var array, sequence, offset, len, + i, s, d, + byteOffset, byteLength, tmp; + + if (typeof arguments[0] === 'object' && arguments[0].constructor === this.constructor) { + // void set(TypedArray array, optional unsigned long offset); + array = arguments[0]; + offset = ECMAScript.ToUint32(arguments[1]); + + if (offset + array.length > this.length) { + throw new RangeError("Offset plus length of array is out of range"); + } + + byteOffset = this.byteOffset + offset * this.BYTES_PER_ELEMENT; + byteLength = array.length * this.BYTES_PER_ELEMENT; + + if (array.buffer === this.buffer) { + tmp = []; + for (i = 0, s = array.byteOffset; i < byteLength; i += 1, s += 1) { + tmp[i] = array.buffer._bytes[s]; + } + for (i = 0, d = byteOffset; i < byteLength; i += 1, d += 1) { + this.buffer._bytes[d] = tmp[i]; + } + } else { + for (i = 0, s = array.byteOffset, d = byteOffset; + i < byteLength; i += 1, s += 1, d += 1) { + this.buffer._bytes[d] = array.buffer._bytes[s]; + } + } + } else if (typeof arguments[0] === 'object' && typeof arguments[0].length !== 'undefined') { + // void set(sequence array, optional unsigned long offset); + sequence = arguments[0]; + len = ECMAScript.ToUint32(sequence.length); + offset = ECMAScript.ToUint32(arguments[1]); + + if (offset + len > this.length) { + throw new RangeError("Offset plus length of array is out of range"); + } + + for (i = 0; i < len; i += 1) { + s = sequence[i]; + this._setter(offset + i, Number(s)); + } + } else { + throw new TypeError("Unexpected argument type(s)"); + } + }; + + // TypedArray subarray(long begin, optional long end); + ctor.prototype.subarray = function(start, end) { + function clamp(v, min, max) { return v < min ? min : v > max ? max : v; } + + start = ECMAScript.ToInt32(start); + end = ECMAScript.ToInt32(end); + + if (arguments.length < 1) { start = 0; } + if (arguments.length < 2) { end = this.length; } + + if (start < 0) { start = this.length + start; } + if (end < 0) { end = this.length + end; } + + start = clamp(start, 0, this.length); + end = clamp(end, 0, this.length); + + var len = end - start; + if (len < 0) { + len = 0; + } + + return new this.constructor( + this.buffer, this.byteOffset + start * this.BYTES_PER_ELEMENT, len); + }; + + return ctor; + } + + var Int8Array = makeConstructor(1, packI8, unpackI8); + var Uint8Array = makeConstructor(1, packU8, unpackU8); + var Uint8ClampedArray = makeConstructor(1, packU8Clamped, unpackU8); + var Int16Array = makeConstructor(2, packI16, unpackI16); + var Uint16Array = makeConstructor(2, packU16, unpackU16); + var Int32Array = makeConstructor(4, packI32, unpackI32); + var Uint32Array = makeConstructor(4, packU32, unpackU32); + var Float32Array = makeConstructor(4, packF32, unpackF32); + var Float64Array = makeConstructor(8, packF64, unpackF64); + + exports.Int8Array = exports.Int8Array || Int8Array; + exports.Uint8Array = exports.Uint8Array || Uint8Array; + exports.Uint8ClampedArray = exports.Uint8ClampedArray || Uint8ClampedArray; + exports.Int16Array = exports.Int16Array || Int16Array; + exports.Uint16Array = exports.Uint16Array || Uint16Array; + exports.Int32Array = exports.Int32Array || Int32Array; + exports.Uint32Array = exports.Uint32Array || Uint32Array; + exports.Float32Array = exports.Float32Array || Float32Array; + exports.Float64Array = exports.Float64Array || Float64Array; +}()); + +// +// 6 The DataView View Type +// + +(function() { + function r(array, index) { + return ECMAScript.IsCallable(array.get) ? array.get(index) : array[index]; + } + + var IS_BIG_ENDIAN = (function() { + var u16array = new(exports.Uint16Array)([0x1234]), + u8array = new(exports.Uint8Array)(u16array.buffer); + return r(u8array, 0) === 0x12; + }()); + + // Constructor(ArrayBuffer buffer, + // optional unsigned long byteOffset, + // optional unsigned long byteLength) + /** @constructor */ + var DataView = function DataView(buffer, byteOffset, byteLength) { + if (arguments.length === 0) { + buffer = new exports.ArrayBuffer(0); + } else if (!(buffer instanceof exports.ArrayBuffer || ECMAScript.Class(buffer) === 'ArrayBuffer')) { + throw new TypeError("TypeError"); + } + + this.buffer = buffer || new exports.ArrayBuffer(0); + + this.byteOffset = ECMAScript.ToUint32(byteOffset); + if (this.byteOffset > this.buffer.byteLength) { + throw new RangeError("byteOffset out of range"); + } + + if (arguments.length < 3) { + this.byteLength = this.buffer.byteLength - this.byteOffset; + } else { + this.byteLength = ECMAScript.ToUint32(byteLength); + } + + if ((this.byteOffset + this.byteLength) > this.buffer.byteLength) { + throw new RangeError("byteOffset and length reference an area beyond the end of the buffer"); + } + + configureProperties(this); + }; + + function makeGetter(arrayType) { + return function(byteOffset, littleEndian) { + + byteOffset = ECMAScript.ToUint32(byteOffset); + + if (byteOffset + arrayType.BYTES_PER_ELEMENT > this.byteLength) { + throw new RangeError("Array index out of range"); + } + byteOffset += this.byteOffset; + + var uint8Array = new exports.Uint8Array(this.buffer, byteOffset, arrayType.BYTES_PER_ELEMENT), + bytes = [], i; + for (i = 0; i < arrayType.BYTES_PER_ELEMENT; i += 1) { + bytes.push(r(uint8Array, i)); + } + + if (Boolean(littleEndian) === Boolean(IS_BIG_ENDIAN)) { + bytes.reverse(); + } + + return r(new arrayType(new exports.Uint8Array(bytes).buffer), 0); + }; + } + + DataView.prototype.getUint8 = makeGetter(exports.Uint8Array); + DataView.prototype.getInt8 = makeGetter(exports.Int8Array); + DataView.prototype.getUint16 = makeGetter(exports.Uint16Array); + DataView.prototype.getInt16 = makeGetter(exports.Int16Array); + DataView.prototype.getUint32 = makeGetter(exports.Uint32Array); + DataView.prototype.getInt32 = makeGetter(exports.Int32Array); + DataView.prototype.getFloat32 = makeGetter(exports.Float32Array); + DataView.prototype.getFloat64 = makeGetter(exports.Float64Array); + + function makeSetter(arrayType) { + return function(byteOffset, value, littleEndian) { + + byteOffset = ECMAScript.ToUint32(byteOffset); + if (byteOffset + arrayType.BYTES_PER_ELEMENT > this.byteLength) { + throw new RangeError("Array index out of range"); + } + + // Get bytes + var typeArray = new arrayType([value]), + byteArray = new exports.Uint8Array(typeArray.buffer), + bytes = [], i, byteView; + + for (i = 0; i < arrayType.BYTES_PER_ELEMENT; i += 1) { + bytes.push(r(byteArray, i)); + } + + // Flip if necessary + if (Boolean(littleEndian) === Boolean(IS_BIG_ENDIAN)) { + bytes.reverse(); + } + + // Write them + byteView = new exports.Uint8Array(this.buffer, byteOffset, arrayType.BYTES_PER_ELEMENT); + byteView.set(bytes); + }; + } + + DataView.prototype.setUint8 = makeSetter(exports.Uint8Array); + DataView.prototype.setInt8 = makeSetter(exports.Int8Array); + DataView.prototype.setUint16 = makeSetter(exports.Uint16Array); + DataView.prototype.setInt16 = makeSetter(exports.Int16Array); + DataView.prototype.setUint32 = makeSetter(exports.Uint32Array); + DataView.prototype.setInt32 = makeSetter(exports.Int32Array); + DataView.prototype.setFloat32 = makeSetter(exports.Float32Array); + DataView.prototype.setFloat64 = makeSetter(exports.Float64Array); + + exports.DataView = exports.DataView || DataView; + +}()); diff --git a/backend/node_modules/typedarray/package.json b/backend/node_modules/typedarray/package.json new file mode 100644 index 0000000000000000000000000000000000000000..a7854a0fc5fb420607f8519afbbf588597f0628e --- /dev/null +++ b/backend/node_modules/typedarray/package.json @@ -0,0 +1,55 @@ +{ + "name": "typedarray", + "version": "0.0.6", + "description": "TypedArray polyfill for old browsers", + "main": "index.js", + "devDependencies": { + "tape": "~2.3.2" + }, + "scripts": { + "test": "tape test/*.js test/server/*.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/substack/typedarray.git" + }, + "homepage": "https://github.com/substack/typedarray", + "keywords": [ + "ArrayBuffer", + "DataView", + "Float32Array", + "Float64Array", + "Int8Array", + "Int16Array", + "Int32Array", + "Uint8Array", + "Uint8ClampedArray", + "Uint16Array", + "Uint32Array", + "typed", + "array", + "polyfill" + ], + "author": { + "name": "James Halliday", + "email": "mail@substack.net", + "url": "http://substack.net" + }, + "license": "MIT", + "testling": { + "files": "test/*.js", + "browsers": [ + "ie/6..latest", + "firefox/16..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/backend/node_modules/typedarray/readme.markdown b/backend/node_modules/typedarray/readme.markdown new file mode 100644 index 0000000000000000000000000000000000000000..d18f6f7197e6a5d852c592ba7539d58e9e4ea729 --- /dev/null +++ b/backend/node_modules/typedarray/readme.markdown @@ -0,0 +1,61 @@ +# typedarray + +TypedArray polyfill ripped from [this +module](https://raw.github.com/inexorabletash/polyfill). + +[![build status](https://secure.travis-ci.org/substack/typedarray.png)](http://travis-ci.org/substack/typedarray) + +[![testling badge](https://ci.testling.com/substack/typedarray.png)](https://ci.testling.com/substack/typedarray) + +# example + +``` js +var Uint8Array = require('typedarray').Uint8Array; +var ua = new Uint8Array(5); +ua[1] = 256 + 55; +console.log(ua[1]); +``` + +output: + +``` +55 +``` + +# methods + +``` js +var TA = require('typedarray') +``` + +The `TA` object has the following constructors: + +* TA.ArrayBuffer +* TA.DataView +* TA.Float32Array +* TA.Float64Array +* TA.Int8Array +* TA.Int16Array +* TA.Int32Array +* TA.Uint8Array +* TA.Uint8ClampedArray +* TA.Uint16Array +* TA.Uint32Array + +# install + +With [npm](https://npmjs.org) do: + +``` +npm install typedarray +``` + +To use this module in the browser, compile with +[browserify](http://browserify.org) +or download a UMD build from browserify CDN: + +http://wzrd.in/standalone/typedarray@latest + +# license + +MIT diff --git a/backend/node_modules/typedarray/test/server/undef_globals.js b/backend/node_modules/typedarray/test/server/undef_globals.js new file mode 100644 index 0000000000000000000000000000000000000000..425950f9fc9ed7c09d78c749f27014cfdf4a84d3 --- /dev/null +++ b/backend/node_modules/typedarray/test/server/undef_globals.js @@ -0,0 +1,19 @@ +var test = require('tape'); +var vm = require('vm'); +var fs = require('fs'); +var src = fs.readFileSync(__dirname + '/../../index.js', 'utf8'); + +test('u8a without globals', function (t) { + var c = { + module: { exports: {} }, + }; + c.exports = c.module.exports; + vm.runInNewContext(src, c); + var TA = c.module.exports; + var ua = new(TA.Uint8Array)(5); + + t.equal(ua.length, 5); + ua[1] = 256 + 55; + t.equal(ua[1], 55); + t.end(); +}); diff --git a/backend/node_modules/typedarray/test/tarray.js b/backend/node_modules/typedarray/test/tarray.js new file mode 100644 index 0000000000000000000000000000000000000000..df596a34f23c0ef931cd5b41139985b8d23e8e2f --- /dev/null +++ b/backend/node_modules/typedarray/test/tarray.js @@ -0,0 +1,10 @@ +var TA = require('../'); +var test = require('tape'); + +test('tiny u8a test', function (t) { + var ua = new(TA.Uint8Array)(5); + t.equal(ua.length, 5); + ua[1] = 256 + 55; + t.equal(ua[1], 55); + t.end(); +}); diff --git a/backend/node_modules/undici-types/README.md b/backend/node_modules/undici-types/README.md new file mode 100644 index 0000000000000000000000000000000000000000..20a721c445a21b60d9d3a20d142da608bffd7d9b --- /dev/null +++ b/backend/node_modules/undici-types/README.md @@ -0,0 +1,6 @@ +# undici-types + +This package is a dual-publish of the [undici](https://www.npmjs.com/package/undici) library types. The `undici` package **still contains types**. This package is for users who _only_ need undici types (such as for `@types/node`). It is published alongside every release of `undici`, so you can always use the same version. + +- [GitHub nodejs/undici](https://github.com/nodejs/undici) +- [Undici Documentation](https://undici.nodejs.org/#/) diff --git a/backend/node_modules/undici-types/agent.d.ts b/backend/node_modules/undici-types/agent.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..58081ce9372633cce609bf6783b7179212b5f32d --- /dev/null +++ b/backend/node_modules/undici-types/agent.d.ts @@ -0,0 +1,31 @@ +import { URL } from 'url' +import Pool from './pool' +import Dispatcher from "./dispatcher"; + +export default Agent + +declare class Agent extends Dispatcher{ + constructor(opts?: Agent.Options) + /** `true` after `dispatcher.close()` has been called. */ + closed: boolean; + /** `true` after `dispatcher.destroyed()` has been called or `dispatcher.close()` has been called and the dispatcher shutdown has completed. */ + destroyed: boolean; + /** Dispatches a request. */ + dispatch(options: Agent.DispatchOptions, handler: Dispatcher.DispatchHandlers): boolean; +} + +declare namespace Agent { + export interface Options extends Pool.Options { + /** Default: `(origin, opts) => new Pool(origin, opts)`. */ + factory?(origin: string | URL, opts: Object): Dispatcher; + /** Integer. Default: `0` */ + maxRedirections?: number; + + interceptors?: { Agent?: readonly Dispatcher.DispatchInterceptor[] } & Pool.Options["interceptors"] + } + + export interface DispatchOptions extends Dispatcher.DispatchOptions { + /** Integer. */ + maxRedirections?: number; + } +} diff --git a/backend/node_modules/undici-types/api.d.ts b/backend/node_modules/undici-types/api.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..400341dddc06f7138b76fe3b3275a7992b3c8ead --- /dev/null +++ b/backend/node_modules/undici-types/api.d.ts @@ -0,0 +1,43 @@ +import { URL, UrlObject } from 'url' +import { Duplex } from 'stream' +import Dispatcher from './dispatcher' + +export { + request, + stream, + pipeline, + connect, + upgrade, +} + +/** Performs an HTTP request. */ +declare function request( + url: string | URL | UrlObject, + options?: { dispatcher?: Dispatcher } & Omit & Partial>, +): Promise; + +/** A faster version of `request`. */ +declare function stream( + url: string | URL | UrlObject, + options: { dispatcher?: Dispatcher } & Omit, + factory: Dispatcher.StreamFactory +): Promise; + +/** For easy use with `stream.pipeline`. */ +declare function pipeline( + url: string | URL | UrlObject, + options: { dispatcher?: Dispatcher } & Omit, + handler: Dispatcher.PipelineHandler +): Duplex; + +/** Starts two-way communications with the requested resource. */ +declare function connect( + url: string | URL | UrlObject, + options?: { dispatcher?: Dispatcher } & Omit +): Promise; + +/** Upgrade to a different protocol. */ +declare function upgrade( + url: string | URL | UrlObject, + options?: { dispatcher?: Dispatcher } & Omit +): Promise; diff --git a/backend/node_modules/undici-types/balanced-pool.d.ts b/backend/node_modules/undici-types/balanced-pool.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d1e9375875f391eadd48a4dfae4bc0d3733fec0c --- /dev/null +++ b/backend/node_modules/undici-types/balanced-pool.d.ts @@ -0,0 +1,18 @@ +import Pool from './pool' +import Dispatcher from './dispatcher' +import { URL } from 'url' + +export default BalancedPool + +declare class BalancedPool extends Dispatcher { + constructor(url: string | string[] | URL | URL[], options?: Pool.Options); + + addUpstream(upstream: string | URL): BalancedPool; + removeUpstream(upstream: string | URL): BalancedPool; + upstreams: Array; + + /** `true` after `pool.close()` has been called. */ + closed: boolean; + /** `true` after `pool.destroyed()` has been called or `pool.close()` has been called and the pool shutdown has completed. */ + destroyed: boolean; +} diff --git a/backend/node_modules/undici-types/cache.d.ts b/backend/node_modules/undici-types/cache.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4c33335766667761460cc464303e80efe0c6eb10 --- /dev/null +++ b/backend/node_modules/undici-types/cache.d.ts @@ -0,0 +1,36 @@ +import type { RequestInfo, Response, Request } from './fetch' + +export interface CacheStorage { + match (request: RequestInfo, options?: MultiCacheQueryOptions): Promise, + has (cacheName: string): Promise, + open (cacheName: string): Promise, + delete (cacheName: string): Promise, + keys (): Promise +} + +declare const CacheStorage: { + prototype: CacheStorage + new(): CacheStorage +} + +export interface Cache { + match (request: RequestInfo, options?: CacheQueryOptions): Promise, + matchAll (request?: RequestInfo, options?: CacheQueryOptions): Promise, + add (request: RequestInfo): Promise, + addAll (requests: RequestInfo[]): Promise, + put (request: RequestInfo, response: Response): Promise, + delete (request: RequestInfo, options?: CacheQueryOptions): Promise, + keys (request?: RequestInfo, options?: CacheQueryOptions): Promise +} + +export interface CacheQueryOptions { + ignoreSearch?: boolean, + ignoreMethod?: boolean, + ignoreVary?: boolean +} + +export interface MultiCacheQueryOptions extends CacheQueryOptions { + cacheName?: string +} + +export declare const caches: CacheStorage diff --git a/backend/node_modules/undici-types/client.d.ts b/backend/node_modules/undici-types/client.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..74948b15f3841faf4d0917b25e0248bd05e3a269 --- /dev/null +++ b/backend/node_modules/undici-types/client.d.ts @@ -0,0 +1,97 @@ +import { URL } from 'url' +import { TlsOptions } from 'tls' +import Dispatcher from './dispatcher' +import buildConnector from "./connector"; + +/** + * A basic HTTP/1.1 client, mapped on top a single TCP/TLS connection. Pipelining is disabled by default. + */ +export class Client extends Dispatcher { + constructor(url: string | URL, options?: Client.Options); + /** Property to get and set the pipelining factor. */ + pipelining: number; + /** `true` after `client.close()` has been called. */ + closed: boolean; + /** `true` after `client.destroyed()` has been called or `client.close()` has been called and the client shutdown has completed. */ + destroyed: boolean; +} + +export declare namespace Client { + export interface OptionsInterceptors { + Client: readonly Dispatcher.DispatchInterceptor[]; + } + export interface Options { + /** TODO */ + interceptors?: OptionsInterceptors; + /** The maximum length of request headers in bytes. Default: Node.js' `--max-http-header-size` or `16384` (16KiB). */ + maxHeaderSize?: number; + /** The amount of time, in milliseconds, the parser will wait to receive the complete HTTP headers (Node 14 and above only). Default: `300e3` milliseconds (300s). */ + headersTimeout?: number; + /** @deprecated unsupported socketTimeout, use headersTimeout & bodyTimeout instead */ + socketTimeout?: never; + /** @deprecated unsupported requestTimeout, use headersTimeout & bodyTimeout instead */ + requestTimeout?: never; + /** TODO */ + connectTimeout?: number; + /** The timeout after which a request will time out, in milliseconds. Monitors time between receiving body data. Use `0` to disable it entirely. Default: `300e3` milliseconds (300s). */ + bodyTimeout?: number; + /** @deprecated unsupported idleTimeout, use keepAliveTimeout instead */ + idleTimeout?: never; + /** @deprecated unsupported keepAlive, use pipelining=0 instead */ + keepAlive?: never; + /** the timeout, in milliseconds, after which a socket without active requests will time out. Monitors time between activity on a connected socket. This value may be overridden by *keep-alive* hints from the server. Default: `4e3` milliseconds (4s). */ + keepAliveTimeout?: number; + /** @deprecated unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead */ + maxKeepAliveTimeout?: never; + /** the maximum allowed `idleTimeout`, in milliseconds, when overridden by *keep-alive* hints from the server. Default: `600e3` milliseconds (10min). */ + keepAliveMaxTimeout?: number; + /** A number of milliseconds subtracted from server *keep-alive* hints when overriding `idleTimeout` to account for timing inaccuracies caused by e.g. transport latency. Default: `1e3` milliseconds (1s). */ + keepAliveTimeoutThreshold?: number; + /** TODO */ + socketPath?: string; + /** The amount of concurrent requests to be sent over the single TCP/TLS connection according to [RFC7230](https://tools.ietf.org/html/rfc7230#section-6.3.2). Default: `1`. */ + pipelining?: number; + /** @deprecated use the connect option instead */ + tls?: never; + /** If `true`, an error is thrown when the request content-length header doesn't match the length of the request body. Default: `true`. */ + strictContentLength?: boolean; + /** TODO */ + maxCachedSessions?: number; + /** TODO */ + maxRedirections?: number; + /** TODO */ + connect?: buildConnector.BuildOptions | buildConnector.connector; + /** TODO */ + maxRequestsPerClient?: number; + /** TODO */ + localAddress?: string; + /** Max response body size in bytes, -1 is disabled */ + maxResponseSize?: number; + /** Enables a family autodetection algorithm that loosely implements section 5 of RFC 8305. */ + autoSelectFamily?: boolean; + /** The amount of time in milliseconds to wait for a connection attempt to finish before trying the next address when using the `autoSelectFamily` option. */ + autoSelectFamilyAttemptTimeout?: number; + /** + * @description Enables support for H2 if the server has assigned bigger priority to it through ALPN negotiation. + * @default false + */ + allowH2?: boolean; + /** + * @description Dictates the maximum number of concurrent streams for a single H2 session. It can be overriden by a SETTINGS remote frame. + * @default 100 + */ + maxConcurrentStreams?: number + } + export interface SocketInfo { + localAddress?: string + localPort?: number + remoteAddress?: string + remotePort?: number + remoteFamily?: string + timeout?: number + bytesWritten?: number + bytesRead?: number + } +} + +export default Client; diff --git a/backend/node_modules/undici-types/connector.d.ts b/backend/node_modules/undici-types/connector.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..bd924339eb3986d17544bd1905c8856e25396e27 --- /dev/null +++ b/backend/node_modules/undici-types/connector.d.ts @@ -0,0 +1,34 @@ +import { TLSSocket, ConnectionOptions } from 'tls' +import { IpcNetConnectOpts, Socket, TcpNetConnectOpts } from 'net' + +export default buildConnector +declare function buildConnector (options?: buildConnector.BuildOptions): buildConnector.connector + +declare namespace buildConnector { + export type BuildOptions = (ConnectionOptions | TcpNetConnectOpts | IpcNetConnectOpts) & { + allowH2?: boolean; + maxCachedSessions?: number | null; + socketPath?: string | null; + timeout?: number | null; + port?: number; + keepAlive?: boolean | null; + keepAliveInitialDelay?: number | null; + } + + export interface Options { + hostname: string + host?: string + protocol: string + port: string + servername?: string + localAddress?: string | null + httpSocket?: Socket + } + + export type Callback = (...args: CallbackArgs) => void + type CallbackArgs = [null, Socket | TLSSocket] | [Error, null] + + export interface connector { + (options: buildConnector.Options, callback: buildConnector.Callback): void + } +} diff --git a/backend/node_modules/undici-types/content-type.d.ts b/backend/node_modules/undici-types/content-type.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f2a87f1b7518f72d94894b21fbfe96b7d0264ab3 --- /dev/null +++ b/backend/node_modules/undici-types/content-type.d.ts @@ -0,0 +1,21 @@ +/// + +interface MIMEType { + type: string + subtype: string + parameters: Map + essence: string +} + +/** + * Parse a string to a {@link MIMEType} object. Returns `failure` if the string + * couldn't be parsed. + * @see https://mimesniff.spec.whatwg.org/#parse-a-mime-type + */ +export function parseMIMEType (input: string): 'failure' | MIMEType + +/** + * Convert a MIMEType object to a string. + * @see https://mimesniff.spec.whatwg.org/#serialize-a-mime-type + */ +export function serializeAMimeType (mimeType: MIMEType): string diff --git a/backend/node_modules/undici-types/cookies.d.ts b/backend/node_modules/undici-types/cookies.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..aa38cae49d7743b3c1e1eabbbaa2c18a34b2e302 --- /dev/null +++ b/backend/node_modules/undici-types/cookies.d.ts @@ -0,0 +1,28 @@ +/// + +import type { Headers } from './fetch' + +export interface Cookie { + name: string + value: string + expires?: Date | number + maxAge?: number + domain?: string + path?: string + secure?: boolean + httpOnly?: boolean + sameSite?: 'Strict' | 'Lax' | 'None' + unparsed?: string[] +} + +export function deleteCookie ( + headers: Headers, + name: string, + attributes?: { name?: string, domain?: string } +): void + +export function getCookies (headers: Headers): Record + +export function getSetCookies (headers: Headers): Cookie[] + +export function setCookie (headers: Headers, cookie: Cookie): void diff --git a/backend/node_modules/undici-types/diagnostics-channel.d.ts b/backend/node_modules/undici-types/diagnostics-channel.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..85d44823978df57f866aa994cbe8e24967ab2706 --- /dev/null +++ b/backend/node_modules/undici-types/diagnostics-channel.d.ts @@ -0,0 +1,67 @@ +import { Socket } from "net"; +import { URL } from "url"; +import Connector from "./connector"; +import Dispatcher from "./dispatcher"; + +declare namespace DiagnosticsChannel { + interface Request { + origin?: string | URL; + completed: boolean; + method?: Dispatcher.HttpMethod; + path: string; + headers: string; + addHeader(key: string, value: string): Request; + } + interface Response { + statusCode: number; + statusText: string; + headers: Array; + } + type Error = unknown; + interface ConnectParams { + host: URL["host"]; + hostname: URL["hostname"]; + protocol: URL["protocol"]; + port: URL["port"]; + servername: string | null; + } + type Connector = Connector.connector; + export interface RequestCreateMessage { + request: Request; + } + export interface RequestBodySentMessage { + request: Request; + } + export interface RequestHeadersMessage { + request: Request; + response: Response; + } + export interface RequestTrailersMessage { + request: Request; + trailers: Array; + } + export interface RequestErrorMessage { + request: Request; + error: Error; + } + export interface ClientSendHeadersMessage { + request: Request; + headers: string; + socket: Socket; + } + export interface ClientBeforeConnectMessage { + connectParams: ConnectParams; + connector: Connector; + } + export interface ClientConnectedMessage { + socket: Socket; + connectParams: ConnectParams; + connector: Connector; + } + export interface ClientConnectErrorMessage { + error: Error; + socket: Socket; + connectParams: ConnectParams; + connector: Connector; + } +} diff --git a/backend/node_modules/undici-types/dispatcher.d.ts b/backend/node_modules/undici-types/dispatcher.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..816db19d20d87881b4d9d45bb13ef0c3a292e451 --- /dev/null +++ b/backend/node_modules/undici-types/dispatcher.d.ts @@ -0,0 +1,241 @@ +import { URL } from 'url' +import { Duplex, Readable, Writable } from 'stream' +import { EventEmitter } from 'events' +import { Blob } from 'buffer' +import { IncomingHttpHeaders } from './header' +import BodyReadable from './readable' +import { FormData } from './formdata' +import Errors from './errors' + +type AbortSignal = unknown; + +export default Dispatcher + +/** Dispatcher is the core API used to dispatch requests. */ +declare class Dispatcher extends EventEmitter { + /** Dispatches a request. This API is expected to evolve through semver-major versions and is less stable than the preceding higher level APIs. It is primarily intended for library developers who implement higher level APIs on top of this. */ + dispatch(options: Dispatcher.DispatchOptions, handler: Dispatcher.DispatchHandlers): boolean; + /** Starts two-way communications with the requested resource. */ + connect(options: Dispatcher.ConnectOptions): Promise; + connect(options: Dispatcher.ConnectOptions, callback: (err: Error | null, data: Dispatcher.ConnectData) => void): void; + /** Performs an HTTP request. */ + request(options: Dispatcher.RequestOptions): Promise; + request(options: Dispatcher.RequestOptions, callback: (err: Error | null, data: Dispatcher.ResponseData) => void): void; + /** For easy use with `stream.pipeline`. */ + pipeline(options: Dispatcher.PipelineOptions, handler: Dispatcher.PipelineHandler): Duplex; + /** A faster version of `Dispatcher.request`. */ + stream(options: Dispatcher.RequestOptions, factory: Dispatcher.StreamFactory): Promise; + stream(options: Dispatcher.RequestOptions, factory: Dispatcher.StreamFactory, callback: (err: Error | null, data: Dispatcher.StreamData) => void): void; + /** Upgrade to a different protocol. */ + upgrade(options: Dispatcher.UpgradeOptions): Promise; + upgrade(options: Dispatcher.UpgradeOptions, callback: (err: Error | null, data: Dispatcher.UpgradeData) => void): void; + /** Closes the client and gracefully waits for enqueued requests to complete before invoking the callback (or returning a promise if no callback is provided). */ + close(): Promise; + close(callback: () => void): void; + /** Destroy the client abruptly with the given err. All the pending and running requests will be asynchronously aborted and error. Waits until socket is closed before invoking the callback (or returning a promise if no callback is provided). Since this operation is asynchronously dispatched there might still be some progress on dispatched requests. */ + destroy(): Promise; + destroy(err: Error | null): Promise; + destroy(callback: () => void): void; + destroy(err: Error | null, callback: () => void): void; + + on(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; + on(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + on(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + on(eventName: 'drain', callback: (origin: URL) => void): this; + + + once(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; + once(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + once(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + once(eventName: 'drain', callback: (origin: URL) => void): this; + + + off(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; + off(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + off(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + off(eventName: 'drain', callback: (origin: URL) => void): this; + + + addListener(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; + addListener(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + addListener(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + addListener(eventName: 'drain', callback: (origin: URL) => void): this; + + removeListener(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; + removeListener(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + removeListener(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + removeListener(eventName: 'drain', callback: (origin: URL) => void): this; + + prependListener(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; + prependListener(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + prependListener(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + prependListener(eventName: 'drain', callback: (origin: URL) => void): this; + + prependOnceListener(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; + prependOnceListener(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + prependOnceListener(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + prependOnceListener(eventName: 'drain', callback: (origin: URL) => void): this; + + listeners(eventName: 'connect'): ((origin: URL, targets: readonly Dispatcher[]) => void)[] + listeners(eventName: 'disconnect'): ((origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[]; + listeners(eventName: 'connectionError'): ((origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[]; + listeners(eventName: 'drain'): ((origin: URL) => void)[]; + + rawListeners(eventName: 'connect'): ((origin: URL, targets: readonly Dispatcher[]) => void)[] + rawListeners(eventName: 'disconnect'): ((origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[]; + rawListeners(eventName: 'connectionError'): ((origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[]; + rawListeners(eventName: 'drain'): ((origin: URL) => void)[]; + + emit(eventName: 'connect', origin: URL, targets: readonly Dispatcher[]): boolean; + emit(eventName: 'disconnect', origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError): boolean; + emit(eventName: 'connectionError', origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError): boolean; + emit(eventName: 'drain', origin: URL): boolean; +} + +declare namespace Dispatcher { + export interface DispatchOptions { + origin?: string | URL; + path: string; + method: HttpMethod; + /** Default: `null` */ + body?: string | Buffer | Uint8Array | Readable | null | FormData; + /** Default: `null` */ + headers?: IncomingHttpHeaders | string[] | null; + /** Query string params to be embedded in the request URL. Default: `null` */ + query?: Record; + /** Whether the requests can be safely retried or not. If `false` the request won't be sent until all preceding requests in the pipeline have completed. Default: `true` if `method` is `HEAD` or `GET`. */ + idempotent?: boolean; + /** Whether the response is expected to take a long time and would end up blocking the pipeline. When this is set to `true` further pipelining will be avoided on the same connection until headers have been received. */ + blocking?: boolean; + /** Upgrade the request. Should be used to specify the kind of upgrade i.e. `'Websocket'`. Default: `method === 'CONNECT' || null`. */ + upgrade?: boolean | string | null; + /** The amount of time, in milliseconds, the parser will wait to receive the complete HTTP headers. Defaults to 300 seconds. */ + headersTimeout?: number | null; + /** The timeout after which a request will time out, in milliseconds. Monitors time between receiving body data. Use 0 to disable it entirely. Defaults to 300 seconds. */ + bodyTimeout?: number | null; + /** Whether the request should stablish a keep-alive or not. Default `false` */ + reset?: boolean; + /** Whether Undici should throw an error upon receiving a 4xx or 5xx response from the server. Defaults to false */ + throwOnError?: boolean; + /** For H2, it appends the expect: 100-continue header, and halts the request body until a 100-continue is received from the remote server*/ + expectContinue?: boolean; + } + export interface ConnectOptions { + path: string; + /** Default: `null` */ + headers?: IncomingHttpHeaders | string[] | null; + /** Default: `null` */ + signal?: AbortSignal | EventEmitter | null; + /** This argument parameter is passed through to `ConnectData` */ + opaque?: unknown; + /** Default: 0 */ + maxRedirections?: number; + /** Default: `null` */ + responseHeader?: 'raw' | null; + } + export interface RequestOptions extends DispatchOptions { + /** Default: `null` */ + opaque?: unknown; + /** Default: `null` */ + signal?: AbortSignal | EventEmitter | null; + /** Default: 0 */ + maxRedirections?: number; + /** Default: `null` */ + onInfo?: (info: { statusCode: number, headers: Record }) => void; + /** Default: `null` */ + responseHeader?: 'raw' | null; + /** Default: `64 KiB` */ + highWaterMark?: number; + } + export interface PipelineOptions extends RequestOptions { + /** `true` if the `handler` will return an object stream. Default: `false` */ + objectMode?: boolean; + } + export interface UpgradeOptions { + path: string; + /** Default: `'GET'` */ + method?: string; + /** Default: `null` */ + headers?: IncomingHttpHeaders | string[] | null; + /** A string of comma separated protocols, in descending preference order. Default: `'Websocket'` */ + protocol?: string; + /** Default: `null` */ + signal?: AbortSignal | EventEmitter | null; + /** Default: 0 */ + maxRedirections?: number; + /** Default: `null` */ + responseHeader?: 'raw' | null; + } + export interface ConnectData { + statusCode: number; + headers: IncomingHttpHeaders; + socket: Duplex; + opaque: unknown; + } + export interface ResponseData { + statusCode: number; + headers: IncomingHttpHeaders; + body: BodyReadable & BodyMixin; + trailers: Record; + opaque: unknown; + context: object; + } + export interface PipelineHandlerData { + statusCode: number; + headers: IncomingHttpHeaders; + opaque: unknown; + body: BodyReadable; + context: object; + } + export interface StreamData { + opaque: unknown; + trailers: Record; + } + export interface UpgradeData { + headers: IncomingHttpHeaders; + socket: Duplex; + opaque: unknown; + } + export interface StreamFactoryData { + statusCode: number; + headers: IncomingHttpHeaders; + opaque: unknown; + context: object; + } + export type StreamFactory = (data: StreamFactoryData) => Writable; + export interface DispatchHandlers { + /** Invoked before request is dispatched on socket. May be invoked multiple times when a request is retried when the request at the head of the pipeline fails. */ + onConnect?(abort: () => void): void; + /** Invoked when an error has occurred. */ + onError?(err: Error): void; + /** Invoked when request is upgraded either due to a `Upgrade` header or `CONNECT` method. */ + onUpgrade?(statusCode: number, headers: Buffer[] | string[] | null, socket: Duplex): void; + /** Invoked when statusCode and headers have been received. May be invoked multiple times due to 1xx informational headers. */ + onHeaders?(statusCode: number, headers: Buffer[] | string[] | null, resume: () => void): boolean; + /** Invoked when response payload data is received. */ + onData?(chunk: Buffer): boolean; + /** Invoked when response payload and trailers have been received and the request has completed. */ + onComplete?(trailers: string[] | null): void; + /** Invoked when a body chunk is sent to the server. May be invoked multiple times for chunked requests */ + onBodySent?(chunkSize: number, totalBytesSent: number): void; + } + export type PipelineHandler = (data: PipelineHandlerData) => Readable; + export type HttpMethod = 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'CONNECT' | 'OPTIONS' | 'TRACE' | 'PATCH'; + + /** + * @link https://fetch.spec.whatwg.org/#body-mixin + */ + interface BodyMixin { + readonly body?: never; // throws on node v16.6.0 + readonly bodyUsed: boolean; + arrayBuffer(): Promise; + blob(): Promise; + formData(): Promise; + json(): Promise; + text(): Promise; + } + + export interface DispatchInterceptor { + (dispatch: Dispatcher['dispatch']): Dispatcher['dispatch'] + } +} diff --git a/backend/node_modules/undici-types/errors.d.ts b/backend/node_modules/undici-types/errors.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7923ddd9796e604c914a54f23fc40cdff2150f19 --- /dev/null +++ b/backend/node_modules/undici-types/errors.d.ts @@ -0,0 +1,128 @@ +import { IncomingHttpHeaders } from "./header"; +import Client from './client' + +export default Errors + +declare namespace Errors { + export class UndiciError extends Error { + name: string; + code: string; + } + + /** Connect timeout error. */ + export class ConnectTimeoutError extends UndiciError { + name: 'ConnectTimeoutError'; + code: 'UND_ERR_CONNECT_TIMEOUT'; + } + + /** A header exceeds the `headersTimeout` option. */ + export class HeadersTimeoutError extends UndiciError { + name: 'HeadersTimeoutError'; + code: 'UND_ERR_HEADERS_TIMEOUT'; + } + + /** Headers overflow error. */ + export class HeadersOverflowError extends UndiciError { + name: 'HeadersOverflowError' + code: 'UND_ERR_HEADERS_OVERFLOW' + } + + /** A body exceeds the `bodyTimeout` option. */ + export class BodyTimeoutError extends UndiciError { + name: 'BodyTimeoutError'; + code: 'UND_ERR_BODY_TIMEOUT'; + } + + export class ResponseStatusCodeError extends UndiciError { + constructor ( + message?: string, + statusCode?: number, + headers?: IncomingHttpHeaders | string[] | null, + body?: null | Record | string + ); + name: 'ResponseStatusCodeError'; + code: 'UND_ERR_RESPONSE_STATUS_CODE'; + body: null | Record | string + status: number + statusCode: number + headers: IncomingHttpHeaders | string[] | null; + } + + /** Passed an invalid argument. */ + export class InvalidArgumentError extends UndiciError { + name: 'InvalidArgumentError'; + code: 'UND_ERR_INVALID_ARG'; + } + + /** Returned an invalid value. */ + export class InvalidReturnValueError extends UndiciError { + name: 'InvalidReturnValueError'; + code: 'UND_ERR_INVALID_RETURN_VALUE'; + } + + /** The request has been aborted by the user. */ + export class RequestAbortedError extends UndiciError { + name: 'AbortError'; + code: 'UND_ERR_ABORTED'; + } + + /** Expected error with reason. */ + export class InformationalError extends UndiciError { + name: 'InformationalError'; + code: 'UND_ERR_INFO'; + } + + /** Request body length does not match content-length header. */ + export class RequestContentLengthMismatchError extends UndiciError { + name: 'RequestContentLengthMismatchError'; + code: 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH'; + } + + /** Response body length does not match content-length header. */ + export class ResponseContentLengthMismatchError extends UndiciError { + name: 'ResponseContentLengthMismatchError'; + code: 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH'; + } + + /** Trying to use a destroyed client. */ + export class ClientDestroyedError extends UndiciError { + name: 'ClientDestroyedError'; + code: 'UND_ERR_DESTROYED'; + } + + /** Trying to use a closed client. */ + export class ClientClosedError extends UndiciError { + name: 'ClientClosedError'; + code: 'UND_ERR_CLOSED'; + } + + /** There is an error with the socket. */ + export class SocketError extends UndiciError { + name: 'SocketError'; + code: 'UND_ERR_SOCKET'; + socket: Client.SocketInfo | null + } + + /** Encountered unsupported functionality. */ + export class NotSupportedError extends UndiciError { + name: 'NotSupportedError'; + code: 'UND_ERR_NOT_SUPPORTED'; + } + + /** No upstream has been added to the BalancedPool. */ + export class BalancedPoolMissingUpstreamError extends UndiciError { + name: 'MissingUpstreamError'; + code: 'UND_ERR_BPL_MISSING_UPSTREAM'; + } + + export class HTTPParserError extends UndiciError { + name: 'HTTPParserError'; + code: string; + } + + /** The response exceed the length allowed. */ + export class ResponseExceededMaxSizeError extends UndiciError { + name: 'ResponseExceededMaxSizeError'; + code: 'UND_ERR_RES_EXCEEDED_MAX_SIZE'; + } +} diff --git a/backend/node_modules/undici-types/fetch.d.ts b/backend/node_modules/undici-types/fetch.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fa4619c918273983f61cd9b66eb7b80edb5077e1 --- /dev/null +++ b/backend/node_modules/undici-types/fetch.d.ts @@ -0,0 +1,209 @@ +// based on https://github.com/Ethan-Arrowood/undici-fetch/blob/249269714db874351589d2d364a0645d5160ae71/index.d.ts (MIT license) +// and https://github.com/node-fetch/node-fetch/blob/914ce6be5ec67a8bab63d68510aabf07cb818b6d/index.d.ts (MIT license) +/// + +import { Blob } from 'buffer' +import { URL, URLSearchParams } from 'url' +import { ReadableStream } from 'stream/web' +import { FormData } from './formdata' + +import Dispatcher from './dispatcher' + +export type RequestInfo = string | URL | Request + +export declare function fetch ( + input: RequestInfo, + init?: RequestInit +): Promise + +export type BodyInit = + | ArrayBuffer + | AsyncIterable + | Blob + | FormData + | Iterable + | NodeJS.ArrayBufferView + | URLSearchParams + | null + | string + +export interface BodyMixin { + readonly body: ReadableStream | null + readonly bodyUsed: boolean + + readonly arrayBuffer: () => Promise + readonly blob: () => Promise + readonly formData: () => Promise + readonly json: () => Promise + readonly text: () => Promise +} + +export interface SpecIterator { + next(...args: [] | [TNext]): IteratorResult; +} + +export interface SpecIterableIterator extends SpecIterator { + [Symbol.iterator](): SpecIterableIterator; +} + +export interface SpecIterable { + [Symbol.iterator](): SpecIterator; +} + +export type HeadersInit = string[][] | Record> | Headers + +export declare class Headers implements SpecIterable<[string, string]> { + constructor (init?: HeadersInit) + readonly append: (name: string, value: string) => void + readonly delete: (name: string) => void + readonly get: (name: string) => string | null + readonly has: (name: string) => boolean + readonly set: (name: string, value: string) => void + readonly getSetCookie: () => string[] + readonly forEach: ( + callbackfn: (value: string, key: string, iterable: Headers) => void, + thisArg?: unknown + ) => void + + readonly keys: () => SpecIterableIterator + readonly values: () => SpecIterableIterator + readonly entries: () => SpecIterableIterator<[string, string]> + readonly [Symbol.iterator]: () => SpecIterator<[string, string]> +} + +export type RequestCache = + | 'default' + | 'force-cache' + | 'no-cache' + | 'no-store' + | 'only-if-cached' + | 'reload' + +export type RequestCredentials = 'omit' | 'include' | 'same-origin' + +type RequestDestination = + | '' + | 'audio' + | 'audioworklet' + | 'document' + | 'embed' + | 'font' + | 'image' + | 'manifest' + | 'object' + | 'paintworklet' + | 'report' + | 'script' + | 'sharedworker' + | 'style' + | 'track' + | 'video' + | 'worker' + | 'xslt' + +export interface RequestInit { + method?: string + keepalive?: boolean + headers?: HeadersInit + body?: BodyInit + redirect?: RequestRedirect + integrity?: string + signal?: AbortSignal + credentials?: RequestCredentials + mode?: RequestMode + referrer?: string + referrerPolicy?: ReferrerPolicy + window?: null + dispatcher?: Dispatcher + duplex?: RequestDuplex +} + +export type ReferrerPolicy = + | '' + | 'no-referrer' + | 'no-referrer-when-downgrade' + | 'origin' + | 'origin-when-cross-origin' + | 'same-origin' + | 'strict-origin' + | 'strict-origin-when-cross-origin' + | 'unsafe-url'; + +export type RequestMode = 'cors' | 'navigate' | 'no-cors' | 'same-origin' + +export type RequestRedirect = 'error' | 'follow' | 'manual' + +export type RequestDuplex = 'half' + +export declare class Request implements BodyMixin { + constructor (input: RequestInfo, init?: RequestInit) + + readonly cache: RequestCache + readonly credentials: RequestCredentials + readonly destination: RequestDestination + readonly headers: Headers + readonly integrity: string + readonly method: string + readonly mode: RequestMode + readonly redirect: RequestRedirect + readonly referrerPolicy: string + readonly url: string + + readonly keepalive: boolean + readonly signal: AbortSignal + readonly duplex: RequestDuplex + + readonly body: ReadableStream | null + readonly bodyUsed: boolean + + readonly arrayBuffer: () => Promise + readonly blob: () => Promise + readonly formData: () => Promise + readonly json: () => Promise + readonly text: () => Promise + + readonly clone: () => Request +} + +export interface ResponseInit { + readonly status?: number + readonly statusText?: string + readonly headers?: HeadersInit +} + +export type ResponseType = + | 'basic' + | 'cors' + | 'default' + | 'error' + | 'opaque' + | 'opaqueredirect' + +export type ResponseRedirectStatus = 301 | 302 | 303 | 307 | 308 + +export declare class Response implements BodyMixin { + constructor (body?: BodyInit, init?: ResponseInit) + + readonly headers: Headers + readonly ok: boolean + readonly status: number + readonly statusText: string + readonly type: ResponseType + readonly url: string + readonly redirected: boolean + + readonly body: ReadableStream | null + readonly bodyUsed: boolean + + readonly arrayBuffer: () => Promise + readonly blob: () => Promise + readonly formData: () => Promise + readonly json: () => Promise + readonly text: () => Promise + + readonly clone: () => Response + + static error (): Response + static json(data: any, init?: ResponseInit): Response + static redirect (url: string | URL, status: ResponseRedirectStatus): Response +} diff --git a/backend/node_modules/undici-types/file.d.ts b/backend/node_modules/undici-types/file.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c695b7ab0baf87c789f9c78375d8aeef767e1c13 --- /dev/null +++ b/backend/node_modules/undici-types/file.d.ts @@ -0,0 +1,39 @@ +// Based on https://github.com/octet-stream/form-data/blob/2d0f0dc371517444ce1f22cdde13f51995d0953a/lib/File.ts (MIT) +/// + +import { Blob } from 'buffer' + +export interface BlobPropertyBag { + type?: string + endings?: 'native' | 'transparent' +} + +export interface FilePropertyBag extends BlobPropertyBag { + /** + * The last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). Files without a known last modified date return the current date. + */ + lastModified?: number +} + +export declare class File extends Blob { + /** + * Creates a new File instance. + * + * @param fileBits An `Array` strings, or [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer), [`ArrayBufferView`](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView), [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) objects, or a mix of any of such objects, that will be put inside the [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File). + * @param fileName The name of the file. + * @param options An options object containing optional attributes for the file. + */ + constructor(fileBits: ReadonlyArray, fileName: string, options?: FilePropertyBag) + + /** + * Name of the file referenced by the File object. + */ + readonly name: string + + /** + * The last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). Files without a known last modified date return the current date. + */ + readonly lastModified: number + + readonly [Symbol.toStringTag]: string +} diff --git a/backend/node_modules/undici-types/filereader.d.ts b/backend/node_modules/undici-types/filereader.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f05d231b2ffac740e266395655cf33f4aaa259bf --- /dev/null +++ b/backend/node_modules/undici-types/filereader.d.ts @@ -0,0 +1,54 @@ +/// + +import { Blob } from 'buffer' +import { DOMException, Event, EventInit, EventTarget } from './patch' + +export declare class FileReader { + __proto__: EventTarget & FileReader + + constructor () + + readAsArrayBuffer (blob: Blob): void + readAsBinaryString (blob: Blob): void + readAsText (blob: Blob, encoding?: string): void + readAsDataURL (blob: Blob): void + + abort (): void + + static readonly EMPTY = 0 + static readonly LOADING = 1 + static readonly DONE = 2 + + readonly EMPTY = 0 + readonly LOADING = 1 + readonly DONE = 2 + + readonly readyState: number + + readonly result: string | ArrayBuffer | null + + readonly error: DOMException | null + + onloadstart: null | ((this: FileReader, event: ProgressEvent) => void) + onprogress: null | ((this: FileReader, event: ProgressEvent) => void) + onload: null | ((this: FileReader, event: ProgressEvent) => void) + onabort: null | ((this: FileReader, event: ProgressEvent) => void) + onerror: null | ((this: FileReader, event: ProgressEvent) => void) + onloadend: null | ((this: FileReader, event: ProgressEvent) => void) +} + +export interface ProgressEventInit extends EventInit { + lengthComputable?: boolean + loaded?: number + total?: number +} + +export declare class ProgressEvent { + __proto__: Event & ProgressEvent + + constructor (type: string, eventInitDict?: ProgressEventInit) + + readonly lengthComputable: boolean + readonly loaded: number + readonly total: number +} diff --git a/backend/node_modules/undici-types/formdata.d.ts b/backend/node_modules/undici-types/formdata.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..df29a572d6bd4faa0a5b15276501da97b6be1bdf --- /dev/null +++ b/backend/node_modules/undici-types/formdata.d.ts @@ -0,0 +1,108 @@ +// Based on https://github.com/octet-stream/form-data/blob/2d0f0dc371517444ce1f22cdde13f51995d0953a/lib/FormData.ts (MIT) +/// + +import { File } from './file' +import { SpecIterator, SpecIterableIterator } from './fetch' + +/** + * A `string` or `File` that represents a single value from a set of `FormData` key-value pairs. + */ +declare type FormDataEntryValue = string | File + +/** + * Provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using fetch(). + */ +export declare class FormData { + /** + * Appends a new value onto an existing key inside a FormData object, + * or adds the key if it does not already exist. + * + * The difference between `set()` and `append()` is that if the specified key already exists, `set()` will overwrite all existing values with the new one, whereas `append()` will append the new value onto the end of the existing set of values. + * + * @param name The name of the field whose data is contained in `value`. + * @param value The field's value. This can be [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) + or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File). If none of these are specified the value is converted to a string. + * @param fileName The filename reported to the server, when a Blob or File is passed as the second parameter. The default filename for Blob objects is "blob". The default filename for File objects is the file's filename. + */ + append(name: string, value: unknown, fileName?: string): void + + /** + * Set a new value for an existing key inside FormData, + * or add the new field if it does not already exist. + * + * @param name The name of the field whose data is contained in `value`. + * @param value The field's value. This can be [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) + or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File). If none of these are specified the value is converted to a string. + * @param fileName The filename reported to the server, when a Blob or File is passed as the second parameter. The default filename for Blob objects is "blob". The default filename for File objects is the file's filename. + * + */ + set(name: string, value: unknown, fileName?: string): void + + /** + * Returns the first value associated with a given key from within a `FormData` object. + * If you expect multiple values and want all of them, use the `getAll()` method instead. + * + * @param {string} name A name of the value you want to retrieve. + * + * @returns A `FormDataEntryValue` containing the value. If the key doesn't exist, the method returns null. + */ + get(name: string): FormDataEntryValue | null + + /** + * Returns all the values associated with a given key from within a `FormData` object. + * + * @param {string} name A name of the value you want to retrieve. + * + * @returns An array of `FormDataEntryValue` whose key matches the value passed in the `name` parameter. If the key doesn't exist, the method returns an empty list. + */ + getAll(name: string): FormDataEntryValue[] + + /** + * Returns a boolean stating whether a `FormData` object contains a certain key. + * + * @param name A string representing the name of the key you want to test for. + * + * @return A boolean value. + */ + has(name: string): boolean + + /** + * Deletes a key and its value(s) from a `FormData` object. + * + * @param name The name of the key you want to delete. + */ + delete(name: string): void + + /** + * Executes given callback function for each field of the FormData instance + */ + forEach: ( + callbackfn: (value: FormDataEntryValue, key: string, iterable: FormData) => void, + thisArg?: unknown + ) => void + + /** + * Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through all keys contained in this `FormData` object. + * Each key is a `string`. + */ + keys: () => SpecIterableIterator + + /** + * Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through all values contained in this object `FormData` object. + * Each value is a [`FormDataValue`](https://developer.mozilla.org/en-US/docs/Web/API/FormDataEntryValue). + */ + values: () => SpecIterableIterator + + /** + * Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through the `FormData` key/value pairs. + * The key of each pair is a string; the value is a [`FormDataValue`](https://developer.mozilla.org/en-US/docs/Web/API/FormDataEntryValue). + */ + entries: () => SpecIterableIterator<[string, FormDataEntryValue]> + + /** + * An alias for FormData#entries() + */ + [Symbol.iterator]: () => SpecIterableIterator<[string, FormDataEntryValue]> + + readonly [Symbol.toStringTag]: string +} diff --git a/backend/node_modules/undici-types/global-dispatcher.d.ts b/backend/node_modules/undici-types/global-dispatcher.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..728f95ce23ce69871cc896a6fd3aa389eae18d7e --- /dev/null +++ b/backend/node_modules/undici-types/global-dispatcher.d.ts @@ -0,0 +1,9 @@ +import Dispatcher from "./dispatcher"; + +export { + getGlobalDispatcher, + setGlobalDispatcher +} + +declare function setGlobalDispatcher(dispatcher: DispatcherImplementation): void; +declare function getGlobalDispatcher(): Dispatcher; diff --git a/backend/node_modules/undici-types/global-origin.d.ts b/backend/node_modules/undici-types/global-origin.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..322542d66756a763a33427610daa398606cb0c61 --- /dev/null +++ b/backend/node_modules/undici-types/global-origin.d.ts @@ -0,0 +1,7 @@ +export { + setGlobalOrigin, + getGlobalOrigin +} + +declare function setGlobalOrigin(origin: string | URL | undefined): void; +declare function getGlobalOrigin(): URL | undefined; \ No newline at end of file diff --git a/backend/node_modules/undici-types/handlers.d.ts b/backend/node_modules/undici-types/handlers.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..eb4f5a9e8dd209a772d301e4254f3dda6f7516bd --- /dev/null +++ b/backend/node_modules/undici-types/handlers.d.ts @@ -0,0 +1,9 @@ +import Dispatcher from "./dispatcher"; + +export declare class RedirectHandler implements Dispatcher.DispatchHandlers{ + constructor (dispatch: Dispatcher, maxRedirections: number, opts: Dispatcher.DispatchOptions, handler: Dispatcher.DispatchHandlers) +} + +export declare class DecoratorHandler implements Dispatcher.DispatchHandlers{ + constructor (handler: Dispatcher.DispatchHandlers) +} diff --git a/backend/node_modules/undici-types/header.d.ts b/backend/node_modules/undici-types/header.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..bfdb3296d4d1fc2f8f1ddaef0aa75124bd6b08cf --- /dev/null +++ b/backend/node_modules/undici-types/header.d.ts @@ -0,0 +1,4 @@ +/** + * The header type declaration of `undici`. + */ +export type IncomingHttpHeaders = Record; diff --git a/backend/node_modules/undici-types/index.d.ts b/backend/node_modules/undici-types/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4589845b4a9bd247b05449396e1ffff4810b0d27 --- /dev/null +++ b/backend/node_modules/undici-types/index.d.ts @@ -0,0 +1,63 @@ +import Dispatcher from'./dispatcher' +import { setGlobalDispatcher, getGlobalDispatcher } from './global-dispatcher' +import { setGlobalOrigin, getGlobalOrigin } from './global-origin' +import Pool from'./pool' +import { RedirectHandler, DecoratorHandler } from './handlers' + +import BalancedPool from './balanced-pool' +import Client from'./client' +import buildConnector from'./connector' +import errors from'./errors' +import Agent from'./agent' +import MockClient from'./mock-client' +import MockPool from'./mock-pool' +import MockAgent from'./mock-agent' +import mockErrors from'./mock-errors' +import ProxyAgent from'./proxy-agent' +import { request, pipeline, stream, connect, upgrade } from './api' + +export * from './cookies' +export * from './fetch' +export * from './file' +export * from './filereader' +export * from './formdata' +export * from './diagnostics-channel' +export * from './websocket' +export * from './content-type' +export * from './cache' +export { Interceptable } from './mock-interceptor' + +export { Dispatcher, BalancedPool, Pool, Client, buildConnector, errors, Agent, request, stream, pipeline, connect, upgrade, setGlobalDispatcher, getGlobalDispatcher, setGlobalOrigin, getGlobalOrigin, MockClient, MockPool, MockAgent, mockErrors, ProxyAgent, RedirectHandler, DecoratorHandler } +export default Undici + +declare namespace Undici { + var Dispatcher: typeof import('./dispatcher').default + var Pool: typeof import('./pool').default; + var RedirectHandler: typeof import ('./handlers').RedirectHandler + var DecoratorHandler: typeof import ('./handlers').DecoratorHandler + var createRedirectInterceptor: typeof import ('./interceptors').createRedirectInterceptor + var BalancedPool: typeof import('./balanced-pool').default; + var Client: typeof import('./client').default; + var buildConnector: typeof import('./connector').default; + var errors: typeof import('./errors').default; + var Agent: typeof import('./agent').default; + var setGlobalDispatcher: typeof import('./global-dispatcher').setGlobalDispatcher; + var getGlobalDispatcher: typeof import('./global-dispatcher').getGlobalDispatcher; + var request: typeof import('./api').request; + var stream: typeof import('./api').stream; + var pipeline: typeof import('./api').pipeline; + var connect: typeof import('./api').connect; + var upgrade: typeof import('./api').upgrade; + var MockClient: typeof import('./mock-client').default; + var MockPool: typeof import('./mock-pool').default; + var MockAgent: typeof import('./mock-agent').default; + var mockErrors: typeof import('./mock-errors').default; + var fetch: typeof import('./fetch').fetch; + var Headers: typeof import('./fetch').Headers; + var Response: typeof import('./fetch').Response; + var Request: typeof import('./fetch').Request; + var FormData: typeof import('./formdata').FormData; + var File: typeof import('./file').File; + var FileReader: typeof import('./filereader').FileReader; + var caches: typeof import('./cache').caches; +} diff --git a/backend/node_modules/undici-types/interceptors.d.ts b/backend/node_modules/undici-types/interceptors.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..047ac175d5005ff9f3ec48def2f87ff159a69245 --- /dev/null +++ b/backend/node_modules/undici-types/interceptors.d.ts @@ -0,0 +1,5 @@ +import Dispatcher from "./dispatcher"; + +type RedirectInterceptorOpts = { maxRedirections?: number } + +export declare function createRedirectInterceptor (opts: RedirectInterceptorOpts): Dispatcher.DispatchInterceptor diff --git a/backend/node_modules/undici-types/mock-agent.d.ts b/backend/node_modules/undici-types/mock-agent.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..98cd645b29bd16d1c25f2ed55327aef8ab27b93a --- /dev/null +++ b/backend/node_modules/undici-types/mock-agent.d.ts @@ -0,0 +1,50 @@ +import Agent from './agent' +import Dispatcher from './dispatcher' +import { Interceptable, MockInterceptor } from './mock-interceptor' +import MockDispatch = MockInterceptor.MockDispatch; + +export default MockAgent + +interface PendingInterceptor extends MockDispatch { + origin: string; +} + +/** A mocked Agent class that implements the Agent API. It allows one to intercept HTTP requests made through undici and return mocked responses instead. */ +declare class MockAgent extends Dispatcher { + constructor(options?: MockAgent.Options) + /** Creates and retrieves mock Dispatcher instances which can then be used to intercept HTTP requests. If the number of connections on the mock agent is set to 1, a MockClient instance is returned. Otherwise a MockPool instance is returned. */ + get(origin: string): TInterceptable; + get(origin: RegExp): TInterceptable; + get(origin: ((origin: string) => boolean)): TInterceptable; + /** Dispatches a mocked request. */ + dispatch(options: Agent.DispatchOptions, handler: Dispatcher.DispatchHandlers): boolean; + /** Closes the mock agent and waits for registered mock pools and clients to also close before resolving. */ + close(): Promise; + /** Disables mocking in MockAgent. */ + deactivate(): void; + /** Enables mocking in a MockAgent instance. When instantiated, a MockAgent is automatically activated. Therefore, this method is only effective after `MockAgent.deactivate` has been called. */ + activate(): void; + /** Define host matchers so only matching requests that aren't intercepted by the mock dispatchers will be attempted. */ + enableNetConnect(): void; + enableNetConnect(host: string): void; + enableNetConnect(host: RegExp): void; + enableNetConnect(host: ((host: string) => boolean)): void; + /** Causes all requests to throw when requests are not matched in a MockAgent intercept. */ + disableNetConnect(): void; + pendingInterceptors(): PendingInterceptor[]; + assertNoPendingInterceptors(options?: { + pendingInterceptorsFormatter?: PendingInterceptorsFormatter; + }): void; +} + +interface PendingInterceptorsFormatter { + format(pendingInterceptors: readonly PendingInterceptor[]): string; +} + +declare namespace MockAgent { + /** MockAgent options. */ + export interface Options extends Agent.Options { + /** A custom agent to be encapsulated by the MockAgent. */ + agent?: Agent; + } +} diff --git a/backend/node_modules/undici-types/mock-client.d.ts b/backend/node_modules/undici-types/mock-client.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..51d008cc11c5cb2a50bfadd2dde680d71980bb77 --- /dev/null +++ b/backend/node_modules/undici-types/mock-client.d.ts @@ -0,0 +1,25 @@ +import Client from './client' +import Dispatcher from './dispatcher' +import MockAgent from './mock-agent' +import { MockInterceptor, Interceptable } from './mock-interceptor' + +export default MockClient + +/** MockClient extends the Client API and allows one to mock requests. */ +declare class MockClient extends Client implements Interceptable { + constructor(origin: string, options: MockClient.Options); + /** Intercepts any matching requests that use the same origin as this mock client. */ + intercept(options: MockInterceptor.Options): MockInterceptor; + /** Dispatches a mocked request. */ + dispatch(options: Dispatcher.DispatchOptions, handlers: Dispatcher.DispatchHandlers): boolean; + /** Closes the mock client and gracefully waits for enqueued requests to complete. */ + close(): Promise; +} + +declare namespace MockClient { + /** MockClient options. */ + export interface Options extends Client.Options { + /** The agent to associate this MockClient with. */ + agent: MockAgent; + } +} diff --git a/backend/node_modules/undici-types/mock-errors.d.ts b/backend/node_modules/undici-types/mock-errors.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3d9e727d70a46a2c3a8c43d1cd2a5beeb60793eb --- /dev/null +++ b/backend/node_modules/undici-types/mock-errors.d.ts @@ -0,0 +1,12 @@ +import Errors from './errors' + +export default MockErrors + +declare namespace MockErrors { + /** The request does not match any registered mock dispatches. */ + export class MockNotMatchedError extends Errors.UndiciError { + constructor(message?: string); + name: 'MockNotMatchedError'; + code: 'UND_MOCK_ERR_MOCK_NOT_MATCHED'; + } +} diff --git a/backend/node_modules/undici-types/mock-interceptor.d.ts b/backend/node_modules/undici-types/mock-interceptor.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6b3961c04829278add6d836644959c5999805664 --- /dev/null +++ b/backend/node_modules/undici-types/mock-interceptor.d.ts @@ -0,0 +1,93 @@ +import { IncomingHttpHeaders } from './header' +import Dispatcher from './dispatcher'; +import { BodyInit, Headers } from './fetch' + +export { + Interceptable, + MockInterceptor, + MockScope +} + +/** The scope associated with a mock dispatch. */ +declare class MockScope { + constructor(mockDispatch: MockInterceptor.MockDispatch); + /** Delay a reply by a set amount of time in ms. */ + delay(waitInMs: number): MockScope; + /** Persist the defined mock data for the associated reply. It will return the defined mock data indefinitely. */ + persist(): MockScope; + /** Define a reply for a set amount of matching requests. */ + times(repeatTimes: number): MockScope; +} + +/** The interceptor for a Mock. */ +declare class MockInterceptor { + constructor(options: MockInterceptor.Options, mockDispatches: MockInterceptor.MockDispatch[]); + /** Mock an undici request with the defined reply. */ + reply(replyOptionsCallback: MockInterceptor.MockReplyOptionsCallback): MockScope; + reply( + statusCode: number, + data?: TData | Buffer | string | MockInterceptor.MockResponseDataHandler, + responseOptions?: MockInterceptor.MockResponseOptions + ): MockScope; + /** Mock an undici request by throwing the defined reply error. */ + replyWithError(error: TError): MockScope; + /** Set default reply headers on the interceptor for subsequent mocked replies. */ + defaultReplyHeaders(headers: IncomingHttpHeaders): MockInterceptor; + /** Set default reply trailers on the interceptor for subsequent mocked replies. */ + defaultReplyTrailers(trailers: Record): MockInterceptor; + /** Set automatically calculated content-length header on subsequent mocked replies. */ + replyContentLength(): MockInterceptor; +} + +declare namespace MockInterceptor { + /** MockInterceptor options. */ + export interface Options { + /** Path to intercept on. */ + path: string | RegExp | ((path: string) => boolean); + /** Method to intercept on. Defaults to GET. */ + method?: string | RegExp | ((method: string) => boolean); + /** Body to intercept on. */ + body?: string | RegExp | ((body: string) => boolean); + /** Headers to intercept on. */ + headers?: Record boolean)> | ((headers: Record) => boolean); + /** Query params to intercept on */ + query?: Record; + } + export interface MockDispatch extends Options { + times: number | null; + persist: boolean; + consumed: boolean; + data: MockDispatchData; + } + export interface MockDispatchData extends MockResponseOptions { + error: TError | null; + statusCode?: number; + data?: TData | string; + } + export interface MockResponseOptions { + headers?: IncomingHttpHeaders; + trailers?: Record; + } + + export interface MockResponseCallbackOptions { + path: string; + origin: string; + method: string; + body?: BodyInit | Dispatcher.DispatchOptions['body']; + headers: Headers | Record; + maxRedirections: number; + } + + export type MockResponseDataHandler = ( + opts: MockResponseCallbackOptions + ) => TData | Buffer | string; + + export type MockReplyOptionsCallback = ( + opts: MockResponseCallbackOptions + ) => { statusCode: number, data?: TData | Buffer | string, responseOptions?: MockResponseOptions } +} + +interface Interceptable extends Dispatcher { + /** Intercepts any matching requests that use the same origin as this mock client. */ + intercept(options: MockInterceptor.Options): MockInterceptor; +} diff --git a/backend/node_modules/undici-types/mock-pool.d.ts b/backend/node_modules/undici-types/mock-pool.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..39e709aaf69a2c3ce2c173b8d908d5ffb6a175f5 --- /dev/null +++ b/backend/node_modules/undici-types/mock-pool.d.ts @@ -0,0 +1,25 @@ +import Pool from './pool' +import MockAgent from './mock-agent' +import { Interceptable, MockInterceptor } from './mock-interceptor' +import Dispatcher from './dispatcher' + +export default MockPool + +/** MockPool extends the Pool API and allows one to mock requests. */ +declare class MockPool extends Pool implements Interceptable { + constructor(origin: string, options: MockPool.Options); + /** Intercepts any matching requests that use the same origin as this mock pool. */ + intercept(options: MockInterceptor.Options): MockInterceptor; + /** Dispatches a mocked request. */ + dispatch(options: Dispatcher.DispatchOptions, handlers: Dispatcher.DispatchHandlers): boolean; + /** Closes the mock pool and gracefully waits for enqueued requests to complete. */ + close(): Promise; +} + +declare namespace MockPool { + /** MockPool options. */ + export interface Options extends Pool.Options { + /** The agent to associate this MockPool with. */ + agent: MockAgent; + } +} diff --git a/backend/node_modules/undici-types/package.json b/backend/node_modules/undici-types/package.json new file mode 100644 index 0000000000000000000000000000000000000000..be7aa4cd5143f86a49c08c3859ca1acf5beb2a5b --- /dev/null +++ b/backend/node_modules/undici-types/package.json @@ -0,0 +1,55 @@ +{ + "name": "undici-types", + "version": "5.26.5", + "description": "A stand-alone types package for Undici", + "homepage": "https://undici.nodejs.org", + "bugs": { + "url": "https://github.com/nodejs/undici/issues" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/nodejs/undici.git" + }, + "license": "MIT", + "types": "index.d.ts", + "files": [ + "*.d.ts" + ], + "contributors": [ + { + "name": "Daniele Belardi", + "url": "https://github.com/dnlup", + "author": true + }, + { + "name": "Ethan Arrowood", + "url": "https://github.com/ethan-arrowood", + "author": true + }, + { + "name": "Matteo Collina", + "url": "https://github.com/mcollina", + "author": true + }, + { + "name": "Matthew Aitken", + "url": "https://github.com/KhafraDev", + "author": true + }, + { + "name": "Robert Nagy", + "url": "https://github.com/ronag", + "author": true + }, + { + "name": "Szymon Marczak", + "url": "https://github.com/szmarczak", + "author": true + }, + { + "name": "Tomas Della Vedova", + "url": "https://github.com/delvedor", + "author": true + } + ] +} \ No newline at end of file diff --git a/backend/node_modules/undici-types/patch.d.ts b/backend/node_modules/undici-types/patch.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3871acfebc658acce853af52e9d54366b0180268 --- /dev/null +++ b/backend/node_modules/undici-types/patch.d.ts @@ -0,0 +1,71 @@ +/// + +// See https://github.com/nodejs/undici/issues/1740 + +export type DOMException = typeof globalThis extends { DOMException: infer T } + ? T + : any + +export type EventTarget = typeof globalThis extends { EventTarget: infer T } + ? T + : { + addEventListener( + type: string, + listener: any, + options?: any, + ): void + dispatchEvent(event: Event): boolean + removeEventListener( + type: string, + listener: any, + options?: any | boolean, + ): void + } + +export type Event = typeof globalThis extends { Event: infer T } + ? T + : { + readonly bubbles: boolean + cancelBubble: () => void + readonly cancelable: boolean + readonly composed: boolean + composedPath(): [EventTarget?] + readonly currentTarget: EventTarget | null + readonly defaultPrevented: boolean + readonly eventPhase: 0 | 2 + readonly isTrusted: boolean + preventDefault(): void + returnValue: boolean + readonly srcElement: EventTarget | null + stopImmediatePropagation(): void + stopPropagation(): void + readonly target: EventTarget | null + readonly timeStamp: number + readonly type: string + } + +export interface EventInit { + bubbles?: boolean + cancelable?: boolean + composed?: boolean +} + +export interface EventListenerOptions { + capture?: boolean +} + +export interface AddEventListenerOptions extends EventListenerOptions { + once?: boolean + passive?: boolean + signal?: AbortSignal +} + +export type EventListenerOrEventListenerObject = EventListener | EventListenerObject + +export interface EventListenerObject { + handleEvent (object: Event): void +} + +export interface EventListener { + (evt: Event): void +} diff --git a/backend/node_modules/undici-types/pool-stats.d.ts b/backend/node_modules/undici-types/pool-stats.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8b6d2bff4ad41652396d53aaca5d49ce836a7118 --- /dev/null +++ b/backend/node_modules/undici-types/pool-stats.d.ts @@ -0,0 +1,19 @@ +import Pool from "./pool" + +export default PoolStats + +declare class PoolStats { + constructor(pool: Pool); + /** Number of open socket connections in this pool. */ + connected: number; + /** Number of open socket connections in this pool that do not have an active request. */ + free: number; + /** Number of pending requests across all clients in this pool. */ + pending: number; + /** Number of queued requests across all clients in this pool. */ + queued: number; + /** Number of currently active requests across all clients in this pool. */ + running: number; + /** Number of active, pending, or queued requests across all clients in this pool. */ + size: number; +} diff --git a/backend/node_modules/undici-types/pool.d.ts b/backend/node_modules/undici-types/pool.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7747d48261ba84c0ca30293bdc1f5bd41ecc3a98 --- /dev/null +++ b/backend/node_modules/undici-types/pool.d.ts @@ -0,0 +1,28 @@ +import Client from './client' +import TPoolStats from './pool-stats' +import { URL } from 'url' +import Dispatcher from "./dispatcher"; + +export default Pool + +declare class Pool extends Dispatcher { + constructor(url: string | URL, options?: Pool.Options) + /** `true` after `pool.close()` has been called. */ + closed: boolean; + /** `true` after `pool.destroyed()` has been called or `pool.close()` has been called and the pool shutdown has completed. */ + destroyed: boolean; + /** Aggregate stats for a Pool. */ + readonly stats: TPoolStats; +} + +declare namespace Pool { + export type PoolStats = TPoolStats; + export interface Options extends Client.Options { + /** Default: `(origin, opts) => new Client(origin, opts)`. */ + factory?(origin: URL, opts: object): Dispatcher; + /** The max number of clients to create. `null` if no limit. Default `null`. */ + connections?: number | null; + + interceptors?: { Pool?: readonly Dispatcher.DispatchInterceptor[] } & Client.Options["interceptors"] + } +} diff --git a/backend/node_modules/undici-types/proxy-agent.d.ts b/backend/node_modules/undici-types/proxy-agent.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..96b26381ced5df4b4873b3247db2782341f1b357 --- /dev/null +++ b/backend/node_modules/undici-types/proxy-agent.d.ts @@ -0,0 +1,30 @@ +import Agent from './agent' +import buildConnector from './connector'; +import Client from './client' +import Dispatcher from './dispatcher' +import { IncomingHttpHeaders } from './header' +import Pool from './pool' + +export default ProxyAgent + +declare class ProxyAgent extends Dispatcher { + constructor(options: ProxyAgent.Options | string) + + dispatch(options: Agent.DispatchOptions, handler: Dispatcher.DispatchHandlers): boolean; + close(): Promise; +} + +declare namespace ProxyAgent { + export interface Options extends Agent.Options { + uri: string; + /** + * @deprecated use opts.token + */ + auth?: string; + token?: string; + headers?: IncomingHttpHeaders; + requestTls?: buildConnector.BuildOptions; + proxyTls?: buildConnector.BuildOptions; + clientFactory?(origin: URL, opts: object): Dispatcher; + } +} diff --git a/backend/node_modules/undici-types/readable.d.ts b/backend/node_modules/undici-types/readable.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4549a8c87e818ca016e2560e03e4aaf1e14c0502 --- /dev/null +++ b/backend/node_modules/undici-types/readable.d.ts @@ -0,0 +1,61 @@ +import { Readable } from "stream"; +import { Blob } from 'buffer' + +export default BodyReadable + +declare class BodyReadable extends Readable { + constructor( + resume?: (this: Readable, size: number) => void | null, + abort?: () => void | null, + contentType?: string + ) + + /** Consumes and returns the body as a string + * https://fetch.spec.whatwg.org/#dom-body-text + */ + text(): Promise + + /** Consumes and returns the body as a JavaScript Object + * https://fetch.spec.whatwg.org/#dom-body-json + */ + json(): Promise + + /** Consumes and returns the body as a Blob + * https://fetch.spec.whatwg.org/#dom-body-blob + */ + blob(): Promise + + /** Consumes and returns the body as an ArrayBuffer + * https://fetch.spec.whatwg.org/#dom-body-arraybuffer + */ + arrayBuffer(): Promise + + /** Not implemented + * + * https://fetch.spec.whatwg.org/#dom-body-formdata + */ + formData(): Promise + + /** Returns true if the body is not null and the body has been consumed + * + * Otherwise, returns false + * + * https://fetch.spec.whatwg.org/#dom-body-bodyused + */ + readonly bodyUsed: boolean + + /** Throws on node 16.6.0 + * + * If body is null, it should return null as the body + * + * If body is not null, should return the body as a ReadableStream + * + * https://fetch.spec.whatwg.org/#dom-body-body + */ + readonly body: never | undefined + + /** Dumps the response body by reading `limit` number of bytes. + * @param opts.limit Number of bytes to read (optional) - Default: 262144 + */ + dump(opts?: { limit: number }): Promise +} diff --git a/backend/node_modules/undici-types/webidl.d.ts b/backend/node_modules/undici-types/webidl.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..40cfe064f8fc33e4ff1138f1afdb4555857d3d73 --- /dev/null +++ b/backend/node_modules/undici-types/webidl.d.ts @@ -0,0 +1,220 @@ +// These types are not exported, and are only used internally + +/** + * Take in an unknown value and return one that is of type T + */ +type Converter = (object: unknown) => T + +type SequenceConverter = (object: unknown) => T[] + +type RecordConverter = (object: unknown) => Record + +interface ConvertToIntOpts { + clamp?: boolean + enforceRange?: boolean +} + +interface WebidlErrors { + exception (opts: { header: string, message: string }): TypeError + /** + * @description Throw an error when conversion from one type to another has failed + */ + conversionFailed (opts: { + prefix: string + argument: string + types: string[] + }): TypeError + /** + * @description Throw an error when an invalid argument is provided + */ + invalidArgument (opts: { + prefix: string + value: string + type: string + }): TypeError +} + +interface WebidlUtil { + /** + * @see https://tc39.es/ecma262/#sec-ecmascript-data-types-and-values + */ + Type (object: unknown): + | 'Undefined' + | 'Boolean' + | 'String' + | 'Symbol' + | 'Number' + | 'BigInt' + | 'Null' + | 'Object' + + /** + * @see https://webidl.spec.whatwg.org/#abstract-opdef-converttoint + */ + ConvertToInt ( + V: unknown, + bitLength: number, + signedness: 'signed' | 'unsigned', + opts?: ConvertToIntOpts + ): number + + /** + * @see https://webidl.spec.whatwg.org/#abstract-opdef-converttoint + */ + IntegerPart (N: number): number +} + +interface WebidlConverters { + /** + * @see https://webidl.spec.whatwg.org/#es-DOMString + */ + DOMString (V: unknown, opts?: { + legacyNullToEmptyString: boolean + }): string + + /** + * @see https://webidl.spec.whatwg.org/#es-ByteString + */ + ByteString (V: unknown): string + + /** + * @see https://webidl.spec.whatwg.org/#es-USVString + */ + USVString (V: unknown): string + + /** + * @see https://webidl.spec.whatwg.org/#es-boolean + */ + boolean (V: unknown): boolean + + /** + * @see https://webidl.spec.whatwg.org/#es-any + */ + any (V: Value): Value + + /** + * @see https://webidl.spec.whatwg.org/#es-long-long + */ + ['long long'] (V: unknown): number + + /** + * @see https://webidl.spec.whatwg.org/#es-unsigned-long-long + */ + ['unsigned long long'] (V: unknown): number + + /** + * @see https://webidl.spec.whatwg.org/#es-unsigned-long + */ + ['unsigned long'] (V: unknown): number + + /** + * @see https://webidl.spec.whatwg.org/#es-unsigned-short + */ + ['unsigned short'] (V: unknown, opts?: ConvertToIntOpts): number + + /** + * @see https://webidl.spec.whatwg.org/#idl-ArrayBuffer + */ + ArrayBuffer (V: unknown): ArrayBufferLike + ArrayBuffer (V: unknown, opts: { allowShared: false }): ArrayBuffer + + /** + * @see https://webidl.spec.whatwg.org/#es-buffer-source-types + */ + TypedArray ( + V: unknown, + TypedArray: NodeJS.TypedArray | ArrayBufferLike + ): NodeJS.TypedArray | ArrayBufferLike + TypedArray ( + V: unknown, + TypedArray: NodeJS.TypedArray | ArrayBufferLike, + opts?: { allowShared: false } + ): NodeJS.TypedArray | ArrayBuffer + + /** + * @see https://webidl.spec.whatwg.org/#es-buffer-source-types + */ + DataView (V: unknown, opts?: { allowShared: boolean }): DataView + + /** + * @see https://webidl.spec.whatwg.org/#BufferSource + */ + BufferSource ( + V: unknown, + opts?: { allowShared: boolean } + ): NodeJS.TypedArray | ArrayBufferLike | DataView + + ['sequence']: SequenceConverter + + ['sequence>']: SequenceConverter + + ['record']: RecordConverter + + [Key: string]: (...args: any[]) => unknown +} + +export interface Webidl { + errors: WebidlErrors + util: WebidlUtil + converters: WebidlConverters + + /** + * @description Performs a brand-check on {@param V} to ensure it is a + * {@param cls} object. + */ + brandCheck (V: unknown, cls: Interface, opts?: { strict?: boolean }): asserts V is Interface + + /** + * @see https://webidl.spec.whatwg.org/#es-sequence + * @description Convert a value, V, to a WebIDL sequence type. + */ + sequenceConverter (C: Converter): SequenceConverter + + illegalConstructor (): never + + /** + * @see https://webidl.spec.whatwg.org/#es-to-record + * @description Convert a value, V, to a WebIDL record type. + */ + recordConverter ( + keyConverter: Converter, + valueConverter: Converter + ): RecordConverter + + /** + * Similar to {@link Webidl.brandCheck} but allows skipping the check if third party + * interfaces are allowed. + */ + interfaceConverter (cls: Interface): ( + V: unknown, + opts?: { strict: boolean } + ) => asserts V is typeof cls + + // TODO(@KhafraDev): a type could likely be implemented that can infer the return type + // from the converters given? + /** + * Converts a value, V, to a WebIDL dictionary types. Allows limiting which keys are + * allowed, values allowed, optional and required keys. Auto converts the value to + * a type given a converter. + */ + dictionaryConverter (converters: { + key: string, + defaultValue?: unknown, + required?: boolean, + converter: (...args: unknown[]) => unknown, + allowedValues?: unknown[] + }[]): (V: unknown) => Record + + /** + * @see https://webidl.spec.whatwg.org/#idl-nullable-type + * @description allows a type, V, to be null + */ + nullableConverter ( + converter: Converter + ): (V: unknown) => ReturnType | null + + argumentLengthCheck (args: { length: number }, min: number, context: { + header: string + message?: string + }): void +} diff --git a/backend/node_modules/undici-types/websocket.d.ts b/backend/node_modules/undici-types/websocket.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..15a357d36d55b58e53bd179771114dd478cefd96 --- /dev/null +++ b/backend/node_modules/undici-types/websocket.d.ts @@ -0,0 +1,131 @@ +/// + +import type { Blob } from 'buffer' +import type { MessagePort } from 'worker_threads' +import { + EventTarget, + Event, + EventInit, + EventListenerOptions, + AddEventListenerOptions, + EventListenerOrEventListenerObject +} from './patch' +import Dispatcher from './dispatcher' +import { HeadersInit } from './fetch' + +export type BinaryType = 'blob' | 'arraybuffer' + +interface WebSocketEventMap { + close: CloseEvent + error: Event + message: MessageEvent + open: Event +} + +interface WebSocket extends EventTarget { + binaryType: BinaryType + + readonly bufferedAmount: number + readonly extensions: string + + onclose: ((this: WebSocket, ev: WebSocketEventMap['close']) => any) | null + onerror: ((this: WebSocket, ev: WebSocketEventMap['error']) => any) | null + onmessage: ((this: WebSocket, ev: WebSocketEventMap['message']) => any) | null + onopen: ((this: WebSocket, ev: WebSocketEventMap['open']) => any) | null + + readonly protocol: string + readonly readyState: number + readonly url: string + + close(code?: number, reason?: string): void + send(data: string | ArrayBufferLike | Blob | ArrayBufferView): void + + readonly CLOSED: number + readonly CLOSING: number + readonly CONNECTING: number + readonly OPEN: number + + addEventListener( + type: K, + listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, + options?: boolean | AddEventListenerOptions + ): void + addEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | AddEventListenerOptions + ): void + removeEventListener( + type: K, + listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, + options?: boolean | EventListenerOptions + ): void + removeEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | EventListenerOptions + ): void +} + +export declare const WebSocket: { + prototype: WebSocket + new (url: string | URL, protocols?: string | string[] | WebSocketInit): WebSocket + readonly CLOSED: number + readonly CLOSING: number + readonly CONNECTING: number + readonly OPEN: number +} + +interface CloseEventInit extends EventInit { + code?: number + reason?: string + wasClean?: boolean +} + +interface CloseEvent extends Event { + readonly code: number + readonly reason: string + readonly wasClean: boolean +} + +export declare const CloseEvent: { + prototype: CloseEvent + new (type: string, eventInitDict?: CloseEventInit): CloseEvent +} + +interface MessageEventInit extends EventInit { + data?: T + lastEventId?: string + origin?: string + ports?: (typeof MessagePort)[] + source?: typeof MessagePort | null +} + +interface MessageEvent extends Event { + readonly data: T + readonly lastEventId: string + readonly origin: string + readonly ports: ReadonlyArray + readonly source: typeof MessagePort | null + initMessageEvent( + type: string, + bubbles?: boolean, + cancelable?: boolean, + data?: any, + origin?: string, + lastEventId?: string, + source?: typeof MessagePort | null, + ports?: (typeof MessagePort)[] + ): void; +} + +export declare const MessageEvent: { + prototype: MessageEvent + new(type: string, eventInitDict?: MessageEventInit): MessageEvent +} + +interface WebSocketInit { + protocols?: string | string[], + dispatcher?: Dispatcher, + headers?: HeadersInit +} diff --git a/backend/node_modules/unpipe/HISTORY.md b/backend/node_modules/unpipe/HISTORY.md new file mode 100644 index 0000000000000000000000000000000000000000..85e0f8d747dc2a960e1ae6640c8bf081631ac0ec --- /dev/null +++ b/backend/node_modules/unpipe/HISTORY.md @@ -0,0 +1,4 @@ +1.0.0 / 2015-06-14 +================== + + * Initial release diff --git a/backend/node_modules/unpipe/LICENSE b/backend/node_modules/unpipe/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..aed0138278a940d6e7b2d43903e04eee233b957e --- /dev/null +++ b/backend/node_modules/unpipe/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/backend/node_modules/unpipe/README.md b/backend/node_modules/unpipe/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e536ad2c045bba26e9d1f93202a44833656adfad --- /dev/null +++ b/backend/node_modules/unpipe/README.md @@ -0,0 +1,43 @@ +# unpipe + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Unpipe a stream from all destinations. + +## Installation + +```sh +$ npm install unpipe +``` + +## API + +```js +var unpipe = require('unpipe') +``` + +### unpipe(stream) + +Unpipes all destinations from a given stream. With stream 2+, this is +equivalent to `stream.unpipe()`. When used with streams 1 style streams +(typically Node.js 0.8 and below), this module attempts to undo the +actions done in `stream.pipe(dest)`. + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/unpipe.svg +[npm-url]: https://npmjs.org/package/unpipe +[node-image]: https://img.shields.io/node/v/unpipe.svg +[node-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/stream-utils/unpipe.svg +[travis-url]: https://travis-ci.org/stream-utils/unpipe +[coveralls-image]: https://img.shields.io/coveralls/stream-utils/unpipe.svg +[coveralls-url]: https://coveralls.io/r/stream-utils/unpipe?branch=master +[downloads-image]: https://img.shields.io/npm/dm/unpipe.svg +[downloads-url]: https://npmjs.org/package/unpipe diff --git a/backend/node_modules/unpipe/index.js b/backend/node_modules/unpipe/index.js new file mode 100644 index 0000000000000000000000000000000000000000..15c3d97a12b484c2a1c9735e24c952c3079876d0 --- /dev/null +++ b/backend/node_modules/unpipe/index.js @@ -0,0 +1,69 @@ +/*! + * unpipe + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = unpipe + +/** + * Determine if there are Node.js pipe-like data listeners. + * @private + */ + +function hasPipeDataListeners(stream) { + var listeners = stream.listeners('data') + + for (var i = 0; i < listeners.length; i++) { + if (listeners[i].name === 'ondata') { + return true + } + } + + return false +} + +/** + * Unpipe a stream from all destinations. + * + * @param {object} stream + * @public + */ + +function unpipe(stream) { + if (!stream) { + throw new TypeError('argument stream is required') + } + + if (typeof stream.unpipe === 'function') { + // new-style + stream.unpipe() + return + } + + // Node.js 0.8 hack + if (!hasPipeDataListeners(stream)) { + return + } + + var listener + var listeners = stream.listeners('close') + + for (var i = 0; i < listeners.length; i++) { + listener = listeners[i] + + if (listener.name !== 'cleanup' && listener.name !== 'onclose') { + continue + } + + // invoke the listener + listener.call(stream) + } +} diff --git a/backend/node_modules/unpipe/package.json b/backend/node_modules/unpipe/package.json new file mode 100644 index 0000000000000000000000000000000000000000..a2b73583bd6e39d785dc00256bd162c4fe2564e7 --- /dev/null +++ b/backend/node_modules/unpipe/package.json @@ -0,0 +1,27 @@ +{ + "name": "unpipe", + "description": "Unpipe a stream from all destinations", + "version": "1.0.0", + "author": "Douglas Christopher Wilson ", + "license": "MIT", + "repository": "stream-utils/unpipe", + "devDependencies": { + "istanbul": "0.3.15", + "mocha": "2.2.5", + "readable-stream": "1.1.13" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + } +} diff --git a/backend/node_modules/util-deprecate/History.md b/backend/node_modules/util-deprecate/History.md new file mode 100644 index 0000000000000000000000000000000000000000..acc8675372e980824723cfcfec09c0ba43a3195a --- /dev/null +++ b/backend/node_modules/util-deprecate/History.md @@ -0,0 +1,16 @@ + +1.0.2 / 2015-10-07 +================== + + * use try/catch when checking `localStorage` (#3, @kumavis) + +1.0.1 / 2014-11-25 +================== + + * browser: use `console.warn()` for deprecation calls + * browser: more jsdocs + +1.0.0 / 2014-04-30 +================== + + * initial commit diff --git a/backend/node_modules/util-deprecate/LICENSE b/backend/node_modules/util-deprecate/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..6a60e8c225c9baca25907f87c74b428e5d85de0c --- /dev/null +++ b/backend/node_modules/util-deprecate/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2014 Nathan Rajlich + +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/backend/node_modules/util-deprecate/README.md b/backend/node_modules/util-deprecate/README.md new file mode 100644 index 0000000000000000000000000000000000000000..75622fa7c250a6605f4778d9dffe97bf60291d17 --- /dev/null +++ b/backend/node_modules/util-deprecate/README.md @@ -0,0 +1,53 @@ +util-deprecate +============== +### The Node.js `util.deprecate()` function with browser support + +In Node.js, this module simply re-exports the `util.deprecate()` function. + +In the web browser (i.e. via browserify), a browser-specific implementation +of the `util.deprecate()` function is used. + + +## API + +A `deprecate()` function is the only thing exposed by this module. + +``` javascript +// setup: +exports.foo = deprecate(foo, 'foo() is deprecated, use bar() instead'); + + +// users see: +foo(); +// foo() is deprecated, use bar() instead +foo(); +foo(); +``` + + +## License + +(The MIT License) + +Copyright (c) 2014 Nathan Rajlich + +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/backend/node_modules/util-deprecate/browser.js b/backend/node_modules/util-deprecate/browser.js new file mode 100644 index 0000000000000000000000000000000000000000..549ae2f065ea5add2c4b3667e412a9d0e7d2b1af --- /dev/null +++ b/backend/node_modules/util-deprecate/browser.js @@ -0,0 +1,67 @@ + +/** + * Module exports. + */ + +module.exports = deprecate; + +/** + * Mark that a method should not be used. + * Returns a modified function which warns once by default. + * + * If `localStorage.noDeprecation = true` is set, then it is a no-op. + * + * If `localStorage.throwDeprecation = true` is set, then deprecated functions + * will throw an Error when invoked. + * + * If `localStorage.traceDeprecation = true` is set, then deprecated functions + * will invoke `console.trace()` instead of `console.error()`. + * + * @param {Function} fn - the function to deprecate + * @param {String} msg - the string to print to the console when `fn` is invoked + * @returns {Function} a new "deprecated" version of `fn` + * @api public + */ + +function deprecate (fn, msg) { + if (config('noDeprecation')) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (config('throwDeprecation')) { + throw new Error(msg); + } else if (config('traceDeprecation')) { + console.trace(msg); + } else { + console.warn(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; +} + +/** + * Checks `localStorage` for boolean values for the given `name`. + * + * @param {String} name + * @returns {Boolean} + * @api private + */ + +function config (name) { + // accessing global.localStorage can trigger a DOMException in sandboxed iframes + try { + if (!global.localStorage) return false; + } catch (_) { + return false; + } + var val = global.localStorage[name]; + if (null == val) return false; + return String(val).toLowerCase() === 'true'; +} diff --git a/backend/node_modules/util-deprecate/node.js b/backend/node_modules/util-deprecate/node.js new file mode 100644 index 0000000000000000000000000000000000000000..5e6fcff5ddd3fbf8bdda6310c224114d30b7509e --- /dev/null +++ b/backend/node_modules/util-deprecate/node.js @@ -0,0 +1,6 @@ + +/** + * For Node.js, simply re-export the core `util.deprecate` function. + */ + +module.exports = require('util').deprecate; diff --git a/backend/node_modules/util-deprecate/package.json b/backend/node_modules/util-deprecate/package.json new file mode 100644 index 0000000000000000000000000000000000000000..2e79f89a90f58369ef197534e8488158f379d264 --- /dev/null +++ b/backend/node_modules/util-deprecate/package.json @@ -0,0 +1,27 @@ +{ + "name": "util-deprecate", + "version": "1.0.2", + "description": "The Node.js `util.deprecate()` function with browser support", + "main": "node.js", + "browser": "browser.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "repository": { + "type": "git", + "url": "git://github.com/TooTallNate/util-deprecate.git" + }, + "keywords": [ + "util", + "deprecate", + "browserify", + "browser", + "node" + ], + "author": "Nathan Rajlich (http://n8.io/)", + "license": "MIT", + "bugs": { + "url": "https://github.com/TooTallNate/util-deprecate/issues" + }, + "homepage": "https://github.com/TooTallNate/util-deprecate" +} diff --git a/backend/node_modules/utils-merge/.npmignore b/backend/node_modules/utils-merge/.npmignore new file mode 100644 index 0000000000000000000000000000000000000000..3e53844186447e50779e1a5d63835e7fb7b134ce --- /dev/null +++ b/backend/node_modules/utils-merge/.npmignore @@ -0,0 +1,9 @@ +CONTRIBUTING.md +Makefile +docs/ +examples/ +reports/ +test/ + +.jshintrc +.travis.yml diff --git a/backend/node_modules/utils-merge/LICENSE b/backend/node_modules/utils-merge/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..76f6d083db5f4d381a91b89f6ff437e10d1a0fb8 --- /dev/null +++ b/backend/node_modules/utils-merge/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2013-2017 Jared Hanson + +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/backend/node_modules/utils-merge/README.md b/backend/node_modules/utils-merge/README.md new file mode 100644 index 0000000000000000000000000000000000000000..0cb71171255f78b087185dba6e09f7bb6a74dd98 --- /dev/null +++ b/backend/node_modules/utils-merge/README.md @@ -0,0 +1,34 @@ +# utils-merge + +[![Version](https://img.shields.io/npm/v/utils-merge.svg?label=version)](https://www.npmjs.com/package/utils-merge) +[![Build](https://img.shields.io/travis/jaredhanson/utils-merge.svg)](https://travis-ci.org/jaredhanson/utils-merge) +[![Quality](https://img.shields.io/codeclimate/github/jaredhanson/utils-merge.svg?label=quality)](https://codeclimate.com/github/jaredhanson/utils-merge) +[![Coverage](https://img.shields.io/coveralls/jaredhanson/utils-merge.svg)](https://coveralls.io/r/jaredhanson/utils-merge) +[![Dependencies](https://img.shields.io/david/jaredhanson/utils-merge.svg)](https://david-dm.org/jaredhanson/utils-merge) + + +Merges the properties from a source object into a destination object. + +## Install + +```bash +$ npm install utils-merge +``` + +## Usage + +```javascript +var a = { foo: 'bar' } + , b = { bar: 'baz' }; + +merge(a, b); +// => { foo: 'bar', bar: 'baz' } +``` + +## License + +[The MIT License](http://opensource.org/licenses/MIT) + +Copyright (c) 2013-2017 Jared Hanson <[http://jaredhanson.net/](http://jaredhanson.net/)> + + Sponsor diff --git a/backend/node_modules/utils-merge/index.js b/backend/node_modules/utils-merge/index.js new file mode 100644 index 0000000000000000000000000000000000000000..4265c694fec6f4eb174612ee434c3ab7da8e40fa --- /dev/null +++ b/backend/node_modules/utils-merge/index.js @@ -0,0 +1,23 @@ +/** + * Merge object b with object a. + * + * var a = { foo: 'bar' } + * , b = { bar: 'baz' }; + * + * merge(a, b); + * // => { foo: 'bar', bar: 'baz' } + * + * @param {Object} a + * @param {Object} b + * @return {Object} + * @api public + */ + +exports = module.exports = function(a, b){ + if (a && b) { + for (var key in b) { + a[key] = b[key]; + } + } + return a; +}; diff --git a/backend/node_modules/utils-merge/package.json b/backend/node_modules/utils-merge/package.json new file mode 100644 index 0000000000000000000000000000000000000000..e36b0781c1909d7893646e532bf617fdcb73d3c0 --- /dev/null +++ b/backend/node_modules/utils-merge/package.json @@ -0,0 +1,40 @@ +{ + "name": "utils-merge", + "version": "1.0.1", + "description": "merge() utility function", + "keywords": [ + "util" + ], + "author": { + "name": "Jared Hanson", + "email": "jaredhanson@gmail.com", + "url": "http://www.jaredhanson.net/" + }, + "repository": { + "type": "git", + "url": "git://github.com/jaredhanson/utils-merge.git" + }, + "bugs": { + "url": "http://github.com/jaredhanson/utils-merge/issues" + }, + "license": "MIT", + "licenses": [ + { + "type": "MIT", + "url": "http://opensource.org/licenses/MIT" + } + ], + "main": "./index", + "dependencies": {}, + "devDependencies": { + "make-node": "0.3.x", + "mocha": "1.x.x", + "chai": "1.x.x" + }, + "engines": { + "node": ">= 0.4.0" + }, + "scripts": { + "test": "node_modules/.bin/mocha --reporter spec --require test/bootstrap/node test/*.test.js" + } +} diff --git a/backend/node_modules/vary/HISTORY.md b/backend/node_modules/vary/HISTORY.md new file mode 100644 index 0000000000000000000000000000000000000000..f6cbcf7f9be9d45391c5e4e14d02541f59087351 --- /dev/null +++ b/backend/node_modules/vary/HISTORY.md @@ -0,0 +1,39 @@ +1.1.2 / 2017-09-23 +================== + + * perf: improve header token parsing speed + +1.1.1 / 2017-03-20 +================== + + * perf: hoist regular expression + +1.1.0 / 2015-09-29 +================== + + * Only accept valid field names in the `field` argument + - Ensures the resulting string is a valid HTTP header value + +1.0.1 / 2015-07-08 +================== + + * Fix setting empty header from empty `field` + * perf: enable strict mode + * perf: remove argument reassignments + +1.0.0 / 2014-08-10 +================== + + * Accept valid `Vary` header string as `field` + * Add `vary.append` for low-level string manipulation + * Move to `jshttp` orgainzation + +0.1.0 / 2014-06-05 +================== + + * Support array of fields to set + +0.0.0 / 2014-06-04 +================== + + * Initial release diff --git a/backend/node_modules/vary/LICENSE b/backend/node_modules/vary/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..84441fbb5709262c2bfc9b5ff0166ad4f024a1b8 --- /dev/null +++ b/backend/node_modules/vary/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/backend/node_modules/vary/README.md b/backend/node_modules/vary/README.md new file mode 100644 index 0000000000000000000000000000000000000000..cc000b34684a1d0b03d4c4cb4fac3e1094a81eec --- /dev/null +++ b/backend/node_modules/vary/README.md @@ -0,0 +1,101 @@ +# vary + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Manipulate the HTTP Vary header + +## 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 vary +``` + +## API + + + +```js +var vary = require('vary') +``` + +### vary(res, field) + +Adds the given header `field` to the `Vary` response header of `res`. +This can be a string of a single field, a string of a valid `Vary` +header, or an array of multiple fields. + +This will append the header if not already listed, otherwise leaves +it listed in the current location. + + + +```js +// Append "Origin" to the Vary header of the response +vary(res, 'Origin') +``` + +### vary.append(header, field) + +Adds the given header `field` to the `Vary` response header string `header`. +This can be a string of a single field, a string of a valid `Vary` header, +or an array of multiple fields. + +This will append the header if not already listed, otherwise leaves +it listed in the current location. The new header string is returned. + + + +```js +// Get header string appending "Origin" to "Accept, User-Agent" +vary.append('Accept, User-Agent', 'Origin') +``` + +## Examples + +### Updating the Vary header when content is based on it + +```js +var http = require('http') +var vary = require('vary') + +http.createServer(function onRequest (req, res) { + // about to user-agent sniff + vary(res, 'User-Agent') + + var ua = req.headers['user-agent'] || '' + var isMobile = /mobi|android|touch|mini/i.test(ua) + + // serve site, depending on isMobile + res.setHeader('Content-Type', 'text/html') + res.end('You are (probably) ' + (isMobile ? '' : 'not ') + 'a mobile user') +}) +``` + +## Testing + +```sh +$ npm test +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/vary.svg +[npm-url]: https://npmjs.org/package/vary +[node-version-image]: https://img.shields.io/node/v/vary.svg +[node-version-url]: https://nodejs.org/en/download +[travis-image]: https://img.shields.io/travis/jshttp/vary/master.svg +[travis-url]: https://travis-ci.org/jshttp/vary +[coveralls-image]: https://img.shields.io/coveralls/jshttp/vary/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/vary +[downloads-image]: https://img.shields.io/npm/dm/vary.svg +[downloads-url]: https://npmjs.org/package/vary diff --git a/backend/node_modules/vary/index.js b/backend/node_modules/vary/index.js new file mode 100644 index 0000000000000000000000000000000000000000..5b5e741279d4b800b0c408c5efbac8de6ece450b --- /dev/null +++ b/backend/node_modules/vary/index.js @@ -0,0 +1,149 @@ +/*! + * vary + * Copyright(c) 2014-2017 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + */ + +module.exports = vary +module.exports.append = append + +/** + * RegExp to match field-name in RFC 7230 sec 3.2 + * + * field-name = token + * token = 1*tchar + * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" + * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" + * / DIGIT / ALPHA + * ; any VCHAR, except delimiters + */ + +var FIELD_NAME_REGEXP = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/ + +/** + * Append a field to a vary header. + * + * @param {String} header + * @param {String|Array} field + * @return {String} + * @public + */ + +function append (header, field) { + if (typeof header !== 'string') { + throw new TypeError('header argument is required') + } + + if (!field) { + throw new TypeError('field argument is required') + } + + // get fields array + var fields = !Array.isArray(field) + ? parse(String(field)) + : field + + // assert on invalid field names + for (var j = 0; j < fields.length; j++) { + if (!FIELD_NAME_REGEXP.test(fields[j])) { + throw new TypeError('field argument contains an invalid header name') + } + } + + // existing, unspecified vary + if (header === '*') { + return header + } + + // enumerate current values + var val = header + var vals = parse(header.toLowerCase()) + + // unspecified vary + if (fields.indexOf('*') !== -1 || vals.indexOf('*') !== -1) { + return '*' + } + + for (var i = 0; i < fields.length; i++) { + var fld = fields[i].toLowerCase() + + // append value (case-preserving) + if (vals.indexOf(fld) === -1) { + vals.push(fld) + val = val + ? val + ', ' + fields[i] + : fields[i] + } + } + + return val +} + +/** + * Parse a vary header into an array. + * + * @param {String} header + * @return {Array} + * @private + */ + +function parse (header) { + var end = 0 + var list = [] + var start = 0 + + // gather tokens + for (var i = 0, len = header.length; i < len; i++) { + switch (header.charCodeAt(i)) { + case 0x20: /* */ + if (start === end) { + start = end = i + 1 + } + break + case 0x2c: /* , */ + list.push(header.substring(start, end)) + start = end = i + 1 + break + default: + end = i + 1 + break + } + } + + // final token + list.push(header.substring(start, end)) + + return list +} + +/** + * Mark that a request is varied on a header field. + * + * @param {Object} res + * @param {String|Array} field + * @public + */ + +function vary (res, field) { + if (!res || !res.getHeader || !res.setHeader) { + // quack quack + throw new TypeError('res argument is required') + } + + // get existing header + var val = res.getHeader('Vary') || '' + var header = Array.isArray(val) + ? val.join(', ') + : String(val) + + // set new header + if ((val = append(header, field))) { + res.setHeader('Vary', val) + } +} diff --git a/backend/node_modules/vary/package.json b/backend/node_modules/vary/package.json new file mode 100644 index 0000000000000000000000000000000000000000..028f72a93c5153af4163764face616d0ccb7a7b8 --- /dev/null +++ b/backend/node_modules/vary/package.json @@ -0,0 +1,43 @@ +{ + "name": "vary", + "description": "Manipulate the HTTP Vary header", + "version": "1.1.2", + "author": "Douglas Christopher Wilson ", + "license": "MIT", + "keywords": [ + "http", + "res", + "vary" + ], + "repository": "jshttp/vary", + "devDependencies": { + "beautify-benchmark": "0.2.4", + "benchmark": "2.1.4", + "eslint": "3.19.0", + "eslint-config-standard": "10.2.1", + "eslint-plugin-import": "2.7.0", + "eslint-plugin-markdown": "1.0.0-beta.6", + "eslint-plugin-node": "5.1.1", + "eslint-plugin-promise": "3.5.0", + "eslint-plugin-standard": "3.0.1", + "istanbul": "0.4.5", + "mocha": "2.5.3", + "supertest": "1.1.0" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "bench": "node benchmark/index.js", + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + } +} diff --git a/backend/node_modules/web-streams-polyfill/LICENSE b/backend/node_modules/web-streams-polyfill/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9fe85ac07facffe645ea92fa7d41c6391773ec90 --- /dev/null +++ b/backend/node_modules/web-streams-polyfill/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2024 Mattias Buelens +Copyright (c) 2016 Diwank Singh Tomer + +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/backend/node_modules/web-streams-polyfill/README.md b/backend/node_modules/web-streams-polyfill/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f4023ff05790d95bb5dd61240af4a4eefa8c5da0 --- /dev/null +++ b/backend/node_modules/web-streams-polyfill/README.md @@ -0,0 +1,110 @@ +# web-streams-polyfill + +Web Streams, based on the WHATWG spec reference implementation. + +[![build status](https://api.travis-ci.com/MattiasBuelens/web-streams-polyfill.svg?branch=master)](https://travis-ci.com/MattiasBuelens/web-streams-polyfill) +[![npm version](https://img.shields.io/npm/v/web-streams-polyfill.svg)](https://www.npmjs.com/package/web-streams-polyfill) +[![license](https://img.shields.io/npm/l/web-streams-polyfill.svg)](https://github.com/MattiasBuelens/web-streams-polyfill/blob/master/LICENSE) + +## Links + + - [Official spec][spec] + - [Reference implementation][ref-impl] + +## Usage + +This library comes in multiple variants: +* `web-streams-polyfill`: a polyfill that replaces the native stream implementations. + Recommended for use in web apps supporting older browsers through a ` + + + +``` +Usage as a Node module: +```js +var streams = require("web-streams-polyfill/ponyfill"); +var readable = new streams.ReadableStream(); +``` +Usage as a ES2015 module: +```js +import { ReadableStream } from "web-streams-polyfill/ponyfill"; +const readable = new ReadableStream(); +``` + +## Compatibility + +The `polyfill` and `ponyfill` variants work in any ES5-compatible environment that has a global `Promise`. +If you need to support older browsers or Node versions that do not have a native `Promise` implementation +(check the [support table][promise-support]), you must first include a `Promise` polyfill +(e.g. [promise-polyfill][promise-polyfill]). + +The `polyfill/es6` and `ponyfill/es6` variants work in any ES2015-compatible environment. + +The `polyfill/es2018` and `ponyfill/es2018` variants work in any ES2018-compatible environment. + +[Async iterable support for `ReadableStream`][rs-asynciterator] is available in all variants, but requires an ES2018-compatible environment or a polyfill for `Symbol.asyncIterator`. + +[`WritableStreamDefaultController.signal`][ws-controller-signal] is available in all variants, but requires a global `AbortController` constructor. If necessary, consider using a polyfill such as [abortcontroller-polyfill]. + +[Reading with a BYOB reader][mdn-byob-read] is available in all variants, but requires `ArrayBuffer.prototype.transfer()` or `structuredClone()` to exist in order to correctly transfer the given view's buffer. If not available, then the buffer won't be transferred during the read. + +## Compliance + +The polyfill implements [version `4dc123a` (13 Nov 2023)][spec-snapshot] of the streams specification. + +The polyfill is tested against the same [web platform tests][wpt] that are used by browsers to test their native implementations. +The polyfill aims to pass all tests, although it allows some exceptions for practical reasons: +* The `es2018` variant passes all of the tests. +* The `es6` variant passes the same tests as the `es2018` variant, except for the [test for the prototype of `ReadableStream`'s async iterator][wpt-async-iterator-prototype]. + Retrieving the correct `%AsyncIteratorPrototype%` requires using an async generator (`async function* () {}`), which is invalid syntax before ES2018. + Instead, the polyfill [creates its own version][stub-async-iterator-prototype] which is functionally equivalent to the real prototype. +* The `es5` variant passes the same tests as the `es6` variant, except for various tests about specific characteristics of the constructors, properties and methods. + These test failures do not affect the run-time behavior of the polyfill. + For example: + * The `name` property of down-leveled constructors is incorrect. + * The `length` property of down-leveled constructors and methods with optional arguments is incorrect. + * Not all properties and methods are correctly marked as non-enumerable. + * Down-leveled class methods are not correctly marked as non-constructable. + +The type definitions are compatible with the built-in stream types of TypeScript 3.3. + +## Contributors + +Thanks to these people for their work on [the original polyfill][creatorrr-polyfill]: + + - Diwank Singh Tomer ([creatorrr](https://github.com/creatorrr)) + - Anders Riutta ([ariutta](https://github.com/ariutta)) + +[spec]: https://streams.spec.whatwg.org +[ref-impl]: https://github.com/whatwg/streams +[ponyfill]: https://github.com/sindresorhus/ponyfill +[promise-support]: https://kangax.github.io/compat-table/es6/#test-Promise +[promise-polyfill]: https://www.npmjs.com/package/promise-polyfill +[rs-asynciterator]: https://streams.spec.whatwg.org/#rs-asynciterator +[ws-controller-signal]: https://streams.spec.whatwg.org/#ws-default-controller-signal +[abortcontroller-polyfill]: https://www.npmjs.com/package/abortcontroller-polyfill +[mdn-byob-read]: https://developer.mozilla.org/en-US/docs/Web/API/ReadableStreamBYOBReader/read +[spec-snapshot]: https://streams.spec.whatwg.org/commit-snapshots/4dc123a6e7f7ba89a8c6a7975b021156f39cab52/ +[wpt]: https://github.com/web-platform-tests/wpt/tree/2a298b616b7c865917d7198a287310881cbfdd8d/streams +[wpt-async-iterator-prototype]: https://github.com/web-platform-tests/wpt/blob/2a298b616b7c865917d7198a287310881cbfdd8d/streams/readable-streams/async-iterator.any.js#L24 +[stub-async-iterator-prototype]: https://github.com/MattiasBuelens/web-streams-polyfill/blob/v2.0.0/src/target/es5/stub/async-iterator-prototype.ts +[creatorrr-polyfill]: https://github.com/creatorrr/web-streams-polyfill diff --git a/backend/node_modules/web-streams-polyfill/dist/polyfill.es2018.js b/backend/node_modules/web-streams-polyfill/dist/polyfill.es2018.js new file mode 100644 index 0000000000000000000000000000000000000000..20a929a8fe3331da5280826723711ef366e1756c --- /dev/null +++ b/backend/node_modules/web-streams-polyfill/dist/polyfill.es2018.js @@ -0,0 +1,4765 @@ +/** + * @license + * web-streams-polyfill v3.3.3 + * Copyright 2024 Mattias Buelens, Diwank Singh Tomer and other contributors. + * This code is released under the MIT license. + * SPDX-License-Identifier: MIT + */ +(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.WebStreamsPolyfill = {})); +})(this, (function (exports) { 'use strict'; + + function noop() { + return undefined; + } + + function typeIsObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; + } + const rethrowAssertionErrorRejection = noop; + function setFunctionName(fn, name) { + try { + Object.defineProperty(fn, 'name', { + value: name, + configurable: true + }); + } + catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility + } + } + + const originalPromise = Promise; + const originalPromiseThen = Promise.prototype.then; + const originalPromiseReject = Promise.reject.bind(originalPromise); + // https://webidl.spec.whatwg.org/#a-new-promise + function newPromise(executor) { + return new originalPromise(executor); + } + // https://webidl.spec.whatwg.org/#a-promise-resolved-with + function promiseResolvedWith(value) { + return newPromise(resolve => resolve(value)); + } + // https://webidl.spec.whatwg.org/#a-promise-rejected-with + function promiseRejectedWith(reason) { + return originalPromiseReject(reason); + } + function PerformPromiseThen(promise, onFulfilled, onRejected) { + // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an + // approximation. + return originalPromiseThen.call(promise, onFulfilled, onRejected); + } + // Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned + // from that handler. To prevent this, return null instead of void from all handlers. + // http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it + function uponPromise(promise, onFulfilled, onRejected) { + PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection); + } + function uponFulfillment(promise, onFulfilled) { + uponPromise(promise, onFulfilled); + } + function uponRejection(promise, onRejected) { + uponPromise(promise, undefined, onRejected); + } + function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { + return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); + } + function setPromiseIsHandledToTrue(promise) { + PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection); + } + let _queueMicrotask = callback => { + if (typeof queueMicrotask === 'function') { + _queueMicrotask = queueMicrotask; + } + else { + const resolvedPromise = promiseResolvedWith(undefined); + _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb); + } + return _queueMicrotask(callback); + }; + function reflectCall(F, V, args) { + if (typeof F !== 'function') { + throw new TypeError('Argument is not a function'); + } + return Function.prototype.apply.call(F, V, args); + } + function promiseCall(F, V, args) { + try { + return promiseResolvedWith(reflectCall(F, V, args)); + } + catch (value) { + return promiseRejectedWith(value); + } + } + + // Original from Chromium + // https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js + const QUEUE_MAX_ARRAY_SIZE = 16384; + /** + * Simple queue structure. + * + * Avoids scalability issues with using a packed array directly by using + * multiple arrays in a linked list and keeping the array size bounded. + */ + class SimpleQueue { + constructor() { + this._cursor = 0; + this._size = 0; + // _front and _back are always defined. + this._front = { + _elements: [], + _next: undefined + }; + this._back = this._front; + // The cursor is used to avoid calling Array.shift(). + // It contains the index of the front element of the array inside the + // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE). + this._cursor = 0; + // When there is only one node, size === elements.length - cursor. + this._size = 0; + } + get length() { + return this._size; + } + // For exception safety, this method is structured in order: + // 1. Read state + // 2. Calculate required state mutations + // 3. Perform state mutations + push(element) { + const oldBack = this._back; + let newBack = oldBack; + if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { + newBack = { + _elements: [], + _next: undefined + }; + } + // push() is the mutation most likely to throw an exception, so it + // goes first. + oldBack._elements.push(element); + if (newBack !== oldBack) { + this._back = newBack; + oldBack._next = newBack; + } + ++this._size; + } + // Like push(), shift() follows the read -> calculate -> mutate pattern for + // exception safety. + shift() { // must not be called on an empty queue + const oldFront = this._front; + let newFront = oldFront; + const oldCursor = this._cursor; + let newCursor = oldCursor + 1; + const elements = oldFront._elements; + const element = elements[oldCursor]; + if (newCursor === QUEUE_MAX_ARRAY_SIZE) { + newFront = oldFront._next; + newCursor = 0; + } + // No mutations before this point. + --this._size; + this._cursor = newCursor; + if (oldFront !== newFront) { + this._front = newFront; + } + // Permit shifted element to be garbage collected. + elements[oldCursor] = undefined; + return element; + } + // The tricky thing about forEach() is that it can be called + // re-entrantly. The queue may be mutated inside the callback. It is easy to + // see that push() within the callback has no negative effects since the end + // of the queue is checked for on every iteration. If shift() is called + // repeatedly within the callback then the next iteration may return an + // element that has been removed. In this case the callback will be called + // with undefined values until we either "catch up" with elements that still + // exist or reach the back of the queue. + forEach(callback) { + let i = this._cursor; + let node = this._front; + let elements = node._elements; + while (i !== elements.length || node._next !== undefined) { + if (i === elements.length) { + node = node._next; + elements = node._elements; + i = 0; + if (elements.length === 0) { + break; + } + } + callback(elements[i]); + ++i; + } + } + // Return the element that would be returned if shift() was called now, + // without modifying the queue. + peek() { // must not be called on an empty queue + const front = this._front; + const cursor = this._cursor; + return front._elements[cursor]; + } + } + + const AbortSteps = Symbol('[[AbortSteps]]'); + const ErrorSteps = Symbol('[[ErrorSteps]]'); + const CancelSteps = Symbol('[[CancelSteps]]'); + const PullSteps = Symbol('[[PullSteps]]'); + const ReleaseSteps = Symbol('[[ReleaseSteps]]'); + + function ReadableStreamReaderGenericInitialize(reader, stream) { + reader._ownerReadableStream = stream; + stream._reader = reader; + if (stream._state === 'readable') { + defaultReaderClosedPromiseInitialize(reader); + } + else if (stream._state === 'closed') { + defaultReaderClosedPromiseInitializeAsResolved(reader); + } + else { + defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); + } + } + // A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state + // check. + function ReadableStreamReaderGenericCancel(reader, reason) { + const stream = reader._ownerReadableStream; + return ReadableStreamCancel(stream, reason); + } + function ReadableStreamReaderGenericRelease(reader) { + const stream = reader._ownerReadableStream; + if (stream._state === 'readable') { + defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + else { + defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + stream._readableStreamController[ReleaseSteps](); + stream._reader = undefined; + reader._ownerReadableStream = undefined; + } + // Helper functions for the readers. + function readerLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released reader'); + } + // Helper functions for the ReadableStreamDefaultReader. + function defaultReaderClosedPromiseInitialize(reader) { + reader._closedPromise = newPromise((resolve, reject) => { + reader._closedPromise_resolve = resolve; + reader._closedPromise_reject = reject; + }); + } + function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseReject(reader, reason); + } + function defaultReaderClosedPromiseInitializeAsResolved(reader) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseResolve(reader); + } + function defaultReaderClosedPromiseReject(reader, reason) { + if (reader._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(reader._closedPromise); + reader._closedPromise_reject(reason); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; + } + function defaultReaderClosedPromiseResetToRejected(reader, reason) { + defaultReaderClosedPromiseInitializeAsRejected(reader, reason); + } + function defaultReaderClosedPromiseResolve(reader) { + if (reader._closedPromise_resolve === undefined) { + return; + } + reader._closedPromise_resolve(undefined); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; + } + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill + const NumberIsFinite = Number.isFinite || function (x) { + return typeof x === 'number' && isFinite(x); + }; + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill + const MathTrunc = Math.trunc || function (v) { + return v < 0 ? Math.ceil(v) : Math.floor(v); + }; + + // https://heycam.github.io/webidl/#idl-dictionaries + function isDictionary(x) { + return typeof x === 'object' || typeof x === 'function'; + } + function assertDictionary(obj, context) { + if (obj !== undefined && !isDictionary(obj)) { + throw new TypeError(`${context} is not an object.`); + } + } + // https://heycam.github.io/webidl/#idl-callback-functions + function assertFunction(x, context) { + if (typeof x !== 'function') { + throw new TypeError(`${context} is not a function.`); + } + } + // https://heycam.github.io/webidl/#idl-object + function isObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; + } + function assertObject(x, context) { + if (!isObject(x)) { + throw new TypeError(`${context} is not an object.`); + } + } + function assertRequiredArgument(x, position, context) { + if (x === undefined) { + throw new TypeError(`Parameter ${position} is required in '${context}'.`); + } + } + function assertRequiredField(x, field, context) { + if (x === undefined) { + throw new TypeError(`${field} is required in '${context}'.`); + } + } + // https://heycam.github.io/webidl/#idl-unrestricted-double + function convertUnrestrictedDouble(value) { + return Number(value); + } + function censorNegativeZero(x) { + return x === 0 ? 0 : x; + } + function integerPart(x) { + return censorNegativeZero(MathTrunc(x)); + } + // https://heycam.github.io/webidl/#idl-unsigned-long-long + function convertUnsignedLongLongWithEnforceRange(value, context) { + const lowerBound = 0; + const upperBound = Number.MAX_SAFE_INTEGER; + let x = Number(value); + x = censorNegativeZero(x); + if (!NumberIsFinite(x)) { + throw new TypeError(`${context} is not a finite number`); + } + x = integerPart(x); + if (x < lowerBound || x > upperBound) { + throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`); + } + if (!NumberIsFinite(x) || x === 0) { + return 0; + } + // TODO Use BigInt if supported? + // let xBigInt = BigInt(integerPart(x)); + // xBigInt = BigInt.asUintN(64, xBigInt); + // return Number(xBigInt); + return x; + } + + function assertReadableStream(x, context) { + if (!IsReadableStream(x)) { + throw new TypeError(`${context} is not a ReadableStream.`); + } + } + + // Abstract operations for the ReadableStream. + function AcquireReadableStreamDefaultReader(stream) { + return new ReadableStreamDefaultReader(stream); + } + // ReadableStream API exposed for controllers. + function ReadableStreamAddReadRequest(stream, readRequest) { + stream._reader._readRequests.push(readRequest); + } + function ReadableStreamFulfillReadRequest(stream, chunk, done) { + const reader = stream._reader; + const readRequest = reader._readRequests.shift(); + if (done) { + readRequest._closeSteps(); + } + else { + readRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadRequests(stream) { + return stream._reader._readRequests.length; + } + function ReadableStreamHasDefaultReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamDefaultReader(reader)) { + return false; + } + return true; + } + /** + * A default reader vended by a {@link ReadableStream}. + * + * @public + */ + class ReadableStreamDefaultReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + /** + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('read')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: () => resolvePromise({ value: undefined, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamDefaultReaderRead(this, readRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamDefaultReader(this)) { + throw defaultReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamDefaultReaderRelease(this); + } + } + Object.defineProperties(ReadableStreamDefaultReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + setFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel'); + setFunctionName(ReadableStreamDefaultReader.prototype.read, 'read'); + setFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, { + value: 'ReadableStreamDefaultReader', + configurable: true + }); + } + // Abstract operations for the readers. + function IsReadableStreamDefaultReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) { + return false; + } + return x instanceof ReadableStreamDefaultReader; + } + function ReadableStreamDefaultReaderRead(reader, readRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'closed') { + readRequest._closeSteps(); + } + else if (stream._state === 'errored') { + readRequest._errorSteps(stream._storedError); + } + else { + stream._readableStreamController[PullSteps](readRequest); + } + } + function ReadableStreamDefaultReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + const e = new TypeError('Reader was released'); + ReadableStreamDefaultReaderErrorReadRequests(reader, e); + } + function ReadableStreamDefaultReaderErrorReadRequests(reader, e) { + const readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(readRequest => { + readRequest._errorSteps(e); + }); + } + // Helper functions for the ReadableStreamDefaultReader. + function defaultReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`); + } + + /// + /* eslint-disable @typescript-eslint/no-empty-function */ + const AsyncIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf(async function* () { }).prototype); + + /// + class ReadableStreamAsyncIteratorImpl { + constructor(reader, preventCancel) { + this._ongoingPromise = undefined; + this._isFinished = false; + this._reader = reader; + this._preventCancel = preventCancel; + } + next() { + const nextSteps = () => this._nextSteps(); + this._ongoingPromise = this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : + nextSteps(); + return this._ongoingPromise; + } + return(value) { + const returnSteps = () => this._returnSteps(value); + return this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : + returnSteps(); + } + _nextSteps() { + if (this._isFinished) { + return Promise.resolve({ value: undefined, done: true }); + } + const reader = this._reader; + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => { + this._ongoingPromise = undefined; + // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test. + // FIXME Is this a bug in the specification, or in the test? + _queueMicrotask(() => resolvePromise({ value: chunk, done: false })); + }, + _closeSteps: () => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + resolvePromise({ value: undefined, done: true }); + }, + _errorSteps: reason => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + rejectPromise(reason); + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promise; + } + _returnSteps(value) { + if (this._isFinished) { + return Promise.resolve({ value, done: true }); + } + this._isFinished = true; + const reader = this._reader; + if (!this._preventCancel) { + const result = ReadableStreamReaderGenericCancel(reader, value); + ReadableStreamReaderGenericRelease(reader); + return transformPromiseWith(result, () => ({ value, done: true })); + } + ReadableStreamReaderGenericRelease(reader); + return promiseResolvedWith({ value, done: true }); + } + } + const ReadableStreamAsyncIteratorPrototype = { + next() { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next')); + } + return this._asyncIteratorImpl.next(); + }, + return(value) { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return')); + } + return this._asyncIteratorImpl.return(value); + } + }; + Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); + // Abstract operations for the ReadableStream. + function AcquireReadableStreamAsyncIterator(stream, preventCancel) { + const reader = AcquireReadableStreamDefaultReader(stream); + const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); + const iterator = Object.create(ReadableStreamAsyncIteratorPrototype); + iterator._asyncIteratorImpl = impl; + return iterator; + } + function IsReadableStreamAsyncIterator(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) { + return false; + } + try { + // noinspection SuspiciousTypeOfGuard + return x._asyncIteratorImpl instanceof + ReadableStreamAsyncIteratorImpl; + } + catch (_a) { + return false; + } + } + // Helper functions for the ReadableStream. + function streamAsyncIteratorBrandCheckException(name) { + return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`); + } + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill + const NumberIsNaN = Number.isNaN || function (x) { + // eslint-disable-next-line no-self-compare + return x !== x; + }; + + var _a, _b, _c; + function CreateArrayFromList(elements) { + // We use arrays to represent lists, so this is basically a no-op. + // Do a slice though just in case we happen to depend on the unique-ness. + return elements.slice(); + } + function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { + new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); + } + let TransferArrayBuffer = (O) => { + if (typeof O.transfer === 'function') { + TransferArrayBuffer = buffer => buffer.transfer(); + } + else if (typeof structuredClone === 'function') { + TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] }); + } + else { + // Not implemented correctly + TransferArrayBuffer = buffer => buffer; + } + return TransferArrayBuffer(O); + }; + let IsDetachedBuffer = (O) => { + if (typeof O.detached === 'boolean') { + IsDetachedBuffer = buffer => buffer.detached; + } + else { + // Not implemented correctly + IsDetachedBuffer = buffer => buffer.byteLength === 0; + } + return IsDetachedBuffer(O); + }; + function ArrayBufferSlice(buffer, begin, end) { + // ArrayBuffer.prototype.slice is not available on IE10 + // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice + if (buffer.slice) { + return buffer.slice(begin, end); + } + const length = end - begin; + const slice = new ArrayBuffer(length); + CopyDataBlockBytes(slice, 0, buffer, begin, length); + return slice; + } + function GetMethod(receiver, prop) { + const func = receiver[prop]; + if (func === undefined || func === null) { + return undefined; + } + if (typeof func !== 'function') { + throw new TypeError(`${String(prop)} is not a function`); + } + return func; + } + function CreateAsyncFromSyncIterator(syncIteratorRecord) { + // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%, + // we use yield* inside an async generator function to achieve the same result. + // Wrap the sync iterator inside a sync iterable, so we can use it with yield*. + const syncIterable = { + [Symbol.iterator]: () => syncIteratorRecord.iterator + }; + // Create an async generator function and immediately invoke it. + const asyncIterator = (async function* () { + return yield* syncIterable; + }()); + // Return as an async iterator record. + const nextMethod = asyncIterator.next; + return { iterator: asyncIterator, nextMethod, done: false }; + } + // Aligns with core-js/modules/es.symbol.async-iterator.js + const SymbolAsyncIterator = (_c = (_a = Symbol.asyncIterator) !== null && _a !== void 0 ? _a : (_b = Symbol.for) === null || _b === void 0 ? void 0 : _b.call(Symbol, 'Symbol.asyncIterator')) !== null && _c !== void 0 ? _c : '@@asyncIterator'; + function GetIterator(obj, hint = 'sync', method) { + if (method === undefined) { + if (hint === 'async') { + method = GetMethod(obj, SymbolAsyncIterator); + if (method === undefined) { + const syncMethod = GetMethod(obj, Symbol.iterator); + const syncIteratorRecord = GetIterator(obj, 'sync', syncMethod); + return CreateAsyncFromSyncIterator(syncIteratorRecord); + } + } + else { + method = GetMethod(obj, Symbol.iterator); + } + } + if (method === undefined) { + throw new TypeError('The object is not iterable'); + } + const iterator = reflectCall(method, obj, []); + if (!typeIsObject(iterator)) { + throw new TypeError('The iterator method must return an object'); + } + const nextMethod = iterator.next; + return { iterator, nextMethod, done: false }; + } + function IteratorNext(iteratorRecord) { + const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []); + if (!typeIsObject(result)) { + throw new TypeError('The iterator.next() method must return an object'); + } + return result; + } + function IteratorComplete(iterResult) { + return Boolean(iterResult.done); + } + function IteratorValue(iterResult) { + return iterResult.value; + } + + function IsNonNegativeNumber(v) { + if (typeof v !== 'number') { + return false; + } + if (NumberIsNaN(v)) { + return false; + } + if (v < 0) { + return false; + } + return true; + } + function CloneAsUint8Array(O) { + const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength); + return new Uint8Array(buffer); + } + + function DequeueValue(container) { + const pair = container._queue.shift(); + container._queueTotalSize -= pair.size; + if (container._queueTotalSize < 0) { + container._queueTotalSize = 0; + } + return pair.value; + } + function EnqueueValueWithSize(container, value, size) { + if (!IsNonNegativeNumber(size) || size === Infinity) { + throw new RangeError('Size must be a finite, non-NaN, non-negative number.'); + } + container._queue.push({ value, size }); + container._queueTotalSize += size; + } + function PeekQueueValue(container) { + const pair = container._queue.peek(); + return pair.value; + } + function ResetQueue(container) { + container._queue = new SimpleQueue(); + container._queueTotalSize = 0; + } + + function isDataViewConstructor(ctor) { + return ctor === DataView; + } + function isDataView(view) { + return isDataViewConstructor(view.constructor); + } + function arrayBufferViewElementSize(ctor) { + if (isDataViewConstructor(ctor)) { + return 1; + } + return ctor.BYTES_PER_ELEMENT; + } + + /** + * A pull-into request in a {@link ReadableByteStreamController}. + * + * @public + */ + class ReadableStreamBYOBRequest { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. + */ + get view() { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('view'); + } + return this._view; + } + respond(bytesWritten) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respond'); + } + assertRequiredArgument(bytesWritten, 1, 'respond'); + bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter'); + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(this._view.buffer)) { + throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`); + } + ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); + } + respondWithNewView(view) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respondWithNewView'); + } + assertRequiredArgument(view, 1, 'respondWithNewView'); + if (!ArrayBuffer.isView(view)) { + throw new TypeError('You can only respond with array buffer views'); + } + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(view.buffer)) { + throw new TypeError('The given view\'s buffer has been detached and so cannot be used as a response'); + } + ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); + } + } + Object.defineProperties(ReadableStreamBYOBRequest.prototype, { + respond: { enumerable: true }, + respondWithNewView: { enumerable: true }, + view: { enumerable: true } + }); + setFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond'); + setFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, { + value: 'ReadableStreamBYOBRequest', + configurable: true + }); + } + /** + * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. + * + * @public + */ + class ReadableByteStreamController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the current BYOB pull request, or `null` if there isn't one. + */ + get byobRequest() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('byobRequest'); + } + return ReadableByteStreamControllerGetBYOBRequest(this); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('desiredSize'); + } + return ReadableByteStreamControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('close'); + } + if (this._closeRequested) { + throw new TypeError('The stream has already been closed; do not close it again!'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`); + } + ReadableByteStreamControllerClose(this); + } + enqueue(chunk) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('enqueue'); + } + assertRequiredArgument(chunk, 1, 'enqueue'); + if (!ArrayBuffer.isView(chunk)) { + throw new TypeError('chunk must be an array buffer view'); + } + if (chunk.byteLength === 0) { + throw new TypeError('chunk must have non-zero byteLength'); + } + if (chunk.buffer.byteLength === 0) { + throw new TypeError(`chunk's buffer must have non-zero byteLength`); + } + if (this._closeRequested) { + throw new TypeError('stream is closed or draining'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`); + } + ReadableByteStreamControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('error'); + } + ReadableByteStreamControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ReadableByteStreamControllerClearPendingPullIntos(this); + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableByteStreamControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableByteStream; + if (this._queueTotalSize > 0) { + ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest); + return; + } + const autoAllocateChunkSize = this._autoAllocateChunkSize; + if (autoAllocateChunkSize !== undefined) { + let buffer; + try { + buffer = new ArrayBuffer(autoAllocateChunkSize); + } + catch (bufferE) { + readRequest._errorSteps(bufferE); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: autoAllocateChunkSize, + byteOffset: 0, + byteLength: autoAllocateChunkSize, + bytesFilled: 0, + minimumFill: 1, + elementSize: 1, + viewConstructor: Uint8Array, + readerType: 'default' + }; + this._pendingPullIntos.push(pullIntoDescriptor); + } + ReadableStreamAddReadRequest(stream, readRequest); + ReadableByteStreamControllerCallPullIfNeeded(this); + } + /** @internal */ + [ReleaseSteps]() { + if (this._pendingPullIntos.length > 0) { + const firstPullInto = this._pendingPullIntos.peek(); + firstPullInto.readerType = 'none'; + this._pendingPullIntos = new SimpleQueue(); + this._pendingPullIntos.push(firstPullInto); + } + } + } + Object.defineProperties(ReadableByteStreamController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + byobRequest: { enumerable: true }, + desiredSize: { enumerable: true } + }); + setFunctionName(ReadableByteStreamController.prototype.close, 'close'); + setFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue'); + setFunctionName(ReadableByteStreamController.prototype.error, 'error'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, { + value: 'ReadableByteStreamController', + configurable: true + }); + } + // Abstract operations for the ReadableByteStreamController. + function IsReadableByteStreamController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) { + return false; + } + return x instanceof ReadableByteStreamController; + } + function IsReadableStreamBYOBRequest(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) { + return false; + } + return x instanceof ReadableStreamBYOBRequest; + } + function ReadableByteStreamControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableByteStreamControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + // TODO: Test controller argument + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + return null; + }, e => { + ReadableByteStreamControllerError(controller, e); + return null; + }); + } + function ReadableByteStreamControllerClearPendingPullIntos(controller) { + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + controller._pendingPullIntos = new SimpleQueue(); + } + function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { + let done = false; + if (stream._state === 'closed') { + done = true; + } + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'default') { + ReadableStreamFulfillReadRequest(stream, filledView, done); + } + else { + ReadableStreamFulfillReadIntoRequest(stream, filledView, done); + } + } + function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { + const bytesFilled = pullIntoDescriptor.bytesFilled; + const elementSize = pullIntoDescriptor.elementSize; + return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); + } + function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { + controller._queue.push({ buffer, byteOffset, byteLength }); + controller._queueTotalSize += byteLength; + } + function ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, buffer, byteOffset, byteLength) { + let clonedChunk; + try { + clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength); + } + catch (cloneE) { + ReadableByteStreamControllerError(controller, cloneE); + throw cloneE; + } + ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength); + } + function ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstDescriptor) { + if (firstDescriptor.bytesFilled > 0) { + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, firstDescriptor.buffer, firstDescriptor.byteOffset, firstDescriptor.bytesFilled); + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { + const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); + const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; + let totalBytesToCopyRemaining = maxBytesToCopy; + let ready = false; + const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize; + const maxAlignedBytes = maxBytesFilled - remainderBytes; + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) { + totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; + ready = true; + } + const queue = controller._queue; + while (totalBytesToCopyRemaining > 0) { + const headOfQueue = queue.peek(); + const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); + const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); + if (headOfQueue.byteLength === bytesToCopy) { + queue.shift(); + } + else { + headOfQueue.byteOffset += bytesToCopy; + headOfQueue.byteLength -= bytesToCopy; + } + controller._queueTotalSize -= bytesToCopy; + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); + totalBytesToCopyRemaining -= bytesToCopy; + } + return ready; + } + function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { + pullIntoDescriptor.bytesFilled += size; + } + function ReadableByteStreamControllerHandleQueueDrain(controller) { + if (controller._queueTotalSize === 0 && controller._closeRequested) { + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(controller._controlledReadableByteStream); + } + else { + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + } + function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { + if (controller._byobRequest === null) { + return; + } + controller._byobRequest._associatedReadableByteStreamController = undefined; + controller._byobRequest._view = null; + controller._byobRequest = null; + } + function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { + while (controller._pendingPullIntos.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const pullIntoDescriptor = controller._pendingPullIntos.peek(); + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller) { + const reader = controller._controlledReadableByteStream._reader; + while (reader._readRequests.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const readRequest = reader._readRequests.shift(); + ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest); + } + } + function ReadableByteStreamControllerPullInto(controller, view, min, readIntoRequest) { + const stream = controller._controlledReadableByteStream; + const ctor = view.constructor; + const elementSize = arrayBufferViewElementSize(ctor); + const { byteOffset, byteLength } = view; + const minimumFill = min * elementSize; + let buffer; + try { + buffer = TransferArrayBuffer(view.buffer); + } + catch (e) { + readIntoRequest._errorSteps(e); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: buffer.byteLength, + byteOffset, + byteLength, + bytesFilled: 0, + minimumFill, + elementSize, + viewConstructor: ctor, + readerType: 'byob' + }; + if (controller._pendingPullIntos.length > 0) { + controller._pendingPullIntos.push(pullIntoDescriptor); + // No ReadableByteStreamControllerCallPullIfNeeded() call since: + // - No change happens on desiredSize + // - The source has already been notified of that there's at least 1 pending read(view) + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + return; + } + if (stream._state === 'closed') { + const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); + readIntoRequest._closeSteps(emptyView); + return; + } + if (controller._queueTotalSize > 0) { + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + ReadableByteStreamControllerHandleQueueDrain(controller); + readIntoRequest._chunkSteps(filledView); + return; + } + if (controller._closeRequested) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + readIntoRequest._errorSteps(e); + return; + } + } + controller._pendingPullIntos.push(pullIntoDescriptor); + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { + if (firstDescriptor.readerType === 'none') { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const stream = controller._controlledReadableByteStream; + if (ReadableStreamHasBYOBReader(stream)) { + while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { + const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + return; + } + if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) { + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + return; + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; + if (remainderSize > 0) { + const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor.buffer, end - remainderSize, remainderSize); + } + pullIntoDescriptor.bytesFilled -= remainderSize; + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor); + } + else { + ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerShiftPendingPullInto(controller) { + const descriptor = controller._pendingPullIntos.shift(); + return descriptor; + } + function ReadableByteStreamControllerShouldCallPull(controller) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return false; + } + if (controller._closeRequested) { + return false; + } + if (!controller._started) { + return false; + } + if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; + } + function ReadableByteStreamControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + } + // A client of ReadableByteStreamController may use these functions directly to bypass state check. + function ReadableByteStreamControllerClose(controller) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + if (controller._queueTotalSize > 0) { + controller._closeRequested = true; + return; + } + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + throw e; + } + } + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } + function ReadableByteStreamControllerEnqueue(controller, chunk) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + const { buffer, byteOffset, byteLength } = chunk; + if (IsDetachedBuffer(buffer)) { + throw new TypeError('chunk\'s buffer is detached and so cannot be enqueued'); + } + const transferredBuffer = TransferArrayBuffer(buffer); + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (IsDetachedBuffer(firstPendingPullInto.buffer)) { + throw new TypeError('The BYOB request\'s buffer has been detached and so cannot be filled with an enqueued chunk'); + } + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer); + if (firstPendingPullInto.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto); + } + } + if (ReadableStreamHasDefaultReader(stream)) { + ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller); + if (ReadableStreamGetNumReadRequests(stream) === 0) { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + else { + if (controller._pendingPullIntos.length > 0) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); + ReadableStreamFulfillReadRequest(stream, transferredView, false); + } + } + else if (ReadableStreamHasBYOBReader(stream)) { + // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully. + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + else { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerError(controller, e) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return; + } + ReadableByteStreamControllerClearPendingPullIntos(controller); + ResetQueue(controller); + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); + } + function ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest) { + const entry = controller._queue.shift(); + controller._queueTotalSize -= entry.byteLength; + ReadableByteStreamControllerHandleQueueDrain(controller); + const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); + readRequest._chunkSteps(view); + } + function ReadableByteStreamControllerGetBYOBRequest(controller) { + if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); + const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); + SetUpReadableStreamBYOBRequest(byobRequest, controller, view); + controller._byobRequest = byobRequest; + } + return controller._byobRequest; + } + function ReadableByteStreamControllerGetDesiredSize(controller) { + const state = controller._controlledReadableByteStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; + } + function ReadableByteStreamControllerRespond(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (bytesWritten !== 0) { + throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream'); + } + } + else { + if (bytesWritten === 0) { + throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream'); + } + if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) { + throw new RangeError('bytesWritten out of range'); + } + } + firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); + ReadableByteStreamControllerRespondInternal(controller, bytesWritten); + } + function ReadableByteStreamControllerRespondWithNewView(controller, view) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (view.byteLength !== 0) { + throw new TypeError('The view\'s length must be 0 when calling respondWithNewView() on a closed stream'); + } + } + else { + if (view.byteLength === 0) { + throw new TypeError('The view\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'); + } + } + if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { + throw new RangeError('The region specified by view does not match byobRequest'); + } + if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) { + throw new RangeError('The buffer of view has different capacity than byobRequest'); + } + if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) { + throw new RangeError('The region specified by view is larger than byobRequest'); + } + const viewByteLength = view.byteLength; + firstDescriptor.buffer = TransferArrayBuffer(view.buffer); + ReadableByteStreamControllerRespondInternal(controller, viewByteLength); + } + function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { + controller._controlledReadableByteStream = stream; + controller._pullAgain = false; + controller._pulling = false; + controller._byobRequest = null; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._closeRequested = false; + controller._started = false; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._autoAllocateChunkSize = autoAllocateChunkSize; + controller._pendingPullIntos = new SimpleQueue(); + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableByteStreamControllerCallPullIfNeeded(controller); + return null; + }, r => { + ReadableByteStreamControllerError(controller, r); + return null; + }); + } + function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { + const controller = Object.create(ReadableByteStreamController.prototype); + let startAlgorithm; + let pullAlgorithm; + let cancelAlgorithm; + if (underlyingByteSource.start !== undefined) { + startAlgorithm = () => underlyingByteSource.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingByteSource.pull !== undefined) { + pullAlgorithm = () => underlyingByteSource.pull(controller); + } + else { + pullAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingByteSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingByteSource.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; + if (autoAllocateChunkSize === 0) { + throw new TypeError('autoAllocateChunkSize must be greater than 0'); + } + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); + } + function SetUpReadableStreamBYOBRequest(request, controller, view) { + request._associatedReadableByteStreamController = controller; + request._view = view; + } + // Helper functions for the ReadableStreamBYOBRequest. + function byobRequestBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`); + } + // Helper functions for the ReadableByteStreamController. + function byteStreamControllerBrandCheckException(name) { + return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`); + } + + function convertReaderOptions(options, context) { + assertDictionary(options, context); + const mode = options === null || options === void 0 ? void 0 : options.mode; + return { + mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`) + }; + } + function convertReadableStreamReaderMode(mode, context) { + mode = `${mode}`; + if (mode !== 'byob') { + throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`); + } + return mode; + } + function convertByobReadOptions(options, context) { + var _a; + assertDictionary(options, context); + const min = (_a = options === null || options === void 0 ? void 0 : options.min) !== null && _a !== void 0 ? _a : 1; + return { + min: convertUnsignedLongLongWithEnforceRange(min, `${context} has member 'min' that`) + }; + } + + // Abstract operations for the ReadableStream. + function AcquireReadableStreamBYOBReader(stream) { + return new ReadableStreamBYOBReader(stream); + } + // ReadableStream API exposed for controllers. + function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { + stream._reader._readIntoRequests.push(readIntoRequest); + } + function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { + const reader = stream._reader; + const readIntoRequest = reader._readIntoRequests.shift(); + if (done) { + readIntoRequest._closeSteps(chunk); + } + else { + readIntoRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadIntoRequests(stream) { + return stream._reader._readIntoRequests.length; + } + function ReadableStreamHasBYOBReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamBYOBReader(reader)) { + return false; + } + return true; + } + /** + * A BYOB reader vended by a {@link ReadableStream}. + * + * @public + */ + class ReadableStreamBYOBReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + if (!IsReadableByteStreamController(stream._readableStreamController)) { + throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' + + 'source'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readIntoRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + read(view, rawOptions = {}) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('read')); + } + if (!ArrayBuffer.isView(view)) { + return promiseRejectedWith(new TypeError('view must be an array buffer view')); + } + if (view.byteLength === 0) { + return promiseRejectedWith(new TypeError('view must have non-zero byteLength')); + } + if (view.buffer.byteLength === 0) { + return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`)); + } + if (IsDetachedBuffer(view.buffer)) { + return promiseRejectedWith(new TypeError('view\'s buffer has been detached')); + } + let options; + try { + options = convertByobReadOptions(rawOptions, 'options'); + } + catch (e) { + return promiseRejectedWith(e); + } + const min = options.min; + if (min === 0) { + return promiseRejectedWith(new TypeError('options.min must be greater than 0')); + } + if (!isDataView(view)) { + if (min > view.length) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s length')); + } + } + else if (min > view.byteLength) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s byteLength')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readIntoRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: chunk => resolvePromise({ value: chunk, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamBYOBReader(this)) { + throw byobReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamBYOBReaderRelease(this); + } + } + Object.defineProperties(ReadableStreamBYOBReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + setFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel'); + setFunctionName(ReadableStreamBYOBReader.prototype.read, 'read'); + setFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, { + value: 'ReadableStreamBYOBReader', + configurable: true + }); + } + // Abstract operations for the readers. + function IsReadableStreamBYOBReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) { + return false; + } + return x instanceof ReadableStreamBYOBReader; + } + function ReadableStreamBYOBReaderRead(reader, view, min, readIntoRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'errored') { + readIntoRequest._errorSteps(stream._storedError); + } + else { + ReadableByteStreamControllerPullInto(stream._readableStreamController, view, min, readIntoRequest); + } + } + function ReadableStreamBYOBReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + const e = new TypeError('Reader was released'); + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); + } + function ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e) { + const readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._errorSteps(e); + }); + } + // Helper functions for the ReadableStreamBYOBReader. + function byobReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`); + } + + function ExtractHighWaterMark(strategy, defaultHWM) { + const { highWaterMark } = strategy; + if (highWaterMark === undefined) { + return defaultHWM; + } + if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { + throw new RangeError('Invalid highWaterMark'); + } + return highWaterMark; + } + function ExtractSizeAlgorithm(strategy) { + const { size } = strategy; + if (!size) { + return () => 1; + } + return size; + } + + function convertQueuingStrategy(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + const size = init === null || init === void 0 ? void 0 : init.size; + return { + highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark), + size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`) + }; + } + function convertQueuingStrategySize(fn, context) { + assertFunction(fn, context); + return chunk => convertUnrestrictedDouble(fn(chunk)); + } + + function convertUnderlyingSink(original, context) { + assertDictionary(original, context); + const abort = original === null || original === void 0 ? void 0 : original.abort; + const close = original === null || original === void 0 ? void 0 : original.close; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + const write = original === null || original === void 0 ? void 0 : original.write; + return { + abort: abort === undefined ? + undefined : + convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`), + close: close === undefined ? + undefined : + convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`), + start: start === undefined ? + undefined : + convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`), + write: write === undefined ? + undefined : + convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`), + type + }; + } + function convertUnderlyingSinkAbortCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); + } + function convertUnderlyingSinkCloseCallback(fn, original, context) { + assertFunction(fn, context); + return () => promiseCall(fn, original, []); + } + function convertUnderlyingSinkStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertUnderlyingSinkWriteCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); + } + + function assertWritableStream(x, context) { + if (!IsWritableStream(x)) { + throw new TypeError(`${context} is not a WritableStream.`); + } + } + + function isAbortSignal(value) { + if (typeof value !== 'object' || value === null) { + return false; + } + try { + return typeof value.aborted === 'boolean'; + } + catch (_a) { + // AbortSignal.prototype.aborted throws if its brand check fails + return false; + } + } + const supportsAbortController = typeof AbortController === 'function'; + /** + * Construct a new AbortController, if supported by the platform. + * + * @internal + */ + function createAbortController() { + if (supportsAbortController) { + return new AbortController(); + } + return undefined; + } + + /** + * A writable stream represents a destination for data, into which you can write. + * + * @public + */ + class WritableStream { + constructor(rawUnderlyingSink = {}, rawStrategy = {}) { + if (rawUnderlyingSink === undefined) { + rawUnderlyingSink = null; + } + else { + assertObject(rawUnderlyingSink, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter'); + InitializeWritableStream(this); + const type = underlyingSink.type; + if (type !== undefined) { + throw new RangeError('Invalid type is specified'); + } + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); + } + /** + * Returns whether or not the writable stream is locked to a writer. + */ + get locked() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('locked'); + } + return IsWritableStreamLocked(this); + } + /** + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort + * mechanism of the underlying sink. + * + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel + * the stream) if the stream is currently locked. + */ + abort(reason = undefined) { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('abort')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer')); + } + return WritableStreamAbort(this, reason); + } + /** + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its + * close behavior. During this time any further attempts to write will fail (without erroring the stream). + * + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + */ + close() { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('close')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer')); + } + if (WritableStreamCloseQueuedOrInFlight(this)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamClose(this); + } + /** + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream + * is locked, no other writer can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at + * the same time, which would cause the resulting written data to be unpredictable and probably useless. + */ + getWriter() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('getWriter'); + } + return AcquireWritableStreamDefaultWriter(this); + } + } + Object.defineProperties(WritableStream.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + getWriter: { enumerable: true }, + locked: { enumerable: true } + }); + setFunctionName(WritableStream.prototype.abort, 'abort'); + setFunctionName(WritableStream.prototype.close, 'close'); + setFunctionName(WritableStream.prototype.getWriter, 'getWriter'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, { + value: 'WritableStream', + configurable: true + }); + } + // Abstract operations for the WritableStream. + function AcquireWritableStreamDefaultWriter(stream) { + return new WritableStreamDefaultWriter(stream); + } + // Throws if and only if startAlgorithm throws. + function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(WritableStream.prototype); + InitializeWritableStream(stream); + const controller = Object.create(WritableStreamDefaultController.prototype); + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + return stream; + } + function InitializeWritableStream(stream) { + stream._state = 'writable'; + // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is + // 'erroring' or 'errored'. May be set to an undefined value. + stream._storedError = undefined; + stream._writer = undefined; + // Initialize to undefined first because the constructor of the controller checks this + // variable to validate the caller. + stream._writableStreamController = undefined; + // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data + // producer without waiting for the queued writes to finish. + stream._writeRequests = new SimpleQueue(); + // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents + // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here. + stream._inFlightWriteRequest = undefined; + // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer + // has been detached. + stream._closeRequest = undefined; + // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it + // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here. + stream._inFlightCloseRequest = undefined; + // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached. + stream._pendingAbortRequest = undefined; + // The backpressure signal set by the controller. + stream._backpressure = false; + } + function IsWritableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) { + return false; + } + return x instanceof WritableStream; + } + function IsWritableStreamLocked(stream) { + if (stream._writer === undefined) { + return false; + } + return true; + } + function WritableStreamAbort(stream, reason) { + var _a; + if (stream._state === 'closed' || stream._state === 'errored') { + return promiseResolvedWith(undefined); + } + stream._writableStreamController._abortReason = reason; + (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort(reason); + // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring', + // but it doesn't know that signaling abort runs author code that might have changed the state. + // Widen the type again by casting to WritableStreamState. + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseResolvedWith(undefined); + } + if (stream._pendingAbortRequest !== undefined) { + return stream._pendingAbortRequest._promise; + } + let wasAlreadyErroring = false; + if (state === 'erroring') { + wasAlreadyErroring = true; + // reason will not be used, so don't keep a reference to it. + reason = undefined; + } + const promise = newPromise((resolve, reject) => { + stream._pendingAbortRequest = { + _promise: undefined, + _resolve: resolve, + _reject: reject, + _reason: reason, + _wasAlreadyErroring: wasAlreadyErroring + }; + }); + stream._pendingAbortRequest._promise = promise; + if (!wasAlreadyErroring) { + WritableStreamStartErroring(stream, reason); + } + return promise; + } + function WritableStreamClose(stream) { + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`)); + } + const promise = newPromise((resolve, reject) => { + const closeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._closeRequest = closeRequest; + }); + const writer = stream._writer; + if (writer !== undefined && stream._backpressure && state === 'writable') { + defaultWriterReadyPromiseResolve(writer); + } + WritableStreamDefaultControllerClose(stream._writableStreamController); + return promise; + } + // WritableStream API exposed for controllers. + function WritableStreamAddWriteRequest(stream) { + const promise = newPromise((resolve, reject) => { + const writeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._writeRequests.push(writeRequest); + }); + return promise; + } + function WritableStreamDealWithRejection(stream, error) { + const state = stream._state; + if (state === 'writable') { + WritableStreamStartErroring(stream, error); + return; + } + WritableStreamFinishErroring(stream); + } + function WritableStreamStartErroring(stream, reason) { + const controller = stream._writableStreamController; + stream._state = 'erroring'; + stream._storedError = reason; + const writer = stream._writer; + if (writer !== undefined) { + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); + } + if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { + WritableStreamFinishErroring(stream); + } + } + function WritableStreamFinishErroring(stream) { + stream._state = 'errored'; + stream._writableStreamController[ErrorSteps](); + const storedError = stream._storedError; + stream._writeRequests.forEach(writeRequest => { + writeRequest._reject(storedError); + }); + stream._writeRequests = new SimpleQueue(); + if (stream._pendingAbortRequest === undefined) { + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const abortRequest = stream._pendingAbortRequest; + stream._pendingAbortRequest = undefined; + if (abortRequest._wasAlreadyErroring) { + abortRequest._reject(storedError); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const promise = stream._writableStreamController[AbortSteps](abortRequest._reason); + uponPromise(promise, () => { + abortRequest._resolve(); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }, (reason) => { + abortRequest._reject(reason); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }); + } + function WritableStreamFinishInFlightWrite(stream) { + stream._inFlightWriteRequest._resolve(undefined); + stream._inFlightWriteRequest = undefined; + } + function WritableStreamFinishInFlightWriteWithError(stream, error) { + stream._inFlightWriteRequest._reject(error); + stream._inFlightWriteRequest = undefined; + WritableStreamDealWithRejection(stream, error); + } + function WritableStreamFinishInFlightClose(stream) { + stream._inFlightCloseRequest._resolve(undefined); + stream._inFlightCloseRequest = undefined; + const state = stream._state; + if (state === 'erroring') { + // The error was too late to do anything, so it is ignored. + stream._storedError = undefined; + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._resolve(); + stream._pendingAbortRequest = undefined; + } + } + stream._state = 'closed'; + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseResolve(writer); + } + } + function WritableStreamFinishInFlightCloseWithError(stream, error) { + stream._inFlightCloseRequest._reject(error); + stream._inFlightCloseRequest = undefined; + // Never execute sink abort() after sink close(). + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._reject(error); + stream._pendingAbortRequest = undefined; + } + WritableStreamDealWithRejection(stream, error); + } + // TODO(ricea): Fix alphabetical order. + function WritableStreamCloseQueuedOrInFlight(stream) { + if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; + } + function WritableStreamHasOperationMarkedInFlight(stream) { + if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; + } + function WritableStreamMarkCloseRequestInFlight(stream) { + stream._inFlightCloseRequest = stream._closeRequest; + stream._closeRequest = undefined; + } + function WritableStreamMarkFirstWriteRequestInFlight(stream) { + stream._inFlightWriteRequest = stream._writeRequests.shift(); + } + function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { + if (stream._closeRequest !== undefined) { + stream._closeRequest._reject(stream._storedError); + stream._closeRequest = undefined; + } + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseReject(writer, stream._storedError); + } + } + function WritableStreamUpdateBackpressure(stream, backpressure) { + const writer = stream._writer; + if (writer !== undefined && backpressure !== stream._backpressure) { + if (backpressure) { + defaultWriterReadyPromiseReset(writer); + } + else { + defaultWriterReadyPromiseResolve(writer); + } + } + stream._backpressure = backpressure; + } + /** + * A default writer vended by a {@link WritableStream}. + * + * @public + */ + class WritableStreamDefaultWriter { + constructor(stream) { + assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter'); + assertWritableStream(stream, 'First parameter'); + if (IsWritableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive writing by another writer'); + } + this._ownerWritableStream = stream; + stream._writer = this; + const state = stream._state; + if (state === 'writable') { + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { + defaultWriterReadyPromiseInitialize(this); + } + else { + defaultWriterReadyPromiseInitializeAsResolved(this); + } + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'erroring') { + defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'closed') { + defaultWriterReadyPromiseInitializeAsResolved(this); + defaultWriterClosedPromiseInitializeAsResolved(this); + } + else { + const storedError = stream._storedError; + defaultWriterReadyPromiseInitializeAsRejected(this, storedError); + defaultWriterClosedPromiseInitializeAsRejected(this, storedError); + } + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the writer’s lock is released before the stream finishes closing. + */ + get closed() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. + * A producer can use this information to determine the right amount of data to write. + * + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when + * the writer’s lock is released. + */ + get desiredSize() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('desiredSize'); + } + if (this._ownerWritableStream === undefined) { + throw defaultWriterLockException('desiredSize'); + } + return WritableStreamDefaultWriterGetDesiredSize(this); + } + /** + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips + * back to zero or below, the getter will return a new promise that stays pending until the next transition. + * + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become + * rejected. + */ + get ready() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('ready')); + } + return this._readyPromise; + } + /** + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + */ + abort(reason = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('abort')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('abort')); + } + return WritableStreamDefaultWriterAbort(this, reason); + } + /** + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + */ + close() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('close')); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return promiseRejectedWith(defaultWriterLockException('close')); + } + if (WritableStreamCloseQueuedOrInFlight(stream)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamDefaultWriterClose(this); + } + /** + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from + * now on; otherwise, the writer will appear closed. + * + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents + * other producers from writing in an interleaved manner. + */ + releaseLock() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('releaseLock'); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return; + } + WritableStreamDefaultWriterRelease(this); + } + write(chunk = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('write')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + return WritableStreamDefaultWriterWrite(this, chunk); + } + } + Object.defineProperties(WritableStreamDefaultWriter.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + releaseLock: { enumerable: true }, + write: { enumerable: true }, + closed: { enumerable: true }, + desiredSize: { enumerable: true }, + ready: { enumerable: true } + }); + setFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort'); + setFunctionName(WritableStreamDefaultWriter.prototype.close, 'close'); + setFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock'); + setFunctionName(WritableStreamDefaultWriter.prototype.write, 'write'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, { + value: 'WritableStreamDefaultWriter', + configurable: true + }); + } + // Abstract operations for the WritableStreamDefaultWriter. + function IsWritableStreamDefaultWriter(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultWriter; + } + // A client of WritableStreamDefaultWriter may use these functions directly to bypass state check. + function WritableStreamDefaultWriterAbort(writer, reason) { + const stream = writer._ownerWritableStream; + return WritableStreamAbort(stream, reason); + } + function WritableStreamDefaultWriterClose(writer) { + const stream = writer._ownerWritableStream; + return WritableStreamClose(stream); + } + function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseResolvedWith(undefined); + } + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + return WritableStreamDefaultWriterClose(writer); + } + function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { + if (writer._closedPromiseState === 'pending') { + defaultWriterClosedPromiseReject(writer, error); + } + else { + defaultWriterClosedPromiseResetToRejected(writer, error); + } + } + function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { + if (writer._readyPromiseState === 'pending') { + defaultWriterReadyPromiseReject(writer, error); + } + else { + defaultWriterReadyPromiseResetToRejected(writer, error); + } + } + function WritableStreamDefaultWriterGetDesiredSize(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (state === 'errored' || state === 'erroring') { + return null; + } + if (state === 'closed') { + return 0; + } + return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); + } + function WritableStreamDefaultWriterRelease(writer) { + const stream = writer._ownerWritableStream; + const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`); + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); + // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not + // rejected until afterwards. This means that simply testing state will not work. + WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); + stream._writer = undefined; + writer._ownerWritableStream = undefined; + } + function WritableStreamDefaultWriterWrite(writer, chunk) { + const stream = writer._ownerWritableStream; + const controller = stream._writableStreamController; + const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); + if (stream !== writer._ownerWritableStream) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + const state = stream._state; + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to')); + } + if (state === 'erroring') { + return promiseRejectedWith(stream._storedError); + } + const promise = WritableStreamAddWriteRequest(stream); + WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); + return promise; + } + const closeSentinel = {}; + /** + * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. + * + * @public + */ + class WritableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. + * + * @deprecated + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. + */ + get abortReason() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('abortReason'); + } + return this._abortReason; + } + /** + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. + */ + get signal() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('signal'); + } + if (this._abortController === undefined) { + // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`. + // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill, + // so instead we only implement support for `signal` if we find a global `AbortController` constructor. + throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported'); + } + return this._abortController.signal; + } + /** + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. + * + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the + * normal lifecycle of interactions with the underlying sink. + */ + error(e = undefined) { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('error'); + } + const state = this._controlledWritableStream._state; + if (state !== 'writable') { + // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so + // just treat it as a no-op. + return; + } + WritableStreamDefaultControllerError(this, e); + } + /** @internal */ + [AbortSteps](reason) { + const result = this._abortAlgorithm(reason); + WritableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [ErrorSteps]() { + ResetQueue(this); + } + } + Object.defineProperties(WritableStreamDefaultController.prototype, { + abortReason: { enumerable: true }, + signal: { enumerable: true }, + error: { enumerable: true } + }); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, { + value: 'WritableStreamDefaultController', + configurable: true + }); + } + // Abstract operations implementing interface required by the WritableStream. + function IsWritableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultController; + } + function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledWritableStream = stream; + stream._writableStreamController = controller; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._abortReason = undefined; + controller._abortController = createAbortController(); + controller._started = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._writeAlgorithm = writeAlgorithm; + controller._closeAlgorithm = closeAlgorithm; + controller._abortAlgorithm = abortAlgorithm; + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + const startResult = startAlgorithm(); + const startPromise = promiseResolvedWith(startResult); + uponPromise(startPromise, () => { + controller._started = true; + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, r => { + controller._started = true; + WritableStreamDealWithRejection(stream, r); + return null; + }); + } + function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { + const controller = Object.create(WritableStreamDefaultController.prototype); + let startAlgorithm; + let writeAlgorithm; + let closeAlgorithm; + let abortAlgorithm; + if (underlyingSink.start !== undefined) { + startAlgorithm = () => underlyingSink.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingSink.write !== undefined) { + writeAlgorithm = chunk => underlyingSink.write(chunk, controller); + } + else { + writeAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSink.close !== undefined) { + closeAlgorithm = () => underlyingSink.close(); + } + else { + closeAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSink.abort !== undefined) { + abortAlgorithm = reason => underlyingSink.abort(reason); + } + else { + abortAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + } + // ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls. + function WritableStreamDefaultControllerClearAlgorithms(controller) { + controller._writeAlgorithm = undefined; + controller._closeAlgorithm = undefined; + controller._abortAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; + } + function WritableStreamDefaultControllerClose(controller) { + EnqueueValueWithSize(controller, closeSentinel, 0); + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + } + function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { + try { + return controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); + return 1; + } + } + function WritableStreamDefaultControllerGetDesiredSize(controller) { + return controller._strategyHWM - controller._queueTotalSize; + } + function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); + return; + } + const stream = controller._controlledWritableStream; + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + } + // Abstract operations for the WritableStreamDefaultController. + function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { + const stream = controller._controlledWritableStream; + if (!controller._started) { + return; + } + if (stream._inFlightWriteRequest !== undefined) { + return; + } + const state = stream._state; + if (state === 'erroring') { + WritableStreamFinishErroring(stream); + return; + } + if (controller._queue.length === 0) { + return; + } + const value = PeekQueueValue(controller); + if (value === closeSentinel) { + WritableStreamDefaultControllerProcessClose(controller); + } + else { + WritableStreamDefaultControllerProcessWrite(controller, value); + } + } + function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { + if (controller._controlledWritableStream._state === 'writable') { + WritableStreamDefaultControllerError(controller, error); + } + } + function WritableStreamDefaultControllerProcessClose(controller) { + const stream = controller._controlledWritableStream; + WritableStreamMarkCloseRequestInFlight(stream); + DequeueValue(controller); + const sinkClosePromise = controller._closeAlgorithm(); + WritableStreamDefaultControllerClearAlgorithms(controller); + uponPromise(sinkClosePromise, () => { + WritableStreamFinishInFlightClose(stream); + return null; + }, reason => { + WritableStreamFinishInFlightCloseWithError(stream, reason); + return null; + }); + } + function WritableStreamDefaultControllerProcessWrite(controller, chunk) { + const stream = controller._controlledWritableStream; + WritableStreamMarkFirstWriteRequestInFlight(stream); + const sinkWritePromise = controller._writeAlgorithm(chunk); + uponPromise(sinkWritePromise, () => { + WritableStreamFinishInFlightWrite(stream); + const state = stream._state; + DequeueValue(controller); + if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, reason => { + if (stream._state === 'writable') { + WritableStreamDefaultControllerClearAlgorithms(controller); + } + WritableStreamFinishInFlightWriteWithError(stream, reason); + return null; + }); + } + function WritableStreamDefaultControllerGetBackpressure(controller) { + const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); + return desiredSize <= 0; + } + // A client of WritableStreamDefaultController may use these functions directly to bypass state check. + function WritableStreamDefaultControllerError(controller, error) { + const stream = controller._controlledWritableStream; + WritableStreamDefaultControllerClearAlgorithms(controller); + WritableStreamStartErroring(stream, error); + } + // Helper functions for the WritableStream. + function streamBrandCheckException$2(name) { + return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`); + } + // Helper functions for the WritableStreamDefaultController. + function defaultControllerBrandCheckException$2(name) { + return new TypeError(`WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`); + } + // Helper functions for the WritableStreamDefaultWriter. + function defaultWriterBrandCheckException(name) { + return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`); + } + function defaultWriterLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released writer'); + } + function defaultWriterClosedPromiseInitialize(writer) { + writer._closedPromise = newPromise((resolve, reject) => { + writer._closedPromise_resolve = resolve; + writer._closedPromise_reject = reject; + writer._closedPromiseState = 'pending'; + }); + } + function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseReject(writer, reason); + } + function defaultWriterClosedPromiseInitializeAsResolved(writer) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseResolve(writer); + } + function defaultWriterClosedPromiseReject(writer, reason) { + if (writer._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._closedPromise); + writer._closedPromise_reject(reason); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'rejected'; + } + function defaultWriterClosedPromiseResetToRejected(writer, reason) { + defaultWriterClosedPromiseInitializeAsRejected(writer, reason); + } + function defaultWriterClosedPromiseResolve(writer) { + if (writer._closedPromise_resolve === undefined) { + return; + } + writer._closedPromise_resolve(undefined); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'resolved'; + } + function defaultWriterReadyPromiseInitialize(writer) { + writer._readyPromise = newPromise((resolve, reject) => { + writer._readyPromise_resolve = resolve; + writer._readyPromise_reject = reject; + }); + writer._readyPromiseState = 'pending'; + } + function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseReject(writer, reason); + } + function defaultWriterReadyPromiseInitializeAsResolved(writer) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseResolve(writer); + } + function defaultWriterReadyPromiseReject(writer, reason) { + if (writer._readyPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._readyPromise); + writer._readyPromise_reject(reason); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'rejected'; + } + function defaultWriterReadyPromiseReset(writer) { + defaultWriterReadyPromiseInitialize(writer); + } + function defaultWriterReadyPromiseResetToRejected(writer, reason) { + defaultWriterReadyPromiseInitializeAsRejected(writer, reason); + } + function defaultWriterReadyPromiseResolve(writer) { + if (writer._readyPromise_resolve === undefined) { + return; + } + writer._readyPromise_resolve(undefined); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'fulfilled'; + } + + /// + function getGlobals() { + if (typeof globalThis !== 'undefined') { + return globalThis; + } + else if (typeof self !== 'undefined') { + return self; + } + else if (typeof global !== 'undefined') { + return global; + } + return undefined; + } + const globals = getGlobals(); + + /// + function isDOMExceptionConstructor(ctor) { + if (!(typeof ctor === 'function' || typeof ctor === 'object')) { + return false; + } + if (ctor.name !== 'DOMException') { + return false; + } + try { + new ctor(); + return true; + } + catch (_a) { + return false; + } + } + /** + * Support: + * - Web browsers + * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87) + */ + function getFromGlobal() { + const ctor = globals === null || globals === void 0 ? void 0 : globals.DOMException; + return isDOMExceptionConstructor(ctor) ? ctor : undefined; + } + /** + * Support: + * - All platforms + */ + function createPolyfill() { + // eslint-disable-next-line @typescript-eslint/no-shadow + const ctor = function DOMException(message, name) { + this.message = message || ''; + this.name = name || 'Error'; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + }; + setFunctionName(ctor, 'DOMException'); + ctor.prototype = Object.create(Error.prototype); + Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true }); + return ctor; + } + // eslint-disable-next-line @typescript-eslint/no-redeclare + const DOMException = getFromGlobal() || createPolyfill(); + + function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { + const reader = AcquireReadableStreamDefaultReader(source); + const writer = AcquireWritableStreamDefaultWriter(dest); + source._disturbed = true; + let shuttingDown = false; + // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown. + let currentWrite = promiseResolvedWith(undefined); + return newPromise((resolve, reject) => { + let abortAlgorithm; + if (signal !== undefined) { + abortAlgorithm = () => { + const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError'); + const actions = []; + if (!preventAbort) { + actions.push(() => { + if (dest._state === 'writable') { + return WritableStreamAbort(dest, error); + } + return promiseResolvedWith(undefined); + }); + } + if (!preventCancel) { + actions.push(() => { + if (source._state === 'readable') { + return ReadableStreamCancel(source, error); + } + return promiseResolvedWith(undefined); + }); + } + shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error); + }; + if (signal.aborted) { + abortAlgorithm(); + return; + } + signal.addEventListener('abort', abortAlgorithm); + } + // Using reader and writer, read all chunks from this and write them to dest + // - Backpressure must be enforced + // - Shutdown must stop all activity + function pipeLoop() { + return newPromise((resolveLoop, rejectLoop) => { + function next(done) { + if (done) { + resolveLoop(); + } + else { + // Use `PerformPromiseThen` instead of `uponPromise` to avoid + // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers + PerformPromiseThen(pipeStep(), next, rejectLoop); + } + } + next(false); + }); + } + function pipeStep() { + if (shuttingDown) { + return promiseResolvedWith(true); + } + return PerformPromiseThen(writer._readyPromise, () => { + return newPromise((resolveRead, rejectRead) => { + ReadableStreamDefaultReaderRead(reader, { + _chunkSteps: chunk => { + currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop); + resolveRead(false); + }, + _closeSteps: () => resolveRead(true), + _errorSteps: rejectRead + }); + }); + }); + } + // Errors must be propagated forward + isOrBecomesErrored(source, reader._closedPromise, storedError => { + if (!preventAbort) { + shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Errors must be propagated backward + isOrBecomesErrored(dest, writer._closedPromise, storedError => { + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Closing must be propagated forward + isOrBecomesClosed(source, reader._closedPromise, () => { + if (!preventClose) { + shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer)); + } + else { + shutdown(); + } + return null; + }); + // Closing must be propagated backward + if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') { + const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it'); + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed); + } + else { + shutdown(true, destClosed); + } + } + setPromiseIsHandledToTrue(pipeLoop()); + function waitForWritesToFinish() { + // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait + // for that too. + const oldCurrentWrite = currentWrite; + return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined); + } + function isOrBecomesErrored(stream, promise, action) { + if (stream._state === 'errored') { + action(stream._storedError); + } + else { + uponRejection(promise, action); + } + } + function isOrBecomesClosed(stream, promise, action) { + if (stream._state === 'closed') { + action(); + } + else { + uponFulfillment(promise, action); + } + } + function shutdownWithAction(action, originalIsError, originalError) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), doTheRest); + } + else { + doTheRest(); + } + function doTheRest() { + uponPromise(action(), () => finalize(originalIsError, originalError), newError => finalize(true, newError)); + return null; + } + } + function shutdown(isError, error) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error)); + } + else { + finalize(isError, error); + } + } + function finalize(isError, error) { + WritableStreamDefaultWriterRelease(writer); + ReadableStreamReaderGenericRelease(reader); + if (signal !== undefined) { + signal.removeEventListener('abort', abortAlgorithm); + } + if (isError) { + reject(error); + } + else { + resolve(undefined); + } + return null; + } + }); + } + + /** + * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. + * + * @public + */ + class ReadableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('desiredSize'); + } + return ReadableStreamDefaultControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('close'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits close'); + } + ReadableStreamDefaultControllerClose(this); + } + enqueue(chunk = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('enqueue'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits enqueue'); + } + return ReadableStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('error'); + } + ReadableStreamDefaultControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableStream; + if (this._queue.length > 0) { + const chunk = DequeueValue(this); + if (this._closeRequested && this._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(this); + ReadableStreamClose(stream); + } + else { + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + readRequest._chunkSteps(chunk); + } + else { + ReadableStreamAddReadRequest(stream, readRequest); + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + } + /** @internal */ + [ReleaseSteps]() { + // Do nothing. + } + } + Object.defineProperties(ReadableStreamDefaultController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + desiredSize: { enumerable: true } + }); + setFunctionName(ReadableStreamDefaultController.prototype.close, 'close'); + setFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue'); + setFunctionName(ReadableStreamDefaultController.prototype.error, 'error'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, { + value: 'ReadableStreamDefaultController', + configurable: true + }); + } + // Abstract operations for the ReadableStreamDefaultController. + function IsReadableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) { + return false; + } + return x instanceof ReadableStreamDefaultController; + } + function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + return null; + }, e => { + ReadableStreamDefaultControllerError(controller, e); + return null; + }); + } + function ReadableStreamDefaultControllerShouldCallPull(controller) { + const stream = controller._controlledReadableStream; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return false; + } + if (!controller._started) { + return false; + } + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; + } + function ReadableStreamDefaultControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; + } + // A client of ReadableStreamDefaultController may use these functions directly to bypass state check. + function ReadableStreamDefaultControllerClose(controller) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + controller._closeRequested = true; + if (controller._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } + } + function ReadableStreamDefaultControllerEnqueue(controller, chunk) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + ReadableStreamFulfillReadRequest(stream, chunk, false); + } + else { + let chunkSize; + try { + chunkSize = controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + ReadableStreamDefaultControllerError(controller, chunkSizeE); + throw chunkSizeE; + } + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + ReadableStreamDefaultControllerError(controller, enqueueE); + throw enqueueE; + } + } + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + function ReadableStreamDefaultControllerError(controller, e) { + const stream = controller._controlledReadableStream; + if (stream._state !== 'readable') { + return; + } + ResetQueue(controller); + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); + } + function ReadableStreamDefaultControllerGetDesiredSize(controller) { + const state = controller._controlledReadableStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; + } + // This is used in the implementation of TransformStream. + function ReadableStreamDefaultControllerHasBackpressure(controller) { + if (ReadableStreamDefaultControllerShouldCallPull(controller)) { + return false; + } + return true; + } + function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { + const state = controller._controlledReadableStream._state; + if (!controller._closeRequested && state === 'readable') { + return true; + } + return false; + } + function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledReadableStream = stream; + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._started = false; + controller._closeRequested = false; + controller._pullAgain = false; + controller._pulling = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + return null; + }, r => { + ReadableStreamDefaultControllerError(controller, r); + return null; + }); + } + function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { + const controller = Object.create(ReadableStreamDefaultController.prototype); + let startAlgorithm; + let pullAlgorithm; + let cancelAlgorithm; + if (underlyingSource.start !== undefined) { + startAlgorithm = () => underlyingSource.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingSource.pull !== undefined) { + pullAlgorithm = () => underlyingSource.pull(controller); + } + else { + pullAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingSource.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + } + // Helper functions for the ReadableStreamDefaultController. + function defaultControllerBrandCheckException$1(name) { + return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`); + } + + function ReadableStreamTee(stream, cloneForBranch2) { + if (IsReadableByteStreamController(stream._readableStreamController)) { + return ReadableByteStreamTee(stream); + } + return ReadableStreamDefaultTee(stream); + } + function ReadableStreamDefaultTee(stream, cloneForBranch2) { + const reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgain = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function pullAlgorithm() { + if (reading) { + readAgain = true; + return promiseResolvedWith(undefined); + } + reading = true; + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgain = false; + const chunk1 = chunk; + const chunk2 = chunk; + // There is no way to access the cloning code right now in the reference implementation. + // If we add one then we'll need an implementation for serializable objects. + // if (!canceled2 && cloneForBranch2) { + // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2)); + // } + if (!canceled1) { + ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgain) { + pullAlgorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableStreamDefaultControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableStreamDefaultControllerClose(branch2._readableStreamController); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + // do nothing + } + branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); + branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); + uponRejection(reader._closedPromise, (r) => { + ReadableStreamDefaultControllerError(branch1._readableStreamController, r); + ReadableStreamDefaultControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + return [branch1, branch2]; + } + function ReadableByteStreamTee(stream) { + let reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgainForBranch1 = false; + let readAgainForBranch2 = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function forwardReaderError(thisReader) { + uponRejection(thisReader._closedPromise, r => { + if (thisReader !== reader) { + return null; + } + ReadableByteStreamControllerError(branch1._readableStreamController, r); + ReadableByteStreamControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + } + function pullWithDefaultReader() { + if (IsReadableStreamBYOBReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamDefaultReader(stream); + forwardReaderError(reader); + } + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const chunk1 = chunk; + let chunk2 = chunk; + if (!canceled1 && !canceled2) { + try { + chunk2 = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(branch1._readableStreamController, cloneE); + ReadableByteStreamControllerError(branch2._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + } + if (!canceled1) { + ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableByteStreamControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableByteStreamControllerClose(branch2._readableStreamController); + } + if (branch1._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch1._readableStreamController, 0); + } + if (branch2._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch2._readableStreamController, 0); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + } + function pullWithBYOBReader(view, forBranch2) { + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamBYOBReader(stream); + forwardReaderError(reader); + } + const byobBranch = forBranch2 ? branch2 : branch1; + const otherBranch = forBranch2 ? branch1 : branch2; + const readIntoRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!otherCanceled) { + let clonedChunk; + try { + clonedChunk = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE); + ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk); + } + else if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: chunk => { + reading = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!byobCanceled) { + ReadableByteStreamControllerClose(byobBranch._readableStreamController); + } + if (!otherCanceled) { + ReadableByteStreamControllerClose(otherBranch._readableStreamController); + } + if (chunk !== undefined) { + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0); + } + } + if (!byobCanceled || !otherCanceled) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest); + } + function pull1Algorithm() { + if (reading) { + readAgainForBranch1 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, false); + } + return promiseResolvedWith(undefined); + } + function pull2Algorithm() { + if (reading) { + readAgainForBranch2 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, true); + } + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + return; + } + branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm); + branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm); + forwardReaderError(reader); + return [branch1, branch2]; + } + + function isReadableStreamLike(stream) { + return typeIsObject(stream) && typeof stream.getReader !== 'undefined'; + } + + function ReadableStreamFrom(source) { + if (isReadableStreamLike(source)) { + return ReadableStreamFromDefaultReader(source.getReader()); + } + return ReadableStreamFromIterable(source); + } + function ReadableStreamFromIterable(asyncIterable) { + let stream; + const iteratorRecord = GetIterator(asyncIterable, 'async'); + const startAlgorithm = noop; + function pullAlgorithm() { + let nextResult; + try { + nextResult = IteratorNext(iteratorRecord); + } + catch (e) { + return promiseRejectedWith(e); + } + const nextPromise = promiseResolvedWith(nextResult); + return transformPromiseWith(nextPromise, iterResult => { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object'); + } + const done = IteratorComplete(iterResult); + if (done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + const value = IteratorValue(iterResult); + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + const iterator = iteratorRecord.iterator; + let returnMethod; + try { + returnMethod = GetMethod(iterator, 'return'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (returnMethod === undefined) { + return promiseResolvedWith(undefined); + } + let returnResult; + try { + returnResult = reflectCall(returnMethod, iterator, [reason]); + } + catch (e) { + return promiseRejectedWith(e); + } + const returnPromise = promiseResolvedWith(returnResult); + return transformPromiseWith(returnPromise, iterResult => { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object'); + } + return undefined; + }); + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; + } + function ReadableStreamFromDefaultReader(reader) { + let stream; + const startAlgorithm = noop; + function pullAlgorithm() { + let readPromise; + try { + readPromise = reader.read(); + } + catch (e) { + return promiseRejectedWith(e); + } + return transformPromiseWith(readPromise, readResult => { + if (!typeIsObject(readResult)) { + throw new TypeError('The promise returned by the reader.read() method must fulfill with an object'); + } + if (readResult.done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + const value = readResult.value; + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + try { + return promiseResolvedWith(reader.cancel(reason)); + } + catch (e) { + return promiseRejectedWith(e); + } + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; + } + + function convertUnderlyingDefaultOrByteSource(source, context) { + assertDictionary(source, context); + const original = source; + const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; + const cancel = original === null || original === void 0 ? void 0 : original.cancel; + const pull = original === null || original === void 0 ? void 0 : original.pull; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + return { + autoAllocateChunkSize: autoAllocateChunkSize === undefined ? + undefined : + convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`), + cancel: cancel === undefined ? + undefined : + convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`), + pull: pull === undefined ? + undefined : + convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`), + start: start === undefined ? + undefined : + convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`), + type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`) + }; + } + function convertUnderlyingSourceCancelCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); + } + function convertUnderlyingSourcePullCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); + } + function convertUnderlyingSourceStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertReadableStreamType(type, context) { + type = `${type}`; + if (type !== 'bytes') { + throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`); + } + return type; + } + + function convertIteratorOptions(options, context) { + assertDictionary(options, context); + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + return { preventCancel: Boolean(preventCancel) }; + } + + function convertPipeOptions(options, context) { + assertDictionary(options, context); + const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort; + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + const preventClose = options === null || options === void 0 ? void 0 : options.preventClose; + const signal = options === null || options === void 0 ? void 0 : options.signal; + if (signal !== undefined) { + assertAbortSignal(signal, `${context} has member 'signal' that`); + } + return { + preventAbort: Boolean(preventAbort), + preventCancel: Boolean(preventCancel), + preventClose: Boolean(preventClose), + signal + }; + } + function assertAbortSignal(signal, context) { + if (!isAbortSignal(signal)) { + throw new TypeError(`${context} is not an AbortSignal.`); + } + } + + function convertReadableWritablePair(pair, context) { + assertDictionary(pair, context); + const readable = pair === null || pair === void 0 ? void 0 : pair.readable; + assertRequiredField(readable, 'readable', 'ReadableWritablePair'); + assertReadableStream(readable, `${context} has member 'readable' that`); + const writable = pair === null || pair === void 0 ? void 0 : pair.writable; + assertRequiredField(writable, 'writable', 'ReadableWritablePair'); + assertWritableStream(writable, `${context} has member 'writable' that`); + return { readable, writable }; + } + + /** + * A readable stream represents a source of data, from which you can read. + * + * @public + */ + class ReadableStream { + constructor(rawUnderlyingSource = {}, rawStrategy = {}) { + if (rawUnderlyingSource === undefined) { + rawUnderlyingSource = null; + } + else { + assertObject(rawUnderlyingSource, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter'); + InitializeReadableStream(this); + if (underlyingSource.type === 'bytes') { + if (strategy.size !== undefined) { + throw new RangeError('The strategy for a byte stream cannot have a size function'); + } + const highWaterMark = ExtractHighWaterMark(strategy, 0); + SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); + } + else { + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); + } + } + /** + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. + */ + get locked() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('locked'); + } + return IsReadableStreamLocked(this); + } + /** + * Cancels the stream, signaling a loss of interest in the stream by a consumer. + * + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} + * method, which might or might not use it. + */ + cancel(reason = undefined) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('cancel')); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader')); + } + return ReadableStreamCancel(this, reason); + } + getReader(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('getReader'); + } + const options = convertReaderOptions(rawOptions, 'First parameter'); + if (options.mode === undefined) { + return AcquireReadableStreamDefaultReader(this); + } + return AcquireReadableStreamBYOBReader(this); + } + pipeThrough(rawTransform, rawOptions = {}) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('pipeThrough'); + } + assertRequiredArgument(rawTransform, 1, 'pipeThrough'); + const transform = convertReadableWritablePair(rawTransform, 'First parameter'); + const options = convertPipeOptions(rawOptions, 'Second parameter'); + if (IsReadableStreamLocked(this)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream'); + } + if (IsWritableStreamLocked(transform.writable)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream'); + } + const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + setPromiseIsHandledToTrue(promise); + return transform.readable; + } + pipeTo(destination, rawOptions = {}) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('pipeTo')); + } + if (destination === undefined) { + return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`); + } + if (!IsWritableStream(destination)) { + return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)); + } + let options; + try { + options = convertPipeOptions(rawOptions, 'Second parameter'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')); + } + if (IsWritableStreamLocked(destination)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')); + } + return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + } + /** + * Tees this readable stream, returning a two-element array containing the two resulting branches as + * new {@link ReadableStream} instances. + * + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be + * propagated to the stream's underlying source. + * + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, + * this could allow interference between the two branches. + */ + tee() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('tee'); + } + const branches = ReadableStreamTee(this); + return CreateArrayFromList(branches); + } + values(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('values'); + } + const options = convertIteratorOptions(rawOptions, 'First parameter'); + return AcquireReadableStreamAsyncIterator(this, options.preventCancel); + } + [SymbolAsyncIterator](options) { + // Stub implementation, overridden below + return this.values(options); + } + /** + * Creates a new ReadableStream wrapping the provided iterable or async iterable. + * + * This can be used to adapt various kinds of objects into a readable stream, + * such as an array, an async generator, or a Node.js readable stream. + */ + static from(asyncIterable) { + return ReadableStreamFrom(asyncIterable); + } + } + Object.defineProperties(ReadableStream, { + from: { enumerable: true } + }); + Object.defineProperties(ReadableStream.prototype, { + cancel: { enumerable: true }, + getReader: { enumerable: true }, + pipeThrough: { enumerable: true }, + pipeTo: { enumerable: true }, + tee: { enumerable: true }, + values: { enumerable: true }, + locked: { enumerable: true } + }); + setFunctionName(ReadableStream.from, 'from'); + setFunctionName(ReadableStream.prototype.cancel, 'cancel'); + setFunctionName(ReadableStream.prototype.getReader, 'getReader'); + setFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough'); + setFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo'); + setFunctionName(ReadableStream.prototype.tee, 'tee'); + setFunctionName(ReadableStream.prototype.values, 'values'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, { + value: 'ReadableStream', + configurable: true + }); + } + Object.defineProperty(ReadableStream.prototype, SymbolAsyncIterator, { + value: ReadableStream.prototype.values, + writable: true, + configurable: true + }); + // Abstract operations for the ReadableStream. + // Throws if and only if startAlgorithm throws. + function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableStreamDefaultController.prototype); + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + return stream; + } + // Throws if and only if startAlgorithm throws. + function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableByteStreamController.prototype); + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined); + return stream; + } + function InitializeReadableStream(stream) { + stream._state = 'readable'; + stream._reader = undefined; + stream._storedError = undefined; + stream._disturbed = false; + } + function IsReadableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) { + return false; + } + return x instanceof ReadableStream; + } + function IsReadableStreamLocked(stream) { + if (stream._reader === undefined) { + return false; + } + return true; + } + // ReadableStream API exposed for controllers. + function ReadableStreamCancel(stream, reason) { + stream._disturbed = true; + if (stream._state === 'closed') { + return promiseResolvedWith(undefined); + } + if (stream._state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + ReadableStreamClose(stream); + const reader = stream._reader; + if (reader !== undefined && IsReadableStreamBYOBReader(reader)) { + const readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._closeSteps(undefined); + }); + } + const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); + return transformPromiseWith(sourceCancelPromise, noop); + } + function ReadableStreamClose(stream) { + stream._state = 'closed'; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseResolve(reader); + if (IsReadableStreamDefaultReader(reader)) { + const readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(readRequest => { + readRequest._closeSteps(); + }); + } + } + function ReadableStreamError(stream, e) { + stream._state = 'errored'; + stream._storedError = e; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseReject(reader, e); + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamDefaultReaderErrorReadRequests(reader, e); + } + else { + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); + } + } + // Helper functions for the ReadableStream. + function streamBrandCheckException$1(name) { + return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`); + } + + function convertQueuingStrategyInit(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit'); + return { + highWaterMark: convertUnrestrictedDouble(highWaterMark) + }; + } + + // The size function must not have a prototype property nor be a constructor + const byteLengthSizeFunction = (chunk) => { + return chunk.byteLength; + }; + setFunctionName(byteLengthSizeFunction, 'size'); + /** + * A queuing strategy that counts the number of bytes in each chunk. + * + * @public + */ + class ByteLengthQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('highWaterMark'); + } + return this._byteLengthQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by returning the value of its `byteLength` property. + */ + get size() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('size'); + } + return byteLengthSizeFunction; + } + } + Object.defineProperties(ByteLengthQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, { + value: 'ByteLengthQueuingStrategy', + configurable: true + }); + } + // Helper functions for the ByteLengthQueuingStrategy. + function byteLengthBrandCheckException(name) { + return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`); + } + function IsByteLengthQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof ByteLengthQueuingStrategy; + } + + // The size function must not have a prototype property nor be a constructor + const countSizeFunction = () => { + return 1; + }; + setFunctionName(countSizeFunction, 'size'); + /** + * A queuing strategy that counts the number of chunks. + * + * @public + */ + class CountQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'CountQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._countQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('highWaterMark'); + } + return this._countQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by always returning 1. + * This ensures that the total queue size is a count of the number of chunks in the queue. + */ + get size() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('size'); + } + return countSizeFunction; + } + } + Object.defineProperties(CountQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, { + value: 'CountQueuingStrategy', + configurable: true + }); + } + // Helper functions for the CountQueuingStrategy. + function countBrandCheckException(name) { + return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`); + } + function IsCountQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof CountQueuingStrategy; + } + + function convertTransformer(original, context) { + assertDictionary(original, context); + const cancel = original === null || original === void 0 ? void 0 : original.cancel; + const flush = original === null || original === void 0 ? void 0 : original.flush; + const readableType = original === null || original === void 0 ? void 0 : original.readableType; + const start = original === null || original === void 0 ? void 0 : original.start; + const transform = original === null || original === void 0 ? void 0 : original.transform; + const writableType = original === null || original === void 0 ? void 0 : original.writableType; + return { + cancel: cancel === undefined ? + undefined : + convertTransformerCancelCallback(cancel, original, `${context} has member 'cancel' that`), + flush: flush === undefined ? + undefined : + convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`), + readableType, + start: start === undefined ? + undefined : + convertTransformerStartCallback(start, original, `${context} has member 'start' that`), + transform: transform === undefined ? + undefined : + convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`), + writableType + }; + } + function convertTransformerFlushCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); + } + function convertTransformerStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertTransformerTransformCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); + } + function convertTransformerCancelCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); + } + + // Class TransformStream + /** + * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, + * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. + * In a manner specific to the transform stream in question, writes to the writable side result in new data being + * made available for reading from the readable side. + * + * @public + */ + class TransformStream { + constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) { + if (rawTransformer === undefined) { + rawTransformer = null; + } + const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter'); + const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter'); + const transformer = convertTransformer(rawTransformer, 'First parameter'); + if (transformer.readableType !== undefined) { + throw new RangeError('Invalid readableType specified'); + } + if (transformer.writableType !== undefined) { + throw new RangeError('Invalid writableType specified'); + } + const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); + const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); + const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); + const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); + let startPromise_resolve; + const startPromise = newPromise(resolve => { + startPromise_resolve = resolve; + }); + InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); + if (transformer.start !== undefined) { + startPromise_resolve(transformer.start(this._transformStreamController)); + } + else { + startPromise_resolve(undefined); + } + } + /** + * The readable side of the transform stream. + */ + get readable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('readable'); + } + return this._readable; + } + /** + * The writable side of the transform stream. + */ + get writable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('writable'); + } + return this._writable; + } + } + Object.defineProperties(TransformStream.prototype, { + readable: { enumerable: true }, + writable: { enumerable: true } + }); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, { + value: 'TransformStream', + configurable: true + }); + } + function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { + function startAlgorithm() { + return startPromise; + } + function writeAlgorithm(chunk) { + return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); + } + function abortAlgorithm(reason) { + return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); + } + function closeAlgorithm() { + return TransformStreamDefaultSinkCloseAlgorithm(stream); + } + stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); + function pullAlgorithm() { + return TransformStreamDefaultSourcePullAlgorithm(stream); + } + function cancelAlgorithm(reason) { + return TransformStreamDefaultSourceCancelAlgorithm(stream, reason); + } + stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure. + stream._backpressure = undefined; + stream._backpressureChangePromise = undefined; + stream._backpressureChangePromise_resolve = undefined; + TransformStreamSetBackpressure(stream, true); + stream._transformStreamController = undefined; + } + function IsTransformStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) { + return false; + } + return x instanceof TransformStream; + } + // This is a no-op if both sides are already errored. + function TransformStreamError(stream, e) { + ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e); + TransformStreamErrorWritableAndUnblockWrite(stream, e); + } + function TransformStreamErrorWritableAndUnblockWrite(stream, e) { + TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); + WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e); + TransformStreamUnblockWrite(stream); + } + function TransformStreamUnblockWrite(stream) { + if (stream._backpressure) { + // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure() + // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time + // _backpressure is set. + TransformStreamSetBackpressure(stream, false); + } + } + function TransformStreamSetBackpressure(stream, backpressure) { + // Passes also when called during construction. + if (stream._backpressureChangePromise !== undefined) { + stream._backpressureChangePromise_resolve(); + } + stream._backpressureChangePromise = newPromise(resolve => { + stream._backpressureChangePromise_resolve = resolve; + }); + stream._backpressure = backpressure; + } + // Class TransformStreamDefaultController + /** + * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. + * + * @public + */ + class TransformStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. + */ + get desiredSize() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('desiredSize'); + } + const readableController = this._controlledTransformStream._readable._readableStreamController; + return ReadableStreamDefaultControllerGetDesiredSize(readableController); + } + enqueue(chunk = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('enqueue'); + } + TransformStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors both the readable side and the writable side of the controlled transform stream, making all future + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. + */ + error(reason = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('error'); + } + TransformStreamDefaultControllerError(this, reason); + } + /** + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the + * transformer only needs to consume a portion of the chunks written to the writable side. + */ + terminate() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('terminate'); + } + TransformStreamDefaultControllerTerminate(this); + } + } + Object.defineProperties(TransformStreamDefaultController.prototype, { + enqueue: { enumerable: true }, + error: { enumerable: true }, + terminate: { enumerable: true }, + desiredSize: { enumerable: true } + }); + setFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue'); + setFunctionName(TransformStreamDefaultController.prototype.error, 'error'); + setFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, { + value: 'TransformStreamDefaultController', + configurable: true + }); + } + // Transform Stream Default Controller Abstract Operations + function IsTransformStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) { + return false; + } + return x instanceof TransformStreamDefaultController; + } + function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm) { + controller._controlledTransformStream = stream; + stream._transformStreamController = controller; + controller._transformAlgorithm = transformAlgorithm; + controller._flushAlgorithm = flushAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._finishPromise = undefined; + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; + } + function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { + const controller = Object.create(TransformStreamDefaultController.prototype); + let transformAlgorithm; + let flushAlgorithm; + let cancelAlgorithm; + if (transformer.transform !== undefined) { + transformAlgorithm = chunk => transformer.transform(chunk, controller); + } + else { + transformAlgorithm = chunk => { + try { + TransformStreamDefaultControllerEnqueue(controller, chunk); + return promiseResolvedWith(undefined); + } + catch (transformResultE) { + return promiseRejectedWith(transformResultE); + } + }; + } + if (transformer.flush !== undefined) { + flushAlgorithm = () => transformer.flush(controller); + } + else { + flushAlgorithm = () => promiseResolvedWith(undefined); + } + if (transformer.cancel !== undefined) { + cancelAlgorithm = reason => transformer.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm); + } + function TransformStreamDefaultControllerClearAlgorithms(controller) { + controller._transformAlgorithm = undefined; + controller._flushAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + } + function TransformStreamDefaultControllerEnqueue(controller, chunk) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { + throw new TypeError('Readable side is not in a state that permits enqueue'); + } + // We throttle transform invocations based on the backpressure of the ReadableStream, but we still + // accept TransformStreamDefaultControllerEnqueue() calls. + try { + ReadableStreamDefaultControllerEnqueue(readableController, chunk); + } + catch (e) { + // This happens when readableStrategy.size() throws. + TransformStreamErrorWritableAndUnblockWrite(stream, e); + throw stream._readable._storedError; + } + const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); + if (backpressure !== stream._backpressure) { + TransformStreamSetBackpressure(stream, true); + } + } + function TransformStreamDefaultControllerError(controller, e) { + TransformStreamError(controller._controlledTransformStream, e); + } + function TransformStreamDefaultControllerPerformTransform(controller, chunk) { + const transformPromise = controller._transformAlgorithm(chunk); + return transformPromiseWith(transformPromise, undefined, r => { + TransformStreamError(controller._controlledTransformStream, r); + throw r; + }); + } + function TransformStreamDefaultControllerTerminate(controller) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + ReadableStreamDefaultControllerClose(readableController); + const error = new TypeError('TransformStream terminated'); + TransformStreamErrorWritableAndUnblockWrite(stream, error); + } + // TransformStreamDefaultSink Algorithms + function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { + const controller = stream._transformStreamController; + if (stream._backpressure) { + const backpressureChangePromise = stream._backpressureChangePromise; + return transformPromiseWith(backpressureChangePromise, () => { + const writable = stream._writable; + const state = writable._state; + if (state === 'erroring') { + throw writable._storedError; + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + }); + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + } + function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + const readable = stream._readable; + // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally, + // we don't run the _cancelAlgorithm again. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, () => { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerError(readable._readableStreamController, reason); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; + } + function TransformStreamDefaultSinkCloseAlgorithm(stream) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + const readable = stream._readable; + // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally, + // we don't also run the _cancelAlgorithm. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const flushPromise = controller._flushAlgorithm(); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(flushPromise, () => { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerClose(readable._readableStreamController); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; + } + // TransformStreamDefaultSource Algorithms + function TransformStreamDefaultSourcePullAlgorithm(stream) { + // Invariant. Enforced by the promises returned by start() and pull(). + TransformStreamSetBackpressure(stream, false); + // Prevent the next pull() call until there is backpressure. + return stream._backpressureChangePromise; + } + function TransformStreamDefaultSourceCancelAlgorithm(stream, reason) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._writable cannot change after construction, so caching it across a call to user code is safe. + const writable = stream._writable; + // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or + // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the + // _flushAlgorithm. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, () => { + if (writable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, writable._storedError); + } + else { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; + } + // Helper functions for the TransformStreamDefaultController. + function defaultControllerBrandCheckException(name) { + return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`); + } + function defaultControllerFinishPromiseResolve(controller) { + if (controller._finishPromise_resolve === undefined) { + return; + } + controller._finishPromise_resolve(); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; + } + function defaultControllerFinishPromiseReject(controller, reason) { + if (controller._finishPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(controller._finishPromise); + controller._finishPromise_reject(reason); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; + } + // Helper functions for the TransformStream. + function streamBrandCheckException(name) { + return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`); + } + + const exports$1 = { + ReadableStream, + ReadableStreamDefaultController, + ReadableByteStreamController, + ReadableStreamBYOBRequest, + ReadableStreamDefaultReader, + ReadableStreamBYOBReader, + WritableStream, + WritableStreamDefaultController, + WritableStreamDefaultWriter, + ByteLengthQueuingStrategy, + CountQueuingStrategy, + TransformStream, + TransformStreamDefaultController + }; + // Add classes to global scope + if (typeof globals !== 'undefined') { + for (const prop in exports$1) { + if (Object.prototype.hasOwnProperty.call(exports$1, prop)) { + Object.defineProperty(globals, prop, { + value: exports$1[prop], + writable: true, + configurable: true + }); + } + } + } + + exports.ByteLengthQueuingStrategy = ByteLengthQueuingStrategy; + exports.CountQueuingStrategy = CountQueuingStrategy; + exports.ReadableByteStreamController = ReadableByteStreamController; + exports.ReadableStream = ReadableStream; + exports.ReadableStreamBYOBReader = ReadableStreamBYOBReader; + exports.ReadableStreamBYOBRequest = ReadableStreamBYOBRequest; + exports.ReadableStreamDefaultController = ReadableStreamDefaultController; + exports.ReadableStreamDefaultReader = ReadableStreamDefaultReader; + exports.TransformStream = TransformStream; + exports.TransformStreamDefaultController = TransformStreamDefaultController; + exports.WritableStream = WritableStream; + exports.WritableStreamDefaultController = WritableStreamDefaultController; + exports.WritableStreamDefaultWriter = WritableStreamDefaultWriter; + +})); +//# sourceMappingURL=polyfill.es2018.js.map diff --git a/backend/node_modules/web-streams-polyfill/dist/polyfill.es2018.js.map b/backend/node_modules/web-streams-polyfill/dist/polyfill.es2018.js.map new file mode 100644 index 0000000000000000000000000000000000000000..cffe625b72188f75e421713845643c18ffa351dc --- /dev/null +++ b/backend/node_modules/web-streams-polyfill/dist/polyfill.es2018.js.map @@ -0,0 +1 @@ +{"version":3,"file":"polyfill.es2018.js","sources":["../src/utils.ts","../src/lib/helpers/miscellaneous.ts","../src/lib/helpers/webidl.ts","../src/lib/simple-queue.ts","../src/lib/abstract-ops/internal-methods.ts","../src/lib/readable-stream/generic-reader.ts","../src/stub/number-isfinite.ts","../src/stub/math-trunc.ts","../src/lib/validators/basic.ts","../src/lib/validators/readable-stream.ts","../src/lib/readable-stream/default-reader.ts","../src/target/es2018/stub/async-iterator-prototype.ts","../src/lib/readable-stream/async-iterator.ts","../src/stub/number-isnan.ts","../src/lib/abstract-ops/ecmascript.ts","../src/lib/abstract-ops/miscellaneous.ts","../src/lib/abstract-ops/queue-with-sizes.ts","../src/lib/helpers/array-buffer-view.ts","../src/lib/readable-stream/byte-stream-controller.ts","../src/lib/validators/reader-options.ts","../src/lib/readable-stream/byob-reader.ts","../src/lib/abstract-ops/queuing-strategy.ts","../src/lib/validators/queuing-strategy.ts","../src/lib/validators/underlying-sink.ts","../src/lib/validators/writable-stream.ts","../src/lib/abort-signal.ts","../src/lib/writable-stream.ts","../src/globals.ts","../src/stub/dom-exception.ts","../src/lib/readable-stream/pipe.ts","../src/lib/readable-stream/default-controller.ts","../src/lib/readable-stream/tee.ts","../src/lib/readable-stream/readable-stream-like.ts","../src/lib/readable-stream/from.ts","../src/lib/validators/underlying-source.ts","../src/lib/validators/iterator-options.ts","../src/lib/validators/pipe-options.ts","../src/lib/validators/readable-writable-pair.ts","../src/lib/readable-stream.ts","../src/lib/validators/queuing-strategy-init.ts","../src/lib/byte-length-queuing-strategy.ts","../src/lib/count-queuing-strategy.ts","../src/lib/validators/transformer.ts","../src/lib/transform-stream.ts","../src/polyfill.ts"],"sourcesContent":["export function noop(): undefined {\n return undefined;\n}\n","import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n\nexport function setFunctionName(fn: Function, name: string): void {\n try {\n Object.defineProperty(fn, 'name', {\n value: name,\n configurable: true\n });\n } catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n }\n}\n","import { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\n// https://webidl.spec.whatwg.org/#a-new-promise\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-resolved-with\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return newPromise(resolve => resolve(value));\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-rejected-with\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\n// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned\n// from that handler. To prevent this, return null instead of void from all handlers.\n// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => null | PromiseLike,\n onRejected?: (reason: any) => null | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => null | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => null | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nlet _queueMicrotask: (callback: () => void) => void = callback => {\n if (typeof queueMicrotask === 'function') {\n _queueMicrotask = queueMicrotask;\n } else {\n const resolvedPromise = promiseResolvedWith(undefined);\n _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb);\n }\n return _queueMicrotask(callback);\n};\n\nexport { _queueMicrotask as queueMicrotask };\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n","import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n","export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\nexport const ReleaseSteps = Symbol('[[ReleaseSteps]]');\n","import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, type ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\nimport { ReleaseSteps } from '../abstract-ops/internal-methods';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n assert(stream._reader === reader);\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n stream._readableStreamController[ReleaseSteps]();\n\n stream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n","import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n","import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamDefaultReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamDefaultReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\nexport function ReadableStreamDefaultReaderRelease(reader: ReadableStreamDefaultReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n}\n\nexport function ReadableStreamDefaultReaderErrorReadRequests(reader: ReadableStreamDefaultReader, e: any) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n","/// \n\n/* eslint-disable @typescript-eslint/no-empty-function */\nexport const AsyncIteratorPrototype: AsyncIterable =\n Object.getPrototypeOf(Object.getPrototypeOf(async function* (): AsyncIterableIterator {}).prototype);\n","/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadableStreamDefaultReadResult,\n type ReadRequest\n} from './default-reader';\nimport { ReadableStreamReaderGenericCancel, ReadableStreamReaderGenericRelease } from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterableIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ninterface ReadableStreamAsyncIteratorInstance extends ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nObject.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n","import { reflectCall } from 'lib/helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport assert from '../../stub/assert';\n\ndeclare global {\n interface ArrayBuffer {\n readonly detached: boolean;\n\n transfer(): ArrayBuffer;\n }\n\n function structuredClone(value: T, options: { transfer: ArrayBuffer[] }): T;\n}\n\nexport function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\nexport let TransferArrayBuffer = (O: ArrayBuffer): ArrayBuffer => {\n if (typeof O.transfer === 'function') {\n TransferArrayBuffer = buffer => buffer.transfer();\n } else if (typeof structuredClone === 'function') {\n TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] });\n } else {\n // Not implemented correctly\n TransferArrayBuffer = buffer => buffer;\n }\n return TransferArrayBuffer(O);\n};\n\nexport function CanTransferArrayBuffer(O: ArrayBuffer): boolean {\n return !IsDetachedBuffer(O);\n}\n\nexport let IsDetachedBuffer = (O: ArrayBuffer): boolean => {\n if (typeof O.detached === 'boolean') {\n IsDetachedBuffer = buffer => buffer.detached;\n } else {\n // Not implemented correctly\n IsDetachedBuffer = buffer => buffer.byteLength === 0;\n }\n return IsDetachedBuffer(O);\n};\n\nexport function ArrayBufferSlice(buffer: ArrayBuffer, begin: number, end: number): ArrayBuffer {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n\nexport type MethodName = {\n [P in keyof T]: T[P] extends Function | undefined ? P : never;\n}[keyof T];\n\nexport function GetMethod>(receiver: T, prop: K): T[K] | undefined {\n const func = receiver[prop];\n if (func === undefined || func === null) {\n return undefined;\n }\n if (typeof func !== 'function') {\n throw new TypeError(`${String(prop)} is not a function`);\n }\n return func;\n}\n\nexport interface SyncIteratorRecord {\n iterator: Iterator,\n nextMethod: Iterator['next'],\n done: boolean;\n}\n\nexport interface AsyncIteratorRecord {\n iterator: AsyncIterator,\n nextMethod: AsyncIterator['next'],\n done: boolean;\n}\n\nexport type SyncOrAsyncIteratorRecord = SyncIteratorRecord | AsyncIteratorRecord;\n\nexport function CreateAsyncFromSyncIterator(syncIteratorRecord: SyncIteratorRecord): AsyncIteratorRecord {\n // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%,\n // we use yield* inside an async generator function to achieve the same result.\n\n // Wrap the sync iterator inside a sync iterable, so we can use it with yield*.\n const syncIterable = {\n [Symbol.iterator]: () => syncIteratorRecord.iterator\n };\n // Create an async generator function and immediately invoke it.\n const asyncIterator = (async function* () {\n return yield* syncIterable;\n }());\n // Return as an async iterator record.\n const nextMethod = asyncIterator.next;\n return { iterator: asyncIterator, nextMethod, done: false };\n}\n\n// Aligns with core-js/modules/es.symbol.async-iterator.js\nexport const SymbolAsyncIterator: (typeof Symbol)['asyncIterator'] =\n Symbol.asyncIterator ??\n Symbol.for?.('Symbol.asyncIterator') ??\n '@@asyncIterator';\n\nexport type SyncOrAsyncIterable = Iterable | AsyncIterable;\nexport type SyncOrAsyncIteratorMethod = () => (Iterator | AsyncIterator);\n\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint: 'async',\n method?: SyncOrAsyncIteratorMethod\n): AsyncIteratorRecord;\nfunction GetIterator(\n obj: Iterable,\n hint: 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncIteratorRecord;\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint = 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncOrAsyncIteratorRecord {\n assert(hint === 'sync' || hint === 'async');\n if (method === undefined) {\n if (hint === 'async') {\n method = GetMethod(obj as AsyncIterable, SymbolAsyncIterator);\n if (method === undefined) {\n const syncMethod = GetMethod(obj as Iterable, Symbol.iterator);\n const syncIteratorRecord = GetIterator(obj as Iterable, 'sync', syncMethod);\n return CreateAsyncFromSyncIterator(syncIteratorRecord);\n }\n } else {\n method = GetMethod(obj as Iterable, Symbol.iterator);\n }\n }\n if (method === undefined) {\n throw new TypeError('The object is not iterable');\n }\n const iterator = reflectCall(method, obj, []);\n if (!typeIsObject(iterator)) {\n throw new TypeError('The iterator method must return an object');\n }\n const nextMethod = iterator.next;\n return { iterator, nextMethod, done: false } as SyncOrAsyncIteratorRecord;\n}\n\nexport { GetIterator };\n\nexport function IteratorNext(iteratorRecord: AsyncIteratorRecord): Promise> {\n const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []);\n if (!typeIsObject(result)) {\n throw new TypeError('The iterator.next() method must return an object');\n }\n return result;\n}\n\nexport function IteratorComplete(\n iterResult: IteratorResult\n): iterResult is IteratorReturnResult {\n assert(typeIsObject(iterResult));\n return Boolean(iterResult.done);\n}\n\nexport function IteratorValue(iterResult: IteratorYieldResult): T {\n assert(typeIsObject(iterResult));\n return iterResult.value;\n}\n","import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: NonShared): NonShared {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer) as NonShared;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n","export type TypedArray =\n | Int8Array\n | Uint8Array\n | Uint8ClampedArray\n | Int16Array\n | Uint16Array\n | Int32Array\n | Uint32Array\n | Float32Array\n | Float64Array;\n\nexport type NonShared = T & {\n buffer: ArrayBuffer;\n}\n\nexport interface ArrayBufferViewConstructor {\n new(buffer: ArrayBuffer, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n}\n\nexport interface TypedArrayConstructor extends ArrayBufferViewConstructor {\n readonly BYTES_PER_ELEMENT: number;\n}\n\nexport type DataViewConstructor = ArrayBufferViewConstructor;\n\nfunction isDataViewConstructor(ctor: Function): ctor is DataViewConstructor {\n return ctor === DataView;\n}\n\nexport function isDataView(view: ArrayBufferView): view is DataView {\n return isDataViewConstructor(view.constructor);\n}\n\nexport function arrayBufferViewElementSize(ctor: ArrayBufferViewConstructor): number {\n if (isDataViewConstructor(ctor)) {\n return 1;\n }\n return (ctor as unknown as TypedArrayConstructor).BYTES_PER_ELEMENT;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n IsReadableStreamDefaultReader,\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n type ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n type ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n type ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport type { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\nimport {\n type ArrayBufferViewConstructor,\n arrayBufferViewElementSize,\n type NonShared,\n type TypedArrayConstructor\n} from '../helpers/array-buffer-view';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: NonShared | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: NonShared): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond');\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBuffer;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor = NonShared> =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: TypedArrayConstructor;\n readerType: 'default' | 'none';\n}\n\ninterface BYOBPullIntoDescriptor = NonShared> {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob' | 'none';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: NonShared): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest>): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n minimumFill: 1,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n if (this._pendingPullIntos.length > 0) {\n const firstPullInto = this._pendingPullIntos.peek();\n firstPullInto.readerType = 'none';\n\n this._pendingPullIntos = new SimpleQueue();\n this._pendingPullIntos.push(firstPullInto);\n }\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableByteStreamController.prototype.close, 'close');\nsetFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableByteStreamController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor>(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n assert(pullIntoDescriptor.readerType !== 'none');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as NonShared, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor>(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n let clonedChunk;\n try {\n clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength);\n } catch (cloneE) {\n ReadableByteStreamControllerError(controller, cloneE);\n throw cloneE;\n }\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength);\n}\n\nfunction ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.readerType === 'none');\n if (firstDescriptor.bytesFilled > 0) {\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n firstDescriptor.buffer,\n firstDescriptor.byteOffset,\n firstDescriptor.bytesFilled\n );\n }\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize;\n const maxAlignedBytes = maxBytesFilled - remainderBytes;\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n assert(pullIntoDescriptor.readerType !== 'none');\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nfunction ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller: ReadableByteStreamController) {\n const reader = controller._controlledReadableByteStream._reader;\n assert(IsReadableStreamDefaultReader(reader));\n while (reader._readRequests.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n const readRequest = reader._readRequests.shift();\n ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest);\n }\n}\n\nexport function ReadableByteStreamControllerPullInto>(\n controller: ReadableByteStreamController,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n const elementSize = arrayBufferViewElementSize(ctor);\n\n const { byteOffset, byteLength } = view;\n\n const minimumFill = min * elementSize;\n assert(minimumFill >= elementSize && minimumFill <= byteLength);\n assert(minimumFill % elementSize === 0);\n\n let buffer: ArrayBuffer;\n try {\n buffer = TransferArrayBuffer(view.buffer);\n } catch (e) {\n readIntoRequest._errorSteps(e);\n return;\n }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset,\n byteLength,\n bytesFilled: 0,\n minimumFill,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled % firstDescriptor.elementSize === 0);\n\n if (firstDescriptor.readerType === 'none') {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n return;\n }\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) {\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n pullIntoDescriptor.buffer,\n end - remainderSize,\n remainderSize\n );\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(\n controller: ReadableByteStreamController,\n chunk: NonShared\n) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const { buffer, byteOffset, byteLength } = chunk;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n if (firstPendingPullInto.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto);\n }\n }\n\n if (ReadableStreamHasDefaultReader(stream)) {\n ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller);\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView as NonShared, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerFillReadRequestFromQueue(\n controller: ReadableByteStreamController,\n readRequest: ReadRequest>\n) {\n assert(controller._queueTotalSize > 0);\n\n const entry = controller._queue.shift();\n controller._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n readRequest._chunkSteps(view as NonShared);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view as NonShared);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: NonShared) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: NonShared) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n","import { assertDictionary, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n\nexport function convertByobReadOptions(\n options: ReadableStreamBYOBReaderReadOptions | null | undefined,\n context: string\n): ValidatedReadableStreamBYOBReaderReadOptions {\n assertDictionary(options, context);\n const min = options?.min ?? 1;\n return {\n min: convertUnsignedLongLongWithEnforceRange(\n min,\n `${context} has member 'min' that`\n )\n };\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, type ReadableByteStream, type ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from './reader-options';\nimport { convertByobReadOptions } from '../validators/reader-options';\nimport { isDataView, type NonShared, type TypedArray } from '../helpers/array-buffer-view';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream as ReadableStream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest>(\n stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest\n): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest> {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(\n view: T,\n options?: ReadableStreamBYOBReaderReadOptions\n ): Promise>;\n read>(\n view: T,\n rawOptions: ReadableStreamBYOBReaderReadOptions | null | undefined = {}\n ): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n let options: ValidatedReadableStreamBYOBReaderReadOptions;\n try {\n options = convertByobReadOptions(rawOptions, 'options');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const min = options.min;\n if (min === 0) {\n return promiseRejectedWith(new TypeError('options.min must be greater than 0'));\n }\n if (!isDataView(view)) {\n if (min > (view as unknown as TypedArray).length) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s length'));\n }\n } else if (min > view.byteLength) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s byteLength'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamBYOBReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamBYOBReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead>(\n reader: ReadableStreamBYOBReader,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n min,\n readIntoRequest\n );\n }\n}\n\nexport function ReadableStreamBYOBReaderRelease(reader: ReadableStreamBYOBReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n}\n\nexport function ReadableStreamBYOBReaderErrorReadIntoRequests(reader: ReadableStreamBYOBReader, e: any) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n","/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * If aborted, returns the reason for aborting.\n */\n readonly reason?: any;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(reason?: any): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n type QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { type AbortController, type AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(WritableStream.prototype.abort, 'abort');\nsetFunctionName(WritableStream.prototype.close, 'close');\nsetFunctionName(WritableStream.prototype.getWriter, 'getWriter');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight\n};\n\nexport type {\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort(reason);\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nsetFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort');\nsetFunctionName(WritableStreamDefaultWriter.prototype.close, 'close');\nsetFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock');\nsetFunctionName(WritableStreamDefaultWriter.prototype.write, 'write');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n return null;\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let writeAlgorithm: (chunk: W) => Promise;\n let closeAlgorithm: () => Promise;\n let abortAlgorithm: (reason: any) => Promise;\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n } else {\n writeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n } else {\n closeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n } else {\n abortAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n return null;\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n","/// \n\nfunction getGlobals(): typeof globalThis | undefined {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n } else if (typeof self !== 'undefined') {\n return self;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n","/// \nimport { globals } from '../globals';\nimport { setFunctionName } from '../lib/helpers/miscellaneous';\n\ninterface DOMException extends Error {\n name: string;\n message: string;\n}\n\ntype DOMExceptionConstructor = new (message?: string, name?: string) => DOMException;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n if ((ctor as DOMExceptionConstructor).name !== 'DOMException') {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Support:\n * - Web browsers\n * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87)\n */\nfunction getFromGlobal(): DOMExceptionConstructor | undefined {\n const ctor = globals?.DOMException;\n return isDOMExceptionConstructor(ctor) ? ctor : undefined;\n}\n\n/**\n * Support:\n * - All platforms\n */\nfunction createPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line @typescript-eslint/no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n setFunctionName(ctor, 'DOMException');\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nconst DOMException: DOMExceptionConstructor = getFromGlobal() || createPolyfill();\n\nexport { DOMException };\n","import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n return null;\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => null) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => null) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest(): null {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n return null;\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any): null {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n\n return null;\n }\n });\n}\n","import type { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, type QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n type ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport type { ValidatedUnderlyingSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n // Do nothing.\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultController.prototype.close, 'close');\nsetFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableStreamDefaultController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n","import {\n CreateReadableByteStream,\n CreateReadableStream,\n type DefaultReadableStream,\n IsReadableStream,\n type ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n type ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n type ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(\n stream: ReadableStream,\n cloneForBranch2: boolean\n): [DefaultReadableStream, DefaultReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: DefaultReadableStream;\n let branch2: DefaultReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader> = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader>) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return null;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: NonShared, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader>(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n","import { typeIsObject } from '../helpers/miscellaneous';\nimport type { ReadableStreamDefaultReadResult } from './default-reader';\n\n/**\n * A common interface for a `ReadadableStream` implementation.\n *\n * @public\n */\nexport interface ReadableStreamLike {\n readonly locked: boolean;\n\n getReader(): ReadableStreamDefaultReaderLike;\n}\n\n/**\n * A common interface for a `ReadableStreamDefaultReader` implementation.\n *\n * @public\n */\nexport interface ReadableStreamDefaultReaderLike {\n readonly closed: Promise;\n\n cancel(reason?: any): Promise;\n\n read(): Promise>;\n\n releaseLock(): void;\n}\n\nexport function isReadableStreamLike(stream: unknown): stream is ReadableStreamLike {\n return typeIsObject(stream) && typeof (stream as ReadableStreamLike).getReader !== 'undefined';\n}\n","import { CreateReadableStream, type DefaultReadableStream } from '../readable-stream';\nimport {\n isReadableStreamLike,\n type ReadableStreamDefaultReaderLike,\n type ReadableStreamLike\n} from './readable-stream-like';\nimport { ReadableStreamDefaultControllerClose, ReadableStreamDefaultControllerEnqueue } from './default-controller';\nimport { GetIterator, GetMethod, IteratorComplete, IteratorNext, IteratorValue } from '../abstract-ops/ecmascript';\nimport { promiseRejectedWith, promiseResolvedWith, reflectCall, transformPromiseWith } from '../helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { noop } from '../../utils';\n\nexport function ReadableStreamFrom(\n source: Iterable | AsyncIterable | ReadableStreamLike\n): DefaultReadableStream {\n if (isReadableStreamLike(source)) {\n return ReadableStreamFromDefaultReader(source.getReader());\n }\n return ReadableStreamFromIterable(source);\n}\n\nexport function ReadableStreamFromIterable(asyncIterable: Iterable | AsyncIterable): DefaultReadableStream {\n let stream: DefaultReadableStream;\n const iteratorRecord = GetIterator(asyncIterable, 'async');\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let nextResult;\n try {\n nextResult = IteratorNext(iteratorRecord);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const nextPromise = promiseResolvedWith(nextResult);\n return transformPromiseWith(nextPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object');\n }\n const done = IteratorComplete(iterResult);\n if (done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = IteratorValue(iterResult);\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n const iterator = iteratorRecord.iterator;\n let returnMethod: (typeof iterator)['return'] | undefined;\n try {\n returnMethod = GetMethod(iterator, 'return');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n if (returnMethod === undefined) {\n return promiseResolvedWith(undefined);\n }\n let returnResult: IteratorResult | Promise>;\n try {\n returnResult = reflectCall(returnMethod, iterator, [reason]);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const returnPromise = promiseResolvedWith(returnResult);\n return transformPromiseWith(returnPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object');\n }\n return undefined;\n });\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n\nexport function ReadableStreamFromDefaultReader(\n reader: ReadableStreamDefaultReaderLike\n): DefaultReadableStream {\n let stream: DefaultReadableStream;\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let readPromise;\n try {\n readPromise = reader.read();\n } catch (e) {\n return promiseRejectedWith(e);\n }\n return transformPromiseWith(readPromise, readResult => {\n if (!typeIsObject(readResult)) {\n throw new TypeError('The promise returned by the reader.read() method must fulfill with an object');\n }\n if (readResult.done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = readResult.value;\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n try {\n return promiseResolvedWith(reader.cancel(reason));\n } catch (e) {\n return promiseRejectedWith(e);\n }\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n","import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n","import { assertDictionary } from './basic';\nimport type {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n","import { assertDictionary } from './basic';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n","import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n","import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, type ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderErrorReadRequests,\n type ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReaderErrorReadIntoRequests,\n type ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { ReadableStreamFrom } from './readable-stream/from';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport type {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList, SymbolAsyncIterator } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions\n} from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport type { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport type { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\nimport type { ReadableStreamDefaultReaderLike, ReadableStreamLike } from './readable-stream/readable-stream-like';\nimport type { NonShared } from './helpers/array-buffer-view';\n\nexport type DefaultReadableStream = ReadableStream & {\n _readableStreamController: ReadableStreamDefaultController\n};\n\nexport type ReadableByteStream = ReadableStream> & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream implements AsyncIterable {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n\n [SymbolAsyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator {\n // Stub implementation, overridden below\n return this.values(options);\n }\n\n /**\n * Creates a new ReadableStream wrapping the provided iterable or async iterable.\n *\n * This can be used to adapt various kinds of objects into a readable stream,\n * such as an array, an async generator, or a Node.js readable stream.\n */\n static from(asyncIterable: Iterable | AsyncIterable | ReadableStreamLike): ReadableStream {\n return ReadableStreamFrom(asyncIterable);\n }\n}\n\nObject.defineProperties(ReadableStream, {\n from: { enumerable: true }\n});\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(ReadableStream.from, 'from');\nsetFunctionName(ReadableStream.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStream.prototype.getReader, 'getReader');\nsetFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough');\nsetFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo');\nsetFunctionName(ReadableStream.prototype.tee, 'tee');\nsetFunctionName(ReadableStream.prototype.values, 'values');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nObject.defineProperty(ReadableStream.prototype, SymbolAsyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n});\n\nexport type {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n ReadableStreamBYOBReaderReadOptions,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions,\n ReadableStreamLike,\n ReadableStreamDefaultReaderLike\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1\n): DefaultReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: DefaultReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n","import type { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\nsetFunctionName(byteLengthSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\nsetFunctionName(countSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const cancel = original?.cancel;\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n cancel: cancel === undefined ?\n undefined :\n convertTransformerCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n\nfunction convertTransformerCancelCallback(\n fn: TransformerCancelCallback,\n original: Transformer,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith,\n uponPromise\n} from './helpers/webidl';\nimport { CreateReadableStream, type DefaultReadableStream, ReadableStream } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: DefaultReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport type {\n Transformer,\n TransformerCancelCallback,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSourceCancelAlgorithm(stream, reason);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n TransformStreamUnblockWrite(stream);\n}\n\nfunction TransformStreamUnblockWrite(stream: TransformStream) {\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _finishPromise: Promise | undefined;\n /** @internal */\n _finishPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _finishPromise_reject?: (reason: any) => void;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n /** @internal */\n _cancelAlgorithm: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(TransformStreamDefaultController.prototype.error, 'error');\nsetFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._finishPromise = undefined;\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm: (chunk: I) => Promise;\n let flushAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n } else {\n transformAlgorithm = chunk => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n }\n\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n } else {\n flushAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n if (transformer.cancel !== undefined) {\n cancelAlgorithm = reason => transformer.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally,\n // we don't run the _cancelAlgorithm again.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerError(readable._readableStreamController, reason);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally,\n // we don't also run the _cancelAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(flushPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerClose(readable._readableStreamController);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\nfunction TransformStreamDefaultSourceCancelAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._writable cannot change after construction, so caching it across a call to user code is safe.\n const writable = stream._writable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or\n // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the\n // _flushAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (writable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, writable._storedError);\n } else {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\nexport function defaultControllerFinishPromiseResolve(controller: TransformStreamDefaultController) {\n if (controller._finishPromise_resolve === undefined) {\n return;\n }\n\n controller._finishPromise_resolve();\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nexport function defaultControllerFinishPromiseReject(controller: TransformStreamDefaultController, reason: any) {\n if (controller._finishPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(controller._finishPromise!);\n controller._finishPromise_reject(reason);\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n","import {\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n ReadableByteStreamController,\n ReadableStream,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultController,\n ReadableStreamDefaultReader,\n TransformStream,\n TransformStreamDefaultController,\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter\n} from './ponyfill';\nimport { globals } from './globals';\n\n// Export\nexport * from './ponyfill';\n\nconst exports = {\n ReadableStream,\n ReadableStreamDefaultController,\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader,\n\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter,\n\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n\n TransformStream,\n TransformStreamDefaultController\n};\n\n// Add classes to global scope\nif (typeof globals !== 'undefined') {\n for (const prop in exports) {\n if (Object.prototype.hasOwnProperty.call(exports, prop)) {\n Object.defineProperty(globals, prop, {\n value: exports[prop as (keyof typeof exports)],\n writable: true,\n configurable: true\n });\n }\n }\n}\n"],"names":["queueMicrotask","streamBrandCheckException","defaultControllerBrandCheckException","exports"],"mappings":";;;;;;;;;;;;;aAAgB,IAAI,GAAA;IAClB,IAAA,OAAO,SAAS,CAAC;IACnB;;ICCM,SAAU,YAAY,CAAC,CAAM,EAAA;IACjC,IAAA,OAAO,CAAC,OAAO,CAAC,KAAK,QAAQ,IAAI,CAAC,KAAK,IAAI,KAAK,OAAO,CAAC,KAAK,UAAU,CAAC;IAC1E,CAAC;IAEM,MAAM,8BAA8B,GAUrC,IAAI,CAAC;IAEK,SAAA,eAAe,CAAC,EAAY,EAAE,IAAY,EAAA;IACxD,IAAA,IAAI;IACF,QAAA,MAAM,CAAC,cAAc,CAAC,EAAE,EAAE,MAAM,EAAE;IAChC,YAAA,KAAK,EAAE,IAAI;IACX,YAAA,YAAY,EAAE,IAAI;IACnB,SAAA,CAAC,CAAC;SACJ;IAAC,IAAA,OAAA,EAAA,EAAM;;;SAGP;IACH;;IC1BA,MAAM,eAAe,GAAG,OAAO,CAAC;IAChC,MAAM,mBAAmB,GAAG,OAAO,CAAC,SAAS,CAAC,IAAI,CAAC;IACnD,MAAM,qBAAqB,GAAG,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC;IAEnE;IACM,SAAU,UAAU,CAAI,QAGrB,EAAA;IACP,IAAA,OAAO,IAAI,eAAe,CAAC,QAAQ,CAAC,CAAC;IACvC,CAAC;IAED;IACM,SAAU,mBAAmB,CAAI,KAAyB,EAAA;QAC9D,O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.es2018.min.js b/backend/node_modules/web-streams-polyfill/dist/polyfill.es2018.min.js new file mode 100644 index 0000000000000000000000000000000000000000..39e9eae87e2c3091ee2c6bc0fe08d0004d96a5a1 --- /dev/null +++ b/backend/node_modules/web-streams-polyfill/dist/polyfill.es2018.min.js @@ -0,0 +1,9 @@ +/** + * @license + * web-streams-polyfill v3.3.3 + * Copyright 2024 Mattias Buelens, Diwank Singh Tomer and other contributors. + * This code is released under the MIT license. + * SPDX-License-Identifier: MIT + */ +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).WebStreamsPolyfill={})}(this,(function(e){"use strict";function t(){}function r(e){return"object"==typeof e&&null!==e||"function"==typeof e}const o=t;function n(e,t){try{Object.defineProperty(e,"name",{value:t,configurable:!0})}catch(e){}}const a=Promise,i=Promise.prototype.then,l=Promise.reject.bind(a);function s(e){return new a(e)}function u(e){return s((t=>t(e)))}function c(e){return l(e)}function d(e,t,r){return i.call(e,t,r)}function f(e,t,r){d(d(e,t,r),void 0,o)}function b(e,t){f(e,t)}function m(e,t){f(e,void 0,t)}function h(e,t,r){return d(e,t,r)}function _(e){d(e,void 0,o)}let p=e=>{if("function"==typeof queueMicrotask)p=queueMicrotask;else{const e=u(void 0);p=t=>d(e,t)}return p(e)};function y(e,t,r){if("function"!=typeof e)throw new TypeError("Argument is not a function");return Function.prototype.apply.call(e,t,r)}function S(e,t,r){try{return u(y(e,t,r))}catch(e){return c(e)}}class g{constructor(){this._cursor=0,this._size=0,this._front={_elements:[],_next:void 0},this._back=this._front,this._cursor=0,this._size=0}get length(){return this._size}push(e){const t=this._back;let r=t;16383===t._elements.length&&(r={_elements:[],_next:void 0}),t._elements.push(e),r!==t&&(this._back=r,t._next=r),++this._size}shift(){const e=this._front;let t=e;const r=this._cursor;let o=r+1;const n=e._elements,a=n[r];return 16384===o&&(t=e._next,o=0),--this._size,this._cursor=o,e!==t&&(this._front=t),n[r]=void 0,a}forEach(e){let t=this._cursor,r=this._front,o=r._elements;for(;!(t===o.length&&void 0===r._next||t===o.length&&(r=r._next,o=r._elements,t=0,0===o.length));)e(o[t]),++t}peek(){const e=this._front,t=this._cursor;return e._elements[t]}}const v=Symbol("[[AbortSteps]]"),w=Symbol("[[ErrorSteps]]"),R=Symbol("[[CancelSteps]]"),T=Symbol("[[PullSteps]]"),C=Symbol("[[ReleaseSteps]]");function P(e,t){e._ownerReadableStream=t,t._reader=e,"readable"===t._state?B(e):"closed"===t._state?function(e){B(e),k(e)}(e):O(e,t._storedError)}function q(e,t){return Er(e._ownerReadableStream,t)}function E(e){const t=e._ownerReadableStream;"readable"===t._state?j(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):function(e,t){O(e,t)}(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),t._readableStreamController[C](),t._reader=void 0,e._ownerReadableStream=void 0}function W(e){return new TypeError("Cannot "+e+" a stream using a released reader")}function B(e){e._closedPromise=s(((t,r)=>{e._closedPromise_resolve=t,e._closedPromise_reject=r}))}function O(e,t){B(e),j(e,t)}function j(e,t){void 0!==e._closedPromise_reject&&(_(e._closedPromise),e._closedPromise_reject(t),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}function k(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}const A=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},D=Math.trunc||function(e){return e<0?Math.ceil(e):Math.floor(e)};function z(e,t){if(void 0!==e&&("object"!=typeof(r=e)&&"function"!=typeof r))throw new TypeError(`${t} is not an object.`);var r}function L(e,t){if("function"!=typeof e)throw new TypeError(`${t} is not a function.`)}function F(e,t){if(!function(e){return"object"==typeof e&&null!==e||"function"==typeof e}(e))throw new TypeError(`${t} is not an object.`)}function I(e,t,r){if(void 0===e)throw new TypeError(`Parameter ${t} is required in '${r}'.`)}function $(e,t,r){if(void 0===e)throw new TypeError(`${t} is required in '${r}'.`)}function M(e){return Number(e)}function Y(e){return 0===e?0:e}function Q(e,t){const r=Number.MAX_SAFE_INTEGER;let o=Number(e);if(o=Y(o),!A(o))throw new TypeError(`${t} is not a finite number`);if(o=function(e){return Y(D(e))}(o),o<0||o>r)throw new TypeError(`${t} is outside the accepted range of 0 to ${r}, inclusive`);return A(o)&&0!==o?o:0}function x(e,t){if(!Pr(e))throw new TypeError(`${t} is not a ReadableStream.`)}function N(e){return new ReadableStreamDefaultReader(e)}function H(e,t){e._reader._readRequests.push(t)}function V(e,t,r){const o=e._reader._readRequests.shift();r?o._closeSteps():o._chunkSteps(t)}function U(e){return e._reader._readRequests.length}function G(e){const t=e._reader;return void 0!==t&&!!X(t)}class ReadableStreamDefaultReader{constructor(e){if(I(e,1,"ReadableStreamDefaultReader"),x(e,"First parameter"),qr(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");P(this,e),this._readRequests=new g}get closed(){return X(this)?this._closedPromise:c(Z("closed"))}cancel(e=void 0){return X(this)?void 0===this._ownerReadableStream?c(W("cancel")):q(this,e):c(Z("cancel"))}read(){if(!X(this))return c(Z("read"));if(void 0===this._ownerReadableStream)return c(W("read from"));let e,t;const r=s(((r,o)=>{e=r,t=o}));return J(this,{_chunkSteps:t=>e({value:t,done:!1}),_closeSteps:()=>e({value:void 0,done:!0}),_errorSteps:e=>t(e)}),r}releaseLock(){if(!X(this))throw Z("releaseLock");void 0!==this._ownerReadableStream&&function(e){E(e);const t=new TypeError("Reader was released");K(e,t)}(this)}}function X(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readRequests")&&e instanceof ReadableStreamDefaultReader)}function J(e,t){const r=e._ownerReadableStream;r._disturbed=!0,"closed"===r._state?t._closeSteps():"errored"===r._state?t._errorSteps(r._storedError):r._readableStreamController[T](t)}function K(e,t){const r=e._readRequests;e._readRequests=new g,r.forEach((e=>{e._errorSteps(t)}))}function Z(e){return new TypeError(`ReadableStreamDefaultReader.prototype.${e} can only be used on a ReadableStreamDefaultReader`)}Object.defineProperties(ReadableStreamDefaultReader.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),n(ReadableStreamDefaultReader.prototype.cancel,"cancel"),n(ReadableStreamDefaultReader.prototype.read,"read"),n(ReadableStreamDefaultReader.prototype.releaseLock,"releaseLock"),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(ReadableStreamDefaultReader.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0});const ee=Object.getPrototypeOf(Object.getPrototypeOf((async function*(){})).prototype);class te{constructor(e,t){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=e,this._preventCancel=t}next(){const e=()=>this._nextSteps();return this._ongoingPromise=this._ongoingPromise?h(this._ongoingPromise,e,e):e(),this._ongoingPromise}return(e){const t=()=>this._returnSteps(e);return this._ongoingPromise?h(this._ongoingPromise,t,t):t()}_nextSteps(){if(this._isFinished)return Promise.resolve({value:void 0,done:!0});const e=this._reader;let t,r;const o=s(((e,o)=>{t=e,r=o}));return J(e,{_chunkSteps:e=>{this._ongoingPromise=void 0,p((()=>t({value:e,done:!1})))},_closeSteps:()=>{this._ongoingPromise=void 0,this._isFinished=!0,E(e),t({value:void 0,done:!0})},_errorSteps:t=>{this._ongoingPromise=void 0,this._isFinished=!0,E(e),r(t)}}),o}_returnSteps(e){if(this._isFinished)return Promise.resolve({value:e,done:!0});this._isFinished=!0;const t=this._reader;if(!this._preventCancel){const r=q(t,e);return E(t),h(r,(()=>({value:e,done:!0})))}return E(t),u({value:e,done:!0})}}const re={next(){return oe(this)?this._asyncIteratorImpl.next():c(ne("next"))},return(e){return oe(this)?this._asyncIteratorImpl.return(e):c(ne("return"))}};function oe(e){if(!r(e))return!1;if(!Object.prototype.hasOwnProperty.call(e,"_asyncIteratorImpl"))return!1;try{return e._asyncIteratorImpl instanceof te}catch(e){return!1}}function ne(e){return new TypeError(`ReadableStreamAsyncIterator.${e} can only be used on a ReadableSteamAsyncIterator`)}Object.setPrototypeOf(re,ee);const ae=Number.isNaN||function(e){return e!=e};var ie,le,se;function ue(e){return e.slice()}function ce(e,t,r,o,n){new Uint8Array(e).set(new Uint8Array(r,o,n),t)}let de=e=>(de="function"==typeof e.transfer?e=>e.transfer():"function"==typeof structuredClone?e=>structuredClone(e,{transfer:[e]}):e=>e,de(e)),fe=e=>(fe="boolean"==typeof e.detached?e=>e.detached:e=>0===e.byteLength,fe(e));function be(e,t,r){if(e.slice)return e.slice(t,r);const o=r-t,n=new ArrayBuffer(o);return ce(n,0,e,t,o),n}function me(e,t){const r=e[t];if(null!=r){if("function"!=typeof r)throw new TypeError(`${String(t)} is not a function`);return r}}const he=null!==(se=null!==(ie=Symbol.asyncIterator)&&void 0!==ie?ie:null===(le=Symbol.for)||void 0===le?void 0:le.call(Symbol,"Symbol.asyncIterator"))&&void 0!==se?se:"@@asyncIterator";function _e(e,t="sync",o){if(void 0===o)if("async"===t){if(void 0===(o=me(e,he))){return function(e){const t={[Symbol.iterator]:()=>e.iterator},r=async function*(){return yield*t}();return{iterator:r,nextMethod:r.next,done:!1}}(_e(e,"sync",me(e,Symbol.iterator)))}}else o=me(e,Symbol.iterator);if(void 0===o)throw new TypeError("The object is not iterable");const n=y(o,e,[]);if(!r(n))throw new TypeError("The iterator method must return an object");return{iterator:n,nextMethod:n.next,done:!1}}function pe(e){const t=be(e.buffer,e.byteOffset,e.byteOffset+e.byteLength);return new Uint8Array(t)}function ye(e){const t=e._queue.shift();return e._queueTotalSize-=t.size,e._queueTotalSize<0&&(e._queueTotalSize=0),t.value}function Se(e,t,r){if("number"!=typeof(o=r)||ae(o)||o<0||r===1/0)throw new RangeError("Size must be a finite, non-NaN, non-negative number.");var o;e._queue.push({value:t,size:r}),e._queueTotalSize+=r}function ge(e){e._queue=new g,e._queueTotalSize=0}function ve(e){return e===DataView}class ReadableStreamBYOBRequest{constructor(){throw new TypeError("Illegal constructor")}get view(){if(!Re(this))throw Ge("view");return this._view}respond(e){if(!Re(this))throw Ge("respond");if(I(e,1,"respond"),e=Q(e,"First parameter"),void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");if(fe(this._view.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be used as a response");He(this._associatedReadableByteStreamController,e)}respondWithNewView(e){if(!Re(this))throw Ge("respondWithNewView");if(I(e,1,"respondWithNewView"),!ArrayBuffer.isView(e))throw new TypeError("You can only respond with array buffer views");if(void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");if(fe(e.buffer))throw new TypeError("The given view's buffer has been detached and so cannot be used as a response");Ve(this._associatedReadableByteStreamController,e)}}Object.defineProperties(ReadableStreamBYOBRequest.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),n(ReadableStreamBYOBRequest.prototype.respond,"respond"),n(ReadableStreamBYOBRequest.prototype.respondWithNewView,"respondWithNewView"),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(ReadableStreamBYOBRequest.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});class ReadableByteStreamController{constructor(){throw new TypeError("Illegal constructor")}get byobRequest(){if(!we(this))throw Xe("byobRequest");return xe(this)}get desiredSize(){if(!we(this))throw Xe("desiredSize");return Ne(this)}close(){if(!we(this))throw Xe("close");if(this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");const e=this._controlledReadableByteStream._state;if("readable"!==e)throw new TypeError(`The stream (in ${e} state) is not in the readable state and cannot be closed`);$e(this)}enqueue(e){if(!we(this))throw Xe("enqueue");if(I(e,1,"enqueue"),!ArrayBuffer.isView(e))throw new TypeError("chunk must be an array buffer view");if(0===e.byteLength)throw new TypeError("chunk must have non-zero byteLength");if(0===e.buffer.byteLength)throw new TypeError("chunk's buffer must have non-zero byteLength");if(this._closeRequested)throw new TypeError("stream is closed or draining");const t=this._controlledReadableByteStream._state;if("readable"!==t)throw new TypeError(`The stream (in ${t} state) is not in the readable state and cannot be enqueued to`);Me(this,e)}error(e=void 0){if(!we(this))throw Xe("error");Ye(this,e)}[R](e){Ce(this),ge(this);const t=this._cancelAlgorithm(e);return Ie(this),t}[T](e){const t=this._controlledReadableByteStream;if(this._queueTotalSize>0)return void Qe(this,e);const r=this._autoAllocateChunkSize;if(void 0!==r){let t;try{t=new ArrayBuffer(r)}catch(t){return void e._errorSteps(t)}const o={buffer:t,bufferByteLength:r,byteOffset:0,byteLength:r,bytesFilled:0,minimumFill:1,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(o)}H(t,e),Te(this)}[C](){if(this._pendingPullIntos.length>0){const e=this._pendingPullIntos.peek();e.readerType="none",this._pendingPullIntos=new g,this._pendingPullIntos.push(e)}}}function we(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableByteStream")&&e instanceof ReadableByteStreamController)}function Re(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_associatedReadableByteStreamController")&&e instanceof ReadableStreamBYOBRequest)}function Te(e){const t=function(e){const t=e._controlledReadableByteStream;if("readable"!==t._state)return!1;if(e._closeRequested)return!1;if(!e._started)return!1;if(G(t)&&U(t)>0)return!0;if(tt(t)&&et(t)>0)return!0;const r=Ne(e);if(r>0)return!0;return!1}(e);if(!t)return;if(e._pulling)return void(e._pullAgain=!0);e._pulling=!0;f(e._pullAlgorithm(),(()=>(e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,Te(e)),null)),(t=>(Ye(e,t),null)))}function Ce(e){Ae(e),e._pendingPullIntos=new g}function Pe(e,t){let r=!1;"closed"===e._state&&(r=!0);const o=qe(t);"default"===t.readerType?V(e,o,r):function(e,t,r){const o=e._reader,n=o._readIntoRequests.shift();r?n._closeSteps(t):n._chunkSteps(t)}(e,o,r)}function qe(e){const t=e.bytesFilled,r=e.elementSize;return new e.viewConstructor(e.buffer,e.byteOffset,t/r)}function Ee(e,t,r,o){e._queue.push({buffer:t,byteOffset:r,byteLength:o}),e._queueTotalSize+=o}function We(e,t,r,o){let n;try{n=be(t,r,r+o)}catch(t){throw Ye(e,t),t}Ee(e,n,0,o)}function Be(e,t){t.bytesFilled>0&&We(e,t.buffer,t.byteOffset,t.bytesFilled),Fe(e)}function Oe(e,t){const r=Math.min(e._queueTotalSize,t.byteLength-t.bytesFilled),o=t.bytesFilled+r;let n=r,a=!1;const i=o-o%t.elementSize;i>=t.minimumFill&&(n=i-t.bytesFilled,a=!0);const l=e._queue;for(;n>0;){const r=l.peek(),o=Math.min(n,r.byteLength),a=t.byteOffset+t.bytesFilled;ce(t.buffer,a,r.buffer,r.byteOffset,o),r.byteLength===o?l.shift():(r.byteOffset+=o,r.byteLength-=o),e._queueTotalSize-=o,je(e,o,t),n-=o}return a}function je(e,t,r){r.bytesFilled+=t}function ke(e){0===e._queueTotalSize&&e._closeRequested?(Ie(e),Wr(e._controlledReadableByteStream)):Te(e)}function Ae(e){null!==e._byobRequest&&(e._byobRequest._associatedReadableByteStreamController=void 0,e._byobRequest._view=null,e._byobRequest=null)}function De(e){for(;e._pendingPullIntos.length>0;){if(0===e._queueTotalSize)return;const t=e._pendingPullIntos.peek();Oe(e,t)&&(Fe(e),Pe(e._controlledReadableByteStream,t))}}function ze(e,t,r,o){const n=e._controlledReadableByteStream,a=t.constructor,i=function(e){return ve(e)?1:e.BYTES_PER_ELEMENT}(a),{byteOffset:l,byteLength:s}=t,u=r*i;let c;try{c=de(t.buffer)}catch(e){return void o._errorSteps(e)}const d={buffer:c,bufferByteLength:c.byteLength,byteOffset:l,byteLength:s,bytesFilled:0,minimumFill:u,elementSize:i,viewConstructor:a,readerType:"byob"};if(e._pendingPullIntos.length>0)return e._pendingPullIntos.push(d),void Ze(n,o);if("closed"!==n._state){if(e._queueTotalSize>0){if(Oe(e,d)){const t=qe(d);return ke(e),void o._chunkSteps(t)}if(e._closeRequested){const t=new TypeError("Insufficient bytes to fill elements in the given buffer");return Ye(e,t),void o._errorSteps(t)}}e._pendingPullIntos.push(d),Ze(n,o),Te(e)}else{const e=new a(d.buffer,d.byteOffset,0);o._closeSteps(e)}}function Le(e,t){const r=e._pendingPullIntos.peek();Ae(e);"closed"===e._controlledReadableByteStream._state?function(e,t){"none"===t.readerType&&Fe(e);const r=e._controlledReadableByteStream;if(tt(r))for(;et(r)>0;)Pe(r,Fe(e))}(e,r):function(e,t,r){if(je(0,t,r),"none"===r.readerType)return Be(e,r),void De(e);if(r.bytesFilled0){const t=r.byteOffset+r.bytesFilled;We(e,r.buffer,t-o,o)}r.bytesFilled-=o,Pe(e._controlledReadableByteStream,r),De(e)}(e,t,r),Te(e)}function Fe(e){return e._pendingPullIntos.shift()}function Ie(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0}function $e(e){const t=e._controlledReadableByteStream;if(!e._closeRequested&&"readable"===t._state)if(e._queueTotalSize>0)e._closeRequested=!0;else{if(e._pendingPullIntos.length>0){const t=e._pendingPullIntos.peek();if(t.bytesFilled%t.elementSize!=0){const t=new TypeError("Insufficient bytes to fill elements in the given buffer");throw Ye(e,t),t}}Ie(e),Wr(t)}}function Me(e,t){const r=e._controlledReadableByteStream;if(e._closeRequested||"readable"!==r._state)return;const{buffer:o,byteOffset:n,byteLength:a}=t;if(fe(o))throw new TypeError("chunk's buffer is detached and so cannot be enqueued");const i=de(o);if(e._pendingPullIntos.length>0){const t=e._pendingPullIntos.peek();if(fe(t.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be filled with an enqueued chunk");Ae(e),t.buffer=de(t.buffer),"none"===t.readerType&&Be(e,t)}if(G(r))if(function(e){const t=e._controlledReadableByteStream._reader;for(;t._readRequests.length>0;){if(0===e._queueTotalSize)return;Qe(e,t._readRequests.shift())}}(e),0===U(r))Ee(e,i,n,a);else{e._pendingPullIntos.length>0&&Fe(e);V(r,new Uint8Array(i,n,a),!1)}else tt(r)?(Ee(e,i,n,a),De(e)):Ee(e,i,n,a);Te(e)}function Ye(e,t){const r=e._controlledReadableByteStream;"readable"===r._state&&(Ce(e),ge(e),Ie(e),Br(r,t))}function Qe(e,t){const r=e._queue.shift();e._queueTotalSize-=r.byteLength,ke(e);const o=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);t._chunkSteps(o)}function xe(e){if(null===e._byobRequest&&e._pendingPullIntos.length>0){const t=e._pendingPullIntos.peek(),r=new Uint8Array(t.buffer,t.byteOffset+t.bytesFilled,t.byteLength-t.bytesFilled),o=Object.create(ReadableStreamBYOBRequest.prototype);!function(e,t,r){e._associatedReadableByteStreamController=t,e._view=r}(o,e,r),e._byobRequest=o}return e._byobRequest}function Ne(e){const t=e._controlledReadableByteStream._state;return"errored"===t?null:"closed"===t?0:e._strategyHWM-e._queueTotalSize}function He(e,t){const r=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==t)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream")}else{if(0===t)throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");if(r.bytesFilled+t>r.byteLength)throw new RangeError("bytesWritten out of range")}r.buffer=de(r.buffer),Le(e,t)}function Ve(e,t){const r=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==t.byteLength)throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream")}else if(0===t.byteLength)throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");if(r.byteOffset+r.bytesFilled!==t.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(r.bufferByteLength!==t.buffer.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");if(r.bytesFilled+t.byteLength>r.byteLength)throw new RangeError("The region specified by view is larger than byobRequest");const o=t.byteLength;r.buffer=de(t.buffer),Le(e,o)}function Ue(e,t,r,o,n,a,i){t._controlledReadableByteStream=e,t._pullAgain=!1,t._pulling=!1,t._byobRequest=null,t._queue=t._queueTotalSize=void 0,ge(t),t._closeRequested=!1,t._started=!1,t._strategyHWM=a,t._pullAlgorithm=o,t._cancelAlgorithm=n,t._autoAllocateChunkSize=i,t._pendingPullIntos=new g,e._readableStreamController=t;f(u(r()),(()=>(t._started=!0,Te(t),null)),(e=>(Ye(t,e),null)))}function Ge(e){return new TypeError(`ReadableStreamBYOBRequest.prototype.${e} can only be used on a ReadableStreamBYOBRequest`)}function Xe(e){return new TypeError(`ReadableByteStreamController.prototype.${e} can only be used on a ReadableByteStreamController`)}function Je(e,t){if("byob"!==(e=`${e}`))throw new TypeError(`${t} '${e}' is not a valid enumeration value for ReadableStreamReaderMode`);return e}function Ke(e){return new ReadableStreamBYOBReader(e)}function Ze(e,t){e._reader._readIntoRequests.push(t)}function et(e){return e._reader._readIntoRequests.length}function tt(e){const t=e._reader;return void 0!==t&&!!rt(t)}Object.defineProperties(ReadableByteStreamController.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),n(ReadableByteStreamController.prototype.close,"close"),n(ReadableByteStreamController.prototype.enqueue,"enqueue"),n(ReadableByteStreamController.prototype.error,"error"),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(ReadableByteStreamController.prototype,Symbol.toStringTag,{value:"ReadableByteStreamController",configurable:!0});class ReadableStreamBYOBReader{constructor(e){if(I(e,1,"ReadableStreamBYOBReader"),x(e,"First parameter"),qr(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!we(e._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");P(this,e),this._readIntoRequests=new g}get closed(){return rt(this)?this._closedPromise:c(at("closed"))}cancel(e=void 0){return rt(this)?void 0===this._ownerReadableStream?c(W("cancel")):q(this,e):c(at("cancel"))}read(e,t={}){if(!rt(this))return c(at("read"));if(!ArrayBuffer.isView(e))return c(new TypeError("view must be an array buffer view"));if(0===e.byteLength)return c(new TypeError("view must have non-zero byteLength"));if(0===e.buffer.byteLength)return c(new TypeError("view's buffer must have non-zero byteLength"));if(fe(e.buffer))return c(new TypeError("view's buffer has been detached"));let r;try{r=function(e,t){var r;return z(e,t),{min:Q(null!==(r=null==e?void 0:e.min)&&void 0!==r?r:1,`${t} has member 'min' that`)}}(t,"options")}catch(e){return c(e)}const o=r.min;if(0===o)return c(new TypeError("options.min must be greater than 0"));if(function(e){return ve(e.constructor)}(e)){if(o>e.byteLength)return c(new RangeError("options.min must be less than or equal to view's byteLength"))}else if(o>e.length)return c(new RangeError("options.min must be less than or equal to view's length"));if(void 0===this._ownerReadableStream)return c(W("read from"));let n,a;const i=s(((e,t)=>{n=e,a=t}));return ot(this,e,o,{_chunkSteps:e=>n({value:e,done:!1}),_closeSteps:e=>n({value:e,done:!0}),_errorSteps:e=>a(e)}),i}releaseLock(){if(!rt(this))throw at("releaseLock");void 0!==this._ownerReadableStream&&function(e){E(e);const t=new TypeError("Reader was released");nt(e,t)}(this)}}function rt(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readIntoRequests")&&e instanceof ReadableStreamBYOBReader)}function ot(e,t,r,o){const n=e._ownerReadableStream;n._disturbed=!0,"errored"===n._state?o._errorSteps(n._storedError):ze(n._readableStreamController,t,r,o)}function nt(e,t){const r=e._readIntoRequests;e._readIntoRequests=new g,r.forEach((e=>{e._errorSteps(t)}))}function at(e){return new TypeError(`ReadableStreamBYOBReader.prototype.${e} can only be used on a ReadableStreamBYOBReader`)}function it(e,t){const{highWaterMark:r}=e;if(void 0===r)return t;if(ae(r)||r<0)throw new RangeError("Invalid highWaterMark");return r}function lt(e){const{size:t}=e;return t||(()=>1)}function st(e,t){z(e,t);const r=null==e?void 0:e.highWaterMark,o=null==e?void 0:e.size;return{highWaterMark:void 0===r?void 0:M(r),size:void 0===o?void 0:ut(o,`${t} has member 'size' that`)}}function ut(e,t){return L(e,t),t=>M(e(t))}function ct(e,t,r){return L(e,r),r=>S(e,t,[r])}function dt(e,t,r){return L(e,r),()=>S(e,t,[])}function ft(e,t,r){return L(e,r),r=>y(e,t,[r])}function bt(e,t,r){return L(e,r),(r,o)=>S(e,t,[r,o])}function mt(e,t){if(!yt(e))throw new TypeError(`${t} is not a WritableStream.`)}Object.defineProperties(ReadableStreamBYOBReader.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),n(ReadableStreamBYOBReader.prototype.cancel,"cancel"),n(ReadableStreamBYOBReader.prototype.read,"read"),n(ReadableStreamBYOBReader.prototype.releaseLock,"releaseLock"),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(ReadableStreamBYOBReader.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});const ht="function"==typeof AbortController;class WritableStream{constructor(e={},t={}){void 0===e?e=null:F(e,"First parameter");const r=st(t,"Second parameter"),o=function(e,t){z(e,t);const r=null==e?void 0:e.abort,o=null==e?void 0:e.close,n=null==e?void 0:e.start,a=null==e?void 0:e.type,i=null==e?void 0:e.write;return{abort:void 0===r?void 0:ct(r,e,`${t} has member 'abort' that`),close:void 0===o?void 0:dt(o,e,`${t} has member 'close' that`),start:void 0===n?void 0:ft(n,e,`${t} has member 'start' that`),write:void 0===i?void 0:bt(i,e,`${t} has member 'write' that`),type:a}}(e,"First parameter");pt(this);if(void 0!==o.type)throw new RangeError("Invalid type is specified");const n=lt(r);!function(e,t,r,o){const n=Object.create(WritableStreamDefaultController.prototype);let a,i,l,s;a=void 0!==t.start?()=>t.start(n):()=>{};i=void 0!==t.write?e=>t.write(e,n):()=>u(void 0);l=void 0!==t.close?()=>t.close():()=>u(void 0);s=void 0!==t.abort?e=>t.abort(e):()=>u(void 0);zt(e,n,a,i,l,s,r,o)}(this,o,it(r,1),n)}get locked(){if(!yt(this))throw Qt("locked");return St(this)}abort(e=void 0){return yt(this)?St(this)?c(new TypeError("Cannot abort a stream that already has a writer")):gt(this,e):c(Qt("abort"))}close(){return yt(this)?St(this)?c(new TypeError("Cannot close a stream that already has a writer")):Ct(this)?c(new TypeError("Cannot close an already-closing stream")):vt(this):c(Qt("close"))}getWriter(){if(!yt(this))throw Qt("getWriter");return _t(this)}}function _t(e){return new WritableStreamDefaultWriter(e)}function pt(e){e._state="writable",e._storedError=void 0,e._writer=void 0,e._writableStreamController=void 0,e._writeRequests=new g,e._inFlightWriteRequest=void 0,e._closeRequest=void 0,e._inFlightCloseRequest=void 0,e._pendingAbortRequest=void 0,e._backpressure=!1}function yt(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_writableStreamController")&&e instanceof WritableStream)}function St(e){return void 0!==e._writer}function gt(e,t){var r;if("closed"===e._state||"errored"===e._state)return u(void 0);e._writableStreamController._abortReason=t,null===(r=e._writableStreamController._abortController)||void 0===r||r.abort(t);const o=e._state;if("closed"===o||"errored"===o)return u(void 0);if(void 0!==e._pendingAbortRequest)return e._pendingAbortRequest._promise;let n=!1;"erroring"===o&&(n=!0,t=void 0);const a=s(((r,o)=>{e._pendingAbortRequest={_promise:void 0,_resolve:r,_reject:o,_reason:t,_wasAlreadyErroring:n}}));return e._pendingAbortRequest._promise=a,n||Rt(e,t),a}function vt(e){const t=e._state;if("closed"===t||"errored"===t)return c(new TypeError(`The stream (in ${t} state) is not in the writable state and cannot be closed`));const r=s(((t,r)=>{const o={_resolve:t,_reject:r};e._closeRequest=o})),o=e._writer;var n;return void 0!==o&&e._backpressure&&"writable"===t&&tr(o),Se(n=e._writableStreamController,At,0),It(n),r}function wt(e,t){"writable"!==e._state?Tt(e):Rt(e,t)}function Rt(e,t){const r=e._writableStreamController;e._state="erroring",e._storedError=t;const o=e._writer;void 0!==o&&Ot(o,t),!function(e){if(void 0===e._inFlightWriteRequest&&void 0===e._inFlightCloseRequest)return!1;return!0}(e)&&r._started&&Tt(e)}function Tt(e){e._state="errored",e._writableStreamController[w]();const t=e._storedError;if(e._writeRequests.forEach((e=>{e._reject(t)})),e._writeRequests=new g,void 0===e._pendingAbortRequest)return void Pt(e);const r=e._pendingAbortRequest;if(e._pendingAbortRequest=void 0,r._wasAlreadyErroring)return r._reject(t),void Pt(e);f(e._writableStreamController[v](r._reason),(()=>(r._resolve(),Pt(e),null)),(t=>(r._reject(t),Pt(e),null)))}function Ct(e){return void 0!==e._closeRequest||void 0!==e._inFlightCloseRequest}function Pt(e){void 0!==e._closeRequest&&(e._closeRequest._reject(e._storedError),e._closeRequest=void 0);const t=e._writer;void 0!==t&&Gt(t,e._storedError)}function qt(e,t){const r=e._writer;void 0!==r&&t!==e._backpressure&&(t?function(e){Jt(e)}(r):tr(r)),e._backpressure=t}Object.defineProperties(WritableStream.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),n(WritableStream.prototype.abort,"abort"),n(WritableStream.prototype.close,"close"),n(WritableStream.prototype.getWriter,"getWriter"),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(WritableStream.prototype,Symbol.toStringTag,{value:"WritableStream",configurable:!0});class WritableStreamDefaultWriter{constructor(e){if(I(e,1,"WritableStreamDefaultWriter"),mt(e,"First parameter"),St(e))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=e,e._writer=this;const t=e._state;if("writable"===t)!Ct(e)&&e._backpressure?Jt(this):Zt(this),Vt(this);else if("erroring"===t)Kt(this,e._storedError),Vt(this);else if("closed"===t)Zt(this),Vt(r=this),Xt(r);else{const t=e._storedError;Kt(this,t),Ut(this,t)}var r}get closed(){return Et(this)?this._closedPromise:c(Nt("closed"))}get desiredSize(){if(!Et(this))throw Nt("desiredSize");if(void 0===this._ownerWritableStream)throw Ht("desiredSize");return function(e){const t=e._ownerWritableStream,r=t._state;if("errored"===r||"erroring"===r)return null;if("closed"===r)return 0;return Ft(t._writableStreamController)}(this)}get ready(){return Et(this)?this._readyPromise:c(Nt("ready"))}abort(e=void 0){return Et(this)?void 0===this._ownerWritableStream?c(Ht("abort")):function(e,t){return gt(e._ownerWritableStream,t)}(this,e):c(Nt("abort"))}close(){if(!Et(this))return c(Nt("close"));const e=this._ownerWritableStream;return void 0===e?c(Ht("close")):Ct(e)?c(new TypeError("Cannot close an already-closing stream")):Wt(this)}releaseLock(){if(!Et(this))throw Nt("releaseLock");void 0!==this._ownerWritableStream&&jt(this)}write(e=void 0){return Et(this)?void 0===this._ownerWritableStream?c(Ht("write to")):kt(this,e):c(Nt("write"))}}function Et(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_ownerWritableStream")&&e instanceof WritableStreamDefaultWriter)}function Wt(e){return vt(e._ownerWritableStream)}function Bt(e,t){"pending"===e._closedPromiseState?Gt(e,t):function(e,t){Ut(e,t)}(e,t)}function Ot(e,t){"pending"===e._readyPromiseState?er(e,t):function(e,t){Kt(e,t)}(e,t)}function jt(e){const t=e._ownerWritableStream,r=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");Ot(e,r),Bt(e,r),t._writer=void 0,e._ownerWritableStream=void 0}function kt(e,t){const r=e._ownerWritableStream,o=r._writableStreamController,n=function(e,t){try{return e._strategySizeAlgorithm(t)}catch(t){return $t(e,t),1}}(o,t);if(r!==e._ownerWritableStream)return c(Ht("write to"));const a=r._state;if("errored"===a)return c(r._storedError);if(Ct(r)||"closed"===a)return c(new TypeError("The stream is closing or closed and cannot be written to"));if("erroring"===a)return c(r._storedError);const i=function(e){return s(((t,r)=>{const o={_resolve:t,_reject:r};e._writeRequests.push(o)}))}(r);return function(e,t,r){try{Se(e,t,r)}catch(t){return void $t(e,t)}const o=e._controlledWritableStream;if(!Ct(o)&&"writable"===o._state){qt(o,Mt(e))}It(e)}(o,t,n),i}Object.defineProperties(WritableStreamDefaultWriter.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),n(WritableStreamDefaultWriter.prototype.abort,"abort"),n(WritableStreamDefaultWriter.prototype.close,"close"),n(WritableStreamDefaultWriter.prototype.releaseLock,"releaseLock"),n(WritableStreamDefaultWriter.prototype.write,"write"),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(WritableStreamDefaultWriter.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});const At={};class WritableStreamDefaultController{constructor(){throw new TypeError("Illegal constructor")}get abortReason(){if(!Dt(this))throw xt("abortReason");return this._abortReason}get signal(){if(!Dt(this))throw xt("signal");if(void 0===this._abortController)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal}error(e=void 0){if(!Dt(this))throw xt("error");"writable"===this._controlledWritableStream._state&&Yt(this,e)}[v](e){const t=this._abortAlgorithm(e);return Lt(this),t}[w](){ge(this)}}function Dt(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledWritableStream")&&e instanceof WritableStreamDefaultController)}function zt(e,t,r,o,n,a,i,l){t._controlledWritableStream=e,e._writableStreamController=t,t._queue=void 0,t._queueTotalSize=void 0,ge(t),t._abortReason=void 0,t._abortController=function(){if(ht)return new AbortController}(),t._started=!1,t._strategySizeAlgorithm=l,t._strategyHWM=i,t._writeAlgorithm=o,t._closeAlgorithm=n,t._abortAlgorithm=a;const s=Mt(t);qt(e,s);f(u(r()),(()=>(t._started=!0,It(t),null)),(r=>(t._started=!0,wt(e,r),null)))}function Lt(e){e._writeAlgorithm=void 0,e._closeAlgorithm=void 0,e._abortAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function Ft(e){return e._strategyHWM-e._queueTotalSize}function It(e){const t=e._controlledWritableStream;if(!e._started)return;if(void 0!==t._inFlightWriteRequest)return;if("erroring"===t._state)return void Tt(t);if(0===e._queue.length)return;const r=e._queue.peek().value;r===At?function(e){const t=e._controlledWritableStream;(function(e){e._inFlightCloseRequest=e._closeRequest,e._closeRequest=void 0})(t),ye(e);const r=e._closeAlgorithm();Lt(e),f(r,(()=>(function(e){e._inFlightCloseRequest._resolve(void 0),e._inFlightCloseRequest=void 0,"erroring"===e._state&&(e._storedError=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._resolve(),e._pendingAbortRequest=void 0)),e._state="closed";const t=e._writer;void 0!==t&&Xt(t)}(t),null)),(e=>(function(e,t){e._inFlightCloseRequest._reject(t),e._inFlightCloseRequest=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._reject(t),e._pendingAbortRequest=void 0),wt(e,t)}(t,e),null)))}(e):function(e,t){const r=e._controlledWritableStream;!function(e){e._inFlightWriteRequest=e._writeRequests.shift()}(r);const o=e._writeAlgorithm(t);f(o,(()=>{!function(e){e._inFlightWriteRequest._resolve(void 0),e._inFlightWriteRequest=void 0}(r);const t=r._state;if(ye(e),!Ct(r)&&"writable"===t){const t=Mt(e);qt(r,t)}return It(e),null}),(t=>("writable"===r._state&&Lt(e),function(e,t){e._inFlightWriteRequest._reject(t),e._inFlightWriteRequest=void 0,wt(e,t)}(r,t),null)))}(e,r)}function $t(e,t){"writable"===e._controlledWritableStream._state&&Yt(e,t)}function Mt(e){return Ft(e)<=0}function Yt(e,t){const r=e._controlledWritableStream;Lt(e),Rt(r,t)}function Qt(e){return new TypeError(`WritableStream.prototype.${e} can only be used on a WritableStream`)}function xt(e){return new TypeError(`WritableStreamDefaultController.prototype.${e} can only be used on a WritableStreamDefaultController`)}function Nt(e){return new TypeError(`WritableStreamDefaultWriter.prototype.${e} can only be used on a WritableStreamDefaultWriter`)}function Ht(e){return new TypeError("Cannot "+e+" a stream using a released writer")}function Vt(e){e._closedPromise=s(((t,r)=>{e._closedPromise_resolve=t,e._closedPromise_reject=r,e._closedPromiseState="pending"}))}function Ut(e,t){Vt(e),Gt(e,t)}function Gt(e,t){void 0!==e._closedPromise_reject&&(_(e._closedPromise),e._closedPromise_reject(t),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="rejected")}function Xt(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="resolved")}function Jt(e){e._readyPromise=s(((t,r)=>{e._readyPromise_resolve=t,e._readyPromise_reject=r})),e._readyPromiseState="pending"}function Kt(e,t){Jt(e),er(e,t)}function Zt(e){Jt(e),tr(e)}function er(e,t){void 0!==e._readyPromise_reject&&(_(e._readyPromise),e._readyPromise_reject(t),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="rejected")}function tr(e){void 0!==e._readyPromise_resolve&&(e._readyPromise_resolve(void 0),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="fulfilled")}Object.defineProperties(WritableStreamDefaultController.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(WritableStreamDefaultController.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});const rr="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof global?global:void 0;const or=function(){const e=null==rr?void 0:rr.DOMException;return function(e){if("function"!=typeof e&&"object"!=typeof e)return!1;if("DOMException"!==e.name)return!1;try{return new e,!0}catch(e){return!1}}(e)?e:void 0}()||function(){const e=function(e,t){this.message=e||"",this.name=t||"Error",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)};return n(e,"DOMException"),e.prototype=Object.create(Error.prototype),Object.defineProperty(e.prototype,"constructor",{value:e,writable:!0,configurable:!0}),e}();function nr(e,r,o,n,a,i){const l=N(e),h=_t(r);e._disturbed=!0;let p=!1,y=u(void 0);return s(((S,g)=>{let v;if(void 0!==i){if(v=()=>{const t=void 0!==i.reason?i.reason:new or("Aborted","AbortError"),o=[];n||o.push((()=>"writable"===r._state?gt(r,t):u(void 0))),a||o.push((()=>"readable"===e._state?Er(e,t):u(void 0))),q((()=>Promise.all(o.map((e=>e())))),!0,t)},i.aborted)return void v();i.addEventListener("abort",v)}var w,R,T;if(P(e,l._closedPromise,(e=>(n?W(!0,e):q((()=>gt(r,e)),!0,e),null))),P(r,h._closedPromise,(t=>(a?W(!0,t):q((()=>Er(e,t)),!0,t),null))),w=e,R=l._closedPromise,T=()=>(o?W():q((()=>function(e){const t=e._ownerWritableStream,r=t._state;return Ct(t)||"closed"===r?u(void 0):"errored"===r?c(t._storedError):Wt(e)}(h))),null),"closed"===w._state?T():b(R,T),Ct(r)||"closed"===r._state){const t=new TypeError("the destination writable stream closed before all data could be piped to it");a?W(!0,t):q((()=>Er(e,t)),!0,t)}function C(){const e=y;return d(y,(()=>e!==y?C():void 0))}function P(e,t,r){"errored"===e._state?r(e._storedError):m(t,r)}function q(e,t,o){function n(){return f(e(),(()=>B(t,o)),(e=>B(!0,e))),null}p||(p=!0,"writable"!==r._state||Ct(r)?n():b(C(),n))}function W(e,t){p||(p=!0,"writable"!==r._state||Ct(r)?B(e,t):b(C(),(()=>B(e,t))))}function B(e,t){return jt(h),E(l),void 0!==i&&i.removeEventListener("abort",v),e?g(t):S(void 0),null}_(s(((e,r)=>{!function o(n){n?e():d(p?u(!0):d(h._readyPromise,(()=>s(((e,r)=>{J(l,{_chunkSteps:r=>{y=d(kt(h,r),void 0,t),e(!1)},_closeSteps:()=>e(!0),_errorSteps:r})})))),o,r)}(!1)})))}))}class ReadableStreamDefaultController{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!ar(this))throw hr("desiredSize");return fr(this)}close(){if(!ar(this))throw hr("close");if(!br(this))throw new TypeError("The stream is not in a state that permits close");ur(this)}enqueue(e=void 0){if(!ar(this))throw hr("enqueue");if(!br(this))throw new TypeError("The stream is not in a state that permits enqueue");return cr(this,e)}error(e=void 0){if(!ar(this))throw hr("error");dr(this,e)}[R](e){ge(this);const t=this._cancelAlgorithm(e);return sr(this),t}[T](e){const t=this._controlledReadableStream;if(this._queue.length>0){const r=ye(this);this._closeRequested&&0===this._queue.length?(sr(this),Wr(t)):ir(this),e._chunkSteps(r)}else H(t,e),ir(this)}[C](){}}function ar(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableStream")&&e instanceof ReadableStreamDefaultController)}function ir(e){if(!lr(e))return;if(e._pulling)return void(e._pullAgain=!0);e._pulling=!0;f(e._pullAlgorithm(),(()=>(e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,ir(e)),null)),(t=>(dr(e,t),null)))}function lr(e){const t=e._controlledReadableStream;if(!br(e))return!1;if(!e._started)return!1;if(qr(t)&&U(t)>0)return!0;return fr(e)>0}function sr(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function ur(e){if(!br(e))return;const t=e._controlledReadableStream;e._closeRequested=!0,0===e._queue.length&&(sr(e),Wr(t))}function cr(e,t){if(!br(e))return;const r=e._controlledReadableStream;if(qr(r)&&U(r)>0)V(r,t,!1);else{let r;try{r=e._strategySizeAlgorithm(t)}catch(t){throw dr(e,t),t}try{Se(e,t,r)}catch(t){throw dr(e,t),t}}ir(e)}function dr(e,t){const r=e._controlledReadableStream;"readable"===r._state&&(ge(e),sr(e),Br(r,t))}function fr(e){const t=e._controlledReadableStream._state;return"errored"===t?null:"closed"===t?0:e._strategyHWM-e._queueTotalSize}function br(e){const t=e._controlledReadableStream._state;return!e._closeRequested&&"readable"===t}function mr(e,t,r,o,n,a,i){t._controlledReadableStream=e,t._queue=void 0,t._queueTotalSize=void 0,ge(t),t._started=!1,t._closeRequested=!1,t._pullAgain=!1,t._pulling=!1,t._strategySizeAlgorithm=i,t._strategyHWM=a,t._pullAlgorithm=o,t._cancelAlgorithm=n,e._readableStreamController=t;f(u(r()),(()=>(t._started=!0,ir(t),null)),(e=>(dr(t,e),null)))}function hr(e){return new TypeError(`ReadableStreamDefaultController.prototype.${e} can only be used on a ReadableStreamDefaultController`)}function _r(e,t){return we(e._readableStreamController)?function(e){let t,r,o,n,a,i=N(e),l=!1,c=!1,d=!1,f=!1,b=!1;const h=s((e=>{a=e}));function _(e){m(e._closedPromise,(t=>(e!==i||(Ye(o._readableStreamController,t),Ye(n._readableStreamController,t),f&&b||a(void 0)),null)))}function y(){rt(i)&&(E(i),i=N(e),_(i));J(i,{_chunkSteps:t=>{p((()=>{c=!1,d=!1;const r=t;let i=t;if(!f&&!b)try{i=pe(t)}catch(t){return Ye(o._readableStreamController,t),Ye(n._readableStreamController,t),void a(Er(e,t))}f||Me(o._readableStreamController,r),b||Me(n._readableStreamController,i),l=!1,c?g():d&&v()}))},_closeSteps:()=>{l=!1,f||$e(o._readableStreamController),b||$e(n._readableStreamController),o._readableStreamController._pendingPullIntos.length>0&&He(o._readableStreamController,0),n._readableStreamController._pendingPullIntos.length>0&&He(n._readableStreamController,0),f&&b||a(void 0)},_errorSteps:()=>{l=!1}})}function S(t,r){X(i)&&(E(i),i=Ke(e),_(i));const s=r?n:o,u=r?o:n;ot(i,t,1,{_chunkSteps:t=>{p((()=>{c=!1,d=!1;const o=r?b:f;if(r?f:b)o||Ve(s._readableStreamController,t);else{let r;try{r=pe(t)}catch(t){return Ye(s._readableStreamController,t),Ye(u._readableStreamController,t),void a(Er(e,t))}o||Ve(s._readableStreamController,t),Me(u._readableStreamController,r)}l=!1,c?g():d&&v()}))},_closeSteps:e=>{l=!1;const t=r?b:f,o=r?f:b;t||$e(s._readableStreamController),o||$e(u._readableStreamController),void 0!==e&&(t||Ve(s._readableStreamController,e),!o&&u._readableStreamController._pendingPullIntos.length>0&&He(u._readableStreamController,0)),t&&o||a(void 0)},_errorSteps:()=>{l=!1}})}function g(){if(l)return c=!0,u(void 0);l=!0;const e=xe(o._readableStreamController);return null===e?y():S(e._view,!1),u(void 0)}function v(){if(l)return d=!0,u(void 0);l=!0;const e=xe(n._readableStreamController);return null===e?y():S(e._view,!0),u(void 0)}function w(o){if(f=!0,t=o,b){const o=ue([t,r]),n=Er(e,o);a(n)}return h}function R(o){if(b=!0,r=o,f){const o=ue([t,r]),n=Er(e,o);a(n)}return h}function T(){}return o=Tr(T,g,w),n=Tr(T,v,R),_(i),[o,n]}(e):function(e,t){const r=N(e);let o,n,a,i,l,c=!1,d=!1,f=!1,b=!1;const h=s((e=>{l=e}));function _(){if(c)return d=!0,u(void 0);c=!0;return J(r,{_chunkSteps:e=>{p((()=>{d=!1;const t=e,r=e;f||cr(a._readableStreamController,t),b||cr(i._readableStreamController,r),c=!1,d&&_()}))},_closeSteps:()=>{c=!1,f||ur(a._readableStreamController),b||ur(i._readableStreamController),f&&b||l(void 0)},_errorSteps:()=>{c=!1}}),u(void 0)}function y(t){if(f=!0,o=t,b){const t=ue([o,n]),r=Er(e,t);l(r)}return h}function S(t){if(b=!0,n=t,f){const t=ue([o,n]),r=Er(e,t);l(r)}return h}function g(){}return a=Rr(g,_,y),i=Rr(g,_,S),m(r._closedPromise,(e=>(dr(a._readableStreamController,e),dr(i._readableStreamController,e),f&&b||l(void 0),null))),[a,i]}(e)}function pr(e){return r(o=e)&&void 0!==o.getReader?function(e){let o;function n(){let t;try{t=e.read()}catch(e){return c(e)}return h(t,(e=>{if(!r(e))throw new TypeError("The promise returned by the reader.read() method must fulfill with an object");if(e.done)ur(o._readableStreamController);else{const t=e.value;cr(o._readableStreamController,t)}}))}function a(t){try{return u(e.cancel(t))}catch(e){return c(e)}}return o=Rr(t,n,a,0),o}(e.getReader()):function(e){let o;const n=_e(e,"async");function a(){let e;try{e=function(e){const t=y(e.nextMethod,e.iterator,[]);if(!r(t))throw new TypeError("The iterator.next() method must return an object");return t}(n)}catch(e){return c(e)}return h(u(e),(e=>{if(!r(e))throw new TypeError("The promise returned by the iterator.next() method must fulfill with an object");const t=function(e){return Boolean(e.done)}(e);if(t)ur(o._readableStreamController);else{const t=function(e){return e.value}(e);cr(o._readableStreamController,t)}}))}function i(e){const t=n.iterator;let o,a;try{o=me(t,"return")}catch(e){return c(e)}if(void 0===o)return u(void 0);try{a=y(o,t,[e])}catch(e){return c(e)}return h(u(a),(e=>{if(!r(e))throw new TypeError("The promise returned by the iterator.return() method must fulfill with an object")}))}return o=Rr(t,a,i,0),o}(e);var o}function yr(e,t,r){return L(e,r),r=>S(e,t,[r])}function Sr(e,t,r){return L(e,r),r=>S(e,t,[r])}function gr(e,t,r){return L(e,r),r=>y(e,t,[r])}function vr(e,t){if("bytes"!==(e=`${e}`))throw new TypeError(`${t} '${e}' is not a valid enumeration value for ReadableStreamType`);return e}function wr(e,t){z(e,t);const r=null==e?void 0:e.preventAbort,o=null==e?void 0:e.preventCancel,n=null==e?void 0:e.preventClose,a=null==e?void 0:e.signal;return void 0!==a&&function(e,t){if(!function(e){if("object"!=typeof e||null===e)return!1;try{return"boolean"==typeof e.aborted}catch(e){return!1}}(e))throw new TypeError(`${t} is not an AbortSignal.`)}(a,`${t} has member 'signal' that`),{preventAbort:Boolean(r),preventCancel:Boolean(o),preventClose:Boolean(n),signal:a}}Object.defineProperties(ReadableStreamDefaultController.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),n(ReadableStreamDefaultController.prototype.close,"close"),n(ReadableStreamDefaultController.prototype.enqueue,"enqueue"),n(ReadableStreamDefaultController.prototype.error,"error"),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(ReadableStreamDefaultController.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});class ReadableStream{constructor(e={},t={}){void 0===e?e=null:F(e,"First parameter");const r=st(t,"Second parameter"),o=function(e,t){z(e,t);const r=e,o=null==r?void 0:r.autoAllocateChunkSize,n=null==r?void 0:r.cancel,a=null==r?void 0:r.pull,i=null==r?void 0:r.start,l=null==r?void 0:r.type;return{autoAllocateChunkSize:void 0===o?void 0:Q(o,`${t} has member 'autoAllocateChunkSize' that`),cancel:void 0===n?void 0:yr(n,r,`${t} has member 'cancel' that`),pull:void 0===a?void 0:Sr(a,r,`${t} has member 'pull' that`),start:void 0===i?void 0:gr(i,r,`${t} has member 'start' that`),type:void 0===l?void 0:vr(l,`${t} has member 'type' that`)}}(e,"First parameter");if(Cr(this),"bytes"===o.type){if(void 0!==r.size)throw new RangeError("The strategy for a byte stream cannot have a size function");!function(e,t,r){const o=Object.create(ReadableByteStreamController.prototype);let n,a,i;n=void 0!==t.start?()=>t.start(o):()=>{},a=void 0!==t.pull?()=>t.pull(o):()=>u(void 0),i=void 0!==t.cancel?e=>t.cancel(e):()=>u(void 0);const l=t.autoAllocateChunkSize;if(0===l)throw new TypeError("autoAllocateChunkSize must be greater than 0");Ue(e,o,n,a,i,r,l)}(this,o,it(r,0))}else{const e=lt(r);!function(e,t,r,o){const n=Object.create(ReadableStreamDefaultController.prototype);let a,i,l;a=void 0!==t.start?()=>t.start(n):()=>{},i=void 0!==t.pull?()=>t.pull(n):()=>u(void 0),l=void 0!==t.cancel?e=>t.cancel(e):()=>u(void 0),mr(e,n,a,i,l,r,o)}(this,o,it(r,1),e)}}get locked(){if(!Pr(this))throw Or("locked");return qr(this)}cancel(e=void 0){return Pr(this)?qr(this)?c(new TypeError("Cannot cancel a stream that already has a reader")):Er(this,e):c(Or("cancel"))}getReader(e=void 0){if(!Pr(this))throw Or("getReader");return void 0===function(e,t){z(e,t);const r=null==e?void 0:e.mode;return{mode:void 0===r?void 0:Je(r,`${t} has member 'mode' that`)}}(e,"First parameter").mode?N(this):Ke(this)}pipeThrough(e,t={}){if(!Pr(this))throw Or("pipeThrough");I(e,1,"pipeThrough");const r=function(e,t){z(e,t);const r=null==e?void 0:e.readable;$(r,"readable","ReadableWritablePair"),x(r,`${t} has member 'readable' that`);const o=null==e?void 0:e.writable;return $(o,"writable","ReadableWritablePair"),mt(o,`${t} has member 'writable' that`),{readable:r,writable:o}}(e,"First parameter"),o=wr(t,"Second parameter");if(qr(this))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(St(r.writable))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");return _(nr(this,r.writable,o.preventClose,o.preventAbort,o.preventCancel,o.signal)),r.readable}pipeTo(e,t={}){if(!Pr(this))return c(Or("pipeTo"));if(void 0===e)return c("Parameter 1 is required in 'pipeTo'.");if(!yt(e))return c(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let r;try{r=wr(t,"Second parameter")}catch(e){return c(e)}return qr(this)?c(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):St(e)?c(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):nr(this,e,r.preventClose,r.preventAbort,r.preventCancel,r.signal)}tee(){if(!Pr(this))throw Or("tee");return ue(_r(this))}values(e=void 0){if(!Pr(this))throw Or("values");return function(e,t){const r=N(e),o=new te(r,t),n=Object.create(re);return n._asyncIteratorImpl=o,n}(this,function(e,t){z(e,t);const r=null==e?void 0:e.preventCancel;return{preventCancel:Boolean(r)}}(e,"First parameter").preventCancel)}[he](e){return this.values(e)}static from(e){return pr(e)}}function Rr(e,t,r,o=1,n=(()=>1)){const a=Object.create(ReadableStream.prototype);Cr(a);return mr(a,Object.create(ReadableStreamDefaultController.prototype),e,t,r,o,n),a}function Tr(e,t,r){const o=Object.create(ReadableStream.prototype);Cr(o);return Ue(o,Object.create(ReadableByteStreamController.prototype),e,t,r,0,void 0),o}function Cr(e){e._state="readable",e._reader=void 0,e._storedError=void 0,e._disturbed=!1}function Pr(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readableStreamController")&&e instanceof ReadableStream)}function qr(e){return void 0!==e._reader}function Er(e,r){if(e._disturbed=!0,"closed"===e._state)return u(void 0);if("errored"===e._state)return c(e._storedError);Wr(e);const o=e._reader;if(void 0!==o&&rt(o)){const e=o._readIntoRequests;o._readIntoRequests=new g,e.forEach((e=>{e._closeSteps(void 0)}))}return h(e._readableStreamController[R](r),t)}function Wr(e){e._state="closed";const t=e._reader;if(void 0!==t&&(k(t),X(t))){const e=t._readRequests;t._readRequests=new g,e.forEach((e=>{e._closeSteps()}))}}function Br(e,t){e._state="errored",e._storedError=t;const r=e._reader;void 0!==r&&(j(r,t),X(r)?K(r,t):nt(r,t))}function Or(e){return new TypeError(`ReadableStream.prototype.${e} can only be used on a ReadableStream`)}function jr(e,t){z(e,t);const r=null==e?void 0:e.highWaterMark;return $(r,"highWaterMark","QueuingStrategyInit"),{highWaterMark:M(r)}}Object.defineProperties(ReadableStream,{from:{enumerable:!0}}),Object.defineProperties(ReadableStream.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),n(ReadableStream.from,"from"),n(ReadableStream.prototype.cancel,"cancel"),n(ReadableStream.prototype.getReader,"getReader"),n(ReadableStream.prototype.pipeThrough,"pipeThrough"),n(ReadableStream.prototype.pipeTo,"pipeTo"),n(ReadableStream.prototype.tee,"tee"),n(ReadableStream.prototype.values,"values"),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(ReadableStream.prototype,Symbol.toStringTag,{value:"ReadableStream",configurable:!0}),Object.defineProperty(ReadableStream.prototype,he,{value:ReadableStream.prototype.values,writable:!0,configurable:!0});const kr=e=>e.byteLength;n(kr,"size");class ByteLengthQueuingStrategy{constructor(e){I(e,1,"ByteLengthQueuingStrategy"),e=jr(e,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=e.highWaterMark}get highWaterMark(){if(!Dr(this))throw Ar("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!Dr(this))throw Ar("size");return kr}}function Ar(e){return new TypeError(`ByteLengthQueuingStrategy.prototype.${e} can only be used on a ByteLengthQueuingStrategy`)}function Dr(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_byteLengthQueuingStrategyHighWaterMark")&&e instanceof ByteLengthQueuingStrategy)}Object.defineProperties(ByteLengthQueuingStrategy.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(ByteLengthQueuingStrategy.prototype,Symbol.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});const zr=()=>1;n(zr,"size");class CountQueuingStrategy{constructor(e){I(e,1,"CountQueuingStrategy"),e=jr(e,"First parameter"),this._countQueuingStrategyHighWaterMark=e.highWaterMark}get highWaterMark(){if(!Fr(this))throw Lr("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!Fr(this))throw Lr("size");return zr}}function Lr(e){return new TypeError(`CountQueuingStrategy.prototype.${e} can only be used on a CountQueuingStrategy`)}function Fr(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_countQueuingStrategyHighWaterMark")&&e instanceof CountQueuingStrategy)}function Ir(e,t,r){return L(e,r),r=>S(e,t,[r])}function $r(e,t,r){return L(e,r),r=>y(e,t,[r])}function Mr(e,t,r){return L(e,r),(r,o)=>S(e,t,[r,o])}function Yr(e,t,r){return L(e,r),r=>S(e,t,[r])}Object.defineProperties(CountQueuingStrategy.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(CountQueuingStrategy.prototype,Symbol.toStringTag,{value:"CountQueuingStrategy",configurable:!0});class TransformStream{constructor(e={},t={},r={}){void 0===e&&(e=null);const o=st(t,"Second parameter"),n=st(r,"Third parameter"),a=function(e,t){z(e,t);const r=null==e?void 0:e.cancel,o=null==e?void 0:e.flush,n=null==e?void 0:e.readableType,a=null==e?void 0:e.start,i=null==e?void 0:e.transform,l=null==e?void 0:e.writableType;return{cancel:void 0===r?void 0:Yr(r,e,`${t} has member 'cancel' that`),flush:void 0===o?void 0:Ir(o,e,`${t} has member 'flush' that`),readableType:n,start:void 0===a?void 0:$r(a,e,`${t} has member 'start' that`),transform:void 0===i?void 0:Mr(i,e,`${t} has member 'transform' that`),writableType:l}}(e,"First parameter");if(void 0!==a.readableType)throw new RangeError("Invalid readableType specified");if(void 0!==a.writableType)throw new RangeError("Invalid writableType specified");const i=it(n,0),l=lt(n),d=it(o,1),b=lt(o);let m;!function(e,t,r,o,n,a){function i(){return t}function l(t){return function(e,t){const r=e._transformStreamController;if(e._backpressure){return h(e._backpressureChangePromise,(()=>{const o=e._writable;if("erroring"===o._state)throw o._storedError;return Jr(r,t)}))}return Jr(r,t)}(e,t)}function u(t){return function(e,t){const r=e._transformStreamController;if(void 0!==r._finishPromise)return r._finishPromise;const o=e._readable;r._finishPromise=s(((e,t)=>{r._finishPromise_resolve=e,r._finishPromise_reject=t}));const n=r._cancelAlgorithm(t);return Gr(r),f(n,(()=>("errored"===o._state?eo(r,o._storedError):(dr(o._readableStreamController,t),Zr(r)),null)),(e=>(dr(o._readableStreamController,e),eo(r,e),null))),r._finishPromise}(e,t)}function c(){return function(e){const t=e._transformStreamController;if(void 0!==t._finishPromise)return t._finishPromise;const r=e._readable;t._finishPromise=s(((e,r)=>{t._finishPromise_resolve=e,t._finishPromise_reject=r}));const o=t._flushAlgorithm();return Gr(t),f(o,(()=>("errored"===r._state?eo(t,r._storedError):(ur(r._readableStreamController),Zr(t)),null)),(e=>(dr(r._readableStreamController,e),eo(t,e),null))),t._finishPromise}(e)}function d(){return function(e){return Vr(e,!1),e._backpressureChangePromise}(e)}function b(t){return function(e,t){const r=e._transformStreamController;if(void 0!==r._finishPromise)return r._finishPromise;const o=e._writable;r._finishPromise=s(((e,t)=>{r._finishPromise_resolve=e,r._finishPromise_reject=t}));const n=r._cancelAlgorithm(t);return Gr(r),f(n,(()=>("errored"===o._state?eo(r,o._storedError):($t(o._writableStreamController,t),Hr(e),Zr(r)),null)),(t=>($t(o._writableStreamController,t),Hr(e),eo(r,t),null))),r._finishPromise}(e,t)}e._writable=function(e,t,r,o,n=1,a=(()=>1)){const i=Object.create(WritableStream.prototype);return pt(i),zt(i,Object.create(WritableStreamDefaultController.prototype),e,t,r,o,n,a),i}(i,l,c,u,r,o),e._readable=Rr(i,d,b,n,a),e._backpressure=void 0,e._backpressureChangePromise=void 0,e._backpressureChangePromise_resolve=void 0,Vr(e,!0),e._transformStreamController=void 0}(this,s((e=>{m=e})),d,b,i,l),function(e,t){const r=Object.create(TransformStreamDefaultController.prototype);let o,n,a;o=void 0!==t.transform?e=>t.transform(e,r):e=>{try{return Xr(r,e),u(void 0)}catch(e){return c(e)}};n=void 0!==t.flush?()=>t.flush(r):()=>u(void 0);a=void 0!==t.cancel?e=>t.cancel(e):()=>u(void 0);!function(e,t,r,o,n){t._controlledTransformStream=e,e._transformStreamController=t,t._transformAlgorithm=r,t._flushAlgorithm=o,t._cancelAlgorithm=n,t._finishPromise=void 0,t._finishPromise_resolve=void 0,t._finishPromise_reject=void 0}(e,r,o,n,a)}(this,a),void 0!==a.start?m(a.start(this._transformStreamController)):m(void 0)}get readable(){if(!Qr(this))throw to("readable");return this._readable}get writable(){if(!Qr(this))throw to("writable");return this._writable}}function Qr(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_transformStreamController")&&e instanceof TransformStream)}function xr(e,t){dr(e._readable._readableStreamController,t),Nr(e,t)}function Nr(e,t){Gr(e._transformStreamController),$t(e._writable._writableStreamController,t),Hr(e)}function Hr(e){e._backpressure&&Vr(e,!1)}function Vr(e,t){void 0!==e._backpressureChangePromise&&e._backpressureChangePromise_resolve(),e._backpressureChangePromise=s((t=>{e._backpressureChangePromise_resolve=t})),e._backpressure=t}Object.defineProperties(TransformStream.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(TransformStream.prototype,Symbol.toStringTag,{value:"TransformStream",configurable:!0});class TransformStreamDefaultController{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Ur(this))throw Kr("desiredSize");return fr(this._controlledTransformStream._readable._readableStreamController)}enqueue(e=void 0){if(!Ur(this))throw Kr("enqueue");Xr(this,e)}error(e=void 0){if(!Ur(this))throw Kr("error");var t;t=e,xr(this._controlledTransformStream,t)}terminate(){if(!Ur(this))throw Kr("terminate");!function(e){const t=e._controlledTransformStream;ur(t._readable._readableStreamController);const r=new TypeError("TransformStream terminated");Nr(t,r)}(this)}}function Ur(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledTransformStream")&&e instanceof TransformStreamDefaultController)}function Gr(e){e._transformAlgorithm=void 0,e._flushAlgorithm=void 0,e._cancelAlgorithm=void 0}function Xr(e,t){const r=e._controlledTransformStream,o=r._readable._readableStreamController;if(!br(o))throw new TypeError("Readable side is not in a state that permits enqueue");try{cr(o,t)}catch(e){throw Nr(r,e),r._readable._storedError}const n=function(e){return!lr(e)}(o);n!==r._backpressure&&Vr(r,!0)}function Jr(e,t){return h(e._transformAlgorithm(t),void 0,(t=>{throw xr(e._controlledTransformStream,t),t}))}function Kr(e){return new TypeError(`TransformStreamDefaultController.prototype.${e} can only be used on a TransformStreamDefaultController`)}function Zr(e){void 0!==e._finishPromise_resolve&&(e._finishPromise_resolve(),e._finishPromise_resolve=void 0,e._finishPromise_reject=void 0)}function eo(e,t){void 0!==e._finishPromise_reject&&(_(e._finishPromise),e._finishPromise_reject(t),e._finishPromise_resolve=void 0,e._finishPromise_reject=void 0)}function to(e){return new TypeError(`TransformStream.prototype.${e} can only be used on a TransformStream`)}Object.defineProperties(TransformStreamDefaultController.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),n(TransformStreamDefaultController.prototype.enqueue,"enqueue"),n(TransformStreamDefaultController.prototype.error,"error"),n(TransformStreamDefaultController.prototype.terminate,"terminate"),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(TransformStreamDefaultController.prototype,Symbol.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});const ro={ReadableStream:ReadableStream,ReadableStreamDefaultController:ReadableStreamDefaultController,ReadableByteStreamController:ReadableByteStreamController,ReadableStreamBYOBRequest:ReadableStreamBYOBRequest,ReadableStreamDefaultReader:ReadableStreamDefaultReader,ReadableStreamBYOBReader:ReadableStreamBYOBReader,WritableStream:WritableStream,WritableStreamDefaultController:WritableStreamDefaultController,WritableStreamDefaultWriter:WritableStreamDefaultWriter,ByteLengthQueuingStrategy:ByteLengthQueuingStrategy,CountQueuingStrategy:CountQueuingStrategy,TransformStream:TransformStream,TransformStreamDefaultController:TransformStreamDefaultController};if(void 0!==rr)for(const e in ro)Object.prototype.hasOwnProperty.call(ro,e)&&Object.defineProperty(rr,e,{value:ro[e],writable:!0,configurable:!0});e.ByteLengthQueuingStrategy=ByteLengthQueuingStrategy,e.CountQueuingStrategy=CountQueuingStrategy,e.ReadableByteStreamController=ReadableByteStreamController,e.ReadableStream=ReadableStream,e.ReadableStreamBYOBReader=ReadableStreamBYOBReader,e.ReadableStreamBYOBRequest=ReadableStreamBYOBRequest,e.ReadableStreamDefaultController=ReadableStreamDefaultController,e.ReadableStreamDefaultReader=ReadableStreamDefaultReader,e.TransformStream=TransformStream,e.TransformStreamDefaultController=TransformStreamDefaultController,e.WritableStream=WritableStream,e.WritableStreamDefaultController=WritableStreamDefaultController,e.WritableStreamDefaultWriter=WritableStreamDefaultWriter})); +//# sourceMappingURL=polyfill.es2018.min.js.map diff --git a/backend/node_modules/web-streams-polyfill/dist/polyfill.es2018.min.js.map b/backend/node_modules/web-streams-polyfill/dist/polyfill.es2018.min.js.map new file mode 100644 index 0000000000000000000000000000000000000000..2a68110c6ba47e09f578d0c47bdb194923af6c99 --- /dev/null +++ b/backend/node_modules/web-streams-polyfill/dist/polyfill.es2018.min.js.map @@ -0,0 +1 @@ +{"version":3,"file":"polyfill.es2018.min.js","sources":["../src/utils.ts","../src/lib/helpers/miscellaneous.ts","../src/lib/helpers/webidl.ts","../src/lib/simple-queue.ts","../src/lib/abstract-ops/internal-methods.ts","../src/lib/readable-stream/generic-reader.ts","../src/stub/number-isfinite.ts","../src/stub/math-trunc.ts","../src/lib/validators/basic.ts","../src/lib/validators/readable-stream.ts","../src/lib/readable-stream/default-reader.ts","../src/target/es2018/stub/async-iterator-prototype.ts","../src/lib/readable-stream/async-iterator.ts","../src/stub/number-isnan.ts","../src/lib/abstract-ops/ecmascript.ts","../src/lib/abstract-ops/miscellaneous.ts","../src/lib/abstract-ops/queue-with-sizes.ts","../src/lib/helpers/array-buffer-view.ts","../src/lib/readable-stream/byte-stream-controller.ts","../src/lib/readable-stream/byob-reader.ts","../src/lib/validators/reader-options.ts","../src/lib/abstract-ops/queuing-strategy.ts","../src/lib/validators/queuing-strategy.ts","../src/lib/validators/underlying-sink.ts","../src/lib/validators/writable-stream.ts","../src/lib/abort-signal.ts","../src/lib/writable-stream.ts","../src/globals.ts","../src/stub/dom-exception.ts","../src/lib/readable-stream/pipe.ts","../src/lib/readable-stream/default-controller.ts","../src/lib/readable-stream/tee.ts","../src/lib/readable-stream/from.ts","../src/lib/readable-stream/readable-stream-like.ts","../src/lib/validators/underlying-source.ts","../src/lib/validators/pipe-options.ts","../src/lib/readable-stream.ts","../src/lib/validators/readable-writable-pair.ts","../src/lib/validators/iterator-options.ts","../src/lib/validators/queuing-strategy-init.ts","../src/lib/byte-length-queuing-strategy.ts","../src/lib/count-queuing-strategy.ts","../src/lib/validators/transformer.ts","../src/lib/transform-stream.ts","../src/polyfill.ts"],"sourcesContent":["export function noop(): undefined {\n return undefined;\n}\n","import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n\nexport function setFunctionName(fn: Function, name: string): void {\n try {\n Object.defineProperty(fn, 'name', {\n value: name,\n configurable: true\n });\n } catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n }\n}\n","import { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\n// https://webidl.spec.whatwg.org/#a-new-promise\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-resolved-with\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return newPromise(resolve => resolve(value));\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-rejected-with\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\n// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned\n// from that handler. To prevent this, return null instead of void from all handlers.\n// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => null | PromiseLike,\n onRejected?: (reason: any) => null | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => null | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => null | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nlet _queueMicrotask: (callback: () => void) => void = callback => {\n if (typeof queueMicrotask === 'function') {\n _queueMicrotask = queueMicrotask;\n } else {\n const resolvedPromise = promiseResolvedWith(undefined);\n _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb);\n }\n return _queueMicrotask(callback);\n};\n\nexport { _queueMicrotask as queueMicrotask };\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n","import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n","export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\nexport const ReleaseSteps = Symbol('[[ReleaseSteps]]');\n","import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, type ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\nimport { ReleaseSteps } from '../abstract-ops/internal-methods';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n assert(stream._reader === reader);\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n stream._readableStreamController[ReleaseSteps]();\n\n stream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n","import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n","import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamDefaultReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamDefaultReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\nexport function ReadableStreamDefaultReaderRelease(reader: ReadableStreamDefaultReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n}\n\nexport function ReadableStreamDefaultReaderErrorReadRequests(reader: ReadableStreamDefaultReader, e: any) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n","/// \n\n/* eslint-disable @typescript-eslint/no-empty-function */\nexport const AsyncIteratorPrototype: AsyncIterable =\n Object.getPrototypeOf(Object.getPrototypeOf(async function* (): AsyncIterableIterator {}).prototype);\n","/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadableStreamDefaultReadResult,\n type ReadRequest\n} from './default-reader';\nimport { ReadableStreamReaderGenericCancel, ReadableStreamReaderGenericRelease } from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterableIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ninterface ReadableStreamAsyncIteratorInstance extends ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nObject.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n","import { reflectCall } from 'lib/helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport assert from '../../stub/assert';\n\ndeclare global {\n interface ArrayBuffer {\n readonly detached: boolean;\n\n transfer(): ArrayBuffer;\n }\n\n function structuredClone(value: T, options: { transfer: ArrayBuffer[] }): T;\n}\n\nexport function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\nexport let TransferArrayBuffer = (O: ArrayBuffer): ArrayBuffer => {\n if (typeof O.transfer === 'function') {\n TransferArrayBuffer = buffer => buffer.transfer();\n } else if (typeof structuredClone === 'function') {\n TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] });\n } else {\n // Not implemented correctly\n TransferArrayBuffer = buffer => buffer;\n }\n return TransferArrayBuffer(O);\n};\n\nexport function CanTransferArrayBuffer(O: ArrayBuffer): boolean {\n return !IsDetachedBuffer(O);\n}\n\nexport let IsDetachedBuffer = (O: ArrayBuffer): boolean => {\n if (typeof O.detached === 'boolean') {\n IsDetachedBuffer = buffer => buffer.detached;\n } else {\n // Not implemented correctly\n IsDetachedBuffer = buffer => buffer.byteLength === 0;\n }\n return IsDetachedBuffer(O);\n};\n\nexport function ArrayBufferSlice(buffer: ArrayBuffer, begin: number, end: number): ArrayBuffer {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n\nexport type MethodName = {\n [P in keyof T]: T[P] extends Function | undefined ? P : never;\n}[keyof T];\n\nexport function GetMethod>(receiver: T, prop: K): T[K] | undefined {\n const func = receiver[prop];\n if (func === undefined || func === null) {\n return undefined;\n }\n if (typeof func !== 'function') {\n throw new TypeError(`${String(prop)} is not a function`);\n }\n return func;\n}\n\nexport interface SyncIteratorRecord {\n iterator: Iterator,\n nextMethod: Iterator['next'],\n done: boolean;\n}\n\nexport interface AsyncIteratorRecord {\n iterator: AsyncIterator,\n nextMethod: AsyncIterator['next'],\n done: boolean;\n}\n\nexport type SyncOrAsyncIteratorRecord = SyncIteratorRecord | AsyncIteratorRecord;\n\nexport function CreateAsyncFromSyncIterator(syncIteratorRecord: SyncIteratorRecord): AsyncIteratorRecord {\n // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%,\n // we use yield* inside an async generator function to achieve the same result.\n\n // Wrap the sync iterator inside a sync iterable, so we can use it with yield*.\n const syncIterable = {\n [Symbol.iterator]: () => syncIteratorRecord.iterator\n };\n // Create an async generator function and immediately invoke it.\n const asyncIterator = (async function* () {\n return yield* syncIterable;\n }());\n // Return as an async iterator record.\n const nextMethod = asyncIterator.next;\n return { iterator: asyncIterator, nextMethod, done: false };\n}\n\n// Aligns with core-js/modules/es.symbol.async-iterator.js\nexport const SymbolAsyncIterator: (typeof Symbol)['asyncIterator'] =\n Symbol.asyncIterator ??\n Symbol.for?.('Symbol.asyncIterator') ??\n '@@asyncIterator';\n\nexport type SyncOrAsyncIterable = Iterable | AsyncIterable;\nexport type SyncOrAsyncIteratorMethod = () => (Iterator | AsyncIterator);\n\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint: 'async',\n method?: SyncOrAsyncIteratorMethod\n): AsyncIteratorRecord;\nfunction GetIterator(\n obj: Iterable,\n hint: 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncIteratorRecord;\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint = 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncOrAsyncIteratorRecord {\n assert(hint === 'sync' || hint === 'async');\n if (method === undefined) {\n if (hint === 'async') {\n method = GetMethod(obj as AsyncIterable, SymbolAsyncIterator);\n if (method === undefined) {\n const syncMethod = GetMethod(obj as Iterable, Symbol.iterator);\n const syncIteratorRecord = GetIterator(obj as Iterable, 'sync', syncMethod);\n return CreateAsyncFromSyncIterator(syncIteratorRecord);\n }\n } else {\n method = GetMethod(obj as Iterable, Symbol.iterator);\n }\n }\n if (method === undefined) {\n throw new TypeError('The object is not iterable');\n }\n const iterator = reflectCall(method, obj, []);\n if (!typeIsObject(iterator)) {\n throw new TypeError('The iterator method must return an object');\n }\n const nextMethod = iterator.next;\n return { iterator, nextMethod, done: false } as SyncOrAsyncIteratorRecord;\n}\n\nexport { GetIterator };\n\nexport function IteratorNext(iteratorRecord: AsyncIteratorRecord): Promise> {\n const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []);\n if (!typeIsObject(result)) {\n throw new TypeError('The iterator.next() method must return an object');\n }\n return result;\n}\n\nexport function IteratorComplete(\n iterResult: IteratorResult\n): iterResult is IteratorReturnResult {\n assert(typeIsObject(iterResult));\n return Boolean(iterResult.done);\n}\n\nexport function IteratorValue(iterResult: IteratorYieldResult): T {\n assert(typeIsObject(iterResult));\n return iterResult.value;\n}\n","import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: NonShared): NonShared {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer) as NonShared;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n","export type TypedArray =\n | Int8Array\n | Uint8Array\n | Uint8ClampedArray\n | Int16Array\n | Uint16Array\n | Int32Array\n | Uint32Array\n | Float32Array\n | Float64Array;\n\nexport type NonShared = T & {\n buffer: ArrayBuffer;\n}\n\nexport interface ArrayBufferViewConstructor {\n new(buffer: ArrayBuffer, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n}\n\nexport interface TypedArrayConstructor extends ArrayBufferViewConstructor {\n readonly BYTES_PER_ELEMENT: number;\n}\n\nexport type DataViewConstructor = ArrayBufferViewConstructor;\n\nfunction isDataViewConstructor(ctor: Function): ctor is DataViewConstructor {\n return ctor === DataView;\n}\n\nexport function isDataView(view: ArrayBufferView): view is DataView {\n return isDataViewConstructor(view.constructor);\n}\n\nexport function arrayBufferViewElementSize(ctor: ArrayBufferViewConstructor): number {\n if (isDataViewConstructor(ctor)) {\n return 1;\n }\n return (ctor as unknown as TypedArrayConstructor).BYTES_PER_ELEMENT;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n IsReadableStreamDefaultReader,\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n type ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n type ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n type ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport type { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\nimport {\n type ArrayBufferViewConstructor,\n arrayBufferViewElementSize,\n type NonShared,\n type TypedArrayConstructor\n} from '../helpers/array-buffer-view';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: NonShared | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: NonShared): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond');\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBuffer;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor = NonShared> =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: TypedArrayConstructor;\n readerType: 'default' | 'none';\n}\n\ninterface BYOBPullIntoDescriptor = NonShared> {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob' | 'none';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: NonShared): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest>): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n minimumFill: 1,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n if (this._pendingPullIntos.length > 0) {\n const firstPullInto = this._pendingPullIntos.peek();\n firstPullInto.readerType = 'none';\n\n this._pendingPullIntos = new SimpleQueue();\n this._pendingPullIntos.push(firstPullInto);\n }\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableByteStreamController.prototype.close, 'close');\nsetFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableByteStreamController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor>(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n assert(pullIntoDescriptor.readerType !== 'none');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as NonShared, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor>(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n let clonedChunk;\n try {\n clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength);\n } catch (cloneE) {\n ReadableByteStreamControllerError(controller, cloneE);\n throw cloneE;\n }\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength);\n}\n\nfunction ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.readerType === 'none');\n if (firstDescriptor.bytesFilled > 0) {\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n firstDescriptor.buffer,\n firstDescriptor.byteOffset,\n firstDescriptor.bytesFilled\n );\n }\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize;\n const maxAlignedBytes = maxBytesFilled - remainderBytes;\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n assert(pullIntoDescriptor.readerType !== 'none');\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nfunction ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller: ReadableByteStreamController) {\n const reader = controller._controlledReadableByteStream._reader;\n assert(IsReadableStreamDefaultReader(reader));\n while (reader._readRequests.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n const readRequest = reader._readRequests.shift();\n ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest);\n }\n}\n\nexport function ReadableByteStreamControllerPullInto>(\n controller: ReadableByteStreamController,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n const elementSize = arrayBufferViewElementSize(ctor);\n\n const { byteOffset, byteLength } = view;\n\n const minimumFill = min * elementSize;\n assert(minimumFill >= elementSize && minimumFill <= byteLength);\n assert(minimumFill % elementSize === 0);\n\n let buffer: ArrayBuffer;\n try {\n buffer = TransferArrayBuffer(view.buffer);\n } catch (e) {\n readIntoRequest._errorSteps(e);\n return;\n }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset,\n byteLength,\n bytesFilled: 0,\n minimumFill,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled % firstDescriptor.elementSize === 0);\n\n if (firstDescriptor.readerType === 'none') {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n return;\n }\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) {\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n pullIntoDescriptor.buffer,\n end - remainderSize,\n remainderSize\n );\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(\n controller: ReadableByteStreamController,\n chunk: NonShared\n) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const { buffer, byteOffset, byteLength } = chunk;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n if (firstPendingPullInto.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto);\n }\n }\n\n if (ReadableStreamHasDefaultReader(stream)) {\n ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller);\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView as NonShared, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerFillReadRequestFromQueue(\n controller: ReadableByteStreamController,\n readRequest: ReadRequest>\n) {\n assert(controller._queueTotalSize > 0);\n\n const entry = controller._queue.shift();\n controller._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n readRequest._chunkSteps(view as NonShared);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view as NonShared);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: NonShared) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: NonShared) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, type ReadableByteStream, type ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from './reader-options';\nimport { convertByobReadOptions } from '../validators/reader-options';\nimport { isDataView, type NonShared, type TypedArray } from '../helpers/array-buffer-view';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream as ReadableStream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest>(\n stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest\n): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest> {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(\n view: T,\n options?: ReadableStreamBYOBReaderReadOptions\n ): Promise>;\n read>(\n view: T,\n rawOptions: ReadableStreamBYOBReaderReadOptions | null | undefined = {}\n ): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n let options: ValidatedReadableStreamBYOBReaderReadOptions;\n try {\n options = convertByobReadOptions(rawOptions, 'options');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const min = options.min;\n if (min === 0) {\n return promiseRejectedWith(new TypeError('options.min must be greater than 0'));\n }\n if (!isDataView(view)) {\n if (min > (view as unknown as TypedArray).length) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s length'));\n }\n } else if (min > view.byteLength) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s byteLength'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamBYOBReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamBYOBReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead>(\n reader: ReadableStreamBYOBReader,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n min,\n readIntoRequest\n );\n }\n}\n\nexport function ReadableStreamBYOBReaderRelease(reader: ReadableStreamBYOBReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n}\n\nexport function ReadableStreamBYOBReaderErrorReadIntoRequests(reader: ReadableStreamBYOBReader, e: any) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n","import { assertDictionary, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n\nexport function convertByobReadOptions(\n options: ReadableStreamBYOBReaderReadOptions | null | undefined,\n context: string\n): ValidatedReadableStreamBYOBReaderReadOptions {\n assertDictionary(options, context);\n const min = options?.min ?? 1;\n return {\n min: convertUnsignedLongLongWithEnforceRange(\n min,\n `${context} has member 'min' that`\n )\n };\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n","/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * If aborted, returns the reason for aborting.\n */\n readonly reason?: any;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(reason?: any): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n type QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { type AbortController, type AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(WritableStream.prototype.abort, 'abort');\nsetFunctionName(WritableStream.prototype.close, 'close');\nsetFunctionName(WritableStream.prototype.getWriter, 'getWriter');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight\n};\n\nexport type {\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort(reason);\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nsetFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort');\nsetFunctionName(WritableStreamDefaultWriter.prototype.close, 'close');\nsetFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock');\nsetFunctionName(WritableStreamDefaultWriter.prototype.write, 'write');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n return null;\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let writeAlgorithm: (chunk: W) => Promise;\n let closeAlgorithm: () => Promise;\n let abortAlgorithm: (reason: any) => Promise;\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n } else {\n writeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n } else {\n closeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n } else {\n abortAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n return null;\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n","/// \n\nfunction getGlobals(): typeof globalThis | undefined {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n } else if (typeof self !== 'undefined') {\n return self;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n","/// \nimport { globals } from '../globals';\nimport { setFunctionName } from '../lib/helpers/miscellaneous';\n\ninterface DOMException extends Error {\n name: string;\n message: string;\n}\n\ntype DOMExceptionConstructor = new (message?: string, name?: string) => DOMException;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n if ((ctor as DOMExceptionConstructor).name !== 'DOMException') {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Support:\n * - Web browsers\n * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87)\n */\nfunction getFromGlobal(): DOMExceptionConstructor | undefined {\n const ctor = globals?.DOMException;\n return isDOMExceptionConstructor(ctor) ? ctor : undefined;\n}\n\n/**\n * Support:\n * - All platforms\n */\nfunction createPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line @typescript-eslint/no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n setFunctionName(ctor, 'DOMException');\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nconst DOMException: DOMExceptionConstructor = getFromGlobal() || createPolyfill();\n\nexport { DOMException };\n","import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n return null;\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => null) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => null) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest(): null {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n return null;\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any): null {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n\n return null;\n }\n });\n}\n","import type { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, type QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n type ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport type { ValidatedUnderlyingSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n // Do nothing.\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultController.prototype.close, 'close');\nsetFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableStreamDefaultController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n","import {\n CreateReadableByteStream,\n CreateReadableStream,\n type DefaultReadableStream,\n IsReadableStream,\n type ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n type ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n type ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(\n stream: ReadableStream,\n cloneForBranch2: boolean\n): [DefaultReadableStream, DefaultReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: DefaultReadableStream;\n let branch2: DefaultReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader> = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader>) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return null;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: NonShared, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader>(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n","import { CreateReadableStream, type DefaultReadableStream } from '../readable-stream';\nimport {\n isReadableStreamLike,\n type ReadableStreamDefaultReaderLike,\n type ReadableStreamLike\n} from './readable-stream-like';\nimport { ReadableStreamDefaultControllerClose, ReadableStreamDefaultControllerEnqueue } from './default-controller';\nimport { GetIterator, GetMethod, IteratorComplete, IteratorNext, IteratorValue } from '../abstract-ops/ecmascript';\nimport { promiseRejectedWith, promiseResolvedWith, reflectCall, transformPromiseWith } from '../helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { noop } from '../../utils';\n\nexport function ReadableStreamFrom(\n source: Iterable | AsyncIterable | ReadableStreamLike\n): DefaultReadableStream {\n if (isReadableStreamLike(source)) {\n return ReadableStreamFromDefaultReader(source.getReader());\n }\n return ReadableStreamFromIterable(source);\n}\n\nexport function ReadableStreamFromIterable(asyncIterable: Iterable | AsyncIterable): DefaultReadableStream {\n let stream: DefaultReadableStream;\n const iteratorRecord = GetIterator(asyncIterable, 'async');\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let nextResult;\n try {\n nextResult = IteratorNext(iteratorRecord);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const nextPromise = promiseResolvedWith(nextResult);\n return transformPromiseWith(nextPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object');\n }\n const done = IteratorComplete(iterResult);\n if (done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = IteratorValue(iterResult);\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n const iterator = iteratorRecord.iterator;\n let returnMethod: (typeof iterator)['return'] | undefined;\n try {\n returnMethod = GetMethod(iterator, 'return');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n if (returnMethod === undefined) {\n return promiseResolvedWith(undefined);\n }\n let returnResult: IteratorResult | Promise>;\n try {\n returnResult = reflectCall(returnMethod, iterator, [reason]);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const returnPromise = promiseResolvedWith(returnResult);\n return transformPromiseWith(returnPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object');\n }\n return undefined;\n });\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n\nexport function ReadableStreamFromDefaultReader(\n reader: ReadableStreamDefaultReaderLike\n): DefaultReadableStream {\n let stream: DefaultReadableStream;\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let readPromise;\n try {\n readPromise = reader.read();\n } catch (e) {\n return promiseRejectedWith(e);\n }\n return transformPromiseWith(readPromise, readResult => {\n if (!typeIsObject(readResult)) {\n throw new TypeError('The promise returned by the reader.read() method must fulfill with an object');\n }\n if (readResult.done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = readResult.value;\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n try {\n return promiseResolvedWith(reader.cancel(reason));\n } catch (e) {\n return promiseRejectedWith(e);\n }\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n","import { typeIsObject } from '../helpers/miscellaneous';\nimport type { ReadableStreamDefaultReadResult } from './default-reader';\n\n/**\n * A common interface for a `ReadadableStream` implementation.\n *\n * @public\n */\nexport interface ReadableStreamLike {\n readonly locked: boolean;\n\n getReader(): ReadableStreamDefaultReaderLike;\n}\n\n/**\n * A common interface for a `ReadableStreamDefaultReader` implementation.\n *\n * @public\n */\nexport interface ReadableStreamDefaultReaderLike {\n readonly closed: Promise;\n\n cancel(reason?: any): Promise;\n\n read(): Promise>;\n\n releaseLock(): void;\n}\n\nexport function isReadableStreamLike(stream: unknown): stream is ReadableStreamLike {\n return typeIsObject(stream) && typeof (stream as ReadableStreamLike).getReader !== 'undefined';\n}\n","import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n","import { assertDictionary } from './basic';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n","import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, type ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderErrorReadRequests,\n type ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReaderErrorReadIntoRequests,\n type ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { ReadableStreamFrom } from './readable-stream/from';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport type {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList, SymbolAsyncIterator } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions\n} from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport type { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport type { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\nimport type { ReadableStreamDefaultReaderLike, ReadableStreamLike } from './readable-stream/readable-stream-like';\nimport type { NonShared } from './helpers/array-buffer-view';\n\nexport type DefaultReadableStream = ReadableStream & {\n _readableStreamController: ReadableStreamDefaultController\n};\n\nexport type ReadableByteStream = ReadableStream> & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream implements AsyncIterable {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n\n [SymbolAsyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator {\n // Stub implementation, overridden below\n return this.values(options);\n }\n\n /**\n * Creates a new ReadableStream wrapping the provided iterable or async iterable.\n *\n * This can be used to adapt various kinds of objects into a readable stream,\n * such as an array, an async generator, or a Node.js readable stream.\n */\n static from(asyncIterable: Iterable | AsyncIterable | ReadableStreamLike): ReadableStream {\n return ReadableStreamFrom(asyncIterable);\n }\n}\n\nObject.defineProperties(ReadableStream, {\n from: { enumerable: true }\n});\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(ReadableStream.from, 'from');\nsetFunctionName(ReadableStream.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStream.prototype.getReader, 'getReader');\nsetFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough');\nsetFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo');\nsetFunctionName(ReadableStream.prototype.tee, 'tee');\nsetFunctionName(ReadableStream.prototype.values, 'values');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nObject.defineProperty(ReadableStream.prototype, SymbolAsyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n});\n\nexport type {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n ReadableStreamBYOBReaderReadOptions,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions,\n ReadableStreamLike,\n ReadableStreamDefaultReaderLike\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1\n): DefaultReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: DefaultReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n","import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n","import { assertDictionary } from './basic';\nimport type {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n","import type { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\nsetFunctionName(byteLengthSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\nsetFunctionName(countSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const cancel = original?.cancel;\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n cancel: cancel === undefined ?\n undefined :\n convertTransformerCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n\nfunction convertTransformerCancelCallback(\n fn: TransformerCancelCallback,\n original: Transformer,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith,\n uponPromise\n} from './helpers/webidl';\nimport { CreateReadableStream, type DefaultReadableStream, ReadableStream } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: DefaultReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport type {\n Transformer,\n TransformerCancelCallback,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSourceCancelAlgorithm(stream, reason);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n TransformStreamUnblockWrite(stream);\n}\n\nfunction TransformStreamUnblockWrite(stream: TransformStream) {\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _finishPromise: Promise | undefined;\n /** @internal */\n _finishPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _finishPromise_reject?: (reason: any) => void;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n /** @internal */\n _cancelAlgorithm: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(TransformStreamDefaultController.prototype.error, 'error');\nsetFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._finishPromise = undefined;\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm: (chunk: I) => Promise;\n let flushAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n } else {\n transformAlgorithm = chunk => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n }\n\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n } else {\n flushAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n if (transformer.cancel !== undefined) {\n cancelAlgorithm = reason => transformer.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally,\n // we don't run the _cancelAlgorithm again.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerError(readable._readableStreamController, reason);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally,\n // we don't also run the _cancelAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(flushPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerClose(readable._readableStreamController);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\nfunction TransformStreamDefaultSourceCancelAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._writable cannot change after construction, so caching it across a call to user code is safe.\n const writable = stream._writable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or\n // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the\n // _flushAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (writable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, writable._storedError);\n } else {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\nexport function defaultControllerFinishPromiseResolve(controller: TransformStreamDefaultController) {\n if (controller._finishPromise_resolve === undefined) {\n return;\n }\n\n controller._finishPromise_resolve();\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nexport function defaultControllerFinishPromiseReject(controller: TransformStreamDefaultController, reason: any) {\n if (controller._finishPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(controller._finishPromise!);\n controller._finishPromise_reject(reason);\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n","import {\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n ReadableByteStreamController,\n ReadableStream,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultController,\n ReadableStreamDefaultReader,\n TransformStream,\n TransformStreamDefaultController,\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter\n} from './ponyfill';\nimport { globals } from './globals';\n\n// Export\nexport * from './ponyfill';\n\nconst exports = {\n ReadableStream,\n ReadableStreamDefaultController,\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader,\n\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter,\n\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n\n TransformStream,\n TransformStreamDefaultController\n};\n\n// Add classes to global scope\nif (typeof globals !== 'undefined') {\n for (const prop in exports) {\n if (Object.prototype.hasOwnProperty.call(exports, prop)) {\n Object.defineProperty(globals, prop, {\n value: exports[prop as (keyof typeof exports)],\n writable: true,\n configurable: true\n });\n }\n }\n}\n"],"names":["noop","typeIsObject","x","rethrowAssertionErrorRejection","setFunctionName","fn","name","Object","defineProperty","value","configurable","_a","originalPromise","Promise","originalPromiseThen","prototype","then","originalPromiseReject","reject","bind","newPromise","executor","promiseResolvedWith","resolve","promiseRejectedWith","reason","PerformPromiseThen","promise","onFulfilled","onRejected","call","uponPromise","undefined","uponFulfillment","uponRejection","transformPromiseWith","fulfillmentHandler","rejectionHandler","setPromiseIsHandledToTrue","_queueMicrotask","callback","queueMicrotask","resolvedPromise","cb","reflectCall","F","V","args","TypeError","Function","apply","promiseCall","SimpleQueue","constructor","this","_cursor","_size","_front","_elements","_next","_back","length","push","element","oldBack","newBack","QUEUE_MAX_ARRAY_SIZE","shift","oldFront","newFront","oldCursor","newCursor","elements","forEach","i","node","peek","front","cursor","AbortSteps","Symbol","ErrorSteps","CancelSteps","PullSteps","ReleaseSteps","ReadableStreamReaderGenericInitialize","reader","stream","_ownerReadableStream","_reader","_state","defaultReaderClosedPromiseInitialize","defaultReaderClosedPromiseResolve","defaultReaderClosedPromiseInitializeAsResolved","defaultReaderClosedPromiseInitializeAsRejected","_storedError","ReadableStreamReaderGenericCancel","ReadableStreamCancel","ReadableStreamReaderGenericRelease","defaultReaderClosedPromiseReject","defaultReaderClosedPromiseResetToRejected","_readableStreamController","readerLockException","_closedPromise","_closedPromise_resolve","_closedPromise_reject","NumberIsFinite","Number","isFinite","MathTrunc","Math","trunc","v","ceil","floor","assertDictionary","obj","context","assertFunction","assertObject","isObject","assertRequiredArgument","position","assertRequiredField","field","convertUnrestrictedDouble","censorNegativeZero","convertUnsignedLongLongWithEnforceRange","upperBound","MAX_SAFE_INTEGER","integerPart","assertReadableStream","IsReadableStream","AcquireReadableStreamDefaultReader","ReadableStreamDefaultReader","ReadableStreamAddReadRequest","readRequest","_readRequests","ReadableStreamFulfillReadRequest","chunk","done","_closeSteps","_chunkSteps","ReadableStreamGetNumReadRequests","ReadableStreamHasDefaultReader","IsReadableStreamDefaultReader","IsReadableStreamLocked","closed","defaultReaderBrandCheckException","cancel","read","resolvePromise","rejectPromise","ReadableStreamDefaultReaderRead","_errorSteps","e","releaseLock","ReadableStreamDefaultReaderErrorReadRequests","ReadableStreamDefaultReaderRelease","hasOwnProperty","_disturbed","readRequests","defineProperties","enumerable","toStringTag","AsyncIteratorPrototype","getPrototypeOf","async","ReadableStreamAsyncIteratorImpl","preventCancel","_ongoingPromise","_isFinished","_preventCancel","next","nextSteps","_nextSteps","returnSteps","_returnSteps","result","ReadableStreamAsyncIteratorPrototype","IsReadableStreamAsyncIterator","_asyncIteratorImpl","streamAsyncIteratorBrandCheckException","return","setPrototypeOf","NumberIsNaN","isNaN","CreateArrayFromList","slice","CopyDataBlockBytes","dest","destOffset","src","srcOffset","n","Uint8Array","set","TransferArrayBuffer","O","transfer","buffer","structuredClone","IsDetachedBuffer","detached","byteLength","ArrayBufferSlice","begin","end","ArrayBuffer","GetMethod","receiver","prop","func","String","SymbolAsyncIterator","_c","asyncIterator","_b","for","GetIterator","hint","method","syncIteratorRecord","syncIterable","iterator","nextMethod","CreateAsyncFromSyncIterator","CloneAsUint8Array","byteOffset","DequeueValue","container","pair","_queue","_queueTotalSize","size","EnqueueValueWithSize","Infinity","RangeError","ResetQueue","isDataViewConstructor","ctor","DataView","ReadableStreamBYOBRequest","view","IsReadableStreamBYOBRequest","byobRequestBrandCheckException","_view","respond","bytesWritten","_associatedReadableByteStreamController","ReadableByteStreamControllerRespond","respondWithNewView","isView","ReadableByteStreamControllerRespondWithNewView","ReadableByteStreamController","byobRequest","IsReadableByteStreamController","byteStreamControllerBrandCheckException","ReadableByteStreamControllerGetBYOBRequest","desiredSize","ReadableByteStreamControllerGetDesiredSize","close","_closeRequested","state","_controlledReadableByteStream","ReadableByteStreamControllerClose","enqueue","ReadableByteStreamControllerEnqueue","error","ReadableByteStreamControllerError","ReadableByteStreamControllerClearPendingPullIntos","_cancelAlgorithm","ReadableByteStreamControllerClearAlgorithms","ReadableByteStreamControllerFillReadRequestFromQueue","autoAllocateChunkSize","_autoAllocateChunkSize","bufferE","pullIntoDescriptor","bufferByteLength","bytesFilled","minimumFill","elementSize","viewConstructor","readerType","_pendingPullIntos","ReadableByteStreamControllerCallPullIfNeeded","firstPullInto","controller","shouldPull","_started","ReadableStreamHasBYOBReader","ReadableStreamGetNumReadIntoRequests","ReadableByteStreamControllerShouldCallPull","_pulling","_pullAgain","_pullAlgorithm","ReadableByteStreamControllerInvalidateBYOBRequest","ReadableByteStreamControllerCommitPullIntoDescriptor","filledView","ReadableByteStreamControllerConvertPullIntoDescriptor","readIntoRequest","_readIntoRequests","ReadableStreamFulfillReadIntoRequest","ReadableByteStreamControllerEnqueueChunkToQueue","ReadableByteStreamControllerEnqueueClonedChunkToQueue","clonedChunk","cloneE","ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue","firstDescriptor","ReadableByteStreamControllerShiftPendingPullInto","ReadableByteStreamControllerFillPullIntoDescriptorFromQueue","maxBytesToCopy","min","maxBytesFilled","totalBytesToCopyRemaining","ready","maxAlignedBytes","queue","headOfQueue","bytesToCopy","destStart","ReadableByteStreamControllerFillHeadPullIntoDescriptor","ReadableByteStreamControllerHandleQueueDrain","ReadableStreamClose","_byobRequest","ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue","ReadableByteStreamControllerPullInto","BYTES_PER_ELEMENT","arrayBufferViewElementSize","ReadableStreamAddReadIntoRequest","emptyView","ReadableByteStreamControllerRespondInternal","ReadableByteStreamControllerRespondInClosedState","remainderSize","ReadableByteStreamControllerRespondInReadableState","firstPendingPullInto","transferredBuffer","ReadableByteStreamControllerProcessReadRequestsUsingQueue","ReadableStreamError","entry","create","request","SetUpReadableStreamBYOBRequest","_strategyHWM","viewByteLength","SetUpReadableByteStreamController","startAlgorithm","pullAlgorithm","cancelAlgorithm","highWaterMark","r","convertReadableStreamReaderMode","mode","AcquireReadableStreamBYOBReader","ReadableStreamBYOBReader","IsReadableStreamBYOBReader","byobReaderBrandCheckException","rawOptions","options","convertByobReadOptions","isDataView","ReadableStreamBYOBReaderRead","ReadableStreamBYOBReaderErrorReadIntoRequests","ReadableStreamBYOBReaderRelease","readIntoRequests","ExtractHighWaterMark","strategy","defaultHWM","ExtractSizeAlgorithm","convertQueuingStrategy","init","convertQueuingStrategySize","convertUnderlyingSinkAbortCallback","original","convertUnderlyingSinkCloseCallback","convertUnderlyingSinkStartCallback","convertUnderlyingSinkWriteCallback","assertWritableStream","IsWritableStream","supportsAbortController","AbortController","WritableStream","rawUnderlyingSink","rawStrategy","underlyingSink","abort","start","type","write","convertUnderlyingSink","InitializeWritableStream","sizeAlgorithm","WritableStreamDefaultController","writeAlgorithm","closeAlgorithm","abortAlgorithm","SetUpWritableStreamDefaultController","SetUpWritableStreamDefaultControllerFromUnderlyingSink","locked","streamBrandCheckException","IsWritableStreamLocked","WritableStreamAbort","WritableStreamCloseQueuedOrInFlight","WritableStreamClose","getWriter","AcquireWritableStreamDefaultWriter","WritableStreamDefaultWriter","_writer","_writableStreamController","_writeRequests","_inFlightWriteRequest","_closeRequest","_inFlightCloseRequest","_pendingAbortRequest","_backpressure","_abortReason","_abortController","_promise","wasAlreadyErroring","_resolve","_reject","_reason","_wasAlreadyErroring","WritableStreamStartErroring","closeRequest","writer","defaultWriterReadyPromiseResolve","closeSentinel","WritableStreamDefaultControllerAdvanceQueueIfNeeded","WritableStreamDealWithRejection","WritableStreamFinishErroring","WritableStreamDefaultWriterEnsureReadyPromiseRejected","WritableStreamHasOperationMarkedInFlight","storedError","writeRequest","WritableStreamRejectCloseAndClosedPromiseIfNeeded","abortRequest","defaultWriterClosedPromiseReject","WritableStreamUpdateBackpressure","backpressure","defaultWriterReadyPromiseInitialize","defaultWriterReadyPromiseReset","_ownerWritableStream","defaultWriterReadyPromiseInitializeAsResolved","defaultWriterClosedPromiseInitialize","defaultWriterReadyPromiseInitializeAsRejected","defaultWriterClosedPromiseResolve","defaultWriterClosedPromiseInitializeAsRejected","IsWritableStreamDefaultWriter","defaultWriterBrandCheckException","defaultWriterLockException","WritableStreamDefaultControllerGetDesiredSize","WritableStreamDefaultWriterGetDesiredSize","_readyPromise","WritableStreamDefaultWriterAbort","WritableStreamDefaultWriterClose","WritableStreamDefaultWriterRelease","WritableStreamDefaultWriterWrite","WritableStreamDefaultWriterEnsureClosedPromiseRejected","_closedPromiseState","defaultWriterClosedPromiseResetToRejected","_readyPromiseState","defaultWriterReadyPromiseReject","defaultWriterReadyPromiseResetToRejected","releasedError","chunkSize","_strategySizeAlgorithm","chunkSizeE","WritableStreamDefaultControllerErrorIfNeeded","WritableStreamDefaultControllerGetChunkSize","WritableStreamAddWriteRequest","enqueueE","_controlledWritableStream","WritableStreamDefaultControllerGetBackpressure","WritableStreamDefaultControllerWrite","abortReason","IsWritableStreamDefaultController","defaultControllerBrandCheckException","signal","WritableStreamDefaultControllerError","_abortAlgorithm","WritableStreamDefaultControllerClearAlgorithms","createAbortController","_writeAlgorithm","_closeAlgorithm","WritableStreamMarkCloseRequestInFlight","sinkClosePromise","WritableStreamFinishInFlightClose","WritableStreamFinishInFlightCloseWithError","WritableStreamDefaultControllerProcessClose","WritableStreamMarkFirstWriteRequestInFlight","sinkWritePromise","WritableStreamFinishInFlightWrite","WritableStreamFinishInFlightWriteWithError","WritableStreamDefaultControllerProcessWrite","_readyPromise_resolve","_readyPromise_reject","globals","globalThis","self","global","DOMException","isDOMExceptionConstructor","getFromGlobal","message","Error","captureStackTrace","writable","createPolyfill","ReadableStreamPipeTo","source","preventClose","preventAbort","shuttingDown","currentWrite","actions","shutdownWithAction","all","map","action","aborted","addEventListener","isOrBecomesErrored","shutdown","WritableStreamDefaultWriterCloseWithErrorPropagation","destClosed","waitForWritesToFinish","oldCurrentWrite","originalIsError","originalError","doTheRest","finalize","newError","isError","removeEventListener","resolveLoop","rejectLoop","resolveRead","rejectRead","ReadableStreamDefaultController","IsReadableStreamDefaultController","ReadableStreamDefaultControllerGetDesiredSize","ReadableStreamDefaultControllerCanCloseOrEnqueue","ReadableStreamDefaultControllerClose","ReadableStreamDefaultControllerEnqueue","ReadableStreamDefaultControllerError","ReadableStreamDefaultControllerClearAlgorithms","_controlledReadableStream","ReadableStreamDefaultControllerCallPullIfNeeded","ReadableStreamDefaultControllerShouldCallPull","SetUpReadableStreamDefaultController","ReadableStreamTee","cloneForBranch2","reason1","reason2","branch1","branch2","resolveCancelPromise","reading","readAgainForBranch1","readAgainForBranch2","canceled1","canceled2","cancelPromise","forwardReaderError","thisReader","pullWithDefaultReader","chunk1","chunk2","pull1Algorithm","pull2Algorithm","pullWithBYOBReader","forBranch2","byobBranch","otherBranch","byobCanceled","otherCanceled","cancel1Algorithm","compositeReason","cancelResult","cancel2Algorithm","CreateReadableByteStream","ReadableByteStreamTee","readAgain","CreateReadableStream","ReadableStreamDefaultTee","ReadableStreamFrom","getReader","readPromise","readResult","ReadableStreamFromDefaultReader","asyncIterable","iteratorRecord","nextResult","IteratorNext","iterResult","Boolean","IteratorComplete","IteratorValue","returnMethod","returnResult","ReadableStreamFromIterable","convertUnderlyingSourceCancelCallback","convertUnderlyingSourcePullCallback","convertUnderlyingSourceStartCallback","convertReadableStreamType","convertPipeOptions","isAbortSignal","assertAbortSignal","ReadableStream","rawUnderlyingSource","underlyingSource","pull","convertUnderlyingDefaultOrByteSource","InitializeReadableStream","underlyingByteSource","SetUpReadableByteStreamControllerFromUnderlyingSource","SetUpReadableStreamDefaultControllerFromUnderlyingSource","convertReaderOptions","pipeThrough","rawTransform","transform","readable","convertReadableWritablePair","pipeTo","destination","tee","values","impl","AcquireReadableStreamAsyncIterator","convertIteratorOptions","from","convertQueuingStrategyInit","byteLengthSizeFunction","ByteLengthQueuingStrategy","_byteLengthQueuingStrategyHighWaterMark","IsByteLengthQueuingStrategy","byteLengthBrandCheckException","countSizeFunction","CountQueuingStrategy","_countQueuingStrategyHighWaterMark","IsCountQueuingStrategy","countBrandCheckException","convertTransformerFlushCallback","convertTransformerStartCallback","convertTransformerTransformCallback","convertTransformerCancelCallback","TransformStream","rawTransformer","rawWritableStrategy","rawReadableStrategy","writableStrategy","readableStrategy","transformer","flush","readableType","writableType","convertTransformer","readableHighWaterMark","readableSizeAlgorithm","writableHighWaterMark","writableSizeAlgorithm","startPromise_resolve","startPromise","_transformStreamController","_backpressureChangePromise","_writable","TransformStreamDefaultControllerPerformTransform","TransformStreamDefaultSinkWriteAlgorithm","_finishPromise","_readable","_finishPromise_resolve","_finishPromise_reject","TransformStreamDefaultControllerClearAlgorithms","defaultControllerFinishPromiseReject","defaultControllerFinishPromiseResolve","TransformStreamDefaultSinkAbortAlgorithm","flushPromise","_flushAlgorithm","TransformStreamDefaultSinkCloseAlgorithm","TransformStreamSetBackpressure","TransformStreamDefaultSourcePullAlgorithm","TransformStreamUnblockWrite","TransformStreamDefaultSourceCancelAlgorithm","CreateWritableStream","_backpressureChangePromise_resolve","InitializeTransformStream","TransformStreamDefaultController","transformAlgorithm","flushAlgorithm","TransformStreamDefaultControllerEnqueue","transformResultE","_controlledTransformStream","_transformAlgorithm","SetUpTransformStreamDefaultController","SetUpTransformStreamDefaultControllerFromTransformer","IsTransformStream","TransformStreamError","TransformStreamErrorWritableAndUnblockWrite","IsTransformStreamDefaultController","terminate","TransformStreamDefaultControllerTerminate","readableController","ReadableStreamDefaultControllerHasBackpressure","exports"],"mappings":";;;;;;;mQAAgBA,IAEhB,CCCM,SAAUC,EAAaC,GAC3B,MAAqB,iBAANA,GAAwB,OAANA,GAA4B,mBAANA,CACzD,CAEO,MAAMC,EAUPH,EAEU,SAAAI,EAAgBC,EAAcC,GAC5C,IACEC,OAAOC,eAAeH,EAAI,OAAQ,CAChCI,MAAOH,EACPI,cAAc,GAEjB,CAAC,MAAAC,GAGD,CACH,CC1BA,MAAMC,EAAkBC,QAClBC,EAAsBD,QAAQE,UAAUC,KACxCC,EAAwBJ,QAAQK,OAAOC,KAAKP,GAG5C,SAAUQ,EAAcC,GAI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,YAAa,CAAEhG,YAAY,KAE7B/J,EAAgB2qB,iCAAiChqB,UAAU2P,QAAS,WACpEtQ,EAAgB2qB,iCAAiChqB,UAAU6P,MAAO,SAClExQ,EAAgB2qB,iCAAiChqB,UAAU6qB,UAAW,aACpC,iBAAvB5mB,OAAOoF,aAChB7J,OAAOC,eAAeuqB,iCAAiChqB,UAAWiE,OAAOoF,YAAa,CACpF3J,MAAO,mCACPC,cAAc,IClVlB,MAAMsrB,GAAU,CACd/F,8BACAtE,gEACA7R,0DACAZ,oDACA5G,wDACA4N,kDAEA2B,8BACAW,gEACAc,wDAEAoO,oDACAK,0CAEAQ,gCACAwC,mEAIF,QAAuB,IAAZ9L,GACT,IAAK,MAAM9R,KAAQ6e,GACbzrB,OAAOQ,UAAUgJ,eAAejI,KAAKkqB,GAAS7e,IAChD5M,OAAOC,eAAeye,GAAS9R,EAAM,CACnC1M,MAAOurB,GAAQ7e,GACfwS,UAAU,EACVjf,cAAc"} \ No newline at end of file diff --git a/backend/node_modules/web-streams-polyfill/dist/polyfill.es2018.mjs b/backend/node_modules/web-streams-polyfill/dist/polyfill.es2018.mjs new file mode 100644 index 0000000000000000000000000000000000000000..822ef39a83973604a68a2febb544852e8177ebb4 --- /dev/null +++ b/backend/node_modules/web-streams-polyfill/dist/polyfill.es2018.mjs @@ -0,0 +1,4745 @@ +/** + * @license + * web-streams-polyfill v3.3.3 + * Copyright 2024 Mattias Buelens, Diwank Singh Tomer and other contributors. + * This code is released under the MIT license. + * SPDX-License-Identifier: MIT + */ +function noop() { + return undefined; +} + +function typeIsObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; +} +const rethrowAssertionErrorRejection = noop; +function setFunctionName(fn, name) { + try { + Object.defineProperty(fn, 'name', { + value: name, + configurable: true + }); + } + catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility + } +} + +const originalPromise = Promise; +const originalPromiseThen = Promise.prototype.then; +const originalPromiseReject = Promise.reject.bind(originalPromise); +// https://webidl.spec.whatwg.org/#a-new-promise +function newPromise(executor) { + return new originalPromise(executor); +} +// https://webidl.spec.whatwg.org/#a-promise-resolved-with +function promiseResolvedWith(value) { + return newPromise(resolve => resolve(value)); +} +// https://webidl.spec.whatwg.org/#a-promise-rejected-with +function promiseRejectedWith(reason) { + return originalPromiseReject(reason); +} +function PerformPromiseThen(promise, onFulfilled, onRejected) { + // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an + // approximation. + return originalPromiseThen.call(promise, onFulfilled, onRejected); +} +// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned +// from that handler. To prevent this, return null instead of void from all handlers. +// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it +function uponPromise(promise, onFulfilled, onRejected) { + PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection); +} +function uponFulfillment(promise, onFulfilled) { + uponPromise(promise, onFulfilled); +} +function uponRejection(promise, onRejected) { + uponPromise(promise, undefined, onRejected); +} +function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { + return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); +} +function setPromiseIsHandledToTrue(promise) { + PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection); +} +let _queueMicrotask = callback => { + if (typeof queueMicrotask === 'function') { + _queueMicrotask = queueMicrotask; + } + else { + const resolvedPromise = promiseResolvedWith(undefined); + _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb); + } + return _queueMicrotask(callback); +}; +function reflectCall(F, V, args) { + if (typeof F !== 'function') { + throw new TypeError('Argument is not a function'); + } + return Function.prototype.apply.call(F, V, args); +} +function promiseCall(F, V, args) { + try { + return promiseResolvedWith(reflectCall(F, V, args)); + } + catch (value) { + return promiseRejectedWith(value); + } +} + +// Original from Chromium +// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js +const QUEUE_MAX_ARRAY_SIZE = 16384; +/** + * Simple queue structure. + * + * Avoids scalability issues with using a packed array directly by using + * multiple arrays in a linked list and keeping the array size bounded. + */ +class SimpleQueue { + constructor() { + this._cursor = 0; + this._size = 0; + // _front and _back are always defined. + this._front = { + _elements: [], + _next: undefined + }; + this._back = this._front; + // The cursor is used to avoid calling Array.shift(). + // It contains the index of the front element of the array inside the + // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE). + this._cursor = 0; + // When there is only one node, size === elements.length - cursor. + this._size = 0; + } + get length() { + return this._size; + } + // For exception safety, this method is structured in order: + // 1. Read state + // 2. Calculate required state mutations + // 3. Perform state mutations + push(element) { + const oldBack = this._back; + let newBack = oldBack; + if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { + newBack = { + _elements: [], + _next: undefined + }; + } + // push() is the mutation most likely to throw an exception, so it + // goes first. + oldBack._elements.push(element); + if (newBack !== oldBack) { + this._back = newBack; + oldBack._next = newBack; + } + ++this._size; + } + // Like push(), shift() follows the read -> calculate -> mutate pattern for + // exception safety. + shift() { // must not be called on an empty queue + const oldFront = this._front; + let newFront = oldFront; + const oldCursor = this._cursor; + let newCursor = oldCursor + 1; + const elements = oldFront._elements; + const element = elements[oldCursor]; + if (newCursor === QUEUE_MAX_ARRAY_SIZE) { + newFront = oldFront._next; + newCursor = 0; + } + // No mutations before this point. + --this._size; + this._cursor = newCursor; + if (oldFront !== newFront) { + this._front = newFront; + } + // Permit shifted element to be garbage collected. + elements[oldCursor] = undefined; + return element; + } + // The tricky thing about forEach() is that it can be called + // re-entrantly. The queue may be mutated inside the callback. It is easy to + // see that push() within the callback has no negative effects since the end + // of the queue is checked for on every iteration. If shift() is called + // repeatedly within the callback then the next iteration may return an + // element that has been removed. In this case the callback will be called + // with undefined values until we either "catch up" with elements that still + // exist or reach the back of the queue. + forEach(callback) { + let i = this._cursor; + let node = this._front; + let elements = node._elements; + while (i !== elements.length || node._next !== undefined) { + if (i === elements.length) { + node = node._next; + elements = node._elements; + i = 0; + if (elements.length === 0) { + break; + } + } + callback(elements[i]); + ++i; + } + } + // Return the element that would be returned if shift() was called now, + // without modifying the queue. + peek() { // must not be called on an empty queue + const front = this._front; + const cursor = this._cursor; + return front._elements[cursor]; + } +} + +const AbortSteps = Symbol('[[AbortSteps]]'); +const ErrorSteps = Symbol('[[ErrorSteps]]'); +const CancelSteps = Symbol('[[CancelSteps]]'); +const PullSteps = Symbol('[[PullSteps]]'); +const ReleaseSteps = Symbol('[[ReleaseSteps]]'); + +function ReadableStreamReaderGenericInitialize(reader, stream) { + reader._ownerReadableStream = stream; + stream._reader = reader; + if (stream._state === 'readable') { + defaultReaderClosedPromiseInitialize(reader); + } + else if (stream._state === 'closed') { + defaultReaderClosedPromiseInitializeAsResolved(reader); + } + else { + defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); + } +} +// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state +// check. +function ReadableStreamReaderGenericCancel(reader, reason) { + const stream = reader._ownerReadableStream; + return ReadableStreamCancel(stream, reason); +} +function ReadableStreamReaderGenericRelease(reader) { + const stream = reader._ownerReadableStream; + if (stream._state === 'readable') { + defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + else { + defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + stream._readableStreamController[ReleaseSteps](); + stream._reader = undefined; + reader._ownerReadableStream = undefined; +} +// Helper functions for the readers. +function readerLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released reader'); +} +// Helper functions for the ReadableStreamDefaultReader. +function defaultReaderClosedPromiseInitialize(reader) { + reader._closedPromise = newPromise((resolve, reject) => { + reader._closedPromise_resolve = resolve; + reader._closedPromise_reject = reject; + }); +} +function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseReject(reader, reason); +} +function defaultReaderClosedPromiseInitializeAsResolved(reader) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseResolve(reader); +} +function defaultReaderClosedPromiseReject(reader, reason) { + if (reader._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(reader._closedPromise); + reader._closedPromise_reject(reason); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; +} +function defaultReaderClosedPromiseResetToRejected(reader, reason) { + defaultReaderClosedPromiseInitializeAsRejected(reader, reason); +} +function defaultReaderClosedPromiseResolve(reader) { + if (reader._closedPromise_resolve === undefined) { + return; + } + reader._closedPromise_resolve(undefined); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; +} + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill +const NumberIsFinite = Number.isFinite || function (x) { + return typeof x === 'number' && isFinite(x); +}; + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill +const MathTrunc = Math.trunc || function (v) { + return v < 0 ? Math.ceil(v) : Math.floor(v); +}; + +// https://heycam.github.io/webidl/#idl-dictionaries +function isDictionary(x) { + return typeof x === 'object' || typeof x === 'function'; +} +function assertDictionary(obj, context) { + if (obj !== undefined && !isDictionary(obj)) { + throw new TypeError(`${context} is not an object.`); + } +} +// https://heycam.github.io/webidl/#idl-callback-functions +function assertFunction(x, context) { + if (typeof x !== 'function') { + throw new TypeError(`${context} is not a function.`); + } +} +// https://heycam.github.io/webidl/#idl-object +function isObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; +} +function assertObject(x, context) { + if (!isObject(x)) { + throw new TypeError(`${context} is not an object.`); + } +} +function assertRequiredArgument(x, position, context) { + if (x === undefined) { + throw new TypeError(`Parameter ${position} is required in '${context}'.`); + } +} +function assertRequiredField(x, field, context) { + if (x === undefined) { + throw new TypeError(`${field} is required in '${context}'.`); + } +} +// https://heycam.github.io/webidl/#idl-unrestricted-double +function convertUnrestrictedDouble(value) { + return Number(value); +} +function censorNegativeZero(x) { + return x === 0 ? 0 : x; +} +function integerPart(x) { + return censorNegativeZero(MathTrunc(x)); +} +// https://heycam.github.io/webidl/#idl-unsigned-long-long +function convertUnsignedLongLongWithEnforceRange(value, context) { + const lowerBound = 0; + const upperBound = Number.MAX_SAFE_INTEGER; + let x = Number(value); + x = censorNegativeZero(x); + if (!NumberIsFinite(x)) { + throw new TypeError(`${context} is not a finite number`); + } + x = integerPart(x); + if (x < lowerBound || x > upperBound) { + throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`); + } + if (!NumberIsFinite(x) || x === 0) { + return 0; + } + // TODO Use BigInt if supported? + // let xBigInt = BigInt(integerPart(x)); + // xBigInt = BigInt.asUintN(64, xBigInt); + // return Number(xBigInt); + return x; +} + +function assertReadableStream(x, context) { + if (!IsReadableStream(x)) { + throw new TypeError(`${context} is not a ReadableStream.`); + } +} + +// Abstract operations for the ReadableStream. +function AcquireReadableStreamDefaultReader(stream) { + return new ReadableStreamDefaultReader(stream); +} +// ReadableStream API exposed for controllers. +function ReadableStreamAddReadRequest(stream, readRequest) { + stream._reader._readRequests.push(readRequest); +} +function ReadableStreamFulfillReadRequest(stream, chunk, done) { + const reader = stream._reader; + const readRequest = reader._readRequests.shift(); + if (done) { + readRequest._closeSteps(); + } + else { + readRequest._chunkSteps(chunk); + } +} +function ReadableStreamGetNumReadRequests(stream) { + return stream._reader._readRequests.length; +} +function ReadableStreamHasDefaultReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamDefaultReader(reader)) { + return false; + } + return true; +} +/** + * A default reader vended by a {@link ReadableStream}. + * + * @public + */ +class ReadableStreamDefaultReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + /** + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('read')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: () => resolvePromise({ value: undefined, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamDefaultReaderRead(this, readRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamDefaultReader(this)) { + throw defaultReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamDefaultReaderRelease(this); + } +} +Object.defineProperties(ReadableStreamDefaultReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } +}); +setFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel'); +setFunctionName(ReadableStreamDefaultReader.prototype.read, 'read'); +setFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, { + value: 'ReadableStreamDefaultReader', + configurable: true + }); +} +// Abstract operations for the readers. +function IsReadableStreamDefaultReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) { + return false; + } + return x instanceof ReadableStreamDefaultReader; +} +function ReadableStreamDefaultReaderRead(reader, readRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'closed') { + readRequest._closeSteps(); + } + else if (stream._state === 'errored') { + readRequest._errorSteps(stream._storedError); + } + else { + stream._readableStreamController[PullSteps](readRequest); + } +} +function ReadableStreamDefaultReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + const e = new TypeError('Reader was released'); + ReadableStreamDefaultReaderErrorReadRequests(reader, e); +} +function ReadableStreamDefaultReaderErrorReadRequests(reader, e) { + const readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(readRequest => { + readRequest._errorSteps(e); + }); +} +// Helper functions for the ReadableStreamDefaultReader. +function defaultReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`); +} + +/// +/* eslint-disable @typescript-eslint/no-empty-function */ +const AsyncIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf(async function* () { }).prototype); + +/// +class ReadableStreamAsyncIteratorImpl { + constructor(reader, preventCancel) { + this._ongoingPromise = undefined; + this._isFinished = false; + this._reader = reader; + this._preventCancel = preventCancel; + } + next() { + const nextSteps = () => this._nextSteps(); + this._ongoingPromise = this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : + nextSteps(); + return this._ongoingPromise; + } + return(value) { + const returnSteps = () => this._returnSteps(value); + return this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : + returnSteps(); + } + _nextSteps() { + if (this._isFinished) { + return Promise.resolve({ value: undefined, done: true }); + } + const reader = this._reader; + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => { + this._ongoingPromise = undefined; + // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test. + // FIXME Is this a bug in the specification, or in the test? + _queueMicrotask(() => resolvePromise({ value: chunk, done: false })); + }, + _closeSteps: () => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + resolvePromise({ value: undefined, done: true }); + }, + _errorSteps: reason => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + rejectPromise(reason); + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promise; + } + _returnSteps(value) { + if (this._isFinished) { + return Promise.resolve({ value, done: true }); + } + this._isFinished = true; + const reader = this._reader; + if (!this._preventCancel) { + const result = ReadableStreamReaderGenericCancel(reader, value); + ReadableStreamReaderGenericRelease(reader); + return transformPromiseWith(result, () => ({ value, done: true })); + } + ReadableStreamReaderGenericRelease(reader); + return promiseResolvedWith({ value, done: true }); + } +} +const ReadableStreamAsyncIteratorPrototype = { + next() { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next')); + } + return this._asyncIteratorImpl.next(); + }, + return(value) { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return')); + } + return this._asyncIteratorImpl.return(value); + } +}; +Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); +// Abstract operations for the ReadableStream. +function AcquireReadableStreamAsyncIterator(stream, preventCancel) { + const reader = AcquireReadableStreamDefaultReader(stream); + const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); + const iterator = Object.create(ReadableStreamAsyncIteratorPrototype); + iterator._asyncIteratorImpl = impl; + return iterator; +} +function IsReadableStreamAsyncIterator(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) { + return false; + } + try { + // noinspection SuspiciousTypeOfGuard + return x._asyncIteratorImpl instanceof + ReadableStreamAsyncIteratorImpl; + } + catch (_a) { + return false; + } +} +// Helper functions for the ReadableStream. +function streamAsyncIteratorBrandCheckException(name) { + return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`); +} + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill +const NumberIsNaN = Number.isNaN || function (x) { + // eslint-disable-next-line no-self-compare + return x !== x; +}; + +var _a, _b, _c; +function CreateArrayFromList(elements) { + // We use arrays to represent lists, so this is basically a no-op. + // Do a slice though just in case we happen to depend on the unique-ness. + return elements.slice(); +} +function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { + new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); +} +let TransferArrayBuffer = (O) => { + if (typeof O.transfer === 'function') { + TransferArrayBuffer = buffer => buffer.transfer(); + } + else if (typeof structuredClone === 'function') { + TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] }); + } + else { + // Not implemented correctly + TransferArrayBuffer = buffer => buffer; + } + return TransferArrayBuffer(O); +}; +let IsDetachedBuffer = (O) => { + if (typeof O.detached === 'boolean') { + IsDetachedBuffer = buffer => buffer.detached; + } + else { + // Not implemented correctly + IsDetachedBuffer = buffer => buffer.byteLength === 0; + } + return IsDetachedBuffer(O); +}; +function ArrayBufferSlice(buffer, begin, end) { + // ArrayBuffer.prototype.slice is not available on IE10 + // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice + if (buffer.slice) { + return buffer.slice(begin, end); + } + const length = end - begin; + const slice = new ArrayBuffer(length); + CopyDataBlockBytes(slice, 0, buffer, begin, length); + return slice; +} +function GetMethod(receiver, prop) { + const func = receiver[prop]; + if (func === undefined || func === null) { + return undefined; + } + if (typeof func !== 'function') { + throw new TypeError(`${String(prop)} is not a function`); + } + return func; +} +function CreateAsyncFromSyncIterator(syncIteratorRecord) { + // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%, + // we use yield* inside an async generator function to achieve the same result. + // Wrap the sync iterator inside a sync iterable, so we can use it with yield*. + const syncIterable = { + [Symbol.iterator]: () => syncIteratorRecord.iterator + }; + // Create an async generator function and immediately invoke it. + const asyncIterator = (async function* () { + return yield* syncIterable; + }()); + // Return as an async iterator record. + const nextMethod = asyncIterator.next; + return { iterator: asyncIterator, nextMethod, done: false }; +} +// Aligns with core-js/modules/es.symbol.async-iterator.js +const SymbolAsyncIterator = (_c = (_a = Symbol.asyncIterator) !== null && _a !== void 0 ? _a : (_b = Symbol.for) === null || _b === void 0 ? void 0 : _b.call(Symbol, 'Symbol.asyncIterator')) !== null && _c !== void 0 ? _c : '@@asyncIterator'; +function GetIterator(obj, hint = 'sync', method) { + if (method === undefined) { + if (hint === 'async') { + method = GetMethod(obj, SymbolAsyncIterator); + if (method === undefined) { + const syncMethod = GetMethod(obj, Symbol.iterator); + const syncIteratorRecord = GetIterator(obj, 'sync', syncMethod); + return CreateAsyncFromSyncIterator(syncIteratorRecord); + } + } + else { + method = GetMethod(obj, Symbol.iterator); + } + } + if (method === undefined) { + throw new TypeError('The object is not iterable'); + } + const iterator = reflectCall(method, obj, []); + if (!typeIsObject(iterator)) { + throw new TypeError('The iterator method must return an object'); + } + const nextMethod = iterator.next; + return { iterator, nextMethod, done: false }; +} +function IteratorNext(iteratorRecord) { + const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []); + if (!typeIsObject(result)) { + throw new TypeError('The iterator.next() method must return an object'); + } + return result; +} +function IteratorComplete(iterResult) { + return Boolean(iterResult.done); +} +function IteratorValue(iterResult) { + return iterResult.value; +} + +function IsNonNegativeNumber(v) { + if (typeof v !== 'number') { + return false; + } + if (NumberIsNaN(v)) { + return false; + } + if (v < 0) { + return false; + } + return true; +} +function CloneAsUint8Array(O) { + const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength); + return new Uint8Array(buffer); +} + +function DequeueValue(container) { + const pair = container._queue.shift(); + container._queueTotalSize -= pair.size; + if (container._queueTotalSize < 0) { + container._queueTotalSize = 0; + } + return pair.value; +} +function EnqueueValueWithSize(container, value, size) { + if (!IsNonNegativeNumber(size) || size === Infinity) { + throw new RangeError('Size must be a finite, non-NaN, non-negative number.'); + } + container._queue.push({ value, size }); + container._queueTotalSize += size; +} +function PeekQueueValue(container) { + const pair = container._queue.peek(); + return pair.value; +} +function ResetQueue(container) { + container._queue = new SimpleQueue(); + container._queueTotalSize = 0; +} + +function isDataViewConstructor(ctor) { + return ctor === DataView; +} +function isDataView(view) { + return isDataViewConstructor(view.constructor); +} +function arrayBufferViewElementSize(ctor) { + if (isDataViewConstructor(ctor)) { + return 1; + } + return ctor.BYTES_PER_ELEMENT; +} + +/** + * A pull-into request in a {@link ReadableByteStreamController}. + * + * @public + */ +class ReadableStreamBYOBRequest { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. + */ + get view() { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('view'); + } + return this._view; + } + respond(bytesWritten) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respond'); + } + assertRequiredArgument(bytesWritten, 1, 'respond'); + bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter'); + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(this._view.buffer)) { + throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`); + } + ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); + } + respondWithNewView(view) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respondWithNewView'); + } + assertRequiredArgument(view, 1, 'respondWithNewView'); + if (!ArrayBuffer.isView(view)) { + throw new TypeError('You can only respond with array buffer views'); + } + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(view.buffer)) { + throw new TypeError('The given view\'s buffer has been detached and so cannot be used as a response'); + } + ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); + } +} +Object.defineProperties(ReadableStreamBYOBRequest.prototype, { + respond: { enumerable: true }, + respondWithNewView: { enumerable: true }, + view: { enumerable: true } +}); +setFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond'); +setFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, { + value: 'ReadableStreamBYOBRequest', + configurable: true + }); +} +/** + * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. + * + * @public + */ +class ReadableByteStreamController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the current BYOB pull request, or `null` if there isn't one. + */ + get byobRequest() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('byobRequest'); + } + return ReadableByteStreamControllerGetBYOBRequest(this); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('desiredSize'); + } + return ReadableByteStreamControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('close'); + } + if (this._closeRequested) { + throw new TypeError('The stream has already been closed; do not close it again!'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`); + } + ReadableByteStreamControllerClose(this); + } + enqueue(chunk) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('enqueue'); + } + assertRequiredArgument(chunk, 1, 'enqueue'); + if (!ArrayBuffer.isView(chunk)) { + throw new TypeError('chunk must be an array buffer view'); + } + if (chunk.byteLength === 0) { + throw new TypeError('chunk must have non-zero byteLength'); + } + if (chunk.buffer.byteLength === 0) { + throw new TypeError(`chunk's buffer must have non-zero byteLength`); + } + if (this._closeRequested) { + throw new TypeError('stream is closed or draining'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`); + } + ReadableByteStreamControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('error'); + } + ReadableByteStreamControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ReadableByteStreamControllerClearPendingPullIntos(this); + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableByteStreamControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableByteStream; + if (this._queueTotalSize > 0) { + ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest); + return; + } + const autoAllocateChunkSize = this._autoAllocateChunkSize; + if (autoAllocateChunkSize !== undefined) { + let buffer; + try { + buffer = new ArrayBuffer(autoAllocateChunkSize); + } + catch (bufferE) { + readRequest._errorSteps(bufferE); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: autoAllocateChunkSize, + byteOffset: 0, + byteLength: autoAllocateChunkSize, + bytesFilled: 0, + minimumFill: 1, + elementSize: 1, + viewConstructor: Uint8Array, + readerType: 'default' + }; + this._pendingPullIntos.push(pullIntoDescriptor); + } + ReadableStreamAddReadRequest(stream, readRequest); + ReadableByteStreamControllerCallPullIfNeeded(this); + } + /** @internal */ + [ReleaseSteps]() { + if (this._pendingPullIntos.length > 0) { + const firstPullInto = this._pendingPullIntos.peek(); + firstPullInto.readerType = 'none'; + this._pendingPullIntos = new SimpleQueue(); + this._pendingPullIntos.push(firstPullInto); + } + } +} +Object.defineProperties(ReadableByteStreamController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + byobRequest: { enumerable: true }, + desiredSize: { enumerable: true } +}); +setFunctionName(ReadableByteStreamController.prototype.close, 'close'); +setFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue'); +setFunctionName(ReadableByteStreamController.prototype.error, 'error'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, { + value: 'ReadableByteStreamController', + configurable: true + }); +} +// Abstract operations for the ReadableByteStreamController. +function IsReadableByteStreamController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) { + return false; + } + return x instanceof ReadableByteStreamController; +} +function IsReadableStreamBYOBRequest(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) { + return false; + } + return x instanceof ReadableStreamBYOBRequest; +} +function ReadableByteStreamControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableByteStreamControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + // TODO: Test controller argument + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + return null; + }, e => { + ReadableByteStreamControllerError(controller, e); + return null; + }); +} +function ReadableByteStreamControllerClearPendingPullIntos(controller) { + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + controller._pendingPullIntos = new SimpleQueue(); +} +function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { + let done = false; + if (stream._state === 'closed') { + done = true; + } + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'default') { + ReadableStreamFulfillReadRequest(stream, filledView, done); + } + else { + ReadableStreamFulfillReadIntoRequest(stream, filledView, done); + } +} +function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { + const bytesFilled = pullIntoDescriptor.bytesFilled; + const elementSize = pullIntoDescriptor.elementSize; + return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); +} +function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { + controller._queue.push({ buffer, byteOffset, byteLength }); + controller._queueTotalSize += byteLength; +} +function ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, buffer, byteOffset, byteLength) { + let clonedChunk; + try { + clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength); + } + catch (cloneE) { + ReadableByteStreamControllerError(controller, cloneE); + throw cloneE; + } + ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength); +} +function ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstDescriptor) { + if (firstDescriptor.bytesFilled > 0) { + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, firstDescriptor.buffer, firstDescriptor.byteOffset, firstDescriptor.bytesFilled); + } + ReadableByteStreamControllerShiftPendingPullInto(controller); +} +function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { + const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); + const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; + let totalBytesToCopyRemaining = maxBytesToCopy; + let ready = false; + const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize; + const maxAlignedBytes = maxBytesFilled - remainderBytes; + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) { + totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; + ready = true; + } + const queue = controller._queue; + while (totalBytesToCopyRemaining > 0) { + const headOfQueue = queue.peek(); + const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); + const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); + if (headOfQueue.byteLength === bytesToCopy) { + queue.shift(); + } + else { + headOfQueue.byteOffset += bytesToCopy; + headOfQueue.byteLength -= bytesToCopy; + } + controller._queueTotalSize -= bytesToCopy; + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); + totalBytesToCopyRemaining -= bytesToCopy; + } + return ready; +} +function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { + pullIntoDescriptor.bytesFilled += size; +} +function ReadableByteStreamControllerHandleQueueDrain(controller) { + if (controller._queueTotalSize === 0 && controller._closeRequested) { + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(controller._controlledReadableByteStream); + } + else { + ReadableByteStreamControllerCallPullIfNeeded(controller); + } +} +function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { + if (controller._byobRequest === null) { + return; + } + controller._byobRequest._associatedReadableByteStreamController = undefined; + controller._byobRequest._view = null; + controller._byobRequest = null; +} +function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { + while (controller._pendingPullIntos.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const pullIntoDescriptor = controller._pendingPullIntos.peek(); + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + } + } +} +function ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller) { + const reader = controller._controlledReadableByteStream._reader; + while (reader._readRequests.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const readRequest = reader._readRequests.shift(); + ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest); + } +} +function ReadableByteStreamControllerPullInto(controller, view, min, readIntoRequest) { + const stream = controller._controlledReadableByteStream; + const ctor = view.constructor; + const elementSize = arrayBufferViewElementSize(ctor); + const { byteOffset, byteLength } = view; + const minimumFill = min * elementSize; + let buffer; + try { + buffer = TransferArrayBuffer(view.buffer); + } + catch (e) { + readIntoRequest._errorSteps(e); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: buffer.byteLength, + byteOffset, + byteLength, + bytesFilled: 0, + minimumFill, + elementSize, + viewConstructor: ctor, + readerType: 'byob' + }; + if (controller._pendingPullIntos.length > 0) { + controller._pendingPullIntos.push(pullIntoDescriptor); + // No ReadableByteStreamControllerCallPullIfNeeded() call since: + // - No change happens on desiredSize + // - The source has already been notified of that there's at least 1 pending read(view) + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + return; + } + if (stream._state === 'closed') { + const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); + readIntoRequest._closeSteps(emptyView); + return; + } + if (controller._queueTotalSize > 0) { + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + ReadableByteStreamControllerHandleQueueDrain(controller); + readIntoRequest._chunkSteps(filledView); + return; + } + if (controller._closeRequested) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + readIntoRequest._errorSteps(e); + return; + } + } + controller._pendingPullIntos.push(pullIntoDescriptor); + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { + if (firstDescriptor.readerType === 'none') { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const stream = controller._controlledReadableByteStream; + if (ReadableStreamHasBYOBReader(stream)) { + while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { + const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); + } + } +} +function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + return; + } + if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) { + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + return; + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; + if (remainderSize > 0) { + const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor.buffer, end - remainderSize, remainderSize); + } + pullIntoDescriptor.bytesFilled -= remainderSize; + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); +} +function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor); + } + else { + ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerShiftPendingPullInto(controller) { + const descriptor = controller._pendingPullIntos.shift(); + return descriptor; +} +function ReadableByteStreamControllerShouldCallPull(controller) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return false; + } + if (controller._closeRequested) { + return false; + } + if (!controller._started) { + return false; + } + if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; +} +function ReadableByteStreamControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; +} +// A client of ReadableByteStreamController may use these functions directly to bypass state check. +function ReadableByteStreamControllerClose(controller) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + if (controller._queueTotalSize > 0) { + controller._closeRequested = true; + return; + } + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + throw e; + } + } + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(stream); +} +function ReadableByteStreamControllerEnqueue(controller, chunk) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + const { buffer, byteOffset, byteLength } = chunk; + if (IsDetachedBuffer(buffer)) { + throw new TypeError('chunk\'s buffer is detached and so cannot be enqueued'); + } + const transferredBuffer = TransferArrayBuffer(buffer); + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (IsDetachedBuffer(firstPendingPullInto.buffer)) { + throw new TypeError('The BYOB request\'s buffer has been detached and so cannot be filled with an enqueued chunk'); + } + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer); + if (firstPendingPullInto.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto); + } + } + if (ReadableStreamHasDefaultReader(stream)) { + ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller); + if (ReadableStreamGetNumReadRequests(stream) === 0) { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + else { + if (controller._pendingPullIntos.length > 0) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); + ReadableStreamFulfillReadRequest(stream, transferredView, false); + } + } + else if (ReadableStreamHasBYOBReader(stream)) { + // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully. + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + else { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerError(controller, e) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return; + } + ReadableByteStreamControllerClearPendingPullIntos(controller); + ResetQueue(controller); + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); +} +function ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest) { + const entry = controller._queue.shift(); + controller._queueTotalSize -= entry.byteLength; + ReadableByteStreamControllerHandleQueueDrain(controller); + const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); + readRequest._chunkSteps(view); +} +function ReadableByteStreamControllerGetBYOBRequest(controller) { + if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); + const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); + SetUpReadableStreamBYOBRequest(byobRequest, controller, view); + controller._byobRequest = byobRequest; + } + return controller._byobRequest; +} +function ReadableByteStreamControllerGetDesiredSize(controller) { + const state = controller._controlledReadableByteStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; +} +function ReadableByteStreamControllerRespond(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (bytesWritten !== 0) { + throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream'); + } + } + else { + if (bytesWritten === 0) { + throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream'); + } + if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) { + throw new RangeError('bytesWritten out of range'); + } + } + firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); + ReadableByteStreamControllerRespondInternal(controller, bytesWritten); +} +function ReadableByteStreamControllerRespondWithNewView(controller, view) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (view.byteLength !== 0) { + throw new TypeError('The view\'s length must be 0 when calling respondWithNewView() on a closed stream'); + } + } + else { + if (view.byteLength === 0) { + throw new TypeError('The view\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'); + } + } + if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { + throw new RangeError('The region specified by view does not match byobRequest'); + } + if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) { + throw new RangeError('The buffer of view has different capacity than byobRequest'); + } + if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) { + throw new RangeError('The region specified by view is larger than byobRequest'); + } + const viewByteLength = view.byteLength; + firstDescriptor.buffer = TransferArrayBuffer(view.buffer); + ReadableByteStreamControllerRespondInternal(controller, viewByteLength); +} +function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { + controller._controlledReadableByteStream = stream; + controller._pullAgain = false; + controller._pulling = false; + controller._byobRequest = null; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._closeRequested = false; + controller._started = false; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._autoAllocateChunkSize = autoAllocateChunkSize; + controller._pendingPullIntos = new SimpleQueue(); + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableByteStreamControllerCallPullIfNeeded(controller); + return null; + }, r => { + ReadableByteStreamControllerError(controller, r); + return null; + }); +} +function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { + const controller = Object.create(ReadableByteStreamController.prototype); + let startAlgorithm; + let pullAlgorithm; + let cancelAlgorithm; + if (underlyingByteSource.start !== undefined) { + startAlgorithm = () => underlyingByteSource.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingByteSource.pull !== undefined) { + pullAlgorithm = () => underlyingByteSource.pull(controller); + } + else { + pullAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingByteSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingByteSource.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; + if (autoAllocateChunkSize === 0) { + throw new TypeError('autoAllocateChunkSize must be greater than 0'); + } + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); +} +function SetUpReadableStreamBYOBRequest(request, controller, view) { + request._associatedReadableByteStreamController = controller; + request._view = view; +} +// Helper functions for the ReadableStreamBYOBRequest. +function byobRequestBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`); +} +// Helper functions for the ReadableByteStreamController. +function byteStreamControllerBrandCheckException(name) { + return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`); +} + +function convertReaderOptions(options, context) { + assertDictionary(options, context); + const mode = options === null || options === void 0 ? void 0 : options.mode; + return { + mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`) + }; +} +function convertReadableStreamReaderMode(mode, context) { + mode = `${mode}`; + if (mode !== 'byob') { + throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`); + } + return mode; +} +function convertByobReadOptions(options, context) { + var _a; + assertDictionary(options, context); + const min = (_a = options === null || options === void 0 ? void 0 : options.min) !== null && _a !== void 0 ? _a : 1; + return { + min: convertUnsignedLongLongWithEnforceRange(min, `${context} has member 'min' that`) + }; +} + +// Abstract operations for the ReadableStream. +function AcquireReadableStreamBYOBReader(stream) { + return new ReadableStreamBYOBReader(stream); +} +// ReadableStream API exposed for controllers. +function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { + stream._reader._readIntoRequests.push(readIntoRequest); +} +function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { + const reader = stream._reader; + const readIntoRequest = reader._readIntoRequests.shift(); + if (done) { + readIntoRequest._closeSteps(chunk); + } + else { + readIntoRequest._chunkSteps(chunk); + } +} +function ReadableStreamGetNumReadIntoRequests(stream) { + return stream._reader._readIntoRequests.length; +} +function ReadableStreamHasBYOBReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamBYOBReader(reader)) { + return false; + } + return true; +} +/** + * A BYOB reader vended by a {@link ReadableStream}. + * + * @public + */ +class ReadableStreamBYOBReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + if (!IsReadableByteStreamController(stream._readableStreamController)) { + throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' + + 'source'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readIntoRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + read(view, rawOptions = {}) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('read')); + } + if (!ArrayBuffer.isView(view)) { + return promiseRejectedWith(new TypeError('view must be an array buffer view')); + } + if (view.byteLength === 0) { + return promiseRejectedWith(new TypeError('view must have non-zero byteLength')); + } + if (view.buffer.byteLength === 0) { + return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`)); + } + if (IsDetachedBuffer(view.buffer)) { + return promiseRejectedWith(new TypeError('view\'s buffer has been detached')); + } + let options; + try { + options = convertByobReadOptions(rawOptions, 'options'); + } + catch (e) { + return promiseRejectedWith(e); + } + const min = options.min; + if (min === 0) { + return promiseRejectedWith(new TypeError('options.min must be greater than 0')); + } + if (!isDataView(view)) { + if (min > view.length) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s length')); + } + } + else if (min > view.byteLength) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s byteLength')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readIntoRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: chunk => resolvePromise({ value: chunk, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamBYOBReader(this)) { + throw byobReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamBYOBReaderRelease(this); + } +} +Object.defineProperties(ReadableStreamBYOBReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } +}); +setFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel'); +setFunctionName(ReadableStreamBYOBReader.prototype.read, 'read'); +setFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, { + value: 'ReadableStreamBYOBReader', + configurable: true + }); +} +// Abstract operations for the readers. +function IsReadableStreamBYOBReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) { + return false; + } + return x instanceof ReadableStreamBYOBReader; +} +function ReadableStreamBYOBReaderRead(reader, view, min, readIntoRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'errored') { + readIntoRequest._errorSteps(stream._storedError); + } + else { + ReadableByteStreamControllerPullInto(stream._readableStreamController, view, min, readIntoRequest); + } +} +function ReadableStreamBYOBReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + const e = new TypeError('Reader was released'); + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); +} +function ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e) { + const readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._errorSteps(e); + }); +} +// Helper functions for the ReadableStreamBYOBReader. +function byobReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`); +} + +function ExtractHighWaterMark(strategy, defaultHWM) { + const { highWaterMark } = strategy; + if (highWaterMark === undefined) { + return defaultHWM; + } + if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { + throw new RangeError('Invalid highWaterMark'); + } + return highWaterMark; +} +function ExtractSizeAlgorithm(strategy) { + const { size } = strategy; + if (!size) { + return () => 1; + } + return size; +} + +function convertQueuingStrategy(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + const size = init === null || init === void 0 ? void 0 : init.size; + return { + highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark), + size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`) + }; +} +function convertQueuingStrategySize(fn, context) { + assertFunction(fn, context); + return chunk => convertUnrestrictedDouble(fn(chunk)); +} + +function convertUnderlyingSink(original, context) { + assertDictionary(original, context); + const abort = original === null || original === void 0 ? void 0 : original.abort; + const close = original === null || original === void 0 ? void 0 : original.close; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + const write = original === null || original === void 0 ? void 0 : original.write; + return { + abort: abort === undefined ? + undefined : + convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`), + close: close === undefined ? + undefined : + convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`), + start: start === undefined ? + undefined : + convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`), + write: write === undefined ? + undefined : + convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`), + type + }; +} +function convertUnderlyingSinkAbortCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); +} +function convertUnderlyingSinkCloseCallback(fn, original, context) { + assertFunction(fn, context); + return () => promiseCall(fn, original, []); +} +function convertUnderlyingSinkStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); +} +function convertUnderlyingSinkWriteCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); +} + +function assertWritableStream(x, context) { + if (!IsWritableStream(x)) { + throw new TypeError(`${context} is not a WritableStream.`); + } +} + +function isAbortSignal(value) { + if (typeof value !== 'object' || value === null) { + return false; + } + try { + return typeof value.aborted === 'boolean'; + } + catch (_a) { + // AbortSignal.prototype.aborted throws if its brand check fails + return false; + } +} +const supportsAbortController = typeof AbortController === 'function'; +/** + * Construct a new AbortController, if supported by the platform. + * + * @internal + */ +function createAbortController() { + if (supportsAbortController) { + return new AbortController(); + } + return undefined; +} + +/** + * A writable stream represents a destination for data, into which you can write. + * + * @public + */ +class WritableStream { + constructor(rawUnderlyingSink = {}, rawStrategy = {}) { + if (rawUnderlyingSink === undefined) { + rawUnderlyingSink = null; + } + else { + assertObject(rawUnderlyingSink, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter'); + InitializeWritableStream(this); + const type = underlyingSink.type; + if (type !== undefined) { + throw new RangeError('Invalid type is specified'); + } + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); + } + /** + * Returns whether or not the writable stream is locked to a writer. + */ + get locked() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('locked'); + } + return IsWritableStreamLocked(this); + } + /** + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort + * mechanism of the underlying sink. + * + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel + * the stream) if the stream is currently locked. + */ + abort(reason = undefined) { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('abort')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer')); + } + return WritableStreamAbort(this, reason); + } + /** + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its + * close behavior. During this time any further attempts to write will fail (without erroring the stream). + * + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + */ + close() { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('close')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer')); + } + if (WritableStreamCloseQueuedOrInFlight(this)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamClose(this); + } + /** + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream + * is locked, no other writer can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at + * the same time, which would cause the resulting written data to be unpredictable and probably useless. + */ + getWriter() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('getWriter'); + } + return AcquireWritableStreamDefaultWriter(this); + } +} +Object.defineProperties(WritableStream.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + getWriter: { enumerable: true }, + locked: { enumerable: true } +}); +setFunctionName(WritableStream.prototype.abort, 'abort'); +setFunctionName(WritableStream.prototype.close, 'close'); +setFunctionName(WritableStream.prototype.getWriter, 'getWriter'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, { + value: 'WritableStream', + configurable: true + }); +} +// Abstract operations for the WritableStream. +function AcquireWritableStreamDefaultWriter(stream) { + return new WritableStreamDefaultWriter(stream); +} +// Throws if and only if startAlgorithm throws. +function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(WritableStream.prototype); + InitializeWritableStream(stream); + const controller = Object.create(WritableStreamDefaultController.prototype); + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + return stream; +} +function InitializeWritableStream(stream) { + stream._state = 'writable'; + // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is + // 'erroring' or 'errored'. May be set to an undefined value. + stream._storedError = undefined; + stream._writer = undefined; + // Initialize to undefined first because the constructor of the controller checks this + // variable to validate the caller. + stream._writableStreamController = undefined; + // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data + // producer without waiting for the queued writes to finish. + stream._writeRequests = new SimpleQueue(); + // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents + // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here. + stream._inFlightWriteRequest = undefined; + // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer + // has been detached. + stream._closeRequest = undefined; + // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it + // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here. + stream._inFlightCloseRequest = undefined; + // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached. + stream._pendingAbortRequest = undefined; + // The backpressure signal set by the controller. + stream._backpressure = false; +} +function IsWritableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) { + return false; + } + return x instanceof WritableStream; +} +function IsWritableStreamLocked(stream) { + if (stream._writer === undefined) { + return false; + } + return true; +} +function WritableStreamAbort(stream, reason) { + var _a; + if (stream._state === 'closed' || stream._state === 'errored') { + return promiseResolvedWith(undefined); + } + stream._writableStreamController._abortReason = reason; + (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort(reason); + // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring', + // but it doesn't know that signaling abort runs author code that might have changed the state. + // Widen the type again by casting to WritableStreamState. + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseResolvedWith(undefined); + } + if (stream._pendingAbortRequest !== undefined) { + return stream._pendingAbortRequest._promise; + } + let wasAlreadyErroring = false; + if (state === 'erroring') { + wasAlreadyErroring = true; + // reason will not be used, so don't keep a reference to it. + reason = undefined; + } + const promise = newPromise((resolve, reject) => { + stream._pendingAbortRequest = { + _promise: undefined, + _resolve: resolve, + _reject: reject, + _reason: reason, + _wasAlreadyErroring: wasAlreadyErroring + }; + }); + stream._pendingAbortRequest._promise = promise; + if (!wasAlreadyErroring) { + WritableStreamStartErroring(stream, reason); + } + return promise; +} +function WritableStreamClose(stream) { + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`)); + } + const promise = newPromise((resolve, reject) => { + const closeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._closeRequest = closeRequest; + }); + const writer = stream._writer; + if (writer !== undefined && stream._backpressure && state === 'writable') { + defaultWriterReadyPromiseResolve(writer); + } + WritableStreamDefaultControllerClose(stream._writableStreamController); + return promise; +} +// WritableStream API exposed for controllers. +function WritableStreamAddWriteRequest(stream) { + const promise = newPromise((resolve, reject) => { + const writeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._writeRequests.push(writeRequest); + }); + return promise; +} +function WritableStreamDealWithRejection(stream, error) { + const state = stream._state; + if (state === 'writable') { + WritableStreamStartErroring(stream, error); + return; + } + WritableStreamFinishErroring(stream); +} +function WritableStreamStartErroring(stream, reason) { + const controller = stream._writableStreamController; + stream._state = 'erroring'; + stream._storedError = reason; + const writer = stream._writer; + if (writer !== undefined) { + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); + } + if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { + WritableStreamFinishErroring(stream); + } +} +function WritableStreamFinishErroring(stream) { + stream._state = 'errored'; + stream._writableStreamController[ErrorSteps](); + const storedError = stream._storedError; + stream._writeRequests.forEach(writeRequest => { + writeRequest._reject(storedError); + }); + stream._writeRequests = new SimpleQueue(); + if (stream._pendingAbortRequest === undefined) { + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const abortRequest = stream._pendingAbortRequest; + stream._pendingAbortRequest = undefined; + if (abortRequest._wasAlreadyErroring) { + abortRequest._reject(storedError); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const promise = stream._writableStreamController[AbortSteps](abortRequest._reason); + uponPromise(promise, () => { + abortRequest._resolve(); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }, (reason) => { + abortRequest._reject(reason); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }); +} +function WritableStreamFinishInFlightWrite(stream) { + stream._inFlightWriteRequest._resolve(undefined); + stream._inFlightWriteRequest = undefined; +} +function WritableStreamFinishInFlightWriteWithError(stream, error) { + stream._inFlightWriteRequest._reject(error); + stream._inFlightWriteRequest = undefined; + WritableStreamDealWithRejection(stream, error); +} +function WritableStreamFinishInFlightClose(stream) { + stream._inFlightCloseRequest._resolve(undefined); + stream._inFlightCloseRequest = undefined; + const state = stream._state; + if (state === 'erroring') { + // The error was too late to do anything, so it is ignored. + stream._storedError = undefined; + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._resolve(); + stream._pendingAbortRequest = undefined; + } + } + stream._state = 'closed'; + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseResolve(writer); + } +} +function WritableStreamFinishInFlightCloseWithError(stream, error) { + stream._inFlightCloseRequest._reject(error); + stream._inFlightCloseRequest = undefined; + // Never execute sink abort() after sink close(). + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._reject(error); + stream._pendingAbortRequest = undefined; + } + WritableStreamDealWithRejection(stream, error); +} +// TODO(ricea): Fix alphabetical order. +function WritableStreamCloseQueuedOrInFlight(stream) { + if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; +} +function WritableStreamHasOperationMarkedInFlight(stream) { + if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; +} +function WritableStreamMarkCloseRequestInFlight(stream) { + stream._inFlightCloseRequest = stream._closeRequest; + stream._closeRequest = undefined; +} +function WritableStreamMarkFirstWriteRequestInFlight(stream) { + stream._inFlightWriteRequest = stream._writeRequests.shift(); +} +function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { + if (stream._closeRequest !== undefined) { + stream._closeRequest._reject(stream._storedError); + stream._closeRequest = undefined; + } + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseReject(writer, stream._storedError); + } +} +function WritableStreamUpdateBackpressure(stream, backpressure) { + const writer = stream._writer; + if (writer !== undefined && backpressure !== stream._backpressure) { + if (backpressure) { + defaultWriterReadyPromiseReset(writer); + } + else { + defaultWriterReadyPromiseResolve(writer); + } + } + stream._backpressure = backpressure; +} +/** + * A default writer vended by a {@link WritableStream}. + * + * @public + */ +class WritableStreamDefaultWriter { + constructor(stream) { + assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter'); + assertWritableStream(stream, 'First parameter'); + if (IsWritableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive writing by another writer'); + } + this._ownerWritableStream = stream; + stream._writer = this; + const state = stream._state; + if (state === 'writable') { + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { + defaultWriterReadyPromiseInitialize(this); + } + else { + defaultWriterReadyPromiseInitializeAsResolved(this); + } + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'erroring') { + defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'closed') { + defaultWriterReadyPromiseInitializeAsResolved(this); + defaultWriterClosedPromiseInitializeAsResolved(this); + } + else { + const storedError = stream._storedError; + defaultWriterReadyPromiseInitializeAsRejected(this, storedError); + defaultWriterClosedPromiseInitializeAsRejected(this, storedError); + } + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the writer’s lock is released before the stream finishes closing. + */ + get closed() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. + * A producer can use this information to determine the right amount of data to write. + * + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when + * the writer’s lock is released. + */ + get desiredSize() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('desiredSize'); + } + if (this._ownerWritableStream === undefined) { + throw defaultWriterLockException('desiredSize'); + } + return WritableStreamDefaultWriterGetDesiredSize(this); + } + /** + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips + * back to zero or below, the getter will return a new promise that stays pending until the next transition. + * + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become + * rejected. + */ + get ready() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('ready')); + } + return this._readyPromise; + } + /** + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + */ + abort(reason = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('abort')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('abort')); + } + return WritableStreamDefaultWriterAbort(this, reason); + } + /** + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + */ + close() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('close')); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return promiseRejectedWith(defaultWriterLockException('close')); + } + if (WritableStreamCloseQueuedOrInFlight(stream)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamDefaultWriterClose(this); + } + /** + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from + * now on; otherwise, the writer will appear closed. + * + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents + * other producers from writing in an interleaved manner. + */ + releaseLock() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('releaseLock'); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return; + } + WritableStreamDefaultWriterRelease(this); + } + write(chunk = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('write')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + return WritableStreamDefaultWriterWrite(this, chunk); + } +} +Object.defineProperties(WritableStreamDefaultWriter.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + releaseLock: { enumerable: true }, + write: { enumerable: true }, + closed: { enumerable: true }, + desiredSize: { enumerable: true }, + ready: { enumerable: true } +}); +setFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort'); +setFunctionName(WritableStreamDefaultWriter.prototype.close, 'close'); +setFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock'); +setFunctionName(WritableStreamDefaultWriter.prototype.write, 'write'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, { + value: 'WritableStreamDefaultWriter', + configurable: true + }); +} +// Abstract operations for the WritableStreamDefaultWriter. +function IsWritableStreamDefaultWriter(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultWriter; +} +// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check. +function WritableStreamDefaultWriterAbort(writer, reason) { + const stream = writer._ownerWritableStream; + return WritableStreamAbort(stream, reason); +} +function WritableStreamDefaultWriterClose(writer) { + const stream = writer._ownerWritableStream; + return WritableStreamClose(stream); +} +function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseResolvedWith(undefined); + } + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + return WritableStreamDefaultWriterClose(writer); +} +function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { + if (writer._closedPromiseState === 'pending') { + defaultWriterClosedPromiseReject(writer, error); + } + else { + defaultWriterClosedPromiseResetToRejected(writer, error); + } +} +function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { + if (writer._readyPromiseState === 'pending') { + defaultWriterReadyPromiseReject(writer, error); + } + else { + defaultWriterReadyPromiseResetToRejected(writer, error); + } +} +function WritableStreamDefaultWriterGetDesiredSize(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (state === 'errored' || state === 'erroring') { + return null; + } + if (state === 'closed') { + return 0; + } + return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); +} +function WritableStreamDefaultWriterRelease(writer) { + const stream = writer._ownerWritableStream; + const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`); + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); + // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not + // rejected until afterwards. This means that simply testing state will not work. + WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); + stream._writer = undefined; + writer._ownerWritableStream = undefined; +} +function WritableStreamDefaultWriterWrite(writer, chunk) { + const stream = writer._ownerWritableStream; + const controller = stream._writableStreamController; + const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); + if (stream !== writer._ownerWritableStream) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + const state = stream._state; + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to')); + } + if (state === 'erroring') { + return promiseRejectedWith(stream._storedError); + } + const promise = WritableStreamAddWriteRequest(stream); + WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); + return promise; +} +const closeSentinel = {}; +/** + * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. + * + * @public + */ +class WritableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. + * + * @deprecated + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. + */ + get abortReason() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('abortReason'); + } + return this._abortReason; + } + /** + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. + */ + get signal() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('signal'); + } + if (this._abortController === undefined) { + // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`. + // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill, + // so instead we only implement support for `signal` if we find a global `AbortController` constructor. + throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported'); + } + return this._abortController.signal; + } + /** + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. + * + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the + * normal lifecycle of interactions with the underlying sink. + */ + error(e = undefined) { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('error'); + } + const state = this._controlledWritableStream._state; + if (state !== 'writable') { + // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so + // just treat it as a no-op. + return; + } + WritableStreamDefaultControllerError(this, e); + } + /** @internal */ + [AbortSteps](reason) { + const result = this._abortAlgorithm(reason); + WritableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [ErrorSteps]() { + ResetQueue(this); + } +} +Object.defineProperties(WritableStreamDefaultController.prototype, { + abortReason: { enumerable: true }, + signal: { enumerable: true }, + error: { enumerable: true } +}); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, { + value: 'WritableStreamDefaultController', + configurable: true + }); +} +// Abstract operations implementing interface required by the WritableStream. +function IsWritableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultController; +} +function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledWritableStream = stream; + stream._writableStreamController = controller; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._abortReason = undefined; + controller._abortController = createAbortController(); + controller._started = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._writeAlgorithm = writeAlgorithm; + controller._closeAlgorithm = closeAlgorithm; + controller._abortAlgorithm = abortAlgorithm; + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + const startResult = startAlgorithm(); + const startPromise = promiseResolvedWith(startResult); + uponPromise(startPromise, () => { + controller._started = true; + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, r => { + controller._started = true; + WritableStreamDealWithRejection(stream, r); + return null; + }); +} +function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { + const controller = Object.create(WritableStreamDefaultController.prototype); + let startAlgorithm; + let writeAlgorithm; + let closeAlgorithm; + let abortAlgorithm; + if (underlyingSink.start !== undefined) { + startAlgorithm = () => underlyingSink.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingSink.write !== undefined) { + writeAlgorithm = chunk => underlyingSink.write(chunk, controller); + } + else { + writeAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSink.close !== undefined) { + closeAlgorithm = () => underlyingSink.close(); + } + else { + closeAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSink.abort !== undefined) { + abortAlgorithm = reason => underlyingSink.abort(reason); + } + else { + abortAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); +} +// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls. +function WritableStreamDefaultControllerClearAlgorithms(controller) { + controller._writeAlgorithm = undefined; + controller._closeAlgorithm = undefined; + controller._abortAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; +} +function WritableStreamDefaultControllerClose(controller) { + EnqueueValueWithSize(controller, closeSentinel, 0); + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); +} +function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { + try { + return controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); + return 1; + } +} +function WritableStreamDefaultControllerGetDesiredSize(controller) { + return controller._strategyHWM - controller._queueTotalSize; +} +function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); + return; + } + const stream = controller._controlledWritableStream; + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); +} +// Abstract operations for the WritableStreamDefaultController. +function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { + const stream = controller._controlledWritableStream; + if (!controller._started) { + return; + } + if (stream._inFlightWriteRequest !== undefined) { + return; + } + const state = stream._state; + if (state === 'erroring') { + WritableStreamFinishErroring(stream); + return; + } + if (controller._queue.length === 0) { + return; + } + const value = PeekQueueValue(controller); + if (value === closeSentinel) { + WritableStreamDefaultControllerProcessClose(controller); + } + else { + WritableStreamDefaultControllerProcessWrite(controller, value); + } +} +function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { + if (controller._controlledWritableStream._state === 'writable') { + WritableStreamDefaultControllerError(controller, error); + } +} +function WritableStreamDefaultControllerProcessClose(controller) { + const stream = controller._controlledWritableStream; + WritableStreamMarkCloseRequestInFlight(stream); + DequeueValue(controller); + const sinkClosePromise = controller._closeAlgorithm(); + WritableStreamDefaultControllerClearAlgorithms(controller); + uponPromise(sinkClosePromise, () => { + WritableStreamFinishInFlightClose(stream); + return null; + }, reason => { + WritableStreamFinishInFlightCloseWithError(stream, reason); + return null; + }); +} +function WritableStreamDefaultControllerProcessWrite(controller, chunk) { + const stream = controller._controlledWritableStream; + WritableStreamMarkFirstWriteRequestInFlight(stream); + const sinkWritePromise = controller._writeAlgorithm(chunk); + uponPromise(sinkWritePromise, () => { + WritableStreamFinishInFlightWrite(stream); + const state = stream._state; + DequeueValue(controller); + if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, reason => { + if (stream._state === 'writable') { + WritableStreamDefaultControllerClearAlgorithms(controller); + } + WritableStreamFinishInFlightWriteWithError(stream, reason); + return null; + }); +} +function WritableStreamDefaultControllerGetBackpressure(controller) { + const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); + return desiredSize <= 0; +} +// A client of WritableStreamDefaultController may use these functions directly to bypass state check. +function WritableStreamDefaultControllerError(controller, error) { + const stream = controller._controlledWritableStream; + WritableStreamDefaultControllerClearAlgorithms(controller); + WritableStreamStartErroring(stream, error); +} +// Helper functions for the WritableStream. +function streamBrandCheckException$2(name) { + return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`); +} +// Helper functions for the WritableStreamDefaultController. +function defaultControllerBrandCheckException$2(name) { + return new TypeError(`WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`); +} +// Helper functions for the WritableStreamDefaultWriter. +function defaultWriterBrandCheckException(name) { + return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`); +} +function defaultWriterLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released writer'); +} +function defaultWriterClosedPromiseInitialize(writer) { + writer._closedPromise = newPromise((resolve, reject) => { + writer._closedPromise_resolve = resolve; + writer._closedPromise_reject = reject; + writer._closedPromiseState = 'pending'; + }); +} +function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseReject(writer, reason); +} +function defaultWriterClosedPromiseInitializeAsResolved(writer) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseResolve(writer); +} +function defaultWriterClosedPromiseReject(writer, reason) { + if (writer._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._closedPromise); + writer._closedPromise_reject(reason); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'rejected'; +} +function defaultWriterClosedPromiseResetToRejected(writer, reason) { + defaultWriterClosedPromiseInitializeAsRejected(writer, reason); +} +function defaultWriterClosedPromiseResolve(writer) { + if (writer._closedPromise_resolve === undefined) { + return; + } + writer._closedPromise_resolve(undefined); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'resolved'; +} +function defaultWriterReadyPromiseInitialize(writer) { + writer._readyPromise = newPromise((resolve, reject) => { + writer._readyPromise_resolve = resolve; + writer._readyPromise_reject = reject; + }); + writer._readyPromiseState = 'pending'; +} +function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseReject(writer, reason); +} +function defaultWriterReadyPromiseInitializeAsResolved(writer) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseResolve(writer); +} +function defaultWriterReadyPromiseReject(writer, reason) { + if (writer._readyPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._readyPromise); + writer._readyPromise_reject(reason); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'rejected'; +} +function defaultWriterReadyPromiseReset(writer) { + defaultWriterReadyPromiseInitialize(writer); +} +function defaultWriterReadyPromiseResetToRejected(writer, reason) { + defaultWriterReadyPromiseInitializeAsRejected(writer, reason); +} +function defaultWriterReadyPromiseResolve(writer) { + if (writer._readyPromise_resolve === undefined) { + return; + } + writer._readyPromise_resolve(undefined); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'fulfilled'; +} + +/// +function getGlobals() { + if (typeof globalThis !== 'undefined') { + return globalThis; + } + else if (typeof self !== 'undefined') { + return self; + } + else if (typeof global !== 'undefined') { + return global; + } + return undefined; +} +const globals = getGlobals(); + +/// +function isDOMExceptionConstructor(ctor) { + if (!(typeof ctor === 'function' || typeof ctor === 'object')) { + return false; + } + if (ctor.name !== 'DOMException') { + return false; + } + try { + new ctor(); + return true; + } + catch (_a) { + return false; + } +} +/** + * Support: + * - Web browsers + * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87) + */ +function getFromGlobal() { + const ctor = globals === null || globals === void 0 ? void 0 : globals.DOMException; + return isDOMExceptionConstructor(ctor) ? ctor : undefined; +} +/** + * Support: + * - All platforms + */ +function createPolyfill() { + // eslint-disable-next-line @typescript-eslint/no-shadow + const ctor = function DOMException(message, name) { + this.message = message || ''; + this.name = name || 'Error'; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + }; + setFunctionName(ctor, 'DOMException'); + ctor.prototype = Object.create(Error.prototype); + Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true }); + return ctor; +} +// eslint-disable-next-line @typescript-eslint/no-redeclare +const DOMException = getFromGlobal() || createPolyfill(); + +function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { + const reader = AcquireReadableStreamDefaultReader(source); + const writer = AcquireWritableStreamDefaultWriter(dest); + source._disturbed = true; + let shuttingDown = false; + // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown. + let currentWrite = promiseResolvedWith(undefined); + return newPromise((resolve, reject) => { + let abortAlgorithm; + if (signal !== undefined) { + abortAlgorithm = () => { + const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError'); + const actions = []; + if (!preventAbort) { + actions.push(() => { + if (dest._state === 'writable') { + return WritableStreamAbort(dest, error); + } + return promiseResolvedWith(undefined); + }); + } + if (!preventCancel) { + actions.push(() => { + if (source._state === 'readable') { + return ReadableStreamCancel(source, error); + } + return promiseResolvedWith(undefined); + }); + } + shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error); + }; + if (signal.aborted) { + abortAlgorithm(); + return; + } + signal.addEventListener('abort', abortAlgorithm); + } + // Using reader and writer, read all chunks from this and write them to dest + // - Backpressure must be enforced + // - Shutdown must stop all activity + function pipeLoop() { + return newPromise((resolveLoop, rejectLoop) => { + function next(done) { + if (done) { + resolveLoop(); + } + else { + // Use `PerformPromiseThen` instead of `uponPromise` to avoid + // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers + PerformPromiseThen(pipeStep(), next, rejectLoop); + } + } + next(false); + }); + } + function pipeStep() { + if (shuttingDown) { + return promiseResolvedWith(true); + } + return PerformPromiseThen(writer._readyPromise, () => { + return newPromise((resolveRead, rejectRead) => { + ReadableStreamDefaultReaderRead(reader, { + _chunkSteps: chunk => { + currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop); + resolveRead(false); + }, + _closeSteps: () => resolveRead(true), + _errorSteps: rejectRead + }); + }); + }); + } + // Errors must be propagated forward + isOrBecomesErrored(source, reader._closedPromise, storedError => { + if (!preventAbort) { + shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Errors must be propagated backward + isOrBecomesErrored(dest, writer._closedPromise, storedError => { + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Closing must be propagated forward + isOrBecomesClosed(source, reader._closedPromise, () => { + if (!preventClose) { + shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer)); + } + else { + shutdown(); + } + return null; + }); + // Closing must be propagated backward + if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') { + const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it'); + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed); + } + else { + shutdown(true, destClosed); + } + } + setPromiseIsHandledToTrue(pipeLoop()); + function waitForWritesToFinish() { + // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait + // for that too. + const oldCurrentWrite = currentWrite; + return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined); + } + function isOrBecomesErrored(stream, promise, action) { + if (stream._state === 'errored') { + action(stream._storedError); + } + else { + uponRejection(promise, action); + } + } + function isOrBecomesClosed(stream, promise, action) { + if (stream._state === 'closed') { + action(); + } + else { + uponFulfillment(promise, action); + } + } + function shutdownWithAction(action, originalIsError, originalError) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), doTheRest); + } + else { + doTheRest(); + } + function doTheRest() { + uponPromise(action(), () => finalize(originalIsError, originalError), newError => finalize(true, newError)); + return null; + } + } + function shutdown(isError, error) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error)); + } + else { + finalize(isError, error); + } + } + function finalize(isError, error) { + WritableStreamDefaultWriterRelease(writer); + ReadableStreamReaderGenericRelease(reader); + if (signal !== undefined) { + signal.removeEventListener('abort', abortAlgorithm); + } + if (isError) { + reject(error); + } + else { + resolve(undefined); + } + return null; + } + }); +} + +/** + * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. + * + * @public + */ +class ReadableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('desiredSize'); + } + return ReadableStreamDefaultControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('close'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits close'); + } + ReadableStreamDefaultControllerClose(this); + } + enqueue(chunk = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('enqueue'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits enqueue'); + } + return ReadableStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('error'); + } + ReadableStreamDefaultControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableStream; + if (this._queue.length > 0) { + const chunk = DequeueValue(this); + if (this._closeRequested && this._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(this); + ReadableStreamClose(stream); + } + else { + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + readRequest._chunkSteps(chunk); + } + else { + ReadableStreamAddReadRequest(stream, readRequest); + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + } + /** @internal */ + [ReleaseSteps]() { + // Do nothing. + } +} +Object.defineProperties(ReadableStreamDefaultController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + desiredSize: { enumerable: true } +}); +setFunctionName(ReadableStreamDefaultController.prototype.close, 'close'); +setFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue'); +setFunctionName(ReadableStreamDefaultController.prototype.error, 'error'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, { + value: 'ReadableStreamDefaultController', + configurable: true + }); +} +// Abstract operations for the ReadableStreamDefaultController. +function IsReadableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) { + return false; + } + return x instanceof ReadableStreamDefaultController; +} +function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + return null; + }, e => { + ReadableStreamDefaultControllerError(controller, e); + return null; + }); +} +function ReadableStreamDefaultControllerShouldCallPull(controller) { + const stream = controller._controlledReadableStream; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return false; + } + if (!controller._started) { + return false; + } + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; +} +function ReadableStreamDefaultControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; +} +// A client of ReadableStreamDefaultController may use these functions directly to bypass state check. +function ReadableStreamDefaultControllerClose(controller) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + controller._closeRequested = true; + if (controller._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } +} +function ReadableStreamDefaultControllerEnqueue(controller, chunk) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + ReadableStreamFulfillReadRequest(stream, chunk, false); + } + else { + let chunkSize; + try { + chunkSize = controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + ReadableStreamDefaultControllerError(controller, chunkSizeE); + throw chunkSizeE; + } + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + ReadableStreamDefaultControllerError(controller, enqueueE); + throw enqueueE; + } + } + ReadableStreamDefaultControllerCallPullIfNeeded(controller); +} +function ReadableStreamDefaultControllerError(controller, e) { + const stream = controller._controlledReadableStream; + if (stream._state !== 'readable') { + return; + } + ResetQueue(controller); + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); +} +function ReadableStreamDefaultControllerGetDesiredSize(controller) { + const state = controller._controlledReadableStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; +} +// This is used in the implementation of TransformStream. +function ReadableStreamDefaultControllerHasBackpressure(controller) { + if (ReadableStreamDefaultControllerShouldCallPull(controller)) { + return false; + } + return true; +} +function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { + const state = controller._controlledReadableStream._state; + if (!controller._closeRequested && state === 'readable') { + return true; + } + return false; +} +function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledReadableStream = stream; + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._started = false; + controller._closeRequested = false; + controller._pullAgain = false; + controller._pulling = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + return null; + }, r => { + ReadableStreamDefaultControllerError(controller, r); + return null; + }); +} +function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { + const controller = Object.create(ReadableStreamDefaultController.prototype); + let startAlgorithm; + let pullAlgorithm; + let cancelAlgorithm; + if (underlyingSource.start !== undefined) { + startAlgorithm = () => underlyingSource.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingSource.pull !== undefined) { + pullAlgorithm = () => underlyingSource.pull(controller); + } + else { + pullAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingSource.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); +} +// Helper functions for the ReadableStreamDefaultController. +function defaultControllerBrandCheckException$1(name) { + return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`); +} + +function ReadableStreamTee(stream, cloneForBranch2) { + if (IsReadableByteStreamController(stream._readableStreamController)) { + return ReadableByteStreamTee(stream); + } + return ReadableStreamDefaultTee(stream); +} +function ReadableStreamDefaultTee(stream, cloneForBranch2) { + const reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgain = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function pullAlgorithm() { + if (reading) { + readAgain = true; + return promiseResolvedWith(undefined); + } + reading = true; + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgain = false; + const chunk1 = chunk; + const chunk2 = chunk; + // There is no way to access the cloning code right now in the reference implementation. + // If we add one then we'll need an implementation for serializable objects. + // if (!canceled2 && cloneForBranch2) { + // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2)); + // } + if (!canceled1) { + ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgain) { + pullAlgorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableStreamDefaultControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableStreamDefaultControllerClose(branch2._readableStreamController); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + // do nothing + } + branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); + branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); + uponRejection(reader._closedPromise, (r) => { + ReadableStreamDefaultControllerError(branch1._readableStreamController, r); + ReadableStreamDefaultControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + return [branch1, branch2]; +} +function ReadableByteStreamTee(stream) { + let reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgainForBranch1 = false; + let readAgainForBranch2 = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function forwardReaderError(thisReader) { + uponRejection(thisReader._closedPromise, r => { + if (thisReader !== reader) { + return null; + } + ReadableByteStreamControllerError(branch1._readableStreamController, r); + ReadableByteStreamControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + } + function pullWithDefaultReader() { + if (IsReadableStreamBYOBReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamDefaultReader(stream); + forwardReaderError(reader); + } + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const chunk1 = chunk; + let chunk2 = chunk; + if (!canceled1 && !canceled2) { + try { + chunk2 = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(branch1._readableStreamController, cloneE); + ReadableByteStreamControllerError(branch2._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + } + if (!canceled1) { + ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableByteStreamControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableByteStreamControllerClose(branch2._readableStreamController); + } + if (branch1._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch1._readableStreamController, 0); + } + if (branch2._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch2._readableStreamController, 0); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + } + function pullWithBYOBReader(view, forBranch2) { + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamBYOBReader(stream); + forwardReaderError(reader); + } + const byobBranch = forBranch2 ? branch2 : branch1; + const otherBranch = forBranch2 ? branch1 : branch2; + const readIntoRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!otherCanceled) { + let clonedChunk; + try { + clonedChunk = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE); + ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk); + } + else if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: chunk => { + reading = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!byobCanceled) { + ReadableByteStreamControllerClose(byobBranch._readableStreamController); + } + if (!otherCanceled) { + ReadableByteStreamControllerClose(otherBranch._readableStreamController); + } + if (chunk !== undefined) { + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0); + } + } + if (!byobCanceled || !otherCanceled) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest); + } + function pull1Algorithm() { + if (reading) { + readAgainForBranch1 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, false); + } + return promiseResolvedWith(undefined); + } + function pull2Algorithm() { + if (reading) { + readAgainForBranch2 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, true); + } + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + return; + } + branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm); + branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm); + forwardReaderError(reader); + return [branch1, branch2]; +} + +function isReadableStreamLike(stream) { + return typeIsObject(stream) && typeof stream.getReader !== 'undefined'; +} + +function ReadableStreamFrom(source) { + if (isReadableStreamLike(source)) { + return ReadableStreamFromDefaultReader(source.getReader()); + } + return ReadableStreamFromIterable(source); +} +function ReadableStreamFromIterable(asyncIterable) { + let stream; + const iteratorRecord = GetIterator(asyncIterable, 'async'); + const startAlgorithm = noop; + function pullAlgorithm() { + let nextResult; + try { + nextResult = IteratorNext(iteratorRecord); + } + catch (e) { + return promiseRejectedWith(e); + } + const nextPromise = promiseResolvedWith(nextResult); + return transformPromiseWith(nextPromise, iterResult => { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object'); + } + const done = IteratorComplete(iterResult); + if (done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + const value = IteratorValue(iterResult); + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + const iterator = iteratorRecord.iterator; + let returnMethod; + try { + returnMethod = GetMethod(iterator, 'return'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (returnMethod === undefined) { + return promiseResolvedWith(undefined); + } + let returnResult; + try { + returnResult = reflectCall(returnMethod, iterator, [reason]); + } + catch (e) { + return promiseRejectedWith(e); + } + const returnPromise = promiseResolvedWith(returnResult); + return transformPromiseWith(returnPromise, iterResult => { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object'); + } + return undefined; + }); + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; +} +function ReadableStreamFromDefaultReader(reader) { + let stream; + const startAlgorithm = noop; + function pullAlgorithm() { + let readPromise; + try { + readPromise = reader.read(); + } + catch (e) { + return promiseRejectedWith(e); + } + return transformPromiseWith(readPromise, readResult => { + if (!typeIsObject(readResult)) { + throw new TypeError('The promise returned by the reader.read() method must fulfill with an object'); + } + if (readResult.done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + const value = readResult.value; + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + try { + return promiseResolvedWith(reader.cancel(reason)); + } + catch (e) { + return promiseRejectedWith(e); + } + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; +} + +function convertUnderlyingDefaultOrByteSource(source, context) { + assertDictionary(source, context); + const original = source; + const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; + const cancel = original === null || original === void 0 ? void 0 : original.cancel; + const pull = original === null || original === void 0 ? void 0 : original.pull; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + return { + autoAllocateChunkSize: autoAllocateChunkSize === undefined ? + undefined : + convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`), + cancel: cancel === undefined ? + undefined : + convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`), + pull: pull === undefined ? + undefined : + convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`), + start: start === undefined ? + undefined : + convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`), + type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`) + }; +} +function convertUnderlyingSourceCancelCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); +} +function convertUnderlyingSourcePullCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); +} +function convertUnderlyingSourceStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); +} +function convertReadableStreamType(type, context) { + type = `${type}`; + if (type !== 'bytes') { + throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`); + } + return type; +} + +function convertIteratorOptions(options, context) { + assertDictionary(options, context); + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + return { preventCancel: Boolean(preventCancel) }; +} + +function convertPipeOptions(options, context) { + assertDictionary(options, context); + const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort; + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + const preventClose = options === null || options === void 0 ? void 0 : options.preventClose; + const signal = options === null || options === void 0 ? void 0 : options.signal; + if (signal !== undefined) { + assertAbortSignal(signal, `${context} has member 'signal' that`); + } + return { + preventAbort: Boolean(preventAbort), + preventCancel: Boolean(preventCancel), + preventClose: Boolean(preventClose), + signal + }; +} +function assertAbortSignal(signal, context) { + if (!isAbortSignal(signal)) { + throw new TypeError(`${context} is not an AbortSignal.`); + } +} + +function convertReadableWritablePair(pair, context) { + assertDictionary(pair, context); + const readable = pair === null || pair === void 0 ? void 0 : pair.readable; + assertRequiredField(readable, 'readable', 'ReadableWritablePair'); + assertReadableStream(readable, `${context} has member 'readable' that`); + const writable = pair === null || pair === void 0 ? void 0 : pair.writable; + assertRequiredField(writable, 'writable', 'ReadableWritablePair'); + assertWritableStream(writable, `${context} has member 'writable' that`); + return { readable, writable }; +} + +/** + * A readable stream represents a source of data, from which you can read. + * + * @public + */ +class ReadableStream { + constructor(rawUnderlyingSource = {}, rawStrategy = {}) { + if (rawUnderlyingSource === undefined) { + rawUnderlyingSource = null; + } + else { + assertObject(rawUnderlyingSource, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter'); + InitializeReadableStream(this); + if (underlyingSource.type === 'bytes') { + if (strategy.size !== undefined) { + throw new RangeError('The strategy for a byte stream cannot have a size function'); + } + const highWaterMark = ExtractHighWaterMark(strategy, 0); + SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); + } + else { + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); + } + } + /** + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. + */ + get locked() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('locked'); + } + return IsReadableStreamLocked(this); + } + /** + * Cancels the stream, signaling a loss of interest in the stream by a consumer. + * + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} + * method, which might or might not use it. + */ + cancel(reason = undefined) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('cancel')); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader')); + } + return ReadableStreamCancel(this, reason); + } + getReader(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('getReader'); + } + const options = convertReaderOptions(rawOptions, 'First parameter'); + if (options.mode === undefined) { + return AcquireReadableStreamDefaultReader(this); + } + return AcquireReadableStreamBYOBReader(this); + } + pipeThrough(rawTransform, rawOptions = {}) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('pipeThrough'); + } + assertRequiredArgument(rawTransform, 1, 'pipeThrough'); + const transform = convertReadableWritablePair(rawTransform, 'First parameter'); + const options = convertPipeOptions(rawOptions, 'Second parameter'); + if (IsReadableStreamLocked(this)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream'); + } + if (IsWritableStreamLocked(transform.writable)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream'); + } + const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + setPromiseIsHandledToTrue(promise); + return transform.readable; + } + pipeTo(destination, rawOptions = {}) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('pipeTo')); + } + if (destination === undefined) { + return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`); + } + if (!IsWritableStream(destination)) { + return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)); + } + let options; + try { + options = convertPipeOptions(rawOptions, 'Second parameter'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')); + } + if (IsWritableStreamLocked(destination)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')); + } + return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + } + /** + * Tees this readable stream, returning a two-element array containing the two resulting branches as + * new {@link ReadableStream} instances. + * + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be + * propagated to the stream's underlying source. + * + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, + * this could allow interference between the two branches. + */ + tee() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('tee'); + } + const branches = ReadableStreamTee(this); + return CreateArrayFromList(branches); + } + values(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('values'); + } + const options = convertIteratorOptions(rawOptions, 'First parameter'); + return AcquireReadableStreamAsyncIterator(this, options.preventCancel); + } + [SymbolAsyncIterator](options) { + // Stub implementation, overridden below + return this.values(options); + } + /** + * Creates a new ReadableStream wrapping the provided iterable or async iterable. + * + * This can be used to adapt various kinds of objects into a readable stream, + * such as an array, an async generator, or a Node.js readable stream. + */ + static from(asyncIterable) { + return ReadableStreamFrom(asyncIterable); + } +} +Object.defineProperties(ReadableStream, { + from: { enumerable: true } +}); +Object.defineProperties(ReadableStream.prototype, { + cancel: { enumerable: true }, + getReader: { enumerable: true }, + pipeThrough: { enumerable: true }, + pipeTo: { enumerable: true }, + tee: { enumerable: true }, + values: { enumerable: true }, + locked: { enumerable: true } +}); +setFunctionName(ReadableStream.from, 'from'); +setFunctionName(ReadableStream.prototype.cancel, 'cancel'); +setFunctionName(ReadableStream.prototype.getReader, 'getReader'); +setFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough'); +setFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo'); +setFunctionName(ReadableStream.prototype.tee, 'tee'); +setFunctionName(ReadableStream.prototype.values, 'values'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, { + value: 'ReadableStream', + configurable: true + }); +} +Object.defineProperty(ReadableStream.prototype, SymbolAsyncIterator, { + value: ReadableStream.prototype.values, + writable: true, + configurable: true +}); +// Abstract operations for the ReadableStream. +// Throws if and only if startAlgorithm throws. +function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableStreamDefaultController.prototype); + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + return stream; +} +// Throws if and only if startAlgorithm throws. +function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableByteStreamController.prototype); + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined); + return stream; +} +function InitializeReadableStream(stream) { + stream._state = 'readable'; + stream._reader = undefined; + stream._storedError = undefined; + stream._disturbed = false; +} +function IsReadableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) { + return false; + } + return x instanceof ReadableStream; +} +function IsReadableStreamLocked(stream) { + if (stream._reader === undefined) { + return false; + } + return true; +} +// ReadableStream API exposed for controllers. +function ReadableStreamCancel(stream, reason) { + stream._disturbed = true; + if (stream._state === 'closed') { + return promiseResolvedWith(undefined); + } + if (stream._state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + ReadableStreamClose(stream); + const reader = stream._reader; + if (reader !== undefined && IsReadableStreamBYOBReader(reader)) { + const readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._closeSteps(undefined); + }); + } + const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); + return transformPromiseWith(sourceCancelPromise, noop); +} +function ReadableStreamClose(stream) { + stream._state = 'closed'; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseResolve(reader); + if (IsReadableStreamDefaultReader(reader)) { + const readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(readRequest => { + readRequest._closeSteps(); + }); + } +} +function ReadableStreamError(stream, e) { + stream._state = 'errored'; + stream._storedError = e; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseReject(reader, e); + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamDefaultReaderErrorReadRequests(reader, e); + } + else { + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); + } +} +// Helper functions for the ReadableStream. +function streamBrandCheckException$1(name) { + return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`); +} + +function convertQueuingStrategyInit(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit'); + return { + highWaterMark: convertUnrestrictedDouble(highWaterMark) + }; +} + +// The size function must not have a prototype property nor be a constructor +const byteLengthSizeFunction = (chunk) => { + return chunk.byteLength; +}; +setFunctionName(byteLengthSizeFunction, 'size'); +/** + * A queuing strategy that counts the number of bytes in each chunk. + * + * @public + */ +class ByteLengthQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('highWaterMark'); + } + return this._byteLengthQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by returning the value of its `byteLength` property. + */ + get size() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('size'); + } + return byteLengthSizeFunction; + } +} +Object.defineProperties(ByteLengthQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } +}); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, { + value: 'ByteLengthQueuingStrategy', + configurable: true + }); +} +// Helper functions for the ByteLengthQueuingStrategy. +function byteLengthBrandCheckException(name) { + return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`); +} +function IsByteLengthQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof ByteLengthQueuingStrategy; +} + +// The size function must not have a prototype property nor be a constructor +const countSizeFunction = () => { + return 1; +}; +setFunctionName(countSizeFunction, 'size'); +/** + * A queuing strategy that counts the number of chunks. + * + * @public + */ +class CountQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'CountQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._countQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('highWaterMark'); + } + return this._countQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by always returning 1. + * This ensures that the total queue size is a count of the number of chunks in the queue. + */ + get size() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('size'); + } + return countSizeFunction; + } +} +Object.defineProperties(CountQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } +}); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, { + value: 'CountQueuingStrategy', + configurable: true + }); +} +// Helper functions for the CountQueuingStrategy. +function countBrandCheckException(name) { + return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`); +} +function IsCountQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof CountQueuingStrategy; +} + +function convertTransformer(original, context) { + assertDictionary(original, context); + const cancel = original === null || original === void 0 ? void 0 : original.cancel; + const flush = original === null || original === void 0 ? void 0 : original.flush; + const readableType = original === null || original === void 0 ? void 0 : original.readableType; + const start = original === null || original === void 0 ? void 0 : original.start; + const transform = original === null || original === void 0 ? void 0 : original.transform; + const writableType = original === null || original === void 0 ? void 0 : original.writableType; + return { + cancel: cancel === undefined ? + undefined : + convertTransformerCancelCallback(cancel, original, `${context} has member 'cancel' that`), + flush: flush === undefined ? + undefined : + convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`), + readableType, + start: start === undefined ? + undefined : + convertTransformerStartCallback(start, original, `${context} has member 'start' that`), + transform: transform === undefined ? + undefined : + convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`), + writableType + }; +} +function convertTransformerFlushCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); +} +function convertTransformerStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); +} +function convertTransformerTransformCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); +} +function convertTransformerCancelCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); +} + +// Class TransformStream +/** + * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, + * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. + * In a manner specific to the transform stream in question, writes to the writable side result in new data being + * made available for reading from the readable side. + * + * @public + */ +class TransformStream { + constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) { + if (rawTransformer === undefined) { + rawTransformer = null; + } + const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter'); + const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter'); + const transformer = convertTransformer(rawTransformer, 'First parameter'); + if (transformer.readableType !== undefined) { + throw new RangeError('Invalid readableType specified'); + } + if (transformer.writableType !== undefined) { + throw new RangeError('Invalid writableType specified'); + } + const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); + const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); + const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); + const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); + let startPromise_resolve; + const startPromise = newPromise(resolve => { + startPromise_resolve = resolve; + }); + InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); + if (transformer.start !== undefined) { + startPromise_resolve(transformer.start(this._transformStreamController)); + } + else { + startPromise_resolve(undefined); + } + } + /** + * The readable side of the transform stream. + */ + get readable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('readable'); + } + return this._readable; + } + /** + * The writable side of the transform stream. + */ + get writable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('writable'); + } + return this._writable; + } +} +Object.defineProperties(TransformStream.prototype, { + readable: { enumerable: true }, + writable: { enumerable: true } +}); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, { + value: 'TransformStream', + configurable: true + }); +} +function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { + function startAlgorithm() { + return startPromise; + } + function writeAlgorithm(chunk) { + return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); + } + function abortAlgorithm(reason) { + return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); + } + function closeAlgorithm() { + return TransformStreamDefaultSinkCloseAlgorithm(stream); + } + stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); + function pullAlgorithm() { + return TransformStreamDefaultSourcePullAlgorithm(stream); + } + function cancelAlgorithm(reason) { + return TransformStreamDefaultSourceCancelAlgorithm(stream, reason); + } + stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure. + stream._backpressure = undefined; + stream._backpressureChangePromise = undefined; + stream._backpressureChangePromise_resolve = undefined; + TransformStreamSetBackpressure(stream, true); + stream._transformStreamController = undefined; +} +function IsTransformStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) { + return false; + } + return x instanceof TransformStream; +} +// This is a no-op if both sides are already errored. +function TransformStreamError(stream, e) { + ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e); + TransformStreamErrorWritableAndUnblockWrite(stream, e); +} +function TransformStreamErrorWritableAndUnblockWrite(stream, e) { + TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); + WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e); + TransformStreamUnblockWrite(stream); +} +function TransformStreamUnblockWrite(stream) { + if (stream._backpressure) { + // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure() + // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time + // _backpressure is set. + TransformStreamSetBackpressure(stream, false); + } +} +function TransformStreamSetBackpressure(stream, backpressure) { + // Passes also when called during construction. + if (stream._backpressureChangePromise !== undefined) { + stream._backpressureChangePromise_resolve(); + } + stream._backpressureChangePromise = newPromise(resolve => { + stream._backpressureChangePromise_resolve = resolve; + }); + stream._backpressure = backpressure; +} +// Class TransformStreamDefaultController +/** + * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. + * + * @public + */ +class TransformStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. + */ + get desiredSize() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('desiredSize'); + } + const readableController = this._controlledTransformStream._readable._readableStreamController; + return ReadableStreamDefaultControllerGetDesiredSize(readableController); + } + enqueue(chunk = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('enqueue'); + } + TransformStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors both the readable side and the writable side of the controlled transform stream, making all future + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. + */ + error(reason = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('error'); + } + TransformStreamDefaultControllerError(this, reason); + } + /** + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the + * transformer only needs to consume a portion of the chunks written to the writable side. + */ + terminate() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('terminate'); + } + TransformStreamDefaultControllerTerminate(this); + } +} +Object.defineProperties(TransformStreamDefaultController.prototype, { + enqueue: { enumerable: true }, + error: { enumerable: true }, + terminate: { enumerable: true }, + desiredSize: { enumerable: true } +}); +setFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue'); +setFunctionName(TransformStreamDefaultController.prototype.error, 'error'); +setFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, { + value: 'TransformStreamDefaultController', + configurable: true + }); +} +// Transform Stream Default Controller Abstract Operations +function IsTransformStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) { + return false; + } + return x instanceof TransformStreamDefaultController; +} +function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm) { + controller._controlledTransformStream = stream; + stream._transformStreamController = controller; + controller._transformAlgorithm = transformAlgorithm; + controller._flushAlgorithm = flushAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._finishPromise = undefined; + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; +} +function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { + const controller = Object.create(TransformStreamDefaultController.prototype); + let transformAlgorithm; + let flushAlgorithm; + let cancelAlgorithm; + if (transformer.transform !== undefined) { + transformAlgorithm = chunk => transformer.transform(chunk, controller); + } + else { + transformAlgorithm = chunk => { + try { + TransformStreamDefaultControllerEnqueue(controller, chunk); + return promiseResolvedWith(undefined); + } + catch (transformResultE) { + return promiseRejectedWith(transformResultE); + } + }; + } + if (transformer.flush !== undefined) { + flushAlgorithm = () => transformer.flush(controller); + } + else { + flushAlgorithm = () => promiseResolvedWith(undefined); + } + if (transformer.cancel !== undefined) { + cancelAlgorithm = reason => transformer.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm); +} +function TransformStreamDefaultControllerClearAlgorithms(controller) { + controller._transformAlgorithm = undefined; + controller._flushAlgorithm = undefined; + controller._cancelAlgorithm = undefined; +} +function TransformStreamDefaultControllerEnqueue(controller, chunk) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { + throw new TypeError('Readable side is not in a state that permits enqueue'); + } + // We throttle transform invocations based on the backpressure of the ReadableStream, but we still + // accept TransformStreamDefaultControllerEnqueue() calls. + try { + ReadableStreamDefaultControllerEnqueue(readableController, chunk); + } + catch (e) { + // This happens when readableStrategy.size() throws. + TransformStreamErrorWritableAndUnblockWrite(stream, e); + throw stream._readable._storedError; + } + const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); + if (backpressure !== stream._backpressure) { + TransformStreamSetBackpressure(stream, true); + } +} +function TransformStreamDefaultControllerError(controller, e) { + TransformStreamError(controller._controlledTransformStream, e); +} +function TransformStreamDefaultControllerPerformTransform(controller, chunk) { + const transformPromise = controller._transformAlgorithm(chunk); + return transformPromiseWith(transformPromise, undefined, r => { + TransformStreamError(controller._controlledTransformStream, r); + throw r; + }); +} +function TransformStreamDefaultControllerTerminate(controller) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + ReadableStreamDefaultControllerClose(readableController); + const error = new TypeError('TransformStream terminated'); + TransformStreamErrorWritableAndUnblockWrite(stream, error); +} +// TransformStreamDefaultSink Algorithms +function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { + const controller = stream._transformStreamController; + if (stream._backpressure) { + const backpressureChangePromise = stream._backpressureChangePromise; + return transformPromiseWith(backpressureChangePromise, () => { + const writable = stream._writable; + const state = writable._state; + if (state === 'erroring') { + throw writable._storedError; + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + }); + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); +} +function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + const readable = stream._readable; + // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally, + // we don't run the _cancelAlgorithm again. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, () => { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerError(readable._readableStreamController, reason); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; +} +function TransformStreamDefaultSinkCloseAlgorithm(stream) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + const readable = stream._readable; + // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally, + // we don't also run the _cancelAlgorithm. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const flushPromise = controller._flushAlgorithm(); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(flushPromise, () => { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerClose(readable._readableStreamController); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; +} +// TransformStreamDefaultSource Algorithms +function TransformStreamDefaultSourcePullAlgorithm(stream) { + // Invariant. Enforced by the promises returned by start() and pull(). + TransformStreamSetBackpressure(stream, false); + // Prevent the next pull() call until there is backpressure. + return stream._backpressureChangePromise; +} +function TransformStreamDefaultSourceCancelAlgorithm(stream, reason) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._writable cannot change after construction, so caching it across a call to user code is safe. + const writable = stream._writable; + // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or + // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the + // _flushAlgorithm. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, () => { + if (writable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, writable._storedError); + } + else { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; +} +// Helper functions for the TransformStreamDefaultController. +function defaultControllerBrandCheckException(name) { + return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`); +} +function defaultControllerFinishPromiseResolve(controller) { + if (controller._finishPromise_resolve === undefined) { + return; + } + controller._finishPromise_resolve(); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; +} +function defaultControllerFinishPromiseReject(controller, reason) { + if (controller._finishPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(controller._finishPromise); + controller._finishPromise_reject(reason); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; +} +// Helper functions for the TransformStream. +function streamBrandCheckException(name) { + return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`); +} + +const exports = { + ReadableStream, + ReadableStreamDefaultController, + ReadableByteStreamController, + ReadableStreamBYOBRequest, + ReadableStreamDefaultReader, + ReadableStreamBYOBReader, + WritableStream, + WritableStreamDefaultController, + WritableStreamDefaultWriter, + ByteLengthQueuingStrategy, + CountQueuingStrategy, + TransformStream, + TransformStreamDefaultController +}; +// Add classes to global scope +if (typeof globals !== 'undefined') { + for (const prop in exports) { + if (Object.prototype.hasOwnProperty.call(exports, prop)) { + Object.defineProperty(globals, prop, { + value: exports[prop], + writable: true, + configurable: true + }); + } + } +} + +export { ByteLengthQueuingStrategy, CountQueuingStrategy, ReadableByteStreamController, ReadableStream, ReadableStreamBYOBReader, ReadableStreamBYOBRequest, ReadableStreamDefaultController, ReadableStreamDefaultReader, TransformStream, TransformStreamDefaultController, WritableStream, WritableStreamDefaultController, WritableStreamDefaultWriter }; +//# sourceMappingURL=polyfill.es2018.mjs.map diff --git a/backend/node_modules/web-streams-polyfill/dist/polyfill.es2018.mjs.map b/backend/node_modules/web-streams-polyfill/dist/polyfill.es2018.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..3d8bc87a611858e05b02dbf151583db370fff205 --- /dev/null +++ b/backend/node_modules/web-streams-polyfill/dist/polyfill.es2018.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"polyfill.es2018.mjs","sources":["../src/utils.ts","../src/lib/helpers/miscellaneous.ts","../src/lib/helpers/webidl.ts","../src/lib/simple-queue.ts","../src/lib/abstract-ops/internal-methods.ts","../src/lib/readable-stream/generic-reader.ts","../src/stub/number-isfinite.ts","../src/stub/math-trunc.ts","../src/lib/validators/basic.ts","../src/lib/validators/readable-stream.ts","../src/lib/readable-stream/default-reader.ts","../src/target/es2018/stub/async-iterator-prototype.ts","../src/lib/readable-stream/async-iterator.ts","../src/stub/number-isnan.ts","../src/lib/abstract-ops/ecmascript.ts","../src/lib/abstract-ops/miscellaneous.ts","../src/lib/abstract-ops/queue-with-sizes.ts","../src/lib/helpers/array-buffer-view.ts","../src/lib/readable-stream/byte-stream-controller.ts","../src/lib/validators/reader-options.ts","../src/lib/readable-stream/byob-reader.ts","../src/lib/abstract-ops/queuing-strategy.ts","../src/lib/validators/queuing-strategy.ts","../src/lib/validators/underlying-sink.ts","../src/lib/validators/writable-stream.ts","../src/lib/abort-signal.ts","../src/lib/writable-stream.ts","../src/globals.ts","../src/stub/dom-exception.ts","../src/lib/readable-stream/pipe.ts","../src/lib/readable-stream/default-controller.ts","../src/lib/readable-stream/tee.ts","../src/lib/readable-stream/readable-stream-like.ts","../src/lib/readable-stream/from.ts","../src/lib/validators/underlying-source.ts","../src/lib/validators/iterator-options.ts","../src/lib/validators/pipe-options.ts","../src/lib/validators/readable-writable-pair.ts","../src/lib/readable-stream.ts","../src/lib/validators/queuing-strategy-init.ts","../src/lib/byte-length-queuing-strategy.ts","../src/lib/count-queuing-strategy.ts","../src/lib/validators/transformer.ts","../src/lib/transform-stream.ts","../src/polyfill.ts"],"sourcesContent":["export function noop(): undefined {\n return undefined;\n}\n","import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n\nexport function setFunctionName(fn: Function, name: string): void {\n try {\n Object.defineProperty(fn, 'name', {\n value: name,\n configurable: true\n });\n } catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n }\n}\n","import { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\n// https://webidl.spec.whatwg.org/#a-new-promise\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-resolved-with\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return newPromise(resolve => resolve(value));\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-rejected-with\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\n// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned\n// from that handler. To prevent this, return null instead of void from all handlers.\n// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => null | PromiseLike,\n onRejected?: (reason: any) => null | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => null | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => null | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nlet _queueMicrotask: (callback: () => void) => void = callback => {\n if (typeof queueMicrotask === 'function') {\n _queueMicrotask = queueMicrotask;\n } else {\n const resolvedPromise = promiseResolvedWith(undefined);\n _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb);\n }\n return _queueMicrotask(callback);\n};\n\nexport { _queueMicrotask as queueMicrotask };\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n","import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n","export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\nexport const ReleaseSteps = Symbol('[[ReleaseSteps]]');\n","import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, type ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\nimport { ReleaseSteps } from '../abstract-ops/internal-methods';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n assert(stream._reader === reader);\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n stream._readableStreamController[ReleaseSteps]();\n\n stream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n","import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n","import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamDefaultReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamDefaultReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\nexport function ReadableStreamDefaultReaderRelease(reader: ReadableStreamDefaultReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n}\n\nexport function ReadableStreamDefaultReaderErrorReadRequests(reader: ReadableStreamDefaultReader, e: any) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n","/// \n\n/* eslint-disable @typescript-eslint/no-empty-function */\nexport const AsyncIteratorPrototype: AsyncIterable =\n Object.getPrototypeOf(Object.getPrototypeOf(async function* (): AsyncIterableIterator {}).prototype);\n","/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadableStreamDefaultReadResult,\n type ReadRequest\n} from './default-reader';\nimport { ReadableStreamReaderGenericCancel, ReadableStreamReaderGenericRelease } from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterableIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ninterface ReadableStreamAsyncIteratorInstance extends ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nObject.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n","import { reflectCall } from 'lib/helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport assert from '../../stub/assert';\n\ndeclare global {\n interface ArrayBuffer {\n readonly detached: boolean;\n\n transfer(): ArrayBuffer;\n }\n\n function structuredClone(value: T, options: { transfer: ArrayBuffer[] }): T;\n}\n\nexport function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\nexport let TransferArrayBuffer = (O: ArrayBuffer): ArrayBuffer => {\n if (typeof O.transfer === 'function') {\n TransferArrayBuffer = buffer => buffer.transfer();\n } else if (typeof structuredClone === 'function') {\n TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] });\n } else {\n // Not implemented correctly\n TransferArrayBuffer = buffer => buffer;\n }\n return TransferArrayBuffer(O);\n};\n\nexport function CanTransferArrayBuffer(O: ArrayBuffer): boolean {\n return !IsDetachedBuffer(O);\n}\n\nexport let IsDetachedBuffer = (O: ArrayBuffer): boolean => {\n if (typeof O.detached === 'boolean') {\n IsDetachedBuffer = buffer => buffer.detached;\n } else {\n // Not implemented correctly\n IsDetachedBuffer = buffer => buffer.byteLength === 0;\n }\n return IsDetachedBuffer(O);\n};\n\nexport function ArrayBufferSlice(buffer: ArrayBuffer, begin: number, end: number): ArrayBuffer {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n\nexport type MethodName = {\n [P in keyof T]: T[P] extends Function | undefined ? P : never;\n}[keyof T];\n\nexport function GetMethod>(receiver: T, prop: K): T[K] | undefined {\n const func = receiver[prop];\n if (func === undefined || func === null) {\n return undefined;\n }\n if (typeof func !== 'function') {\n throw new TypeError(`${String(prop)} is not a function`);\n }\n return func;\n}\n\nexport interface SyncIteratorRecord {\n iterator: Iterator,\n nextMethod: Iterator['next'],\n done: boolean;\n}\n\nexport interface AsyncIteratorRecord {\n iterator: AsyncIterator,\n nextMethod: AsyncIterator['next'],\n done: boolean;\n}\n\nexport type SyncOrAsyncIteratorRecord = SyncIteratorRecord | AsyncIteratorRecord;\n\nexport function CreateAsyncFromSyncIterator(syncIteratorRecord: SyncIteratorRecord): AsyncIteratorRecord {\n // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%,\n // we use yield* inside an async generator function to achieve the same result.\n\n // Wrap the sync iterator inside a sync iterable, so we can use it with yield*.\n const syncIterable = {\n [Symbol.iterator]: () => syncIteratorRecord.iterator\n };\n // Create an async generator function and immediately invoke it.\n const asyncIterator = (async function* () {\n return yield* syncIterable;\n }());\n // Return as an async iterator record.\n const nextMethod = asyncIterator.next;\n return { iterator: asyncIterator, nextMethod, done: false };\n}\n\n// Aligns with core-js/modules/es.symbol.async-iterator.js\nexport const SymbolAsyncIterator: (typeof Symbol)['asyncIterator'] =\n Symbol.asyncIterator ??\n Symbol.for?.('Symbol.asyncIterator') ??\n '@@asyncIterator';\n\nexport type SyncOrAsyncIterable = Iterable | AsyncIterable;\nexport type SyncOrAsyncIteratorMethod = () => (Iterator | AsyncIterator);\n\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint: 'async',\n method?: SyncOrAsyncIteratorMethod\n): AsyncIteratorRecord;\nfunction GetIterator(\n obj: Iterable,\n hint: 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncIteratorRecord;\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint = 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncOrAsyncIteratorRecord {\n assert(hint === 'sync' || hint === 'async');\n if (method === undefined) {\n if (hint === 'async') {\n method = GetMethod(obj as AsyncIterable, SymbolAsyncIterator);\n if (method === undefined) {\n const syncMethod = GetMethod(obj as Iterable, Symbol.iterator);\n const syncIteratorRecord = GetIterator(obj as Iterable, 'sync', syncMethod);\n return CreateAsyncFromSyncIterator(syncIteratorRecord);\n }\n } else {\n method = GetMethod(obj as Iterable, Symbol.iterator);\n }\n }\n if (method === undefined) {\n throw new TypeError('The object is not iterable');\n }\n const iterator = reflectCall(method, obj, []);\n if (!typeIsObject(iterator)) {\n throw new TypeError('The iterator method must return an object');\n }\n const nextMethod = iterator.next;\n return { iterator, nextMethod, done: false } as SyncOrAsyncIteratorRecord;\n}\n\nexport { GetIterator };\n\nexport function IteratorNext(iteratorRecord: AsyncIteratorRecord): Promise> {\n const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []);\n if (!typeIsObject(result)) {\n throw new TypeError('The iterator.next() method must return an object');\n }\n return result;\n}\n\nexport function IteratorComplete(\n iterResult: IteratorResult\n): iterResult is IteratorReturnResult {\n assert(typeIsObject(iterResult));\n return Boolean(iterResult.done);\n}\n\nexport function IteratorValue(iterResult: IteratorYieldResult): T {\n assert(typeIsObject(iterResult));\n return iterResult.value;\n}\n","import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: NonShared): NonShared {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer) as NonShared;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n","export type TypedArray =\n | Int8Array\n | Uint8Array\n | Uint8ClampedArray\n | Int16Array\n | Uint16Array\n | Int32Array\n | Uint32Array\n | Float32Array\n | Float64Array;\n\nexport type NonShared = T & {\n buffer: ArrayBuffer;\n}\n\nexport interface ArrayBufferViewConstructor {\n new(buffer: ArrayBuffer, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n}\n\nexport interface TypedArrayConstructor extends ArrayBufferViewConstructor {\n readonly BYTES_PER_ELEMENT: number;\n}\n\nexport type DataViewConstructor = ArrayBufferViewConstructor;\n\nfunction isDataViewConstructor(ctor: Function): ctor is DataViewConstructor {\n return ctor === DataView;\n}\n\nexport function isDataView(view: ArrayBufferView): view is DataView {\n return isDataViewConstructor(view.constructor);\n}\n\nexport function arrayBufferViewElementSize(ctor: ArrayBufferViewConstructor): number {\n if (isDataViewConstructor(ctor)) {\n return 1;\n }\n return (ctor as unknown as TypedArrayConstructor).BYTES_PER_ELEMENT;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n IsReadableStreamDefaultReader,\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n type ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n type ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n type ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport type { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\nimport {\n type ArrayBufferViewConstructor,\n arrayBufferViewElementSize,\n type NonShared,\n type TypedArrayConstructor\n} from '../helpers/array-buffer-view';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: NonShared | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: NonShared): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond');\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBuffer;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor = NonShared> =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: TypedArrayConstructor;\n readerType: 'default' | 'none';\n}\n\ninterface BYOBPullIntoDescriptor = NonShared> {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob' | 'none';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: NonShared): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest>): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n minimumFill: 1,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n if (this._pendingPullIntos.length > 0) {\n const firstPullInto = this._pendingPullIntos.peek();\n firstPullInto.readerType = 'none';\n\n this._pendingPullIntos = new SimpleQueue();\n this._pendingPullIntos.push(firstPullInto);\n }\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableByteStreamController.prototype.close, 'close');\nsetFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableByteStreamController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor>(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n assert(pullIntoDescriptor.readerType !== 'none');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as NonShared, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor>(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n let clonedChunk;\n try {\n clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength);\n } catch (cloneE) {\n ReadableByteStreamControllerError(controller, cloneE);\n throw cloneE;\n }\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength);\n}\n\nfunction ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.readerType === 'none');\n if (firstDescriptor.bytesFilled > 0) {\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n firstDescriptor.buffer,\n firstDescriptor.byteOffset,\n firstDescriptor.bytesFilled\n );\n }\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize;\n const maxAlignedBytes = maxBytesFilled - remainderBytes;\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n assert(pullIntoDescriptor.readerType !== 'none');\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nfunction ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller: ReadableByteStreamController) {\n const reader = controller._controlledReadableByteStream._reader;\n assert(IsReadableStreamDefaultReader(reader));\n while (reader._readRequests.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n const readRequest = reader._readRequests.shift();\n ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest);\n }\n}\n\nexport function ReadableByteStreamControllerPullInto>(\n controller: ReadableByteStreamController,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n const elementSize = arrayBufferViewElementSize(ctor);\n\n const { byteOffset, byteLength } = view;\n\n const minimumFill = min * elementSize;\n assert(minimumFill >= elementSize && minimumFill <= byteLength);\n assert(minimumFill % elementSize === 0);\n\n let buffer: ArrayBuffer;\n try {\n buffer = TransferArrayBuffer(view.buffer);\n } catch (e) {\n readIntoRequest._errorSteps(e);\n return;\n }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset,\n byteLength,\n bytesFilled: 0,\n minimumFill,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled % firstDescriptor.elementSize === 0);\n\n if (firstDescriptor.readerType === 'none') {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n return;\n }\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) {\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n pullIntoDescriptor.buffer,\n end - remainderSize,\n remainderSize\n );\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(\n controller: ReadableByteStreamController,\n chunk: NonShared\n) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const { buffer, byteOffset, byteLength } = chunk;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n if (firstPendingPullInto.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto);\n }\n }\n\n if (ReadableStreamHasDefaultReader(stream)) {\n ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller);\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView as NonShared, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerFillReadRequestFromQueue(\n controller: ReadableByteStreamController,\n readRequest: ReadRequest>\n) {\n assert(controller._queueTotalSize > 0);\n\n const entry = controller._queue.shift();\n controller._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n readRequest._chunkSteps(view as NonShared);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view as NonShared);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: NonShared) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: NonShared) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n","import { assertDictionary, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n\nexport function convertByobReadOptions(\n options: ReadableStreamBYOBReaderReadOptions | null | undefined,\n context: string\n): ValidatedReadableStreamBYOBReaderReadOptions {\n assertDictionary(options, context);\n const min = options?.min ?? 1;\n return {\n min: convertUnsignedLongLongWithEnforceRange(\n min,\n `${context} has member 'min' that`\n )\n };\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, type ReadableByteStream, type ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from './reader-options';\nimport { convertByobReadOptions } from '../validators/reader-options';\nimport { isDataView, type NonShared, type TypedArray } from '../helpers/array-buffer-view';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream as ReadableStream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest>(\n stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest\n): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest> {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(\n view: T,\n options?: ReadableStreamBYOBReaderReadOptions\n ): Promise>;\n read>(\n view: T,\n rawOptions: ReadableStreamBYOBReaderReadOptions | null | undefined = {}\n ): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n let options: ValidatedReadableStreamBYOBReaderReadOptions;\n try {\n options = convertByobReadOptions(rawOptions, 'options');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const min = options.min;\n if (min === 0) {\n return promiseRejectedWith(new TypeError('options.min must be greater than 0'));\n }\n if (!isDataView(view)) {\n if (min > (view as unknown as TypedArray).length) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s length'));\n }\n } else if (min > view.byteLength) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s byteLength'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamBYOBReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamBYOBReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead>(\n reader: ReadableStreamBYOBReader,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n min,\n readIntoRequest\n );\n }\n}\n\nexport function ReadableStreamBYOBReaderRelease(reader: ReadableStreamBYOBReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n}\n\nexport function ReadableStreamBYOBReaderErrorReadIntoRequests(reader: ReadableStreamBYOBReader, e: any) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n","/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * If aborted, returns the reason for aborting.\n */\n readonly reason?: any;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(reason?: any): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n type QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { type AbortController, type AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(WritableStream.prototype.abort, 'abort');\nsetFunctionName(WritableStream.prototype.close, 'close');\nsetFunctionName(WritableStream.prototype.getWriter, 'getWriter');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight\n};\n\nexport type {\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort(reason);\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nsetFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort');\nsetFunctionName(WritableStreamDefaultWriter.prototype.close, 'close');\nsetFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock');\nsetFunctionName(WritableStreamDefaultWriter.prototype.write, 'write');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n return null;\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let writeAlgorithm: (chunk: W) => Promise;\n let closeAlgorithm: () => Promise;\n let abortAlgorithm: (reason: any) => Promise;\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n } else {\n writeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n } else {\n closeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n } else {\n abortAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n return null;\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n","/// \n\nfunction getGlobals(): typeof globalThis | undefined {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n } else if (typeof self !== 'undefined') {\n return self;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n","/// \nimport { globals } from '../globals';\nimport { setFunctionName } from '../lib/helpers/miscellaneous';\n\ninterface DOMException extends Error {\n name: string;\n message: string;\n}\n\ntype DOMExceptionConstructor = new (message?: string, name?: string) => DOMException;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n if ((ctor as DOMExceptionConstructor).name !== 'DOMException') {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Support:\n * - Web browsers\n * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87)\n */\nfunction getFromGlobal(): DOMExceptionConstructor | undefined {\n const ctor = globals?.DOMException;\n return isDOMExceptionConstructor(ctor) ? ctor : undefined;\n}\n\n/**\n * Support:\n * - All platforms\n */\nfunction createPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line @typescript-eslint/no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n setFunctionName(ctor, 'DOMException');\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nconst DOMException: DOMExceptionConstructor = getFromGlobal() || createPolyfill();\n\nexport { DOMException };\n","import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n return null;\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => null) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => null) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest(): null {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n return null;\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any): null {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n\n return null;\n }\n });\n}\n","import type { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, type QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n type ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport type { ValidatedUnderlyingSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n // Do nothing.\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultController.prototype.close, 'close');\nsetFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableStreamDefaultController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n","import {\n CreateReadableByteStream,\n CreateReadableStream,\n type DefaultReadableStream,\n IsReadableStream,\n type ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n type ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n type ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(\n stream: ReadableStream,\n cloneForBranch2: boolean\n): [DefaultReadableStream, DefaultReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: DefaultReadableStream;\n let branch2: DefaultReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader> = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader>) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return null;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: NonShared, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader>(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n","import { typeIsObject } from '../helpers/miscellaneous';\nimport type { ReadableStreamDefaultReadResult } from './default-reader';\n\n/**\n * A common interface for a `ReadadableStream` implementation.\n *\n * @public\n */\nexport interface ReadableStreamLike {\n readonly locked: boolean;\n\n getReader(): ReadableStreamDefaultReaderLike;\n}\n\n/**\n * A common interface for a `ReadableStreamDefaultReader` implementation.\n *\n * @public\n */\nexport interface ReadableStreamDefaultReaderLike {\n readonly closed: Promise;\n\n cancel(reason?: any): Promise;\n\n read(): Promise>;\n\n releaseLock(): void;\n}\n\nexport function isReadableStreamLike(stream: unknown): stream is ReadableStreamLike {\n return typeIsObject(stream) && typeof (stream as ReadableStreamLike).getReader !== 'undefined';\n}\n","import { CreateReadableStream, type DefaultReadableStream } from '../readable-stream';\nimport {\n isReadableStreamLike,\n type ReadableStreamDefaultReaderLike,\n type ReadableStreamLike\n} from './readable-stream-like';\nimport { ReadableStreamDefaultControllerClose, ReadableStreamDefaultControllerEnqueue } from './default-controller';\nimport { GetIterator, GetMethod, IteratorComplete, IteratorNext, IteratorValue } from '../abstract-ops/ecmascript';\nimport { promiseRejectedWith, promiseResolvedWith, reflectCall, transformPromiseWith } from '../helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { noop } from '../../utils';\n\nexport function ReadableStreamFrom(\n source: Iterable | AsyncIterable | ReadableStreamLike\n): DefaultReadableStream {\n if (isReadableStreamLike(source)) {\n return ReadableStreamFromDefaultReader(source.getReader());\n }\n return ReadableStreamFromIterable(source);\n}\n\nexport function ReadableStreamFromIterable(asyncIterable: Iterable | AsyncIterable): DefaultReadableStream {\n let stream: DefaultReadableStream;\n const iteratorRecord = GetIterator(asyncIterable, 'async');\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let nextResult;\n try {\n nextResult = IteratorNext(iteratorRecord);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const nextPromise = promiseResolvedWith(nextResult);\n return transformPromiseWith(nextPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object');\n }\n const done = IteratorComplete(iterResult);\n if (done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = IteratorValue(iterResult);\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n const iterator = iteratorRecord.iterator;\n let returnMethod: (typeof iterator)['return'] | undefined;\n try {\n returnMethod = GetMethod(iterator, 'return');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n if (returnMethod === undefined) {\n return promiseResolvedWith(undefined);\n }\n let returnResult: IteratorResult | Promise>;\n try {\n returnResult = reflectCall(returnMethod, iterator, [reason]);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const returnPromise = promiseResolvedWith(returnResult);\n return transformPromiseWith(returnPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object');\n }\n return undefined;\n });\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n\nexport function ReadableStreamFromDefaultReader(\n reader: ReadableStreamDefaultReaderLike\n): DefaultReadableStream {\n let stream: DefaultReadableStream;\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let readPromise;\n try {\n readPromise = reader.read();\n } catch (e) {\n return promiseRejectedWith(e);\n }\n return transformPromiseWith(readPromise, readResult => {\n if (!typeIsObject(readResult)) {\n throw new TypeError('The promise returned by the reader.read() method must fulfill with an object');\n }\n if (readResult.done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = readResult.value;\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n try {\n return promiseResolvedWith(reader.cancel(reason));\n } catch (e) {\n return promiseRejectedWith(e);\n }\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n","import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n","import { assertDictionary } from './basic';\nimport type {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n","import { assertDictionary } from './basic';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n","import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n","import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, type ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderErrorReadRequests,\n type ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReaderErrorReadIntoRequests,\n type ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { ReadableStreamFrom } from './readable-stream/from';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport type {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList, SymbolAsyncIterator } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions\n} from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport type { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport type { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\nimport type { ReadableStreamDefaultReaderLike, ReadableStreamLike } from './readable-stream/readable-stream-like';\nimport type { NonShared } from './helpers/array-buffer-view';\n\nexport type DefaultReadableStream = ReadableStream & {\n _readableStreamController: ReadableStreamDefaultController\n};\n\nexport type ReadableByteStream = ReadableStream> & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream implements AsyncIterable {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n\n [SymbolAsyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator {\n // Stub implementation, overridden below\n return this.values(options);\n }\n\n /**\n * Creates a new ReadableStream wrapping the provided iterable or async iterable.\n *\n * This can be used to adapt various kinds of objects into a readable stream,\n * such as an array, an async generator, or a Node.js readable stream.\n */\n static from(asyncIterable: Iterable | AsyncIterable | ReadableStreamLike): ReadableStream {\n return ReadableStreamFrom(asyncIterable);\n }\n}\n\nObject.defineProperties(ReadableStream, {\n from: { enumerable: true }\n});\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(ReadableStream.from, 'from');\nsetFunctionName(ReadableStream.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStream.prototype.getReader, 'getReader');\nsetFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough');\nsetFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo');\nsetFunctionName(ReadableStream.prototype.tee, 'tee');\nsetFunctionName(ReadableStream.prototype.values, 'values');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nObject.defineProperty(ReadableStream.prototype, SymbolAsyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n});\n\nexport type {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n ReadableStreamBYOBReaderReadOptions,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions,\n ReadableStreamLike,\n ReadableStreamDefaultReaderLike\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1\n): DefaultReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: DefaultReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n","import type { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\nsetFunctionName(byteLengthSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\nsetFunctionName(countSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const cancel = original?.cancel;\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n cancel: cancel === undefined ?\n undefined :\n convertTransformerCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n\nfunction convertTransformerCancelCallback(\n fn: TransformerCancelCallback,\n original: Transformer,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith,\n uponPromise\n} from './helpers/webidl';\nimport { CreateReadableStream, type DefaultReadableStream, ReadableStream } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: DefaultReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport type {\n Transformer,\n TransformerCancelCallback,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSourceCancelAlgorithm(stream, reason);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n TransformStreamUnblockWrite(stream);\n}\n\nfunction TransformStreamUnblockWrite(stream: TransformStream) {\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _finishPromise: Promise | undefined;\n /** @internal */\n _finishPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _finishPromise_reject?: (reason: any) => void;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n /** @internal */\n _cancelAlgorithm: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(TransformStreamDefaultController.prototype.error, 'error');\nsetFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._finishPromise = undefined;\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm: (chunk: I) => Promise;\n let flushAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n } else {\n transformAlgorithm = chunk => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n }\n\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n } else {\n flushAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n if (transformer.cancel !== undefined) {\n cancelAlgorithm = reason => transformer.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally,\n // we don't run the _cancelAlgorithm again.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerError(readable._readableStreamController, reason);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally,\n // we don't also run the _cancelAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(flushPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerClose(readable._readableStreamController);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\nfunction TransformStreamDefaultSourceCancelAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._writable cannot change after construction, so caching it across a call to user code is safe.\n const writable = stream._writable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or\n // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the\n // _flushAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (writable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, writable._storedError);\n } else {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\nexport function defaultControllerFinishPromiseResolve(controller: TransformStreamDefaultController) {\n if (controller._finishPromise_resolve === undefined) {\n return;\n }\n\n controller._finishPromise_resolve();\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nexport function defaultControllerFinishPromiseReject(controller: TransformStreamDefaultController, reason: any) {\n if (controller._finishPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(controller._finishPromise!);\n controller._finishPromise_reject(reason);\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n","import {\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n ReadableByteStreamController,\n ReadableStream,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultController,\n ReadableStreamDefaultReader,\n TransformStream,\n TransformStreamDefaultController,\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter\n} from './ponyfill';\nimport { globals } from './globals';\n\n// Export\nexport * from './ponyfill';\n\nconst exports = {\n ReadableStream,\n ReadableStreamDefaultController,\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader,\n\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter,\n\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n\n TransformStream,\n TransformStreamDefaultController\n};\n\n// Add classes to global scope\nif (typeof globals !== 'undefined') {\n for (const prop in exports) {\n if (Object.prototype.hasOwnProperty.call(exports, prop)) {\n Object.defineProperty(globals, prop, {\n value: exports[prop as (keyof typeof exports)],\n writable: true,\n configurable: true\n });\n }\n }\n}\n"],"names":["queueMicrotask","streamBrandCheckException","defaultControllerBrandCheckException"],"mappings":";;;;;;;SAAgB,IAAI,GAAA;AAClB,IAAA,OAAO,SAAS,CAAC;AACnB;;ACCM,SAAU,YAAY,CAAC,CAAM,EAAA;AACjC,IAAA,OAAO,CAAC,OAAO,CAAC,KAAK,QAAQ,IAAI,CAAC,KAAK,IAAI,KAAK,OAAO,CAAC,KAAK,UAAU,CAAC;AAC1E,CAAC;AAEM,MAAM,8BAA8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,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,EAAE;AACvD,YAAA,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,IAAI,EAAE;AACnC,gBAAA,KAAK,EAAE,OAAO,CAAC,IAA8B,CAAC;AAC9C,gBAAA,QAAQ,EAAE,IAAI;AACd,gBAAA,YAAY,EAAE,IAAI;AACnB,aAAA,CAAC,CAAC;SACJ;KACF;AACH;;;;"} \ No newline at end of file diff --git a/backend/node_modules/web-streams-polyfill/dist/polyfill.es6.js b/backend/node_modules/web-streams-polyfill/dist/polyfill.es6.js new file mode 100644 index 0000000000000000000000000000000000000000..c93a0cb2f5a8f48f8dcc1db36d1e2a2c592cd88b --- /dev/null +++ b/backend/node_modules/web-streams-polyfill/dist/polyfill.es6.js @@ -0,0 +1,4838 @@ +/** + * @license + * web-streams-polyfill v3.3.3 + * Copyright 2024 Mattias Buelens, Diwank Singh Tomer and other contributors. + * This code is released under the MIT license. + * SPDX-License-Identifier: MIT + */ +(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.WebStreamsPolyfill = {})); +})(this, (function (exports) { 'use strict'; + + function noop() { + return undefined; + } + + function typeIsObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; + } + const rethrowAssertionErrorRejection = noop; + function setFunctionName(fn, name) { + try { + Object.defineProperty(fn, 'name', { + value: name, + configurable: true + }); + } + catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility + } + } + + const originalPromise = Promise; + const originalPromiseThen = Promise.prototype.then; + const originalPromiseReject = Promise.reject.bind(originalPromise); + // https://webidl.spec.whatwg.org/#a-new-promise + function newPromise(executor) { + return new originalPromise(executor); + } + // https://webidl.spec.whatwg.org/#a-promise-resolved-with + function promiseResolvedWith(value) { + return newPromise(resolve => resolve(value)); + } + // https://webidl.spec.whatwg.org/#a-promise-rejected-with + function promiseRejectedWith(reason) { + return originalPromiseReject(reason); + } + function PerformPromiseThen(promise, onFulfilled, onRejected) { + // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an + // approximation. + return originalPromiseThen.call(promise, onFulfilled, onRejected); + } + // Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned + // from that handler. To prevent this, return null instead of void from all handlers. + // http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it + function uponPromise(promise, onFulfilled, onRejected) { + PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection); + } + function uponFulfillment(promise, onFulfilled) { + uponPromise(promise, onFulfilled); + } + function uponRejection(promise, onRejected) { + uponPromise(promise, undefined, onRejected); + } + function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { + return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); + } + function setPromiseIsHandledToTrue(promise) { + PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection); + } + let _queueMicrotask = callback => { + if (typeof queueMicrotask === 'function') { + _queueMicrotask = queueMicrotask; + } + else { + const resolvedPromise = promiseResolvedWith(undefined); + _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb); + } + return _queueMicrotask(callback); + }; + function reflectCall(F, V, args) { + if (typeof F !== 'function') { + throw new TypeError('Argument is not a function'); + } + return Function.prototype.apply.call(F, V, args); + } + function promiseCall(F, V, args) { + try { + return promiseResolvedWith(reflectCall(F, V, args)); + } + catch (value) { + return promiseRejectedWith(value); + } + } + + // Original from Chromium + // https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js + const QUEUE_MAX_ARRAY_SIZE = 16384; + /** + * Simple queue structure. + * + * Avoids scalability issues with using a packed array directly by using + * multiple arrays in a linked list and keeping the array size bounded. + */ + class SimpleQueue { + constructor() { + this._cursor = 0; + this._size = 0; + // _front and _back are always defined. + this._front = { + _elements: [], + _next: undefined + }; + this._back = this._front; + // The cursor is used to avoid calling Array.shift(). + // It contains the index of the front element of the array inside the + // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE). + this._cursor = 0; + // When there is only one node, size === elements.length - cursor. + this._size = 0; + } + get length() { + return this._size; + } + // For exception safety, this method is structured in order: + // 1. Read state + // 2. Calculate required state mutations + // 3. Perform state mutations + push(element) { + const oldBack = this._back; + let newBack = oldBack; + if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { + newBack = { + _elements: [], + _next: undefined + }; + } + // push() is the mutation most likely to throw an exception, so it + // goes first. + oldBack._elements.push(element); + if (newBack !== oldBack) { + this._back = newBack; + oldBack._next = newBack; + } + ++this._size; + } + // Like push(), shift() follows the read -> calculate -> mutate pattern for + // exception safety. + shift() { // must not be called on an empty queue + const oldFront = this._front; + let newFront = oldFront; + const oldCursor = this._cursor; + let newCursor = oldCursor + 1; + const elements = oldFront._elements; + const element = elements[oldCursor]; + if (newCursor === QUEUE_MAX_ARRAY_SIZE) { + newFront = oldFront._next; + newCursor = 0; + } + // No mutations before this point. + --this._size; + this._cursor = newCursor; + if (oldFront !== newFront) { + this._front = newFront; + } + // Permit shifted element to be garbage collected. + elements[oldCursor] = undefined; + return element; + } + // The tricky thing about forEach() is that it can be called + // re-entrantly. The queue may be mutated inside the callback. It is easy to + // see that push() within the callback has no negative effects since the end + // of the queue is checked for on every iteration. If shift() is called + // repeatedly within the callback then the next iteration may return an + // element that has been removed. In this case the callback will be called + // with undefined values until we either "catch up" with elements that still + // exist or reach the back of the queue. + forEach(callback) { + let i = this._cursor; + let node = this._front; + let elements = node._elements; + while (i !== elements.length || node._next !== undefined) { + if (i === elements.length) { + node = node._next; + elements = node._elements; + i = 0; + if (elements.length === 0) { + break; + } + } + callback(elements[i]); + ++i; + } + } + // Return the element that would be returned if shift() was called now, + // without modifying the queue. + peek() { // must not be called on an empty queue + const front = this._front; + const cursor = this._cursor; + return front._elements[cursor]; + } + } + + const AbortSteps = Symbol('[[AbortSteps]]'); + const ErrorSteps = Symbol('[[ErrorSteps]]'); + const CancelSteps = Symbol('[[CancelSteps]]'); + const PullSteps = Symbol('[[PullSteps]]'); + const ReleaseSteps = Symbol('[[ReleaseSteps]]'); + + function ReadableStreamReaderGenericInitialize(reader, stream) { + reader._ownerReadableStream = stream; + stream._reader = reader; + if (stream._state === 'readable') { + defaultReaderClosedPromiseInitialize(reader); + } + else if (stream._state === 'closed') { + defaultReaderClosedPromiseInitializeAsResolved(reader); + } + else { + defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); + } + } + // A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state + // check. + function ReadableStreamReaderGenericCancel(reader, reason) { + const stream = reader._ownerReadableStream; + return ReadableStreamCancel(stream, reason); + } + function ReadableStreamReaderGenericRelease(reader) { + const stream = reader._ownerReadableStream; + if (stream._state === 'readable') { + defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + else { + defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + stream._readableStreamController[ReleaseSteps](); + stream._reader = undefined; + reader._ownerReadableStream = undefined; + } + // Helper functions for the readers. + function readerLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released reader'); + } + // Helper functions for the ReadableStreamDefaultReader. + function defaultReaderClosedPromiseInitialize(reader) { + reader._closedPromise = newPromise((resolve, reject) => { + reader._closedPromise_resolve = resolve; + reader._closedPromise_reject = reject; + }); + } + function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseReject(reader, reason); + } + function defaultReaderClosedPromiseInitializeAsResolved(reader) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseResolve(reader); + } + function defaultReaderClosedPromiseReject(reader, reason) { + if (reader._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(reader._closedPromise); + reader._closedPromise_reject(reason); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; + } + function defaultReaderClosedPromiseResetToRejected(reader, reason) { + defaultReaderClosedPromiseInitializeAsRejected(reader, reason); + } + function defaultReaderClosedPromiseResolve(reader) { + if (reader._closedPromise_resolve === undefined) { + return; + } + reader._closedPromise_resolve(undefined); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; + } + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill + const NumberIsFinite = Number.isFinite || function (x) { + return typeof x === 'number' && isFinite(x); + }; + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill + const MathTrunc = Math.trunc || function (v) { + return v < 0 ? Math.ceil(v) : Math.floor(v); + }; + + // https://heycam.github.io/webidl/#idl-dictionaries + function isDictionary(x) { + return typeof x === 'object' || typeof x === 'function'; + } + function assertDictionary(obj, context) { + if (obj !== undefined && !isDictionary(obj)) { + throw new TypeError(`${context} is not an object.`); + } + } + // https://heycam.github.io/webidl/#idl-callback-functions + function assertFunction(x, context) { + if (typeof x !== 'function') { + throw new TypeError(`${context} is not a function.`); + } + } + // https://heycam.github.io/webidl/#idl-object + function isObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; + } + function assertObject(x, context) { + if (!isObject(x)) { + throw new TypeError(`${context} is not an object.`); + } + } + function assertRequiredArgument(x, position, context) { + if (x === undefined) { + throw new TypeError(`Parameter ${position} is required in '${context}'.`); + } + } + function assertRequiredField(x, field, context) { + if (x === undefined) { + throw new TypeError(`${field} is required in '${context}'.`); + } + } + // https://heycam.github.io/webidl/#idl-unrestricted-double + function convertUnrestrictedDouble(value) { + return Number(value); + } + function censorNegativeZero(x) { + return x === 0 ? 0 : x; + } + function integerPart(x) { + return censorNegativeZero(MathTrunc(x)); + } + // https://heycam.github.io/webidl/#idl-unsigned-long-long + function convertUnsignedLongLongWithEnforceRange(value, context) { + const lowerBound = 0; + const upperBound = Number.MAX_SAFE_INTEGER; + let x = Number(value); + x = censorNegativeZero(x); + if (!NumberIsFinite(x)) { + throw new TypeError(`${context} is not a finite number`); + } + x = integerPart(x); + if (x < lowerBound || x > upperBound) { + throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`); + } + if (!NumberIsFinite(x) || x === 0) { + return 0; + } + // TODO Use BigInt if supported? + // let xBigInt = BigInt(integerPart(x)); + // xBigInt = BigInt.asUintN(64, xBigInt); + // return Number(xBigInt); + return x; + } + + function assertReadableStream(x, context) { + if (!IsReadableStream(x)) { + throw new TypeError(`${context} is not a ReadableStream.`); + } + } + + // Abstract operations for the ReadableStream. + function AcquireReadableStreamDefaultReader(stream) { + return new ReadableStreamDefaultReader(stream); + } + // ReadableStream API exposed for controllers. + function ReadableStreamAddReadRequest(stream, readRequest) { + stream._reader._readRequests.push(readRequest); + } + function ReadableStreamFulfillReadRequest(stream, chunk, done) { + const reader = stream._reader; + const readRequest = reader._readRequests.shift(); + if (done) { + readRequest._closeSteps(); + } + else { + readRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadRequests(stream) { + return stream._reader._readRequests.length; + } + function ReadableStreamHasDefaultReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamDefaultReader(reader)) { + return false; + } + return true; + } + /** + * A default reader vended by a {@link ReadableStream}. + * + * @public + */ + class ReadableStreamDefaultReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + /** + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('read')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: () => resolvePromise({ value: undefined, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamDefaultReaderRead(this, readRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamDefaultReader(this)) { + throw defaultReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamDefaultReaderRelease(this); + } + } + Object.defineProperties(ReadableStreamDefaultReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + setFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel'); + setFunctionName(ReadableStreamDefaultReader.prototype.read, 'read'); + setFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, { + value: 'ReadableStreamDefaultReader', + configurable: true + }); + } + // Abstract operations for the readers. + function IsReadableStreamDefaultReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) { + return false; + } + return x instanceof ReadableStreamDefaultReader; + } + function ReadableStreamDefaultReaderRead(reader, readRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'closed') { + readRequest._closeSteps(); + } + else if (stream._state === 'errored') { + readRequest._errorSteps(stream._storedError); + } + else { + stream._readableStreamController[PullSteps](readRequest); + } + } + function ReadableStreamDefaultReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + const e = new TypeError('Reader was released'); + ReadableStreamDefaultReaderErrorReadRequests(reader, e); + } + function ReadableStreamDefaultReaderErrorReadRequests(reader, e) { + const readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(readRequest => { + readRequest._errorSteps(e); + }); + } + // Helper functions for the ReadableStreamDefaultReader. + function defaultReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`); + } + + /****************************************************************************** + 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 */ + + + function __values(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + } + + function __await(v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); + } + + function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } + } + + function __asyncDelegator(o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } + } + + function __asyncValues(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } + } + + 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 _a, _b, _c; + function CreateArrayFromList(elements) { + // We use arrays to represent lists, so this is basically a no-op. + // Do a slice though just in case we happen to depend on the unique-ness. + return elements.slice(); + } + function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { + new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); + } + let TransferArrayBuffer = (O) => { + if (typeof O.transfer === 'function') { + TransferArrayBuffer = buffer => buffer.transfer(); + } + else if (typeof structuredClone === 'function') { + TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] }); + } + else { + // Not implemented correctly + TransferArrayBuffer = buffer => buffer; + } + return TransferArrayBuffer(O); + }; + let IsDetachedBuffer = (O) => { + if (typeof O.detached === 'boolean') { + IsDetachedBuffer = buffer => buffer.detached; + } + else { + // Not implemented correctly + IsDetachedBuffer = buffer => buffer.byteLength === 0; + } + return IsDetachedBuffer(O); + }; + function ArrayBufferSlice(buffer, begin, end) { + // ArrayBuffer.prototype.slice is not available on IE10 + // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice + if (buffer.slice) { + return buffer.slice(begin, end); + } + const length = end - begin; + const slice = new ArrayBuffer(length); + CopyDataBlockBytes(slice, 0, buffer, begin, length); + return slice; + } + function GetMethod(receiver, prop) { + const func = receiver[prop]; + if (func === undefined || func === null) { + return undefined; + } + if (typeof func !== 'function') { + throw new TypeError(`${String(prop)} is not a function`); + } + return func; + } + function CreateAsyncFromSyncIterator(syncIteratorRecord) { + // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%, + // we use yield* inside an async generator function to achieve the same result. + // Wrap the sync iterator inside a sync iterable, so we can use it with yield*. + const syncIterable = { + [Symbol.iterator]: () => syncIteratorRecord.iterator + }; + // Create an async generator function and immediately invoke it. + const asyncIterator = (function () { + return __asyncGenerator(this, arguments, function* () { + return yield __await(yield __await(yield* __asyncDelegator(__asyncValues(syncIterable)))); + }); + }()); + // Return as an async iterator record. + const nextMethod = asyncIterator.next; + return { iterator: asyncIterator, nextMethod, done: false }; + } + // Aligns with core-js/modules/es.symbol.async-iterator.js + const SymbolAsyncIterator = (_c = (_a = Symbol.asyncIterator) !== null && _a !== void 0 ? _a : (_b = Symbol.for) === null || _b === void 0 ? void 0 : _b.call(Symbol, 'Symbol.asyncIterator')) !== null && _c !== void 0 ? _c : '@@asyncIterator'; + function GetIterator(obj, hint = 'sync', method) { + if (method === undefined) { + if (hint === 'async') { + method = GetMethod(obj, SymbolAsyncIterator); + if (method === undefined) { + const syncMethod = GetMethod(obj, Symbol.iterator); + const syncIteratorRecord = GetIterator(obj, 'sync', syncMethod); + return CreateAsyncFromSyncIterator(syncIteratorRecord); + } + } + else { + method = GetMethod(obj, Symbol.iterator); + } + } + if (method === undefined) { + throw new TypeError('The object is not iterable'); + } + const iterator = reflectCall(method, obj, []); + if (!typeIsObject(iterator)) { + throw new TypeError('The iterator method must return an object'); + } + const nextMethod = iterator.next; + return { iterator, nextMethod, done: false }; + } + function IteratorNext(iteratorRecord) { + const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []); + if (!typeIsObject(result)) { + throw new TypeError('The iterator.next() method must return an object'); + } + return result; + } + function IteratorComplete(iterResult) { + return Boolean(iterResult.done); + } + function IteratorValue(iterResult) { + return iterResult.value; + } + + /// + // We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it. + const AsyncIteratorPrototype = { + // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( ) + // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator + [SymbolAsyncIterator]() { + return this; + } + }; + Object.defineProperty(AsyncIteratorPrototype, SymbolAsyncIterator, { enumerable: false }); + + /// + class ReadableStreamAsyncIteratorImpl { + constructor(reader, preventCancel) { + this._ongoingPromise = undefined; + this._isFinished = false; + this._reader = reader; + this._preventCancel = preventCancel; + } + next() { + const nextSteps = () => this._nextSteps(); + this._ongoingPromise = this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : + nextSteps(); + return this._ongoingPromise; + } + return(value) { + const returnSteps = () => this._returnSteps(value); + return this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : + returnSteps(); + } + _nextSteps() { + if (this._isFinished) { + return Promise.resolve({ value: undefined, done: true }); + } + const reader = this._reader; + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => { + this._ongoingPromise = undefined; + // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test. + // FIXME Is this a bug in the specification, or in the test? + _queueMicrotask(() => resolvePromise({ value: chunk, done: false })); + }, + _closeSteps: () => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + resolvePromise({ value: undefined, done: true }); + }, + _errorSteps: reason => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + rejectPromise(reason); + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promise; + } + _returnSteps(value) { + if (this._isFinished) { + return Promise.resolve({ value, done: true }); + } + this._isFinished = true; + const reader = this._reader; + if (!this._preventCancel) { + const result = ReadableStreamReaderGenericCancel(reader, value); + ReadableStreamReaderGenericRelease(reader); + return transformPromiseWith(result, () => ({ value, done: true })); + } + ReadableStreamReaderGenericRelease(reader); + return promiseResolvedWith({ value, done: true }); + } + } + const ReadableStreamAsyncIteratorPrototype = { + next() { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next')); + } + return this._asyncIteratorImpl.next(); + }, + return(value) { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return')); + } + return this._asyncIteratorImpl.return(value); + } + }; + Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); + // Abstract operations for the ReadableStream. + function AcquireReadableStreamAsyncIterator(stream, preventCancel) { + const reader = AcquireReadableStreamDefaultReader(stream); + const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); + const iterator = Object.create(ReadableStreamAsyncIteratorPrototype); + iterator._asyncIteratorImpl = impl; + return iterator; + } + function IsReadableStreamAsyncIterator(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) { + return false; + } + try { + // noinspection SuspiciousTypeOfGuard + return x._asyncIteratorImpl instanceof + ReadableStreamAsyncIteratorImpl; + } + catch (_a) { + return false; + } + } + // Helper functions for the ReadableStream. + function streamAsyncIteratorBrandCheckException(name) { + return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`); + } + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill + const NumberIsNaN = Number.isNaN || function (x) { + // eslint-disable-next-line no-self-compare + return x !== x; + }; + + function IsNonNegativeNumber(v) { + if (typeof v !== 'number') { + return false; + } + if (NumberIsNaN(v)) { + return false; + } + if (v < 0) { + return false; + } + return true; + } + function CloneAsUint8Array(O) { + const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength); + return new Uint8Array(buffer); + } + + function DequeueValue(container) { + const pair = container._queue.shift(); + container._queueTotalSize -= pair.size; + if (container._queueTotalSize < 0) { + container._queueTotalSize = 0; + } + return pair.value; + } + function EnqueueValueWithSize(container, value, size) { + if (!IsNonNegativeNumber(size) || size === Infinity) { + throw new RangeError('Size must be a finite, non-NaN, non-negative number.'); + } + container._queue.push({ value, size }); + container._queueTotalSize += size; + } + function PeekQueueValue(container) { + const pair = container._queue.peek(); + return pair.value; + } + function ResetQueue(container) { + container._queue = new SimpleQueue(); + container._queueTotalSize = 0; + } + + function isDataViewConstructor(ctor) { + return ctor === DataView; + } + function isDataView(view) { + return isDataViewConstructor(view.constructor); + } + function arrayBufferViewElementSize(ctor) { + if (isDataViewConstructor(ctor)) { + return 1; + } + return ctor.BYTES_PER_ELEMENT; + } + + /** + * A pull-into request in a {@link ReadableByteStreamController}. + * + * @public + */ + class ReadableStreamBYOBRequest { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. + */ + get view() { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('view'); + } + return this._view; + } + respond(bytesWritten) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respond'); + } + assertRequiredArgument(bytesWritten, 1, 'respond'); + bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter'); + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(this._view.buffer)) { + throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`); + } + ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); + } + respondWithNewView(view) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respondWithNewView'); + } + assertRequiredArgument(view, 1, 'respondWithNewView'); + if (!ArrayBuffer.isView(view)) { + throw new TypeError('You can only respond with array buffer views'); + } + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(view.buffer)) { + throw new TypeError('The given view\'s buffer has been detached and so cannot be used as a response'); + } + ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); + } + } + Object.defineProperties(ReadableStreamBYOBRequest.prototype, { + respond: { enumerable: true }, + respondWithNewView: { enumerable: true }, + view: { enumerable: true } + }); + setFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond'); + setFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, { + value: 'ReadableStreamBYOBRequest', + configurable: true + }); + } + /** + * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. + * + * @public + */ + class ReadableByteStreamController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the current BYOB pull request, or `null` if there isn't one. + */ + get byobRequest() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('byobRequest'); + } + return ReadableByteStreamControllerGetBYOBRequest(this); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('desiredSize'); + } + return ReadableByteStreamControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('close'); + } + if (this._closeRequested) { + throw new TypeError('The stream has already been closed; do not close it again!'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`); + } + ReadableByteStreamControllerClose(this); + } + enqueue(chunk) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('enqueue'); + } + assertRequiredArgument(chunk, 1, 'enqueue'); + if (!ArrayBuffer.isView(chunk)) { + throw new TypeError('chunk must be an array buffer view'); + } + if (chunk.byteLength === 0) { + throw new TypeError('chunk must have non-zero byteLength'); + } + if (chunk.buffer.byteLength === 0) { + throw new TypeError(`chunk's buffer must have non-zero byteLength`); + } + if (this._closeRequested) { + throw new TypeError('stream is closed or draining'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`); + } + ReadableByteStreamControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('error'); + } + ReadableByteStreamControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ReadableByteStreamControllerClearPendingPullIntos(this); + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableByteStreamControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableByteStream; + if (this._queueTotalSize > 0) { + ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest); + return; + } + const autoAllocateChunkSize = this._autoAllocateChunkSize; + if (autoAllocateChunkSize !== undefined) { + let buffer; + try { + buffer = new ArrayBuffer(autoAllocateChunkSize); + } + catch (bufferE) { + readRequest._errorSteps(bufferE); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: autoAllocateChunkSize, + byteOffset: 0, + byteLength: autoAllocateChunkSize, + bytesFilled: 0, + minimumFill: 1, + elementSize: 1, + viewConstructor: Uint8Array, + readerType: 'default' + }; + this._pendingPullIntos.push(pullIntoDescriptor); + } + ReadableStreamAddReadRequest(stream, readRequest); + ReadableByteStreamControllerCallPullIfNeeded(this); + } + /** @internal */ + [ReleaseSteps]() { + if (this._pendingPullIntos.length > 0) { + const firstPullInto = this._pendingPullIntos.peek(); + firstPullInto.readerType = 'none'; + this._pendingPullIntos = new SimpleQueue(); + this._pendingPullIntos.push(firstPullInto); + } + } + } + Object.defineProperties(ReadableByteStreamController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + byobRequest: { enumerable: true }, + desiredSize: { enumerable: true } + }); + setFunctionName(ReadableByteStreamController.prototype.close, 'close'); + setFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue'); + setFunctionName(ReadableByteStreamController.prototype.error, 'error'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, { + value: 'ReadableByteStreamController', + configurable: true + }); + } + // Abstract operations for the ReadableByteStreamController. + function IsReadableByteStreamController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) { + return false; + } + return x instanceof ReadableByteStreamController; + } + function IsReadableStreamBYOBRequest(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) { + return false; + } + return x instanceof ReadableStreamBYOBRequest; + } + function ReadableByteStreamControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableByteStreamControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + // TODO: Test controller argument + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + return null; + }, e => { + ReadableByteStreamControllerError(controller, e); + return null; + }); + } + function ReadableByteStreamControllerClearPendingPullIntos(controller) { + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + controller._pendingPullIntos = new SimpleQueue(); + } + function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { + let done = false; + if (stream._state === 'closed') { + done = true; + } + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'default') { + ReadableStreamFulfillReadRequest(stream, filledView, done); + } + else { + ReadableStreamFulfillReadIntoRequest(stream, filledView, done); + } + } + function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { + const bytesFilled = pullIntoDescriptor.bytesFilled; + const elementSize = pullIntoDescriptor.elementSize; + return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); + } + function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { + controller._queue.push({ buffer, byteOffset, byteLength }); + controller._queueTotalSize += byteLength; + } + function ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, buffer, byteOffset, byteLength) { + let clonedChunk; + try { + clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength); + } + catch (cloneE) { + ReadableByteStreamControllerError(controller, cloneE); + throw cloneE; + } + ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength); + } + function ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstDescriptor) { + if (firstDescriptor.bytesFilled > 0) { + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, firstDescriptor.buffer, firstDescriptor.byteOffset, firstDescriptor.bytesFilled); + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { + const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); + const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; + let totalBytesToCopyRemaining = maxBytesToCopy; + let ready = false; + const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize; + const maxAlignedBytes = maxBytesFilled - remainderBytes; + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) { + totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; + ready = true; + } + const queue = controller._queue; + while (totalBytesToCopyRemaining > 0) { + const headOfQueue = queue.peek(); + const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); + const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); + if (headOfQueue.byteLength === bytesToCopy) { + queue.shift(); + } + else { + headOfQueue.byteOffset += bytesToCopy; + headOfQueue.byteLength -= bytesToCopy; + } + controller._queueTotalSize -= bytesToCopy; + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); + totalBytesToCopyRemaining -= bytesToCopy; + } + return ready; + } + function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { + pullIntoDescriptor.bytesFilled += size; + } + function ReadableByteStreamControllerHandleQueueDrain(controller) { + if (controller._queueTotalSize === 0 && controller._closeRequested) { + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(controller._controlledReadableByteStream); + } + else { + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + } + function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { + if (controller._byobRequest === null) { + return; + } + controller._byobRequest._associatedReadableByteStreamController = undefined; + controller._byobRequest._view = null; + controller._byobRequest = null; + } + function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { + while (controller._pendingPullIntos.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const pullIntoDescriptor = controller._pendingPullIntos.peek(); + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller) { + const reader = controller._controlledReadableByteStream._reader; + while (reader._readRequests.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const readRequest = reader._readRequests.shift(); + ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest); + } + } + function ReadableByteStreamControllerPullInto(controller, view, min, readIntoRequest) { + const stream = controller._controlledReadableByteStream; + const ctor = view.constructor; + const elementSize = arrayBufferViewElementSize(ctor); + const { byteOffset, byteLength } = view; + const minimumFill = min * elementSize; + let buffer; + try { + buffer = TransferArrayBuffer(view.buffer); + } + catch (e) { + readIntoRequest._errorSteps(e); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: buffer.byteLength, + byteOffset, + byteLength, + bytesFilled: 0, + minimumFill, + elementSize, + viewConstructor: ctor, + readerType: 'byob' + }; + if (controller._pendingPullIntos.length > 0) { + controller._pendingPullIntos.push(pullIntoDescriptor); + // No ReadableByteStreamControllerCallPullIfNeeded() call since: + // - No change happens on desiredSize + // - The source has already been notified of that there's at least 1 pending read(view) + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + return; + } + if (stream._state === 'closed') { + const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); + readIntoRequest._closeSteps(emptyView); + return; + } + if (controller._queueTotalSize > 0) { + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + ReadableByteStreamControllerHandleQueueDrain(controller); + readIntoRequest._chunkSteps(filledView); + return; + } + if (controller._closeRequested) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + readIntoRequest._errorSteps(e); + return; + } + } + controller._pendingPullIntos.push(pullIntoDescriptor); + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { + if (firstDescriptor.readerType === 'none') { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const stream = controller._controlledReadableByteStream; + if (ReadableStreamHasBYOBReader(stream)) { + while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { + const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + return; + } + if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) { + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + return; + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; + if (remainderSize > 0) { + const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor.buffer, end - remainderSize, remainderSize); + } + pullIntoDescriptor.bytesFilled -= remainderSize; + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor); + } + else { + ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerShiftPendingPullInto(controller) { + const descriptor = controller._pendingPullIntos.shift(); + return descriptor; + } + function ReadableByteStreamControllerShouldCallPull(controller) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return false; + } + if (controller._closeRequested) { + return false; + } + if (!controller._started) { + return false; + } + if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; + } + function ReadableByteStreamControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + } + // A client of ReadableByteStreamController may use these functions directly to bypass state check. + function ReadableByteStreamControllerClose(controller) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + if (controller._queueTotalSize > 0) { + controller._closeRequested = true; + return; + } + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + throw e; + } + } + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } + function ReadableByteStreamControllerEnqueue(controller, chunk) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + const { buffer, byteOffset, byteLength } = chunk; + if (IsDetachedBuffer(buffer)) { + throw new TypeError('chunk\'s buffer is detached and so cannot be enqueued'); + } + const transferredBuffer = TransferArrayBuffer(buffer); + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (IsDetachedBuffer(firstPendingPullInto.buffer)) { + throw new TypeError('The BYOB request\'s buffer has been detached and so cannot be filled with an enqueued chunk'); + } + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer); + if (firstPendingPullInto.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto); + } + } + if (ReadableStreamHasDefaultReader(stream)) { + ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller); + if (ReadableStreamGetNumReadRequests(stream) === 0) { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + else { + if (controller._pendingPullIntos.length > 0) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); + ReadableStreamFulfillReadRequest(stream, transferredView, false); + } + } + else if (ReadableStreamHasBYOBReader(stream)) { + // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully. + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + else { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerError(controller, e) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return; + } + ReadableByteStreamControllerClearPendingPullIntos(controller); + ResetQueue(controller); + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); + } + function ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest) { + const entry = controller._queue.shift(); + controller._queueTotalSize -= entry.byteLength; + ReadableByteStreamControllerHandleQueueDrain(controller); + const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); + readRequest._chunkSteps(view); + } + function ReadableByteStreamControllerGetBYOBRequest(controller) { + if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); + const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); + SetUpReadableStreamBYOBRequest(byobRequest, controller, view); + controller._byobRequest = byobRequest; + } + return controller._byobRequest; + } + function ReadableByteStreamControllerGetDesiredSize(controller) { + const state = controller._controlledReadableByteStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; + } + function ReadableByteStreamControllerRespond(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (bytesWritten !== 0) { + throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream'); + } + } + else { + if (bytesWritten === 0) { + throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream'); + } + if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) { + throw new RangeError('bytesWritten out of range'); + } + } + firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); + ReadableByteStreamControllerRespondInternal(controller, bytesWritten); + } + function ReadableByteStreamControllerRespondWithNewView(controller, view) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (view.byteLength !== 0) { + throw new TypeError('The view\'s length must be 0 when calling respondWithNewView() on a closed stream'); + } + } + else { + if (view.byteLength === 0) { + throw new TypeError('The view\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'); + } + } + if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { + throw new RangeError('The region specified by view does not match byobRequest'); + } + if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) { + throw new RangeError('The buffer of view has different capacity than byobRequest'); + } + if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) { + throw new RangeError('The region specified by view is larger than byobRequest'); + } + const viewByteLength = view.byteLength; + firstDescriptor.buffer = TransferArrayBuffer(view.buffer); + ReadableByteStreamControllerRespondInternal(controller, viewByteLength); + } + function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { + controller._controlledReadableByteStream = stream; + controller._pullAgain = false; + controller._pulling = false; + controller._byobRequest = null; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._closeRequested = false; + controller._started = false; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._autoAllocateChunkSize = autoAllocateChunkSize; + controller._pendingPullIntos = new SimpleQueue(); + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableByteStreamControllerCallPullIfNeeded(controller); + return null; + }, r => { + ReadableByteStreamControllerError(controller, r); + return null; + }); + } + function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { + const controller = Object.create(ReadableByteStreamController.prototype); + let startAlgorithm; + let pullAlgorithm; + let cancelAlgorithm; + if (underlyingByteSource.start !== undefined) { + startAlgorithm = () => underlyingByteSource.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingByteSource.pull !== undefined) { + pullAlgorithm = () => underlyingByteSource.pull(controller); + } + else { + pullAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingByteSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingByteSource.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; + if (autoAllocateChunkSize === 0) { + throw new TypeError('autoAllocateChunkSize must be greater than 0'); + } + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); + } + function SetUpReadableStreamBYOBRequest(request, controller, view) { + request._associatedReadableByteStreamController = controller; + request._view = view; + } + // Helper functions for the ReadableStreamBYOBRequest. + function byobRequestBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`); + } + // Helper functions for the ReadableByteStreamController. + function byteStreamControllerBrandCheckException(name) { + return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`); + } + + function convertReaderOptions(options, context) { + assertDictionary(options, context); + const mode = options === null || options === void 0 ? void 0 : options.mode; + return { + mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`) + }; + } + function convertReadableStreamReaderMode(mode, context) { + mode = `${mode}`; + if (mode !== 'byob') { + throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`); + } + return mode; + } + function convertByobReadOptions(options, context) { + var _a; + assertDictionary(options, context); + const min = (_a = options === null || options === void 0 ? void 0 : options.min) !== null && _a !== void 0 ? _a : 1; + return { + min: convertUnsignedLongLongWithEnforceRange(min, `${context} has member 'min' that`) + }; + } + + // Abstract operations for the ReadableStream. + function AcquireReadableStreamBYOBReader(stream) { + return new ReadableStreamBYOBReader(stream); + } + // ReadableStream API exposed for controllers. + function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { + stream._reader._readIntoRequests.push(readIntoRequest); + } + function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { + const reader = stream._reader; + const readIntoRequest = reader._readIntoRequests.shift(); + if (done) { + readIntoRequest._closeSteps(chunk); + } + else { + readIntoRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadIntoRequests(stream) { + return stream._reader._readIntoRequests.length; + } + function ReadableStreamHasBYOBReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamBYOBReader(reader)) { + return false; + } + return true; + } + /** + * A BYOB reader vended by a {@link ReadableStream}. + * + * @public + */ + class ReadableStreamBYOBReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + if (!IsReadableByteStreamController(stream._readableStreamController)) { + throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' + + 'source'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readIntoRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + read(view, rawOptions = {}) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('read')); + } + if (!ArrayBuffer.isView(view)) { + return promiseRejectedWith(new TypeError('view must be an array buffer view')); + } + if (view.byteLength === 0) { + return promiseRejectedWith(new TypeError('view must have non-zero byteLength')); + } + if (view.buffer.byteLength === 0) { + return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`)); + } + if (IsDetachedBuffer(view.buffer)) { + return promiseRejectedWith(new TypeError('view\'s buffer has been detached')); + } + let options; + try { + options = convertByobReadOptions(rawOptions, 'options'); + } + catch (e) { + return promiseRejectedWith(e); + } + const min = options.min; + if (min === 0) { + return promiseRejectedWith(new TypeError('options.min must be greater than 0')); + } + if (!isDataView(view)) { + if (min > view.length) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s length')); + } + } + else if (min > view.byteLength) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s byteLength')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readIntoRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: chunk => resolvePromise({ value: chunk, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamBYOBReader(this)) { + throw byobReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamBYOBReaderRelease(this); + } + } + Object.defineProperties(ReadableStreamBYOBReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + setFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel'); + setFunctionName(ReadableStreamBYOBReader.prototype.read, 'read'); + setFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, { + value: 'ReadableStreamBYOBReader', + configurable: true + }); + } + // Abstract operations for the readers. + function IsReadableStreamBYOBReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) { + return false; + } + return x instanceof ReadableStreamBYOBReader; + } + function ReadableStreamBYOBReaderRead(reader, view, min, readIntoRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'errored') { + readIntoRequest._errorSteps(stream._storedError); + } + else { + ReadableByteStreamControllerPullInto(stream._readableStreamController, view, min, readIntoRequest); + } + } + function ReadableStreamBYOBReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + const e = new TypeError('Reader was released'); + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); + } + function ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e) { + const readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._errorSteps(e); + }); + } + // Helper functions for the ReadableStreamBYOBReader. + function byobReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`); + } + + function ExtractHighWaterMark(strategy, defaultHWM) { + const { highWaterMark } = strategy; + if (highWaterMark === undefined) { + return defaultHWM; + } + if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { + throw new RangeError('Invalid highWaterMark'); + } + return highWaterMark; + } + function ExtractSizeAlgorithm(strategy) { + const { size } = strategy; + if (!size) { + return () => 1; + } + return size; + } + + function convertQueuingStrategy(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + const size = init === null || init === void 0 ? void 0 : init.size; + return { + highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark), + size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`) + }; + } + function convertQueuingStrategySize(fn, context) { + assertFunction(fn, context); + return chunk => convertUnrestrictedDouble(fn(chunk)); + } + + function convertUnderlyingSink(original, context) { + assertDictionary(original, context); + const abort = original === null || original === void 0 ? void 0 : original.abort; + const close = original === null || original === void 0 ? void 0 : original.close; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + const write = original === null || original === void 0 ? void 0 : original.write; + return { + abort: abort === undefined ? + undefined : + convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`), + close: close === undefined ? + undefined : + convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`), + start: start === undefined ? + undefined : + convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`), + write: write === undefined ? + undefined : + convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`), + type + }; + } + function convertUnderlyingSinkAbortCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); + } + function convertUnderlyingSinkCloseCallback(fn, original, context) { + assertFunction(fn, context); + return () => promiseCall(fn, original, []); + } + function convertUnderlyingSinkStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertUnderlyingSinkWriteCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); + } + + function assertWritableStream(x, context) { + if (!IsWritableStream(x)) { + throw new TypeError(`${context} is not a WritableStream.`); + } + } + + function isAbortSignal(value) { + if (typeof value !== 'object' || value === null) { + return false; + } + try { + return typeof value.aborted === 'boolean'; + } + catch (_a) { + // AbortSignal.prototype.aborted throws if its brand check fails + return false; + } + } + const supportsAbortController = typeof AbortController === 'function'; + /** + * Construct a new AbortController, if supported by the platform. + * + * @internal + */ + function createAbortController() { + if (supportsAbortController) { + return new AbortController(); + } + return undefined; + } + + /** + * A writable stream represents a destination for data, into which you can write. + * + * @public + */ + class WritableStream { + constructor(rawUnderlyingSink = {}, rawStrategy = {}) { + if (rawUnderlyingSink === undefined) { + rawUnderlyingSink = null; + } + else { + assertObject(rawUnderlyingSink, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter'); + InitializeWritableStream(this); + const type = underlyingSink.type; + if (type !== undefined) { + throw new RangeError('Invalid type is specified'); + } + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); + } + /** + * Returns whether or not the writable stream is locked to a writer. + */ + get locked() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('locked'); + } + return IsWritableStreamLocked(this); + } + /** + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort + * mechanism of the underlying sink. + * + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel + * the stream) if the stream is currently locked. + */ + abort(reason = undefined) { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('abort')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer')); + } + return WritableStreamAbort(this, reason); + } + /** + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its + * close behavior. During this time any further attempts to write will fail (without erroring the stream). + * + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + */ + close() { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('close')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer')); + } + if (WritableStreamCloseQueuedOrInFlight(this)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamClose(this); + } + /** + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream + * is locked, no other writer can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at + * the same time, which would cause the resulting written data to be unpredictable and probably useless. + */ + getWriter() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('getWriter'); + } + return AcquireWritableStreamDefaultWriter(this); + } + } + Object.defineProperties(WritableStream.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + getWriter: { enumerable: true }, + locked: { enumerable: true } + }); + setFunctionName(WritableStream.prototype.abort, 'abort'); + setFunctionName(WritableStream.prototype.close, 'close'); + setFunctionName(WritableStream.prototype.getWriter, 'getWriter'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, { + value: 'WritableStream', + configurable: true + }); + } + // Abstract operations for the WritableStream. + function AcquireWritableStreamDefaultWriter(stream) { + return new WritableStreamDefaultWriter(stream); + } + // Throws if and only if startAlgorithm throws. + function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(WritableStream.prototype); + InitializeWritableStream(stream); + const controller = Object.create(WritableStreamDefaultController.prototype); + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + return stream; + } + function InitializeWritableStream(stream) { + stream._state = 'writable'; + // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is + // 'erroring' or 'errored'. May be set to an undefined value. + stream._storedError = undefined; + stream._writer = undefined; + // Initialize to undefined first because the constructor of the controller checks this + // variable to validate the caller. + stream._writableStreamController = undefined; + // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data + // producer without waiting for the queued writes to finish. + stream._writeRequests = new SimpleQueue(); + // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents + // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here. + stream._inFlightWriteRequest = undefined; + // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer + // has been detached. + stream._closeRequest = undefined; + // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it + // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here. + stream._inFlightCloseRequest = undefined; + // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached. + stream._pendingAbortRequest = undefined; + // The backpressure signal set by the controller. + stream._backpressure = false; + } + function IsWritableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) { + return false; + } + return x instanceof WritableStream; + } + function IsWritableStreamLocked(stream) { + if (stream._writer === undefined) { + return false; + } + return true; + } + function WritableStreamAbort(stream, reason) { + var _a; + if (stream._state === 'closed' || stream._state === 'errored') { + return promiseResolvedWith(undefined); + } + stream._writableStreamController._abortReason = reason; + (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort(reason); + // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring', + // but it doesn't know that signaling abort runs author code that might have changed the state. + // Widen the type again by casting to WritableStreamState. + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseResolvedWith(undefined); + } + if (stream._pendingAbortRequest !== undefined) { + return stream._pendingAbortRequest._promise; + } + let wasAlreadyErroring = false; + if (state === 'erroring') { + wasAlreadyErroring = true; + // reason will not be used, so don't keep a reference to it. + reason = undefined; + } + const promise = newPromise((resolve, reject) => { + stream._pendingAbortRequest = { + _promise: undefined, + _resolve: resolve, + _reject: reject, + _reason: reason, + _wasAlreadyErroring: wasAlreadyErroring + }; + }); + stream._pendingAbortRequest._promise = promise; + if (!wasAlreadyErroring) { + WritableStreamStartErroring(stream, reason); + } + return promise; + } + function WritableStreamClose(stream) { + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`)); + } + const promise = newPromise((resolve, reject) => { + const closeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._closeRequest = closeRequest; + }); + const writer = stream._writer; + if (writer !== undefined && stream._backpressure && state === 'writable') { + defaultWriterReadyPromiseResolve(writer); + } + WritableStreamDefaultControllerClose(stream._writableStreamController); + return promise; + } + // WritableStream API exposed for controllers. + function WritableStreamAddWriteRequest(stream) { + const promise = newPromise((resolve, reject) => { + const writeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._writeRequests.push(writeRequest); + }); + return promise; + } + function WritableStreamDealWithRejection(stream, error) { + const state = stream._state; + if (state === 'writable') { + WritableStreamStartErroring(stream, error); + return; + } + WritableStreamFinishErroring(stream); + } + function WritableStreamStartErroring(stream, reason) { + const controller = stream._writableStreamController; + stream._state = 'erroring'; + stream._storedError = reason; + const writer = stream._writer; + if (writer !== undefined) { + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); + } + if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { + WritableStreamFinishErroring(stream); + } + } + function WritableStreamFinishErroring(stream) { + stream._state = 'errored'; + stream._writableStreamController[ErrorSteps](); + const storedError = stream._storedError; + stream._writeRequests.forEach(writeRequest => { + writeRequest._reject(storedError); + }); + stream._writeRequests = new SimpleQueue(); + if (stream._pendingAbortRequest === undefined) { + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const abortRequest = stream._pendingAbortRequest; + stream._pendingAbortRequest = undefined; + if (abortRequest._wasAlreadyErroring) { + abortRequest._reject(storedError); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const promise = stream._writableStreamController[AbortSteps](abortRequest._reason); + uponPromise(promise, () => { + abortRequest._resolve(); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }, (reason) => { + abortRequest._reject(reason); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }); + } + function WritableStreamFinishInFlightWrite(stream) { + stream._inFlightWriteRequest._resolve(undefined); + stream._inFlightWriteRequest = undefined; + } + function WritableStreamFinishInFlightWriteWithError(stream, error) { + stream._inFlightWriteRequest._reject(error); + stream._inFlightWriteRequest = undefined; + WritableStreamDealWithRejection(stream, error); + } + function WritableStreamFinishInFlightClose(stream) { + stream._inFlightCloseRequest._resolve(undefined); + stream._inFlightCloseRequest = undefined; + const state = stream._state; + if (state === 'erroring') { + // The error was too late to do anything, so it is ignored. + stream._storedError = undefined; + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._resolve(); + stream._pendingAbortRequest = undefined; + } + } + stream._state = 'closed'; + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseResolve(writer); + } + } + function WritableStreamFinishInFlightCloseWithError(stream, error) { + stream._inFlightCloseRequest._reject(error); + stream._inFlightCloseRequest = undefined; + // Never execute sink abort() after sink close(). + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._reject(error); + stream._pendingAbortRequest = undefined; + } + WritableStreamDealWithRejection(stream, error); + } + // TODO(ricea): Fix alphabetical order. + function WritableStreamCloseQueuedOrInFlight(stream) { + if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; + } + function WritableStreamHasOperationMarkedInFlight(stream) { + if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; + } + function WritableStreamMarkCloseRequestInFlight(stream) { + stream._inFlightCloseRequest = stream._closeRequest; + stream._closeRequest = undefined; + } + function WritableStreamMarkFirstWriteRequestInFlight(stream) { + stream._inFlightWriteRequest = stream._writeRequests.shift(); + } + function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { + if (stream._closeRequest !== undefined) { + stream._closeRequest._reject(stream._storedError); + stream._closeRequest = undefined; + } + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseReject(writer, stream._storedError); + } + } + function WritableStreamUpdateBackpressure(stream, backpressure) { + const writer = stream._writer; + if (writer !== undefined && backpressure !== stream._backpressure) { + if (backpressure) { + defaultWriterReadyPromiseReset(writer); + } + else { + defaultWriterReadyPromiseResolve(writer); + } + } + stream._backpressure = backpressure; + } + /** + * A default writer vended by a {@link WritableStream}. + * + * @public + */ + class WritableStreamDefaultWriter { + constructor(stream) { + assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter'); + assertWritableStream(stream, 'First parameter'); + if (IsWritableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive writing by another writer'); + } + this._ownerWritableStream = stream; + stream._writer = this; + const state = stream._state; + if (state === 'writable') { + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { + defaultWriterReadyPromiseInitialize(this); + } + else { + defaultWriterReadyPromiseInitializeAsResolved(this); + } + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'erroring') { + defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'closed') { + defaultWriterReadyPromiseInitializeAsResolved(this); + defaultWriterClosedPromiseInitializeAsResolved(this); + } + else { + const storedError = stream._storedError; + defaultWriterReadyPromiseInitializeAsRejected(this, storedError); + defaultWriterClosedPromiseInitializeAsRejected(this, storedError); + } + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the writer’s lock is released before the stream finishes closing. + */ + get closed() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. + * A producer can use this information to determine the right amount of data to write. + * + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when + * the writer’s lock is released. + */ + get desiredSize() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('desiredSize'); + } + if (this._ownerWritableStream === undefined) { + throw defaultWriterLockException('desiredSize'); + } + return WritableStreamDefaultWriterGetDesiredSize(this); + } + /** + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips + * back to zero or below, the getter will return a new promise that stays pending until the next transition. + * + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become + * rejected. + */ + get ready() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('ready')); + } + return this._readyPromise; + } + /** + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + */ + abort(reason = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('abort')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('abort')); + } + return WritableStreamDefaultWriterAbort(this, reason); + } + /** + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + */ + close() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('close')); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return promiseRejectedWith(defaultWriterLockException('close')); + } + if (WritableStreamCloseQueuedOrInFlight(stream)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamDefaultWriterClose(this); + } + /** + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from + * now on; otherwise, the writer will appear closed. + * + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents + * other producers from writing in an interleaved manner. + */ + releaseLock() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('releaseLock'); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return; + } + WritableStreamDefaultWriterRelease(this); + } + write(chunk = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('write')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + return WritableStreamDefaultWriterWrite(this, chunk); + } + } + Object.defineProperties(WritableStreamDefaultWriter.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + releaseLock: { enumerable: true }, + write: { enumerable: true }, + closed: { enumerable: true }, + desiredSize: { enumerable: true }, + ready: { enumerable: true } + }); + setFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort'); + setFunctionName(WritableStreamDefaultWriter.prototype.close, 'close'); + setFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock'); + setFunctionName(WritableStreamDefaultWriter.prototype.write, 'write'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, { + value: 'WritableStreamDefaultWriter', + configurable: true + }); + } + // Abstract operations for the WritableStreamDefaultWriter. + function IsWritableStreamDefaultWriter(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultWriter; + } + // A client of WritableStreamDefaultWriter may use these functions directly to bypass state check. + function WritableStreamDefaultWriterAbort(writer, reason) { + const stream = writer._ownerWritableStream; + return WritableStreamAbort(stream, reason); + } + function WritableStreamDefaultWriterClose(writer) { + const stream = writer._ownerWritableStream; + return WritableStreamClose(stream); + } + function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseResolvedWith(undefined); + } + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + return WritableStreamDefaultWriterClose(writer); + } + function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { + if (writer._closedPromiseState === 'pending') { + defaultWriterClosedPromiseReject(writer, error); + } + else { + defaultWriterClosedPromiseResetToRejected(writer, error); + } + } + function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { + if (writer._readyPromiseState === 'pending') { + defaultWriterReadyPromiseReject(writer, error); + } + else { + defaultWriterReadyPromiseResetToRejected(writer, error); + } + } + function WritableStreamDefaultWriterGetDesiredSize(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (state === 'errored' || state === 'erroring') { + return null; + } + if (state === 'closed') { + return 0; + } + return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); + } + function WritableStreamDefaultWriterRelease(writer) { + const stream = writer._ownerWritableStream; + const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`); + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); + // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not + // rejected until afterwards. This means that simply testing state will not work. + WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); + stream._writer = undefined; + writer._ownerWritableStream = undefined; + } + function WritableStreamDefaultWriterWrite(writer, chunk) { + const stream = writer._ownerWritableStream; + const controller = stream._writableStreamController; + const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); + if (stream !== writer._ownerWritableStream) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + const state = stream._state; + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to')); + } + if (state === 'erroring') { + return promiseRejectedWith(stream._storedError); + } + const promise = WritableStreamAddWriteRequest(stream); + WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); + return promise; + } + const closeSentinel = {}; + /** + * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. + * + * @public + */ + class WritableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. + * + * @deprecated + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. + */ + get abortReason() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('abortReason'); + } + return this._abortReason; + } + /** + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. + */ + get signal() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('signal'); + } + if (this._abortController === undefined) { + // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`. + // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill, + // so instead we only implement support for `signal` if we find a global `AbortController` constructor. + throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported'); + } + return this._abortController.signal; + } + /** + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. + * + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the + * normal lifecycle of interactions with the underlying sink. + */ + error(e = undefined) { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('error'); + } + const state = this._controlledWritableStream._state; + if (state !== 'writable') { + // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so + // just treat it as a no-op. + return; + } + WritableStreamDefaultControllerError(this, e); + } + /** @internal */ + [AbortSteps](reason) { + const result = this._abortAlgorithm(reason); + WritableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [ErrorSteps]() { + ResetQueue(this); + } + } + Object.defineProperties(WritableStreamDefaultController.prototype, { + abortReason: { enumerable: true }, + signal: { enumerable: true }, + error: { enumerable: true } + }); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, { + value: 'WritableStreamDefaultController', + configurable: true + }); + } + // Abstract operations implementing interface required by the WritableStream. + function IsWritableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultController; + } + function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledWritableStream = stream; + stream._writableStreamController = controller; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._abortReason = undefined; + controller._abortController = createAbortController(); + controller._started = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._writeAlgorithm = writeAlgorithm; + controller._closeAlgorithm = closeAlgorithm; + controller._abortAlgorithm = abortAlgorithm; + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + const startResult = startAlgorithm(); + const startPromise = promiseResolvedWith(startResult); + uponPromise(startPromise, () => { + controller._started = true; + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, r => { + controller._started = true; + WritableStreamDealWithRejection(stream, r); + return null; + }); + } + function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { + const controller = Object.create(WritableStreamDefaultController.prototype); + let startAlgorithm; + let writeAlgorithm; + let closeAlgorithm; + let abortAlgorithm; + if (underlyingSink.start !== undefined) { + startAlgorithm = () => underlyingSink.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingSink.write !== undefined) { + writeAlgorithm = chunk => underlyingSink.write(chunk, controller); + } + else { + writeAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSink.close !== undefined) { + closeAlgorithm = () => underlyingSink.close(); + } + else { + closeAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSink.abort !== undefined) { + abortAlgorithm = reason => underlyingSink.abort(reason); + } + else { + abortAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + } + // ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls. + function WritableStreamDefaultControllerClearAlgorithms(controller) { + controller._writeAlgorithm = undefined; + controller._closeAlgorithm = undefined; + controller._abortAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; + } + function WritableStreamDefaultControllerClose(controller) { + EnqueueValueWithSize(controller, closeSentinel, 0); + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + } + function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { + try { + return controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); + return 1; + } + } + function WritableStreamDefaultControllerGetDesiredSize(controller) { + return controller._strategyHWM - controller._queueTotalSize; + } + function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); + return; + } + const stream = controller._controlledWritableStream; + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + } + // Abstract operations for the WritableStreamDefaultController. + function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { + const stream = controller._controlledWritableStream; + if (!controller._started) { + return; + } + if (stream._inFlightWriteRequest !== undefined) { + return; + } + const state = stream._state; + if (state === 'erroring') { + WritableStreamFinishErroring(stream); + return; + } + if (controller._queue.length === 0) { + return; + } + const value = PeekQueueValue(controller); + if (value === closeSentinel) { + WritableStreamDefaultControllerProcessClose(controller); + } + else { + WritableStreamDefaultControllerProcessWrite(controller, value); + } + } + function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { + if (controller._controlledWritableStream._state === 'writable') { + WritableStreamDefaultControllerError(controller, error); + } + } + function WritableStreamDefaultControllerProcessClose(controller) { + const stream = controller._controlledWritableStream; + WritableStreamMarkCloseRequestInFlight(stream); + DequeueValue(controller); + const sinkClosePromise = controller._closeAlgorithm(); + WritableStreamDefaultControllerClearAlgorithms(controller); + uponPromise(sinkClosePromise, () => { + WritableStreamFinishInFlightClose(stream); + return null; + }, reason => { + WritableStreamFinishInFlightCloseWithError(stream, reason); + return null; + }); + } + function WritableStreamDefaultControllerProcessWrite(controller, chunk) { + const stream = controller._controlledWritableStream; + WritableStreamMarkFirstWriteRequestInFlight(stream); + const sinkWritePromise = controller._writeAlgorithm(chunk); + uponPromise(sinkWritePromise, () => { + WritableStreamFinishInFlightWrite(stream); + const state = stream._state; + DequeueValue(controller); + if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, reason => { + if (stream._state === 'writable') { + WritableStreamDefaultControllerClearAlgorithms(controller); + } + WritableStreamFinishInFlightWriteWithError(stream, reason); + return null; + }); + } + function WritableStreamDefaultControllerGetBackpressure(controller) { + const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); + return desiredSize <= 0; + } + // A client of WritableStreamDefaultController may use these functions directly to bypass state check. + function WritableStreamDefaultControllerError(controller, error) { + const stream = controller._controlledWritableStream; + WritableStreamDefaultControllerClearAlgorithms(controller); + WritableStreamStartErroring(stream, error); + } + // Helper functions for the WritableStream. + function streamBrandCheckException$2(name) { + return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`); + } + // Helper functions for the WritableStreamDefaultController. + function defaultControllerBrandCheckException$2(name) { + return new TypeError(`WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`); + } + // Helper functions for the WritableStreamDefaultWriter. + function defaultWriterBrandCheckException(name) { + return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`); + } + function defaultWriterLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released writer'); + } + function defaultWriterClosedPromiseInitialize(writer) { + writer._closedPromise = newPromise((resolve, reject) => { + writer._closedPromise_resolve = resolve; + writer._closedPromise_reject = reject; + writer._closedPromiseState = 'pending'; + }); + } + function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseReject(writer, reason); + } + function defaultWriterClosedPromiseInitializeAsResolved(writer) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseResolve(writer); + } + function defaultWriterClosedPromiseReject(writer, reason) { + if (writer._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._closedPromise); + writer._closedPromise_reject(reason); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'rejected'; + } + function defaultWriterClosedPromiseResetToRejected(writer, reason) { + defaultWriterClosedPromiseInitializeAsRejected(writer, reason); + } + function defaultWriterClosedPromiseResolve(writer) { + if (writer._closedPromise_resolve === undefined) { + return; + } + writer._closedPromise_resolve(undefined); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'resolved'; + } + function defaultWriterReadyPromiseInitialize(writer) { + writer._readyPromise = newPromise((resolve, reject) => { + writer._readyPromise_resolve = resolve; + writer._readyPromise_reject = reject; + }); + writer._readyPromiseState = 'pending'; + } + function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseReject(writer, reason); + } + function defaultWriterReadyPromiseInitializeAsResolved(writer) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseResolve(writer); + } + function defaultWriterReadyPromiseReject(writer, reason) { + if (writer._readyPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._readyPromise); + writer._readyPromise_reject(reason); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'rejected'; + } + function defaultWriterReadyPromiseReset(writer) { + defaultWriterReadyPromiseInitialize(writer); + } + function defaultWriterReadyPromiseResetToRejected(writer, reason) { + defaultWriterReadyPromiseInitializeAsRejected(writer, reason); + } + function defaultWriterReadyPromiseResolve(writer) { + if (writer._readyPromise_resolve === undefined) { + return; + } + writer._readyPromise_resolve(undefined); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'fulfilled'; + } + + /// + function getGlobals() { + if (typeof globalThis !== 'undefined') { + return globalThis; + } + else if (typeof self !== 'undefined') { + return self; + } + else if (typeof global !== 'undefined') { + return global; + } + return undefined; + } + const globals = getGlobals(); + + /// + function isDOMExceptionConstructor(ctor) { + if (!(typeof ctor === 'function' || typeof ctor === 'object')) { + return false; + } + if (ctor.name !== 'DOMException') { + return false; + } + try { + new ctor(); + return true; + } + catch (_a) { + return false; + } + } + /** + * Support: + * - Web browsers + * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87) + */ + function getFromGlobal() { + const ctor = globals === null || globals === void 0 ? void 0 : globals.DOMException; + return isDOMExceptionConstructor(ctor) ? ctor : undefined; + } + /** + * Support: + * - All platforms + */ + function createPolyfill() { + // eslint-disable-next-line @typescript-eslint/no-shadow + const ctor = function DOMException(message, name) { + this.message = message || ''; + this.name = name || 'Error'; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + }; + setFunctionName(ctor, 'DOMException'); + ctor.prototype = Object.create(Error.prototype); + Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true }); + return ctor; + } + // eslint-disable-next-line @typescript-eslint/no-redeclare + const DOMException = getFromGlobal() || createPolyfill(); + + function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { + const reader = AcquireReadableStreamDefaultReader(source); + const writer = AcquireWritableStreamDefaultWriter(dest); + source._disturbed = true; + let shuttingDown = false; + // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown. + let currentWrite = promiseResolvedWith(undefined); + return newPromise((resolve, reject) => { + let abortAlgorithm; + if (signal !== undefined) { + abortAlgorithm = () => { + const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError'); + const actions = []; + if (!preventAbort) { + actions.push(() => { + if (dest._state === 'writable') { + return WritableStreamAbort(dest, error); + } + return promiseResolvedWith(undefined); + }); + } + if (!preventCancel) { + actions.push(() => { + if (source._state === 'readable') { + return ReadableStreamCancel(source, error); + } + return promiseResolvedWith(undefined); + }); + } + shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error); + }; + if (signal.aborted) { + abortAlgorithm(); + return; + } + signal.addEventListener('abort', abortAlgorithm); + } + // Using reader and writer, read all chunks from this and write them to dest + // - Backpressure must be enforced + // - Shutdown must stop all activity + function pipeLoop() { + return newPromise((resolveLoop, rejectLoop) => { + function next(done) { + if (done) { + resolveLoop(); + } + else { + // Use `PerformPromiseThen` instead of `uponPromise` to avoid + // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers + PerformPromiseThen(pipeStep(), next, rejectLoop); + } + } + next(false); + }); + } + function pipeStep() { + if (shuttingDown) { + return promiseResolvedWith(true); + } + return PerformPromiseThen(writer._readyPromise, () => { + return newPromise((resolveRead, rejectRead) => { + ReadableStreamDefaultReaderRead(reader, { + _chunkSteps: chunk => { + currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop); + resolveRead(false); + }, + _closeSteps: () => resolveRead(true), + _errorSteps: rejectRead + }); + }); + }); + } + // Errors must be propagated forward + isOrBecomesErrored(source, reader._closedPromise, storedError => { + if (!preventAbort) { + shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Errors must be propagated backward + isOrBecomesErrored(dest, writer._closedPromise, storedError => { + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Closing must be propagated forward + isOrBecomesClosed(source, reader._closedPromise, () => { + if (!preventClose) { + shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer)); + } + else { + shutdown(); + } + return null; + }); + // Closing must be propagated backward + if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') { + const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it'); + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed); + } + else { + shutdown(true, destClosed); + } + } + setPromiseIsHandledToTrue(pipeLoop()); + function waitForWritesToFinish() { + // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait + // for that too. + const oldCurrentWrite = currentWrite; + return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined); + } + function isOrBecomesErrored(stream, promise, action) { + if (stream._state === 'errored') { + action(stream._storedError); + } + else { + uponRejection(promise, action); + } + } + function isOrBecomesClosed(stream, promise, action) { + if (stream._state === 'closed') { + action(); + } + else { + uponFulfillment(promise, action); + } + } + function shutdownWithAction(action, originalIsError, originalError) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), doTheRest); + } + else { + doTheRest(); + } + function doTheRest() { + uponPromise(action(), () => finalize(originalIsError, originalError), newError => finalize(true, newError)); + return null; + } + } + function shutdown(isError, error) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error)); + } + else { + finalize(isError, error); + } + } + function finalize(isError, error) { + WritableStreamDefaultWriterRelease(writer); + ReadableStreamReaderGenericRelease(reader); + if (signal !== undefined) { + signal.removeEventListener('abort', abortAlgorithm); + } + if (isError) { + reject(error); + } + else { + resolve(undefined); + } + return null; + } + }); + } + + /** + * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. + * + * @public + */ + class ReadableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('desiredSize'); + } + return ReadableStreamDefaultControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('close'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits close'); + } + ReadableStreamDefaultControllerClose(this); + } + enqueue(chunk = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('enqueue'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits enqueue'); + } + return ReadableStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('error'); + } + ReadableStreamDefaultControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableStream; + if (this._queue.length > 0) { + const chunk = DequeueValue(this); + if (this._closeRequested && this._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(this); + ReadableStreamClose(stream); + } + else { + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + readRequest._chunkSteps(chunk); + } + else { + ReadableStreamAddReadRequest(stream, readRequest); + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + } + /** @internal */ + [ReleaseSteps]() { + // Do nothing. + } + } + Object.defineProperties(ReadableStreamDefaultController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + desiredSize: { enumerable: true } + }); + setFunctionName(ReadableStreamDefaultController.prototype.close, 'close'); + setFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue'); + setFunctionName(ReadableStreamDefaultController.prototype.error, 'error'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, { + value: 'ReadableStreamDefaultController', + configurable: true + }); + } + // Abstract operations for the ReadableStreamDefaultController. + function IsReadableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) { + return false; + } + return x instanceof ReadableStreamDefaultController; + } + function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + return null; + }, e => { + ReadableStreamDefaultControllerError(controller, e); + return null; + }); + } + function ReadableStreamDefaultControllerShouldCallPull(controller) { + const stream = controller._controlledReadableStream; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return false; + } + if (!controller._started) { + return false; + } + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; + } + function ReadableStreamDefaultControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; + } + // A client of ReadableStreamDefaultController may use these functions directly to bypass state check. + function ReadableStreamDefaultControllerClose(controller) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + controller._closeRequested = true; + if (controller._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } + } + function ReadableStreamDefaultControllerEnqueue(controller, chunk) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + ReadableStreamFulfillReadRequest(stream, chunk, false); + } + else { + let chunkSize; + try { + chunkSize = controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + ReadableStreamDefaultControllerError(controller, chunkSizeE); + throw chunkSizeE; + } + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + ReadableStreamDefaultControllerError(controller, enqueueE); + throw enqueueE; + } + } + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + function ReadableStreamDefaultControllerError(controller, e) { + const stream = controller._controlledReadableStream; + if (stream._state !== 'readable') { + return; + } + ResetQueue(controller); + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); + } + function ReadableStreamDefaultControllerGetDesiredSize(controller) { + const state = controller._controlledReadableStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; + } + // This is used in the implementation of TransformStream. + function ReadableStreamDefaultControllerHasBackpressure(controller) { + if (ReadableStreamDefaultControllerShouldCallPull(controller)) { + return false; + } + return true; + } + function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { + const state = controller._controlledReadableStream._state; + if (!controller._closeRequested && state === 'readable') { + return true; + } + return false; + } + function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledReadableStream = stream; + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._started = false; + controller._closeRequested = false; + controller._pullAgain = false; + controller._pulling = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + return null; + }, r => { + ReadableStreamDefaultControllerError(controller, r); + return null; + }); + } + function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { + const controller = Object.create(ReadableStreamDefaultController.prototype); + let startAlgorithm; + let pullAlgorithm; + let cancelAlgorithm; + if (underlyingSource.start !== undefined) { + startAlgorithm = () => underlyingSource.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingSource.pull !== undefined) { + pullAlgorithm = () => underlyingSource.pull(controller); + } + else { + pullAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingSource.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + } + // Helper functions for the ReadableStreamDefaultController. + function defaultControllerBrandCheckException$1(name) { + return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`); + } + + function ReadableStreamTee(stream, cloneForBranch2) { + if (IsReadableByteStreamController(stream._readableStreamController)) { + return ReadableByteStreamTee(stream); + } + return ReadableStreamDefaultTee(stream); + } + function ReadableStreamDefaultTee(stream, cloneForBranch2) { + const reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgain = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function pullAlgorithm() { + if (reading) { + readAgain = true; + return promiseResolvedWith(undefined); + } + reading = true; + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgain = false; + const chunk1 = chunk; + const chunk2 = chunk; + // There is no way to access the cloning code right now in the reference implementation. + // If we add one then we'll need an implementation for serializable objects. + // if (!canceled2 && cloneForBranch2) { + // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2)); + // } + if (!canceled1) { + ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgain) { + pullAlgorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableStreamDefaultControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableStreamDefaultControllerClose(branch2._readableStreamController); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + // do nothing + } + branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); + branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); + uponRejection(reader._closedPromise, (r) => { + ReadableStreamDefaultControllerError(branch1._readableStreamController, r); + ReadableStreamDefaultControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + return [branch1, branch2]; + } + function ReadableByteStreamTee(stream) { + let reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgainForBranch1 = false; + let readAgainForBranch2 = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function forwardReaderError(thisReader) { + uponRejection(thisReader._closedPromise, r => { + if (thisReader !== reader) { + return null; + } + ReadableByteStreamControllerError(branch1._readableStreamController, r); + ReadableByteStreamControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + } + function pullWithDefaultReader() { + if (IsReadableStreamBYOBReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamDefaultReader(stream); + forwardReaderError(reader); + } + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const chunk1 = chunk; + let chunk2 = chunk; + if (!canceled1 && !canceled2) { + try { + chunk2 = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(branch1._readableStreamController, cloneE); + ReadableByteStreamControllerError(branch2._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + } + if (!canceled1) { + ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableByteStreamControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableByteStreamControllerClose(branch2._readableStreamController); + } + if (branch1._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch1._readableStreamController, 0); + } + if (branch2._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch2._readableStreamController, 0); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + } + function pullWithBYOBReader(view, forBranch2) { + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamBYOBReader(stream); + forwardReaderError(reader); + } + const byobBranch = forBranch2 ? branch2 : branch1; + const otherBranch = forBranch2 ? branch1 : branch2; + const readIntoRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!otherCanceled) { + let clonedChunk; + try { + clonedChunk = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE); + ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk); + } + else if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: chunk => { + reading = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!byobCanceled) { + ReadableByteStreamControllerClose(byobBranch._readableStreamController); + } + if (!otherCanceled) { + ReadableByteStreamControllerClose(otherBranch._readableStreamController); + } + if (chunk !== undefined) { + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0); + } + } + if (!byobCanceled || !otherCanceled) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest); + } + function pull1Algorithm() { + if (reading) { + readAgainForBranch1 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, false); + } + return promiseResolvedWith(undefined); + } + function pull2Algorithm() { + if (reading) { + readAgainForBranch2 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, true); + } + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + return; + } + branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm); + branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm); + forwardReaderError(reader); + return [branch1, branch2]; + } + + function isReadableStreamLike(stream) { + return typeIsObject(stream) && typeof stream.getReader !== 'undefined'; + } + + function ReadableStreamFrom(source) { + if (isReadableStreamLike(source)) { + return ReadableStreamFromDefaultReader(source.getReader()); + } + return ReadableStreamFromIterable(source); + } + function ReadableStreamFromIterable(asyncIterable) { + let stream; + const iteratorRecord = GetIterator(asyncIterable, 'async'); + const startAlgorithm = noop; + function pullAlgorithm() { + let nextResult; + try { + nextResult = IteratorNext(iteratorRecord); + } + catch (e) { + return promiseRejectedWith(e); + } + const nextPromise = promiseResolvedWith(nextResult); + return transformPromiseWith(nextPromise, iterResult => { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object'); + } + const done = IteratorComplete(iterResult); + if (done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + const value = IteratorValue(iterResult); + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + const iterator = iteratorRecord.iterator; + let returnMethod; + try { + returnMethod = GetMethod(iterator, 'return'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (returnMethod === undefined) { + return promiseResolvedWith(undefined); + } + let returnResult; + try { + returnResult = reflectCall(returnMethod, iterator, [reason]); + } + catch (e) { + return promiseRejectedWith(e); + } + const returnPromise = promiseResolvedWith(returnResult); + return transformPromiseWith(returnPromise, iterResult => { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object'); + } + return undefined; + }); + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; + } + function ReadableStreamFromDefaultReader(reader) { + let stream; + const startAlgorithm = noop; + function pullAlgorithm() { + let readPromise; + try { + readPromise = reader.read(); + } + catch (e) { + return promiseRejectedWith(e); + } + return transformPromiseWith(readPromise, readResult => { + if (!typeIsObject(readResult)) { + throw new TypeError('The promise returned by the reader.read() method must fulfill with an object'); + } + if (readResult.done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + const value = readResult.value; + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + try { + return promiseResolvedWith(reader.cancel(reason)); + } + catch (e) { + return promiseRejectedWith(e); + } + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; + } + + function convertUnderlyingDefaultOrByteSource(source, context) { + assertDictionary(source, context); + const original = source; + const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; + const cancel = original === null || original === void 0 ? void 0 : original.cancel; + const pull = original === null || original === void 0 ? void 0 : original.pull; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + return { + autoAllocateChunkSize: autoAllocateChunkSize === undefined ? + undefined : + convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`), + cancel: cancel === undefined ? + undefined : + convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`), + pull: pull === undefined ? + undefined : + convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`), + start: start === undefined ? + undefined : + convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`), + type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`) + }; + } + function convertUnderlyingSourceCancelCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); + } + function convertUnderlyingSourcePullCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); + } + function convertUnderlyingSourceStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertReadableStreamType(type, context) { + type = `${type}`; + if (type !== 'bytes') { + throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`); + } + return type; + } + + function convertIteratorOptions(options, context) { + assertDictionary(options, context); + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + return { preventCancel: Boolean(preventCancel) }; + } + + function convertPipeOptions(options, context) { + assertDictionary(options, context); + const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort; + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + const preventClose = options === null || options === void 0 ? void 0 : options.preventClose; + const signal = options === null || options === void 0 ? void 0 : options.signal; + if (signal !== undefined) { + assertAbortSignal(signal, `${context} has member 'signal' that`); + } + return { + preventAbort: Boolean(preventAbort), + preventCancel: Boolean(preventCancel), + preventClose: Boolean(preventClose), + signal + }; + } + function assertAbortSignal(signal, context) { + if (!isAbortSignal(signal)) { + throw new TypeError(`${context} is not an AbortSignal.`); + } + } + + function convertReadableWritablePair(pair, context) { + assertDictionary(pair, context); + const readable = pair === null || pair === void 0 ? void 0 : pair.readable; + assertRequiredField(readable, 'readable', 'ReadableWritablePair'); + assertReadableStream(readable, `${context} has member 'readable' that`); + const writable = pair === null || pair === void 0 ? void 0 : pair.writable; + assertRequiredField(writable, 'writable', 'ReadableWritablePair'); + assertWritableStream(writable, `${context} has member 'writable' that`); + return { readable, writable }; + } + + /** + * A readable stream represents a source of data, from which you can read. + * + * @public + */ + class ReadableStream { + constructor(rawUnderlyingSource = {}, rawStrategy = {}) { + if (rawUnderlyingSource === undefined) { + rawUnderlyingSource = null; + } + else { + assertObject(rawUnderlyingSource, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter'); + InitializeReadableStream(this); + if (underlyingSource.type === 'bytes') { + if (strategy.size !== undefined) { + throw new RangeError('The strategy for a byte stream cannot have a size function'); + } + const highWaterMark = ExtractHighWaterMark(strategy, 0); + SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); + } + else { + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); + } + } + /** + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. + */ + get locked() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('locked'); + } + return IsReadableStreamLocked(this); + } + /** + * Cancels the stream, signaling a loss of interest in the stream by a consumer. + * + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} + * method, which might or might not use it. + */ + cancel(reason = undefined) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('cancel')); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader')); + } + return ReadableStreamCancel(this, reason); + } + getReader(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('getReader'); + } + const options = convertReaderOptions(rawOptions, 'First parameter'); + if (options.mode === undefined) { + return AcquireReadableStreamDefaultReader(this); + } + return AcquireReadableStreamBYOBReader(this); + } + pipeThrough(rawTransform, rawOptions = {}) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('pipeThrough'); + } + assertRequiredArgument(rawTransform, 1, 'pipeThrough'); + const transform = convertReadableWritablePair(rawTransform, 'First parameter'); + const options = convertPipeOptions(rawOptions, 'Second parameter'); + if (IsReadableStreamLocked(this)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream'); + } + if (IsWritableStreamLocked(transform.writable)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream'); + } + const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + setPromiseIsHandledToTrue(promise); + return transform.readable; + } + pipeTo(destination, rawOptions = {}) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('pipeTo')); + } + if (destination === undefined) { + return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`); + } + if (!IsWritableStream(destination)) { + return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)); + } + let options; + try { + options = convertPipeOptions(rawOptions, 'Second parameter'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')); + } + if (IsWritableStreamLocked(destination)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')); + } + return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + } + /** + * Tees this readable stream, returning a two-element array containing the two resulting branches as + * new {@link ReadableStream} instances. + * + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be + * propagated to the stream's underlying source. + * + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, + * this could allow interference between the two branches. + */ + tee() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('tee'); + } + const branches = ReadableStreamTee(this); + return CreateArrayFromList(branches); + } + values(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('values'); + } + const options = convertIteratorOptions(rawOptions, 'First parameter'); + return AcquireReadableStreamAsyncIterator(this, options.preventCancel); + } + [SymbolAsyncIterator](options) { + // Stub implementation, overridden below + return this.values(options); + } + /** + * Creates a new ReadableStream wrapping the provided iterable or async iterable. + * + * This can be used to adapt various kinds of objects into a readable stream, + * such as an array, an async generator, or a Node.js readable stream. + */ + static from(asyncIterable) { + return ReadableStreamFrom(asyncIterable); + } + } + Object.defineProperties(ReadableStream, { + from: { enumerable: true } + }); + Object.defineProperties(ReadableStream.prototype, { + cancel: { enumerable: true }, + getReader: { enumerable: true }, + pipeThrough: { enumerable: true }, + pipeTo: { enumerable: true }, + tee: { enumerable: true }, + values: { enumerable: true }, + locked: { enumerable: true } + }); + setFunctionName(ReadableStream.from, 'from'); + setFunctionName(ReadableStream.prototype.cancel, 'cancel'); + setFunctionName(ReadableStream.prototype.getReader, 'getReader'); + setFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough'); + setFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo'); + setFunctionName(ReadableStream.prototype.tee, 'tee'); + setFunctionName(ReadableStream.prototype.values, 'values'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, { + value: 'ReadableStream', + configurable: true + }); + } + Object.defineProperty(ReadableStream.prototype, SymbolAsyncIterator, { + value: ReadableStream.prototype.values, + writable: true, + configurable: true + }); + // Abstract operations for the ReadableStream. + // Throws if and only if startAlgorithm throws. + function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableStreamDefaultController.prototype); + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + return stream; + } + // Throws if and only if startAlgorithm throws. + function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableByteStreamController.prototype); + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined); + return stream; + } + function InitializeReadableStream(stream) { + stream._state = 'readable'; + stream._reader = undefined; + stream._storedError = undefined; + stream._disturbed = false; + } + function IsReadableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) { + return false; + } + return x instanceof ReadableStream; + } + function IsReadableStreamLocked(stream) { + if (stream._reader === undefined) { + return false; + } + return true; + } + // ReadableStream API exposed for controllers. + function ReadableStreamCancel(stream, reason) { + stream._disturbed = true; + if (stream._state === 'closed') { + return promiseResolvedWith(undefined); + } + if (stream._state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + ReadableStreamClose(stream); + const reader = stream._reader; + if (reader !== undefined && IsReadableStreamBYOBReader(reader)) { + const readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._closeSteps(undefined); + }); + } + const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); + return transformPromiseWith(sourceCancelPromise, noop); + } + function ReadableStreamClose(stream) { + stream._state = 'closed'; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseResolve(reader); + if (IsReadableStreamDefaultReader(reader)) { + const readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(readRequest => { + readRequest._closeSteps(); + }); + } + } + function ReadableStreamError(stream, e) { + stream._state = 'errored'; + stream._storedError = e; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseReject(reader, e); + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamDefaultReaderErrorReadRequests(reader, e); + } + else { + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); + } + } + // Helper functions for the ReadableStream. + function streamBrandCheckException$1(name) { + return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`); + } + + function convertQueuingStrategyInit(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit'); + return { + highWaterMark: convertUnrestrictedDouble(highWaterMark) + }; + } + + // The size function must not have a prototype property nor be a constructor + const byteLengthSizeFunction = (chunk) => { + return chunk.byteLength; + }; + setFunctionName(byteLengthSizeFunction, 'size'); + /** + * A queuing strategy that counts the number of bytes in each chunk. + * + * @public + */ + class ByteLengthQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('highWaterMark'); + } + return this._byteLengthQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by returning the value of its `byteLength` property. + */ + get size() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('size'); + } + return byteLengthSizeFunction; + } + } + Object.defineProperties(ByteLengthQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, { + value: 'ByteLengthQueuingStrategy', + configurable: true + }); + } + // Helper functions for the ByteLengthQueuingStrategy. + function byteLengthBrandCheckException(name) { + return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`); + } + function IsByteLengthQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof ByteLengthQueuingStrategy; + } + + // The size function must not have a prototype property nor be a constructor + const countSizeFunction = () => { + return 1; + }; + setFunctionName(countSizeFunction, 'size'); + /** + * A queuing strategy that counts the number of chunks. + * + * @public + */ + class CountQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'CountQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._countQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('highWaterMark'); + } + return this._countQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by always returning 1. + * This ensures that the total queue size is a count of the number of chunks in the queue. + */ + get size() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('size'); + } + return countSizeFunction; + } + } + Object.defineProperties(CountQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, { + value: 'CountQueuingStrategy', + configurable: true + }); + } + // Helper functions for the CountQueuingStrategy. + function countBrandCheckException(name) { + return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`); + } + function IsCountQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof CountQueuingStrategy; + } + + function convertTransformer(original, context) { + assertDictionary(original, context); + const cancel = original === null || original === void 0 ? void 0 : original.cancel; + const flush = original === null || original === void 0 ? void 0 : original.flush; + const readableType = original === null || original === void 0 ? void 0 : original.readableType; + const start = original === null || original === void 0 ? void 0 : original.start; + const transform = original === null || original === void 0 ? void 0 : original.transform; + const writableType = original === null || original === void 0 ? void 0 : original.writableType; + return { + cancel: cancel === undefined ? + undefined : + convertTransformerCancelCallback(cancel, original, `${context} has member 'cancel' that`), + flush: flush === undefined ? + undefined : + convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`), + readableType, + start: start === undefined ? + undefined : + convertTransformerStartCallback(start, original, `${context} has member 'start' that`), + transform: transform === undefined ? + undefined : + convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`), + writableType + }; + } + function convertTransformerFlushCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); + } + function convertTransformerStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertTransformerTransformCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); + } + function convertTransformerCancelCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); + } + + // Class TransformStream + /** + * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, + * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. + * In a manner specific to the transform stream in question, writes to the writable side result in new data being + * made available for reading from the readable side. + * + * @public + */ + class TransformStream { + constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) { + if (rawTransformer === undefined) { + rawTransformer = null; + } + const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter'); + const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter'); + const transformer = convertTransformer(rawTransformer, 'First parameter'); + if (transformer.readableType !== undefined) { + throw new RangeError('Invalid readableType specified'); + } + if (transformer.writableType !== undefined) { + throw new RangeError('Invalid writableType specified'); + } + const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); + const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); + const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); + const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); + let startPromise_resolve; + const startPromise = newPromise(resolve => { + startPromise_resolve = resolve; + }); + InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); + if (transformer.start !== undefined) { + startPromise_resolve(transformer.start(this._transformStreamController)); + } + else { + startPromise_resolve(undefined); + } + } + /** + * The readable side of the transform stream. + */ + get readable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('readable'); + } + return this._readable; + } + /** + * The writable side of the transform stream. + */ + get writable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('writable'); + } + return this._writable; + } + } + Object.defineProperties(TransformStream.prototype, { + readable: { enumerable: true }, + writable: { enumerable: true } + }); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, { + value: 'TransformStream', + configurable: true + }); + } + function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { + function startAlgorithm() { + return startPromise; + } + function writeAlgorithm(chunk) { + return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); + } + function abortAlgorithm(reason) { + return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); + } + function closeAlgorithm() { + return TransformStreamDefaultSinkCloseAlgorithm(stream); + } + stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); + function pullAlgorithm() { + return TransformStreamDefaultSourcePullAlgorithm(stream); + } + function cancelAlgorithm(reason) { + return TransformStreamDefaultSourceCancelAlgorithm(stream, reason); + } + stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure. + stream._backpressure = undefined; + stream._backpressureChangePromise = undefined; + stream._backpressureChangePromise_resolve = undefined; + TransformStreamSetBackpressure(stream, true); + stream._transformStreamController = undefined; + } + function IsTransformStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) { + return false; + } + return x instanceof TransformStream; + } + // This is a no-op if both sides are already errored. + function TransformStreamError(stream, e) { + ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e); + TransformStreamErrorWritableAndUnblockWrite(stream, e); + } + function TransformStreamErrorWritableAndUnblockWrite(stream, e) { + TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); + WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e); + TransformStreamUnblockWrite(stream); + } + function TransformStreamUnblockWrite(stream) { + if (stream._backpressure) { + // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure() + // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time + // _backpressure is set. + TransformStreamSetBackpressure(stream, false); + } + } + function TransformStreamSetBackpressure(stream, backpressure) { + // Passes also when called during construction. + if (stream._backpressureChangePromise !== undefined) { + stream._backpressureChangePromise_resolve(); + } + stream._backpressureChangePromise = newPromise(resolve => { + stream._backpressureChangePromise_resolve = resolve; + }); + stream._backpressure = backpressure; + } + // Class TransformStreamDefaultController + /** + * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. + * + * @public + */ + class TransformStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. + */ + get desiredSize() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('desiredSize'); + } + const readableController = this._controlledTransformStream._readable._readableStreamController; + return ReadableStreamDefaultControllerGetDesiredSize(readableController); + } + enqueue(chunk = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('enqueue'); + } + TransformStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors both the readable side and the writable side of the controlled transform stream, making all future + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. + */ + error(reason = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('error'); + } + TransformStreamDefaultControllerError(this, reason); + } + /** + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the + * transformer only needs to consume a portion of the chunks written to the writable side. + */ + terminate() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('terminate'); + } + TransformStreamDefaultControllerTerminate(this); + } + } + Object.defineProperties(TransformStreamDefaultController.prototype, { + enqueue: { enumerable: true }, + error: { enumerable: true }, + terminate: { enumerable: true }, + desiredSize: { enumerable: true } + }); + setFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue'); + setFunctionName(TransformStreamDefaultController.prototype.error, 'error'); + setFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, { + value: 'TransformStreamDefaultController', + configurable: true + }); + } + // Transform Stream Default Controller Abstract Operations + function IsTransformStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) { + return false; + } + return x instanceof TransformStreamDefaultController; + } + function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm) { + controller._controlledTransformStream = stream; + stream._transformStreamController = controller; + controller._transformAlgorithm = transformAlgorithm; + controller._flushAlgorithm = flushAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._finishPromise = undefined; + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; + } + function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { + const controller = Object.create(TransformStreamDefaultController.prototype); + let transformAlgorithm; + let flushAlgorithm; + let cancelAlgorithm; + if (transformer.transform !== undefined) { + transformAlgorithm = chunk => transformer.transform(chunk, controller); + } + else { + transformAlgorithm = chunk => { + try { + TransformStreamDefaultControllerEnqueue(controller, chunk); + return promiseResolvedWith(undefined); + } + catch (transformResultE) { + return promiseRejectedWith(transformResultE); + } + }; + } + if (transformer.flush !== undefined) { + flushAlgorithm = () => transformer.flush(controller); + } + else { + flushAlgorithm = () => promiseResolvedWith(undefined); + } + if (transformer.cancel !== undefined) { + cancelAlgorithm = reason => transformer.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm); + } + function TransformStreamDefaultControllerClearAlgorithms(controller) { + controller._transformAlgorithm = undefined; + controller._flushAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + } + function TransformStreamDefaultControllerEnqueue(controller, chunk) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { + throw new TypeError('Readable side is not in a state that permits enqueue'); + } + // We throttle transform invocations based on the backpressure of the ReadableStream, but we still + // accept TransformStreamDefaultControllerEnqueue() calls. + try { + ReadableStreamDefaultControllerEnqueue(readableController, chunk); + } + catch (e) { + // This happens when readableStrategy.size() throws. + TransformStreamErrorWritableAndUnblockWrite(stream, e); + throw stream._readable._storedError; + } + const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); + if (backpressure !== stream._backpressure) { + TransformStreamSetBackpressure(stream, true); + } + } + function TransformStreamDefaultControllerError(controller, e) { + TransformStreamError(controller._controlledTransformStream, e); + } + function TransformStreamDefaultControllerPerformTransform(controller, chunk) { + const transformPromise = controller._transformAlgorithm(chunk); + return transformPromiseWith(transformPromise, undefined, r => { + TransformStreamError(controller._controlledTransformStream, r); + throw r; + }); + } + function TransformStreamDefaultControllerTerminate(controller) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + ReadableStreamDefaultControllerClose(readableController); + const error = new TypeError('TransformStream terminated'); + TransformStreamErrorWritableAndUnblockWrite(stream, error); + } + // TransformStreamDefaultSink Algorithms + function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { + const controller = stream._transformStreamController; + if (stream._backpressure) { + const backpressureChangePromise = stream._backpressureChangePromise; + return transformPromiseWith(backpressureChangePromise, () => { + const writable = stream._writable; + const state = writable._state; + if (state === 'erroring') { + throw writable._storedError; + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + }); + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + } + function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + const readable = stream._readable; + // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally, + // we don't run the _cancelAlgorithm again. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, () => { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerError(readable._readableStreamController, reason); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; + } + function TransformStreamDefaultSinkCloseAlgorithm(stream) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + const readable = stream._readable; + // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally, + // we don't also run the _cancelAlgorithm. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const flushPromise = controller._flushAlgorithm(); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(flushPromise, () => { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerClose(readable._readableStreamController); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; + } + // TransformStreamDefaultSource Algorithms + function TransformStreamDefaultSourcePullAlgorithm(stream) { + // Invariant. Enforced by the promises returned by start() and pull(). + TransformStreamSetBackpressure(stream, false); + // Prevent the next pull() call until there is backpressure. + return stream._backpressureChangePromise; + } + function TransformStreamDefaultSourceCancelAlgorithm(stream, reason) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._writable cannot change after construction, so caching it across a call to user code is safe. + const writable = stream._writable; + // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or + // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the + // _flushAlgorithm. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, () => { + if (writable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, writable._storedError); + } + else { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; + } + // Helper functions for the TransformStreamDefaultController. + function defaultControllerBrandCheckException(name) { + return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`); + } + function defaultControllerFinishPromiseResolve(controller) { + if (controller._finishPromise_resolve === undefined) { + return; + } + controller._finishPromise_resolve(); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; + } + function defaultControllerFinishPromiseReject(controller, reason) { + if (controller._finishPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(controller._finishPromise); + controller._finishPromise_reject(reason); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; + } + // Helper functions for the TransformStream. + function streamBrandCheckException(name) { + return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`); + } + + const exports$1 = { + ReadableStream, + ReadableStreamDefaultController, + ReadableByteStreamController, + ReadableStreamBYOBRequest, + ReadableStreamDefaultReader, + ReadableStreamBYOBReader, + WritableStream, + WritableStreamDefaultController, + WritableStreamDefaultWriter, + ByteLengthQueuingStrategy, + CountQueuingStrategy, + TransformStream, + TransformStreamDefaultController + }; + // Add classes to global scope + if (typeof globals !== 'undefined') { + for (const prop in exports$1) { + if (Object.prototype.hasOwnProperty.call(exports$1, prop)) { + Object.defineProperty(globals, prop, { + value: exports$1[prop], + writable: true, + configurable: true + }); + } + } + } + + exports.ByteLengthQueuingStrategy = ByteLengthQueuingStrategy; + exports.CountQueuingStrategy = CountQueuingStrategy; + exports.ReadableByteStreamController = ReadableByteStreamController; + exports.ReadableStream = ReadableStream; + exports.ReadableStreamBYOBReader = ReadableStreamBYOBReader; + exports.ReadableStreamBYOBRequest = ReadableStreamBYOBRequest; + exports.ReadableStreamDefaultController = ReadableStreamDefaultController; + exports.ReadableStreamDefaultReader = ReadableStreamDefaultReader; + exports.TransformStream = TransformStream; + exports.TransformStreamDefaultController = TransformStreamDefaultController; + exports.WritableStream = WritableStream; + exports.WritableStreamDefaultController = WritableStreamDefaultController; + exports.WritableStreamDefaultWriter = WritableStreamDefaultWriter; + +})); +//# sourceMappingURL=polyfill.es6.js.map diff --git a/backend/node_modules/web-streams-polyfill/dist/polyfill.es6.js.map b/backend/node_modules/web-streams-polyfill/dist/polyfill.es6.js.map new file mode 100644 index 0000000000000000000000000000000000000000..1f20a0a20203788461c7ff9465e3b75a83d66488 --- /dev/null +++ b/backend/node_modules/web-streams-polyfill/dist/polyfill.es6.js.map @@ -0,0 +1 @@ +{"version":3,"file":"polyfill.es6.js","sources":["../src/utils.ts","../src/lib/helpers/miscellaneous.ts","../src/lib/helpers/webidl.ts","../src/lib/simple-queue.ts","../src/lib/abstract-ops/internal-methods.ts","../src/lib/readable-stream/generic-reader.ts","../src/stub/number-isfinite.ts","../src/stub/math-trunc.ts","../src/lib/validators/basic.ts","../src/lib/validators/readable-stream.ts","../src/lib/readable-stream/default-reader.ts","../node_modules/tslib/tslib.es6.js","../src/lib/abstract-ops/ecmascript.ts","../src/target/es5/stub/async-iterator-prototype.ts","../src/lib/readable-stream/async-iterator.ts","../src/stub/number-isnan.ts","../src/lib/abstract-ops/miscellaneous.ts","../src/lib/abstract-ops/queue-with-sizes.ts","../src/lib/helpers/array-buffer-view.ts","../src/lib/readable-stream/byte-stream-controller.ts","../src/lib/validators/reader-options.ts","../src/lib/readable-stream/byob-reader.ts","../src/lib/abstract-ops/queuing-strategy.ts","../src/lib/validators/queuing-strategy.ts","../src/lib/validators/underlying-sink.ts","../src/lib/validators/writable-stream.ts","../src/lib/abort-signal.ts","../src/lib/writable-stream.ts","../src/globals.ts","../src/stub/dom-exception.ts","../src/lib/readable-stream/pipe.ts","../src/lib/readable-stream/default-controller.ts","../src/lib/readable-stream/tee.ts","../src/lib/readable-stream/readable-stream-like.ts","../src/lib/readable-stream/from.ts","../src/lib/validators/underlying-source.ts","../src/lib/validators/iterator-options.ts","../src/lib/validators/pipe-options.ts","../src/lib/validators/readable-writable-pair.ts","../src/lib/readable-stream.ts","../src/lib/validators/queuing-strategy-init.ts","../src/lib/byte-length-queuing-strategy.ts","../src/lib/count-queuing-strategy.ts","../src/lib/validators/transformer.ts","../src/lib/transform-stream.ts","../src/polyfill.ts"],"sourcesContent":["export function noop(): undefined {\n return undefined;\n}\n","import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n\nexport function setFunctionName(fn: Function, name: string): void {\n try {\n Object.defineProperty(fn, 'name', {\n value: name,\n configurable: true\n });\n } catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n }\n}\n","import { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\n// https://webidl.spec.whatwg.org/#a-new-promise\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-resolved-with\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return newPromise(resolve => resolve(value));\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-rejected-with\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\n// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned\n// from that handler. To prevent this, return null instead of void from all handlers.\n// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => null | PromiseLike,\n onRejected?: (reason: any) => null | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => null | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => null | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nlet _queueMicrotask: (callback: () => void) => void = callback => {\n if (typeof queueMicrotask === 'function') {\n _queueMicrotask = queueMicrotask;\n } else {\n const resolvedPromise = promiseResolvedWith(undefined);\n _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb);\n }\n return _queueMicrotask(callback);\n};\n\nexport { _queueMicrotask as queueMicrotask };\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n","import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n","export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\nexport const ReleaseSteps = Symbol('[[ReleaseSteps]]');\n","import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, type ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\nimport { ReleaseSteps } from '../abstract-ops/internal-methods';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n assert(stream._reader === reader);\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n stream._readableStreamController[ReleaseSteps]();\n\n stream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n","import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n","import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamDefaultReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamDefaultReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\nexport function ReadableStreamDefaultReaderRelease(reader: ReadableStreamDefaultReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n}\n\nexport function ReadableStreamDefaultReaderErrorReadRequests(reader: ReadableStreamDefaultReader, e: any) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n","/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise, SuppressedError, Symbol */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\r\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\r\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\r\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\r\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\r\n var _, done = false;\r\n for (var i = decorators.length - 1; i >= 0; i--) {\r\n var context = {};\r\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\r\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\r\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\r\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\r\n if (kind === \"accessor\") {\r\n if (result === void 0) continue;\r\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\r\n if (_ = accept(result.get)) descriptor.get = _;\r\n if (_ = accept(result.set)) descriptor.set = _;\r\n if (_ = accept(result.init)) initializers.unshift(_);\r\n }\r\n else if (_ = accept(result)) {\r\n if (kind === \"field\") initializers.unshift(_);\r\n else descriptor[key] = _;\r\n }\r\n }\r\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\r\n done = true;\r\n};\r\n\r\nexport function __runInitializers(thisArg, initializers, value) {\r\n var useValue = arguments.length > 2;\r\n for (var i = 0; i < initializers.length; i++) {\r\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\r\n }\r\n return useValue ? value : void 0;\r\n};\r\n\r\nexport function __propKey(x) {\r\n return typeof x === \"symbol\" ? x : \"\".concat(x);\r\n};\r\n\r\nexport function __setFunctionName(f, name, prefix) {\r\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\r\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\r\n};\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n var desc = Object.getOwnPropertyDescriptor(m, k);\r\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\r\n desc = { enumerable: true, get: function() { return m[k]; } };\r\n }\r\n Object.defineProperty(o, k2, desc);\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\nexport function __classPrivateFieldIn(state, receiver) {\r\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\r\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\r\n}\r\n\r\nexport function __addDisposableResource(env, value, async) {\r\n if (value !== null && value !== void 0) {\r\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\r\n var dispose;\r\n if (async) {\r\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\r\n dispose = value[Symbol.asyncDispose];\r\n }\r\n if (dispose === void 0) {\r\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\r\n dispose = value[Symbol.dispose];\r\n }\r\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\r\n env.stack.push({ value: value, dispose: dispose, async: async });\r\n }\r\n else if (async) {\r\n env.stack.push({ async: true });\r\n }\r\n return value;\r\n}\r\n\r\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n};\r\n\r\nexport function __disposeResources(env) {\r\n function fail(e) {\r\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\r\n env.hasError = true;\r\n }\r\n function next() {\r\n while (env.stack.length) {\r\n var rec = env.stack.pop();\r\n try {\r\n var result = rec.dispose && rec.dispose.call(rec.value);\r\n if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\r\n }\r\n catch (e) {\r\n fail(e);\r\n }\r\n }\r\n if (env.hasError) throw env.error;\r\n }\r\n return next();\r\n}\r\n\r\nexport default {\r\n __extends: __extends,\r\n __assign: __assign,\r\n __rest: __rest,\r\n __decorate: __decorate,\r\n __param: __param,\r\n __metadata: __metadata,\r\n __awaiter: __awaiter,\r\n __generator: __generator,\r\n __createBinding: __createBinding,\r\n __exportStar: __exportStar,\r\n __values: __values,\r\n __read: __read,\r\n __spread: __spread,\r\n __spreadArrays: __spreadArrays,\r\n __spreadArray: __spreadArray,\r\n __await: __await,\r\n __asyncGenerator: __asyncGenerator,\r\n __asyncDelegator: __asyncDelegator,\r\n __asyncValues: __asyncValues,\r\n __makeTemplateObject: __makeTemplateObject,\r\n __importStar: __importStar,\r\n __importDefault: __importDefault,\r\n __classPrivateFieldGet: __classPrivateFieldGet,\r\n __classPrivateFieldSet: __classPrivateFieldSet,\r\n __classPrivateFieldIn: __classPrivateFieldIn,\r\n __addDisposableResource: __addDisposableResource,\r\n __disposeResources: __disposeResources,\r\n};\r\n","import { reflectCall } from 'lib/helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport assert from '../../stub/assert';\n\ndeclare global {\n interface ArrayBuffer {\n readonly detached: boolean;\n\n transfer(): ArrayBuffer;\n }\n\n function structuredClone(value: T, options: { transfer: ArrayBuffer[] }): T;\n}\n\nexport function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\nexport let TransferArrayBuffer = (O: ArrayBuffer): ArrayBuffer => {\n if (typeof O.transfer === 'function') {\n TransferArrayBuffer = buffer => buffer.transfer();\n } else if (typeof structuredClone === 'function') {\n TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] });\n } else {\n // Not implemented correctly\n TransferArrayBuffer = buffer => buffer;\n }\n return TransferArrayBuffer(O);\n};\n\nexport function CanTransferArrayBuffer(O: ArrayBuffer): boolean {\n return !IsDetachedBuffer(O);\n}\n\nexport let IsDetachedBuffer = (O: ArrayBuffer): boolean => {\n if (typeof O.detached === 'boolean') {\n IsDetachedBuffer = buffer => buffer.detached;\n } else {\n // Not implemented correctly\n IsDetachedBuffer = buffer => buffer.byteLength === 0;\n }\n return IsDetachedBuffer(O);\n};\n\nexport function ArrayBufferSlice(buffer: ArrayBuffer, begin: number, end: number): ArrayBuffer {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n\nexport type MethodName = {\n [P in keyof T]: T[P] extends Function | undefined ? P : never;\n}[keyof T];\n\nexport function GetMethod>(receiver: T, prop: K): T[K] | undefined {\n const func = receiver[prop];\n if (func === undefined || func === null) {\n return undefined;\n }\n if (typeof func !== 'function') {\n throw new TypeError(`${String(prop)} is not a function`);\n }\n return func;\n}\n\nexport interface SyncIteratorRecord {\n iterator: Iterator,\n nextMethod: Iterator['next'],\n done: boolean;\n}\n\nexport interface AsyncIteratorRecord {\n iterator: AsyncIterator,\n nextMethod: AsyncIterator['next'],\n done: boolean;\n}\n\nexport type SyncOrAsyncIteratorRecord = SyncIteratorRecord | AsyncIteratorRecord;\n\nexport function CreateAsyncFromSyncIterator(syncIteratorRecord: SyncIteratorRecord): AsyncIteratorRecord {\n // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%,\n // we use yield* inside an async generator function to achieve the same result.\n\n // Wrap the sync iterator inside a sync iterable, so we can use it with yield*.\n const syncIterable = {\n [Symbol.iterator]: () => syncIteratorRecord.iterator\n };\n // Create an async generator function and immediately invoke it.\n const asyncIterator = (async function* () {\n return yield* syncIterable;\n }());\n // Return as an async iterator record.\n const nextMethod = asyncIterator.next;\n return { iterator: asyncIterator, nextMethod, done: false };\n}\n\n// Aligns with core-js/modules/es.symbol.async-iterator.js\nexport const SymbolAsyncIterator: (typeof Symbol)['asyncIterator'] =\n Symbol.asyncIterator ??\n Symbol.for?.('Symbol.asyncIterator') ??\n '@@asyncIterator';\n\nexport type SyncOrAsyncIterable = Iterable | AsyncIterable;\nexport type SyncOrAsyncIteratorMethod = () => (Iterator | AsyncIterator);\n\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint: 'async',\n method?: SyncOrAsyncIteratorMethod\n): AsyncIteratorRecord;\nfunction GetIterator(\n obj: Iterable,\n hint: 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncIteratorRecord;\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint = 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncOrAsyncIteratorRecord {\n assert(hint === 'sync' || hint === 'async');\n if (method === undefined) {\n if (hint === 'async') {\n method = GetMethod(obj as AsyncIterable, SymbolAsyncIterator);\n if (method === undefined) {\n const syncMethod = GetMethod(obj as Iterable, Symbol.iterator);\n const syncIteratorRecord = GetIterator(obj as Iterable, 'sync', syncMethod);\n return CreateAsyncFromSyncIterator(syncIteratorRecord);\n }\n } else {\n method = GetMethod(obj as Iterable, Symbol.iterator);\n }\n }\n if (method === undefined) {\n throw new TypeError('The object is not iterable');\n }\n const iterator = reflectCall(method, obj, []);\n if (!typeIsObject(iterator)) {\n throw new TypeError('The iterator method must return an object');\n }\n const nextMethod = iterator.next;\n return { iterator, nextMethod, done: false } as SyncOrAsyncIteratorRecord;\n}\n\nexport { GetIterator };\n\nexport function IteratorNext(iteratorRecord: AsyncIteratorRecord): Promise> {\n const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []);\n if (!typeIsObject(result)) {\n throw new TypeError('The iterator.next() method must return an object');\n }\n return result;\n}\n\nexport function IteratorComplete(\n iterResult: IteratorResult\n): iterResult is IteratorReturnResult {\n assert(typeIsObject(iterResult));\n return Boolean(iterResult.done);\n}\n\nexport function IteratorValue(iterResult: IteratorYieldResult): T {\n assert(typeIsObject(iterResult));\n return iterResult.value;\n}\n","/// \n\nimport { SymbolAsyncIterator } from '../../../lib/abstract-ops/ecmascript';\n\n// We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it.\nexport const AsyncIteratorPrototype: AsyncIterable = {\n // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( )\n // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator\n [SymbolAsyncIterator](this: AsyncIterator) {\n return this;\n }\n};\nObject.defineProperty(AsyncIteratorPrototype, SymbolAsyncIterator, { enumerable: false });\n","/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadableStreamDefaultReadResult,\n type ReadRequest\n} from './default-reader';\nimport { ReadableStreamReaderGenericCancel, ReadableStreamReaderGenericRelease } from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterableIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ninterface ReadableStreamAsyncIteratorInstance extends ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nObject.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n","import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: NonShared): NonShared {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer) as NonShared;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n","export type TypedArray =\n | Int8Array\n | Uint8Array\n | Uint8ClampedArray\n | Int16Array\n | Uint16Array\n | Int32Array\n | Uint32Array\n | Float32Array\n | Float64Array;\n\nexport type NonShared = T & {\n buffer: ArrayBuffer;\n}\n\nexport interface ArrayBufferViewConstructor {\n new(buffer: ArrayBuffer, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n}\n\nexport interface TypedArrayConstructor extends ArrayBufferViewConstructor {\n readonly BYTES_PER_ELEMENT: number;\n}\n\nexport type DataViewConstructor = ArrayBufferViewConstructor;\n\nfunction isDataViewConstructor(ctor: Function): ctor is DataViewConstructor {\n return ctor === DataView;\n}\n\nexport function isDataView(view: ArrayBufferView): view is DataView {\n return isDataViewConstructor(view.constructor);\n}\n\nexport function arrayBufferViewElementSize(ctor: ArrayBufferViewConstructor): number {\n if (isDataViewConstructor(ctor)) {\n return 1;\n }\n return (ctor as unknown as TypedArrayConstructor).BYTES_PER_ELEMENT;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n IsReadableStreamDefaultReader,\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n type ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n type ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n type ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport type { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\nimport {\n type ArrayBufferViewConstructor,\n arrayBufferViewElementSize,\n type NonShared,\n type TypedArrayConstructor\n} from '../helpers/array-buffer-view';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: NonShared | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: NonShared): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond');\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBuffer;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor = NonShared> =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: TypedArrayConstructor;\n readerType: 'default' | 'none';\n}\n\ninterface BYOBPullIntoDescriptor = NonShared> {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob' | 'none';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: NonShared): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest>): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n minimumFill: 1,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n if (this._pendingPullIntos.length > 0) {\n const firstPullInto = this._pendingPullIntos.peek();\n firstPullInto.readerType = 'none';\n\n this._pendingPullIntos = new SimpleQueue();\n this._pendingPullIntos.push(firstPullInto);\n }\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableByteStreamController.prototype.close, 'close');\nsetFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableByteStreamController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor>(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n assert(pullIntoDescriptor.readerType !== 'none');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as NonShared, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor>(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n let clonedChunk;\n try {\n clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength);\n } catch (cloneE) {\n ReadableByteStreamControllerError(controller, cloneE);\n throw cloneE;\n }\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength);\n}\n\nfunction ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.readerType === 'none');\n if (firstDescriptor.bytesFilled > 0) {\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n firstDescriptor.buffer,\n firstDescriptor.byteOffset,\n firstDescriptor.bytesFilled\n );\n }\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize;\n const maxAlignedBytes = maxBytesFilled - remainderBytes;\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n assert(pullIntoDescriptor.readerType !== 'none');\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nfunction ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller: ReadableByteStreamController) {\n const reader = controller._controlledReadableByteStream._reader;\n assert(IsReadableStreamDefaultReader(reader));\n while (reader._readRequests.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n const readRequest = reader._readRequests.shift();\n ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest);\n }\n}\n\nexport function ReadableByteStreamControllerPullInto>(\n controller: ReadableByteStreamController,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n const elementSize = arrayBufferViewElementSize(ctor);\n\n const { byteOffset, byteLength } = view;\n\n const minimumFill = min * elementSize;\n assert(minimumFill >= elementSize && minimumFill <= byteLength);\n assert(minimumFill % elementSize === 0);\n\n let buffer: ArrayBuffer;\n try {\n buffer = TransferArrayBuffer(view.buffer);\n } catch (e) {\n readIntoRequest._errorSteps(e);\n return;\n }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset,\n byteLength,\n bytesFilled: 0,\n minimumFill,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled % firstDescriptor.elementSize === 0);\n\n if (firstDescriptor.readerType === 'none') {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n return;\n }\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) {\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n pullIntoDescriptor.buffer,\n end - remainderSize,\n remainderSize\n );\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(\n controller: ReadableByteStreamController,\n chunk: NonShared\n) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const { buffer, byteOffset, byteLength } = chunk;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n if (firstPendingPullInto.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto);\n }\n }\n\n if (ReadableStreamHasDefaultReader(stream)) {\n ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller);\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView as NonShared, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerFillReadRequestFromQueue(\n controller: ReadableByteStreamController,\n readRequest: ReadRequest>\n) {\n assert(controller._queueTotalSize > 0);\n\n const entry = controller._queue.shift();\n controller._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n readRequest._chunkSteps(view as NonShared);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view as NonShared);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: NonShared) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: NonShared) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n","import { assertDictionary, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n\nexport function convertByobReadOptions(\n options: ReadableStreamBYOBReaderReadOptions | null | undefined,\n context: string\n): ValidatedReadableStreamBYOBReaderReadOptions {\n assertDictionary(options, context);\n const min = options?.min ?? 1;\n return {\n min: convertUnsignedLongLongWithEnforceRange(\n min,\n `${context} has member 'min' that`\n )\n };\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, type ReadableByteStream, type ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from './reader-options';\nimport { convertByobReadOptions } from '../validators/reader-options';\nimport { isDataView, type NonShared, type TypedArray } from '../helpers/array-buffer-view';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream as ReadableStream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest>(\n stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest\n): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest> {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(\n view: T,\n options?: ReadableStreamBYOBReaderReadOptions\n ): Promise>;\n read>(\n view: T,\n rawOptions: ReadableStreamBYOBReaderReadOptions | null | undefined = {}\n ): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n let options: ValidatedReadableStreamBYOBReaderReadOptions;\n try {\n options = convertByobReadOptions(rawOptions, 'options');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const min = options.min;\n if (min === 0) {\n return promiseRejectedWith(new TypeError('options.min must be greater than 0'));\n }\n if (!isDataView(view)) {\n if (min > (view as unknown as TypedArray).length) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s length'));\n }\n } else if (min > view.byteLength) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s byteLength'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamBYOBReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamBYOBReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead>(\n reader: ReadableStreamBYOBReader,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n min,\n readIntoRequest\n );\n }\n}\n\nexport function ReadableStreamBYOBReaderRelease(reader: ReadableStreamBYOBReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n}\n\nexport function ReadableStreamBYOBReaderErrorReadIntoRequests(reader: ReadableStreamBYOBReader, e: any) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n","/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * If aborted, returns the reason for aborting.\n */\n readonly reason?: any;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(reason?: any): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n type QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { type AbortController, type AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(WritableStream.prototype.abort, 'abort');\nsetFunctionName(WritableStream.prototype.close, 'close');\nsetFunctionName(WritableStream.prototype.getWriter, 'getWriter');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight\n};\n\nexport type {\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort(reason);\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nsetFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort');\nsetFunctionName(WritableStreamDefaultWriter.prototype.close, 'close');\nsetFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock');\nsetFunctionName(WritableStreamDefaultWriter.prototype.write, 'write');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n return null;\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let writeAlgorithm: (chunk: W) => Promise;\n let closeAlgorithm: () => Promise;\n let abortAlgorithm: (reason: any) => Promise;\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n } else {\n writeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n } else {\n closeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n } else {\n abortAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n return null;\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n","/// \n\nfunction getGlobals(): typeof globalThis | undefined {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n } else if (typeof self !== 'undefined') {\n return self;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n","/// \nimport { globals } from '../globals';\nimport { setFunctionName } from '../lib/helpers/miscellaneous';\n\ninterface DOMException extends Error {\n name: string;\n message: string;\n}\n\ntype DOMExceptionConstructor = new (message?: string, name?: string) => DOMException;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n if ((ctor as DOMExceptionConstructor).name !== 'DOMException') {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Support:\n * - Web browsers\n * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87)\n */\nfunction getFromGlobal(): DOMExceptionConstructor | undefined {\n const ctor = globals?.DOMException;\n return isDOMExceptionConstructor(ctor) ? ctor : undefined;\n}\n\n/**\n * Support:\n * - All platforms\n */\nfunction createPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line @typescript-eslint/no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n setFunctionName(ctor, 'DOMException');\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nconst DOMException: DOMExceptionConstructor = getFromGlobal() || createPolyfill();\n\nexport { DOMException };\n","import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n return null;\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => null) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => null) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest(): null {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n return null;\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any): null {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n\n return null;\n }\n });\n}\n","import type { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, type QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n type ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport type { ValidatedUnderlyingSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n // Do nothing.\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultController.prototype.close, 'close');\nsetFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableStreamDefaultController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n","import {\n CreateReadableByteStream,\n CreateReadableStream,\n type DefaultReadableStream,\n IsReadableStream,\n type ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n type ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n type ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(\n stream: ReadableStream,\n cloneForBranch2: boolean\n): [DefaultReadableStream, DefaultReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: DefaultReadableStream;\n let branch2: DefaultReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader> = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader>) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return null;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: NonShared, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader>(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n","import { typeIsObject } from '../helpers/miscellaneous';\nimport type { ReadableStreamDefaultReadResult } from './default-reader';\n\n/**\n * A common interface for a `ReadadableStream` implementation.\n *\n * @public\n */\nexport interface ReadableStreamLike {\n readonly locked: boolean;\n\n getReader(): ReadableStreamDefaultReaderLike;\n}\n\n/**\n * A common interface for a `ReadableStreamDefaultReader` implementation.\n *\n * @public\n */\nexport interface ReadableStreamDefaultReaderLike {\n readonly closed: Promise;\n\n cancel(reason?: any): Promise;\n\n read(): Promise>;\n\n releaseLock(): void;\n}\n\nexport function isReadableStreamLike(stream: unknown): stream is ReadableStreamLike {\n return typeIsObject(stream) && typeof (stream as ReadableStreamLike).getReader !== 'undefined';\n}\n","import { CreateReadableStream, type DefaultReadableStream } from '../readable-stream';\nimport {\n isReadableStreamLike,\n type ReadableStreamDefaultReaderLike,\n type ReadableStreamLike\n} from './readable-stream-like';\nimport { ReadableStreamDefaultControllerClose, ReadableStreamDefaultControllerEnqueue } from './default-controller';\nimport { GetIterator, GetMethod, IteratorComplete, IteratorNext, IteratorValue } from '../abstract-ops/ecmascript';\nimport { promiseRejectedWith, promiseResolvedWith, reflectCall, transformPromiseWith } from '../helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { noop } from '../../utils';\n\nexport function ReadableStreamFrom(\n source: Iterable | AsyncIterable | ReadableStreamLike\n): DefaultReadableStream {\n if (isReadableStreamLike(source)) {\n return ReadableStreamFromDefaultReader(source.getReader());\n }\n return ReadableStreamFromIterable(source);\n}\n\nexport function ReadableStreamFromIterable(asyncIterable: Iterable | AsyncIterable): DefaultReadableStream {\n let stream: DefaultReadableStream;\n const iteratorRecord = GetIterator(asyncIterable, 'async');\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let nextResult;\n try {\n nextResult = IteratorNext(iteratorRecord);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const nextPromise = promiseResolvedWith(nextResult);\n return transformPromiseWith(nextPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object');\n }\n const done = IteratorComplete(iterResult);\n if (done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = IteratorValue(iterResult);\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n const iterator = iteratorRecord.iterator;\n let returnMethod: (typeof iterator)['return'] | undefined;\n try {\n returnMethod = GetMethod(iterator, 'return');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n if (returnMethod === undefined) {\n return promiseResolvedWith(undefined);\n }\n let returnResult: IteratorResult | Promise>;\n try {\n returnResult = reflectCall(returnMethod, iterator, [reason]);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const returnPromise = promiseResolvedWith(returnResult);\n return transformPromiseWith(returnPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object');\n }\n return undefined;\n });\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n\nexport function ReadableStreamFromDefaultReader(\n reader: ReadableStreamDefaultReaderLike\n): DefaultReadableStream {\n let stream: DefaultReadableStream;\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let readPromise;\n try {\n readPromise = reader.read();\n } catch (e) {\n return promiseRejectedWith(e);\n }\n return transformPromiseWith(readPromise, readResult => {\n if (!typeIsObject(readResult)) {\n throw new TypeError('The promise returned by the reader.read() method must fulfill with an object');\n }\n if (readResult.done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = readResult.value;\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n try {\n return promiseResolvedWith(reader.cancel(reason));\n } catch (e) {\n return promiseRejectedWith(e);\n }\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n","import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n","import { assertDictionary } from './basic';\nimport type {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n","import { assertDictionary } from './basic';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n","import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n","import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, type ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderErrorReadRequests,\n type ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReaderErrorReadIntoRequests,\n type ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { ReadableStreamFrom } from './readable-stream/from';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport type {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList, SymbolAsyncIterator } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions\n} from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport type { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport type { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\nimport type { ReadableStreamDefaultReaderLike, ReadableStreamLike } from './readable-stream/readable-stream-like';\nimport type { NonShared } from './helpers/array-buffer-view';\n\nexport type DefaultReadableStream = ReadableStream & {\n _readableStreamController: ReadableStreamDefaultController\n};\n\nexport type ReadableByteStream = ReadableStream> & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream implements AsyncIterable {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n\n [SymbolAsyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator {\n // Stub implementation, overridden below\n return this.values(options);\n }\n\n /**\n * Creates a new ReadableStream wrapping the provided iterable or async iterable.\n *\n * This can be used to adapt various kinds of objects into a readable stream,\n * such as an array, an async generator, or a Node.js readable stream.\n */\n static from(asyncIterable: Iterable | AsyncIterable | ReadableStreamLike): ReadableStream {\n return ReadableStreamFrom(asyncIterable);\n }\n}\n\nObject.defineProperties(ReadableStream, {\n from: { enumerable: true }\n});\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(ReadableStream.from, 'from');\nsetFunctionName(ReadableStream.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStream.prototype.getReader, 'getReader');\nsetFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough');\nsetFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo');\nsetFunctionName(ReadableStream.prototype.tee, 'tee');\nsetFunctionName(ReadableStream.prototype.values, 'values');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nObject.defineProperty(ReadableStream.prototype, SymbolAsyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n});\n\nexport type {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n ReadableStreamBYOBReaderReadOptions,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions,\n ReadableStreamLike,\n ReadableStreamDefaultReaderLike\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1\n): DefaultReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: DefaultReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n","import type { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\nsetFunctionName(byteLengthSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\nsetFunctionName(countSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const cancel = original?.cancel;\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n cancel: cancel === undefined ?\n undefined :\n convertTransformerCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n\nfunction convertTransformerCancelCallback(\n fn: TransformerCancelCallback,\n original: Transformer,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith,\n uponPromise\n} from './helpers/webidl';\nimport { CreateReadableStream, type DefaultReadableStream, ReadableStream } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: DefaultReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport type {\n Transformer,\n TransformerCancelCallback,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSourceCancelAlgorithm(stream, reason);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n TransformStreamUnblockWrite(stream);\n}\n\nfunction TransformStreamUnblockWrite(stream: TransformStream) {\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _finishPromise: Promise | undefined;\n /** @internal */\n _finishPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _finishPromise_reject?: (reason: any) => void;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n /** @internal */\n _cancelAlgorithm: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(TransformStreamDefaultController.prototype.error, 'error');\nsetFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._finishPromise = undefined;\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm: (chunk: I) => Promise;\n let flushAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n } else {\n transformAlgorithm = chunk => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n }\n\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n } else {\n flushAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n if (transformer.cancel !== undefined) {\n cancelAlgorithm = reason => transformer.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally,\n // we don't run the _cancelAlgorithm again.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerError(readable._readableStreamController, reason);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally,\n // we don't also run the _cancelAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(flushPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerClose(readable._readableStreamController);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\nfunction TransformStreamDefaultSourceCancelAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._writable cannot change after construction, so caching it across a call to user code is safe.\n const writable = stream._writable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or\n // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the\n // _flushAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (writable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, writable._storedError);\n } else {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\nexport function defaultControllerFinishPromiseResolve(controller: TransformStreamDefaultController) {\n if (controller._finishPromise_resolve === undefined) {\n return;\n }\n\n controller._finishPromise_resolve();\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nexport function defaultControllerFinishPromiseReject(controller: TransformStreamDefaultController, reason: any) {\n if (controller._finishPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(controller._finishPromise!);\n controller._finishPromise_reject(reason);\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n","import {\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n ReadableByteStreamController,\n ReadableStream,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultController,\n ReadableStreamDefaultReader,\n TransformStream,\n TransformStreamDefaultController,\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter\n} from './ponyfill';\nimport { globals } from './globals';\n\n// Export\nexport * from './ponyfill';\n\nconst exports = {\n ReadableStream,\n ReadableStreamDefaultController,\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader,\n\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter,\n\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n\n TransformStream,\n TransformStreamDefaultController\n};\n\n// Add classes to global scope\nif (typeof globals !== 'undefined') {\n for (const prop in exports) {\n if (Object.prototype.hasOwnProperty.call(exports, prop)) {\n Object.defineProperty(globals, prop, {\n value: exports[prop as (keyof typeof exports)],\n writable: true,\n configurable: true\n });\n }\n }\n}\n"],"names":["queueMicrotask","streamBrandCheckException","defaultControllerBrandCheckException","exports"],"mappings":";;;;;;;;;;;;;aAAgB,IAAI,GAAA;IAClB,IAAA,OAAO,SAAS,CAAC;IACnB;;ICCM,SAAU,YAAY,CAAC,CAAM,EAAA;IACjC,IAAA,OAAO,CAAC,OAAO,CAAC,KAAK,QAAQ,IAAI,CAAC,KAAK,IAAI,KAAK,OAAO,CAAC,KAAK,UAAU,CAAC;IAC1E,CAAC;IAEM,MAAM,8BAA8B,GAUrC,IAAI,CAAC;IAEK,SAAA,eAAe,CAAC,EAAY,EAAE,IAAY,EAAA;IACxD,IAAA,IAAI;IACF,QAAA,MAAM,CAAC,cAAc,CAAC,EAAE,EAAE,MAAM,EAAE;IAChC,YAAA,KAAK,EAAE,IAAI;IACX,YAAA,YAAY,EAAE,IAAI;IACnB,SAAA,CAAC,CAAC;SACJ;IAAC,IAAA,OAAA,EAAA,EAAM;;;SAGP;IACH;;IC1BA,MAAM,eAAe,GAAG,OAAO,CAAC;IAChC,MAAM,mBAAmB,GAAG,OAAO,CAAC,SAAS,CAAC,IAAI,CAAC;IACnD,MAAM,qBAAqB,GAAG,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC;IAEnE;IACM,SAAU,UAAU,CAAI,QAGrB,EAAA;IACP,IAAA,OAAO,IAAI,eAAe,CAAC,QAAQ,CAAC,CAAC;IACvC,CAAC;IAED;IACM,SAAU,mBAAmB,CAAI,KAAyB,EAAA;QAC9D,OAAO,UAAU,CAAC,OAAO,IAAI,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC;IAC/C,CAAC;IAED;IACM,SAAU,mBAAmB,CAAY,MAAW,EAAA;IACxD,IAAA,OAAO,qBAAqB,CAAC,MAAM,CAAC,CAAC;IACvC,CAAC;aAEe,kBAAkB,CAChC,OAAmB,EACnB,WAA4D,EAC5D,UAA8D,EAA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A,SAAO,EAAE,IAAI,CAAC,EAAE;IACvD,YAAA,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,IAAI,EAAE;IACnC,gBAAA,KAAK,EAAEA,SAAO,CAAC,IAA8B,CAAC;IAC9C,gBAAA,QAAQ,EAAE,IAAI;IACd,gBAAA,YAAY,EAAE,IAAI;IACnB,aAAA,CAAC,CAAC;aACJ;SACF;IACH;;;;;;;;;;;;;;;;;;;;","x_google_ignoreList":[11]} \ No newline at end of file diff --git a/backend/node_modules/web-streams-polyfill/dist/polyfill.es6.min.js b/backend/node_modules/web-streams-polyfill/dist/polyfill.es6.min.js new file mode 100644 index 0000000000000000000000000000000000000000..daaa95c3f85a71475b373fa4f7cfd4e432c82e85 --- /dev/null +++ b/backend/node_modules/web-streams-polyfill/dist/polyfill.es6.min.js @@ -0,0 +1,9 @@ +/** + * @license + * web-streams-polyfill v3.3.3 + * Copyright 2024 Mattias Buelens, Diwank Singh Tomer and other contributors. + * This code is released under the MIT license. + * SPDX-License-Identifier: MIT + */ +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).WebStreamsPolyfill={})}(this,(function(e){"use strict";function t(){}function r(e){return"object"==typeof e&&null!==e||"function"==typeof e}const o=t;function n(e,t){try{Object.defineProperty(e,"name",{value:t,configurable:!0})}catch(e){}}const a=Promise,i=Promise.prototype.then,l=Promise.reject.bind(a);function s(e){return new a(e)}function u(e){return s((t=>t(e)))}function c(e){return l(e)}function d(e,t,r){return i.call(e,t,r)}function f(e,t,r){d(d(e,t,r),void 0,o)}function b(e,t){f(e,t)}function m(e,t){f(e,void 0,t)}function h(e,t,r){return d(e,t,r)}function _(e){d(e,void 0,o)}let p=e=>{if("function"==typeof queueMicrotask)p=queueMicrotask;else{const e=u(void 0);p=t=>d(e,t)}return p(e)};function y(e,t,r){if("function"!=typeof e)throw new TypeError("Argument is not a function");return Function.prototype.apply.call(e,t,r)}function S(e,t,r){try{return u(y(e,t,r))}catch(e){return c(e)}}class g{constructor(){this._cursor=0,this._size=0,this._front={_elements:[],_next:void 0},this._back=this._front,this._cursor=0,this._size=0}get length(){return this._size}push(e){const t=this._back;let r=t;16383===t._elements.length&&(r={_elements:[],_next:void 0}),t._elements.push(e),r!==t&&(this._back=r,t._next=r),++this._size}shift(){const e=this._front;let t=e;const r=this._cursor;let o=r+1;const n=e._elements,a=n[r];return 16384===o&&(t=e._next,o=0),--this._size,this._cursor=o,e!==t&&(this._front=t),n[r]=void 0,a}forEach(e){let t=this._cursor,r=this._front,o=r._elements;for(;!(t===o.length&&void 0===r._next||t===o.length&&(r=r._next,o=r._elements,t=0,0===o.length));)e(o[t]),++t}peek(){const e=this._front,t=this._cursor;return e._elements[t]}}const v=Symbol("[[AbortSteps]]"),w=Symbol("[[ErrorSteps]]"),R=Symbol("[[CancelSteps]]"),T=Symbol("[[PullSteps]]"),C=Symbol("[[ReleaseSteps]]");function P(e,t){e._ownerReadableStream=t,t._reader=e,"readable"===t._state?B(e):"closed"===t._state?function(e){B(e),k(e)}(e):O(e,t._storedError)}function q(e,t){return kr(e._ownerReadableStream,t)}function E(e){const t=e._ownerReadableStream;"readable"===t._state?j(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):function(e,t){O(e,t)}(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),t._readableStreamController[C](),t._reader=void 0,e._ownerReadableStream=void 0}function W(e){return new TypeError("Cannot "+e+" a stream using a released reader")}function B(e){e._closedPromise=s(((t,r)=>{e._closedPromise_resolve=t,e._closedPromise_reject=r}))}function O(e,t){B(e),j(e,t)}function j(e,t){void 0!==e._closedPromise_reject&&(_(e._closedPromise),e._closedPromise_reject(t),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}function k(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}const A=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},D=Math.trunc||function(e){return e<0?Math.ceil(e):Math.floor(e)};function z(e,t){if(void 0!==e&&("object"!=typeof(r=e)&&"function"!=typeof r))throw new TypeError(`${t} is not an object.`);var r}function I(e,t){if("function"!=typeof e)throw new TypeError(`${t} is not a function.`)}function L(e,t){if(!function(e){return"object"==typeof e&&null!==e||"function"==typeof e}(e))throw new TypeError(`${t} is not an object.`)}function F(e,t,r){if(void 0===e)throw new TypeError(`Parameter ${t} is required in '${r}'.`)}function $(e,t,r){if(void 0===e)throw new TypeError(`${t} is required in '${r}'.`)}function M(e){return Number(e)}function Y(e){return 0===e?0:e}function x(e,t){const r=Number.MAX_SAFE_INTEGER;let o=Number(e);if(o=Y(o),!A(o))throw new TypeError(`${t} is not a finite number`);if(o=function(e){return Y(D(e))}(o),o<0||o>r)throw new TypeError(`${t} is outside the accepted range of 0 to ${r}, inclusive`);return A(o)&&0!==o?o:0}function Q(e,t){if(!Or(e))throw new TypeError(`${t} is not a ReadableStream.`)}function N(e){return new ReadableStreamDefaultReader(e)}function H(e,t){e._reader._readRequests.push(t)}function V(e,t,r){const o=e._reader._readRequests.shift();r?o._closeSteps():o._chunkSteps(t)}function U(e){return e._reader._readRequests.length}function G(e){const t=e._reader;return void 0!==t&&!!X(t)}class ReadableStreamDefaultReader{constructor(e){if(F(e,1,"ReadableStreamDefaultReader"),Q(e,"First parameter"),jr(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");P(this,e),this._readRequests=new g}get closed(){return X(this)?this._closedPromise:c(Z("closed"))}cancel(e=void 0){return X(this)?void 0===this._ownerReadableStream?c(W("cancel")):q(this,e):c(Z("cancel"))}read(){if(!X(this))return c(Z("read"));if(void 0===this._ownerReadableStream)return c(W("read from"));let e,t;const r=s(((r,o)=>{e=r,t=o}));return J(this,{_chunkSteps:t=>e({value:t,done:!1}),_closeSteps:()=>e({value:void 0,done:!0}),_errorSteps:e=>t(e)}),r}releaseLock(){if(!X(this))throw Z("releaseLock");void 0!==this._ownerReadableStream&&function(e){E(e);const t=new TypeError("Reader was released");K(e,t)}(this)}}function X(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readRequests")&&e instanceof ReadableStreamDefaultReader)}function J(e,t){const r=e._ownerReadableStream;r._disturbed=!0,"closed"===r._state?t._closeSteps():"errored"===r._state?t._errorSteps(r._storedError):r._readableStreamController[T](t)}function K(e,t){const r=e._readRequests;e._readRequests=new g,r.forEach((e=>{e._errorSteps(t)}))}function Z(e){return new TypeError(`ReadableStreamDefaultReader.prototype.${e} can only be used on a ReadableStreamDefaultReader`)}function ee(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],o=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&o>=e.length&&(e=void 0),{value:e&&e[o++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function te(e){return this instanceof te?(this.v=e,this):new te(e)}function re(e,t,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var o,n=r.apply(e,t||[]),a=[];return o={},i("next"),i("throw"),i("return"),o[Symbol.asyncIterator]=function(){return this},o;function i(e){n[e]&&(o[e]=function(t){return new Promise((function(r,o){a.push([e,t,r,o])>1||l(e,t)}))})}function l(e,t){try{(r=n[e](t)).value instanceof te?Promise.resolve(r.value.v).then(s,u):c(a[0][2],r)}catch(e){c(a[0][3],e)}var r}function s(e){l("next",e)}function u(e){l("throw",e)}function c(e,t){e(t),a.shift(),a.length&&l(a[0][0],a[0][1])}}function oe(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e=ee(e),t={},o("next"),o("throw"),o("return"),t[Symbol.asyncIterator]=function(){return this},t);function o(r){t[r]=e[r]&&function(t){return new Promise((function(o,n){(function(e,t,r,o){Promise.resolve(o).then((function(t){e({value:t,done:r})}),t)})(o,n,(t=e[r](t)).done,t.value)}))}}}var ne,ae,ie;function le(e){return e.slice()}function se(e,t,r,o,n){new Uint8Array(e).set(new Uint8Array(r,o,n),t)}Object.defineProperties(ReadableStreamDefaultReader.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),n(ReadableStreamDefaultReader.prototype.cancel,"cancel"),n(ReadableStreamDefaultReader.prototype.read,"read"),n(ReadableStreamDefaultReader.prototype.releaseLock,"releaseLock"),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(ReadableStreamDefaultReader.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0}),"function"==typeof SuppressedError&&SuppressedError;let ue=e=>(ue="function"==typeof e.transfer?e=>e.transfer():"function"==typeof structuredClone?e=>structuredClone(e,{transfer:[e]}):e=>e,ue(e)),ce=e=>(ce="boolean"==typeof e.detached?e=>e.detached:e=>0===e.byteLength,ce(e));function de(e,t,r){if(e.slice)return e.slice(t,r);const o=r-t,n=new ArrayBuffer(o);return se(n,0,e,t,o),n}function fe(e,t){const r=e[t];if(null!=r){if("function"!=typeof r)throw new TypeError(`${String(t)} is not a function`);return r}}function be(e){const t={[Symbol.iterator]:()=>e.iterator},r=function(){return re(this,arguments,(function*(){return yield te(yield te(yield*function(e){var t,r;return t={},o("next"),o("throw",(function(e){throw e})),o("return"),t[Symbol.iterator]=function(){return this},t;function o(o,n){t[o]=e[o]?function(t){return(r=!r)?{value:te(e[o](t)),done:!1}:n?n(t):t}:n}}(oe(t))))}))}();return{iterator:r,nextMethod:r.next,done:!1}}const me=null!==(ie=null!==(ne=Symbol.asyncIterator)&&void 0!==ne?ne:null===(ae=Symbol.for)||void 0===ae?void 0:ae.call(Symbol,"Symbol.asyncIterator"))&&void 0!==ie?ie:"@@asyncIterator";function he(e,t="sync",o){if(void 0===o)if("async"===t){if(void 0===(o=fe(e,me))){return be(he(e,"sync",fe(e,Symbol.iterator)))}}else o=fe(e,Symbol.iterator);if(void 0===o)throw new TypeError("The object is not iterable");const n=y(o,e,[]);if(!r(n))throw new TypeError("The iterator method must return an object");return{iterator:n,nextMethod:n.next,done:!1}}const _e={[me](){return this}};Object.defineProperty(_e,me,{enumerable:!1});class pe{constructor(e,t){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=e,this._preventCancel=t}next(){const e=()=>this._nextSteps();return this._ongoingPromise=this._ongoingPromise?h(this._ongoingPromise,e,e):e(),this._ongoingPromise}return(e){const t=()=>this._returnSteps(e);return this._ongoingPromise?h(this._ongoingPromise,t,t):t()}_nextSteps(){if(this._isFinished)return Promise.resolve({value:void 0,done:!0});const e=this._reader;let t,r;const o=s(((e,o)=>{t=e,r=o}));return J(e,{_chunkSteps:e=>{this._ongoingPromise=void 0,p((()=>t({value:e,done:!1})))},_closeSteps:()=>{this._ongoingPromise=void 0,this._isFinished=!0,E(e),t({value:void 0,done:!0})},_errorSteps:t=>{this._ongoingPromise=void 0,this._isFinished=!0,E(e),r(t)}}),o}_returnSteps(e){if(this._isFinished)return Promise.resolve({value:e,done:!0});this._isFinished=!0;const t=this._reader;if(!this._preventCancel){const r=q(t,e);return E(t),h(r,(()=>({value:e,done:!0})))}return E(t),u({value:e,done:!0})}}const ye={next(){return Se(this)?this._asyncIteratorImpl.next():c(ge("next"))},return(e){return Se(this)?this._asyncIteratorImpl.return(e):c(ge("return"))}};function Se(e){if(!r(e))return!1;if(!Object.prototype.hasOwnProperty.call(e,"_asyncIteratorImpl"))return!1;try{return e._asyncIteratorImpl instanceof pe}catch(e){return!1}}function ge(e){return new TypeError(`ReadableStreamAsyncIterator.${e} can only be used on a ReadableSteamAsyncIterator`)}Object.setPrototypeOf(ye,_e);const ve=Number.isNaN||function(e){return e!=e};function we(e){const t=de(e.buffer,e.byteOffset,e.byteOffset+e.byteLength);return new Uint8Array(t)}function Re(e){const t=e._queue.shift();return e._queueTotalSize-=t.size,e._queueTotalSize<0&&(e._queueTotalSize=0),t.value}function Te(e,t,r){if("number"!=typeof(o=r)||ve(o)||o<0||r===1/0)throw new RangeError("Size must be a finite, non-NaN, non-negative number.");var o;e._queue.push({value:t,size:r}),e._queueTotalSize+=r}function Ce(e){e._queue=new g,e._queueTotalSize=0}function Pe(e){return e===DataView}class ReadableStreamBYOBRequest{constructor(){throw new TypeError("Illegal constructor")}get view(){if(!Ee(this))throw et("view");return this._view}respond(e){if(!Ee(this))throw et("respond");if(F(e,1,"respond"),e=x(e,"First parameter"),void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");if(ce(this._view.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be used as a response");Je(this._associatedReadableByteStreamController,e)}respondWithNewView(e){if(!Ee(this))throw et("respondWithNewView");if(F(e,1,"respondWithNewView"),!ArrayBuffer.isView(e))throw new TypeError("You can only respond with array buffer views");if(void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");if(ce(e.buffer))throw new TypeError("The given view's buffer has been detached and so cannot be used as a response");Ke(this._associatedReadableByteStreamController,e)}}Object.defineProperties(ReadableStreamBYOBRequest.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),n(ReadableStreamBYOBRequest.prototype.respond,"respond"),n(ReadableStreamBYOBRequest.prototype.respondWithNewView,"respondWithNewView"),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(ReadableStreamBYOBRequest.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});class ReadableByteStreamController{constructor(){throw new TypeError("Illegal constructor")}get byobRequest(){if(!qe(this))throw tt("byobRequest");return Ge(this)}get desiredSize(){if(!qe(this))throw tt("desiredSize");return Xe(this)}close(){if(!qe(this))throw tt("close");if(this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");const e=this._controlledReadableByteStream._state;if("readable"!==e)throw new TypeError(`The stream (in ${e} state) is not in the readable state and cannot be closed`);Ne(this)}enqueue(e){if(!qe(this))throw tt("enqueue");if(F(e,1,"enqueue"),!ArrayBuffer.isView(e))throw new TypeError("chunk must be an array buffer view");if(0===e.byteLength)throw new TypeError("chunk must have non-zero byteLength");if(0===e.buffer.byteLength)throw new TypeError("chunk's buffer must have non-zero byteLength");if(this._closeRequested)throw new TypeError("stream is closed or draining");const t=this._controlledReadableByteStream._state;if("readable"!==t)throw new TypeError(`The stream (in ${t} state) is not in the readable state and cannot be enqueued to`);He(this,e)}error(e=void 0){if(!qe(this))throw tt("error");Ve(this,e)}[R](e){Be(this),Ce(this);const t=this._cancelAlgorithm(e);return Qe(this),t}[T](e){const t=this._controlledReadableByteStream;if(this._queueTotalSize>0)return void Ue(this,e);const r=this._autoAllocateChunkSize;if(void 0!==r){let t;try{t=new ArrayBuffer(r)}catch(t){return void e._errorSteps(t)}const o={buffer:t,bufferByteLength:r,byteOffset:0,byteLength:r,bytesFilled:0,minimumFill:1,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(o)}H(t,e),We(this)}[C](){if(this._pendingPullIntos.length>0){const e=this._pendingPullIntos.peek();e.readerType="none",this._pendingPullIntos=new g,this._pendingPullIntos.push(e)}}}function qe(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableByteStream")&&e instanceof ReadableByteStreamController)}function Ee(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_associatedReadableByteStreamController")&&e instanceof ReadableStreamBYOBRequest)}function We(e){const t=function(e){const t=e._controlledReadableByteStream;if("readable"!==t._state)return!1;if(e._closeRequested)return!1;if(!e._started)return!1;if(G(t)&&U(t)>0)return!0;if(it(t)&&at(t)>0)return!0;const r=Xe(e);if(r>0)return!0;return!1}(e);if(!t)return;if(e._pulling)return void(e._pullAgain=!0);e._pulling=!0;f(e._pullAlgorithm(),(()=>(e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,We(e)),null)),(t=>(Ve(e,t),null)))}function Be(e){Fe(e),e._pendingPullIntos=new g}function Oe(e,t){let r=!1;"closed"===e._state&&(r=!0);const o=je(t);"default"===t.readerType?V(e,o,r):function(e,t,r){const o=e._reader,n=o._readIntoRequests.shift();r?n._closeSteps(t):n._chunkSteps(t)}(e,o,r)}function je(e){const t=e.bytesFilled,r=e.elementSize;return new e.viewConstructor(e.buffer,e.byteOffset,t/r)}function ke(e,t,r,o){e._queue.push({buffer:t,byteOffset:r,byteLength:o}),e._queueTotalSize+=o}function Ae(e,t,r,o){let n;try{n=de(t,r,r+o)}catch(t){throw Ve(e,t),t}ke(e,n,0,o)}function De(e,t){t.bytesFilled>0&&Ae(e,t.buffer,t.byteOffset,t.bytesFilled),xe(e)}function ze(e,t){const r=Math.min(e._queueTotalSize,t.byteLength-t.bytesFilled),o=t.bytesFilled+r;let n=r,a=!1;const i=o-o%t.elementSize;i>=t.minimumFill&&(n=i-t.bytesFilled,a=!0);const l=e._queue;for(;n>0;){const r=l.peek(),o=Math.min(n,r.byteLength),a=t.byteOffset+t.bytesFilled;se(t.buffer,a,r.buffer,r.byteOffset,o),r.byteLength===o?l.shift():(r.byteOffset+=o,r.byteLength-=o),e._queueTotalSize-=o,Ie(e,o,t),n-=o}return a}function Ie(e,t,r){r.bytesFilled+=t}function Le(e){0===e._queueTotalSize&&e._closeRequested?(Qe(e),Ar(e._controlledReadableByteStream)):We(e)}function Fe(e){null!==e._byobRequest&&(e._byobRequest._associatedReadableByteStreamController=void 0,e._byobRequest._view=null,e._byobRequest=null)}function $e(e){for(;e._pendingPullIntos.length>0;){if(0===e._queueTotalSize)return;const t=e._pendingPullIntos.peek();ze(e,t)&&(xe(e),Oe(e._controlledReadableByteStream,t))}}function Me(e,t,r,o){const n=e._controlledReadableByteStream,a=t.constructor,i=function(e){return Pe(e)?1:e.BYTES_PER_ELEMENT}(a),{byteOffset:l,byteLength:s}=t,u=r*i;let c;try{c=ue(t.buffer)}catch(e){return void o._errorSteps(e)}const d={buffer:c,bufferByteLength:c.byteLength,byteOffset:l,byteLength:s,bytesFilled:0,minimumFill:u,elementSize:i,viewConstructor:a,readerType:"byob"};if(e._pendingPullIntos.length>0)return e._pendingPullIntos.push(d),void nt(n,o);if("closed"!==n._state){if(e._queueTotalSize>0){if(ze(e,d)){const t=je(d);return Le(e),void o._chunkSteps(t)}if(e._closeRequested){const t=new TypeError("Insufficient bytes to fill elements in the given buffer");return Ve(e,t),void o._errorSteps(t)}}e._pendingPullIntos.push(d),nt(n,o),We(e)}else{const e=new a(d.buffer,d.byteOffset,0);o._closeSteps(e)}}function Ye(e,t){const r=e._pendingPullIntos.peek();Fe(e);"closed"===e._controlledReadableByteStream._state?function(e,t){"none"===t.readerType&&xe(e);const r=e._controlledReadableByteStream;if(it(r))for(;at(r)>0;)Oe(r,xe(e))}(e,r):function(e,t,r){if(Ie(0,t,r),"none"===r.readerType)return De(e,r),void $e(e);if(r.bytesFilled0){const t=r.byteOffset+r.bytesFilled;Ae(e,r.buffer,t-o,o)}r.bytesFilled-=o,Oe(e._controlledReadableByteStream,r),$e(e)}(e,t,r),We(e)}function xe(e){return e._pendingPullIntos.shift()}function Qe(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0}function Ne(e){const t=e._controlledReadableByteStream;if(!e._closeRequested&&"readable"===t._state)if(e._queueTotalSize>0)e._closeRequested=!0;else{if(e._pendingPullIntos.length>0){const t=e._pendingPullIntos.peek();if(t.bytesFilled%t.elementSize!=0){const t=new TypeError("Insufficient bytes to fill elements in the given buffer");throw Ve(e,t),t}}Qe(e),Ar(t)}}function He(e,t){const r=e._controlledReadableByteStream;if(e._closeRequested||"readable"!==r._state)return;const{buffer:o,byteOffset:n,byteLength:a}=t;if(ce(o))throw new TypeError("chunk's buffer is detached and so cannot be enqueued");const i=ue(o);if(e._pendingPullIntos.length>0){const t=e._pendingPullIntos.peek();if(ce(t.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be filled with an enqueued chunk");Fe(e),t.buffer=ue(t.buffer),"none"===t.readerType&&De(e,t)}if(G(r))if(function(e){const t=e._controlledReadableByteStream._reader;for(;t._readRequests.length>0;){if(0===e._queueTotalSize)return;Ue(e,t._readRequests.shift())}}(e),0===U(r))ke(e,i,n,a);else{e._pendingPullIntos.length>0&&xe(e);V(r,new Uint8Array(i,n,a),!1)}else it(r)?(ke(e,i,n,a),$e(e)):ke(e,i,n,a);We(e)}function Ve(e,t){const r=e._controlledReadableByteStream;"readable"===r._state&&(Be(e),Ce(e),Qe(e),Dr(r,t))}function Ue(e,t){const r=e._queue.shift();e._queueTotalSize-=r.byteLength,Le(e);const o=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);t._chunkSteps(o)}function Ge(e){if(null===e._byobRequest&&e._pendingPullIntos.length>0){const t=e._pendingPullIntos.peek(),r=new Uint8Array(t.buffer,t.byteOffset+t.bytesFilled,t.byteLength-t.bytesFilled),o=Object.create(ReadableStreamBYOBRequest.prototype);!function(e,t,r){e._associatedReadableByteStreamController=t,e._view=r}(o,e,r),e._byobRequest=o}return e._byobRequest}function Xe(e){const t=e._controlledReadableByteStream._state;return"errored"===t?null:"closed"===t?0:e._strategyHWM-e._queueTotalSize}function Je(e,t){const r=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==t)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream")}else{if(0===t)throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");if(r.bytesFilled+t>r.byteLength)throw new RangeError("bytesWritten out of range")}r.buffer=ue(r.buffer),Ye(e,t)}function Ke(e,t){const r=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==t.byteLength)throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream")}else if(0===t.byteLength)throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");if(r.byteOffset+r.bytesFilled!==t.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(r.bufferByteLength!==t.buffer.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");if(r.bytesFilled+t.byteLength>r.byteLength)throw new RangeError("The region specified by view is larger than byobRequest");const o=t.byteLength;r.buffer=ue(t.buffer),Ye(e,o)}function Ze(e,t,r,o,n,a,i){t._controlledReadableByteStream=e,t._pullAgain=!1,t._pulling=!1,t._byobRequest=null,t._queue=t._queueTotalSize=void 0,Ce(t),t._closeRequested=!1,t._started=!1,t._strategyHWM=a,t._pullAlgorithm=o,t._cancelAlgorithm=n,t._autoAllocateChunkSize=i,t._pendingPullIntos=new g,e._readableStreamController=t;f(u(r()),(()=>(t._started=!0,We(t),null)),(e=>(Ve(t,e),null)))}function et(e){return new TypeError(`ReadableStreamBYOBRequest.prototype.${e} can only be used on a ReadableStreamBYOBRequest`)}function tt(e){return new TypeError(`ReadableByteStreamController.prototype.${e} can only be used on a ReadableByteStreamController`)}function rt(e,t){if("byob"!==(e=`${e}`))throw new TypeError(`${t} '${e}' is not a valid enumeration value for ReadableStreamReaderMode`);return e}function ot(e){return new ReadableStreamBYOBReader(e)}function nt(e,t){e._reader._readIntoRequests.push(t)}function at(e){return e._reader._readIntoRequests.length}function it(e){const t=e._reader;return void 0!==t&&!!lt(t)}Object.defineProperties(ReadableByteStreamController.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),n(ReadableByteStreamController.prototype.close,"close"),n(ReadableByteStreamController.prototype.enqueue,"enqueue"),n(ReadableByteStreamController.prototype.error,"error"),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(ReadableByteStreamController.prototype,Symbol.toStringTag,{value:"ReadableByteStreamController",configurable:!0});class ReadableStreamBYOBReader{constructor(e){if(F(e,1,"ReadableStreamBYOBReader"),Q(e,"First parameter"),jr(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!qe(e._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");P(this,e),this._readIntoRequests=new g}get closed(){return lt(this)?this._closedPromise:c(ct("closed"))}cancel(e=void 0){return lt(this)?void 0===this._ownerReadableStream?c(W("cancel")):q(this,e):c(ct("cancel"))}read(e,t={}){if(!lt(this))return c(ct("read"));if(!ArrayBuffer.isView(e))return c(new TypeError("view must be an array buffer view"));if(0===e.byteLength)return c(new TypeError("view must have non-zero byteLength"));if(0===e.buffer.byteLength)return c(new TypeError("view's buffer must have non-zero byteLength"));if(ce(e.buffer))return c(new TypeError("view's buffer has been detached"));let r;try{r=function(e,t){var r;return z(e,t),{min:x(null!==(r=null==e?void 0:e.min)&&void 0!==r?r:1,`${t} has member 'min' that`)}}(t,"options")}catch(e){return c(e)}const o=r.min;if(0===o)return c(new TypeError("options.min must be greater than 0"));if(function(e){return Pe(e.constructor)}(e)){if(o>e.byteLength)return c(new RangeError("options.min must be less than or equal to view's byteLength"))}else if(o>e.length)return c(new RangeError("options.min must be less than or equal to view's length"));if(void 0===this._ownerReadableStream)return c(W("read from"));let n,a;const i=s(((e,t)=>{n=e,a=t}));return st(this,e,o,{_chunkSteps:e=>n({value:e,done:!1}),_closeSteps:e=>n({value:e,done:!0}),_errorSteps:e=>a(e)}),i}releaseLock(){if(!lt(this))throw ct("releaseLock");void 0!==this._ownerReadableStream&&function(e){E(e);const t=new TypeError("Reader was released");ut(e,t)}(this)}}function lt(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readIntoRequests")&&e instanceof ReadableStreamBYOBReader)}function st(e,t,r,o){const n=e._ownerReadableStream;n._disturbed=!0,"errored"===n._state?o._errorSteps(n._storedError):Me(n._readableStreamController,t,r,o)}function ut(e,t){const r=e._readIntoRequests;e._readIntoRequests=new g,r.forEach((e=>{e._errorSteps(t)}))}function ct(e){return new TypeError(`ReadableStreamBYOBReader.prototype.${e} can only be used on a ReadableStreamBYOBReader`)}function dt(e,t){const{highWaterMark:r}=e;if(void 0===r)return t;if(ve(r)||r<0)throw new RangeError("Invalid highWaterMark");return r}function ft(e){const{size:t}=e;return t||(()=>1)}function bt(e,t){z(e,t);const r=null==e?void 0:e.highWaterMark,o=null==e?void 0:e.size;return{highWaterMark:void 0===r?void 0:M(r),size:void 0===o?void 0:mt(o,`${t} has member 'size' that`)}}function mt(e,t){return I(e,t),t=>M(e(t))}function ht(e,t,r){return I(e,r),r=>S(e,t,[r])}function _t(e,t,r){return I(e,r),()=>S(e,t,[])}function pt(e,t,r){return I(e,r),r=>y(e,t,[r])}function yt(e,t,r){return I(e,r),(r,o)=>S(e,t,[r,o])}function St(e,t){if(!Rt(e))throw new TypeError(`${t} is not a WritableStream.`)}Object.defineProperties(ReadableStreamBYOBReader.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),n(ReadableStreamBYOBReader.prototype.cancel,"cancel"),n(ReadableStreamBYOBReader.prototype.read,"read"),n(ReadableStreamBYOBReader.prototype.releaseLock,"releaseLock"),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(ReadableStreamBYOBReader.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});const gt="function"==typeof AbortController;class WritableStream{constructor(e={},t={}){void 0===e?e=null:L(e,"First parameter");const r=bt(t,"Second parameter"),o=function(e,t){z(e,t);const r=null==e?void 0:e.abort,o=null==e?void 0:e.close,n=null==e?void 0:e.start,a=null==e?void 0:e.type,i=null==e?void 0:e.write;return{abort:void 0===r?void 0:ht(r,e,`${t} has member 'abort' that`),close:void 0===o?void 0:_t(o,e,`${t} has member 'close' that`),start:void 0===n?void 0:pt(n,e,`${t} has member 'start' that`),write:void 0===i?void 0:yt(i,e,`${t} has member 'write' that`),type:a}}(e,"First parameter");wt(this);if(void 0!==o.type)throw new RangeError("Invalid type is specified");const n=ft(r);!function(e,t,r,o){const n=Object.create(WritableStreamDefaultController.prototype);let a,i,l,s;a=void 0!==t.start?()=>t.start(n):()=>{};i=void 0!==t.write?e=>t.write(e,n):()=>u(void 0);l=void 0!==t.close?()=>t.close():()=>u(void 0);s=void 0!==t.abort?e=>t.abort(e):()=>u(void 0);Mt(e,n,a,i,l,s,r,o)}(this,o,dt(r,1),n)}get locked(){if(!Rt(this))throw Ut("locked");return Tt(this)}abort(e=void 0){return Rt(this)?Tt(this)?c(new TypeError("Cannot abort a stream that already has a writer")):Ct(this,e):c(Ut("abort"))}close(){return Rt(this)?Tt(this)?c(new TypeError("Cannot close a stream that already has a writer")):Bt(this)?c(new TypeError("Cannot close an already-closing stream")):Pt(this):c(Ut("close"))}getWriter(){if(!Rt(this))throw Ut("getWriter");return vt(this)}}function vt(e){return new WritableStreamDefaultWriter(e)}function wt(e){e._state="writable",e._storedError=void 0,e._writer=void 0,e._writableStreamController=void 0,e._writeRequests=new g,e._inFlightWriteRequest=void 0,e._closeRequest=void 0,e._inFlightCloseRequest=void 0,e._pendingAbortRequest=void 0,e._backpressure=!1}function Rt(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_writableStreamController")&&e instanceof WritableStream)}function Tt(e){return void 0!==e._writer}function Ct(e,t){var r;if("closed"===e._state||"errored"===e._state)return u(void 0);e._writableStreamController._abortReason=t,null===(r=e._writableStreamController._abortController)||void 0===r||r.abort(t);const o=e._state;if("closed"===o||"errored"===o)return u(void 0);if(void 0!==e._pendingAbortRequest)return e._pendingAbortRequest._promise;let n=!1;"erroring"===o&&(n=!0,t=void 0);const a=s(((r,o)=>{e._pendingAbortRequest={_promise:void 0,_resolve:r,_reject:o,_reason:t,_wasAlreadyErroring:n}}));return e._pendingAbortRequest._promise=a,n||Et(e,t),a}function Pt(e){const t=e._state;if("closed"===t||"errored"===t)return c(new TypeError(`The stream (in ${t} state) is not in the writable state and cannot be closed`));const r=s(((t,r)=>{const o={_resolve:t,_reject:r};e._closeRequest=o})),o=e._writer;var n;return void 0!==o&&e._backpressure&&"writable"===t&&ir(o),Te(n=e._writableStreamController,Ft,0),Qt(n),r}function qt(e,t){"writable"!==e._state?Wt(e):Et(e,t)}function Et(e,t){const r=e._writableStreamController;e._state="erroring",e._storedError=t;const o=e._writer;void 0!==o&&zt(o,t),!function(e){if(void 0===e._inFlightWriteRequest&&void 0===e._inFlightCloseRequest)return!1;return!0}(e)&&r._started&&Wt(e)}function Wt(e){e._state="errored",e._writableStreamController[w]();const t=e._storedError;if(e._writeRequests.forEach((e=>{e._reject(t)})),e._writeRequests=new g,void 0===e._pendingAbortRequest)return void Ot(e);const r=e._pendingAbortRequest;if(e._pendingAbortRequest=void 0,r._wasAlreadyErroring)return r._reject(t),void Ot(e);f(e._writableStreamController[v](r._reason),(()=>(r._resolve(),Ot(e),null)),(t=>(r._reject(t),Ot(e),null)))}function Bt(e){return void 0!==e._closeRequest||void 0!==e._inFlightCloseRequest}function Ot(e){void 0!==e._closeRequest&&(e._closeRequest._reject(e._storedError),e._closeRequest=void 0);const t=e._writer;void 0!==t&&er(t,e._storedError)}function jt(e,t){const r=e._writer;void 0!==r&&t!==e._backpressure&&(t?function(e){rr(e)}(r):ir(r)),e._backpressure=t}Object.defineProperties(WritableStream.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),n(WritableStream.prototype.abort,"abort"),n(WritableStream.prototype.close,"close"),n(WritableStream.prototype.getWriter,"getWriter"),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(WritableStream.prototype,Symbol.toStringTag,{value:"WritableStream",configurable:!0});class WritableStreamDefaultWriter{constructor(e){if(F(e,1,"WritableStreamDefaultWriter"),St(e,"First parameter"),Tt(e))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=e,e._writer=this;const t=e._state;if("writable"===t)!Bt(e)&&e._backpressure?rr(this):nr(this),Kt(this);else if("erroring"===t)or(this,e._storedError),Kt(this);else if("closed"===t)nr(this),Kt(r=this),tr(r);else{const t=e._storedError;or(this,t),Zt(this,t)}var r}get closed(){return kt(this)?this._closedPromise:c(Xt("closed"))}get desiredSize(){if(!kt(this))throw Xt("desiredSize");if(void 0===this._ownerWritableStream)throw Jt("desiredSize");return function(e){const t=e._ownerWritableStream,r=t._state;if("errored"===r||"erroring"===r)return null;if("closed"===r)return 0;return xt(t._writableStreamController)}(this)}get ready(){return kt(this)?this._readyPromise:c(Xt("ready"))}abort(e=void 0){return kt(this)?void 0===this._ownerWritableStream?c(Jt("abort")):function(e,t){return Ct(e._ownerWritableStream,t)}(this,e):c(Xt("abort"))}close(){if(!kt(this))return c(Xt("close"));const e=this._ownerWritableStream;return void 0===e?c(Jt("close")):Bt(e)?c(new TypeError("Cannot close an already-closing stream")):At(this)}releaseLock(){if(!kt(this))throw Xt("releaseLock");void 0!==this._ownerWritableStream&&It(this)}write(e=void 0){return kt(this)?void 0===this._ownerWritableStream?c(Jt("write to")):Lt(this,e):c(Xt("write"))}}function kt(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_ownerWritableStream")&&e instanceof WritableStreamDefaultWriter)}function At(e){return Pt(e._ownerWritableStream)}function Dt(e,t){"pending"===e._closedPromiseState?er(e,t):function(e,t){Zt(e,t)}(e,t)}function zt(e,t){"pending"===e._readyPromiseState?ar(e,t):function(e,t){or(e,t)}(e,t)}function It(e){const t=e._ownerWritableStream,r=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");zt(e,r),Dt(e,r),t._writer=void 0,e._ownerWritableStream=void 0}function Lt(e,t){const r=e._ownerWritableStream,o=r._writableStreamController,n=function(e,t){try{return e._strategySizeAlgorithm(t)}catch(t){return Nt(e,t),1}}(o,t);if(r!==e._ownerWritableStream)return c(Jt("write to"));const a=r._state;if("errored"===a)return c(r._storedError);if(Bt(r)||"closed"===a)return c(new TypeError("The stream is closing or closed and cannot be written to"));if("erroring"===a)return c(r._storedError);const i=function(e){return s(((t,r)=>{const o={_resolve:t,_reject:r};e._writeRequests.push(o)}))}(r);return function(e,t,r){try{Te(e,t,r)}catch(t){return void Nt(e,t)}const o=e._controlledWritableStream;if(!Bt(o)&&"writable"===o._state){jt(o,Ht(e))}Qt(e)}(o,t,n),i}Object.defineProperties(WritableStreamDefaultWriter.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),n(WritableStreamDefaultWriter.prototype.abort,"abort"),n(WritableStreamDefaultWriter.prototype.close,"close"),n(WritableStreamDefaultWriter.prototype.releaseLock,"releaseLock"),n(WritableStreamDefaultWriter.prototype.write,"write"),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(WritableStreamDefaultWriter.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});const Ft={};class WritableStreamDefaultController{constructor(){throw new TypeError("Illegal constructor")}get abortReason(){if(!$t(this))throw Gt("abortReason");return this._abortReason}get signal(){if(!$t(this))throw Gt("signal");if(void 0===this._abortController)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal}error(e=void 0){if(!$t(this))throw Gt("error");"writable"===this._controlledWritableStream._state&&Vt(this,e)}[v](e){const t=this._abortAlgorithm(e);return Yt(this),t}[w](){Ce(this)}}function $t(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledWritableStream")&&e instanceof WritableStreamDefaultController)}function Mt(e,t,r,o,n,a,i,l){t._controlledWritableStream=e,e._writableStreamController=t,t._queue=void 0,t._queueTotalSize=void 0,Ce(t),t._abortReason=void 0,t._abortController=function(){if(gt)return new AbortController}(),t._started=!1,t._strategySizeAlgorithm=l,t._strategyHWM=i,t._writeAlgorithm=o,t._closeAlgorithm=n,t._abortAlgorithm=a;const s=Ht(t);jt(e,s);f(u(r()),(()=>(t._started=!0,Qt(t),null)),(r=>(t._started=!0,qt(e,r),null)))}function Yt(e){e._writeAlgorithm=void 0,e._closeAlgorithm=void 0,e._abortAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function xt(e){return e._strategyHWM-e._queueTotalSize}function Qt(e){const t=e._controlledWritableStream;if(!e._started)return;if(void 0!==t._inFlightWriteRequest)return;if("erroring"===t._state)return void Wt(t);if(0===e._queue.length)return;const r=e._queue.peek().value;r===Ft?function(e){const t=e._controlledWritableStream;(function(e){e._inFlightCloseRequest=e._closeRequest,e._closeRequest=void 0})(t),Re(e);const r=e._closeAlgorithm();Yt(e),f(r,(()=>(function(e){e._inFlightCloseRequest._resolve(void 0),e._inFlightCloseRequest=void 0,"erroring"===e._state&&(e._storedError=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._resolve(),e._pendingAbortRequest=void 0)),e._state="closed";const t=e._writer;void 0!==t&&tr(t)}(t),null)),(e=>(function(e,t){e._inFlightCloseRequest._reject(t),e._inFlightCloseRequest=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._reject(t),e._pendingAbortRequest=void 0),qt(e,t)}(t,e),null)))}(e):function(e,t){const r=e._controlledWritableStream;!function(e){e._inFlightWriteRequest=e._writeRequests.shift()}(r);const o=e._writeAlgorithm(t);f(o,(()=>{!function(e){e._inFlightWriteRequest._resolve(void 0),e._inFlightWriteRequest=void 0}(r);const t=r._state;if(Re(e),!Bt(r)&&"writable"===t){const t=Ht(e);jt(r,t)}return Qt(e),null}),(t=>("writable"===r._state&&Yt(e),function(e,t){e._inFlightWriteRequest._reject(t),e._inFlightWriteRequest=void 0,qt(e,t)}(r,t),null)))}(e,r)}function Nt(e,t){"writable"===e._controlledWritableStream._state&&Vt(e,t)}function Ht(e){return xt(e)<=0}function Vt(e,t){const r=e._controlledWritableStream;Yt(e),Et(r,t)}function Ut(e){return new TypeError(`WritableStream.prototype.${e} can only be used on a WritableStream`)}function Gt(e){return new TypeError(`WritableStreamDefaultController.prototype.${e} can only be used on a WritableStreamDefaultController`)}function Xt(e){return new TypeError(`WritableStreamDefaultWriter.prototype.${e} can only be used on a WritableStreamDefaultWriter`)}function Jt(e){return new TypeError("Cannot "+e+" a stream using a released writer")}function Kt(e){e._closedPromise=s(((t,r)=>{e._closedPromise_resolve=t,e._closedPromise_reject=r,e._closedPromiseState="pending"}))}function Zt(e,t){Kt(e),er(e,t)}function er(e,t){void 0!==e._closedPromise_reject&&(_(e._closedPromise),e._closedPromise_reject(t),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="rejected")}function tr(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="resolved")}function rr(e){e._readyPromise=s(((t,r)=>{e._readyPromise_resolve=t,e._readyPromise_reject=r})),e._readyPromiseState="pending"}function or(e,t){rr(e),ar(e,t)}function nr(e){rr(e),ir(e)}function ar(e,t){void 0!==e._readyPromise_reject&&(_(e._readyPromise),e._readyPromise_reject(t),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="rejected")}function ir(e){void 0!==e._readyPromise_resolve&&(e._readyPromise_resolve(void 0),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="fulfilled")}Object.defineProperties(WritableStreamDefaultController.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(WritableStreamDefaultController.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});const lr="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof global?global:void 0;const sr=function(){const e=null==lr?void 0:lr.DOMException;return function(e){if("function"!=typeof e&&"object"!=typeof e)return!1;if("DOMException"!==e.name)return!1;try{return new e,!0}catch(e){return!1}}(e)?e:void 0}()||function(){const e=function(e,t){this.message=e||"",this.name=t||"Error",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)};return n(e,"DOMException"),e.prototype=Object.create(Error.prototype),Object.defineProperty(e.prototype,"constructor",{value:e,writable:!0,configurable:!0}),e}();function ur(e,r,o,n,a,i){const l=N(e),h=vt(r);e._disturbed=!0;let p=!1,y=u(void 0);return s(((S,g)=>{let v;if(void 0!==i){if(v=()=>{const t=void 0!==i.reason?i.reason:new sr("Aborted","AbortError"),o=[];n||o.push((()=>"writable"===r._state?Ct(r,t):u(void 0))),a||o.push((()=>"readable"===e._state?kr(e,t):u(void 0))),q((()=>Promise.all(o.map((e=>e())))),!0,t)},i.aborted)return void v();i.addEventListener("abort",v)}var w,R,T;if(P(e,l._closedPromise,(e=>(n?W(!0,e):q((()=>Ct(r,e)),!0,e),null))),P(r,h._closedPromise,(t=>(a?W(!0,t):q((()=>kr(e,t)),!0,t),null))),w=e,R=l._closedPromise,T=()=>(o?W():q((()=>function(e){const t=e._ownerWritableStream,r=t._state;return Bt(t)||"closed"===r?u(void 0):"errored"===r?c(t._storedError):At(e)}(h))),null),"closed"===w._state?T():b(R,T),Bt(r)||"closed"===r._state){const t=new TypeError("the destination writable stream closed before all data could be piped to it");a?W(!0,t):q((()=>kr(e,t)),!0,t)}function C(){const e=y;return d(y,(()=>e!==y?C():void 0))}function P(e,t,r){"errored"===e._state?r(e._storedError):m(t,r)}function q(e,t,o){function n(){return f(e(),(()=>B(t,o)),(e=>B(!0,e))),null}p||(p=!0,"writable"!==r._state||Bt(r)?n():b(C(),n))}function W(e,t){p||(p=!0,"writable"!==r._state||Bt(r)?B(e,t):b(C(),(()=>B(e,t))))}function B(e,t){return It(h),E(l),void 0!==i&&i.removeEventListener("abort",v),e?g(t):S(void 0),null}_(s(((e,r)=>{!function o(n){n?e():d(p?u(!0):d(h._readyPromise,(()=>s(((e,r)=>{J(l,{_chunkSteps:r=>{y=d(Lt(h,r),void 0,t),e(!1)},_closeSteps:()=>e(!0),_errorSteps:r})})))),o,r)}(!1)})))}))}class ReadableStreamDefaultController{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!cr(this))throw gr("desiredSize");return pr(this)}close(){if(!cr(this))throw gr("close");if(!yr(this))throw new TypeError("The stream is not in a state that permits close");mr(this)}enqueue(e=void 0){if(!cr(this))throw gr("enqueue");if(!yr(this))throw new TypeError("The stream is not in a state that permits enqueue");return hr(this,e)}error(e=void 0){if(!cr(this))throw gr("error");_r(this,e)}[R](e){Ce(this);const t=this._cancelAlgorithm(e);return br(this),t}[T](e){const t=this._controlledReadableStream;if(this._queue.length>0){const r=Re(this);this._closeRequested&&0===this._queue.length?(br(this),Ar(t)):dr(this),e._chunkSteps(r)}else H(t,e),dr(this)}[C](){}}function cr(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableStream")&&e instanceof ReadableStreamDefaultController)}function dr(e){if(!fr(e))return;if(e._pulling)return void(e._pullAgain=!0);e._pulling=!0;f(e._pullAlgorithm(),(()=>(e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,dr(e)),null)),(t=>(_r(e,t),null)))}function fr(e){const t=e._controlledReadableStream;if(!yr(e))return!1;if(!e._started)return!1;if(jr(t)&&U(t)>0)return!0;return pr(e)>0}function br(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function mr(e){if(!yr(e))return;const t=e._controlledReadableStream;e._closeRequested=!0,0===e._queue.length&&(br(e),Ar(t))}function hr(e,t){if(!yr(e))return;const r=e._controlledReadableStream;if(jr(r)&&U(r)>0)V(r,t,!1);else{let r;try{r=e._strategySizeAlgorithm(t)}catch(t){throw _r(e,t),t}try{Te(e,t,r)}catch(t){throw _r(e,t),t}}dr(e)}function _r(e,t){const r=e._controlledReadableStream;"readable"===r._state&&(Ce(e),br(e),Dr(r,t))}function pr(e){const t=e._controlledReadableStream._state;return"errored"===t?null:"closed"===t?0:e._strategyHWM-e._queueTotalSize}function yr(e){const t=e._controlledReadableStream._state;return!e._closeRequested&&"readable"===t}function Sr(e,t,r,o,n,a,i){t._controlledReadableStream=e,t._queue=void 0,t._queueTotalSize=void 0,Ce(t),t._started=!1,t._closeRequested=!1,t._pullAgain=!1,t._pulling=!1,t._strategySizeAlgorithm=i,t._strategyHWM=a,t._pullAlgorithm=o,t._cancelAlgorithm=n,e._readableStreamController=t;f(u(r()),(()=>(t._started=!0,dr(t),null)),(e=>(_r(t,e),null)))}function gr(e){return new TypeError(`ReadableStreamDefaultController.prototype.${e} can only be used on a ReadableStreamDefaultController`)}function vr(e,t){return qe(e._readableStreamController)?function(e){let t,r,o,n,a,i=N(e),l=!1,c=!1,d=!1,f=!1,b=!1;const h=s((e=>{a=e}));function _(e){m(e._closedPromise,(t=>(e!==i||(Ve(o._readableStreamController,t),Ve(n._readableStreamController,t),f&&b||a(void 0)),null)))}function y(){lt(i)&&(E(i),i=N(e),_(i));J(i,{_chunkSteps:t=>{p((()=>{c=!1,d=!1;const r=t;let i=t;if(!f&&!b)try{i=we(t)}catch(t){return Ve(o._readableStreamController,t),Ve(n._readableStreamController,t),void a(kr(e,t))}f||He(o._readableStreamController,r),b||He(n._readableStreamController,i),l=!1,c?g():d&&v()}))},_closeSteps:()=>{l=!1,f||Ne(o._readableStreamController),b||Ne(n._readableStreamController),o._readableStreamController._pendingPullIntos.length>0&&Je(o._readableStreamController,0),n._readableStreamController._pendingPullIntos.length>0&&Je(n._readableStreamController,0),f&&b||a(void 0)},_errorSteps:()=>{l=!1}})}function S(t,r){X(i)&&(E(i),i=ot(e),_(i));const s=r?n:o,u=r?o:n;st(i,t,1,{_chunkSteps:t=>{p((()=>{c=!1,d=!1;const o=r?b:f;if(r?f:b)o||Ke(s._readableStreamController,t);else{let r;try{r=we(t)}catch(t){return Ve(s._readableStreamController,t),Ve(u._readableStreamController,t),void a(kr(e,t))}o||Ke(s._readableStreamController,t),He(u._readableStreamController,r)}l=!1,c?g():d&&v()}))},_closeSteps:e=>{l=!1;const t=r?b:f,o=r?f:b;t||Ne(s._readableStreamController),o||Ne(u._readableStreamController),void 0!==e&&(t||Ke(s._readableStreamController,e),!o&&u._readableStreamController._pendingPullIntos.length>0&&Je(u._readableStreamController,0)),t&&o||a(void 0)},_errorSteps:()=>{l=!1}})}function g(){if(l)return c=!0,u(void 0);l=!0;const e=Ge(o._readableStreamController);return null===e?y():S(e._view,!1),u(void 0)}function v(){if(l)return d=!0,u(void 0);l=!0;const e=Ge(n._readableStreamController);return null===e?y():S(e._view,!0),u(void 0)}function w(o){if(f=!0,t=o,b){const o=le([t,r]),n=kr(e,o);a(n)}return h}function R(o){if(b=!0,r=o,f){const o=le([t,r]),n=kr(e,o);a(n)}return h}function T(){}return o=Wr(T,g,w),n=Wr(T,v,R),_(i),[o,n]}(e):function(e,t){const r=N(e);let o,n,a,i,l,c=!1,d=!1,f=!1,b=!1;const h=s((e=>{l=e}));function _(){if(c)return d=!0,u(void 0);c=!0;return J(r,{_chunkSteps:e=>{p((()=>{d=!1;const t=e,r=e;f||hr(a._readableStreamController,t),b||hr(i._readableStreamController,r),c=!1,d&&_()}))},_closeSteps:()=>{c=!1,f||mr(a._readableStreamController),b||mr(i._readableStreamController),f&&b||l(void 0)},_errorSteps:()=>{c=!1}}),u(void 0)}function y(t){if(f=!0,o=t,b){const t=le([o,n]),r=kr(e,t);l(r)}return h}function S(t){if(b=!0,n=t,f){const t=le([o,n]),r=kr(e,t);l(r)}return h}function g(){}return a=Er(g,_,y),i=Er(g,_,S),m(r._closedPromise,(e=>(_r(a._readableStreamController,e),_r(i._readableStreamController,e),f&&b||l(void 0),null))),[a,i]}(e)}function wr(e){return r(o=e)&&void 0!==o.getReader?function(e){let o;function n(){let t;try{t=e.read()}catch(e){return c(e)}return h(t,(e=>{if(!r(e))throw new TypeError("The promise returned by the reader.read() method must fulfill with an object");if(e.done)mr(o._readableStreamController);else{const t=e.value;hr(o._readableStreamController,t)}}))}function a(t){try{return u(e.cancel(t))}catch(e){return c(e)}}return o=Er(t,n,a,0),o}(e.getReader()):function(e){let o;const n=he(e,"async");function a(){let e;try{e=function(e){const t=y(e.nextMethod,e.iterator,[]);if(!r(t))throw new TypeError("The iterator.next() method must return an object");return t}(n)}catch(e){return c(e)}return h(u(e),(e=>{if(!r(e))throw new TypeError("The promise returned by the iterator.next() method must fulfill with an object");const t=function(e){return Boolean(e.done)}(e);if(t)mr(o._readableStreamController);else{const t=function(e){return e.value}(e);hr(o._readableStreamController,t)}}))}function i(e){const t=n.iterator;let o,a;try{o=fe(t,"return")}catch(e){return c(e)}if(void 0===o)return u(void 0);try{a=y(o,t,[e])}catch(e){return c(e)}return h(u(a),(e=>{if(!r(e))throw new TypeError("The promise returned by the iterator.return() method must fulfill with an object")}))}return o=Er(t,a,i,0),o}(e);var o}function Rr(e,t,r){return I(e,r),r=>S(e,t,[r])}function Tr(e,t,r){return I(e,r),r=>S(e,t,[r])}function Cr(e,t,r){return I(e,r),r=>y(e,t,[r])}function Pr(e,t){if("bytes"!==(e=`${e}`))throw new TypeError(`${t} '${e}' is not a valid enumeration value for ReadableStreamType`);return e}function qr(e,t){z(e,t);const r=null==e?void 0:e.preventAbort,o=null==e?void 0:e.preventCancel,n=null==e?void 0:e.preventClose,a=null==e?void 0:e.signal;return void 0!==a&&function(e,t){if(!function(e){if("object"!=typeof e||null===e)return!1;try{return"boolean"==typeof e.aborted}catch(e){return!1}}(e))throw new TypeError(`${t} is not an AbortSignal.`)}(a,`${t} has member 'signal' that`),{preventAbort:Boolean(r),preventCancel:Boolean(o),preventClose:Boolean(n),signal:a}}Object.defineProperties(ReadableStreamDefaultController.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),n(ReadableStreamDefaultController.prototype.close,"close"),n(ReadableStreamDefaultController.prototype.enqueue,"enqueue"),n(ReadableStreamDefaultController.prototype.error,"error"),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(ReadableStreamDefaultController.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});class ReadableStream{constructor(e={},t={}){void 0===e?e=null:L(e,"First parameter");const r=bt(t,"Second parameter"),o=function(e,t){z(e,t);const r=e,o=null==r?void 0:r.autoAllocateChunkSize,n=null==r?void 0:r.cancel,a=null==r?void 0:r.pull,i=null==r?void 0:r.start,l=null==r?void 0:r.type;return{autoAllocateChunkSize:void 0===o?void 0:x(o,`${t} has member 'autoAllocateChunkSize' that`),cancel:void 0===n?void 0:Rr(n,r,`${t} has member 'cancel' that`),pull:void 0===a?void 0:Tr(a,r,`${t} has member 'pull' that`),start:void 0===i?void 0:Cr(i,r,`${t} has member 'start' that`),type:void 0===l?void 0:Pr(l,`${t} has member 'type' that`)}}(e,"First parameter");if(Br(this),"bytes"===o.type){if(void 0!==r.size)throw new RangeError("The strategy for a byte stream cannot have a size function");!function(e,t,r){const o=Object.create(ReadableByteStreamController.prototype);let n,a,i;n=void 0!==t.start?()=>t.start(o):()=>{},a=void 0!==t.pull?()=>t.pull(o):()=>u(void 0),i=void 0!==t.cancel?e=>t.cancel(e):()=>u(void 0);const l=t.autoAllocateChunkSize;if(0===l)throw new TypeError("autoAllocateChunkSize must be greater than 0");Ze(e,o,n,a,i,r,l)}(this,o,dt(r,0))}else{const e=ft(r);!function(e,t,r,o){const n=Object.create(ReadableStreamDefaultController.prototype);let a,i,l;a=void 0!==t.start?()=>t.start(n):()=>{},i=void 0!==t.pull?()=>t.pull(n):()=>u(void 0),l=void 0!==t.cancel?e=>t.cancel(e):()=>u(void 0),Sr(e,n,a,i,l,r,o)}(this,o,dt(r,1),e)}}get locked(){if(!Or(this))throw zr("locked");return jr(this)}cancel(e=void 0){return Or(this)?jr(this)?c(new TypeError("Cannot cancel a stream that already has a reader")):kr(this,e):c(zr("cancel"))}getReader(e=void 0){if(!Or(this))throw zr("getReader");return void 0===function(e,t){z(e,t);const r=null==e?void 0:e.mode;return{mode:void 0===r?void 0:rt(r,`${t} has member 'mode' that`)}}(e,"First parameter").mode?N(this):ot(this)}pipeThrough(e,t={}){if(!Or(this))throw zr("pipeThrough");F(e,1,"pipeThrough");const r=function(e,t){z(e,t);const r=null==e?void 0:e.readable;$(r,"readable","ReadableWritablePair"),Q(r,`${t} has member 'readable' that`);const o=null==e?void 0:e.writable;return $(o,"writable","ReadableWritablePair"),St(o,`${t} has member 'writable' that`),{readable:r,writable:o}}(e,"First parameter"),o=qr(t,"Second parameter");if(jr(this))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(Tt(r.writable))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");return _(ur(this,r.writable,o.preventClose,o.preventAbort,o.preventCancel,o.signal)),r.readable}pipeTo(e,t={}){if(!Or(this))return c(zr("pipeTo"));if(void 0===e)return c("Parameter 1 is required in 'pipeTo'.");if(!Rt(e))return c(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let r;try{r=qr(t,"Second parameter")}catch(e){return c(e)}return jr(this)?c(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):Tt(e)?c(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):ur(this,e,r.preventClose,r.preventAbort,r.preventCancel,r.signal)}tee(){if(!Or(this))throw zr("tee");return le(vr(this))}values(e=void 0){if(!Or(this))throw zr("values");return function(e,t){const r=N(e),o=new pe(r,t),n=Object.create(ye);return n._asyncIteratorImpl=o,n}(this,function(e,t){z(e,t);const r=null==e?void 0:e.preventCancel;return{preventCancel:Boolean(r)}}(e,"First parameter").preventCancel)}[me](e){return this.values(e)}static from(e){return wr(e)}}function Er(e,t,r,o=1,n=(()=>1)){const a=Object.create(ReadableStream.prototype);Br(a);return Sr(a,Object.create(ReadableStreamDefaultController.prototype),e,t,r,o,n),a}function Wr(e,t,r){const o=Object.create(ReadableStream.prototype);Br(o);return Ze(o,Object.create(ReadableByteStreamController.prototype),e,t,r,0,void 0),o}function Br(e){e._state="readable",e._reader=void 0,e._storedError=void 0,e._disturbed=!1}function Or(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readableStreamController")&&e instanceof ReadableStream)}function jr(e){return void 0!==e._reader}function kr(e,r){if(e._disturbed=!0,"closed"===e._state)return u(void 0);if("errored"===e._state)return c(e._storedError);Ar(e);const o=e._reader;if(void 0!==o&<(o)){const e=o._readIntoRequests;o._readIntoRequests=new g,e.forEach((e=>{e._closeSteps(void 0)}))}return h(e._readableStreamController[R](r),t)}function Ar(e){e._state="closed";const t=e._reader;if(void 0!==t&&(k(t),X(t))){const e=t._readRequests;t._readRequests=new g,e.forEach((e=>{e._closeSteps()}))}}function Dr(e,t){e._state="errored",e._storedError=t;const r=e._reader;void 0!==r&&(j(r,t),X(r)?K(r,t):ut(r,t))}function zr(e){return new TypeError(`ReadableStream.prototype.${e} can only be used on a ReadableStream`)}function Ir(e,t){z(e,t);const r=null==e?void 0:e.highWaterMark;return $(r,"highWaterMark","QueuingStrategyInit"),{highWaterMark:M(r)}}Object.defineProperties(ReadableStream,{from:{enumerable:!0}}),Object.defineProperties(ReadableStream.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),n(ReadableStream.from,"from"),n(ReadableStream.prototype.cancel,"cancel"),n(ReadableStream.prototype.getReader,"getReader"),n(ReadableStream.prototype.pipeThrough,"pipeThrough"),n(ReadableStream.prototype.pipeTo,"pipeTo"),n(ReadableStream.prototype.tee,"tee"),n(ReadableStream.prototype.values,"values"),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(ReadableStream.prototype,Symbol.toStringTag,{value:"ReadableStream",configurable:!0}),Object.defineProperty(ReadableStream.prototype,me,{value:ReadableStream.prototype.values,writable:!0,configurable:!0});const Lr=e=>e.byteLength;n(Lr,"size");class ByteLengthQueuingStrategy{constructor(e){F(e,1,"ByteLengthQueuingStrategy"),e=Ir(e,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=e.highWaterMark}get highWaterMark(){if(!$r(this))throw Fr("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!$r(this))throw Fr("size");return Lr}}function Fr(e){return new TypeError(`ByteLengthQueuingStrategy.prototype.${e} can only be used on a ByteLengthQueuingStrategy`)}function $r(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_byteLengthQueuingStrategyHighWaterMark")&&e instanceof ByteLengthQueuingStrategy)}Object.defineProperties(ByteLengthQueuingStrategy.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(ByteLengthQueuingStrategy.prototype,Symbol.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});const Mr=()=>1;n(Mr,"size");class CountQueuingStrategy{constructor(e){F(e,1,"CountQueuingStrategy"),e=Ir(e,"First parameter"),this._countQueuingStrategyHighWaterMark=e.highWaterMark}get highWaterMark(){if(!xr(this))throw Yr("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!xr(this))throw Yr("size");return Mr}}function Yr(e){return new TypeError(`CountQueuingStrategy.prototype.${e} can only be used on a CountQueuingStrategy`)}function xr(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_countQueuingStrategyHighWaterMark")&&e instanceof CountQueuingStrategy)}function Qr(e,t,r){return I(e,r),r=>S(e,t,[r])}function Nr(e,t,r){return I(e,r),r=>y(e,t,[r])}function Hr(e,t,r){return I(e,r),(r,o)=>S(e,t,[r,o])}function Vr(e,t,r){return I(e,r),r=>S(e,t,[r])}Object.defineProperties(CountQueuingStrategy.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(CountQueuingStrategy.prototype,Symbol.toStringTag,{value:"CountQueuingStrategy",configurable:!0});class TransformStream{constructor(e={},t={},r={}){void 0===e&&(e=null);const o=bt(t,"Second parameter"),n=bt(r,"Third parameter"),a=function(e,t){z(e,t);const r=null==e?void 0:e.cancel,o=null==e?void 0:e.flush,n=null==e?void 0:e.readableType,a=null==e?void 0:e.start,i=null==e?void 0:e.transform,l=null==e?void 0:e.writableType;return{cancel:void 0===r?void 0:Vr(r,e,`${t} has member 'cancel' that`),flush:void 0===o?void 0:Qr(o,e,`${t} has member 'flush' that`),readableType:n,start:void 0===a?void 0:Nr(a,e,`${t} has member 'start' that`),transform:void 0===i?void 0:Hr(i,e,`${t} has member 'transform' that`),writableType:l}}(e,"First parameter");if(void 0!==a.readableType)throw new RangeError("Invalid readableType specified");if(void 0!==a.writableType)throw new RangeError("Invalid writableType specified");const i=dt(n,0),l=ft(n),d=dt(o,1),b=ft(o);let m;!function(e,t,r,o,n,a){function i(){return t}function l(t){return function(e,t){const r=e._transformStreamController;if(e._backpressure){return h(e._backpressureChangePromise,(()=>{const o=e._writable;if("erroring"===o._state)throw o._storedError;return ro(r,t)}))}return ro(r,t)}(e,t)}function u(t){return function(e,t){const r=e._transformStreamController;if(void 0!==r._finishPromise)return r._finishPromise;const o=e._readable;r._finishPromise=s(((e,t)=>{r._finishPromise_resolve=e,r._finishPromise_reject=t}));const n=r._cancelAlgorithm(t);return eo(r),f(n,(()=>("errored"===o._state?ao(r,o._storedError):(_r(o._readableStreamController,t),no(r)),null)),(e=>(_r(o._readableStreamController,e),ao(r,e),null))),r._finishPromise}(e,t)}function c(){return function(e){const t=e._transformStreamController;if(void 0!==t._finishPromise)return t._finishPromise;const r=e._readable;t._finishPromise=s(((e,r)=>{t._finishPromise_resolve=e,t._finishPromise_reject=r}));const o=t._flushAlgorithm();return eo(t),f(o,(()=>("errored"===r._state?ao(t,r._storedError):(mr(r._readableStreamController),no(t)),null)),(e=>(_r(r._readableStreamController,e),ao(t,e),null))),t._finishPromise}(e)}function d(){return function(e){return Kr(e,!1),e._backpressureChangePromise}(e)}function b(t){return function(e,t){const r=e._transformStreamController;if(void 0!==r._finishPromise)return r._finishPromise;const o=e._writable;r._finishPromise=s(((e,t)=>{r._finishPromise_resolve=e,r._finishPromise_reject=t}));const n=r._cancelAlgorithm(t);return eo(r),f(n,(()=>("errored"===o._state?ao(r,o._storedError):(Nt(o._writableStreamController,t),Jr(e),no(r)),null)),(t=>(Nt(o._writableStreamController,t),Jr(e),ao(r,t),null))),r._finishPromise}(e,t)}e._writable=function(e,t,r,o,n=1,a=(()=>1)){const i=Object.create(WritableStream.prototype);return wt(i),Mt(i,Object.create(WritableStreamDefaultController.prototype),e,t,r,o,n,a),i}(i,l,c,u,r,o),e._readable=Er(i,d,b,n,a),e._backpressure=void 0,e._backpressureChangePromise=void 0,e._backpressureChangePromise_resolve=void 0,Kr(e,!0),e._transformStreamController=void 0}(this,s((e=>{m=e})),d,b,i,l),function(e,t){const r=Object.create(TransformStreamDefaultController.prototype);let o,n,a;o=void 0!==t.transform?e=>t.transform(e,r):e=>{try{return to(r,e),u(void 0)}catch(e){return c(e)}};n=void 0!==t.flush?()=>t.flush(r):()=>u(void 0);a=void 0!==t.cancel?e=>t.cancel(e):()=>u(void 0);!function(e,t,r,o,n){t._controlledTransformStream=e,e._transformStreamController=t,t._transformAlgorithm=r,t._flushAlgorithm=o,t._cancelAlgorithm=n,t._finishPromise=void 0,t._finishPromise_resolve=void 0,t._finishPromise_reject=void 0}(e,r,o,n,a)}(this,a),void 0!==a.start?m(a.start(this._transformStreamController)):m(void 0)}get readable(){if(!Ur(this))throw io("readable");return this._readable}get writable(){if(!Ur(this))throw io("writable");return this._writable}}function Ur(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_transformStreamController")&&e instanceof TransformStream)}function Gr(e,t){_r(e._readable._readableStreamController,t),Xr(e,t)}function Xr(e,t){eo(e._transformStreamController),Nt(e._writable._writableStreamController,t),Jr(e)}function Jr(e){e._backpressure&&Kr(e,!1)}function Kr(e,t){void 0!==e._backpressureChangePromise&&e._backpressureChangePromise_resolve(),e._backpressureChangePromise=s((t=>{e._backpressureChangePromise_resolve=t})),e._backpressure=t}Object.defineProperties(TransformStream.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(TransformStream.prototype,Symbol.toStringTag,{value:"TransformStream",configurable:!0});class TransformStreamDefaultController{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Zr(this))throw oo("desiredSize");return pr(this._controlledTransformStream._readable._readableStreamController)}enqueue(e=void 0){if(!Zr(this))throw oo("enqueue");to(this,e)}error(e=void 0){if(!Zr(this))throw oo("error");var t;t=e,Gr(this._controlledTransformStream,t)}terminate(){if(!Zr(this))throw oo("terminate");!function(e){const t=e._controlledTransformStream;mr(t._readable._readableStreamController);const r=new TypeError("TransformStream terminated");Xr(t,r)}(this)}}function Zr(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledTransformStream")&&e instanceof TransformStreamDefaultController)}function eo(e){e._transformAlgorithm=void 0,e._flushAlgorithm=void 0,e._cancelAlgorithm=void 0}function to(e,t){const r=e._controlledTransformStream,o=r._readable._readableStreamController;if(!yr(o))throw new TypeError("Readable side is not in a state that permits enqueue");try{hr(o,t)}catch(e){throw Xr(r,e),r._readable._storedError}const n=function(e){return!fr(e)}(o);n!==r._backpressure&&Kr(r,!0)}function ro(e,t){return h(e._transformAlgorithm(t),void 0,(t=>{throw Gr(e._controlledTransformStream,t),t}))}function oo(e){return new TypeError(`TransformStreamDefaultController.prototype.${e} can only be used on a TransformStreamDefaultController`)}function no(e){void 0!==e._finishPromise_resolve&&(e._finishPromise_resolve(),e._finishPromise_resolve=void 0,e._finishPromise_reject=void 0)}function ao(e,t){void 0!==e._finishPromise_reject&&(_(e._finishPromise),e._finishPromise_reject(t),e._finishPromise_resolve=void 0,e._finishPromise_reject=void 0)}function io(e){return new TypeError(`TransformStream.prototype.${e} can only be used on a TransformStream`)}Object.defineProperties(TransformStreamDefaultController.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),n(TransformStreamDefaultController.prototype.enqueue,"enqueue"),n(TransformStreamDefaultController.prototype.error,"error"),n(TransformStreamDefaultController.prototype.terminate,"terminate"),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(TransformStreamDefaultController.prototype,Symbol.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});const lo={ReadableStream:ReadableStream,ReadableStreamDefaultController:ReadableStreamDefaultController,ReadableByteStreamController:ReadableByteStreamController,ReadableStreamBYOBRequest:ReadableStreamBYOBRequest,ReadableStreamDefaultReader:ReadableStreamDefaultReader,ReadableStreamBYOBReader:ReadableStreamBYOBReader,WritableStream:WritableStream,WritableStreamDefaultController:WritableStreamDefaultController,WritableStreamDefaultWriter:WritableStreamDefaultWriter,ByteLengthQueuingStrategy:ByteLengthQueuingStrategy,CountQueuingStrategy:CountQueuingStrategy,TransformStream:TransformStream,TransformStreamDefaultController:TransformStreamDefaultController};if(void 0!==lr)for(const e in lo)Object.prototype.hasOwnProperty.call(lo,e)&&Object.defineProperty(lr,e,{value:lo[e],writable:!0,configurable:!0});e.ByteLengthQueuingStrategy=ByteLengthQueuingStrategy,e.CountQueuingStrategy=CountQueuingStrategy,e.ReadableByteStreamController=ReadableByteStreamController,e.ReadableStream=ReadableStream,e.ReadableStreamBYOBReader=ReadableStreamBYOBReader,e.ReadableStreamBYOBRequest=ReadableStreamBYOBRequest,e.ReadableStreamDefaultController=ReadableStreamDefaultController,e.ReadableStreamDefaultReader=ReadableStreamDefaultReader,e.TransformStream=TransformStream,e.TransformStreamDefaultController=TransformStreamDefaultController,e.WritableStream=WritableStream,e.WritableStreamDefaultController=WritableStreamDefaultController,e.WritableStreamDefaultWriter=WritableStreamDefaultWriter})); +//# sourceMappingURL=polyfill.es6.min.js.map diff --git a/backend/node_modules/web-streams-polyfill/dist/polyfill.es6.min.js.map b/backend/node_modules/web-streams-polyfill/dist/polyfill.es6.min.js.map new file mode 100644 index 0000000000000000000000000000000000000000..8f6055cb7a9870785ff86afb353373bcca961967 --- /dev/null +++ b/backend/node_modules/web-streams-polyfill/dist/polyfill.es6.min.js.map @@ -0,0 +1 @@ +{"version":3,"file":"polyfill.es6.min.js","sources":["../src/utils.ts","../src/lib/helpers/miscellaneous.ts","../src/lib/helpers/webidl.ts","../src/lib/simple-queue.ts","../src/lib/abstract-ops/internal-methods.ts","../src/lib/readable-stream/generic-reader.ts","../src/stub/number-isfinite.ts","../src/stub/math-trunc.ts","../src/lib/validators/basic.ts","../src/lib/validators/readable-stream.ts","../src/lib/readable-stream/default-reader.ts","../node_modules/tslib/tslib.es6.js","../src/lib/abstract-ops/ecmascript.ts","../src/target/es5/stub/async-iterator-prototype.ts","../src/lib/readable-stream/async-iterator.ts","../src/stub/number-isnan.ts","../src/lib/abstract-ops/miscellaneous.ts","../src/lib/abstract-ops/queue-with-sizes.ts","../src/lib/helpers/array-buffer-view.ts","../src/lib/readable-stream/byte-stream-controller.ts","../src/lib/readable-stream/byob-reader.ts","../src/lib/validators/reader-options.ts","../src/lib/abstract-ops/queuing-strategy.ts","../src/lib/validators/queuing-strategy.ts","../src/lib/validators/underlying-sink.ts","../src/lib/validators/writable-stream.ts","../src/lib/abort-signal.ts","../src/lib/writable-stream.ts","../src/globals.ts","../src/stub/dom-exception.ts","../src/lib/readable-stream/pipe.ts","../src/lib/readable-stream/default-controller.ts","../src/lib/readable-stream/tee.ts","../src/lib/readable-stream/from.ts","../src/lib/readable-stream/readable-stream-like.ts","../src/lib/validators/underlying-source.ts","../src/lib/validators/pipe-options.ts","../src/lib/readable-stream.ts","../src/lib/validators/readable-writable-pair.ts","../src/lib/validators/iterator-options.ts","../src/lib/validators/queuing-strategy-init.ts","../src/lib/byte-length-queuing-strategy.ts","../src/lib/count-queuing-strategy.ts","../src/lib/validators/transformer.ts","../src/lib/transform-stream.ts","../src/polyfill.ts"],"sourcesContent":["export function noop(): undefined {\n return undefined;\n}\n","import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n\nexport function setFunctionName(fn: Function, name: string): void {\n try {\n Object.defineProperty(fn, 'name', {\n value: name,\n configurable: true\n });\n } catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n }\n}\n","import { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\n// https://webidl.spec.whatwg.org/#a-new-promise\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-resolved-with\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return newPromise(resolve => resolve(value));\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-rejected-with\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\n// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned\n// from that handler. To prevent this, return null instead of void from all handlers.\n// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => null | PromiseLike,\n onRejected?: (reason: any) => null | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => null | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => null | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nlet _queueMicrotask: (callback: () => void) => void = callback => {\n if (typeof queueMicrotask === 'function') {\n _queueMicrotask = queueMicrotask;\n } else {\n const resolvedPromise = promiseResolvedWith(undefined);\n _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb);\n }\n return _queueMicrotask(callback);\n};\n\nexport { _queueMicrotask as queueMicrotask };\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n","import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n","export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\nexport const ReleaseSteps = Symbol('[[ReleaseSteps]]');\n","import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, type ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\nimport { ReleaseSteps } from '../abstract-ops/internal-methods';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n assert(stream._reader === reader);\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n stream._readableStreamController[ReleaseSteps]();\n\n stream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n","import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n","import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamDefaultReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamDefaultReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\nexport function ReadableStreamDefaultReaderRelease(reader: ReadableStreamDefaultReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n}\n\nexport function ReadableStreamDefaultReaderErrorReadRequests(reader: ReadableStreamDefaultReader, e: any) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n","/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise, SuppressedError, Symbol */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\r\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\r\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\r\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\r\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\r\n var _, done = false;\r\n for (var i = decorators.length - 1; i >= 0; i--) {\r\n var context = {};\r\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\r\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\r\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\r\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\r\n if (kind === \"accessor\") {\r\n if (result === void 0) continue;\r\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\r\n if (_ = accept(result.get)) descriptor.get = _;\r\n if (_ = accept(result.set)) descriptor.set = _;\r\n if (_ = accept(result.init)) initializers.unshift(_);\r\n }\r\n else if (_ = accept(result)) {\r\n if (kind === \"field\") initializers.unshift(_);\r\n else descriptor[key] = _;\r\n }\r\n }\r\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\r\n done = true;\r\n};\r\n\r\nexport function __runInitializers(thisArg, initializers, value) {\r\n var useValue = arguments.length > 2;\r\n for (var i = 0; i < initializers.length; i++) {\r\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\r\n }\r\n return useValue ? value : void 0;\r\n};\r\n\r\nexport function __propKey(x) {\r\n return typeof x === \"symbol\" ? x : \"\".concat(x);\r\n};\r\n\r\nexport function __setFunctionName(f, name, prefix) {\r\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\r\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\r\n};\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n var desc = Object.getOwnPropertyDescriptor(m, k);\r\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\r\n desc = { enumerable: true, get: function() { return m[k]; } };\r\n }\r\n Object.defineProperty(o, k2, desc);\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\nexport function __classPrivateFieldIn(state, receiver) {\r\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\r\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\r\n}\r\n\r\nexport function __addDisposableResource(env, value, async) {\r\n if (value !== null && value !== void 0) {\r\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\r\n var dispose;\r\n if (async) {\r\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\r\n dispose = value[Symbol.asyncDispose];\r\n }\r\n if (dispose === void 0) {\r\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\r\n dispose = value[Symbol.dispose];\r\n }\r\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\r\n env.stack.push({ value: value, dispose: dispose, async: async });\r\n }\r\n else if (async) {\r\n env.stack.push({ async: true });\r\n }\r\n return value;\r\n}\r\n\r\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n};\r\n\r\nexport function __disposeResources(env) {\r\n function fail(e) {\r\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\r\n env.hasError = true;\r\n }\r\n function next() {\r\n while (env.stack.length) {\r\n var rec = env.stack.pop();\r\n try {\r\n var result = rec.dispose && rec.dispose.call(rec.value);\r\n if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\r\n }\r\n catch (e) {\r\n fail(e);\r\n }\r\n }\r\n if (env.hasError) throw env.error;\r\n }\r\n return next();\r\n}\r\n\r\nexport default {\r\n __extends: __extends,\r\n __assign: __assign,\r\n __rest: __rest,\r\n __decorate: __decorate,\r\n __param: __param,\r\n __metadata: __metadata,\r\n __awaiter: __awaiter,\r\n __generator: __generator,\r\n __createBinding: __createBinding,\r\n __exportStar: __exportStar,\r\n __values: __values,\r\n __read: __read,\r\n __spread: __spread,\r\n __spreadArrays: __spreadArrays,\r\n __spreadArray: __spreadArray,\r\n __await: __await,\r\n __asyncGenerator: __asyncGenerator,\r\n __asyncDelegator: __asyncDelegator,\r\n __asyncValues: __asyncValues,\r\n __makeTemplateObject: __makeTemplateObject,\r\n __importStar: __importStar,\r\n __importDefault: __importDefault,\r\n __classPrivateFieldGet: __classPrivateFieldGet,\r\n __classPrivateFieldSet: __classPrivateFieldSet,\r\n __classPrivateFieldIn: __classPrivateFieldIn,\r\n __addDisposableResource: __addDisposableResource,\r\n __disposeResources: __disposeResources,\r\n};\r\n","import { reflectCall } from 'lib/helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport assert from '../../stub/assert';\n\ndeclare global {\n interface ArrayBuffer {\n readonly detached: boolean;\n\n transfer(): ArrayBuffer;\n }\n\n function structuredClone(value: T, options: { transfer: ArrayBuffer[] }): T;\n}\n\nexport function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\nexport let TransferArrayBuffer = (O: ArrayBuffer): ArrayBuffer => {\n if (typeof O.transfer === 'function') {\n TransferArrayBuffer = buffer => buffer.transfer();\n } else if (typeof structuredClone === 'function') {\n TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] });\n } else {\n // Not implemented correctly\n TransferArrayBuffer = buffer => buffer;\n }\n return TransferArrayBuffer(O);\n};\n\nexport function CanTransferArrayBuffer(O: ArrayBuffer): boolean {\n return !IsDetachedBuffer(O);\n}\n\nexport let IsDetachedBuffer = (O: ArrayBuffer): boolean => {\n if (typeof O.detached === 'boolean') {\n IsDetachedBuffer = buffer => buffer.detached;\n } else {\n // Not implemented correctly\n IsDetachedBuffer = buffer => buffer.byteLength === 0;\n }\n return IsDetachedBuffer(O);\n};\n\nexport function ArrayBufferSlice(buffer: ArrayBuffer, begin: number, end: number): ArrayBuffer {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n\nexport type MethodName = {\n [P in keyof T]: T[P] extends Function | undefined ? P : never;\n}[keyof T];\n\nexport function GetMethod>(receiver: T, prop: K): T[K] | undefined {\n const func = receiver[prop];\n if (func === undefined || func === null) {\n return undefined;\n }\n if (typeof func !== 'function') {\n throw new TypeError(`${String(prop)} is not a function`);\n }\n return func;\n}\n\nexport interface SyncIteratorRecord {\n iterator: Iterator,\n nextMethod: Iterator['next'],\n done: boolean;\n}\n\nexport interface AsyncIteratorRecord {\n iterator: AsyncIterator,\n nextMethod: AsyncIterator['next'],\n done: boolean;\n}\n\nexport type SyncOrAsyncIteratorRecord = SyncIteratorRecord | AsyncIteratorRecord;\n\nexport function CreateAsyncFromSyncIterator(syncIteratorRecord: SyncIteratorRecord): AsyncIteratorRecord {\n // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%,\n // we use yield* inside an async generator function to achieve the same result.\n\n // Wrap the sync iterator inside a sync iterable, so we can use it with yield*.\n const syncIterable = {\n [Symbol.iterator]: () => syncIteratorRecord.iterator\n };\n // Create an async generator function and immediately invoke it.\n const asyncIterator = (async function* () {\n return yield* syncIterable;\n }());\n // Return as an async iterator record.\n const nextMethod = asyncIterator.next;\n return { iterator: asyncIterator, nextMethod, done: false };\n}\n\n// Aligns with core-js/modules/es.symbol.async-iterator.js\nexport const SymbolAsyncIterator: (typeof Symbol)['asyncIterator'] =\n Symbol.asyncIterator ??\n Symbol.for?.('Symbol.asyncIterator') ??\n '@@asyncIterator';\n\nexport type SyncOrAsyncIterable = Iterable | AsyncIterable;\nexport type SyncOrAsyncIteratorMethod = () => (Iterator | AsyncIterator);\n\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint: 'async',\n method?: SyncOrAsyncIteratorMethod\n): AsyncIteratorRecord;\nfunction GetIterator(\n obj: Iterable,\n hint: 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncIteratorRecord;\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint = 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncOrAsyncIteratorRecord {\n assert(hint === 'sync' || hint === 'async');\n if (method === undefined) {\n if (hint === 'async') {\n method = GetMethod(obj as AsyncIterable, SymbolAsyncIterator);\n if (method === undefined) {\n const syncMethod = GetMethod(obj as Iterable, Symbol.iterator);\n const syncIteratorRecord = GetIterator(obj as Iterable, 'sync', syncMethod);\n return CreateAsyncFromSyncIterator(syncIteratorRecord);\n }\n } else {\n method = GetMethod(obj as Iterable, Symbol.iterator);\n }\n }\n if (method === undefined) {\n throw new TypeError('The object is not iterable');\n }\n const iterator = reflectCall(method, obj, []);\n if (!typeIsObject(iterator)) {\n throw new TypeError('The iterator method must return an object');\n }\n const nextMethod = iterator.next;\n return { iterator, nextMethod, done: false } as SyncOrAsyncIteratorRecord;\n}\n\nexport { GetIterator };\n\nexport function IteratorNext(iteratorRecord: AsyncIteratorRecord): Promise> {\n const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []);\n if (!typeIsObject(result)) {\n throw new TypeError('The iterator.next() method must return an object');\n }\n return result;\n}\n\nexport function IteratorComplete(\n iterResult: IteratorResult\n): iterResult is IteratorReturnResult {\n assert(typeIsObject(iterResult));\n return Boolean(iterResult.done);\n}\n\nexport function IteratorValue(iterResult: IteratorYieldResult): T {\n assert(typeIsObject(iterResult));\n return iterResult.value;\n}\n","/// \n\nimport { SymbolAsyncIterator } from '../../../lib/abstract-ops/ecmascript';\n\n// We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it.\nexport const AsyncIteratorPrototype: AsyncIterable = {\n // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( )\n // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator\n [SymbolAsyncIterator](this: AsyncIterator) {\n return this;\n }\n};\nObject.defineProperty(AsyncIteratorPrototype, SymbolAsyncIterator, { enumerable: false });\n","/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadableStreamDefaultReadResult,\n type ReadRequest\n} from './default-reader';\nimport { ReadableStreamReaderGenericCancel, ReadableStreamReaderGenericRelease } from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterableIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ninterface ReadableStreamAsyncIteratorInstance extends ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nObject.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n","import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: NonShared): NonShared {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer) as NonShared;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n","export type TypedArray =\n | Int8Array\n | Uint8Array\n | Uint8ClampedArray\n | Int16Array\n | Uint16Array\n | Int32Array\n | Uint32Array\n | Float32Array\n | Float64Array;\n\nexport type NonShared = T & {\n buffer: ArrayBuffer;\n}\n\nexport interface ArrayBufferViewConstructor {\n new(buffer: ArrayBuffer, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n}\n\nexport interface TypedArrayConstructor extends ArrayBufferViewConstructor {\n readonly BYTES_PER_ELEMENT: number;\n}\n\nexport type DataViewConstructor = ArrayBufferViewConstructor;\n\nfunction isDataViewConstructor(ctor: Function): ctor is DataViewConstructor {\n return ctor === DataView;\n}\n\nexport function isDataView(view: ArrayBufferView): view is DataView {\n return isDataViewConstructor(view.constructor);\n}\n\nexport function arrayBufferViewElementSize(ctor: ArrayBufferViewConstructor): number {\n if (isDataViewConstructor(ctor)) {\n return 1;\n }\n return (ctor as unknown as TypedArrayConstructor).BYTES_PER_ELEMENT;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n IsReadableStreamDefaultReader,\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n type ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n type ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n type ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport type { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\nimport {\n type ArrayBufferViewConstructor,\n arrayBufferViewElementSize,\n type NonShared,\n type TypedArrayConstructor\n} from '../helpers/array-buffer-view';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: NonShared | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: NonShared): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond');\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBuffer;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor = NonShared> =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: TypedArrayConstructor;\n readerType: 'default' | 'none';\n}\n\ninterface BYOBPullIntoDescriptor = NonShared> {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob' | 'none';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: NonShared): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest>): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n minimumFill: 1,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n if (this._pendingPullIntos.length > 0) {\n const firstPullInto = this._pendingPullIntos.peek();\n firstPullInto.readerType = 'none';\n\n this._pendingPullIntos = new SimpleQueue();\n this._pendingPullIntos.push(firstPullInto);\n }\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableByteStreamController.prototype.close, 'close');\nsetFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableByteStreamController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor>(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n assert(pullIntoDescriptor.readerType !== 'none');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as NonShared, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor>(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n let clonedChunk;\n try {\n clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength);\n } catch (cloneE) {\n ReadableByteStreamControllerError(controller, cloneE);\n throw cloneE;\n }\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength);\n}\n\nfunction ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.readerType === 'none');\n if (firstDescriptor.bytesFilled > 0) {\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n firstDescriptor.buffer,\n firstDescriptor.byteOffset,\n firstDescriptor.bytesFilled\n );\n }\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize;\n const maxAlignedBytes = maxBytesFilled - remainderBytes;\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n assert(pullIntoDescriptor.readerType !== 'none');\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nfunction ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller: ReadableByteStreamController) {\n const reader = controller._controlledReadableByteStream._reader;\n assert(IsReadableStreamDefaultReader(reader));\n while (reader._readRequests.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n const readRequest = reader._readRequests.shift();\n ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest);\n }\n}\n\nexport function ReadableByteStreamControllerPullInto>(\n controller: ReadableByteStreamController,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n const elementSize = arrayBufferViewElementSize(ctor);\n\n const { byteOffset, byteLength } = view;\n\n const minimumFill = min * elementSize;\n assert(minimumFill >= elementSize && minimumFill <= byteLength);\n assert(minimumFill % elementSize === 0);\n\n let buffer: ArrayBuffer;\n try {\n buffer = TransferArrayBuffer(view.buffer);\n } catch (e) {\n readIntoRequest._errorSteps(e);\n return;\n }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset,\n byteLength,\n bytesFilled: 0,\n minimumFill,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled % firstDescriptor.elementSize === 0);\n\n if (firstDescriptor.readerType === 'none') {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n return;\n }\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) {\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n pullIntoDescriptor.buffer,\n end - remainderSize,\n remainderSize\n );\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(\n controller: ReadableByteStreamController,\n chunk: NonShared\n) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const { buffer, byteOffset, byteLength } = chunk;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n if (firstPendingPullInto.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto);\n }\n }\n\n if (ReadableStreamHasDefaultReader(stream)) {\n ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller);\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView as NonShared, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerFillReadRequestFromQueue(\n controller: ReadableByteStreamController,\n readRequest: ReadRequest>\n) {\n assert(controller._queueTotalSize > 0);\n\n const entry = controller._queue.shift();\n controller._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n readRequest._chunkSteps(view as NonShared);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view as NonShared);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: NonShared) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: NonShared) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, type ReadableByteStream, type ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from './reader-options';\nimport { convertByobReadOptions } from '../validators/reader-options';\nimport { isDataView, type NonShared, type TypedArray } from '../helpers/array-buffer-view';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream as ReadableStream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest>(\n stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest\n): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest> {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(\n view: T,\n options?: ReadableStreamBYOBReaderReadOptions\n ): Promise>;\n read>(\n view: T,\n rawOptions: ReadableStreamBYOBReaderReadOptions | null | undefined = {}\n ): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n let options: ValidatedReadableStreamBYOBReaderReadOptions;\n try {\n options = convertByobReadOptions(rawOptions, 'options');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const min = options.min;\n if (min === 0) {\n return promiseRejectedWith(new TypeError('options.min must be greater than 0'));\n }\n if (!isDataView(view)) {\n if (min > (view as unknown as TypedArray).length) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s length'));\n }\n } else if (min > view.byteLength) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s byteLength'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamBYOBReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamBYOBReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead>(\n reader: ReadableStreamBYOBReader,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n min,\n readIntoRequest\n );\n }\n}\n\nexport function ReadableStreamBYOBReaderRelease(reader: ReadableStreamBYOBReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n}\n\nexport function ReadableStreamBYOBReaderErrorReadIntoRequests(reader: ReadableStreamBYOBReader, e: any) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n","import { assertDictionary, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n\nexport function convertByobReadOptions(\n options: ReadableStreamBYOBReaderReadOptions | null | undefined,\n context: string\n): ValidatedReadableStreamBYOBReaderReadOptions {\n assertDictionary(options, context);\n const min = options?.min ?? 1;\n return {\n min: convertUnsignedLongLongWithEnforceRange(\n min,\n `${context} has member 'min' that`\n )\n };\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n","/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * If aborted, returns the reason for aborting.\n */\n readonly reason?: any;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(reason?: any): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n type QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { type AbortController, type AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(WritableStream.prototype.abort, 'abort');\nsetFunctionName(WritableStream.prototype.close, 'close');\nsetFunctionName(WritableStream.prototype.getWriter, 'getWriter');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight\n};\n\nexport type {\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort(reason);\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nsetFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort');\nsetFunctionName(WritableStreamDefaultWriter.prototype.close, 'close');\nsetFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock');\nsetFunctionName(WritableStreamDefaultWriter.prototype.write, 'write');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n return null;\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let writeAlgorithm: (chunk: W) => Promise;\n let closeAlgorithm: () => Promise;\n let abortAlgorithm: (reason: any) => Promise;\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n } else {\n writeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n } else {\n closeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n } else {\n abortAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n return null;\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n","/// \n\nfunction getGlobals(): typeof globalThis | undefined {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n } else if (typeof self !== 'undefined') {\n return self;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n","/// \nimport { globals } from '../globals';\nimport { setFunctionName } from '../lib/helpers/miscellaneous';\n\ninterface DOMException extends Error {\n name: string;\n message: string;\n}\n\ntype DOMExceptionConstructor = new (message?: string, name?: string) => DOMException;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n if ((ctor as DOMExceptionConstructor).name !== 'DOMException') {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Support:\n * - Web browsers\n * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87)\n */\nfunction getFromGlobal(): DOMExceptionConstructor | undefined {\n const ctor = globals?.DOMException;\n return isDOMExceptionConstructor(ctor) ? ctor : undefined;\n}\n\n/**\n * Support:\n * - All platforms\n */\nfunction createPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line @typescript-eslint/no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n setFunctionName(ctor, 'DOMException');\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nconst DOMException: DOMExceptionConstructor = getFromGlobal() || createPolyfill();\n\nexport { DOMException };\n","import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n return null;\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => null) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => null) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest(): null {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n return null;\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any): null {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n\n return null;\n }\n });\n}\n","import type { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, type QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n type ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport type { ValidatedUnderlyingSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n // Do nothing.\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultController.prototype.close, 'close');\nsetFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableStreamDefaultController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n","import {\n CreateReadableByteStream,\n CreateReadableStream,\n type DefaultReadableStream,\n IsReadableStream,\n type ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n type ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n type ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(\n stream: ReadableStream,\n cloneForBranch2: boolean\n): [DefaultReadableStream, DefaultReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: DefaultReadableStream;\n let branch2: DefaultReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader> = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader>) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return null;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: NonShared, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader>(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n","import { CreateReadableStream, type DefaultReadableStream } from '../readable-stream';\nimport {\n isReadableStreamLike,\n type ReadableStreamDefaultReaderLike,\n type ReadableStreamLike\n} from './readable-stream-like';\nimport { ReadableStreamDefaultControllerClose, ReadableStreamDefaultControllerEnqueue } from './default-controller';\nimport { GetIterator, GetMethod, IteratorComplete, IteratorNext, IteratorValue } from '../abstract-ops/ecmascript';\nimport { promiseRejectedWith, promiseResolvedWith, reflectCall, transformPromiseWith } from '../helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { noop } from '../../utils';\n\nexport function ReadableStreamFrom(\n source: Iterable | AsyncIterable | ReadableStreamLike\n): DefaultReadableStream {\n if (isReadableStreamLike(source)) {\n return ReadableStreamFromDefaultReader(source.getReader());\n }\n return ReadableStreamFromIterable(source);\n}\n\nexport function ReadableStreamFromIterable(asyncIterable: Iterable | AsyncIterable): DefaultReadableStream {\n let stream: DefaultReadableStream;\n const iteratorRecord = GetIterator(asyncIterable, 'async');\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let nextResult;\n try {\n nextResult = IteratorNext(iteratorRecord);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const nextPromise = promiseResolvedWith(nextResult);\n return transformPromiseWith(nextPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object');\n }\n const done = IteratorComplete(iterResult);\n if (done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = IteratorValue(iterResult);\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n const iterator = iteratorRecord.iterator;\n let returnMethod: (typeof iterator)['return'] | undefined;\n try {\n returnMethod = GetMethod(iterator, 'return');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n if (returnMethod === undefined) {\n return promiseResolvedWith(undefined);\n }\n let returnResult: IteratorResult | Promise>;\n try {\n returnResult = reflectCall(returnMethod, iterator, [reason]);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const returnPromise = promiseResolvedWith(returnResult);\n return transformPromiseWith(returnPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object');\n }\n return undefined;\n });\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n\nexport function ReadableStreamFromDefaultReader(\n reader: ReadableStreamDefaultReaderLike\n): DefaultReadableStream {\n let stream: DefaultReadableStream;\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let readPromise;\n try {\n readPromise = reader.read();\n } catch (e) {\n return promiseRejectedWith(e);\n }\n return transformPromiseWith(readPromise, readResult => {\n if (!typeIsObject(readResult)) {\n throw new TypeError('The promise returned by the reader.read() method must fulfill with an object');\n }\n if (readResult.done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = readResult.value;\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n try {\n return promiseResolvedWith(reader.cancel(reason));\n } catch (e) {\n return promiseRejectedWith(e);\n }\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n","import { typeIsObject } from '../helpers/miscellaneous';\nimport type { ReadableStreamDefaultReadResult } from './default-reader';\n\n/**\n * A common interface for a `ReadadableStream` implementation.\n *\n * @public\n */\nexport interface ReadableStreamLike {\n readonly locked: boolean;\n\n getReader(): ReadableStreamDefaultReaderLike;\n}\n\n/**\n * A common interface for a `ReadableStreamDefaultReader` implementation.\n *\n * @public\n */\nexport interface ReadableStreamDefaultReaderLike {\n readonly closed: Promise;\n\n cancel(reason?: any): Promise;\n\n read(): Promise>;\n\n releaseLock(): void;\n}\n\nexport function isReadableStreamLike(stream: unknown): stream is ReadableStreamLike {\n return typeIsObject(stream) && typeof (stream as ReadableStreamLike).getReader !== 'undefined';\n}\n","import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n","import { assertDictionary } from './basic';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n","import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, type ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderErrorReadRequests,\n type ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReaderErrorReadIntoRequests,\n type ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { ReadableStreamFrom } from './readable-stream/from';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport type {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList, SymbolAsyncIterator } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions\n} from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport type { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport type { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\nimport type { ReadableStreamDefaultReaderLike, ReadableStreamLike } from './readable-stream/readable-stream-like';\nimport type { NonShared } from './helpers/array-buffer-view';\n\nexport type DefaultReadableStream = ReadableStream & {\n _readableStreamController: ReadableStreamDefaultController\n};\n\nexport type ReadableByteStream = ReadableStream> & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream implements AsyncIterable {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n\n [SymbolAsyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator {\n // Stub implementation, overridden below\n return this.values(options);\n }\n\n /**\n * Creates a new ReadableStream wrapping the provided iterable or async iterable.\n *\n * This can be used to adapt various kinds of objects into a readable stream,\n * such as an array, an async generator, or a Node.js readable stream.\n */\n static from(asyncIterable: Iterable | AsyncIterable | ReadableStreamLike): ReadableStream {\n return ReadableStreamFrom(asyncIterable);\n }\n}\n\nObject.defineProperties(ReadableStream, {\n from: { enumerable: true }\n});\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(ReadableStream.from, 'from');\nsetFunctionName(ReadableStream.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStream.prototype.getReader, 'getReader');\nsetFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough');\nsetFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo');\nsetFunctionName(ReadableStream.prototype.tee, 'tee');\nsetFunctionName(ReadableStream.prototype.values, 'values');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nObject.defineProperty(ReadableStream.prototype, SymbolAsyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n});\n\nexport type {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n ReadableStreamBYOBReaderReadOptions,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions,\n ReadableStreamLike,\n ReadableStreamDefaultReaderLike\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1\n): DefaultReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: DefaultReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n","import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n","import { assertDictionary } from './basic';\nimport type {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n","import type { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\nsetFunctionName(byteLengthSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\nsetFunctionName(countSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const cancel = original?.cancel;\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n cancel: cancel === undefined ?\n undefined :\n convertTransformerCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n\nfunction convertTransformerCancelCallback(\n fn: TransformerCancelCallback,\n original: Transformer,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith,\n uponPromise\n} from './helpers/webidl';\nimport { CreateReadableStream, type DefaultReadableStream, ReadableStream } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: DefaultReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport type {\n Transformer,\n TransformerCancelCallback,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSourceCancelAlgorithm(stream, reason);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n TransformStreamUnblockWrite(stream);\n}\n\nfunction TransformStreamUnblockWrite(stream: TransformStream) {\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _finishPromise: Promise | undefined;\n /** @internal */\n _finishPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _finishPromise_reject?: (reason: any) => void;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n /** @internal */\n _cancelAlgorithm: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(TransformStreamDefaultController.prototype.error, 'error');\nsetFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._finishPromise = undefined;\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm: (chunk: I) => Promise;\n let flushAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n } else {\n transformAlgorithm = chunk => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n }\n\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n } else {\n flushAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n if (transformer.cancel !== undefined) {\n cancelAlgorithm = reason => transformer.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally,\n // we don't run the _cancelAlgorithm again.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerError(readable._readableStreamController, reason);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally,\n // we don't also run the _cancelAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(flushPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerClose(readable._readableStreamController);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\nfunction TransformStreamDefaultSourceCancelAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._writable cannot change after construction, so caching it across a call to user code is safe.\n const writable = stream._writable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or\n // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the\n // _flushAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (writable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, writable._storedError);\n } else {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\nexport function defaultControllerFinishPromiseResolve(controller: TransformStreamDefaultController) {\n if (controller._finishPromise_resolve === undefined) {\n return;\n }\n\n controller._finishPromise_resolve();\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nexport function defaultControllerFinishPromiseReject(controller: TransformStreamDefaultController, reason: any) {\n if (controller._finishPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(controller._finishPromise!);\n controller._finishPromise_reject(reason);\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n","import {\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n ReadableByteStreamController,\n ReadableStream,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultController,\n ReadableStreamDefaultReader,\n TransformStream,\n TransformStreamDefaultController,\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter\n} from './ponyfill';\nimport { globals } from './globals';\n\n// Export\nexport * from './ponyfill';\n\nconst exports = {\n ReadableStream,\n ReadableStreamDefaultController,\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader,\n\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter,\n\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n\n TransformStream,\n TransformStreamDefaultController\n};\n\n// Add classes to global scope\nif (typeof globals !== 'undefined') {\n for (const prop in exports) {\n if (Object.prototype.hasOwnProperty.call(exports, prop)) {\n Object.defineProperty(globals, prop, {\n value: exports[prop as (keyof typeof exports)],\n writable: true,\n configurable: true\n });\n }\n }\n}\n"],"names":["noop","typeIsObject","x","rethrowAssertionErrorRejection","setFunctionName","fn","name","Object","defineProperty","value","configurable","_a","originalPromise","Promise","originalPromiseThen","prototype","then","originalPromiseReject","reject","bind","newPromise","executor","promiseResolvedWith","resolve","promiseRejectedWith","reason","PerformPromiseThen","promise","onFulfilled","onRejected","call","uponPromise","undefined","uponFulfillment","uponRejection","transformPromiseWith","fulfillmentHandler","rejectionHandler","setPromiseIsHandledToTrue","_queueMicrotask","callback","queueMicrotask","resolvedPromise","cb","reflectCall","F","V","args","TypeError","Function","apply","promiseCall","SimpleQueue","constructor","this","_cursor","_size","_front","_elements","_next","_back","length","push","element","oldBack","newBack","QUEUE_MAX_ARRAY_SIZE","shift","oldFront","newFront","oldCursor","newCursor","elements","forEach","i","node","peek","front","cursor","AbortSteps","Symbol","ErrorSteps","CancelSteps","PullSteps","ReleaseSteps","ReadableStreamReaderGenericInitialize","reader","stream","_ownerReadableStream","_reader","_state","defaultReaderClosedPromiseInitialize","defaultReaderClosedPromiseResolve","defaultReaderClosedPromiseInitializeAsResolved","defaultReaderClosedPromiseInitializeAsRejected","_storedError","ReadableStreamReaderGenericCancel","ReadableStreamCancel","ReadableStreamReaderGenericRelease","defaultReaderClosedPromiseReject","defaultReaderClosedPromiseResetToRejected","_readableStreamController","readerLockException","_closedPromise","_closedPromise_resolve","_closedPromise_reject","NumberIsFinite","Number","isFinite","MathTrunc","Math","trunc","v","ceil","floor","assertDictionary","obj","context","assertFunction","assertObject","isObject","assertRequiredArgument","position","assertRequiredField","field","convertUnrestrictedDouble","censorNegativeZero","convertUnsignedLongLongWithEnforceRange","upperBound","MAX_SAFE_INTEGER","integerPart","assertReadableStream","IsReadableStream","AcquireReadableStreamDefaultReader","ReadableStreamDefaultReader","ReadableStreamAddReadRequest","readRequest","_readRequests","ReadableStreamFulfillReadRequest","chunk","done","_closeSteps","_chunkSteps","ReadableStreamGetNumReadRequests","ReadableStreamHasDefaultReader","IsReadableStreamDefaultReader","IsReadableStreamLocked","closed","defaultReaderBrandCheckException","cancel","read","resolvePromise","rejectPromise","ReadableStreamDefaultReaderRead","_errorSteps","e","releaseLock","ReadableStreamDefaultReaderErrorReadRequests","ReadableStreamDefaultReaderRelease","hasOwnProperty","_disturbed","readRequests","__values","o","s","iterator","m","next","__await","__asyncGenerator","thisArg","_arguments","generator","asyncIterator","g","q","verb","n","a","b","resume","r","fulfill","settle","f","__asyncValues","d","CreateArrayFromList","slice","CopyDataBlockBytes","dest","destOffset","src","srcOffset","Uint8Array","set","defineProperties","enumerable","toStringTag","SuppressedError","TransferArrayBuffer","O","transfer","buffer","structuredClone","IsDetachedBuffer","detached","byteLength","ArrayBufferSlice","begin","end","ArrayBuffer","GetMethod","receiver","prop","func","String","CreateAsyncFromSyncIterator","syncIteratorRecord","syncIterable","p","__asyncDelegator","nextMethod","SymbolAsyncIterator","_c","_b","for","GetIterator","hint","method","AsyncIteratorPrototype","ReadableStreamAsyncIteratorImpl","preventCancel","_ongoingPromise","_isFinished","_preventCancel","nextSteps","_nextSteps","returnSteps","_returnSteps","result","ReadableStreamAsyncIteratorPrototype","IsReadableStreamAsyncIterator","_asyncIteratorImpl","streamAsyncIteratorBrandCheckException","return","setPrototypeOf","NumberIsNaN","isNaN","CloneAsUint8Array","byteOffset","DequeueValue","container","pair","_queue","_queueTotalSize","size","EnqueueValueWithSize","Infinity","RangeError","ResetQueue","isDataViewConstructor","ctor","DataView","ReadableStreamBYOBRequest","view","IsReadableStreamBYOBRequest","byobRequestBrandCheckException","_view","respond","bytesWritten","_associatedReadableByteStreamController","ReadableByteStreamControllerRespond","respondWithNewView","isView","ReadableByteStreamControllerRespondWithNewView","ReadableByteStreamController","byobRequest","IsReadableByteStreamController","byteStreamControllerBrandCheckException","ReadableByteStreamControllerGetBYOBRequest","desiredSize","ReadableByteStreamControllerGetDesiredSize","close","_closeRequested","state","_controlledReadableByteStream","ReadableByteStreamControllerClose","enqueue","ReadableByteStreamControllerEnqueue","error","ReadableByteStreamControllerError","ReadableByteStreamControllerClearPendingPullIntos","_cancelAlgorithm","ReadableByteStreamControllerClearAlgorithms","ReadableByteStreamControllerFillReadRequestFromQueue","autoAllocateChunkSize","_autoAllocateChunkSize","bufferE","pullIntoDescriptor","bufferByteLength","bytesFilled","minimumFill","elementSize","viewConstructor","readerType","_pendingPullIntos","ReadableByteStreamControllerCallPullIfNeeded","firstPullInto","controller","shouldPull","_started","ReadableStreamHasBYOBReader","ReadableStreamGetNumReadIntoRequests","ReadableByteStreamControllerShouldCallPull","_pulling","_pullAgain","_pullAlgorithm","ReadableByteStreamControllerInvalidateBYOBRequest","ReadableByteStreamControllerCommitPullIntoDescriptor","filledView","ReadableByteStreamControllerConvertPullIntoDescriptor","readIntoRequest","_readIntoRequests","ReadableStreamFulfillReadIntoRequest","ReadableByteStreamControllerEnqueueChunkToQueue","ReadableByteStreamControllerEnqueueClonedChunkToQueue","clonedChunk","cloneE","ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue","firstDescriptor","ReadableByteStreamControllerShiftPendingPullInto","ReadableByteStreamControllerFillPullIntoDescriptorFromQueue","maxBytesToCopy","min","maxBytesFilled","totalBytesToCopyRemaining","ready","maxAlignedBytes","queue","headOfQueue","bytesToCopy","destStart","ReadableByteStreamControllerFillHeadPullIntoDescriptor","ReadableByteStreamControllerHandleQueueDrain","ReadableStreamClose","_byobRequest","ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue","ReadableByteStreamControllerPullInto","BYTES_PER_ELEMENT","arrayBufferViewElementSize","ReadableStreamAddReadIntoRequest","emptyView","ReadableByteStreamControllerRespondInternal","ReadableByteStreamControllerRespondInClosedState","remainderSize","ReadableByteStreamControllerRespondInReadableState","firstPendingPullInto","transferredBuffer","ReadableByteStreamControllerProcessReadRequestsUsingQueue","ReadableStreamError","entry","create","request","SetUpReadableStreamBYOBRequest","_strategyHWM","viewByteLength","SetUpReadableByteStreamController","startAlgorithm","pullAlgorithm","cancelAlgorithm","highWaterMark","convertReadableStreamReaderMode","mode","AcquireReadableStreamBYOBReader","ReadableStreamBYOBReader","IsReadableStreamBYOBReader","byobReaderBrandCheckException","rawOptions","options","convertByobReadOptions","isDataView","ReadableStreamBYOBReaderRead","ReadableStreamBYOBReaderErrorReadIntoRequests","ReadableStreamBYOBReaderRelease","readIntoRequests","ExtractHighWaterMark","strategy","defaultHWM","ExtractSizeAlgorithm","convertQueuingStrategy","init","convertQueuingStrategySize","convertUnderlyingSinkAbortCallback","original","convertUnderlyingSinkCloseCallback","convertUnderlyingSinkStartCallback","convertUnderlyingSinkWriteCallback","assertWritableStream","IsWritableStream","supportsAbortController","AbortController","WritableStream","rawUnderlyingSink","rawStrategy","underlyingSink","abort","start","type","write","convertUnderlyingSink","InitializeWritableStream","sizeAlgorithm","WritableStreamDefaultController","writeAlgorithm","closeAlgorithm","abortAlgorithm","SetUpWritableStreamDefaultController","SetUpWritableStreamDefaultControllerFromUnderlyingSink","locked","streamBrandCheckException","IsWritableStreamLocked","WritableStreamAbort","WritableStreamCloseQueuedOrInFlight","WritableStreamClose","getWriter","AcquireWritableStreamDefaultWriter","WritableStreamDefaultWriter","_writer","_writableStreamController","_writeRequests","_inFlightWriteRequest","_closeRequest","_inFlightCloseRequest","_pendingAbortRequest","_backpressure","_abortReason","_abortController","_promise","wasAlreadyErroring","_resolve","_reject","_reason","_wasAlreadyErroring","WritableStreamStartErroring","closeRequest","writer","defaultWriterReadyPromiseResolve","closeSentinel","WritableStreamDefaultControllerAdvanceQueueIfNeeded","WritableStreamDealWithRejection","WritableStreamFinishErroring","WritableStreamDefaultWriterEnsureReadyPromiseRejected","WritableStreamHasOperationMarkedInFlight","storedError","writeRequest","WritableStreamRejectCloseAndClosedPromiseIfNeeded","abortRequest","defaultWriterClosedPromiseReject","WritableStreamUpdateBackpressure","backpressure","defaultWriterReadyPromiseInitialize","defaultWriterReadyPromiseReset","_ownerWritableStream","defaultWriterReadyPromiseInitializeAsResolved","defaultWriterClosedPromiseInitialize","defaultWriterReadyPromiseInitializeAsRejected","defaultWriterClosedPromiseResolve","defaultWriterClosedPromiseInitializeAsRejected","IsWritableStreamDefaultWriter","defaultWriterBrandCheckException","defaultWriterLockException","WritableStreamDefaultControllerGetDesiredSize","WritableStreamDefaultWriterGetDesiredSize","_readyPromise","WritableStreamDefaultWriterAbort","WritableStreamDefaultWriterClose","WritableStreamDefaultWriterRelease","WritableStreamDefaultWriterWrite","WritableStreamDefaultWriterEnsureClosedPromiseRejected","_closedPromiseState","defaultWriterClosedPromiseResetToRejected","_readyPromiseState","defaultWriterReadyPromiseReject","defaultWriterReadyPromiseResetToRejected","releasedError","chunkSize","_strategySizeAlgorithm","chunkSizeE","WritableStreamDefaultControllerErrorIfNeeded","WritableStreamDefaultControllerGetChunkSize","WritableStreamAddWriteRequest","enqueueE","_controlledWritableStream","WritableStreamDefaultControllerGetBackpressure","WritableStreamDefaultControllerWrite","abortReason","IsWritableStreamDefaultController","defaultControllerBrandCheckException","signal","WritableStreamDefaultControllerError","_abortAlgorithm","WritableStreamDefaultControllerClearAlgorithms","createAbortController","_writeAlgorithm","_closeAlgorithm","WritableStreamMarkCloseRequestInFlight","sinkClosePromise","WritableStreamFinishInFlightClose","WritableStreamFinishInFlightCloseWithError","WritableStreamDefaultControllerProcessClose","WritableStreamMarkFirstWriteRequestInFlight","sinkWritePromise","WritableStreamFinishInFlightWrite","WritableStreamFinishInFlightWriteWithError","WritableStreamDefaultControllerProcessWrite","_readyPromise_resolve","_readyPromise_reject","globals","globalThis","self","global","DOMException","isDOMExceptionConstructor","getFromGlobal","message","Error","captureStackTrace","writable","createPolyfill","ReadableStreamPipeTo","source","preventClose","preventAbort","shuttingDown","currentWrite","actions","shutdownWithAction","all","map","action","aborted","addEventListener","isOrBecomesErrored","shutdown","WritableStreamDefaultWriterCloseWithErrorPropagation","destClosed","waitForWritesToFinish","oldCurrentWrite","originalIsError","originalError","doTheRest","finalize","newError","isError","removeEventListener","resolveLoop","rejectLoop","resolveRead","rejectRead","ReadableStreamDefaultController","IsReadableStreamDefaultController","ReadableStreamDefaultControllerGetDesiredSize","ReadableStreamDefaultControllerCanCloseOrEnqueue","ReadableStreamDefaultControllerClose","ReadableStreamDefaultControllerEnqueue","ReadableStreamDefaultControllerError","ReadableStreamDefaultControllerClearAlgorithms","_controlledReadableStream","ReadableStreamDefaultControllerCallPullIfNeeded","ReadableStreamDefaultControllerShouldCallPull","SetUpReadableStreamDefaultController","ReadableStreamTee","cloneForBranch2","reason1","reason2","branch1","branch2","resolveCancelPromise","reading","readAgainForBranch1","readAgainForBranch2","canceled1","canceled2","cancelPromise","forwardReaderError","thisReader","pullWithDefaultReader","chunk1","chunk2","pull1Algorithm","pull2Algorithm","pullWithBYOBReader","forBranch2","byobBranch","otherBranch","byobCanceled","otherCanceled","cancel1Algorithm","compositeReason","cancelResult","cancel2Algorithm","CreateReadableByteStream","ReadableByteStreamTee","readAgain","CreateReadableStream","ReadableStreamDefaultTee","ReadableStreamFrom","getReader","readPromise","readResult","ReadableStreamFromDefaultReader","asyncIterable","iteratorRecord","nextResult","IteratorNext","iterResult","Boolean","IteratorComplete","IteratorValue","returnMethod","returnResult","ReadableStreamFromIterable","convertUnderlyingSourceCancelCallback","convertUnderlyingSourcePullCallback","convertUnderlyingSourceStartCallback","convertReadableStreamType","convertPipeOptions","isAbortSignal","assertAbortSignal","ReadableStream","rawUnderlyingSource","underlyingSource","pull","convertUnderlyingDefaultOrByteSource","InitializeReadableStream","underlyingByteSource","SetUpReadableByteStreamControllerFromUnderlyingSource","SetUpReadableStreamDefaultControllerFromUnderlyingSource","convertReaderOptions","pipeThrough","rawTransform","transform","readable","convertReadableWritablePair","pipeTo","destination","tee","values","impl","AcquireReadableStreamAsyncIterator","convertIteratorOptions","from","convertQueuingStrategyInit","byteLengthSizeFunction","ByteLengthQueuingStrategy","_byteLengthQueuingStrategyHighWaterMark","IsByteLengthQueuingStrategy","byteLengthBrandCheckException","countSizeFunction","CountQueuingStrategy","_countQueuingStrategyHighWaterMark","IsCountQueuingStrategy","countBrandCheckException","convertTransformerFlushCallback","convertTransformerStartCallback","convertTransformerTransformCallback","convertTransformerCancelCallback","TransformStream","rawTransformer","rawWritableStrategy","rawReadableStrategy","writableStrategy","readableStrategy","transformer","flush","readableType","writableType","convertTransformer","readableHighWaterMark","readableSizeAlgorithm","writableHighWaterMark","writableSizeAlgorithm","startPromise_resolve","startPromise","_transformStreamController","_backpressureChangePromise","_writable","TransformStreamDefaultControllerPerformTransform","TransformStreamDefaultSinkWriteAlgorithm","_finishPromise","_readable","_finishPromise_resolve","_finishPromise_reject","TransformStreamDefaultControllerClearAlgorithms","defaultControllerFinishPromiseReject","defaultControllerFinishPromiseResolve","TransformStreamDefaultSinkAbortAlgorithm","flushPromise","_flushAlgorithm","TransformStreamDefaultSinkCloseAlgorithm","TransformStreamSetBackpressure","TransformStreamDefaultSourcePullAlgorithm","TransformStreamUnblockWrite","TransformStreamDefaultSourceCancelAlgorithm","CreateWritableStream","_backpressureChangePromise_resolve","InitializeTransformStream","TransformStreamDefaultController","transformAlgorithm","flushAlgorithm","TransformStreamDefaultControllerEnqueue","transformResultE","_controlledTransformStream","_transformAlgorithm","SetUpTransformStreamDefaultController","SetUpTransformStreamDefaultControllerFromTransformer","IsTransformStream","TransformStreamError","TransformStreamErrorWritableAndUnblockWrite","IsTransformStreamDefaultController","terminate","TransformStreamDefaultControllerTerminate","readableController","ReadableStreamDefaultControllerHasBackpressure","exports"],"mappings":";;;;;;;mQAAgBA,IAEhB,CCCM,SAAUC,EAAaC,GAC3B,MAAqB,iBAANA,GAAwB,OAANA,GAA4B,mBAANA,CACzD,CAEO,MAAMC,EAUPH,EAEU,SAAAI,EAAgBC,EAAcC,GAC5C,IACEC,OAAOC,eAAeH,EAAI,OAAQ,CAChCI,MAAOH,EACPI,cAAc,GAEjB,CAAC,MAAAC,GAGD,CACH,CC1BA,MAAMC,EAAkBC,QAClBC,EAAsBD,QAAQE,UAAUC,KACxCC,EAAwBJ,QAAQK,OAAOC,KAAKP,GAG5C,SAAUQ,EAAcC,GAI5B,OAAO,IAAIT,EAAgBS,EAC7B,CAGM,SAAUC,EAAuBb,GACrC,OAAOW,GAAWG,GAAWA,EAAQd,IACvC,CAGM,SAAUe,EAA+BC,GAC7C,OAAOR,EAAsBQ,EAC/B,UAEgBC,EACdC,EACAC,EACAC,GAGA,OAAOf,EAAoBgB,KAAKH,EAASC,EAAaC,EACxD,UAKgBE,EACdJ,EACAC,EACAC,GACAH,EACEA,EAAmBC,EAASC,EAAaC,QACzCG,EACA7B,EAEJ,CAEgB,SAAA8B,EAAmBN,EAAqBC,GACtDG,EAAYJ,EAASC,EACvB,CAEgB,SAAAM,EAAcP,EAA2BE,GACvDE,EAAYJ,OAASK,EAAWH,EAClC,UAEgBM,EACdR,EACAS,EACAC,GACA,OAAOX,EAAmBC,EAASS,EAAoBC,EACzD,CAEM,SAAUC,EAA0BX,GACxCD,EAAmBC,OAASK,EAAW7B,EACzC,CAEA,IAAIoC,EAAkDC,IACpD,GAA8B,mBAAnBC,eACTF,EAAkBE,mBACb,CACL,MAAMC,EAAkBpB,OAAoBU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AOC,eAAe4rB,iCAAiCrrB,UAAWiE,OAAOsH,YAAa,CACpF7L,MAAO,mCACPC,cAAc,IClVlB,MAAM2sB,GAAU,CACd/F,8BACAtE,gEACA5R,0DACAZ,oDACAlI,wDACAiP,kDAEA2B,8BACAW,gEACAc,wDAEAoO,oDACAK,0CAEAQ,gCACAwC,mEAIF,QAAuB,IAAZ9L,GACT,IAAK,MAAMhT,KAAQ+f,GACb9sB,OAAOQ,UAAUgJ,eAAejI,KAAKurB,GAAS/f,IAChD/M,OAAOC,eAAe8f,GAAShT,EAAM,CACnC7M,MAAO4sB,GAAQ/f,GACf0T,UAAU,EACVtgB,cAAc","x_google_ignoreList":[11]} \ No newline at end of file diff --git a/backend/node_modules/web-streams-polyfill/dist/polyfill.es6.mjs b/backend/node_modules/web-streams-polyfill/dist/polyfill.es6.mjs new file mode 100644 index 0000000000000000000000000000000000000000..9c3f00f88bb2c187673f42f841f9fe9fc4777ec6 --- /dev/null +++ b/backend/node_modules/web-streams-polyfill/dist/polyfill.es6.mjs @@ -0,0 +1,4818 @@ +/** + * @license + * web-streams-polyfill v3.3.3 + * Copyright 2024 Mattias Buelens, Diwank Singh Tomer and other contributors. + * This code is released under the MIT license. + * SPDX-License-Identifier: MIT + */ +function noop() { + return undefined; +} + +function typeIsObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; +} +const rethrowAssertionErrorRejection = noop; +function setFunctionName(fn, name) { + try { + Object.defineProperty(fn, 'name', { + value: name, + configurable: true + }); + } + catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility + } +} + +const originalPromise = Promise; +const originalPromiseThen = Promise.prototype.then; +const originalPromiseReject = Promise.reject.bind(originalPromise); +// https://webidl.spec.whatwg.org/#a-new-promise +function newPromise(executor) { + return new originalPromise(executor); +} +// https://webidl.spec.whatwg.org/#a-promise-resolved-with +function promiseResolvedWith(value) { + return newPromise(resolve => resolve(value)); +} +// https://webidl.spec.whatwg.org/#a-promise-rejected-with +function promiseRejectedWith(reason) { + return originalPromiseReject(reason); +} +function PerformPromiseThen(promise, onFulfilled, onRejected) { + // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an + // approximation. + return originalPromiseThen.call(promise, onFulfilled, onRejected); +} +// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned +// from that handler. To prevent this, return null instead of void from all handlers. +// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it +function uponPromise(promise, onFulfilled, onRejected) { + PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection); +} +function uponFulfillment(promise, onFulfilled) { + uponPromise(promise, onFulfilled); +} +function uponRejection(promise, onRejected) { + uponPromise(promise, undefined, onRejected); +} +function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { + return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); +} +function setPromiseIsHandledToTrue(promise) { + PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection); +} +let _queueMicrotask = callback => { + if (typeof queueMicrotask === 'function') { + _queueMicrotask = queueMicrotask; + } + else { + const resolvedPromise = promiseResolvedWith(undefined); + _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb); + } + return _queueMicrotask(callback); +}; +function reflectCall(F, V, args) { + if (typeof F !== 'function') { + throw new TypeError('Argument is not a function'); + } + return Function.prototype.apply.call(F, V, args); +} +function promiseCall(F, V, args) { + try { + return promiseResolvedWith(reflectCall(F, V, args)); + } + catch (value) { + return promiseRejectedWith(value); + } +} + +// Original from Chromium +// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js +const QUEUE_MAX_ARRAY_SIZE = 16384; +/** + * Simple queue structure. + * + * Avoids scalability issues with using a packed array directly by using + * multiple arrays in a linked list and keeping the array size bounded. + */ +class SimpleQueue { + constructor() { + this._cursor = 0; + this._size = 0; + // _front and _back are always defined. + this._front = { + _elements: [], + _next: undefined + }; + this._back = this._front; + // The cursor is used to avoid calling Array.shift(). + // It contains the index of the front element of the array inside the + // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE). + this._cursor = 0; + // When there is only one node, size === elements.length - cursor. + this._size = 0; + } + get length() { + return this._size; + } + // For exception safety, this method is structured in order: + // 1. Read state + // 2. Calculate required state mutations + // 3. Perform state mutations + push(element) { + const oldBack = this._back; + let newBack = oldBack; + if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { + newBack = { + _elements: [], + _next: undefined + }; + } + // push() is the mutation most likely to throw an exception, so it + // goes first. + oldBack._elements.push(element); + if (newBack !== oldBack) { + this._back = newBack; + oldBack._next = newBack; + } + ++this._size; + } + // Like push(), shift() follows the read -> calculate -> mutate pattern for + // exception safety. + shift() { // must not be called on an empty queue + const oldFront = this._front; + let newFront = oldFront; + const oldCursor = this._cursor; + let newCursor = oldCursor + 1; + const elements = oldFront._elements; + const element = elements[oldCursor]; + if (newCursor === QUEUE_MAX_ARRAY_SIZE) { + newFront = oldFront._next; + newCursor = 0; + } + // No mutations before this point. + --this._size; + this._cursor = newCursor; + if (oldFront !== newFront) { + this._front = newFront; + } + // Permit shifted element to be garbage collected. + elements[oldCursor] = undefined; + return element; + } + // The tricky thing about forEach() is that it can be called + // re-entrantly. The queue may be mutated inside the callback. It is easy to + // see that push() within the callback has no negative effects since the end + // of the queue is checked for on every iteration. If shift() is called + // repeatedly within the callback then the next iteration may return an + // element that has been removed. In this case the callback will be called + // with undefined values until we either "catch up" with elements that still + // exist or reach the back of the queue. + forEach(callback) { + let i = this._cursor; + let node = this._front; + let elements = node._elements; + while (i !== elements.length || node._next !== undefined) { + if (i === elements.length) { + node = node._next; + elements = node._elements; + i = 0; + if (elements.length === 0) { + break; + } + } + callback(elements[i]); + ++i; + } + } + // Return the element that would be returned if shift() was called now, + // without modifying the queue. + peek() { // must not be called on an empty queue + const front = this._front; + const cursor = this._cursor; + return front._elements[cursor]; + } +} + +const AbortSteps = Symbol('[[AbortSteps]]'); +const ErrorSteps = Symbol('[[ErrorSteps]]'); +const CancelSteps = Symbol('[[CancelSteps]]'); +const PullSteps = Symbol('[[PullSteps]]'); +const ReleaseSteps = Symbol('[[ReleaseSteps]]'); + +function ReadableStreamReaderGenericInitialize(reader, stream) { + reader._ownerReadableStream = stream; + stream._reader = reader; + if (stream._state === 'readable') { + defaultReaderClosedPromiseInitialize(reader); + } + else if (stream._state === 'closed') { + defaultReaderClosedPromiseInitializeAsResolved(reader); + } + else { + defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); + } +} +// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state +// check. +function ReadableStreamReaderGenericCancel(reader, reason) { + const stream = reader._ownerReadableStream; + return ReadableStreamCancel(stream, reason); +} +function ReadableStreamReaderGenericRelease(reader) { + const stream = reader._ownerReadableStream; + if (stream._state === 'readable') { + defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + else { + defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + stream._readableStreamController[ReleaseSteps](); + stream._reader = undefined; + reader._ownerReadableStream = undefined; +} +// Helper functions for the readers. +function readerLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released reader'); +} +// Helper functions for the ReadableStreamDefaultReader. +function defaultReaderClosedPromiseInitialize(reader) { + reader._closedPromise = newPromise((resolve, reject) => { + reader._closedPromise_resolve = resolve; + reader._closedPromise_reject = reject; + }); +} +function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseReject(reader, reason); +} +function defaultReaderClosedPromiseInitializeAsResolved(reader) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseResolve(reader); +} +function defaultReaderClosedPromiseReject(reader, reason) { + if (reader._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(reader._closedPromise); + reader._closedPromise_reject(reason); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; +} +function defaultReaderClosedPromiseResetToRejected(reader, reason) { + defaultReaderClosedPromiseInitializeAsRejected(reader, reason); +} +function defaultReaderClosedPromiseResolve(reader) { + if (reader._closedPromise_resolve === undefined) { + return; + } + reader._closedPromise_resolve(undefined); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; +} + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill +const NumberIsFinite = Number.isFinite || function (x) { + return typeof x === 'number' && isFinite(x); +}; + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill +const MathTrunc = Math.trunc || function (v) { + return v < 0 ? Math.ceil(v) : Math.floor(v); +}; + +// https://heycam.github.io/webidl/#idl-dictionaries +function isDictionary(x) { + return typeof x === 'object' || typeof x === 'function'; +} +function assertDictionary(obj, context) { + if (obj !== undefined && !isDictionary(obj)) { + throw new TypeError(`${context} is not an object.`); + } +} +// https://heycam.github.io/webidl/#idl-callback-functions +function assertFunction(x, context) { + if (typeof x !== 'function') { + throw new TypeError(`${context} is not a function.`); + } +} +// https://heycam.github.io/webidl/#idl-object +function isObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; +} +function assertObject(x, context) { + if (!isObject(x)) { + throw new TypeError(`${context} is not an object.`); + } +} +function assertRequiredArgument(x, position, context) { + if (x === undefined) { + throw new TypeError(`Parameter ${position} is required in '${context}'.`); + } +} +function assertRequiredField(x, field, context) { + if (x === undefined) { + throw new TypeError(`${field} is required in '${context}'.`); + } +} +// https://heycam.github.io/webidl/#idl-unrestricted-double +function convertUnrestrictedDouble(value) { + return Number(value); +} +function censorNegativeZero(x) { + return x === 0 ? 0 : x; +} +function integerPart(x) { + return censorNegativeZero(MathTrunc(x)); +} +// https://heycam.github.io/webidl/#idl-unsigned-long-long +function convertUnsignedLongLongWithEnforceRange(value, context) { + const lowerBound = 0; + const upperBound = Number.MAX_SAFE_INTEGER; + let x = Number(value); + x = censorNegativeZero(x); + if (!NumberIsFinite(x)) { + throw new TypeError(`${context} is not a finite number`); + } + x = integerPart(x); + if (x < lowerBound || x > upperBound) { + throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`); + } + if (!NumberIsFinite(x) || x === 0) { + return 0; + } + // TODO Use BigInt if supported? + // let xBigInt = BigInt(integerPart(x)); + // xBigInt = BigInt.asUintN(64, xBigInt); + // return Number(xBigInt); + return x; +} + +function assertReadableStream(x, context) { + if (!IsReadableStream(x)) { + throw new TypeError(`${context} is not a ReadableStream.`); + } +} + +// Abstract operations for the ReadableStream. +function AcquireReadableStreamDefaultReader(stream) { + return new ReadableStreamDefaultReader(stream); +} +// ReadableStream API exposed for controllers. +function ReadableStreamAddReadRequest(stream, readRequest) { + stream._reader._readRequests.push(readRequest); +} +function ReadableStreamFulfillReadRequest(stream, chunk, done) { + const reader = stream._reader; + const readRequest = reader._readRequests.shift(); + if (done) { + readRequest._closeSteps(); + } + else { + readRequest._chunkSteps(chunk); + } +} +function ReadableStreamGetNumReadRequests(stream) { + return stream._reader._readRequests.length; +} +function ReadableStreamHasDefaultReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamDefaultReader(reader)) { + return false; + } + return true; +} +/** + * A default reader vended by a {@link ReadableStream}. + * + * @public + */ +class ReadableStreamDefaultReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + /** + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('read')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: () => resolvePromise({ value: undefined, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamDefaultReaderRead(this, readRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamDefaultReader(this)) { + throw defaultReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamDefaultReaderRelease(this); + } +} +Object.defineProperties(ReadableStreamDefaultReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } +}); +setFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel'); +setFunctionName(ReadableStreamDefaultReader.prototype.read, 'read'); +setFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, { + value: 'ReadableStreamDefaultReader', + configurable: true + }); +} +// Abstract operations for the readers. +function IsReadableStreamDefaultReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) { + return false; + } + return x instanceof ReadableStreamDefaultReader; +} +function ReadableStreamDefaultReaderRead(reader, readRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'closed') { + readRequest._closeSteps(); + } + else if (stream._state === 'errored') { + readRequest._errorSteps(stream._storedError); + } + else { + stream._readableStreamController[PullSteps](readRequest); + } +} +function ReadableStreamDefaultReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + const e = new TypeError('Reader was released'); + ReadableStreamDefaultReaderErrorReadRequests(reader, e); +} +function ReadableStreamDefaultReaderErrorReadRequests(reader, e) { + const readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(readRequest => { + readRequest._errorSteps(e); + }); +} +// Helper functions for the ReadableStreamDefaultReader. +function defaultReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`); +} + +/****************************************************************************** +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 */ + + +function __values(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); +} + +function __await(v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); +} + +function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } +} + +function __asyncDelegator(o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } +} + +function __asyncValues(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } +} + +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 _a, _b, _c; +function CreateArrayFromList(elements) { + // We use arrays to represent lists, so this is basically a no-op. + // Do a slice though just in case we happen to depend on the unique-ness. + return elements.slice(); +} +function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { + new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); +} +let TransferArrayBuffer = (O) => { + if (typeof O.transfer === 'function') { + TransferArrayBuffer = buffer => buffer.transfer(); + } + else if (typeof structuredClone === 'function') { + TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] }); + } + else { + // Not implemented correctly + TransferArrayBuffer = buffer => buffer; + } + return TransferArrayBuffer(O); +}; +let IsDetachedBuffer = (O) => { + if (typeof O.detached === 'boolean') { + IsDetachedBuffer = buffer => buffer.detached; + } + else { + // Not implemented correctly + IsDetachedBuffer = buffer => buffer.byteLength === 0; + } + return IsDetachedBuffer(O); +}; +function ArrayBufferSlice(buffer, begin, end) { + // ArrayBuffer.prototype.slice is not available on IE10 + // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice + if (buffer.slice) { + return buffer.slice(begin, end); + } + const length = end - begin; + const slice = new ArrayBuffer(length); + CopyDataBlockBytes(slice, 0, buffer, begin, length); + return slice; +} +function GetMethod(receiver, prop) { + const func = receiver[prop]; + if (func === undefined || func === null) { + return undefined; + } + if (typeof func !== 'function') { + throw new TypeError(`${String(prop)} is not a function`); + } + return func; +} +function CreateAsyncFromSyncIterator(syncIteratorRecord) { + // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%, + // we use yield* inside an async generator function to achieve the same result. + // Wrap the sync iterator inside a sync iterable, so we can use it with yield*. + const syncIterable = { + [Symbol.iterator]: () => syncIteratorRecord.iterator + }; + // Create an async generator function and immediately invoke it. + const asyncIterator = (function () { + return __asyncGenerator(this, arguments, function* () { + return yield __await(yield __await(yield* __asyncDelegator(__asyncValues(syncIterable)))); + }); + }()); + // Return as an async iterator record. + const nextMethod = asyncIterator.next; + return { iterator: asyncIterator, nextMethod, done: false }; +} +// Aligns with core-js/modules/es.symbol.async-iterator.js +const SymbolAsyncIterator = (_c = (_a = Symbol.asyncIterator) !== null && _a !== void 0 ? _a : (_b = Symbol.for) === null || _b === void 0 ? void 0 : _b.call(Symbol, 'Symbol.asyncIterator')) !== null && _c !== void 0 ? _c : '@@asyncIterator'; +function GetIterator(obj, hint = 'sync', method) { + if (method === undefined) { + if (hint === 'async') { + method = GetMethod(obj, SymbolAsyncIterator); + if (method === undefined) { + const syncMethod = GetMethod(obj, Symbol.iterator); + const syncIteratorRecord = GetIterator(obj, 'sync', syncMethod); + return CreateAsyncFromSyncIterator(syncIteratorRecord); + } + } + else { + method = GetMethod(obj, Symbol.iterator); + } + } + if (method === undefined) { + throw new TypeError('The object is not iterable'); + } + const iterator = reflectCall(method, obj, []); + if (!typeIsObject(iterator)) { + throw new TypeError('The iterator method must return an object'); + } + const nextMethod = iterator.next; + return { iterator, nextMethod, done: false }; +} +function IteratorNext(iteratorRecord) { + const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []); + if (!typeIsObject(result)) { + throw new TypeError('The iterator.next() method must return an object'); + } + return result; +} +function IteratorComplete(iterResult) { + return Boolean(iterResult.done); +} +function IteratorValue(iterResult) { + return iterResult.value; +} + +/// +// We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it. +const AsyncIteratorPrototype = { + // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( ) + // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator + [SymbolAsyncIterator]() { + return this; + } +}; +Object.defineProperty(AsyncIteratorPrototype, SymbolAsyncIterator, { enumerable: false }); + +/// +class ReadableStreamAsyncIteratorImpl { + constructor(reader, preventCancel) { + this._ongoingPromise = undefined; + this._isFinished = false; + this._reader = reader; + this._preventCancel = preventCancel; + } + next() { + const nextSteps = () => this._nextSteps(); + this._ongoingPromise = this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : + nextSteps(); + return this._ongoingPromise; + } + return(value) { + const returnSteps = () => this._returnSteps(value); + return this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : + returnSteps(); + } + _nextSteps() { + if (this._isFinished) { + return Promise.resolve({ value: undefined, done: true }); + } + const reader = this._reader; + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => { + this._ongoingPromise = undefined; + // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test. + // FIXME Is this a bug in the specification, or in the test? + _queueMicrotask(() => resolvePromise({ value: chunk, done: false })); + }, + _closeSteps: () => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + resolvePromise({ value: undefined, done: true }); + }, + _errorSteps: reason => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + rejectPromise(reason); + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promise; + } + _returnSteps(value) { + if (this._isFinished) { + return Promise.resolve({ value, done: true }); + } + this._isFinished = true; + const reader = this._reader; + if (!this._preventCancel) { + const result = ReadableStreamReaderGenericCancel(reader, value); + ReadableStreamReaderGenericRelease(reader); + return transformPromiseWith(result, () => ({ value, done: true })); + } + ReadableStreamReaderGenericRelease(reader); + return promiseResolvedWith({ value, done: true }); + } +} +const ReadableStreamAsyncIteratorPrototype = { + next() { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next')); + } + return this._asyncIteratorImpl.next(); + }, + return(value) { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return')); + } + return this._asyncIteratorImpl.return(value); + } +}; +Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); +// Abstract operations for the ReadableStream. +function AcquireReadableStreamAsyncIterator(stream, preventCancel) { + const reader = AcquireReadableStreamDefaultReader(stream); + const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); + const iterator = Object.create(ReadableStreamAsyncIteratorPrototype); + iterator._asyncIteratorImpl = impl; + return iterator; +} +function IsReadableStreamAsyncIterator(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) { + return false; + } + try { + // noinspection SuspiciousTypeOfGuard + return x._asyncIteratorImpl instanceof + ReadableStreamAsyncIteratorImpl; + } + catch (_a) { + return false; + } +} +// Helper functions for the ReadableStream. +function streamAsyncIteratorBrandCheckException(name) { + return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`); +} + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill +const NumberIsNaN = Number.isNaN || function (x) { + // eslint-disable-next-line no-self-compare + return x !== x; +}; + +function IsNonNegativeNumber(v) { + if (typeof v !== 'number') { + return false; + } + if (NumberIsNaN(v)) { + return false; + } + if (v < 0) { + return false; + } + return true; +} +function CloneAsUint8Array(O) { + const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength); + return new Uint8Array(buffer); +} + +function DequeueValue(container) { + const pair = container._queue.shift(); + container._queueTotalSize -= pair.size; + if (container._queueTotalSize < 0) { + container._queueTotalSize = 0; + } + return pair.value; +} +function EnqueueValueWithSize(container, value, size) { + if (!IsNonNegativeNumber(size) || size === Infinity) { + throw new RangeError('Size must be a finite, non-NaN, non-negative number.'); + } + container._queue.push({ value, size }); + container._queueTotalSize += size; +} +function PeekQueueValue(container) { + const pair = container._queue.peek(); + return pair.value; +} +function ResetQueue(container) { + container._queue = new SimpleQueue(); + container._queueTotalSize = 0; +} + +function isDataViewConstructor(ctor) { + return ctor === DataView; +} +function isDataView(view) { + return isDataViewConstructor(view.constructor); +} +function arrayBufferViewElementSize(ctor) { + if (isDataViewConstructor(ctor)) { + return 1; + } + return ctor.BYTES_PER_ELEMENT; +} + +/** + * A pull-into request in a {@link ReadableByteStreamController}. + * + * @public + */ +class ReadableStreamBYOBRequest { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. + */ + get view() { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('view'); + } + return this._view; + } + respond(bytesWritten) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respond'); + } + assertRequiredArgument(bytesWritten, 1, 'respond'); + bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter'); + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(this._view.buffer)) { + throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`); + } + ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); + } + respondWithNewView(view) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respondWithNewView'); + } + assertRequiredArgument(view, 1, 'respondWithNewView'); + if (!ArrayBuffer.isView(view)) { + throw new TypeError('You can only respond with array buffer views'); + } + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(view.buffer)) { + throw new TypeError('The given view\'s buffer has been detached and so cannot be used as a response'); + } + ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); + } +} +Object.defineProperties(ReadableStreamBYOBRequest.prototype, { + respond: { enumerable: true }, + respondWithNewView: { enumerable: true }, + view: { enumerable: true } +}); +setFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond'); +setFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, { + value: 'ReadableStreamBYOBRequest', + configurable: true + }); +} +/** + * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. + * + * @public + */ +class ReadableByteStreamController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the current BYOB pull request, or `null` if there isn't one. + */ + get byobRequest() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('byobRequest'); + } + return ReadableByteStreamControllerGetBYOBRequest(this); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('desiredSize'); + } + return ReadableByteStreamControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('close'); + } + if (this._closeRequested) { + throw new TypeError('The stream has already been closed; do not close it again!'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`); + } + ReadableByteStreamControllerClose(this); + } + enqueue(chunk) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('enqueue'); + } + assertRequiredArgument(chunk, 1, 'enqueue'); + if (!ArrayBuffer.isView(chunk)) { + throw new TypeError('chunk must be an array buffer view'); + } + if (chunk.byteLength === 0) { + throw new TypeError('chunk must have non-zero byteLength'); + } + if (chunk.buffer.byteLength === 0) { + throw new TypeError(`chunk's buffer must have non-zero byteLength`); + } + if (this._closeRequested) { + throw new TypeError('stream is closed or draining'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`); + } + ReadableByteStreamControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('error'); + } + ReadableByteStreamControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ReadableByteStreamControllerClearPendingPullIntos(this); + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableByteStreamControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableByteStream; + if (this._queueTotalSize > 0) { + ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest); + return; + } + const autoAllocateChunkSize = this._autoAllocateChunkSize; + if (autoAllocateChunkSize !== undefined) { + let buffer; + try { + buffer = new ArrayBuffer(autoAllocateChunkSize); + } + catch (bufferE) { + readRequest._errorSteps(bufferE); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: autoAllocateChunkSize, + byteOffset: 0, + byteLength: autoAllocateChunkSize, + bytesFilled: 0, + minimumFill: 1, + elementSize: 1, + viewConstructor: Uint8Array, + readerType: 'default' + }; + this._pendingPullIntos.push(pullIntoDescriptor); + } + ReadableStreamAddReadRequest(stream, readRequest); + ReadableByteStreamControllerCallPullIfNeeded(this); + } + /** @internal */ + [ReleaseSteps]() { + if (this._pendingPullIntos.length > 0) { + const firstPullInto = this._pendingPullIntos.peek(); + firstPullInto.readerType = 'none'; + this._pendingPullIntos = new SimpleQueue(); + this._pendingPullIntos.push(firstPullInto); + } + } +} +Object.defineProperties(ReadableByteStreamController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + byobRequest: { enumerable: true }, + desiredSize: { enumerable: true } +}); +setFunctionName(ReadableByteStreamController.prototype.close, 'close'); +setFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue'); +setFunctionName(ReadableByteStreamController.prototype.error, 'error'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, { + value: 'ReadableByteStreamController', + configurable: true + }); +} +// Abstract operations for the ReadableByteStreamController. +function IsReadableByteStreamController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) { + return false; + } + return x instanceof ReadableByteStreamController; +} +function IsReadableStreamBYOBRequest(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) { + return false; + } + return x instanceof ReadableStreamBYOBRequest; +} +function ReadableByteStreamControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableByteStreamControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + // TODO: Test controller argument + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + return null; + }, e => { + ReadableByteStreamControllerError(controller, e); + return null; + }); +} +function ReadableByteStreamControllerClearPendingPullIntos(controller) { + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + controller._pendingPullIntos = new SimpleQueue(); +} +function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { + let done = false; + if (stream._state === 'closed') { + done = true; + } + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'default') { + ReadableStreamFulfillReadRequest(stream, filledView, done); + } + else { + ReadableStreamFulfillReadIntoRequest(stream, filledView, done); + } +} +function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { + const bytesFilled = pullIntoDescriptor.bytesFilled; + const elementSize = pullIntoDescriptor.elementSize; + return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); +} +function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { + controller._queue.push({ buffer, byteOffset, byteLength }); + controller._queueTotalSize += byteLength; +} +function ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, buffer, byteOffset, byteLength) { + let clonedChunk; + try { + clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength); + } + catch (cloneE) { + ReadableByteStreamControllerError(controller, cloneE); + throw cloneE; + } + ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength); +} +function ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstDescriptor) { + if (firstDescriptor.bytesFilled > 0) { + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, firstDescriptor.buffer, firstDescriptor.byteOffset, firstDescriptor.bytesFilled); + } + ReadableByteStreamControllerShiftPendingPullInto(controller); +} +function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { + const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); + const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; + let totalBytesToCopyRemaining = maxBytesToCopy; + let ready = false; + const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize; + const maxAlignedBytes = maxBytesFilled - remainderBytes; + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) { + totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; + ready = true; + } + const queue = controller._queue; + while (totalBytesToCopyRemaining > 0) { + const headOfQueue = queue.peek(); + const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); + const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); + if (headOfQueue.byteLength === bytesToCopy) { + queue.shift(); + } + else { + headOfQueue.byteOffset += bytesToCopy; + headOfQueue.byteLength -= bytesToCopy; + } + controller._queueTotalSize -= bytesToCopy; + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); + totalBytesToCopyRemaining -= bytesToCopy; + } + return ready; +} +function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { + pullIntoDescriptor.bytesFilled += size; +} +function ReadableByteStreamControllerHandleQueueDrain(controller) { + if (controller._queueTotalSize === 0 && controller._closeRequested) { + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(controller._controlledReadableByteStream); + } + else { + ReadableByteStreamControllerCallPullIfNeeded(controller); + } +} +function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { + if (controller._byobRequest === null) { + return; + } + controller._byobRequest._associatedReadableByteStreamController = undefined; + controller._byobRequest._view = null; + controller._byobRequest = null; +} +function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { + while (controller._pendingPullIntos.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const pullIntoDescriptor = controller._pendingPullIntos.peek(); + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + } + } +} +function ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller) { + const reader = controller._controlledReadableByteStream._reader; + while (reader._readRequests.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const readRequest = reader._readRequests.shift(); + ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest); + } +} +function ReadableByteStreamControllerPullInto(controller, view, min, readIntoRequest) { + const stream = controller._controlledReadableByteStream; + const ctor = view.constructor; + const elementSize = arrayBufferViewElementSize(ctor); + const { byteOffset, byteLength } = view; + const minimumFill = min * elementSize; + let buffer; + try { + buffer = TransferArrayBuffer(view.buffer); + } + catch (e) { + readIntoRequest._errorSteps(e); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: buffer.byteLength, + byteOffset, + byteLength, + bytesFilled: 0, + minimumFill, + elementSize, + viewConstructor: ctor, + readerType: 'byob' + }; + if (controller._pendingPullIntos.length > 0) { + controller._pendingPullIntos.push(pullIntoDescriptor); + // No ReadableByteStreamControllerCallPullIfNeeded() call since: + // - No change happens on desiredSize + // - The source has already been notified of that there's at least 1 pending read(view) + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + return; + } + if (stream._state === 'closed') { + const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); + readIntoRequest._closeSteps(emptyView); + return; + } + if (controller._queueTotalSize > 0) { + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + ReadableByteStreamControllerHandleQueueDrain(controller); + readIntoRequest._chunkSteps(filledView); + return; + } + if (controller._closeRequested) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + readIntoRequest._errorSteps(e); + return; + } + } + controller._pendingPullIntos.push(pullIntoDescriptor); + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { + if (firstDescriptor.readerType === 'none') { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const stream = controller._controlledReadableByteStream; + if (ReadableStreamHasBYOBReader(stream)) { + while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { + const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); + } + } +} +function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + return; + } + if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) { + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + return; + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; + if (remainderSize > 0) { + const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor.buffer, end - remainderSize, remainderSize); + } + pullIntoDescriptor.bytesFilled -= remainderSize; + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); +} +function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor); + } + else { + ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerShiftPendingPullInto(controller) { + const descriptor = controller._pendingPullIntos.shift(); + return descriptor; +} +function ReadableByteStreamControllerShouldCallPull(controller) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return false; + } + if (controller._closeRequested) { + return false; + } + if (!controller._started) { + return false; + } + if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; +} +function ReadableByteStreamControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; +} +// A client of ReadableByteStreamController may use these functions directly to bypass state check. +function ReadableByteStreamControllerClose(controller) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + if (controller._queueTotalSize > 0) { + controller._closeRequested = true; + return; + } + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + throw e; + } + } + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(stream); +} +function ReadableByteStreamControllerEnqueue(controller, chunk) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + const { buffer, byteOffset, byteLength } = chunk; + if (IsDetachedBuffer(buffer)) { + throw new TypeError('chunk\'s buffer is detached and so cannot be enqueued'); + } + const transferredBuffer = TransferArrayBuffer(buffer); + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (IsDetachedBuffer(firstPendingPullInto.buffer)) { + throw new TypeError('The BYOB request\'s buffer has been detached and so cannot be filled with an enqueued chunk'); + } + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer); + if (firstPendingPullInto.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto); + } + } + if (ReadableStreamHasDefaultReader(stream)) { + ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller); + if (ReadableStreamGetNumReadRequests(stream) === 0) { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + else { + if (controller._pendingPullIntos.length > 0) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); + ReadableStreamFulfillReadRequest(stream, transferredView, false); + } + } + else if (ReadableStreamHasBYOBReader(stream)) { + // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully. + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + else { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerError(controller, e) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return; + } + ReadableByteStreamControllerClearPendingPullIntos(controller); + ResetQueue(controller); + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); +} +function ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest) { + const entry = controller._queue.shift(); + controller._queueTotalSize -= entry.byteLength; + ReadableByteStreamControllerHandleQueueDrain(controller); + const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); + readRequest._chunkSteps(view); +} +function ReadableByteStreamControllerGetBYOBRequest(controller) { + if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); + const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); + SetUpReadableStreamBYOBRequest(byobRequest, controller, view); + controller._byobRequest = byobRequest; + } + return controller._byobRequest; +} +function ReadableByteStreamControllerGetDesiredSize(controller) { + const state = controller._controlledReadableByteStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; +} +function ReadableByteStreamControllerRespond(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (bytesWritten !== 0) { + throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream'); + } + } + else { + if (bytesWritten === 0) { + throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream'); + } + if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) { + throw new RangeError('bytesWritten out of range'); + } + } + firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); + ReadableByteStreamControllerRespondInternal(controller, bytesWritten); +} +function ReadableByteStreamControllerRespondWithNewView(controller, view) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (view.byteLength !== 0) { + throw new TypeError('The view\'s length must be 0 when calling respondWithNewView() on a closed stream'); + } + } + else { + if (view.byteLength === 0) { + throw new TypeError('The view\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'); + } + } + if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { + throw new RangeError('The region specified by view does not match byobRequest'); + } + if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) { + throw new RangeError('The buffer of view has different capacity than byobRequest'); + } + if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) { + throw new RangeError('The region specified by view is larger than byobRequest'); + } + const viewByteLength = view.byteLength; + firstDescriptor.buffer = TransferArrayBuffer(view.buffer); + ReadableByteStreamControllerRespondInternal(controller, viewByteLength); +} +function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { + controller._controlledReadableByteStream = stream; + controller._pullAgain = false; + controller._pulling = false; + controller._byobRequest = null; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._closeRequested = false; + controller._started = false; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._autoAllocateChunkSize = autoAllocateChunkSize; + controller._pendingPullIntos = new SimpleQueue(); + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableByteStreamControllerCallPullIfNeeded(controller); + return null; + }, r => { + ReadableByteStreamControllerError(controller, r); + return null; + }); +} +function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { + const controller = Object.create(ReadableByteStreamController.prototype); + let startAlgorithm; + let pullAlgorithm; + let cancelAlgorithm; + if (underlyingByteSource.start !== undefined) { + startAlgorithm = () => underlyingByteSource.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingByteSource.pull !== undefined) { + pullAlgorithm = () => underlyingByteSource.pull(controller); + } + else { + pullAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingByteSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingByteSource.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; + if (autoAllocateChunkSize === 0) { + throw new TypeError('autoAllocateChunkSize must be greater than 0'); + } + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); +} +function SetUpReadableStreamBYOBRequest(request, controller, view) { + request._associatedReadableByteStreamController = controller; + request._view = view; +} +// Helper functions for the ReadableStreamBYOBRequest. +function byobRequestBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`); +} +// Helper functions for the ReadableByteStreamController. +function byteStreamControllerBrandCheckException(name) { + return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`); +} + +function convertReaderOptions(options, context) { + assertDictionary(options, context); + const mode = options === null || options === void 0 ? void 0 : options.mode; + return { + mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`) + }; +} +function convertReadableStreamReaderMode(mode, context) { + mode = `${mode}`; + if (mode !== 'byob') { + throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`); + } + return mode; +} +function convertByobReadOptions(options, context) { + var _a; + assertDictionary(options, context); + const min = (_a = options === null || options === void 0 ? void 0 : options.min) !== null && _a !== void 0 ? _a : 1; + return { + min: convertUnsignedLongLongWithEnforceRange(min, `${context} has member 'min' that`) + }; +} + +// Abstract operations for the ReadableStream. +function AcquireReadableStreamBYOBReader(stream) { + return new ReadableStreamBYOBReader(stream); +} +// ReadableStream API exposed for controllers. +function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { + stream._reader._readIntoRequests.push(readIntoRequest); +} +function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { + const reader = stream._reader; + const readIntoRequest = reader._readIntoRequests.shift(); + if (done) { + readIntoRequest._closeSteps(chunk); + } + else { + readIntoRequest._chunkSteps(chunk); + } +} +function ReadableStreamGetNumReadIntoRequests(stream) { + return stream._reader._readIntoRequests.length; +} +function ReadableStreamHasBYOBReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamBYOBReader(reader)) { + return false; + } + return true; +} +/** + * A BYOB reader vended by a {@link ReadableStream}. + * + * @public + */ +class ReadableStreamBYOBReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + if (!IsReadableByteStreamController(stream._readableStreamController)) { + throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' + + 'source'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readIntoRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + read(view, rawOptions = {}) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('read')); + } + if (!ArrayBuffer.isView(view)) { + return promiseRejectedWith(new TypeError('view must be an array buffer view')); + } + if (view.byteLength === 0) { + return promiseRejectedWith(new TypeError('view must have non-zero byteLength')); + } + if (view.buffer.byteLength === 0) { + return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`)); + } + if (IsDetachedBuffer(view.buffer)) { + return promiseRejectedWith(new TypeError('view\'s buffer has been detached')); + } + let options; + try { + options = convertByobReadOptions(rawOptions, 'options'); + } + catch (e) { + return promiseRejectedWith(e); + } + const min = options.min; + if (min === 0) { + return promiseRejectedWith(new TypeError('options.min must be greater than 0')); + } + if (!isDataView(view)) { + if (min > view.length) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s length')); + } + } + else if (min > view.byteLength) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s byteLength')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readIntoRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: chunk => resolvePromise({ value: chunk, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamBYOBReader(this)) { + throw byobReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamBYOBReaderRelease(this); + } +} +Object.defineProperties(ReadableStreamBYOBReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } +}); +setFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel'); +setFunctionName(ReadableStreamBYOBReader.prototype.read, 'read'); +setFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, { + value: 'ReadableStreamBYOBReader', + configurable: true + }); +} +// Abstract operations for the readers. +function IsReadableStreamBYOBReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) { + return false; + } + return x instanceof ReadableStreamBYOBReader; +} +function ReadableStreamBYOBReaderRead(reader, view, min, readIntoRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'errored') { + readIntoRequest._errorSteps(stream._storedError); + } + else { + ReadableByteStreamControllerPullInto(stream._readableStreamController, view, min, readIntoRequest); + } +} +function ReadableStreamBYOBReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + const e = new TypeError('Reader was released'); + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); +} +function ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e) { + const readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._errorSteps(e); + }); +} +// Helper functions for the ReadableStreamBYOBReader. +function byobReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`); +} + +function ExtractHighWaterMark(strategy, defaultHWM) { + const { highWaterMark } = strategy; + if (highWaterMark === undefined) { + return defaultHWM; + } + if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { + throw new RangeError('Invalid highWaterMark'); + } + return highWaterMark; +} +function ExtractSizeAlgorithm(strategy) { + const { size } = strategy; + if (!size) { + return () => 1; + } + return size; +} + +function convertQueuingStrategy(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + const size = init === null || init === void 0 ? void 0 : init.size; + return { + highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark), + size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`) + }; +} +function convertQueuingStrategySize(fn, context) { + assertFunction(fn, context); + return chunk => convertUnrestrictedDouble(fn(chunk)); +} + +function convertUnderlyingSink(original, context) { + assertDictionary(original, context); + const abort = original === null || original === void 0 ? void 0 : original.abort; + const close = original === null || original === void 0 ? void 0 : original.close; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + const write = original === null || original === void 0 ? void 0 : original.write; + return { + abort: abort === undefined ? + undefined : + convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`), + close: close === undefined ? + undefined : + convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`), + start: start === undefined ? + undefined : + convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`), + write: write === undefined ? + undefined : + convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`), + type + }; +} +function convertUnderlyingSinkAbortCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); +} +function convertUnderlyingSinkCloseCallback(fn, original, context) { + assertFunction(fn, context); + return () => promiseCall(fn, original, []); +} +function convertUnderlyingSinkStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); +} +function convertUnderlyingSinkWriteCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); +} + +function assertWritableStream(x, context) { + if (!IsWritableStream(x)) { + throw new TypeError(`${context} is not a WritableStream.`); + } +} + +function isAbortSignal(value) { + if (typeof value !== 'object' || value === null) { + return false; + } + try { + return typeof value.aborted === 'boolean'; + } + catch (_a) { + // AbortSignal.prototype.aborted throws if its brand check fails + return false; + } +} +const supportsAbortController = typeof AbortController === 'function'; +/** + * Construct a new AbortController, if supported by the platform. + * + * @internal + */ +function createAbortController() { + if (supportsAbortController) { + return new AbortController(); + } + return undefined; +} + +/** + * A writable stream represents a destination for data, into which you can write. + * + * @public + */ +class WritableStream { + constructor(rawUnderlyingSink = {}, rawStrategy = {}) { + if (rawUnderlyingSink === undefined) { + rawUnderlyingSink = null; + } + else { + assertObject(rawUnderlyingSink, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter'); + InitializeWritableStream(this); + const type = underlyingSink.type; + if (type !== undefined) { + throw new RangeError('Invalid type is specified'); + } + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); + } + /** + * Returns whether or not the writable stream is locked to a writer. + */ + get locked() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('locked'); + } + return IsWritableStreamLocked(this); + } + /** + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort + * mechanism of the underlying sink. + * + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel + * the stream) if the stream is currently locked. + */ + abort(reason = undefined) { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('abort')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer')); + } + return WritableStreamAbort(this, reason); + } + /** + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its + * close behavior. During this time any further attempts to write will fail (without erroring the stream). + * + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + */ + close() { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('close')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer')); + } + if (WritableStreamCloseQueuedOrInFlight(this)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamClose(this); + } + /** + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream + * is locked, no other writer can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at + * the same time, which would cause the resulting written data to be unpredictable and probably useless. + */ + getWriter() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('getWriter'); + } + return AcquireWritableStreamDefaultWriter(this); + } +} +Object.defineProperties(WritableStream.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + getWriter: { enumerable: true }, + locked: { enumerable: true } +}); +setFunctionName(WritableStream.prototype.abort, 'abort'); +setFunctionName(WritableStream.prototype.close, 'close'); +setFunctionName(WritableStream.prototype.getWriter, 'getWriter'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, { + value: 'WritableStream', + configurable: true + }); +} +// Abstract operations for the WritableStream. +function AcquireWritableStreamDefaultWriter(stream) { + return new WritableStreamDefaultWriter(stream); +} +// Throws if and only if startAlgorithm throws. +function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(WritableStream.prototype); + InitializeWritableStream(stream); + const controller = Object.create(WritableStreamDefaultController.prototype); + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + return stream; +} +function InitializeWritableStream(stream) { + stream._state = 'writable'; + // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is + // 'erroring' or 'errored'. May be set to an undefined value. + stream._storedError = undefined; + stream._writer = undefined; + // Initialize to undefined first because the constructor of the controller checks this + // variable to validate the caller. + stream._writableStreamController = undefined; + // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data + // producer without waiting for the queued writes to finish. + stream._writeRequests = new SimpleQueue(); + // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents + // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here. + stream._inFlightWriteRequest = undefined; + // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer + // has been detached. + stream._closeRequest = undefined; + // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it + // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here. + stream._inFlightCloseRequest = undefined; + // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached. + stream._pendingAbortRequest = undefined; + // The backpressure signal set by the controller. + stream._backpressure = false; +} +function IsWritableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) { + return false; + } + return x instanceof WritableStream; +} +function IsWritableStreamLocked(stream) { + if (stream._writer === undefined) { + return false; + } + return true; +} +function WritableStreamAbort(stream, reason) { + var _a; + if (stream._state === 'closed' || stream._state === 'errored') { + return promiseResolvedWith(undefined); + } + stream._writableStreamController._abortReason = reason; + (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort(reason); + // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring', + // but it doesn't know that signaling abort runs author code that might have changed the state. + // Widen the type again by casting to WritableStreamState. + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseResolvedWith(undefined); + } + if (stream._pendingAbortRequest !== undefined) { + return stream._pendingAbortRequest._promise; + } + let wasAlreadyErroring = false; + if (state === 'erroring') { + wasAlreadyErroring = true; + // reason will not be used, so don't keep a reference to it. + reason = undefined; + } + const promise = newPromise((resolve, reject) => { + stream._pendingAbortRequest = { + _promise: undefined, + _resolve: resolve, + _reject: reject, + _reason: reason, + _wasAlreadyErroring: wasAlreadyErroring + }; + }); + stream._pendingAbortRequest._promise = promise; + if (!wasAlreadyErroring) { + WritableStreamStartErroring(stream, reason); + } + return promise; +} +function WritableStreamClose(stream) { + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`)); + } + const promise = newPromise((resolve, reject) => { + const closeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._closeRequest = closeRequest; + }); + const writer = stream._writer; + if (writer !== undefined && stream._backpressure && state === 'writable') { + defaultWriterReadyPromiseResolve(writer); + } + WritableStreamDefaultControllerClose(stream._writableStreamController); + return promise; +} +// WritableStream API exposed for controllers. +function WritableStreamAddWriteRequest(stream) { + const promise = newPromise((resolve, reject) => { + const writeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._writeRequests.push(writeRequest); + }); + return promise; +} +function WritableStreamDealWithRejection(stream, error) { + const state = stream._state; + if (state === 'writable') { + WritableStreamStartErroring(stream, error); + return; + } + WritableStreamFinishErroring(stream); +} +function WritableStreamStartErroring(stream, reason) { + const controller = stream._writableStreamController; + stream._state = 'erroring'; + stream._storedError = reason; + const writer = stream._writer; + if (writer !== undefined) { + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); + } + if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { + WritableStreamFinishErroring(stream); + } +} +function WritableStreamFinishErroring(stream) { + stream._state = 'errored'; + stream._writableStreamController[ErrorSteps](); + const storedError = stream._storedError; + stream._writeRequests.forEach(writeRequest => { + writeRequest._reject(storedError); + }); + stream._writeRequests = new SimpleQueue(); + if (stream._pendingAbortRequest === undefined) { + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const abortRequest = stream._pendingAbortRequest; + stream._pendingAbortRequest = undefined; + if (abortRequest._wasAlreadyErroring) { + abortRequest._reject(storedError); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const promise = stream._writableStreamController[AbortSteps](abortRequest._reason); + uponPromise(promise, () => { + abortRequest._resolve(); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }, (reason) => { + abortRequest._reject(reason); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }); +} +function WritableStreamFinishInFlightWrite(stream) { + stream._inFlightWriteRequest._resolve(undefined); + stream._inFlightWriteRequest = undefined; +} +function WritableStreamFinishInFlightWriteWithError(stream, error) { + stream._inFlightWriteRequest._reject(error); + stream._inFlightWriteRequest = undefined; + WritableStreamDealWithRejection(stream, error); +} +function WritableStreamFinishInFlightClose(stream) { + stream._inFlightCloseRequest._resolve(undefined); + stream._inFlightCloseRequest = undefined; + const state = stream._state; + if (state === 'erroring') { + // The error was too late to do anything, so it is ignored. + stream._storedError = undefined; + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._resolve(); + stream._pendingAbortRequest = undefined; + } + } + stream._state = 'closed'; + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseResolve(writer); + } +} +function WritableStreamFinishInFlightCloseWithError(stream, error) { + stream._inFlightCloseRequest._reject(error); + stream._inFlightCloseRequest = undefined; + // Never execute sink abort() after sink close(). + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._reject(error); + stream._pendingAbortRequest = undefined; + } + WritableStreamDealWithRejection(stream, error); +} +// TODO(ricea): Fix alphabetical order. +function WritableStreamCloseQueuedOrInFlight(stream) { + if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; +} +function WritableStreamHasOperationMarkedInFlight(stream) { + if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; +} +function WritableStreamMarkCloseRequestInFlight(stream) { + stream._inFlightCloseRequest = stream._closeRequest; + stream._closeRequest = undefined; +} +function WritableStreamMarkFirstWriteRequestInFlight(stream) { + stream._inFlightWriteRequest = stream._writeRequests.shift(); +} +function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { + if (stream._closeRequest !== undefined) { + stream._closeRequest._reject(stream._storedError); + stream._closeRequest = undefined; + } + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseReject(writer, stream._storedError); + } +} +function WritableStreamUpdateBackpressure(stream, backpressure) { + const writer = stream._writer; + if (writer !== undefined && backpressure !== stream._backpressure) { + if (backpressure) { + defaultWriterReadyPromiseReset(writer); + } + else { + defaultWriterReadyPromiseResolve(writer); + } + } + stream._backpressure = backpressure; +} +/** + * A default writer vended by a {@link WritableStream}. + * + * @public + */ +class WritableStreamDefaultWriter { + constructor(stream) { + assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter'); + assertWritableStream(stream, 'First parameter'); + if (IsWritableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive writing by another writer'); + } + this._ownerWritableStream = stream; + stream._writer = this; + const state = stream._state; + if (state === 'writable') { + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { + defaultWriterReadyPromiseInitialize(this); + } + else { + defaultWriterReadyPromiseInitializeAsResolved(this); + } + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'erroring') { + defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'closed') { + defaultWriterReadyPromiseInitializeAsResolved(this); + defaultWriterClosedPromiseInitializeAsResolved(this); + } + else { + const storedError = stream._storedError; + defaultWriterReadyPromiseInitializeAsRejected(this, storedError); + defaultWriterClosedPromiseInitializeAsRejected(this, storedError); + } + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the writer’s lock is released before the stream finishes closing. + */ + get closed() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. + * A producer can use this information to determine the right amount of data to write. + * + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when + * the writer’s lock is released. + */ + get desiredSize() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('desiredSize'); + } + if (this._ownerWritableStream === undefined) { + throw defaultWriterLockException('desiredSize'); + } + return WritableStreamDefaultWriterGetDesiredSize(this); + } + /** + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips + * back to zero or below, the getter will return a new promise that stays pending until the next transition. + * + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become + * rejected. + */ + get ready() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('ready')); + } + return this._readyPromise; + } + /** + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + */ + abort(reason = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('abort')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('abort')); + } + return WritableStreamDefaultWriterAbort(this, reason); + } + /** + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + */ + close() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('close')); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return promiseRejectedWith(defaultWriterLockException('close')); + } + if (WritableStreamCloseQueuedOrInFlight(stream)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamDefaultWriterClose(this); + } + /** + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from + * now on; otherwise, the writer will appear closed. + * + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents + * other producers from writing in an interleaved manner. + */ + releaseLock() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('releaseLock'); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return; + } + WritableStreamDefaultWriterRelease(this); + } + write(chunk = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('write')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + return WritableStreamDefaultWriterWrite(this, chunk); + } +} +Object.defineProperties(WritableStreamDefaultWriter.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + releaseLock: { enumerable: true }, + write: { enumerable: true }, + closed: { enumerable: true }, + desiredSize: { enumerable: true }, + ready: { enumerable: true } +}); +setFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort'); +setFunctionName(WritableStreamDefaultWriter.prototype.close, 'close'); +setFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock'); +setFunctionName(WritableStreamDefaultWriter.prototype.write, 'write'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, { + value: 'WritableStreamDefaultWriter', + configurable: true + }); +} +// Abstract operations for the WritableStreamDefaultWriter. +function IsWritableStreamDefaultWriter(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultWriter; +} +// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check. +function WritableStreamDefaultWriterAbort(writer, reason) { + const stream = writer._ownerWritableStream; + return WritableStreamAbort(stream, reason); +} +function WritableStreamDefaultWriterClose(writer) { + const stream = writer._ownerWritableStream; + return WritableStreamClose(stream); +} +function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseResolvedWith(undefined); + } + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + return WritableStreamDefaultWriterClose(writer); +} +function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { + if (writer._closedPromiseState === 'pending') { + defaultWriterClosedPromiseReject(writer, error); + } + else { + defaultWriterClosedPromiseResetToRejected(writer, error); + } +} +function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { + if (writer._readyPromiseState === 'pending') { + defaultWriterReadyPromiseReject(writer, error); + } + else { + defaultWriterReadyPromiseResetToRejected(writer, error); + } +} +function WritableStreamDefaultWriterGetDesiredSize(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (state === 'errored' || state === 'erroring') { + return null; + } + if (state === 'closed') { + return 0; + } + return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); +} +function WritableStreamDefaultWriterRelease(writer) { + const stream = writer._ownerWritableStream; + const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`); + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); + // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not + // rejected until afterwards. This means that simply testing state will not work. + WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); + stream._writer = undefined; + writer._ownerWritableStream = undefined; +} +function WritableStreamDefaultWriterWrite(writer, chunk) { + const stream = writer._ownerWritableStream; + const controller = stream._writableStreamController; + const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); + if (stream !== writer._ownerWritableStream) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + const state = stream._state; + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to')); + } + if (state === 'erroring') { + return promiseRejectedWith(stream._storedError); + } + const promise = WritableStreamAddWriteRequest(stream); + WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); + return promise; +} +const closeSentinel = {}; +/** + * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. + * + * @public + */ +class WritableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. + * + * @deprecated + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. + */ + get abortReason() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('abortReason'); + } + return this._abortReason; + } + /** + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. + */ + get signal() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('signal'); + } + if (this._abortController === undefined) { + // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`. + // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill, + // so instead we only implement support for `signal` if we find a global `AbortController` constructor. + throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported'); + } + return this._abortController.signal; + } + /** + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. + * + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the + * normal lifecycle of interactions with the underlying sink. + */ + error(e = undefined) { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('error'); + } + const state = this._controlledWritableStream._state; + if (state !== 'writable') { + // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so + // just treat it as a no-op. + return; + } + WritableStreamDefaultControllerError(this, e); + } + /** @internal */ + [AbortSteps](reason) { + const result = this._abortAlgorithm(reason); + WritableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [ErrorSteps]() { + ResetQueue(this); + } +} +Object.defineProperties(WritableStreamDefaultController.prototype, { + abortReason: { enumerable: true }, + signal: { enumerable: true }, + error: { enumerable: true } +}); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, { + value: 'WritableStreamDefaultController', + configurable: true + }); +} +// Abstract operations implementing interface required by the WritableStream. +function IsWritableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultController; +} +function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledWritableStream = stream; + stream._writableStreamController = controller; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._abortReason = undefined; + controller._abortController = createAbortController(); + controller._started = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._writeAlgorithm = writeAlgorithm; + controller._closeAlgorithm = closeAlgorithm; + controller._abortAlgorithm = abortAlgorithm; + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + const startResult = startAlgorithm(); + const startPromise = promiseResolvedWith(startResult); + uponPromise(startPromise, () => { + controller._started = true; + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, r => { + controller._started = true; + WritableStreamDealWithRejection(stream, r); + return null; + }); +} +function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { + const controller = Object.create(WritableStreamDefaultController.prototype); + let startAlgorithm; + let writeAlgorithm; + let closeAlgorithm; + let abortAlgorithm; + if (underlyingSink.start !== undefined) { + startAlgorithm = () => underlyingSink.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingSink.write !== undefined) { + writeAlgorithm = chunk => underlyingSink.write(chunk, controller); + } + else { + writeAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSink.close !== undefined) { + closeAlgorithm = () => underlyingSink.close(); + } + else { + closeAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSink.abort !== undefined) { + abortAlgorithm = reason => underlyingSink.abort(reason); + } + else { + abortAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); +} +// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls. +function WritableStreamDefaultControllerClearAlgorithms(controller) { + controller._writeAlgorithm = undefined; + controller._closeAlgorithm = undefined; + controller._abortAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; +} +function WritableStreamDefaultControllerClose(controller) { + EnqueueValueWithSize(controller, closeSentinel, 0); + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); +} +function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { + try { + return controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); + return 1; + } +} +function WritableStreamDefaultControllerGetDesiredSize(controller) { + return controller._strategyHWM - controller._queueTotalSize; +} +function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); + return; + } + const stream = controller._controlledWritableStream; + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); +} +// Abstract operations for the WritableStreamDefaultController. +function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { + const stream = controller._controlledWritableStream; + if (!controller._started) { + return; + } + if (stream._inFlightWriteRequest !== undefined) { + return; + } + const state = stream._state; + if (state === 'erroring') { + WritableStreamFinishErroring(stream); + return; + } + if (controller._queue.length === 0) { + return; + } + const value = PeekQueueValue(controller); + if (value === closeSentinel) { + WritableStreamDefaultControllerProcessClose(controller); + } + else { + WritableStreamDefaultControllerProcessWrite(controller, value); + } +} +function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { + if (controller._controlledWritableStream._state === 'writable') { + WritableStreamDefaultControllerError(controller, error); + } +} +function WritableStreamDefaultControllerProcessClose(controller) { + const stream = controller._controlledWritableStream; + WritableStreamMarkCloseRequestInFlight(stream); + DequeueValue(controller); + const sinkClosePromise = controller._closeAlgorithm(); + WritableStreamDefaultControllerClearAlgorithms(controller); + uponPromise(sinkClosePromise, () => { + WritableStreamFinishInFlightClose(stream); + return null; + }, reason => { + WritableStreamFinishInFlightCloseWithError(stream, reason); + return null; + }); +} +function WritableStreamDefaultControllerProcessWrite(controller, chunk) { + const stream = controller._controlledWritableStream; + WritableStreamMarkFirstWriteRequestInFlight(stream); + const sinkWritePromise = controller._writeAlgorithm(chunk); + uponPromise(sinkWritePromise, () => { + WritableStreamFinishInFlightWrite(stream); + const state = stream._state; + DequeueValue(controller); + if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, reason => { + if (stream._state === 'writable') { + WritableStreamDefaultControllerClearAlgorithms(controller); + } + WritableStreamFinishInFlightWriteWithError(stream, reason); + return null; + }); +} +function WritableStreamDefaultControllerGetBackpressure(controller) { + const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); + return desiredSize <= 0; +} +// A client of WritableStreamDefaultController may use these functions directly to bypass state check. +function WritableStreamDefaultControllerError(controller, error) { + const stream = controller._controlledWritableStream; + WritableStreamDefaultControllerClearAlgorithms(controller); + WritableStreamStartErroring(stream, error); +} +// Helper functions for the WritableStream. +function streamBrandCheckException$2(name) { + return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`); +} +// Helper functions for the WritableStreamDefaultController. +function defaultControllerBrandCheckException$2(name) { + return new TypeError(`WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`); +} +// Helper functions for the WritableStreamDefaultWriter. +function defaultWriterBrandCheckException(name) { + return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`); +} +function defaultWriterLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released writer'); +} +function defaultWriterClosedPromiseInitialize(writer) { + writer._closedPromise = newPromise((resolve, reject) => { + writer._closedPromise_resolve = resolve; + writer._closedPromise_reject = reject; + writer._closedPromiseState = 'pending'; + }); +} +function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseReject(writer, reason); +} +function defaultWriterClosedPromiseInitializeAsResolved(writer) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseResolve(writer); +} +function defaultWriterClosedPromiseReject(writer, reason) { + if (writer._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._closedPromise); + writer._closedPromise_reject(reason); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'rejected'; +} +function defaultWriterClosedPromiseResetToRejected(writer, reason) { + defaultWriterClosedPromiseInitializeAsRejected(writer, reason); +} +function defaultWriterClosedPromiseResolve(writer) { + if (writer._closedPromise_resolve === undefined) { + return; + } + writer._closedPromise_resolve(undefined); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'resolved'; +} +function defaultWriterReadyPromiseInitialize(writer) { + writer._readyPromise = newPromise((resolve, reject) => { + writer._readyPromise_resolve = resolve; + writer._readyPromise_reject = reject; + }); + writer._readyPromiseState = 'pending'; +} +function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseReject(writer, reason); +} +function defaultWriterReadyPromiseInitializeAsResolved(writer) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseResolve(writer); +} +function defaultWriterReadyPromiseReject(writer, reason) { + if (writer._readyPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._readyPromise); + writer._readyPromise_reject(reason); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'rejected'; +} +function defaultWriterReadyPromiseReset(writer) { + defaultWriterReadyPromiseInitialize(writer); +} +function defaultWriterReadyPromiseResetToRejected(writer, reason) { + defaultWriterReadyPromiseInitializeAsRejected(writer, reason); +} +function defaultWriterReadyPromiseResolve(writer) { + if (writer._readyPromise_resolve === undefined) { + return; + } + writer._readyPromise_resolve(undefined); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'fulfilled'; +} + +/// +function getGlobals() { + if (typeof globalThis !== 'undefined') { + return globalThis; + } + else if (typeof self !== 'undefined') { + return self; + } + else if (typeof global !== 'undefined') { + return global; + } + return undefined; +} +const globals = getGlobals(); + +/// +function isDOMExceptionConstructor(ctor) { + if (!(typeof ctor === 'function' || typeof ctor === 'object')) { + return false; + } + if (ctor.name !== 'DOMException') { + return false; + } + try { + new ctor(); + return true; + } + catch (_a) { + return false; + } +} +/** + * Support: + * - Web browsers + * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87) + */ +function getFromGlobal() { + const ctor = globals === null || globals === void 0 ? void 0 : globals.DOMException; + return isDOMExceptionConstructor(ctor) ? ctor : undefined; +} +/** + * Support: + * - All platforms + */ +function createPolyfill() { + // eslint-disable-next-line @typescript-eslint/no-shadow + const ctor = function DOMException(message, name) { + this.message = message || ''; + this.name = name || 'Error'; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + }; + setFunctionName(ctor, 'DOMException'); + ctor.prototype = Object.create(Error.prototype); + Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true }); + return ctor; +} +// eslint-disable-next-line @typescript-eslint/no-redeclare +const DOMException = getFromGlobal() || createPolyfill(); + +function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { + const reader = AcquireReadableStreamDefaultReader(source); + const writer = AcquireWritableStreamDefaultWriter(dest); + source._disturbed = true; + let shuttingDown = false; + // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown. + let currentWrite = promiseResolvedWith(undefined); + return newPromise((resolve, reject) => { + let abortAlgorithm; + if (signal !== undefined) { + abortAlgorithm = () => { + const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError'); + const actions = []; + if (!preventAbort) { + actions.push(() => { + if (dest._state === 'writable') { + return WritableStreamAbort(dest, error); + } + return promiseResolvedWith(undefined); + }); + } + if (!preventCancel) { + actions.push(() => { + if (source._state === 'readable') { + return ReadableStreamCancel(source, error); + } + return promiseResolvedWith(undefined); + }); + } + shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error); + }; + if (signal.aborted) { + abortAlgorithm(); + return; + } + signal.addEventListener('abort', abortAlgorithm); + } + // Using reader and writer, read all chunks from this and write them to dest + // - Backpressure must be enforced + // - Shutdown must stop all activity + function pipeLoop() { + return newPromise((resolveLoop, rejectLoop) => { + function next(done) { + if (done) { + resolveLoop(); + } + else { + // Use `PerformPromiseThen` instead of `uponPromise` to avoid + // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers + PerformPromiseThen(pipeStep(), next, rejectLoop); + } + } + next(false); + }); + } + function pipeStep() { + if (shuttingDown) { + return promiseResolvedWith(true); + } + return PerformPromiseThen(writer._readyPromise, () => { + return newPromise((resolveRead, rejectRead) => { + ReadableStreamDefaultReaderRead(reader, { + _chunkSteps: chunk => { + currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop); + resolveRead(false); + }, + _closeSteps: () => resolveRead(true), + _errorSteps: rejectRead + }); + }); + }); + } + // Errors must be propagated forward + isOrBecomesErrored(source, reader._closedPromise, storedError => { + if (!preventAbort) { + shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Errors must be propagated backward + isOrBecomesErrored(dest, writer._closedPromise, storedError => { + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Closing must be propagated forward + isOrBecomesClosed(source, reader._closedPromise, () => { + if (!preventClose) { + shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer)); + } + else { + shutdown(); + } + return null; + }); + // Closing must be propagated backward + if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') { + const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it'); + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed); + } + else { + shutdown(true, destClosed); + } + } + setPromiseIsHandledToTrue(pipeLoop()); + function waitForWritesToFinish() { + // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait + // for that too. + const oldCurrentWrite = currentWrite; + return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined); + } + function isOrBecomesErrored(stream, promise, action) { + if (stream._state === 'errored') { + action(stream._storedError); + } + else { + uponRejection(promise, action); + } + } + function isOrBecomesClosed(stream, promise, action) { + if (stream._state === 'closed') { + action(); + } + else { + uponFulfillment(promise, action); + } + } + function shutdownWithAction(action, originalIsError, originalError) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), doTheRest); + } + else { + doTheRest(); + } + function doTheRest() { + uponPromise(action(), () => finalize(originalIsError, originalError), newError => finalize(true, newError)); + return null; + } + } + function shutdown(isError, error) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error)); + } + else { + finalize(isError, error); + } + } + function finalize(isError, error) { + WritableStreamDefaultWriterRelease(writer); + ReadableStreamReaderGenericRelease(reader); + if (signal !== undefined) { + signal.removeEventListener('abort', abortAlgorithm); + } + if (isError) { + reject(error); + } + else { + resolve(undefined); + } + return null; + } + }); +} + +/** + * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. + * + * @public + */ +class ReadableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('desiredSize'); + } + return ReadableStreamDefaultControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('close'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits close'); + } + ReadableStreamDefaultControllerClose(this); + } + enqueue(chunk = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('enqueue'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits enqueue'); + } + return ReadableStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('error'); + } + ReadableStreamDefaultControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableStream; + if (this._queue.length > 0) { + const chunk = DequeueValue(this); + if (this._closeRequested && this._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(this); + ReadableStreamClose(stream); + } + else { + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + readRequest._chunkSteps(chunk); + } + else { + ReadableStreamAddReadRequest(stream, readRequest); + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + } + /** @internal */ + [ReleaseSteps]() { + // Do nothing. + } +} +Object.defineProperties(ReadableStreamDefaultController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + desiredSize: { enumerable: true } +}); +setFunctionName(ReadableStreamDefaultController.prototype.close, 'close'); +setFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue'); +setFunctionName(ReadableStreamDefaultController.prototype.error, 'error'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, { + value: 'ReadableStreamDefaultController', + configurable: true + }); +} +// Abstract operations for the ReadableStreamDefaultController. +function IsReadableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) { + return false; + } + return x instanceof ReadableStreamDefaultController; +} +function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + return null; + }, e => { + ReadableStreamDefaultControllerError(controller, e); + return null; + }); +} +function ReadableStreamDefaultControllerShouldCallPull(controller) { + const stream = controller._controlledReadableStream; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return false; + } + if (!controller._started) { + return false; + } + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; +} +function ReadableStreamDefaultControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; +} +// A client of ReadableStreamDefaultController may use these functions directly to bypass state check. +function ReadableStreamDefaultControllerClose(controller) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + controller._closeRequested = true; + if (controller._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } +} +function ReadableStreamDefaultControllerEnqueue(controller, chunk) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + ReadableStreamFulfillReadRequest(stream, chunk, false); + } + else { + let chunkSize; + try { + chunkSize = controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + ReadableStreamDefaultControllerError(controller, chunkSizeE); + throw chunkSizeE; + } + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + ReadableStreamDefaultControllerError(controller, enqueueE); + throw enqueueE; + } + } + ReadableStreamDefaultControllerCallPullIfNeeded(controller); +} +function ReadableStreamDefaultControllerError(controller, e) { + const stream = controller._controlledReadableStream; + if (stream._state !== 'readable') { + return; + } + ResetQueue(controller); + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); +} +function ReadableStreamDefaultControllerGetDesiredSize(controller) { + const state = controller._controlledReadableStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; +} +// This is used in the implementation of TransformStream. +function ReadableStreamDefaultControllerHasBackpressure(controller) { + if (ReadableStreamDefaultControllerShouldCallPull(controller)) { + return false; + } + return true; +} +function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { + const state = controller._controlledReadableStream._state; + if (!controller._closeRequested && state === 'readable') { + return true; + } + return false; +} +function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledReadableStream = stream; + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._started = false; + controller._closeRequested = false; + controller._pullAgain = false; + controller._pulling = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + return null; + }, r => { + ReadableStreamDefaultControllerError(controller, r); + return null; + }); +} +function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { + const controller = Object.create(ReadableStreamDefaultController.prototype); + let startAlgorithm; + let pullAlgorithm; + let cancelAlgorithm; + if (underlyingSource.start !== undefined) { + startAlgorithm = () => underlyingSource.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingSource.pull !== undefined) { + pullAlgorithm = () => underlyingSource.pull(controller); + } + else { + pullAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingSource.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); +} +// Helper functions for the ReadableStreamDefaultController. +function defaultControllerBrandCheckException$1(name) { + return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`); +} + +function ReadableStreamTee(stream, cloneForBranch2) { + if (IsReadableByteStreamController(stream._readableStreamController)) { + return ReadableByteStreamTee(stream); + } + return ReadableStreamDefaultTee(stream); +} +function ReadableStreamDefaultTee(stream, cloneForBranch2) { + const reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgain = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function pullAlgorithm() { + if (reading) { + readAgain = true; + return promiseResolvedWith(undefined); + } + reading = true; + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgain = false; + const chunk1 = chunk; + const chunk2 = chunk; + // There is no way to access the cloning code right now in the reference implementation. + // If we add one then we'll need an implementation for serializable objects. + // if (!canceled2 && cloneForBranch2) { + // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2)); + // } + if (!canceled1) { + ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgain) { + pullAlgorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableStreamDefaultControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableStreamDefaultControllerClose(branch2._readableStreamController); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + // do nothing + } + branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); + branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); + uponRejection(reader._closedPromise, (r) => { + ReadableStreamDefaultControllerError(branch1._readableStreamController, r); + ReadableStreamDefaultControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + return [branch1, branch2]; +} +function ReadableByteStreamTee(stream) { + let reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgainForBranch1 = false; + let readAgainForBranch2 = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function forwardReaderError(thisReader) { + uponRejection(thisReader._closedPromise, r => { + if (thisReader !== reader) { + return null; + } + ReadableByteStreamControllerError(branch1._readableStreamController, r); + ReadableByteStreamControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + } + function pullWithDefaultReader() { + if (IsReadableStreamBYOBReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamDefaultReader(stream); + forwardReaderError(reader); + } + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const chunk1 = chunk; + let chunk2 = chunk; + if (!canceled1 && !canceled2) { + try { + chunk2 = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(branch1._readableStreamController, cloneE); + ReadableByteStreamControllerError(branch2._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + } + if (!canceled1) { + ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableByteStreamControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableByteStreamControllerClose(branch2._readableStreamController); + } + if (branch1._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch1._readableStreamController, 0); + } + if (branch2._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch2._readableStreamController, 0); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + } + function pullWithBYOBReader(view, forBranch2) { + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamBYOBReader(stream); + forwardReaderError(reader); + } + const byobBranch = forBranch2 ? branch2 : branch1; + const otherBranch = forBranch2 ? branch1 : branch2; + const readIntoRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!otherCanceled) { + let clonedChunk; + try { + clonedChunk = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE); + ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk); + } + else if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: chunk => { + reading = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!byobCanceled) { + ReadableByteStreamControllerClose(byobBranch._readableStreamController); + } + if (!otherCanceled) { + ReadableByteStreamControllerClose(otherBranch._readableStreamController); + } + if (chunk !== undefined) { + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0); + } + } + if (!byobCanceled || !otherCanceled) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest); + } + function pull1Algorithm() { + if (reading) { + readAgainForBranch1 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, false); + } + return promiseResolvedWith(undefined); + } + function pull2Algorithm() { + if (reading) { + readAgainForBranch2 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, true); + } + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + return; + } + branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm); + branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm); + forwardReaderError(reader); + return [branch1, branch2]; +} + +function isReadableStreamLike(stream) { + return typeIsObject(stream) && typeof stream.getReader !== 'undefined'; +} + +function ReadableStreamFrom(source) { + if (isReadableStreamLike(source)) { + return ReadableStreamFromDefaultReader(source.getReader()); + } + return ReadableStreamFromIterable(source); +} +function ReadableStreamFromIterable(asyncIterable) { + let stream; + const iteratorRecord = GetIterator(asyncIterable, 'async'); + const startAlgorithm = noop; + function pullAlgorithm() { + let nextResult; + try { + nextResult = IteratorNext(iteratorRecord); + } + catch (e) { + return promiseRejectedWith(e); + } + const nextPromise = promiseResolvedWith(nextResult); + return transformPromiseWith(nextPromise, iterResult => { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object'); + } + const done = IteratorComplete(iterResult); + if (done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + const value = IteratorValue(iterResult); + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + const iterator = iteratorRecord.iterator; + let returnMethod; + try { + returnMethod = GetMethod(iterator, 'return'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (returnMethod === undefined) { + return promiseResolvedWith(undefined); + } + let returnResult; + try { + returnResult = reflectCall(returnMethod, iterator, [reason]); + } + catch (e) { + return promiseRejectedWith(e); + } + const returnPromise = promiseResolvedWith(returnResult); + return transformPromiseWith(returnPromise, iterResult => { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object'); + } + return undefined; + }); + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; +} +function ReadableStreamFromDefaultReader(reader) { + let stream; + const startAlgorithm = noop; + function pullAlgorithm() { + let readPromise; + try { + readPromise = reader.read(); + } + catch (e) { + return promiseRejectedWith(e); + } + return transformPromiseWith(readPromise, readResult => { + if (!typeIsObject(readResult)) { + throw new TypeError('The promise returned by the reader.read() method must fulfill with an object'); + } + if (readResult.done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + const value = readResult.value; + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + try { + return promiseResolvedWith(reader.cancel(reason)); + } + catch (e) { + return promiseRejectedWith(e); + } + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; +} + +function convertUnderlyingDefaultOrByteSource(source, context) { + assertDictionary(source, context); + const original = source; + const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; + const cancel = original === null || original === void 0 ? void 0 : original.cancel; + const pull = original === null || original === void 0 ? void 0 : original.pull; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + return { + autoAllocateChunkSize: autoAllocateChunkSize === undefined ? + undefined : + convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`), + cancel: cancel === undefined ? + undefined : + convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`), + pull: pull === undefined ? + undefined : + convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`), + start: start === undefined ? + undefined : + convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`), + type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`) + }; +} +function convertUnderlyingSourceCancelCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); +} +function convertUnderlyingSourcePullCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); +} +function convertUnderlyingSourceStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); +} +function convertReadableStreamType(type, context) { + type = `${type}`; + if (type !== 'bytes') { + throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`); + } + return type; +} + +function convertIteratorOptions(options, context) { + assertDictionary(options, context); + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + return { preventCancel: Boolean(preventCancel) }; +} + +function convertPipeOptions(options, context) { + assertDictionary(options, context); + const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort; + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + const preventClose = options === null || options === void 0 ? void 0 : options.preventClose; + const signal = options === null || options === void 0 ? void 0 : options.signal; + if (signal !== undefined) { + assertAbortSignal(signal, `${context} has member 'signal' that`); + } + return { + preventAbort: Boolean(preventAbort), + preventCancel: Boolean(preventCancel), + preventClose: Boolean(preventClose), + signal + }; +} +function assertAbortSignal(signal, context) { + if (!isAbortSignal(signal)) { + throw new TypeError(`${context} is not an AbortSignal.`); + } +} + +function convertReadableWritablePair(pair, context) { + assertDictionary(pair, context); + const readable = pair === null || pair === void 0 ? void 0 : pair.readable; + assertRequiredField(readable, 'readable', 'ReadableWritablePair'); + assertReadableStream(readable, `${context} has member 'readable' that`); + const writable = pair === null || pair === void 0 ? void 0 : pair.writable; + assertRequiredField(writable, 'writable', 'ReadableWritablePair'); + assertWritableStream(writable, `${context} has member 'writable' that`); + return { readable, writable }; +} + +/** + * A readable stream represents a source of data, from which you can read. + * + * @public + */ +class ReadableStream { + constructor(rawUnderlyingSource = {}, rawStrategy = {}) { + if (rawUnderlyingSource === undefined) { + rawUnderlyingSource = null; + } + else { + assertObject(rawUnderlyingSource, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter'); + InitializeReadableStream(this); + if (underlyingSource.type === 'bytes') { + if (strategy.size !== undefined) { + throw new RangeError('The strategy for a byte stream cannot have a size function'); + } + const highWaterMark = ExtractHighWaterMark(strategy, 0); + SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); + } + else { + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); + } + } + /** + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. + */ + get locked() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('locked'); + } + return IsReadableStreamLocked(this); + } + /** + * Cancels the stream, signaling a loss of interest in the stream by a consumer. + * + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} + * method, which might or might not use it. + */ + cancel(reason = undefined) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('cancel')); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader')); + } + return ReadableStreamCancel(this, reason); + } + getReader(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('getReader'); + } + const options = convertReaderOptions(rawOptions, 'First parameter'); + if (options.mode === undefined) { + return AcquireReadableStreamDefaultReader(this); + } + return AcquireReadableStreamBYOBReader(this); + } + pipeThrough(rawTransform, rawOptions = {}) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('pipeThrough'); + } + assertRequiredArgument(rawTransform, 1, 'pipeThrough'); + const transform = convertReadableWritablePair(rawTransform, 'First parameter'); + const options = convertPipeOptions(rawOptions, 'Second parameter'); + if (IsReadableStreamLocked(this)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream'); + } + if (IsWritableStreamLocked(transform.writable)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream'); + } + const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + setPromiseIsHandledToTrue(promise); + return transform.readable; + } + pipeTo(destination, rawOptions = {}) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('pipeTo')); + } + if (destination === undefined) { + return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`); + } + if (!IsWritableStream(destination)) { + return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)); + } + let options; + try { + options = convertPipeOptions(rawOptions, 'Second parameter'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')); + } + if (IsWritableStreamLocked(destination)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')); + } + return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + } + /** + * Tees this readable stream, returning a two-element array containing the two resulting branches as + * new {@link ReadableStream} instances. + * + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be + * propagated to the stream's underlying source. + * + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, + * this could allow interference between the two branches. + */ + tee() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('tee'); + } + const branches = ReadableStreamTee(this); + return CreateArrayFromList(branches); + } + values(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('values'); + } + const options = convertIteratorOptions(rawOptions, 'First parameter'); + return AcquireReadableStreamAsyncIterator(this, options.preventCancel); + } + [SymbolAsyncIterator](options) { + // Stub implementation, overridden below + return this.values(options); + } + /** + * Creates a new ReadableStream wrapping the provided iterable or async iterable. + * + * This can be used to adapt various kinds of objects into a readable stream, + * such as an array, an async generator, or a Node.js readable stream. + */ + static from(asyncIterable) { + return ReadableStreamFrom(asyncIterable); + } +} +Object.defineProperties(ReadableStream, { + from: { enumerable: true } +}); +Object.defineProperties(ReadableStream.prototype, { + cancel: { enumerable: true }, + getReader: { enumerable: true }, + pipeThrough: { enumerable: true }, + pipeTo: { enumerable: true }, + tee: { enumerable: true }, + values: { enumerable: true }, + locked: { enumerable: true } +}); +setFunctionName(ReadableStream.from, 'from'); +setFunctionName(ReadableStream.prototype.cancel, 'cancel'); +setFunctionName(ReadableStream.prototype.getReader, 'getReader'); +setFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough'); +setFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo'); +setFunctionName(ReadableStream.prototype.tee, 'tee'); +setFunctionName(ReadableStream.prototype.values, 'values'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, { + value: 'ReadableStream', + configurable: true + }); +} +Object.defineProperty(ReadableStream.prototype, SymbolAsyncIterator, { + value: ReadableStream.prototype.values, + writable: true, + configurable: true +}); +// Abstract operations for the ReadableStream. +// Throws if and only if startAlgorithm throws. +function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableStreamDefaultController.prototype); + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + return stream; +} +// Throws if and only if startAlgorithm throws. +function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableByteStreamController.prototype); + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined); + return stream; +} +function InitializeReadableStream(stream) { + stream._state = 'readable'; + stream._reader = undefined; + stream._storedError = undefined; + stream._disturbed = false; +} +function IsReadableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) { + return false; + } + return x instanceof ReadableStream; +} +function IsReadableStreamLocked(stream) { + if (stream._reader === undefined) { + return false; + } + return true; +} +// ReadableStream API exposed for controllers. +function ReadableStreamCancel(stream, reason) { + stream._disturbed = true; + if (stream._state === 'closed') { + return promiseResolvedWith(undefined); + } + if (stream._state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + ReadableStreamClose(stream); + const reader = stream._reader; + if (reader !== undefined && IsReadableStreamBYOBReader(reader)) { + const readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._closeSteps(undefined); + }); + } + const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); + return transformPromiseWith(sourceCancelPromise, noop); +} +function ReadableStreamClose(stream) { + stream._state = 'closed'; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseResolve(reader); + if (IsReadableStreamDefaultReader(reader)) { + const readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(readRequest => { + readRequest._closeSteps(); + }); + } +} +function ReadableStreamError(stream, e) { + stream._state = 'errored'; + stream._storedError = e; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseReject(reader, e); + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamDefaultReaderErrorReadRequests(reader, e); + } + else { + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); + } +} +// Helper functions for the ReadableStream. +function streamBrandCheckException$1(name) { + return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`); +} + +function convertQueuingStrategyInit(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit'); + return { + highWaterMark: convertUnrestrictedDouble(highWaterMark) + }; +} + +// The size function must not have a prototype property nor be a constructor +const byteLengthSizeFunction = (chunk) => { + return chunk.byteLength; +}; +setFunctionName(byteLengthSizeFunction, 'size'); +/** + * A queuing strategy that counts the number of bytes in each chunk. + * + * @public + */ +class ByteLengthQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('highWaterMark'); + } + return this._byteLengthQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by returning the value of its `byteLength` property. + */ + get size() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('size'); + } + return byteLengthSizeFunction; + } +} +Object.defineProperties(ByteLengthQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } +}); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, { + value: 'ByteLengthQueuingStrategy', + configurable: true + }); +} +// Helper functions for the ByteLengthQueuingStrategy. +function byteLengthBrandCheckException(name) { + return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`); +} +function IsByteLengthQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof ByteLengthQueuingStrategy; +} + +// The size function must not have a prototype property nor be a constructor +const countSizeFunction = () => { + return 1; +}; +setFunctionName(countSizeFunction, 'size'); +/** + * A queuing strategy that counts the number of chunks. + * + * @public + */ +class CountQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'CountQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._countQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('highWaterMark'); + } + return this._countQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by always returning 1. + * This ensures that the total queue size is a count of the number of chunks in the queue. + */ + get size() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('size'); + } + return countSizeFunction; + } +} +Object.defineProperties(CountQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } +}); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, { + value: 'CountQueuingStrategy', + configurable: true + }); +} +// Helper functions for the CountQueuingStrategy. +function countBrandCheckException(name) { + return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`); +} +function IsCountQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof CountQueuingStrategy; +} + +function convertTransformer(original, context) { + assertDictionary(original, context); + const cancel = original === null || original === void 0 ? void 0 : original.cancel; + const flush = original === null || original === void 0 ? void 0 : original.flush; + const readableType = original === null || original === void 0 ? void 0 : original.readableType; + const start = original === null || original === void 0 ? void 0 : original.start; + const transform = original === null || original === void 0 ? void 0 : original.transform; + const writableType = original === null || original === void 0 ? void 0 : original.writableType; + return { + cancel: cancel === undefined ? + undefined : + convertTransformerCancelCallback(cancel, original, `${context} has member 'cancel' that`), + flush: flush === undefined ? + undefined : + convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`), + readableType, + start: start === undefined ? + undefined : + convertTransformerStartCallback(start, original, `${context} has member 'start' that`), + transform: transform === undefined ? + undefined : + convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`), + writableType + }; +} +function convertTransformerFlushCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); +} +function convertTransformerStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); +} +function convertTransformerTransformCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); +} +function convertTransformerCancelCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); +} + +// Class TransformStream +/** + * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, + * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. + * In a manner specific to the transform stream in question, writes to the writable side result in new data being + * made available for reading from the readable side. + * + * @public + */ +class TransformStream { + constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) { + if (rawTransformer === undefined) { + rawTransformer = null; + } + const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter'); + const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter'); + const transformer = convertTransformer(rawTransformer, 'First parameter'); + if (transformer.readableType !== undefined) { + throw new RangeError('Invalid readableType specified'); + } + if (transformer.writableType !== undefined) { + throw new RangeError('Invalid writableType specified'); + } + const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); + const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); + const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); + const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); + let startPromise_resolve; + const startPromise = newPromise(resolve => { + startPromise_resolve = resolve; + }); + InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); + if (transformer.start !== undefined) { + startPromise_resolve(transformer.start(this._transformStreamController)); + } + else { + startPromise_resolve(undefined); + } + } + /** + * The readable side of the transform stream. + */ + get readable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('readable'); + } + return this._readable; + } + /** + * The writable side of the transform stream. + */ + get writable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('writable'); + } + return this._writable; + } +} +Object.defineProperties(TransformStream.prototype, { + readable: { enumerable: true }, + writable: { enumerable: true } +}); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, { + value: 'TransformStream', + configurable: true + }); +} +function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { + function startAlgorithm() { + return startPromise; + } + function writeAlgorithm(chunk) { + return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); + } + function abortAlgorithm(reason) { + return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); + } + function closeAlgorithm() { + return TransformStreamDefaultSinkCloseAlgorithm(stream); + } + stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); + function pullAlgorithm() { + return TransformStreamDefaultSourcePullAlgorithm(stream); + } + function cancelAlgorithm(reason) { + return TransformStreamDefaultSourceCancelAlgorithm(stream, reason); + } + stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure. + stream._backpressure = undefined; + stream._backpressureChangePromise = undefined; + stream._backpressureChangePromise_resolve = undefined; + TransformStreamSetBackpressure(stream, true); + stream._transformStreamController = undefined; +} +function IsTransformStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) { + return false; + } + return x instanceof TransformStream; +} +// This is a no-op if both sides are already errored. +function TransformStreamError(stream, e) { + ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e); + TransformStreamErrorWritableAndUnblockWrite(stream, e); +} +function TransformStreamErrorWritableAndUnblockWrite(stream, e) { + TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); + WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e); + TransformStreamUnblockWrite(stream); +} +function TransformStreamUnblockWrite(stream) { + if (stream._backpressure) { + // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure() + // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time + // _backpressure is set. + TransformStreamSetBackpressure(stream, false); + } +} +function TransformStreamSetBackpressure(stream, backpressure) { + // Passes also when called during construction. + if (stream._backpressureChangePromise !== undefined) { + stream._backpressureChangePromise_resolve(); + } + stream._backpressureChangePromise = newPromise(resolve => { + stream._backpressureChangePromise_resolve = resolve; + }); + stream._backpressure = backpressure; +} +// Class TransformStreamDefaultController +/** + * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. + * + * @public + */ +class TransformStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. + */ + get desiredSize() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('desiredSize'); + } + const readableController = this._controlledTransformStream._readable._readableStreamController; + return ReadableStreamDefaultControllerGetDesiredSize(readableController); + } + enqueue(chunk = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('enqueue'); + } + TransformStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors both the readable side and the writable side of the controlled transform stream, making all future + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. + */ + error(reason = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('error'); + } + TransformStreamDefaultControllerError(this, reason); + } + /** + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the + * transformer only needs to consume a portion of the chunks written to the writable side. + */ + terminate() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('terminate'); + } + TransformStreamDefaultControllerTerminate(this); + } +} +Object.defineProperties(TransformStreamDefaultController.prototype, { + enqueue: { enumerable: true }, + error: { enumerable: true }, + terminate: { enumerable: true }, + desiredSize: { enumerable: true } +}); +setFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue'); +setFunctionName(TransformStreamDefaultController.prototype.error, 'error'); +setFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, { + value: 'TransformStreamDefaultController', + configurable: true + }); +} +// Transform Stream Default Controller Abstract Operations +function IsTransformStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) { + return false; + } + return x instanceof TransformStreamDefaultController; +} +function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm) { + controller._controlledTransformStream = stream; + stream._transformStreamController = controller; + controller._transformAlgorithm = transformAlgorithm; + controller._flushAlgorithm = flushAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._finishPromise = undefined; + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; +} +function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { + const controller = Object.create(TransformStreamDefaultController.prototype); + let transformAlgorithm; + let flushAlgorithm; + let cancelAlgorithm; + if (transformer.transform !== undefined) { + transformAlgorithm = chunk => transformer.transform(chunk, controller); + } + else { + transformAlgorithm = chunk => { + try { + TransformStreamDefaultControllerEnqueue(controller, chunk); + return promiseResolvedWith(undefined); + } + catch (transformResultE) { + return promiseRejectedWith(transformResultE); + } + }; + } + if (transformer.flush !== undefined) { + flushAlgorithm = () => transformer.flush(controller); + } + else { + flushAlgorithm = () => promiseResolvedWith(undefined); + } + if (transformer.cancel !== undefined) { + cancelAlgorithm = reason => transformer.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm); +} +function TransformStreamDefaultControllerClearAlgorithms(controller) { + controller._transformAlgorithm = undefined; + controller._flushAlgorithm = undefined; + controller._cancelAlgorithm = undefined; +} +function TransformStreamDefaultControllerEnqueue(controller, chunk) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { + throw new TypeError('Readable side is not in a state that permits enqueue'); + } + // We throttle transform invocations based on the backpressure of the ReadableStream, but we still + // accept TransformStreamDefaultControllerEnqueue() calls. + try { + ReadableStreamDefaultControllerEnqueue(readableController, chunk); + } + catch (e) { + // This happens when readableStrategy.size() throws. + TransformStreamErrorWritableAndUnblockWrite(stream, e); + throw stream._readable._storedError; + } + const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); + if (backpressure !== stream._backpressure) { + TransformStreamSetBackpressure(stream, true); + } +} +function TransformStreamDefaultControllerError(controller, e) { + TransformStreamError(controller._controlledTransformStream, e); +} +function TransformStreamDefaultControllerPerformTransform(controller, chunk) { + const transformPromise = controller._transformAlgorithm(chunk); + return transformPromiseWith(transformPromise, undefined, r => { + TransformStreamError(controller._controlledTransformStream, r); + throw r; + }); +} +function TransformStreamDefaultControllerTerminate(controller) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + ReadableStreamDefaultControllerClose(readableController); + const error = new TypeError('TransformStream terminated'); + TransformStreamErrorWritableAndUnblockWrite(stream, error); +} +// TransformStreamDefaultSink Algorithms +function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { + const controller = stream._transformStreamController; + if (stream._backpressure) { + const backpressureChangePromise = stream._backpressureChangePromise; + return transformPromiseWith(backpressureChangePromise, () => { + const writable = stream._writable; + const state = writable._state; + if (state === 'erroring') { + throw writable._storedError; + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + }); + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); +} +function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + const readable = stream._readable; + // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally, + // we don't run the _cancelAlgorithm again. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, () => { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerError(readable._readableStreamController, reason); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; +} +function TransformStreamDefaultSinkCloseAlgorithm(stream) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + const readable = stream._readable; + // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally, + // we don't also run the _cancelAlgorithm. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const flushPromise = controller._flushAlgorithm(); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(flushPromise, () => { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerClose(readable._readableStreamController); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; +} +// TransformStreamDefaultSource Algorithms +function TransformStreamDefaultSourcePullAlgorithm(stream) { + // Invariant. Enforced by the promises returned by start() and pull(). + TransformStreamSetBackpressure(stream, false); + // Prevent the next pull() call until there is backpressure. + return stream._backpressureChangePromise; +} +function TransformStreamDefaultSourceCancelAlgorithm(stream, reason) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._writable cannot change after construction, so caching it across a call to user code is safe. + const writable = stream._writable; + // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or + // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the + // _flushAlgorithm. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, () => { + if (writable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, writable._storedError); + } + else { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; +} +// Helper functions for the TransformStreamDefaultController. +function defaultControllerBrandCheckException(name) { + return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`); +} +function defaultControllerFinishPromiseResolve(controller) { + if (controller._finishPromise_resolve === undefined) { + return; + } + controller._finishPromise_resolve(); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; +} +function defaultControllerFinishPromiseReject(controller, reason) { + if (controller._finishPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(controller._finishPromise); + controller._finishPromise_reject(reason); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; +} +// Helper functions for the TransformStream. +function streamBrandCheckException(name) { + return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`); +} + +const exports = { + ReadableStream, + ReadableStreamDefaultController, + ReadableByteStreamController, + ReadableStreamBYOBRequest, + ReadableStreamDefaultReader, + ReadableStreamBYOBReader, + WritableStream, + WritableStreamDefaultController, + WritableStreamDefaultWriter, + ByteLengthQueuingStrategy, + CountQueuingStrategy, + TransformStream, + TransformStreamDefaultController +}; +// Add classes to global scope +if (typeof globals !== 'undefined') { + for (const prop in exports) { + if (Object.prototype.hasOwnProperty.call(exports, prop)) { + Object.defineProperty(globals, prop, { + value: exports[prop], + writable: true, + configurable: true + }); + } + } +} + +export { ByteLengthQueuingStrategy, CountQueuingStrategy, ReadableByteStreamController, ReadableStream, ReadableStreamBYOBReader, ReadableStreamBYOBRequest, ReadableStreamDefaultController, ReadableStreamDefaultReader, TransformStream, TransformStreamDefaultController, WritableStream, WritableStreamDefaultController, WritableStreamDefaultWriter }; +//# sourceMappingURL=polyfill.es6.mjs.map diff --git a/backend/node_modules/web-streams-polyfill/dist/polyfill.es6.mjs.map b/backend/node_modules/web-streams-polyfill/dist/polyfill.es6.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..d37f8bc2681e3450bd1cab8170adf5ae94eec861 --- /dev/null +++ b/backend/node_modules/web-streams-polyfill/dist/polyfill.es6.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"polyfill.es6.mjs","sources":["../src/utils.ts","../src/lib/helpers/miscellaneous.ts","../src/lib/helpers/webidl.ts","../src/lib/simple-queue.ts","../src/lib/abstract-ops/internal-methods.ts","../src/lib/readable-stream/generic-reader.ts","../src/stub/number-isfinite.ts","../src/stub/math-trunc.ts","../src/lib/validators/basic.ts","../src/lib/validators/readable-stream.ts","../src/lib/readable-stream/default-reader.ts","../node_modules/tslib/tslib.es6.js","../src/lib/abstract-ops/ecmascript.ts","../src/target/es5/stub/async-iterator-prototype.ts","../src/lib/readable-stream/async-iterator.ts","../src/stub/number-isnan.ts","../src/lib/abstract-ops/miscellaneous.ts","../src/lib/abstract-ops/queue-with-sizes.ts","../src/lib/helpers/array-buffer-view.ts","../src/lib/readable-stream/byte-stream-controller.ts","../src/lib/validators/reader-options.ts","../src/lib/readable-stream/byob-reader.ts","../src/lib/abstract-ops/queuing-strategy.ts","../src/lib/validators/queuing-strategy.ts","../src/lib/validators/underlying-sink.ts","../src/lib/validators/writable-stream.ts","../src/lib/abort-signal.ts","../src/lib/writable-stream.ts","../src/globals.ts","../src/stub/dom-exception.ts","../src/lib/readable-stream/pipe.ts","../src/lib/readable-stream/default-controller.ts","../src/lib/readable-stream/tee.ts","../src/lib/readable-stream/readable-stream-like.ts","../src/lib/readable-stream/from.ts","../src/lib/validators/underlying-source.ts","../src/lib/validators/iterator-options.ts","../src/lib/validators/pipe-options.ts","../src/lib/validators/readable-writable-pair.ts","../src/lib/readable-stream.ts","../src/lib/validators/queuing-strategy-init.ts","../src/lib/byte-length-queuing-strategy.ts","../src/lib/count-queuing-strategy.ts","../src/lib/validators/transformer.ts","../src/lib/transform-stream.ts","../src/polyfill.ts"],"sourcesContent":["export function noop(): undefined {\n return undefined;\n}\n","import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n\nexport function setFunctionName(fn: Function, name: string): void {\n try {\n Object.defineProperty(fn, 'name', {\n value: name,\n configurable: true\n });\n } catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n }\n}\n","import { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\n// https://webidl.spec.whatwg.org/#a-new-promise\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-resolved-with\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return newPromise(resolve => resolve(value));\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-rejected-with\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\n// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned\n// from that handler. To prevent this, return null instead of void from all handlers.\n// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => null | PromiseLike,\n onRejected?: (reason: any) => null | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => null | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => null | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nlet _queueMicrotask: (callback: () => void) => void = callback => {\n if (typeof queueMicrotask === 'function') {\n _queueMicrotask = queueMicrotask;\n } else {\n const resolvedPromise = promiseResolvedWith(undefined);\n _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb);\n }\n return _queueMicrotask(callback);\n};\n\nexport { _queueMicrotask as queueMicrotask };\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n","import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n","export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\nexport const ReleaseSteps = Symbol('[[ReleaseSteps]]');\n","import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, type ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\nimport { ReleaseSteps } from '../abstract-ops/internal-methods';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n assert(stream._reader === reader);\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n stream._readableStreamController[ReleaseSteps]();\n\n stream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n","import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n","import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamDefaultReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamDefaultReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\nexport function ReadableStreamDefaultReaderRelease(reader: ReadableStreamDefaultReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n}\n\nexport function ReadableStreamDefaultReaderErrorReadRequests(reader: ReadableStreamDefaultReader, e: any) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n","/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise, SuppressedError, Symbol */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\r\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\r\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\r\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\r\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\r\n var _, done = false;\r\n for (var i = decorators.length - 1; i >= 0; i--) {\r\n var context = {};\r\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\r\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\r\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\r\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\r\n if (kind === \"accessor\") {\r\n if (result === void 0) continue;\r\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\r\n if (_ = accept(result.get)) descriptor.get = _;\r\n if (_ = accept(result.set)) descriptor.set = _;\r\n if (_ = accept(result.init)) initializers.unshift(_);\r\n }\r\n else if (_ = accept(result)) {\r\n if (kind === \"field\") initializers.unshift(_);\r\n else descriptor[key] = _;\r\n }\r\n }\r\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\r\n done = true;\r\n};\r\n\r\nexport function __runInitializers(thisArg, initializers, value) {\r\n var useValue = arguments.length > 2;\r\n for (var i = 0; i < initializers.length; i++) {\r\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\r\n }\r\n return useValue ? value : void 0;\r\n};\r\n\r\nexport function __propKey(x) {\r\n return typeof x === \"symbol\" ? x : \"\".concat(x);\r\n};\r\n\r\nexport function __setFunctionName(f, name, prefix) {\r\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\r\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\r\n};\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n var desc = Object.getOwnPropertyDescriptor(m, k);\r\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\r\n desc = { enumerable: true, get: function() { return m[k]; } };\r\n }\r\n Object.defineProperty(o, k2, desc);\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\nexport function __classPrivateFieldIn(state, receiver) {\r\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\r\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\r\n}\r\n\r\nexport function __addDisposableResource(env, value, async) {\r\n if (value !== null && value !== void 0) {\r\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\r\n var dispose;\r\n if (async) {\r\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\r\n dispose = value[Symbol.asyncDispose];\r\n }\r\n if (dispose === void 0) {\r\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\r\n dispose = value[Symbol.dispose];\r\n }\r\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\r\n env.stack.push({ value: value, dispose: dispose, async: async });\r\n }\r\n else if (async) {\r\n env.stack.push({ async: true });\r\n }\r\n return value;\r\n}\r\n\r\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n};\r\n\r\nexport function __disposeResources(env) {\r\n function fail(e) {\r\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\r\n env.hasError = true;\r\n }\r\n function next() {\r\n while (env.stack.length) {\r\n var rec = env.stack.pop();\r\n try {\r\n var result = rec.dispose && rec.dispose.call(rec.value);\r\n if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\r\n }\r\n catch (e) {\r\n fail(e);\r\n }\r\n }\r\n if (env.hasError) throw env.error;\r\n }\r\n return next();\r\n}\r\n\r\nexport default {\r\n __extends: __extends,\r\n __assign: __assign,\r\n __rest: __rest,\r\n __decorate: __decorate,\r\n __param: __param,\r\n __metadata: __metadata,\r\n __awaiter: __awaiter,\r\n __generator: __generator,\r\n __createBinding: __createBinding,\r\n __exportStar: __exportStar,\r\n __values: __values,\r\n __read: __read,\r\n __spread: __spread,\r\n __spreadArrays: __spreadArrays,\r\n __spreadArray: __spreadArray,\r\n __await: __await,\r\n __asyncGenerator: __asyncGenerator,\r\n __asyncDelegator: __asyncDelegator,\r\n __asyncValues: __asyncValues,\r\n __makeTemplateObject: __makeTemplateObject,\r\n __importStar: __importStar,\r\n __importDefault: __importDefault,\r\n __classPrivateFieldGet: __classPrivateFieldGet,\r\n __classPrivateFieldSet: __classPrivateFieldSet,\r\n __classPrivateFieldIn: __classPrivateFieldIn,\r\n __addDisposableResource: __addDisposableResource,\r\n __disposeResources: __disposeResources,\r\n};\r\n","import { reflectCall } from 'lib/helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport assert from '../../stub/assert';\n\ndeclare global {\n interface ArrayBuffer {\n readonly detached: boolean;\n\n transfer(): ArrayBuffer;\n }\n\n function structuredClone(value: T, options: { transfer: ArrayBuffer[] }): T;\n}\n\nexport function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\nexport let TransferArrayBuffer = (O: ArrayBuffer): ArrayBuffer => {\n if (typeof O.transfer === 'function') {\n TransferArrayBuffer = buffer => buffer.transfer();\n } else if (typeof structuredClone === 'function') {\n TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] });\n } else {\n // Not implemented correctly\n TransferArrayBuffer = buffer => buffer;\n }\n return TransferArrayBuffer(O);\n};\n\nexport function CanTransferArrayBuffer(O: ArrayBuffer): boolean {\n return !IsDetachedBuffer(O);\n}\n\nexport let IsDetachedBuffer = (O: ArrayBuffer): boolean => {\n if (typeof O.detached === 'boolean') {\n IsDetachedBuffer = buffer => buffer.detached;\n } else {\n // Not implemented correctly\n IsDetachedBuffer = buffer => buffer.byteLength === 0;\n }\n return IsDetachedBuffer(O);\n};\n\nexport function ArrayBufferSlice(buffer: ArrayBuffer, begin: number, end: number): ArrayBuffer {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n\nexport type MethodName = {\n [P in keyof T]: T[P] extends Function | undefined ? P : never;\n}[keyof T];\n\nexport function GetMethod>(receiver: T, prop: K): T[K] | undefined {\n const func = receiver[prop];\n if (func === undefined || func === null) {\n return undefined;\n }\n if (typeof func !== 'function') {\n throw new TypeError(`${String(prop)} is not a function`);\n }\n return func;\n}\n\nexport interface SyncIteratorRecord {\n iterator: Iterator,\n nextMethod: Iterator['next'],\n done: boolean;\n}\n\nexport interface AsyncIteratorRecord {\n iterator: AsyncIterator,\n nextMethod: AsyncIterator['next'],\n done: boolean;\n}\n\nexport type SyncOrAsyncIteratorRecord = SyncIteratorRecord | AsyncIteratorRecord;\n\nexport function CreateAsyncFromSyncIterator(syncIteratorRecord: SyncIteratorRecord): AsyncIteratorRecord {\n // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%,\n // we use yield* inside an async generator function to achieve the same result.\n\n // Wrap the sync iterator inside a sync iterable, so we can use it with yield*.\n const syncIterable = {\n [Symbol.iterator]: () => syncIteratorRecord.iterator\n };\n // Create an async generator function and immediately invoke it.\n const asyncIterator = (async function* () {\n return yield* syncIterable;\n }());\n // Return as an async iterator record.\n const nextMethod = asyncIterator.next;\n return { iterator: asyncIterator, nextMethod, done: false };\n}\n\n// Aligns with core-js/modules/es.symbol.async-iterator.js\nexport const SymbolAsyncIterator: (typeof Symbol)['asyncIterator'] =\n Symbol.asyncIterator ??\n Symbol.for?.('Symbol.asyncIterator') ??\n '@@asyncIterator';\n\nexport type SyncOrAsyncIterable = Iterable | AsyncIterable;\nexport type SyncOrAsyncIteratorMethod = () => (Iterator | AsyncIterator);\n\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint: 'async',\n method?: SyncOrAsyncIteratorMethod\n): AsyncIteratorRecord;\nfunction GetIterator(\n obj: Iterable,\n hint: 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncIteratorRecord;\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint = 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncOrAsyncIteratorRecord {\n assert(hint === 'sync' || hint === 'async');\n if (method === undefined) {\n if (hint === 'async') {\n method = GetMethod(obj as AsyncIterable, SymbolAsyncIterator);\n if (method === undefined) {\n const syncMethod = GetMethod(obj as Iterable, Symbol.iterator);\n const syncIteratorRecord = GetIterator(obj as Iterable, 'sync', syncMethod);\n return CreateAsyncFromSyncIterator(syncIteratorRecord);\n }\n } else {\n method = GetMethod(obj as Iterable, Symbol.iterator);\n }\n }\n if (method === undefined) {\n throw new TypeError('The object is not iterable');\n }\n const iterator = reflectCall(method, obj, []);\n if (!typeIsObject(iterator)) {\n throw new TypeError('The iterator method must return an object');\n }\n const nextMethod = iterator.next;\n return { iterator, nextMethod, done: false } as SyncOrAsyncIteratorRecord;\n}\n\nexport { GetIterator };\n\nexport function IteratorNext(iteratorRecord: AsyncIteratorRecord): Promise> {\n const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []);\n if (!typeIsObject(result)) {\n throw new TypeError('The iterator.next() method must return an object');\n }\n return result;\n}\n\nexport function IteratorComplete(\n iterResult: IteratorResult\n): iterResult is IteratorReturnResult {\n assert(typeIsObject(iterResult));\n return Boolean(iterResult.done);\n}\n\nexport function IteratorValue(iterResult: IteratorYieldResult): T {\n assert(typeIsObject(iterResult));\n return iterResult.value;\n}\n","/// \n\nimport { SymbolAsyncIterator } from '../../../lib/abstract-ops/ecmascript';\n\n// We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it.\nexport const AsyncIteratorPrototype: AsyncIterable = {\n // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( )\n // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator\n [SymbolAsyncIterator](this: AsyncIterator) {\n return this;\n }\n};\nObject.defineProperty(AsyncIteratorPrototype, SymbolAsyncIterator, { enumerable: false });\n","/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadableStreamDefaultReadResult,\n type ReadRequest\n} from './default-reader';\nimport { ReadableStreamReaderGenericCancel, ReadableStreamReaderGenericRelease } from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterableIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ninterface ReadableStreamAsyncIteratorInstance extends ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nObject.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n","import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: NonShared): NonShared {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer) as NonShared;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n","export type TypedArray =\n | Int8Array\n | Uint8Array\n | Uint8ClampedArray\n | Int16Array\n | Uint16Array\n | Int32Array\n | Uint32Array\n | Float32Array\n | Float64Array;\n\nexport type NonShared = T & {\n buffer: ArrayBuffer;\n}\n\nexport interface ArrayBufferViewConstructor {\n new(buffer: ArrayBuffer, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n}\n\nexport interface TypedArrayConstructor extends ArrayBufferViewConstructor {\n readonly BYTES_PER_ELEMENT: number;\n}\n\nexport type DataViewConstructor = ArrayBufferViewConstructor;\n\nfunction isDataViewConstructor(ctor: Function): ctor is DataViewConstructor {\n return ctor === DataView;\n}\n\nexport function isDataView(view: ArrayBufferView): view is DataView {\n return isDataViewConstructor(view.constructor);\n}\n\nexport function arrayBufferViewElementSize(ctor: ArrayBufferViewConstructor): number {\n if (isDataViewConstructor(ctor)) {\n return 1;\n }\n return (ctor as unknown as TypedArrayConstructor).BYTES_PER_ELEMENT;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n IsReadableStreamDefaultReader,\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n type ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n type ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n type ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport type { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\nimport {\n type ArrayBufferViewConstructor,\n arrayBufferViewElementSize,\n type NonShared,\n type TypedArrayConstructor\n} from '../helpers/array-buffer-view';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: NonShared | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: NonShared): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond');\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBuffer;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor = NonShared> =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: TypedArrayConstructor;\n readerType: 'default' | 'none';\n}\n\ninterface BYOBPullIntoDescriptor = NonShared> {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob' | 'none';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: NonShared): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest>): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n minimumFill: 1,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n if (this._pendingPullIntos.length > 0) {\n const firstPullInto = this._pendingPullIntos.peek();\n firstPullInto.readerType = 'none';\n\n this._pendingPullIntos = new SimpleQueue();\n this._pendingPullIntos.push(firstPullInto);\n }\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableByteStreamController.prototype.close, 'close');\nsetFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableByteStreamController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor>(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n assert(pullIntoDescriptor.readerType !== 'none');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as NonShared, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor>(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n let clonedChunk;\n try {\n clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength);\n } catch (cloneE) {\n ReadableByteStreamControllerError(controller, cloneE);\n throw cloneE;\n }\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength);\n}\n\nfunction ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.readerType === 'none');\n if (firstDescriptor.bytesFilled > 0) {\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n firstDescriptor.buffer,\n firstDescriptor.byteOffset,\n firstDescriptor.bytesFilled\n );\n }\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize;\n const maxAlignedBytes = maxBytesFilled - remainderBytes;\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n assert(pullIntoDescriptor.readerType !== 'none');\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nfunction ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller: ReadableByteStreamController) {\n const reader = controller._controlledReadableByteStream._reader;\n assert(IsReadableStreamDefaultReader(reader));\n while (reader._readRequests.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n const readRequest = reader._readRequests.shift();\n ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest);\n }\n}\n\nexport function ReadableByteStreamControllerPullInto>(\n controller: ReadableByteStreamController,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n const elementSize = arrayBufferViewElementSize(ctor);\n\n const { byteOffset, byteLength } = view;\n\n const minimumFill = min * elementSize;\n assert(minimumFill >= elementSize && minimumFill <= byteLength);\n assert(minimumFill % elementSize === 0);\n\n let buffer: ArrayBuffer;\n try {\n buffer = TransferArrayBuffer(view.buffer);\n } catch (e) {\n readIntoRequest._errorSteps(e);\n return;\n }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset,\n byteLength,\n bytesFilled: 0,\n minimumFill,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled % firstDescriptor.elementSize === 0);\n\n if (firstDescriptor.readerType === 'none') {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n return;\n }\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) {\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n pullIntoDescriptor.buffer,\n end - remainderSize,\n remainderSize\n );\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(\n controller: ReadableByteStreamController,\n chunk: NonShared\n) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const { buffer, byteOffset, byteLength } = chunk;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n if (firstPendingPullInto.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto);\n }\n }\n\n if (ReadableStreamHasDefaultReader(stream)) {\n ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller);\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView as NonShared, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerFillReadRequestFromQueue(\n controller: ReadableByteStreamController,\n readRequest: ReadRequest>\n) {\n assert(controller._queueTotalSize > 0);\n\n const entry = controller._queue.shift();\n controller._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n readRequest._chunkSteps(view as NonShared);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view as NonShared);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: NonShared) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: NonShared) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n","import { assertDictionary, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n\nexport function convertByobReadOptions(\n options: ReadableStreamBYOBReaderReadOptions | null | undefined,\n context: string\n): ValidatedReadableStreamBYOBReaderReadOptions {\n assertDictionary(options, context);\n const min = options?.min ?? 1;\n return {\n min: convertUnsignedLongLongWithEnforceRange(\n min,\n `${context} has member 'min' that`\n )\n };\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, type ReadableByteStream, type ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from './reader-options';\nimport { convertByobReadOptions } from '../validators/reader-options';\nimport { isDataView, type NonShared, type TypedArray } from '../helpers/array-buffer-view';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream as ReadableStream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest>(\n stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest\n): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest> {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(\n view: T,\n options?: ReadableStreamBYOBReaderReadOptions\n ): Promise>;\n read>(\n view: T,\n rawOptions: ReadableStreamBYOBReaderReadOptions | null | undefined = {}\n ): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n let options: ValidatedReadableStreamBYOBReaderReadOptions;\n try {\n options = convertByobReadOptions(rawOptions, 'options');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const min = options.min;\n if (min === 0) {\n return promiseRejectedWith(new TypeError('options.min must be greater than 0'));\n }\n if (!isDataView(view)) {\n if (min > (view as unknown as TypedArray).length) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s length'));\n }\n } else if (min > view.byteLength) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s byteLength'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamBYOBReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamBYOBReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead>(\n reader: ReadableStreamBYOBReader,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n min,\n readIntoRequest\n );\n }\n}\n\nexport function ReadableStreamBYOBReaderRelease(reader: ReadableStreamBYOBReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n}\n\nexport function ReadableStreamBYOBReaderErrorReadIntoRequests(reader: ReadableStreamBYOBReader, e: any) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n","/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * If aborted, returns the reason for aborting.\n */\n readonly reason?: any;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(reason?: any): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n type QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { type AbortController, type AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(WritableStream.prototype.abort, 'abort');\nsetFunctionName(WritableStream.prototype.close, 'close');\nsetFunctionName(WritableStream.prototype.getWriter, 'getWriter');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight\n};\n\nexport type {\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort(reason);\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nsetFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort');\nsetFunctionName(WritableStreamDefaultWriter.prototype.close, 'close');\nsetFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock');\nsetFunctionName(WritableStreamDefaultWriter.prototype.write, 'write');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n return null;\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let writeAlgorithm: (chunk: W) => Promise;\n let closeAlgorithm: () => Promise;\n let abortAlgorithm: (reason: any) => Promise;\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n } else {\n writeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n } else {\n closeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n } else {\n abortAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n return null;\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n","/// \n\nfunction getGlobals(): typeof globalThis | undefined {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n } else if (typeof self !== 'undefined') {\n return self;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n","/// \nimport { globals } from '../globals';\nimport { setFunctionName } from '../lib/helpers/miscellaneous';\n\ninterface DOMException extends Error {\n name: string;\n message: string;\n}\n\ntype DOMExceptionConstructor = new (message?: string, name?: string) => DOMException;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n if ((ctor as DOMExceptionConstructor).name !== 'DOMException') {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Support:\n * - Web browsers\n * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87)\n */\nfunction getFromGlobal(): DOMExceptionConstructor | undefined {\n const ctor = globals?.DOMException;\n return isDOMExceptionConstructor(ctor) ? ctor : undefined;\n}\n\n/**\n * Support:\n * - All platforms\n */\nfunction createPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line @typescript-eslint/no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n setFunctionName(ctor, 'DOMException');\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nconst DOMException: DOMExceptionConstructor = getFromGlobal() || createPolyfill();\n\nexport { DOMException };\n","import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n return null;\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => null) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => null) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest(): null {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n return null;\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any): null {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n\n return null;\n }\n });\n}\n","import type { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, type QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n type ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport type { ValidatedUnderlyingSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n // Do nothing.\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultController.prototype.close, 'close');\nsetFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableStreamDefaultController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n","import {\n CreateReadableByteStream,\n CreateReadableStream,\n type DefaultReadableStream,\n IsReadableStream,\n type ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n type ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n type ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(\n stream: ReadableStream,\n cloneForBranch2: boolean\n): [DefaultReadableStream, DefaultReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: DefaultReadableStream;\n let branch2: DefaultReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader> = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader>) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return null;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: NonShared, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader>(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n","import { typeIsObject } from '../helpers/miscellaneous';\nimport type { ReadableStreamDefaultReadResult } from './default-reader';\n\n/**\n * A common interface for a `ReadadableStream` implementation.\n *\n * @public\n */\nexport interface ReadableStreamLike {\n readonly locked: boolean;\n\n getReader(): ReadableStreamDefaultReaderLike;\n}\n\n/**\n * A common interface for a `ReadableStreamDefaultReader` implementation.\n *\n * @public\n */\nexport interface ReadableStreamDefaultReaderLike {\n readonly closed: Promise;\n\n cancel(reason?: any): Promise;\n\n read(): Promise>;\n\n releaseLock(): void;\n}\n\nexport function isReadableStreamLike(stream: unknown): stream is ReadableStreamLike {\n return typeIsObject(stream) && typeof (stream as ReadableStreamLike).getReader !== 'undefined';\n}\n","import { CreateReadableStream, type DefaultReadableStream } from '../readable-stream';\nimport {\n isReadableStreamLike,\n type ReadableStreamDefaultReaderLike,\n type ReadableStreamLike\n} from './readable-stream-like';\nimport { ReadableStreamDefaultControllerClose, ReadableStreamDefaultControllerEnqueue } from './default-controller';\nimport { GetIterator, GetMethod, IteratorComplete, IteratorNext, IteratorValue } from '../abstract-ops/ecmascript';\nimport { promiseRejectedWith, promiseResolvedWith, reflectCall, transformPromiseWith } from '../helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { noop } from '../../utils';\n\nexport function ReadableStreamFrom(\n source: Iterable | AsyncIterable | ReadableStreamLike\n): DefaultReadableStream {\n if (isReadableStreamLike(source)) {\n return ReadableStreamFromDefaultReader(source.getReader());\n }\n return ReadableStreamFromIterable(source);\n}\n\nexport function ReadableStreamFromIterable(asyncIterable: Iterable | AsyncIterable): DefaultReadableStream {\n let stream: DefaultReadableStream;\n const iteratorRecord = GetIterator(asyncIterable, 'async');\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let nextResult;\n try {\n nextResult = IteratorNext(iteratorRecord);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const nextPromise = promiseResolvedWith(nextResult);\n return transformPromiseWith(nextPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object');\n }\n const done = IteratorComplete(iterResult);\n if (done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = IteratorValue(iterResult);\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n const iterator = iteratorRecord.iterator;\n let returnMethod: (typeof iterator)['return'] | undefined;\n try {\n returnMethod = GetMethod(iterator, 'return');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n if (returnMethod === undefined) {\n return promiseResolvedWith(undefined);\n }\n let returnResult: IteratorResult | Promise>;\n try {\n returnResult = reflectCall(returnMethod, iterator, [reason]);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const returnPromise = promiseResolvedWith(returnResult);\n return transformPromiseWith(returnPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object');\n }\n return undefined;\n });\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n\nexport function ReadableStreamFromDefaultReader(\n reader: ReadableStreamDefaultReaderLike\n): DefaultReadableStream {\n let stream: DefaultReadableStream;\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let readPromise;\n try {\n readPromise = reader.read();\n } catch (e) {\n return promiseRejectedWith(e);\n }\n return transformPromiseWith(readPromise, readResult => {\n if (!typeIsObject(readResult)) {\n throw new TypeError('The promise returned by the reader.read() method must fulfill with an object');\n }\n if (readResult.done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = readResult.value;\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n try {\n return promiseResolvedWith(reader.cancel(reason));\n } catch (e) {\n return promiseRejectedWith(e);\n }\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n","import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n","import { assertDictionary } from './basic';\nimport type {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n","import { assertDictionary } from './basic';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n","import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n","import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, type ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderErrorReadRequests,\n type ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReaderErrorReadIntoRequests,\n type ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { ReadableStreamFrom } from './readable-stream/from';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport type {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList, SymbolAsyncIterator } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions\n} from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport type { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport type { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\nimport type { ReadableStreamDefaultReaderLike, ReadableStreamLike } from './readable-stream/readable-stream-like';\nimport type { NonShared } from './helpers/array-buffer-view';\n\nexport type DefaultReadableStream = ReadableStream & {\n _readableStreamController: ReadableStreamDefaultController\n};\n\nexport type ReadableByteStream = ReadableStream> & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream implements AsyncIterable {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n\n [SymbolAsyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator {\n // Stub implementation, overridden below\n return this.values(options);\n }\n\n /**\n * Creates a new ReadableStream wrapping the provided iterable or async iterable.\n *\n * This can be used to adapt various kinds of objects into a readable stream,\n * such as an array, an async generator, or a Node.js readable stream.\n */\n static from(asyncIterable: Iterable | AsyncIterable | ReadableStreamLike): ReadableStream {\n return ReadableStreamFrom(asyncIterable);\n }\n}\n\nObject.defineProperties(ReadableStream, {\n from: { enumerable: true }\n});\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(ReadableStream.from, 'from');\nsetFunctionName(ReadableStream.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStream.prototype.getReader, 'getReader');\nsetFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough');\nsetFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo');\nsetFunctionName(ReadableStream.prototype.tee, 'tee');\nsetFunctionName(ReadableStream.prototype.values, 'values');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nObject.defineProperty(ReadableStream.prototype, SymbolAsyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n});\n\nexport type {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n ReadableStreamBYOBReaderReadOptions,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions,\n ReadableStreamLike,\n ReadableStreamDefaultReaderLike\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1\n): DefaultReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: DefaultReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n","import type { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\nsetFunctionName(byteLengthSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\nsetFunctionName(countSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const cancel = original?.cancel;\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n cancel: cancel === undefined ?\n undefined :\n convertTransformerCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n\nfunction convertTransformerCancelCallback(\n fn: TransformerCancelCallback,\n original: Transformer,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith,\n uponPromise\n} from './helpers/webidl';\nimport { CreateReadableStream, type DefaultReadableStream, ReadableStream } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: DefaultReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport type {\n Transformer,\n TransformerCancelCallback,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSourceCancelAlgorithm(stream, reason);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n TransformStreamUnblockWrite(stream);\n}\n\nfunction TransformStreamUnblockWrite(stream: TransformStream) {\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _finishPromise: Promise | undefined;\n /** @internal */\n _finishPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _finishPromise_reject?: (reason: any) => void;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n /** @internal */\n _cancelAlgorithm: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(TransformStreamDefaultController.prototype.error, 'error');\nsetFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._finishPromise = undefined;\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm: (chunk: I) => Promise;\n let flushAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n } else {\n transformAlgorithm = chunk => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n }\n\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n } else {\n flushAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n if (transformer.cancel !== undefined) {\n cancelAlgorithm = reason => transformer.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally,\n // we don't run the _cancelAlgorithm again.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerError(readable._readableStreamController, reason);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally,\n // we don't also run the _cancelAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(flushPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerClose(readable._readableStreamController);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\nfunction TransformStreamDefaultSourceCancelAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._writable cannot change after construction, so caching it across a call to user code is safe.\n const writable = stream._writable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or\n // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the\n // _flushAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (writable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, writable._storedError);\n } else {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\nexport function defaultControllerFinishPromiseResolve(controller: TransformStreamDefaultController) {\n if (controller._finishPromise_resolve === undefined) {\n return;\n }\n\n controller._finishPromise_resolve();\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nexport function defaultControllerFinishPromiseReject(controller: TransformStreamDefaultController, reason: any) {\n if (controller._finishPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(controller._finishPromise!);\n controller._finishPromise_reject(reason);\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n","import {\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n ReadableByteStreamController,\n ReadableStream,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultController,\n ReadableStreamDefaultReader,\n TransformStream,\n TransformStreamDefaultController,\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter\n} from './ponyfill';\nimport { globals } from './globals';\n\n// Export\nexport * from './ponyfill';\n\nconst exports = {\n ReadableStream,\n ReadableStreamDefaultController,\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader,\n\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter,\n\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n\n TransformStream,\n TransformStreamDefaultController\n};\n\n// Add classes to global scope\nif (typeof globals !== 'undefined') {\n for (const prop in exports) {\n if (Object.prototype.hasOwnProperty.call(exports, prop)) {\n Object.defineProperty(globals, prop, {\n value: exports[prop as (keyof typeof exports)],\n writable: true,\n configurable: true\n });\n }\n }\n}\n"],"names":["queueMicrotask","streamBrandCheckException","defaultControllerBrandCheckException"],"mappings":";;;;;;;SAAgB,IAAI,GAAA;AAClB,IAAA,OAAO,SAAS,CAAC;AACnB;;ACCM,SAAU,YAAY,CAAC,CAAM,EAAA;AACjC,IAAA,OAAO,CAAC,OAAO,CAAC,KAAK,QAAQ,IAAI,CAAC,KAAK,I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AA,UAAU,CAAC,qBAAqB,CAAC,MAAM,CAAC,CAAC;AACzC,IAAA,UAAU,CAAC,sBAAsB,GAAG,SAAS,CAAC;AAC9C,IAAA,UAAU,CAAC,qBAAqB,GAAG,SAAS,CAAC;AAC/C,CAAC;AAED;AAEA,SAAS,yBAAyB,CAAC,IAAY,EAAA;AAC7C,IAAA,OAAO,IAAI,SAAS,CAClB,6BAA6B,IAAI,CAAA,sCAAA,CAAwC,CAAC,CAAC;AAC/E;;ACzoBA,MAAM,OAAO,GAAG;IACd,cAAc;IACd,+BAA+B;IAC/B,4BAA4B;IAC5B,yBAAyB;IACzB,2BAA2B;IAC3B,wBAAwB;IAExB,cAAc;IACd,+BAA+B;IAC/B,2BAA2B;IAE3B,yBAAyB;IACzB,oBAAoB;IAEpB,eAAe;IACf,gCAAgC;CACjC,CAAC;AAEF;AACA,IAAI,OAAO,OAAO,KAAK,WAAW,EAAE;AAClC,IAAA,KAAK,MAAM,IAAI,IAAI,OAAO,EAAE;AAC1B,QAAA,IAAI,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,EAAE;AACvD,YAAA,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,IAAI,EAAE;AACnC,gBAAA,KAAK,EAAE,OAAO,CAAC,IAA8B,CAAC;AAC9C,gBAAA,QAAQ,EAAE,IAAI;AACd,gBAAA,YAAY,EAAE,IAAI;AACnB,aAAA,CAAC,CAAC;SACJ;KACF;AACH;;;;","x_google_ignoreList":[11]} \ No newline at end of file diff --git a/backend/node_modules/web-streams-polyfill/dist/polyfill.js b/backend/node_modules/web-streams-polyfill/dist/polyfill.js new file mode 100644 index 0000000000000000000000000000000000000000..a4ebd70690b9f8b7d3a837c4a98c0bc1ccb5e33d --- /dev/null +++ b/backend/node_modules/web-streams-polyfill/dist/polyfill.js @@ -0,0 +1,5011 @@ +/** + * @license + * web-streams-polyfill v3.3.3 + * Copyright 2024 Mattias Buelens, Diwank Singh Tomer and other contributors. + * This code is released under the MIT license. + * SPDX-License-Identifier: MIT + */ +(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.WebStreamsPolyfill = {})); +})(this, (function (exports) { 'use strict'; + + /// + var SymbolPolyfill = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? + Symbol : + function (description) { return "Symbol(".concat(description, ")"); }; + + /****************************************************************************** + 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 */ + + + function __generator(thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (g && (g = 0, op[0] && (_ = 0)), _) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + } + + function __values(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + } + + function __await(v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); + } + + function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } + } + + function __asyncDelegator(o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } + } + + function __asyncValues(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } + } + + typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; + }; + + function noop() { + return undefined; + } + + function typeIsObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; + } + var rethrowAssertionErrorRejection = noop; + function setFunctionName(fn, name) { + try { + Object.defineProperty(fn, 'name', { + value: name, + configurable: true + }); + } + catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility + } + } + + var originalPromise = Promise; + var originalPromiseThen = Promise.prototype.then; + var originalPromiseReject = Promise.reject.bind(originalPromise); + // https://webidl.spec.whatwg.org/#a-new-promise + function newPromise(executor) { + return new originalPromise(executor); + } + // https://webidl.spec.whatwg.org/#a-promise-resolved-with + function promiseResolvedWith(value) { + return newPromise(function (resolve) { return resolve(value); }); + } + // https://webidl.spec.whatwg.org/#a-promise-rejected-with + function promiseRejectedWith(reason) { + return originalPromiseReject(reason); + } + function PerformPromiseThen(promise, onFulfilled, onRejected) { + // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an + // approximation. + return originalPromiseThen.call(promise, onFulfilled, onRejected); + } + // Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned + // from that handler. To prevent this, return null instead of void from all handlers. + // http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it + function uponPromise(promise, onFulfilled, onRejected) { + PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection); + } + function uponFulfillment(promise, onFulfilled) { + uponPromise(promise, onFulfilled); + } + function uponRejection(promise, onRejected) { + uponPromise(promise, undefined, onRejected); + } + function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { + return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); + } + function setPromiseIsHandledToTrue(promise) { + PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection); + } + var _queueMicrotask = function (callback) { + if (typeof queueMicrotask === 'function') { + _queueMicrotask = queueMicrotask; + } + else { + var resolvedPromise_1 = promiseResolvedWith(undefined); + _queueMicrotask = function (cb) { return PerformPromiseThen(resolvedPromise_1, cb); }; + } + return _queueMicrotask(callback); + }; + function reflectCall(F, V, args) { + if (typeof F !== 'function') { + throw new TypeError('Argument is not a function'); + } + return Function.prototype.apply.call(F, V, args); + } + function promiseCall(F, V, args) { + try { + return promiseResolvedWith(reflectCall(F, V, args)); + } + catch (value) { + return promiseRejectedWith(value); + } + } + + // Original from Chromium + // https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js + var QUEUE_MAX_ARRAY_SIZE = 16384; + /** + * Simple queue structure. + * + * Avoids scalability issues with using a packed array directly by using + * multiple arrays in a linked list and keeping the array size bounded. + */ + var SimpleQueue = /** @class */ (function () { + function SimpleQueue() { + this._cursor = 0; + this._size = 0; + // _front and _back are always defined. + this._front = { + _elements: [], + _next: undefined + }; + this._back = this._front; + // The cursor is used to avoid calling Array.shift(). + // It contains the index of the front element of the array inside the + // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE). + this._cursor = 0; + // When there is only one node, size === elements.length - cursor. + this._size = 0; + } + Object.defineProperty(SimpleQueue.prototype, "length", { + get: function () { + return this._size; + }, + enumerable: false, + configurable: true + }); + // For exception safety, this method is structured in order: + // 1. Read state + // 2. Calculate required state mutations + // 3. Perform state mutations + SimpleQueue.prototype.push = function (element) { + var oldBack = this._back; + var newBack = oldBack; + if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { + newBack = { + _elements: [], + _next: undefined + }; + } + // push() is the mutation most likely to throw an exception, so it + // goes first. + oldBack._elements.push(element); + if (newBack !== oldBack) { + this._back = newBack; + oldBack._next = newBack; + } + ++this._size; + }; + // Like push(), shift() follows the read -> calculate -> mutate pattern for + // exception safety. + SimpleQueue.prototype.shift = function () { // must not be called on an empty queue + var oldFront = this._front; + var newFront = oldFront; + var oldCursor = this._cursor; + var newCursor = oldCursor + 1; + var elements = oldFront._elements; + var element = elements[oldCursor]; + if (newCursor === QUEUE_MAX_ARRAY_SIZE) { + newFront = oldFront._next; + newCursor = 0; + } + // No mutations before this point. + --this._size; + this._cursor = newCursor; + if (oldFront !== newFront) { + this._front = newFront; + } + // Permit shifted element to be garbage collected. + elements[oldCursor] = undefined; + return element; + }; + // The tricky thing about forEach() is that it can be called + // re-entrantly. The queue may be mutated inside the callback. It is easy to + // see that push() within the callback has no negative effects since the end + // of the queue is checked for on every iteration. If shift() is called + // repeatedly within the callback then the next iteration may return an + // element that has been removed. In this case the callback will be called + // with undefined values until we either "catch up" with elements that still + // exist or reach the back of the queue. + SimpleQueue.prototype.forEach = function (callback) { + var i = this._cursor; + var node = this._front; + var elements = node._elements; + while (i !== elements.length || node._next !== undefined) { + if (i === elements.length) { + node = node._next; + elements = node._elements; + i = 0; + if (elements.length === 0) { + break; + } + } + callback(elements[i]); + ++i; + } + }; + // Return the element that would be returned if shift() was called now, + // without modifying the queue. + SimpleQueue.prototype.peek = function () { // must not be called on an empty queue + var front = this._front; + var cursor = this._cursor; + return front._elements[cursor]; + }; + return SimpleQueue; + }()); + + var AbortSteps = SymbolPolyfill('[[AbortSteps]]'); + var ErrorSteps = SymbolPolyfill('[[ErrorSteps]]'); + var CancelSteps = SymbolPolyfill('[[CancelSteps]]'); + var PullSteps = SymbolPolyfill('[[PullSteps]]'); + var ReleaseSteps = SymbolPolyfill('[[ReleaseSteps]]'); + + function ReadableStreamReaderGenericInitialize(reader, stream) { + reader._ownerReadableStream = stream; + stream._reader = reader; + if (stream._state === 'readable') { + defaultReaderClosedPromiseInitialize(reader); + } + else if (stream._state === 'closed') { + defaultReaderClosedPromiseInitializeAsResolved(reader); + } + else { + defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); + } + } + // A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state + // check. + function ReadableStreamReaderGenericCancel(reader, reason) { + var stream = reader._ownerReadableStream; + return ReadableStreamCancel(stream, reason); + } + function ReadableStreamReaderGenericRelease(reader) { + var stream = reader._ownerReadableStream; + if (stream._state === 'readable') { + defaultReaderClosedPromiseReject(reader, new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")); + } + else { + defaultReaderClosedPromiseResetToRejected(reader, new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")); + } + stream._readableStreamController[ReleaseSteps](); + stream._reader = undefined; + reader._ownerReadableStream = undefined; + } + // Helper functions for the readers. + function readerLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released reader'); + } + // Helper functions for the ReadableStreamDefaultReader. + function defaultReaderClosedPromiseInitialize(reader) { + reader._closedPromise = newPromise(function (resolve, reject) { + reader._closedPromise_resolve = resolve; + reader._closedPromise_reject = reject; + }); + } + function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseReject(reader, reason); + } + function defaultReaderClosedPromiseInitializeAsResolved(reader) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseResolve(reader); + } + function defaultReaderClosedPromiseReject(reader, reason) { + if (reader._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(reader._closedPromise); + reader._closedPromise_reject(reason); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; + } + function defaultReaderClosedPromiseResetToRejected(reader, reason) { + defaultReaderClosedPromiseInitializeAsRejected(reader, reason); + } + function defaultReaderClosedPromiseResolve(reader) { + if (reader._closedPromise_resolve === undefined) { + return; + } + reader._closedPromise_resolve(undefined); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; + } + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill + var NumberIsFinite = Number.isFinite || function (x) { + return typeof x === 'number' && isFinite(x); + }; + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill + var MathTrunc = Math.trunc || function (v) { + return v < 0 ? Math.ceil(v) : Math.floor(v); + }; + + // https://heycam.github.io/webidl/#idl-dictionaries + function isDictionary(x) { + return typeof x === 'object' || typeof x === 'function'; + } + function assertDictionary(obj, context) { + if (obj !== undefined && !isDictionary(obj)) { + throw new TypeError("".concat(context, " is not an object.")); + } + } + // https://heycam.github.io/webidl/#idl-callback-functions + function assertFunction(x, context) { + if (typeof x !== 'function') { + throw new TypeError("".concat(context, " is not a function.")); + } + } + // https://heycam.github.io/webidl/#idl-object + function isObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; + } + function assertObject(x, context) { + if (!isObject(x)) { + throw new TypeError("".concat(context, " is not an object.")); + } + } + function assertRequiredArgument(x, position, context) { + if (x === undefined) { + throw new TypeError("Parameter ".concat(position, " is required in '").concat(context, "'.")); + } + } + function assertRequiredField(x, field, context) { + if (x === undefined) { + throw new TypeError("".concat(field, " is required in '").concat(context, "'.")); + } + } + // https://heycam.github.io/webidl/#idl-unrestricted-double + function convertUnrestrictedDouble(value) { + return Number(value); + } + function censorNegativeZero(x) { + return x === 0 ? 0 : x; + } + function integerPart(x) { + return censorNegativeZero(MathTrunc(x)); + } + // https://heycam.github.io/webidl/#idl-unsigned-long-long + function convertUnsignedLongLongWithEnforceRange(value, context) { + var lowerBound = 0; + var upperBound = Number.MAX_SAFE_INTEGER; + var x = Number(value); + x = censorNegativeZero(x); + if (!NumberIsFinite(x)) { + throw new TypeError("".concat(context, " is not a finite number")); + } + x = integerPart(x); + if (x < lowerBound || x > upperBound) { + throw new TypeError("".concat(context, " is outside the accepted range of ").concat(lowerBound, " to ").concat(upperBound, ", inclusive")); + } + if (!NumberIsFinite(x) || x === 0) { + return 0; + } + // TODO Use BigInt if supported? + // let xBigInt = BigInt(integerPart(x)); + // xBigInt = BigInt.asUintN(64, xBigInt); + // return Number(xBigInt); + return x; + } + + function assertReadableStream(x, context) { + if (!IsReadableStream(x)) { + throw new TypeError("".concat(context, " is not a ReadableStream.")); + } + } + + // Abstract operations for the ReadableStream. + function AcquireReadableStreamDefaultReader(stream) { + return new ReadableStreamDefaultReader(stream); + } + // ReadableStream API exposed for controllers. + function ReadableStreamAddReadRequest(stream, readRequest) { + stream._reader._readRequests.push(readRequest); + } + function ReadableStreamFulfillReadRequest(stream, chunk, done) { + var reader = stream._reader; + var readRequest = reader._readRequests.shift(); + if (done) { + readRequest._closeSteps(); + } + else { + readRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadRequests(stream) { + return stream._reader._readRequests.length; + } + function ReadableStreamHasDefaultReader(stream) { + var reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamDefaultReader(reader)) { + return false; + } + return true; + } + /** + * A default reader vended by a {@link ReadableStream}. + * + * @public + */ + var ReadableStreamDefaultReader = /** @class */ (function () { + function ReadableStreamDefaultReader(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readRequests = new SimpleQueue(); + } + Object.defineProperty(ReadableStreamDefaultReader.prototype, "closed", { + /** + * Returns a promise that will be fulfilled when the stream becomes closed, + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + */ + get: function () { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('closed')); + } + return this._closedPromise; + }, + enumerable: false, + configurable: true + }); + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + ReadableStreamDefaultReader.prototype.cancel = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + }; + /** + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + ReadableStreamDefaultReader.prototype.read = function () { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('read')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + var resolvePromise; + var rejectPromise; + var promise = newPromise(function (resolve, reject) { + resolvePromise = resolve; + rejectPromise = reject; + }); + var readRequest = { + _chunkSteps: function (chunk) { return resolvePromise({ value: chunk, done: false }); }, + _closeSteps: function () { return resolvePromise({ value: undefined, done: true }); }, + _errorSteps: function (e) { return rejectPromise(e); } + }; + ReadableStreamDefaultReaderRead(this, readRequest); + return promise; + }; + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + ReadableStreamDefaultReader.prototype.releaseLock = function () { + if (!IsReadableStreamDefaultReader(this)) { + throw defaultReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamDefaultReaderRelease(this); + }; + return ReadableStreamDefaultReader; + }()); + Object.defineProperties(ReadableStreamDefaultReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + setFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel'); + setFunctionName(ReadableStreamDefaultReader.prototype.read, 'read'); + setFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultReader', + configurable: true + }); + } + // Abstract operations for the readers. + function IsReadableStreamDefaultReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) { + return false; + } + return x instanceof ReadableStreamDefaultReader; + } + function ReadableStreamDefaultReaderRead(reader, readRequest) { + var stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'closed') { + readRequest._closeSteps(); + } + else if (stream._state === 'errored') { + readRequest._errorSteps(stream._storedError); + } + else { + stream._readableStreamController[PullSteps](readRequest); + } + } + function ReadableStreamDefaultReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + var e = new TypeError('Reader was released'); + ReadableStreamDefaultReaderErrorReadRequests(reader, e); + } + function ReadableStreamDefaultReaderErrorReadRequests(reader, e) { + var readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(function (readRequest) { + readRequest._errorSteps(e); + }); + } + // Helper functions for the ReadableStreamDefaultReader. + function defaultReaderBrandCheckException(name) { + return new TypeError("ReadableStreamDefaultReader.prototype.".concat(name, " can only be used on a ReadableStreamDefaultReader")); + } + + var _a$1, _b, _c; + function CreateArrayFromList(elements) { + // We use arrays to represent lists, so this is basically a no-op. + // Do a slice though just in case we happen to depend on the unique-ness. + return elements.slice(); + } + function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { + new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); + } + var TransferArrayBuffer = function (O) { + if (typeof O.transfer === 'function') { + TransferArrayBuffer = function (buffer) { return buffer.transfer(); }; + } + else if (typeof structuredClone === 'function') { + TransferArrayBuffer = function (buffer) { return structuredClone(buffer, { transfer: [buffer] }); }; + } + else { + // Not implemented correctly + TransferArrayBuffer = function (buffer) { return buffer; }; + } + return TransferArrayBuffer(O); + }; + var IsDetachedBuffer = function (O) { + if (typeof O.detached === 'boolean') { + IsDetachedBuffer = function (buffer) { return buffer.detached; }; + } + else { + // Not implemented correctly + IsDetachedBuffer = function (buffer) { return buffer.byteLength === 0; }; + } + return IsDetachedBuffer(O); + }; + function ArrayBufferSlice(buffer, begin, end) { + // ArrayBuffer.prototype.slice is not available on IE10 + // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice + if (buffer.slice) { + return buffer.slice(begin, end); + } + var length = end - begin; + var slice = new ArrayBuffer(length); + CopyDataBlockBytes(slice, 0, buffer, begin, length); + return slice; + } + function GetMethod(receiver, prop) { + var func = receiver[prop]; + if (func === undefined || func === null) { + return undefined; + } + if (typeof func !== 'function') { + throw new TypeError("".concat(String(prop), " is not a function")); + } + return func; + } + function CreateAsyncFromSyncIterator(syncIteratorRecord) { + // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%, + // we use yield* inside an async generator function to achieve the same result. + var _a; + // Wrap the sync iterator inside a sync iterable, so we can use it with yield*. + var syncIterable = (_a = {}, + _a[SymbolPolyfill.iterator] = function () { return syncIteratorRecord.iterator; }, + _a); + // Create an async generator function and immediately invoke it. + var asyncIterator = (function () { + return __asyncGenerator(this, arguments, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [5 /*yield**/, __values(__asyncDelegator(__asyncValues(syncIterable)))]; + case 1: return [4 /*yield*/, __await.apply(void 0, [_a.sent()])]; + case 2: return [4 /*yield*/, __await.apply(void 0, [_a.sent()])]; + case 3: return [2 /*return*/, _a.sent()]; + } + }); + }); + }()); + // Return as an async iterator record. + var nextMethod = asyncIterator.next; + return { iterator: asyncIterator, nextMethod: nextMethod, done: false }; + } + // Aligns with core-js/modules/es.symbol.async-iterator.js + var SymbolAsyncIterator = (_c = (_a$1 = SymbolPolyfill.asyncIterator) !== null && _a$1 !== void 0 ? _a$1 : (_b = SymbolPolyfill.for) === null || _b === void 0 ? void 0 : _b.call(SymbolPolyfill, 'Symbol.asyncIterator')) !== null && _c !== void 0 ? _c : '@@asyncIterator'; + function GetIterator(obj, hint, method) { + if (hint === void 0) { hint = 'sync'; } + if (method === undefined) { + if (hint === 'async') { + method = GetMethod(obj, SymbolAsyncIterator); + if (method === undefined) { + var syncMethod = GetMethod(obj, SymbolPolyfill.iterator); + var syncIteratorRecord = GetIterator(obj, 'sync', syncMethod); + return CreateAsyncFromSyncIterator(syncIteratorRecord); + } + } + else { + method = GetMethod(obj, SymbolPolyfill.iterator); + } + } + if (method === undefined) { + throw new TypeError('The object is not iterable'); + } + var iterator = reflectCall(method, obj, []); + if (!typeIsObject(iterator)) { + throw new TypeError('The iterator method must return an object'); + } + var nextMethod = iterator.next; + return { iterator: iterator, nextMethod: nextMethod, done: false }; + } + function IteratorNext(iteratorRecord) { + var result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []); + if (!typeIsObject(result)) { + throw new TypeError('The iterator.next() method must return an object'); + } + return result; + } + function IteratorComplete(iterResult) { + return Boolean(iterResult.done); + } + function IteratorValue(iterResult) { + return iterResult.value; + } + + /// + var _a; + // We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it. + var AsyncIteratorPrototype = (_a = {}, + // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( ) + // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator + _a[SymbolAsyncIterator] = function () { + return this; + }, + _a); + Object.defineProperty(AsyncIteratorPrototype, SymbolAsyncIterator, { enumerable: false }); + + /// + var ReadableStreamAsyncIteratorImpl = /** @class */ (function () { + function ReadableStreamAsyncIteratorImpl(reader, preventCancel) { + this._ongoingPromise = undefined; + this._isFinished = false; + this._reader = reader; + this._preventCancel = preventCancel; + } + ReadableStreamAsyncIteratorImpl.prototype.next = function () { + var _this = this; + var nextSteps = function () { return _this._nextSteps(); }; + this._ongoingPromise = this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : + nextSteps(); + return this._ongoingPromise; + }; + ReadableStreamAsyncIteratorImpl.prototype.return = function (value) { + var _this = this; + var returnSteps = function () { return _this._returnSteps(value); }; + return this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : + returnSteps(); + }; + ReadableStreamAsyncIteratorImpl.prototype._nextSteps = function () { + var _this = this; + if (this._isFinished) { + return Promise.resolve({ value: undefined, done: true }); + } + var reader = this._reader; + var resolvePromise; + var rejectPromise; + var promise = newPromise(function (resolve, reject) { + resolvePromise = resolve; + rejectPromise = reject; + }); + var readRequest = { + _chunkSteps: function (chunk) { + _this._ongoingPromise = undefined; + // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test. + // FIXME Is this a bug in the specification, or in the test? + _queueMicrotask(function () { return resolvePromise({ value: chunk, done: false }); }); + }, + _closeSteps: function () { + _this._ongoingPromise = undefined; + _this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + resolvePromise({ value: undefined, done: true }); + }, + _errorSteps: function (reason) { + _this._ongoingPromise = undefined; + _this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + rejectPromise(reason); + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promise; + }; + ReadableStreamAsyncIteratorImpl.prototype._returnSteps = function (value) { + if (this._isFinished) { + return Promise.resolve({ value: value, done: true }); + } + this._isFinished = true; + var reader = this._reader; + if (!this._preventCancel) { + var result = ReadableStreamReaderGenericCancel(reader, value); + ReadableStreamReaderGenericRelease(reader); + return transformPromiseWith(result, function () { return ({ value: value, done: true }); }); + } + ReadableStreamReaderGenericRelease(reader); + return promiseResolvedWith({ value: value, done: true }); + }; + return ReadableStreamAsyncIteratorImpl; + }()); + var ReadableStreamAsyncIteratorPrototype = { + next: function () { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next')); + } + return this._asyncIteratorImpl.next(); + }, + return: function (value) { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return')); + } + return this._asyncIteratorImpl.return(value); + } + }; + Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); + // Abstract operations for the ReadableStream. + function AcquireReadableStreamAsyncIterator(stream, preventCancel) { + var reader = AcquireReadableStreamDefaultReader(stream); + var impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); + var iterator = Object.create(ReadableStreamAsyncIteratorPrototype); + iterator._asyncIteratorImpl = impl; + return iterator; + } + function IsReadableStreamAsyncIterator(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) { + return false; + } + try { + // noinspection SuspiciousTypeOfGuard + return x._asyncIteratorImpl instanceof + ReadableStreamAsyncIteratorImpl; + } + catch (_a) { + return false; + } + } + // Helper functions for the ReadableStream. + function streamAsyncIteratorBrandCheckException(name) { + return new TypeError("ReadableStreamAsyncIterator.".concat(name, " can only be used on a ReadableSteamAsyncIterator")); + } + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill + var NumberIsNaN = Number.isNaN || function (x) { + // eslint-disable-next-line no-self-compare + return x !== x; + }; + + function IsNonNegativeNumber(v) { + if (typeof v !== 'number') { + return false; + } + if (NumberIsNaN(v)) { + return false; + } + if (v < 0) { + return false; + } + return true; + } + function CloneAsUint8Array(O) { + var buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength); + return new Uint8Array(buffer); + } + + function DequeueValue(container) { + var pair = container._queue.shift(); + container._queueTotalSize -= pair.size; + if (container._queueTotalSize < 0) { + container._queueTotalSize = 0; + } + return pair.value; + } + function EnqueueValueWithSize(container, value, size) { + if (!IsNonNegativeNumber(size) || size === Infinity) { + throw new RangeError('Size must be a finite, non-NaN, non-negative number.'); + } + container._queue.push({ value: value, size: size }); + container._queueTotalSize += size; + } + function PeekQueueValue(container) { + var pair = container._queue.peek(); + return pair.value; + } + function ResetQueue(container) { + container._queue = new SimpleQueue(); + container._queueTotalSize = 0; + } + + function isDataViewConstructor(ctor) { + return ctor === DataView; + } + function isDataView(view) { + return isDataViewConstructor(view.constructor); + } + function arrayBufferViewElementSize(ctor) { + if (isDataViewConstructor(ctor)) { + return 1; + } + return ctor.BYTES_PER_ELEMENT; + } + + /** + * A pull-into request in a {@link ReadableByteStreamController}. + * + * @public + */ + var ReadableStreamBYOBRequest = /** @class */ (function () { + function ReadableStreamBYOBRequest() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(ReadableStreamBYOBRequest.prototype, "view", { + /** + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. + */ + get: function () { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('view'); + } + return this._view; + }, + enumerable: false, + configurable: true + }); + ReadableStreamBYOBRequest.prototype.respond = function (bytesWritten) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respond'); + } + assertRequiredArgument(bytesWritten, 1, 'respond'); + bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter'); + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(this._view.buffer)) { + throw new TypeError("The BYOB request's buffer has been detached and so cannot be used as a response"); + } + ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); + }; + ReadableStreamBYOBRequest.prototype.respondWithNewView = function (view) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respondWithNewView'); + } + assertRequiredArgument(view, 1, 'respondWithNewView'); + if (!ArrayBuffer.isView(view)) { + throw new TypeError('You can only respond with array buffer views'); + } + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(view.buffer)) { + throw new TypeError('The given view\'s buffer has been detached and so cannot be used as a response'); + } + ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); + }; + return ReadableStreamBYOBRequest; + }()); + Object.defineProperties(ReadableStreamBYOBRequest.prototype, { + respond: { enumerable: true }, + respondWithNewView: { enumerable: true }, + view: { enumerable: true } + }); + setFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond'); + setFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBRequest', + configurable: true + }); + } + /** + * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. + * + * @public + */ + var ReadableByteStreamController = /** @class */ (function () { + function ReadableByteStreamController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(ReadableByteStreamController.prototype, "byobRequest", { + /** + * Returns the current BYOB pull request, or `null` if there isn't one. + */ + get: function () { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('byobRequest'); + } + return ReadableByteStreamControllerGetBYOBRequest(this); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ReadableByteStreamController.prototype, "desiredSize", { + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + */ + get: function () { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('desiredSize'); + } + return ReadableByteStreamControllerGetDesiredSize(this); + }, + enumerable: false, + configurable: true + }); + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + ReadableByteStreamController.prototype.close = function () { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('close'); + } + if (this._closeRequested) { + throw new TypeError('The stream has already been closed; do not close it again!'); + } + var state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError("The stream (in ".concat(state, " state) is not in the readable state and cannot be closed")); + } + ReadableByteStreamControllerClose(this); + }; + ReadableByteStreamController.prototype.enqueue = function (chunk) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('enqueue'); + } + assertRequiredArgument(chunk, 1, 'enqueue'); + if (!ArrayBuffer.isView(chunk)) { + throw new TypeError('chunk must be an array buffer view'); + } + if (chunk.byteLength === 0) { + throw new TypeError('chunk must have non-zero byteLength'); + } + if (chunk.buffer.byteLength === 0) { + throw new TypeError("chunk's buffer must have non-zero byteLength"); + } + if (this._closeRequested) { + throw new TypeError('stream is closed or draining'); + } + var state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError("The stream (in ".concat(state, " state) is not in the readable state and cannot be enqueued to")); + } + ReadableByteStreamControllerEnqueue(this, chunk); + }; + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + ReadableByteStreamController.prototype.error = function (e) { + if (e === void 0) { e = undefined; } + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('error'); + } + ReadableByteStreamControllerError(this, e); + }; + /** @internal */ + ReadableByteStreamController.prototype[CancelSteps] = function (reason) { + ReadableByteStreamControllerClearPendingPullIntos(this); + ResetQueue(this); + var result = this._cancelAlgorithm(reason); + ReadableByteStreamControllerClearAlgorithms(this); + return result; + }; + /** @internal */ + ReadableByteStreamController.prototype[PullSteps] = function (readRequest) { + var stream = this._controlledReadableByteStream; + if (this._queueTotalSize > 0) { + ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest); + return; + } + var autoAllocateChunkSize = this._autoAllocateChunkSize; + if (autoAllocateChunkSize !== undefined) { + var buffer = void 0; + try { + buffer = new ArrayBuffer(autoAllocateChunkSize); + } + catch (bufferE) { + readRequest._errorSteps(bufferE); + return; + } + var pullIntoDescriptor = { + buffer: buffer, + bufferByteLength: autoAllocateChunkSize, + byteOffset: 0, + byteLength: autoAllocateChunkSize, + bytesFilled: 0, + minimumFill: 1, + elementSize: 1, + viewConstructor: Uint8Array, + readerType: 'default' + }; + this._pendingPullIntos.push(pullIntoDescriptor); + } + ReadableStreamAddReadRequest(stream, readRequest); + ReadableByteStreamControllerCallPullIfNeeded(this); + }; + /** @internal */ + ReadableByteStreamController.prototype[ReleaseSteps] = function () { + if (this._pendingPullIntos.length > 0) { + var firstPullInto = this._pendingPullIntos.peek(); + firstPullInto.readerType = 'none'; + this._pendingPullIntos = new SimpleQueue(); + this._pendingPullIntos.push(firstPullInto); + } + }; + return ReadableByteStreamController; + }()); + Object.defineProperties(ReadableByteStreamController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + byobRequest: { enumerable: true }, + desiredSize: { enumerable: true } + }); + setFunctionName(ReadableByteStreamController.prototype.close, 'close'); + setFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue'); + setFunctionName(ReadableByteStreamController.prototype.error, 'error'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableByteStreamController', + configurable: true + }); + } + // Abstract operations for the ReadableByteStreamController. + function IsReadableByteStreamController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) { + return false; + } + return x instanceof ReadableByteStreamController; + } + function IsReadableStreamBYOBRequest(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) { + return false; + } + return x instanceof ReadableStreamBYOBRequest; + } + function ReadableByteStreamControllerCallPullIfNeeded(controller) { + var shouldPull = ReadableByteStreamControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + // TODO: Test controller argument + var pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, function () { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + return null; + }, function (e) { + ReadableByteStreamControllerError(controller, e); + return null; + }); + } + function ReadableByteStreamControllerClearPendingPullIntos(controller) { + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + controller._pendingPullIntos = new SimpleQueue(); + } + function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { + var done = false; + if (stream._state === 'closed') { + done = true; + } + var filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'default') { + ReadableStreamFulfillReadRequest(stream, filledView, done); + } + else { + ReadableStreamFulfillReadIntoRequest(stream, filledView, done); + } + } + function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { + var bytesFilled = pullIntoDescriptor.bytesFilled; + var elementSize = pullIntoDescriptor.elementSize; + return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); + } + function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { + controller._queue.push({ buffer: buffer, byteOffset: byteOffset, byteLength: byteLength }); + controller._queueTotalSize += byteLength; + } + function ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, buffer, byteOffset, byteLength) { + var clonedChunk; + try { + clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength); + } + catch (cloneE) { + ReadableByteStreamControllerError(controller, cloneE); + throw cloneE; + } + ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength); + } + function ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstDescriptor) { + if (firstDescriptor.bytesFilled > 0) { + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, firstDescriptor.buffer, firstDescriptor.byteOffset, firstDescriptor.bytesFilled); + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { + var maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); + var maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; + var totalBytesToCopyRemaining = maxBytesToCopy; + var ready = false; + var remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize; + var maxAlignedBytes = maxBytesFilled - remainderBytes; + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) { + totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; + ready = true; + } + var queue = controller._queue; + while (totalBytesToCopyRemaining > 0) { + var headOfQueue = queue.peek(); + var bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); + var destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); + if (headOfQueue.byteLength === bytesToCopy) { + queue.shift(); + } + else { + headOfQueue.byteOffset += bytesToCopy; + headOfQueue.byteLength -= bytesToCopy; + } + controller._queueTotalSize -= bytesToCopy; + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); + totalBytesToCopyRemaining -= bytesToCopy; + } + return ready; + } + function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { + pullIntoDescriptor.bytesFilled += size; + } + function ReadableByteStreamControllerHandleQueueDrain(controller) { + if (controller._queueTotalSize === 0 && controller._closeRequested) { + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(controller._controlledReadableByteStream); + } + else { + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + } + function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { + if (controller._byobRequest === null) { + return; + } + controller._byobRequest._associatedReadableByteStreamController = undefined; + controller._byobRequest._view = null; + controller._byobRequest = null; + } + function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { + while (controller._pendingPullIntos.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + var pullIntoDescriptor = controller._pendingPullIntos.peek(); + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller) { + var reader = controller._controlledReadableByteStream._reader; + while (reader._readRequests.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + var readRequest = reader._readRequests.shift(); + ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest); + } + } + function ReadableByteStreamControllerPullInto(controller, view, min, readIntoRequest) { + var stream = controller._controlledReadableByteStream; + var ctor = view.constructor; + var elementSize = arrayBufferViewElementSize(ctor); + var byteOffset = view.byteOffset, byteLength = view.byteLength; + var minimumFill = min * elementSize; + var buffer; + try { + buffer = TransferArrayBuffer(view.buffer); + } + catch (e) { + readIntoRequest._errorSteps(e); + return; + } + var pullIntoDescriptor = { + buffer: buffer, + bufferByteLength: buffer.byteLength, + byteOffset: byteOffset, + byteLength: byteLength, + bytesFilled: 0, + minimumFill: minimumFill, + elementSize: elementSize, + viewConstructor: ctor, + readerType: 'byob' + }; + if (controller._pendingPullIntos.length > 0) { + controller._pendingPullIntos.push(pullIntoDescriptor); + // No ReadableByteStreamControllerCallPullIfNeeded() call since: + // - No change happens on desiredSize + // - The source has already been notified of that there's at least 1 pending read(view) + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + return; + } + if (stream._state === 'closed') { + var emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); + readIntoRequest._closeSteps(emptyView); + return; + } + if (controller._queueTotalSize > 0) { + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + var filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + ReadableByteStreamControllerHandleQueueDrain(controller); + readIntoRequest._chunkSteps(filledView); + return; + } + if (controller._closeRequested) { + var e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + readIntoRequest._errorSteps(e); + return; + } + } + controller._pendingPullIntos.push(pullIntoDescriptor); + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { + if (firstDescriptor.readerType === 'none') { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + var stream = controller._controlledReadableByteStream; + if (ReadableStreamHasBYOBReader(stream)) { + while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { + var pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + return; + } + if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) { + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + return; + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + var remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; + if (remainderSize > 0) { + var end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor.buffer, end - remainderSize, remainderSize); + } + pullIntoDescriptor.bytesFilled -= remainderSize; + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { + var firstDescriptor = controller._pendingPullIntos.peek(); + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + var state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor); + } + else { + ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerShiftPendingPullInto(controller) { + var descriptor = controller._pendingPullIntos.shift(); + return descriptor; + } + function ReadableByteStreamControllerShouldCallPull(controller) { + var stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return false; + } + if (controller._closeRequested) { + return false; + } + if (!controller._started) { + return false; + } + if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { + return true; + } + var desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; + } + function ReadableByteStreamControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + } + // A client of ReadableByteStreamController may use these functions directly to bypass state check. + function ReadableByteStreamControllerClose(controller) { + var stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + if (controller._queueTotalSize > 0) { + controller._closeRequested = true; + return; + } + if (controller._pendingPullIntos.length > 0) { + var firstPendingPullInto = controller._pendingPullIntos.peek(); + if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) { + var e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + throw e; + } + } + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } + function ReadableByteStreamControllerEnqueue(controller, chunk) { + var stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + var buffer = chunk.buffer, byteOffset = chunk.byteOffset, byteLength = chunk.byteLength; + if (IsDetachedBuffer(buffer)) { + throw new TypeError('chunk\'s buffer is detached and so cannot be enqueued'); + } + var transferredBuffer = TransferArrayBuffer(buffer); + if (controller._pendingPullIntos.length > 0) { + var firstPendingPullInto = controller._pendingPullIntos.peek(); + if (IsDetachedBuffer(firstPendingPullInto.buffer)) { + throw new TypeError('The BYOB request\'s buffer has been detached and so cannot be filled with an enqueued chunk'); + } + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer); + if (firstPendingPullInto.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto); + } + } + if (ReadableStreamHasDefaultReader(stream)) { + ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller); + if (ReadableStreamGetNumReadRequests(stream) === 0) { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + else { + if (controller._pendingPullIntos.length > 0) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + var transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); + ReadableStreamFulfillReadRequest(stream, transferredView, false); + } + } + else if (ReadableStreamHasBYOBReader(stream)) { + // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully. + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + else { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerError(controller, e) { + var stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return; + } + ReadableByteStreamControllerClearPendingPullIntos(controller); + ResetQueue(controller); + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); + } + function ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest) { + var entry = controller._queue.shift(); + controller._queueTotalSize -= entry.byteLength; + ReadableByteStreamControllerHandleQueueDrain(controller); + var view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); + readRequest._chunkSteps(view); + } + function ReadableByteStreamControllerGetBYOBRequest(controller) { + if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) { + var firstDescriptor = controller._pendingPullIntos.peek(); + var view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); + var byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); + SetUpReadableStreamBYOBRequest(byobRequest, controller, view); + controller._byobRequest = byobRequest; + } + return controller._byobRequest; + } + function ReadableByteStreamControllerGetDesiredSize(controller) { + var state = controller._controlledReadableByteStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; + } + function ReadableByteStreamControllerRespond(controller, bytesWritten) { + var firstDescriptor = controller._pendingPullIntos.peek(); + var state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (bytesWritten !== 0) { + throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream'); + } + } + else { + if (bytesWritten === 0) { + throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream'); + } + if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) { + throw new RangeError('bytesWritten out of range'); + } + } + firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); + ReadableByteStreamControllerRespondInternal(controller, bytesWritten); + } + function ReadableByteStreamControllerRespondWithNewView(controller, view) { + var firstDescriptor = controller._pendingPullIntos.peek(); + var state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (view.byteLength !== 0) { + throw new TypeError('The view\'s length must be 0 when calling respondWithNewView() on a closed stream'); + } + } + else { + if (view.byteLength === 0) { + throw new TypeError('The view\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'); + } + } + if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { + throw new RangeError('The region specified by view does not match byobRequest'); + } + if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) { + throw new RangeError('The buffer of view has different capacity than byobRequest'); + } + if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) { + throw new RangeError('The region specified by view is larger than byobRequest'); + } + var viewByteLength = view.byteLength; + firstDescriptor.buffer = TransferArrayBuffer(view.buffer); + ReadableByteStreamControllerRespondInternal(controller, viewByteLength); + } + function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { + controller._controlledReadableByteStream = stream; + controller._pullAgain = false; + controller._pulling = false; + controller._byobRequest = null; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._closeRequested = false; + controller._started = false; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._autoAllocateChunkSize = autoAllocateChunkSize; + controller._pendingPullIntos = new SimpleQueue(); + stream._readableStreamController = controller; + var startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), function () { + controller._started = true; + ReadableByteStreamControllerCallPullIfNeeded(controller); + return null; + }, function (r) { + ReadableByteStreamControllerError(controller, r); + return null; + }); + } + function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { + var controller = Object.create(ReadableByteStreamController.prototype); + var startAlgorithm; + var pullAlgorithm; + var cancelAlgorithm; + if (underlyingByteSource.start !== undefined) { + startAlgorithm = function () { return underlyingByteSource.start(controller); }; + } + else { + startAlgorithm = function () { return undefined; }; + } + if (underlyingByteSource.pull !== undefined) { + pullAlgorithm = function () { return underlyingByteSource.pull(controller); }; + } + else { + pullAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + if (underlyingByteSource.cancel !== undefined) { + cancelAlgorithm = function (reason) { return underlyingByteSource.cancel(reason); }; + } + else { + cancelAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + var autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; + if (autoAllocateChunkSize === 0) { + throw new TypeError('autoAllocateChunkSize must be greater than 0'); + } + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); + } + function SetUpReadableStreamBYOBRequest(request, controller, view) { + request._associatedReadableByteStreamController = controller; + request._view = view; + } + // Helper functions for the ReadableStreamBYOBRequest. + function byobRequestBrandCheckException(name) { + return new TypeError("ReadableStreamBYOBRequest.prototype.".concat(name, " can only be used on a ReadableStreamBYOBRequest")); + } + // Helper functions for the ReadableByteStreamController. + function byteStreamControllerBrandCheckException(name) { + return new TypeError("ReadableByteStreamController.prototype.".concat(name, " can only be used on a ReadableByteStreamController")); + } + + function convertReaderOptions(options, context) { + assertDictionary(options, context); + var mode = options === null || options === void 0 ? void 0 : options.mode; + return { + mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, "".concat(context, " has member 'mode' that")) + }; + } + function convertReadableStreamReaderMode(mode, context) { + mode = "".concat(mode); + if (mode !== 'byob') { + throw new TypeError("".concat(context, " '").concat(mode, "' is not a valid enumeration value for ReadableStreamReaderMode")); + } + return mode; + } + function convertByobReadOptions(options, context) { + var _a; + assertDictionary(options, context); + var min = (_a = options === null || options === void 0 ? void 0 : options.min) !== null && _a !== void 0 ? _a : 1; + return { + min: convertUnsignedLongLongWithEnforceRange(min, "".concat(context, " has member 'min' that")) + }; + } + + // Abstract operations for the ReadableStream. + function AcquireReadableStreamBYOBReader(stream) { + return new ReadableStreamBYOBReader(stream); + } + // ReadableStream API exposed for controllers. + function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { + stream._reader._readIntoRequests.push(readIntoRequest); + } + function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { + var reader = stream._reader; + var readIntoRequest = reader._readIntoRequests.shift(); + if (done) { + readIntoRequest._closeSteps(chunk); + } + else { + readIntoRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadIntoRequests(stream) { + return stream._reader._readIntoRequests.length; + } + function ReadableStreamHasBYOBReader(stream) { + var reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamBYOBReader(reader)) { + return false; + } + return true; + } + /** + * A BYOB reader vended by a {@link ReadableStream}. + * + * @public + */ + var ReadableStreamBYOBReader = /** @class */ (function () { + function ReadableStreamBYOBReader(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + if (!IsReadableByteStreamController(stream._readableStreamController)) { + throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' + + 'source'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readIntoRequests = new SimpleQueue(); + } + Object.defineProperty(ReadableStreamBYOBReader.prototype, "closed", { + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the reader's lock is released before the stream finishes closing. + */ + get: function () { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('closed')); + } + return this._closedPromise; + }, + enumerable: false, + configurable: true + }); + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + ReadableStreamBYOBReader.prototype.cancel = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + }; + ReadableStreamBYOBReader.prototype.read = function (view, rawOptions) { + if (rawOptions === void 0) { rawOptions = {}; } + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('read')); + } + if (!ArrayBuffer.isView(view)) { + return promiseRejectedWith(new TypeError('view must be an array buffer view')); + } + if (view.byteLength === 0) { + return promiseRejectedWith(new TypeError('view must have non-zero byteLength')); + } + if (view.buffer.byteLength === 0) { + return promiseRejectedWith(new TypeError("view's buffer must have non-zero byteLength")); + } + if (IsDetachedBuffer(view.buffer)) { + return promiseRejectedWith(new TypeError('view\'s buffer has been detached')); + } + var options; + try { + options = convertByobReadOptions(rawOptions, 'options'); + } + catch (e) { + return promiseRejectedWith(e); + } + var min = options.min; + if (min === 0) { + return promiseRejectedWith(new TypeError('options.min must be greater than 0')); + } + if (!isDataView(view)) { + if (min > view.length) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s length')); + } + } + else if (min > view.byteLength) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s byteLength')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + var resolvePromise; + var rejectPromise; + var promise = newPromise(function (resolve, reject) { + resolvePromise = resolve; + rejectPromise = reject; + }); + var readIntoRequest = { + _chunkSteps: function (chunk) { return resolvePromise({ value: chunk, done: false }); }, + _closeSteps: function (chunk) { return resolvePromise({ value: chunk, done: true }); }, + _errorSteps: function (e) { return rejectPromise(e); } + }; + ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest); + return promise; + }; + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + ReadableStreamBYOBReader.prototype.releaseLock = function () { + if (!IsReadableStreamBYOBReader(this)) { + throw byobReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamBYOBReaderRelease(this); + }; + return ReadableStreamBYOBReader; + }()); + Object.defineProperties(ReadableStreamBYOBReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + setFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel'); + setFunctionName(ReadableStreamBYOBReader.prototype.read, 'read'); + setFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBReader', + configurable: true + }); + } + // Abstract operations for the readers. + function IsReadableStreamBYOBReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) { + return false; + } + return x instanceof ReadableStreamBYOBReader; + } + function ReadableStreamBYOBReaderRead(reader, view, min, readIntoRequest) { + var stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'errored') { + readIntoRequest._errorSteps(stream._storedError); + } + else { + ReadableByteStreamControllerPullInto(stream._readableStreamController, view, min, readIntoRequest); + } + } + function ReadableStreamBYOBReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + var e = new TypeError('Reader was released'); + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); + } + function ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e) { + var readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(function (readIntoRequest) { + readIntoRequest._errorSteps(e); + }); + } + // Helper functions for the ReadableStreamBYOBReader. + function byobReaderBrandCheckException(name) { + return new TypeError("ReadableStreamBYOBReader.prototype.".concat(name, " can only be used on a ReadableStreamBYOBReader")); + } + + function ExtractHighWaterMark(strategy, defaultHWM) { + var highWaterMark = strategy.highWaterMark; + if (highWaterMark === undefined) { + return defaultHWM; + } + if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { + throw new RangeError('Invalid highWaterMark'); + } + return highWaterMark; + } + function ExtractSizeAlgorithm(strategy) { + var size = strategy.size; + if (!size) { + return function () { return 1; }; + } + return size; + } + + function convertQueuingStrategy(init, context) { + assertDictionary(init, context); + var highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + var size = init === null || init === void 0 ? void 0 : init.size; + return { + highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark), + size: size === undefined ? undefined : convertQueuingStrategySize(size, "".concat(context, " has member 'size' that")) + }; + } + function convertQueuingStrategySize(fn, context) { + assertFunction(fn, context); + return function (chunk) { return convertUnrestrictedDouble(fn(chunk)); }; + } + + function convertUnderlyingSink(original, context) { + assertDictionary(original, context); + var abort = original === null || original === void 0 ? void 0 : original.abort; + var close = original === null || original === void 0 ? void 0 : original.close; + var start = original === null || original === void 0 ? void 0 : original.start; + var type = original === null || original === void 0 ? void 0 : original.type; + var write = original === null || original === void 0 ? void 0 : original.write; + return { + abort: abort === undefined ? + undefined : + convertUnderlyingSinkAbortCallback(abort, original, "".concat(context, " has member 'abort' that")), + close: close === undefined ? + undefined : + convertUnderlyingSinkCloseCallback(close, original, "".concat(context, " has member 'close' that")), + start: start === undefined ? + undefined : + convertUnderlyingSinkStartCallback(start, original, "".concat(context, " has member 'start' that")), + write: write === undefined ? + undefined : + convertUnderlyingSinkWriteCallback(write, original, "".concat(context, " has member 'write' that")), + type: type + }; + } + function convertUnderlyingSinkAbortCallback(fn, original, context) { + assertFunction(fn, context); + return function (reason) { return promiseCall(fn, original, [reason]); }; + } + function convertUnderlyingSinkCloseCallback(fn, original, context) { + assertFunction(fn, context); + return function () { return promiseCall(fn, original, []); }; + } + function convertUnderlyingSinkStartCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return reflectCall(fn, original, [controller]); }; + } + function convertUnderlyingSinkWriteCallback(fn, original, context) { + assertFunction(fn, context); + return function (chunk, controller) { return promiseCall(fn, original, [chunk, controller]); }; + } + + function assertWritableStream(x, context) { + if (!IsWritableStream(x)) { + throw new TypeError("".concat(context, " is not a WritableStream.")); + } + } + + function isAbortSignal(value) { + if (typeof value !== 'object' || value === null) { + return false; + } + try { + return typeof value.aborted === 'boolean'; + } + catch (_a) { + // AbortSignal.prototype.aborted throws if its brand check fails + return false; + } + } + var supportsAbortController = typeof AbortController === 'function'; + /** + * Construct a new AbortController, if supported by the platform. + * + * @internal + */ + function createAbortController() { + if (supportsAbortController) { + return new AbortController(); + } + return undefined; + } + + /** + * A writable stream represents a destination for data, into which you can write. + * + * @public + */ + var WritableStream = /** @class */ (function () { + function WritableStream(rawUnderlyingSink, rawStrategy) { + if (rawUnderlyingSink === void 0) { rawUnderlyingSink = {}; } + if (rawStrategy === void 0) { rawStrategy = {}; } + if (rawUnderlyingSink === undefined) { + rawUnderlyingSink = null; + } + else { + assertObject(rawUnderlyingSink, 'First parameter'); + } + var strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + var underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter'); + InitializeWritableStream(this); + var type = underlyingSink.type; + if (type !== undefined) { + throw new RangeError('Invalid type is specified'); + } + var sizeAlgorithm = ExtractSizeAlgorithm(strategy); + var highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); + } + Object.defineProperty(WritableStream.prototype, "locked", { + /** + * Returns whether or not the writable stream is locked to a writer. + */ + get: function () { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('locked'); + } + return IsWritableStreamLocked(this); + }, + enumerable: false, + configurable: true + }); + /** + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort + * mechanism of the underlying sink. + * + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel + * the stream) if the stream is currently locked. + */ + WritableStream.prototype.abort = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('abort')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer')); + } + return WritableStreamAbort(this, reason); + }; + /** + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its + * close behavior. During this time any further attempts to write will fail (without erroring the stream). + * + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + */ + WritableStream.prototype.close = function () { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('close')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer')); + } + if (WritableStreamCloseQueuedOrInFlight(this)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamClose(this); + }; + /** + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream + * is locked, no other writer can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at + * the same time, which would cause the resulting written data to be unpredictable and probably useless. + */ + WritableStream.prototype.getWriter = function () { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('getWriter'); + } + return AcquireWritableStreamDefaultWriter(this); + }; + return WritableStream; + }()); + Object.defineProperties(WritableStream.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + getWriter: { enumerable: true }, + locked: { enumerable: true } + }); + setFunctionName(WritableStream.prototype.abort, 'abort'); + setFunctionName(WritableStream.prototype.close, 'close'); + setFunctionName(WritableStream.prototype.getWriter, 'getWriter'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStream', + configurable: true + }); + } + // Abstract operations for the WritableStream. + function AcquireWritableStreamDefaultWriter(stream) { + return new WritableStreamDefaultWriter(stream); + } + // Throws if and only if startAlgorithm throws. + function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + if (highWaterMark === void 0) { highWaterMark = 1; } + if (sizeAlgorithm === void 0) { sizeAlgorithm = function () { return 1; }; } + var stream = Object.create(WritableStream.prototype); + InitializeWritableStream(stream); + var controller = Object.create(WritableStreamDefaultController.prototype); + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + return stream; + } + function InitializeWritableStream(stream) { + stream._state = 'writable'; + // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is + // 'erroring' or 'errored'. May be set to an undefined value. + stream._storedError = undefined; + stream._writer = undefined; + // Initialize to undefined first because the constructor of the controller checks this + // variable to validate the caller. + stream._writableStreamController = undefined; + // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data + // producer without waiting for the queued writes to finish. + stream._writeRequests = new SimpleQueue(); + // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents + // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here. + stream._inFlightWriteRequest = undefined; + // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer + // has been detached. + stream._closeRequest = undefined; + // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it + // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here. + stream._inFlightCloseRequest = undefined; + // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached. + stream._pendingAbortRequest = undefined; + // The backpressure signal set by the controller. + stream._backpressure = false; + } + function IsWritableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) { + return false; + } + return x instanceof WritableStream; + } + function IsWritableStreamLocked(stream) { + if (stream._writer === undefined) { + return false; + } + return true; + } + function WritableStreamAbort(stream, reason) { + var _a; + if (stream._state === 'closed' || stream._state === 'errored') { + return promiseResolvedWith(undefined); + } + stream._writableStreamController._abortReason = reason; + (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort(reason); + // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring', + // but it doesn't know that signaling abort runs author code that might have changed the state. + // Widen the type again by casting to WritableStreamState. + var state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseResolvedWith(undefined); + } + if (stream._pendingAbortRequest !== undefined) { + return stream._pendingAbortRequest._promise; + } + var wasAlreadyErroring = false; + if (state === 'erroring') { + wasAlreadyErroring = true; + // reason will not be used, so don't keep a reference to it. + reason = undefined; + } + var promise = newPromise(function (resolve, reject) { + stream._pendingAbortRequest = { + _promise: undefined, + _resolve: resolve, + _reject: reject, + _reason: reason, + _wasAlreadyErroring: wasAlreadyErroring + }; + }); + stream._pendingAbortRequest._promise = promise; + if (!wasAlreadyErroring) { + WritableStreamStartErroring(stream, reason); + } + return promise; + } + function WritableStreamClose(stream) { + var state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseRejectedWith(new TypeError("The stream (in ".concat(state, " state) is not in the writable state and cannot be closed"))); + } + var promise = newPromise(function (resolve, reject) { + var closeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._closeRequest = closeRequest; + }); + var writer = stream._writer; + if (writer !== undefined && stream._backpressure && state === 'writable') { + defaultWriterReadyPromiseResolve(writer); + } + WritableStreamDefaultControllerClose(stream._writableStreamController); + return promise; + } + // WritableStream API exposed for controllers. + function WritableStreamAddWriteRequest(stream) { + var promise = newPromise(function (resolve, reject) { + var writeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._writeRequests.push(writeRequest); + }); + return promise; + } + function WritableStreamDealWithRejection(stream, error) { + var state = stream._state; + if (state === 'writable') { + WritableStreamStartErroring(stream, error); + return; + } + WritableStreamFinishErroring(stream); + } + function WritableStreamStartErroring(stream, reason) { + var controller = stream._writableStreamController; + stream._state = 'erroring'; + stream._storedError = reason; + var writer = stream._writer; + if (writer !== undefined) { + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); + } + if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { + WritableStreamFinishErroring(stream); + } + } + function WritableStreamFinishErroring(stream) { + stream._state = 'errored'; + stream._writableStreamController[ErrorSteps](); + var storedError = stream._storedError; + stream._writeRequests.forEach(function (writeRequest) { + writeRequest._reject(storedError); + }); + stream._writeRequests = new SimpleQueue(); + if (stream._pendingAbortRequest === undefined) { + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + var abortRequest = stream._pendingAbortRequest; + stream._pendingAbortRequest = undefined; + if (abortRequest._wasAlreadyErroring) { + abortRequest._reject(storedError); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + var promise = stream._writableStreamController[AbortSteps](abortRequest._reason); + uponPromise(promise, function () { + abortRequest._resolve(); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }, function (reason) { + abortRequest._reject(reason); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }); + } + function WritableStreamFinishInFlightWrite(stream) { + stream._inFlightWriteRequest._resolve(undefined); + stream._inFlightWriteRequest = undefined; + } + function WritableStreamFinishInFlightWriteWithError(stream, error) { + stream._inFlightWriteRequest._reject(error); + stream._inFlightWriteRequest = undefined; + WritableStreamDealWithRejection(stream, error); + } + function WritableStreamFinishInFlightClose(stream) { + stream._inFlightCloseRequest._resolve(undefined); + stream._inFlightCloseRequest = undefined; + var state = stream._state; + if (state === 'erroring') { + // The error was too late to do anything, so it is ignored. + stream._storedError = undefined; + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._resolve(); + stream._pendingAbortRequest = undefined; + } + } + stream._state = 'closed'; + var writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseResolve(writer); + } + } + function WritableStreamFinishInFlightCloseWithError(stream, error) { + stream._inFlightCloseRequest._reject(error); + stream._inFlightCloseRequest = undefined; + // Never execute sink abort() after sink close(). + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._reject(error); + stream._pendingAbortRequest = undefined; + } + WritableStreamDealWithRejection(stream, error); + } + // TODO(ricea): Fix alphabetical order. + function WritableStreamCloseQueuedOrInFlight(stream) { + if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; + } + function WritableStreamHasOperationMarkedInFlight(stream) { + if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; + } + function WritableStreamMarkCloseRequestInFlight(stream) { + stream._inFlightCloseRequest = stream._closeRequest; + stream._closeRequest = undefined; + } + function WritableStreamMarkFirstWriteRequestInFlight(stream) { + stream._inFlightWriteRequest = stream._writeRequests.shift(); + } + function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { + if (stream._closeRequest !== undefined) { + stream._closeRequest._reject(stream._storedError); + stream._closeRequest = undefined; + } + var writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseReject(writer, stream._storedError); + } + } + function WritableStreamUpdateBackpressure(stream, backpressure) { + var writer = stream._writer; + if (writer !== undefined && backpressure !== stream._backpressure) { + if (backpressure) { + defaultWriterReadyPromiseReset(writer); + } + else { + defaultWriterReadyPromiseResolve(writer); + } + } + stream._backpressure = backpressure; + } + /** + * A default writer vended by a {@link WritableStream}. + * + * @public + */ + var WritableStreamDefaultWriter = /** @class */ (function () { + function WritableStreamDefaultWriter(stream) { + assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter'); + assertWritableStream(stream, 'First parameter'); + if (IsWritableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive writing by another writer'); + } + this._ownerWritableStream = stream; + stream._writer = this; + var state = stream._state; + if (state === 'writable') { + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { + defaultWriterReadyPromiseInitialize(this); + } + else { + defaultWriterReadyPromiseInitializeAsResolved(this); + } + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'erroring') { + defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'closed') { + defaultWriterReadyPromiseInitializeAsResolved(this); + defaultWriterClosedPromiseInitializeAsResolved(this); + } + else { + var storedError = stream._storedError; + defaultWriterReadyPromiseInitializeAsRejected(this, storedError); + defaultWriterClosedPromiseInitializeAsRejected(this, storedError); + } + } + Object.defineProperty(WritableStreamDefaultWriter.prototype, "closed", { + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the writer’s lock is released before the stream finishes closing. + */ + get: function () { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('closed')); + } + return this._closedPromise; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(WritableStreamDefaultWriter.prototype, "desiredSize", { + /** + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. + * A producer can use this information to determine the right amount of data to write. + * + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when + * the writer’s lock is released. + */ + get: function () { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('desiredSize'); + } + if (this._ownerWritableStream === undefined) { + throw defaultWriterLockException('desiredSize'); + } + return WritableStreamDefaultWriterGetDesiredSize(this); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(WritableStreamDefaultWriter.prototype, "ready", { + /** + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips + * back to zero or below, the getter will return a new promise that stays pending until the next transition. + * + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become + * rejected. + */ + get: function () { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('ready')); + } + return this._readyPromise; + }, + enumerable: false, + configurable: true + }); + /** + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + */ + WritableStreamDefaultWriter.prototype.abort = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('abort')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('abort')); + } + return WritableStreamDefaultWriterAbort(this, reason); + }; + /** + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + */ + WritableStreamDefaultWriter.prototype.close = function () { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('close')); + } + var stream = this._ownerWritableStream; + if (stream === undefined) { + return promiseRejectedWith(defaultWriterLockException('close')); + } + if (WritableStreamCloseQueuedOrInFlight(stream)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamDefaultWriterClose(this); + }; + /** + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from + * now on; otherwise, the writer will appear closed. + * + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents + * other producers from writing in an interleaved manner. + */ + WritableStreamDefaultWriter.prototype.releaseLock = function () { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('releaseLock'); + } + var stream = this._ownerWritableStream; + if (stream === undefined) { + return; + } + WritableStreamDefaultWriterRelease(this); + }; + WritableStreamDefaultWriter.prototype.write = function (chunk) { + if (chunk === void 0) { chunk = undefined; } + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('write')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + return WritableStreamDefaultWriterWrite(this, chunk); + }; + return WritableStreamDefaultWriter; + }()); + Object.defineProperties(WritableStreamDefaultWriter.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + releaseLock: { enumerable: true }, + write: { enumerable: true }, + closed: { enumerable: true }, + desiredSize: { enumerable: true }, + ready: { enumerable: true } + }); + setFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort'); + setFunctionName(WritableStreamDefaultWriter.prototype.close, 'close'); + setFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock'); + setFunctionName(WritableStreamDefaultWriter.prototype.write, 'write'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultWriter', + configurable: true + }); + } + // Abstract operations for the WritableStreamDefaultWriter. + function IsWritableStreamDefaultWriter(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultWriter; + } + // A client of WritableStreamDefaultWriter may use these functions directly to bypass state check. + function WritableStreamDefaultWriterAbort(writer, reason) { + var stream = writer._ownerWritableStream; + return WritableStreamAbort(stream, reason); + } + function WritableStreamDefaultWriterClose(writer) { + var stream = writer._ownerWritableStream; + return WritableStreamClose(stream); + } + function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { + var stream = writer._ownerWritableStream; + var state = stream._state; + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseResolvedWith(undefined); + } + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + return WritableStreamDefaultWriterClose(writer); + } + function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { + if (writer._closedPromiseState === 'pending') { + defaultWriterClosedPromiseReject(writer, error); + } + else { + defaultWriterClosedPromiseResetToRejected(writer, error); + } + } + function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { + if (writer._readyPromiseState === 'pending') { + defaultWriterReadyPromiseReject(writer, error); + } + else { + defaultWriterReadyPromiseResetToRejected(writer, error); + } + } + function WritableStreamDefaultWriterGetDesiredSize(writer) { + var stream = writer._ownerWritableStream; + var state = stream._state; + if (state === 'errored' || state === 'erroring') { + return null; + } + if (state === 'closed') { + return 0; + } + return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); + } + function WritableStreamDefaultWriterRelease(writer) { + var stream = writer._ownerWritableStream; + var releasedError = new TypeError("Writer was released and can no longer be used to monitor the stream's closedness"); + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); + // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not + // rejected until afterwards. This means that simply testing state will not work. + WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); + stream._writer = undefined; + writer._ownerWritableStream = undefined; + } + function WritableStreamDefaultWriterWrite(writer, chunk) { + var stream = writer._ownerWritableStream; + var controller = stream._writableStreamController; + var chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); + if (stream !== writer._ownerWritableStream) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + var state = stream._state; + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to')); + } + if (state === 'erroring') { + return promiseRejectedWith(stream._storedError); + } + var promise = WritableStreamAddWriteRequest(stream); + WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); + return promise; + } + var closeSentinel = {}; + /** + * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. + * + * @public + */ + var WritableStreamDefaultController = /** @class */ (function () { + function WritableStreamDefaultController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(WritableStreamDefaultController.prototype, "abortReason", { + /** + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. + * + * @deprecated + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. + */ + get: function () { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('abortReason'); + } + return this._abortReason; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(WritableStreamDefaultController.prototype, "signal", { + /** + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. + */ + get: function () { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('signal'); + } + if (this._abortController === undefined) { + // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`. + // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill, + // so instead we only implement support for `signal` if we find a global `AbortController` constructor. + throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported'); + } + return this._abortController.signal; + }, + enumerable: false, + configurable: true + }); + /** + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. + * + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the + * normal lifecycle of interactions with the underlying sink. + */ + WritableStreamDefaultController.prototype.error = function (e) { + if (e === void 0) { e = undefined; } + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('error'); + } + var state = this._controlledWritableStream._state; + if (state !== 'writable') { + // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so + // just treat it as a no-op. + return; + } + WritableStreamDefaultControllerError(this, e); + }; + /** @internal */ + WritableStreamDefaultController.prototype[AbortSteps] = function (reason) { + var result = this._abortAlgorithm(reason); + WritableStreamDefaultControllerClearAlgorithms(this); + return result; + }; + /** @internal */ + WritableStreamDefaultController.prototype[ErrorSteps] = function () { + ResetQueue(this); + }; + return WritableStreamDefaultController; + }()); + Object.defineProperties(WritableStreamDefaultController.prototype, { + abortReason: { enumerable: true }, + signal: { enumerable: true }, + error: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultController', + configurable: true + }); + } + // Abstract operations implementing interface required by the WritableStream. + function IsWritableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultController; + } + function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledWritableStream = stream; + stream._writableStreamController = controller; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._abortReason = undefined; + controller._abortController = createAbortController(); + controller._started = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._writeAlgorithm = writeAlgorithm; + controller._closeAlgorithm = closeAlgorithm; + controller._abortAlgorithm = abortAlgorithm; + var backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + var startResult = startAlgorithm(); + var startPromise = promiseResolvedWith(startResult); + uponPromise(startPromise, function () { + controller._started = true; + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, function (r) { + controller._started = true; + WritableStreamDealWithRejection(stream, r); + return null; + }); + } + function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { + var controller = Object.create(WritableStreamDefaultController.prototype); + var startAlgorithm; + var writeAlgorithm; + var closeAlgorithm; + var abortAlgorithm; + if (underlyingSink.start !== undefined) { + startAlgorithm = function () { return underlyingSink.start(controller); }; + } + else { + startAlgorithm = function () { return undefined; }; + } + if (underlyingSink.write !== undefined) { + writeAlgorithm = function (chunk) { return underlyingSink.write(chunk, controller); }; + } + else { + writeAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + if (underlyingSink.close !== undefined) { + closeAlgorithm = function () { return underlyingSink.close(); }; + } + else { + closeAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + if (underlyingSink.abort !== undefined) { + abortAlgorithm = function (reason) { return underlyingSink.abort(reason); }; + } + else { + abortAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + } + // ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls. + function WritableStreamDefaultControllerClearAlgorithms(controller) { + controller._writeAlgorithm = undefined; + controller._closeAlgorithm = undefined; + controller._abortAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; + } + function WritableStreamDefaultControllerClose(controller) { + EnqueueValueWithSize(controller, closeSentinel, 0); + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + } + function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { + try { + return controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); + return 1; + } + } + function WritableStreamDefaultControllerGetDesiredSize(controller) { + return controller._strategyHWM - controller._queueTotalSize; + } + function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); + return; + } + var stream = controller._controlledWritableStream; + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') { + var backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + } + // Abstract operations for the WritableStreamDefaultController. + function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { + var stream = controller._controlledWritableStream; + if (!controller._started) { + return; + } + if (stream._inFlightWriteRequest !== undefined) { + return; + } + var state = stream._state; + if (state === 'erroring') { + WritableStreamFinishErroring(stream); + return; + } + if (controller._queue.length === 0) { + return; + } + var value = PeekQueueValue(controller); + if (value === closeSentinel) { + WritableStreamDefaultControllerProcessClose(controller); + } + else { + WritableStreamDefaultControllerProcessWrite(controller, value); + } + } + function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { + if (controller._controlledWritableStream._state === 'writable') { + WritableStreamDefaultControllerError(controller, error); + } + } + function WritableStreamDefaultControllerProcessClose(controller) { + var stream = controller._controlledWritableStream; + WritableStreamMarkCloseRequestInFlight(stream); + DequeueValue(controller); + var sinkClosePromise = controller._closeAlgorithm(); + WritableStreamDefaultControllerClearAlgorithms(controller); + uponPromise(sinkClosePromise, function () { + WritableStreamFinishInFlightClose(stream); + return null; + }, function (reason) { + WritableStreamFinishInFlightCloseWithError(stream, reason); + return null; + }); + } + function WritableStreamDefaultControllerProcessWrite(controller, chunk) { + var stream = controller._controlledWritableStream; + WritableStreamMarkFirstWriteRequestInFlight(stream); + var sinkWritePromise = controller._writeAlgorithm(chunk); + uponPromise(sinkWritePromise, function () { + WritableStreamFinishInFlightWrite(stream); + var state = stream._state; + DequeueValue(controller); + if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') { + var backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, function (reason) { + if (stream._state === 'writable') { + WritableStreamDefaultControllerClearAlgorithms(controller); + } + WritableStreamFinishInFlightWriteWithError(stream, reason); + return null; + }); + } + function WritableStreamDefaultControllerGetBackpressure(controller) { + var desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); + return desiredSize <= 0; + } + // A client of WritableStreamDefaultController may use these functions directly to bypass state check. + function WritableStreamDefaultControllerError(controller, error) { + var stream = controller._controlledWritableStream; + WritableStreamDefaultControllerClearAlgorithms(controller); + WritableStreamStartErroring(stream, error); + } + // Helper functions for the WritableStream. + function streamBrandCheckException$2(name) { + return new TypeError("WritableStream.prototype.".concat(name, " can only be used on a WritableStream")); + } + // Helper functions for the WritableStreamDefaultController. + function defaultControllerBrandCheckException$2(name) { + return new TypeError("WritableStreamDefaultController.prototype.".concat(name, " can only be used on a WritableStreamDefaultController")); + } + // Helper functions for the WritableStreamDefaultWriter. + function defaultWriterBrandCheckException(name) { + return new TypeError("WritableStreamDefaultWriter.prototype.".concat(name, " can only be used on a WritableStreamDefaultWriter")); + } + function defaultWriterLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released writer'); + } + function defaultWriterClosedPromiseInitialize(writer) { + writer._closedPromise = newPromise(function (resolve, reject) { + writer._closedPromise_resolve = resolve; + writer._closedPromise_reject = reject; + writer._closedPromiseState = 'pending'; + }); + } + function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseReject(writer, reason); + } + function defaultWriterClosedPromiseInitializeAsResolved(writer) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseResolve(writer); + } + function defaultWriterClosedPromiseReject(writer, reason) { + if (writer._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._closedPromise); + writer._closedPromise_reject(reason); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'rejected'; + } + function defaultWriterClosedPromiseResetToRejected(writer, reason) { + defaultWriterClosedPromiseInitializeAsRejected(writer, reason); + } + function defaultWriterClosedPromiseResolve(writer) { + if (writer._closedPromise_resolve === undefined) { + return; + } + writer._closedPromise_resolve(undefined); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'resolved'; + } + function defaultWriterReadyPromiseInitialize(writer) { + writer._readyPromise = newPromise(function (resolve, reject) { + writer._readyPromise_resolve = resolve; + writer._readyPromise_reject = reject; + }); + writer._readyPromiseState = 'pending'; + } + function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseReject(writer, reason); + } + function defaultWriterReadyPromiseInitializeAsResolved(writer) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseResolve(writer); + } + function defaultWriterReadyPromiseReject(writer, reason) { + if (writer._readyPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._readyPromise); + writer._readyPromise_reject(reason); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'rejected'; + } + function defaultWriterReadyPromiseReset(writer) { + defaultWriterReadyPromiseInitialize(writer); + } + function defaultWriterReadyPromiseResetToRejected(writer, reason) { + defaultWriterReadyPromiseInitializeAsRejected(writer, reason); + } + function defaultWriterReadyPromiseResolve(writer) { + if (writer._readyPromise_resolve === undefined) { + return; + } + writer._readyPromise_resolve(undefined); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'fulfilled'; + } + + /// + function getGlobals() { + if (typeof globalThis !== 'undefined') { + return globalThis; + } + else if (typeof self !== 'undefined') { + return self; + } + else if (typeof global !== 'undefined') { + return global; + } + return undefined; + } + var globals = getGlobals(); + + /// + function isDOMExceptionConstructor(ctor) { + if (!(typeof ctor === 'function' || typeof ctor === 'object')) { + return false; + } + if (ctor.name !== 'DOMException') { + return false; + } + try { + new ctor(); + return true; + } + catch (_a) { + return false; + } + } + /** + * Support: + * - Web browsers + * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87) + */ + function getFromGlobal() { + var ctor = globals === null || globals === void 0 ? void 0 : globals.DOMException; + return isDOMExceptionConstructor(ctor) ? ctor : undefined; + } + /** + * Support: + * - All platforms + */ + function createPolyfill() { + // eslint-disable-next-line @typescript-eslint/no-shadow + var ctor = function DOMException(message, name) { + this.message = message || ''; + this.name = name || 'Error'; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + }; + setFunctionName(ctor, 'DOMException'); + ctor.prototype = Object.create(Error.prototype); + Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true }); + return ctor; + } + // eslint-disable-next-line @typescript-eslint/no-redeclare + var DOMException = getFromGlobal() || createPolyfill(); + + function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { + var reader = AcquireReadableStreamDefaultReader(source); + var writer = AcquireWritableStreamDefaultWriter(dest); + source._disturbed = true; + var shuttingDown = false; + // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown. + var currentWrite = promiseResolvedWith(undefined); + return newPromise(function (resolve, reject) { + var abortAlgorithm; + if (signal !== undefined) { + abortAlgorithm = function () { + var error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError'); + var actions = []; + if (!preventAbort) { + actions.push(function () { + if (dest._state === 'writable') { + return WritableStreamAbort(dest, error); + } + return promiseResolvedWith(undefined); + }); + } + if (!preventCancel) { + actions.push(function () { + if (source._state === 'readable') { + return ReadableStreamCancel(source, error); + } + return promiseResolvedWith(undefined); + }); + } + shutdownWithAction(function () { return Promise.all(actions.map(function (action) { return action(); })); }, true, error); + }; + if (signal.aborted) { + abortAlgorithm(); + return; + } + signal.addEventListener('abort', abortAlgorithm); + } + // Using reader and writer, read all chunks from this and write them to dest + // - Backpressure must be enforced + // - Shutdown must stop all activity + function pipeLoop() { + return newPromise(function (resolveLoop, rejectLoop) { + function next(done) { + if (done) { + resolveLoop(); + } + else { + // Use `PerformPromiseThen` instead of `uponPromise` to avoid + // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers + PerformPromiseThen(pipeStep(), next, rejectLoop); + } + } + next(false); + }); + } + function pipeStep() { + if (shuttingDown) { + return promiseResolvedWith(true); + } + return PerformPromiseThen(writer._readyPromise, function () { + return newPromise(function (resolveRead, rejectRead) { + ReadableStreamDefaultReaderRead(reader, { + _chunkSteps: function (chunk) { + currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop); + resolveRead(false); + }, + _closeSteps: function () { return resolveRead(true); }, + _errorSteps: rejectRead + }); + }); + }); + } + // Errors must be propagated forward + isOrBecomesErrored(source, reader._closedPromise, function (storedError) { + if (!preventAbort) { + shutdownWithAction(function () { return WritableStreamAbort(dest, storedError); }, true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Errors must be propagated backward + isOrBecomesErrored(dest, writer._closedPromise, function (storedError) { + if (!preventCancel) { + shutdownWithAction(function () { return ReadableStreamCancel(source, storedError); }, true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Closing must be propagated forward + isOrBecomesClosed(source, reader._closedPromise, function () { + if (!preventClose) { + shutdownWithAction(function () { return WritableStreamDefaultWriterCloseWithErrorPropagation(writer); }); + } + else { + shutdown(); + } + return null; + }); + // Closing must be propagated backward + if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') { + var destClosed_1 = new TypeError('the destination writable stream closed before all data could be piped to it'); + if (!preventCancel) { + shutdownWithAction(function () { return ReadableStreamCancel(source, destClosed_1); }, true, destClosed_1); + } + else { + shutdown(true, destClosed_1); + } + } + setPromiseIsHandledToTrue(pipeLoop()); + function waitForWritesToFinish() { + // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait + // for that too. + var oldCurrentWrite = currentWrite; + return PerformPromiseThen(currentWrite, function () { return oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined; }); + } + function isOrBecomesErrored(stream, promise, action) { + if (stream._state === 'errored') { + action(stream._storedError); + } + else { + uponRejection(promise, action); + } + } + function isOrBecomesClosed(stream, promise, action) { + if (stream._state === 'closed') { + action(); + } + else { + uponFulfillment(promise, action); + } + } + function shutdownWithAction(action, originalIsError, originalError) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), doTheRest); + } + else { + doTheRest(); + } + function doTheRest() { + uponPromise(action(), function () { return finalize(originalIsError, originalError); }, function (newError) { return finalize(true, newError); }); + return null; + } + } + function shutdown(isError, error) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), function () { return finalize(isError, error); }); + } + else { + finalize(isError, error); + } + } + function finalize(isError, error) { + WritableStreamDefaultWriterRelease(writer); + ReadableStreamReaderGenericRelease(reader); + if (signal !== undefined) { + signal.removeEventListener('abort', abortAlgorithm); + } + if (isError) { + reject(error); + } + else { + resolve(undefined); + } + return null; + } + }); + } + + /** + * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. + * + * @public + */ + var ReadableStreamDefaultController = /** @class */ (function () { + function ReadableStreamDefaultController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(ReadableStreamDefaultController.prototype, "desiredSize", { + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + */ + get: function () { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('desiredSize'); + } + return ReadableStreamDefaultControllerGetDesiredSize(this); + }, + enumerable: false, + configurable: true + }); + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + ReadableStreamDefaultController.prototype.close = function () { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('close'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits close'); + } + ReadableStreamDefaultControllerClose(this); + }; + ReadableStreamDefaultController.prototype.enqueue = function (chunk) { + if (chunk === void 0) { chunk = undefined; } + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('enqueue'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits enqueue'); + } + return ReadableStreamDefaultControllerEnqueue(this, chunk); + }; + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + ReadableStreamDefaultController.prototype.error = function (e) { + if (e === void 0) { e = undefined; } + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('error'); + } + ReadableStreamDefaultControllerError(this, e); + }; + /** @internal */ + ReadableStreamDefaultController.prototype[CancelSteps] = function (reason) { + ResetQueue(this); + var result = this._cancelAlgorithm(reason); + ReadableStreamDefaultControllerClearAlgorithms(this); + return result; + }; + /** @internal */ + ReadableStreamDefaultController.prototype[PullSteps] = function (readRequest) { + var stream = this._controlledReadableStream; + if (this._queue.length > 0) { + var chunk = DequeueValue(this); + if (this._closeRequested && this._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(this); + ReadableStreamClose(stream); + } + else { + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + readRequest._chunkSteps(chunk); + } + else { + ReadableStreamAddReadRequest(stream, readRequest); + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + }; + /** @internal */ + ReadableStreamDefaultController.prototype[ReleaseSteps] = function () { + // Do nothing. + }; + return ReadableStreamDefaultController; + }()); + Object.defineProperties(ReadableStreamDefaultController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + desiredSize: { enumerable: true } + }); + setFunctionName(ReadableStreamDefaultController.prototype.close, 'close'); + setFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue'); + setFunctionName(ReadableStreamDefaultController.prototype.error, 'error'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultController', + configurable: true + }); + } + // Abstract operations for the ReadableStreamDefaultController. + function IsReadableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) { + return false; + } + return x instanceof ReadableStreamDefaultController; + } + function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { + var shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + var pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, function () { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + return null; + }, function (e) { + ReadableStreamDefaultControllerError(controller, e); + return null; + }); + } + function ReadableStreamDefaultControllerShouldCallPull(controller) { + var stream = controller._controlledReadableStream; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return false; + } + if (!controller._started) { + return false; + } + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + var desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; + } + function ReadableStreamDefaultControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; + } + // A client of ReadableStreamDefaultController may use these functions directly to bypass state check. + function ReadableStreamDefaultControllerClose(controller) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + var stream = controller._controlledReadableStream; + controller._closeRequested = true; + if (controller._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } + } + function ReadableStreamDefaultControllerEnqueue(controller, chunk) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + var stream = controller._controlledReadableStream; + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + ReadableStreamFulfillReadRequest(stream, chunk, false); + } + else { + var chunkSize = void 0; + try { + chunkSize = controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + ReadableStreamDefaultControllerError(controller, chunkSizeE); + throw chunkSizeE; + } + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + ReadableStreamDefaultControllerError(controller, enqueueE); + throw enqueueE; + } + } + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + function ReadableStreamDefaultControllerError(controller, e) { + var stream = controller._controlledReadableStream; + if (stream._state !== 'readable') { + return; + } + ResetQueue(controller); + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); + } + function ReadableStreamDefaultControllerGetDesiredSize(controller) { + var state = controller._controlledReadableStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; + } + // This is used in the implementation of TransformStream. + function ReadableStreamDefaultControllerHasBackpressure(controller) { + if (ReadableStreamDefaultControllerShouldCallPull(controller)) { + return false; + } + return true; + } + function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { + var state = controller._controlledReadableStream._state; + if (!controller._closeRequested && state === 'readable') { + return true; + } + return false; + } + function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledReadableStream = stream; + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._started = false; + controller._closeRequested = false; + controller._pullAgain = false; + controller._pulling = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + stream._readableStreamController = controller; + var startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), function () { + controller._started = true; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + return null; + }, function (r) { + ReadableStreamDefaultControllerError(controller, r); + return null; + }); + } + function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { + var controller = Object.create(ReadableStreamDefaultController.prototype); + var startAlgorithm; + var pullAlgorithm; + var cancelAlgorithm; + if (underlyingSource.start !== undefined) { + startAlgorithm = function () { return underlyingSource.start(controller); }; + } + else { + startAlgorithm = function () { return undefined; }; + } + if (underlyingSource.pull !== undefined) { + pullAlgorithm = function () { return underlyingSource.pull(controller); }; + } + else { + pullAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + if (underlyingSource.cancel !== undefined) { + cancelAlgorithm = function (reason) { return underlyingSource.cancel(reason); }; + } + else { + cancelAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + } + // Helper functions for the ReadableStreamDefaultController. + function defaultControllerBrandCheckException$1(name) { + return new TypeError("ReadableStreamDefaultController.prototype.".concat(name, " can only be used on a ReadableStreamDefaultController")); + } + + function ReadableStreamTee(stream, cloneForBranch2) { + if (IsReadableByteStreamController(stream._readableStreamController)) { + return ReadableByteStreamTee(stream); + } + return ReadableStreamDefaultTee(stream); + } + function ReadableStreamDefaultTee(stream, cloneForBranch2) { + var reader = AcquireReadableStreamDefaultReader(stream); + var reading = false; + var readAgain = false; + var canceled1 = false; + var canceled2 = false; + var reason1; + var reason2; + var branch1; + var branch2; + var resolveCancelPromise; + var cancelPromise = newPromise(function (resolve) { + resolveCancelPromise = resolve; + }); + function pullAlgorithm() { + if (reading) { + readAgain = true; + return promiseResolvedWith(undefined); + } + reading = true; + var readRequest = { + _chunkSteps: function (chunk) { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(function () { + readAgain = false; + var chunk1 = chunk; + var chunk2 = chunk; + // There is no way to access the cloning code right now in the reference implementation. + // If we add one then we'll need an implementation for serializable objects. + // if (!canceled2 && cloneForBranch2) { + // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2)); + // } + if (!canceled1) { + ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgain) { + pullAlgorithm(); + } + }); + }, + _closeSteps: function () { + reading = false; + if (!canceled1) { + ReadableStreamDefaultControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableStreamDefaultControllerClose(branch2._readableStreamController); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: function () { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + // do nothing + } + branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); + branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); + uponRejection(reader._closedPromise, function (r) { + ReadableStreamDefaultControllerError(branch1._readableStreamController, r); + ReadableStreamDefaultControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + return [branch1, branch2]; + } + function ReadableByteStreamTee(stream) { + var reader = AcquireReadableStreamDefaultReader(stream); + var reading = false; + var readAgainForBranch1 = false; + var readAgainForBranch2 = false; + var canceled1 = false; + var canceled2 = false; + var reason1; + var reason2; + var branch1; + var branch2; + var resolveCancelPromise; + var cancelPromise = newPromise(function (resolve) { + resolveCancelPromise = resolve; + }); + function forwardReaderError(thisReader) { + uponRejection(thisReader._closedPromise, function (r) { + if (thisReader !== reader) { + return null; + } + ReadableByteStreamControllerError(branch1._readableStreamController, r); + ReadableByteStreamControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + } + function pullWithDefaultReader() { + if (IsReadableStreamBYOBReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamDefaultReader(stream); + forwardReaderError(reader); + } + var readRequest = { + _chunkSteps: function (chunk) { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(function () { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + var chunk1 = chunk; + var chunk2 = chunk; + if (!canceled1 && !canceled2) { + try { + chunk2 = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(branch1._readableStreamController, cloneE); + ReadableByteStreamControllerError(branch2._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + } + if (!canceled1) { + ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: function () { + reading = false; + if (!canceled1) { + ReadableByteStreamControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableByteStreamControllerClose(branch2._readableStreamController); + } + if (branch1._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch1._readableStreamController, 0); + } + if (branch2._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch2._readableStreamController, 0); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: function () { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + } + function pullWithBYOBReader(view, forBranch2) { + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamBYOBReader(stream); + forwardReaderError(reader); + } + var byobBranch = forBranch2 ? branch2 : branch1; + var otherBranch = forBranch2 ? branch1 : branch2; + var readIntoRequest = { + _chunkSteps: function (chunk) { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(function () { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + var byobCanceled = forBranch2 ? canceled2 : canceled1; + var otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!otherCanceled) { + var clonedChunk = void 0; + try { + clonedChunk = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE); + ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk); + } + else if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: function (chunk) { + reading = false; + var byobCanceled = forBranch2 ? canceled2 : canceled1; + var otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!byobCanceled) { + ReadableByteStreamControllerClose(byobBranch._readableStreamController); + } + if (!otherCanceled) { + ReadableByteStreamControllerClose(otherBranch._readableStreamController); + } + if (chunk !== undefined) { + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0); + } + } + if (!byobCanceled || !otherCanceled) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: function () { + reading = false; + } + }; + ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest); + } + function pull1Algorithm() { + if (reading) { + readAgainForBranch1 = true; + return promiseResolvedWith(undefined); + } + reading = true; + var byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, false); + } + return promiseResolvedWith(undefined); + } + function pull2Algorithm() { + if (reading) { + readAgainForBranch2 = true; + return promiseResolvedWith(undefined); + } + reading = true; + var byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, true); + } + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + return; + } + branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm); + branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm); + forwardReaderError(reader); + return [branch1, branch2]; + } + + function isReadableStreamLike(stream) { + return typeIsObject(stream) && typeof stream.getReader !== 'undefined'; + } + + function ReadableStreamFrom(source) { + if (isReadableStreamLike(source)) { + return ReadableStreamFromDefaultReader(source.getReader()); + } + return ReadableStreamFromIterable(source); + } + function ReadableStreamFromIterable(asyncIterable) { + var stream; + var iteratorRecord = GetIterator(asyncIterable, 'async'); + var startAlgorithm = noop; + function pullAlgorithm() { + var nextResult; + try { + nextResult = IteratorNext(iteratorRecord); + } + catch (e) { + return promiseRejectedWith(e); + } + var nextPromise = promiseResolvedWith(nextResult); + return transformPromiseWith(nextPromise, function (iterResult) { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object'); + } + var done = IteratorComplete(iterResult); + if (done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + var value = IteratorValue(iterResult); + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + var iterator = iteratorRecord.iterator; + var returnMethod; + try { + returnMethod = GetMethod(iterator, 'return'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (returnMethod === undefined) { + return promiseResolvedWith(undefined); + } + var returnResult; + try { + returnResult = reflectCall(returnMethod, iterator, [reason]); + } + catch (e) { + return promiseRejectedWith(e); + } + var returnPromise = promiseResolvedWith(returnResult); + return transformPromiseWith(returnPromise, function (iterResult) { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object'); + } + return undefined; + }); + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; + } + function ReadableStreamFromDefaultReader(reader) { + var stream; + var startAlgorithm = noop; + function pullAlgorithm() { + var readPromise; + try { + readPromise = reader.read(); + } + catch (e) { + return promiseRejectedWith(e); + } + return transformPromiseWith(readPromise, function (readResult) { + if (!typeIsObject(readResult)) { + throw new TypeError('The promise returned by the reader.read() method must fulfill with an object'); + } + if (readResult.done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + var value = readResult.value; + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + try { + return promiseResolvedWith(reader.cancel(reason)); + } + catch (e) { + return promiseRejectedWith(e); + } + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; + } + + function convertUnderlyingDefaultOrByteSource(source, context) { + assertDictionary(source, context); + var original = source; + var autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; + var cancel = original === null || original === void 0 ? void 0 : original.cancel; + var pull = original === null || original === void 0 ? void 0 : original.pull; + var start = original === null || original === void 0 ? void 0 : original.start; + var type = original === null || original === void 0 ? void 0 : original.type; + return { + autoAllocateChunkSize: autoAllocateChunkSize === undefined ? + undefined : + convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, "".concat(context, " has member 'autoAllocateChunkSize' that")), + cancel: cancel === undefined ? + undefined : + convertUnderlyingSourceCancelCallback(cancel, original, "".concat(context, " has member 'cancel' that")), + pull: pull === undefined ? + undefined : + convertUnderlyingSourcePullCallback(pull, original, "".concat(context, " has member 'pull' that")), + start: start === undefined ? + undefined : + convertUnderlyingSourceStartCallback(start, original, "".concat(context, " has member 'start' that")), + type: type === undefined ? undefined : convertReadableStreamType(type, "".concat(context, " has member 'type' that")) + }; + } + function convertUnderlyingSourceCancelCallback(fn, original, context) { + assertFunction(fn, context); + return function (reason) { return promiseCall(fn, original, [reason]); }; + } + function convertUnderlyingSourcePullCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return promiseCall(fn, original, [controller]); }; + } + function convertUnderlyingSourceStartCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return reflectCall(fn, original, [controller]); }; + } + function convertReadableStreamType(type, context) { + type = "".concat(type); + if (type !== 'bytes') { + throw new TypeError("".concat(context, " '").concat(type, "' is not a valid enumeration value for ReadableStreamType")); + } + return type; + } + + function convertIteratorOptions(options, context) { + assertDictionary(options, context); + var preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + return { preventCancel: Boolean(preventCancel) }; + } + + function convertPipeOptions(options, context) { + assertDictionary(options, context); + var preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort; + var preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + var preventClose = options === null || options === void 0 ? void 0 : options.preventClose; + var signal = options === null || options === void 0 ? void 0 : options.signal; + if (signal !== undefined) { + assertAbortSignal(signal, "".concat(context, " has member 'signal' that")); + } + return { + preventAbort: Boolean(preventAbort), + preventCancel: Boolean(preventCancel), + preventClose: Boolean(preventClose), + signal: signal + }; + } + function assertAbortSignal(signal, context) { + if (!isAbortSignal(signal)) { + throw new TypeError("".concat(context, " is not an AbortSignal.")); + } + } + + function convertReadableWritablePair(pair, context) { + assertDictionary(pair, context); + var readable = pair === null || pair === void 0 ? void 0 : pair.readable; + assertRequiredField(readable, 'readable', 'ReadableWritablePair'); + assertReadableStream(readable, "".concat(context, " has member 'readable' that")); + var writable = pair === null || pair === void 0 ? void 0 : pair.writable; + assertRequiredField(writable, 'writable', 'ReadableWritablePair'); + assertWritableStream(writable, "".concat(context, " has member 'writable' that")); + return { readable: readable, writable: writable }; + } + + /** + * A readable stream represents a source of data, from which you can read. + * + * @public + */ + var ReadableStream = /** @class */ (function () { + function ReadableStream(rawUnderlyingSource, rawStrategy) { + if (rawUnderlyingSource === void 0) { rawUnderlyingSource = {}; } + if (rawStrategy === void 0) { rawStrategy = {}; } + if (rawUnderlyingSource === undefined) { + rawUnderlyingSource = null; + } + else { + assertObject(rawUnderlyingSource, 'First parameter'); + } + var strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + var underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter'); + InitializeReadableStream(this); + if (underlyingSource.type === 'bytes') { + if (strategy.size !== undefined) { + throw new RangeError('The strategy for a byte stream cannot have a size function'); + } + var highWaterMark = ExtractHighWaterMark(strategy, 0); + SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); + } + else { + var sizeAlgorithm = ExtractSizeAlgorithm(strategy); + var highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); + } + } + Object.defineProperty(ReadableStream.prototype, "locked", { + /** + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. + */ + get: function () { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('locked'); + } + return IsReadableStreamLocked(this); + }, + enumerable: false, + configurable: true + }); + /** + * Cancels the stream, signaling a loss of interest in the stream by a consumer. + * + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} + * method, which might or might not use it. + */ + ReadableStream.prototype.cancel = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('cancel')); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader')); + } + return ReadableStreamCancel(this, reason); + }; + ReadableStream.prototype.getReader = function (rawOptions) { + if (rawOptions === void 0) { rawOptions = undefined; } + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('getReader'); + } + var options = convertReaderOptions(rawOptions, 'First parameter'); + if (options.mode === undefined) { + return AcquireReadableStreamDefaultReader(this); + } + return AcquireReadableStreamBYOBReader(this); + }; + ReadableStream.prototype.pipeThrough = function (rawTransform, rawOptions) { + if (rawOptions === void 0) { rawOptions = {}; } + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('pipeThrough'); + } + assertRequiredArgument(rawTransform, 1, 'pipeThrough'); + var transform = convertReadableWritablePair(rawTransform, 'First parameter'); + var options = convertPipeOptions(rawOptions, 'Second parameter'); + if (IsReadableStreamLocked(this)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream'); + } + if (IsWritableStreamLocked(transform.writable)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream'); + } + var promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + setPromiseIsHandledToTrue(promise); + return transform.readable; + }; + ReadableStream.prototype.pipeTo = function (destination, rawOptions) { + if (rawOptions === void 0) { rawOptions = {}; } + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('pipeTo')); + } + if (destination === undefined) { + return promiseRejectedWith("Parameter 1 is required in 'pipeTo'."); + } + if (!IsWritableStream(destination)) { + return promiseRejectedWith(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream")); + } + var options; + try { + options = convertPipeOptions(rawOptions, 'Second parameter'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')); + } + if (IsWritableStreamLocked(destination)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')); + } + return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + }; + /** + * Tees this readable stream, returning a two-element array containing the two resulting branches as + * new {@link ReadableStream} instances. + * + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be + * propagated to the stream's underlying source. + * + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, + * this could allow interference between the two branches. + */ + ReadableStream.prototype.tee = function () { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('tee'); + } + var branches = ReadableStreamTee(this); + return CreateArrayFromList(branches); + }; + ReadableStream.prototype.values = function (rawOptions) { + if (rawOptions === void 0) { rawOptions = undefined; } + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('values'); + } + var options = convertIteratorOptions(rawOptions, 'First parameter'); + return AcquireReadableStreamAsyncIterator(this, options.preventCancel); + }; + ReadableStream.prototype[SymbolAsyncIterator] = function (options) { + // Stub implementation, overridden below + return this.values(options); + }; + /** + * Creates a new ReadableStream wrapping the provided iterable or async iterable. + * + * This can be used to adapt various kinds of objects into a readable stream, + * such as an array, an async generator, or a Node.js readable stream. + */ + ReadableStream.from = function (asyncIterable) { + return ReadableStreamFrom(asyncIterable); + }; + return ReadableStream; + }()); + Object.defineProperties(ReadableStream, { + from: { enumerable: true } + }); + Object.defineProperties(ReadableStream.prototype, { + cancel: { enumerable: true }, + getReader: { enumerable: true }, + pipeThrough: { enumerable: true }, + pipeTo: { enumerable: true }, + tee: { enumerable: true }, + values: { enumerable: true }, + locked: { enumerable: true } + }); + setFunctionName(ReadableStream.from, 'from'); + setFunctionName(ReadableStream.prototype.cancel, 'cancel'); + setFunctionName(ReadableStream.prototype.getReader, 'getReader'); + setFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough'); + setFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo'); + setFunctionName(ReadableStream.prototype.tee, 'tee'); + setFunctionName(ReadableStream.prototype.values, 'values'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStream', + configurable: true + }); + } + Object.defineProperty(ReadableStream.prototype, SymbolAsyncIterator, { + value: ReadableStream.prototype.values, + writable: true, + configurable: true + }); + // Abstract operations for the ReadableStream. + // Throws if and only if startAlgorithm throws. + function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + if (highWaterMark === void 0) { highWaterMark = 1; } + if (sizeAlgorithm === void 0) { sizeAlgorithm = function () { return 1; }; } + var stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + var controller = Object.create(ReadableStreamDefaultController.prototype); + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + return stream; + } + // Throws if and only if startAlgorithm throws. + function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) { + var stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + var controller = Object.create(ReadableByteStreamController.prototype); + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined); + return stream; + } + function InitializeReadableStream(stream) { + stream._state = 'readable'; + stream._reader = undefined; + stream._storedError = undefined; + stream._disturbed = false; + } + function IsReadableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) { + return false; + } + return x instanceof ReadableStream; + } + function IsReadableStreamLocked(stream) { + if (stream._reader === undefined) { + return false; + } + return true; + } + // ReadableStream API exposed for controllers. + function ReadableStreamCancel(stream, reason) { + stream._disturbed = true; + if (stream._state === 'closed') { + return promiseResolvedWith(undefined); + } + if (stream._state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + ReadableStreamClose(stream); + var reader = stream._reader; + if (reader !== undefined && IsReadableStreamBYOBReader(reader)) { + var readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(function (readIntoRequest) { + readIntoRequest._closeSteps(undefined); + }); + } + var sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); + return transformPromiseWith(sourceCancelPromise, noop); + } + function ReadableStreamClose(stream) { + stream._state = 'closed'; + var reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseResolve(reader); + if (IsReadableStreamDefaultReader(reader)) { + var readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(function (readRequest) { + readRequest._closeSteps(); + }); + } + } + function ReadableStreamError(stream, e) { + stream._state = 'errored'; + stream._storedError = e; + var reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseReject(reader, e); + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamDefaultReaderErrorReadRequests(reader, e); + } + else { + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); + } + } + // Helper functions for the ReadableStream. + function streamBrandCheckException$1(name) { + return new TypeError("ReadableStream.prototype.".concat(name, " can only be used on a ReadableStream")); + } + + function convertQueuingStrategyInit(init, context) { + assertDictionary(init, context); + var highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit'); + return { + highWaterMark: convertUnrestrictedDouble(highWaterMark) + }; + } + + // The size function must not have a prototype property nor be a constructor + var byteLengthSizeFunction = function (chunk) { + return chunk.byteLength; + }; + setFunctionName(byteLengthSizeFunction, 'size'); + /** + * A queuing strategy that counts the number of bytes in each chunk. + * + * @public + */ + var ByteLengthQueuingStrategy = /** @class */ (function () { + function ByteLengthQueuingStrategy(options) { + assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; + } + Object.defineProperty(ByteLengthQueuingStrategy.prototype, "highWaterMark", { + /** + * Returns the high water mark provided to the constructor. + */ + get: function () { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('highWaterMark'); + } + return this._byteLengthQueuingStrategyHighWaterMark; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ByteLengthQueuingStrategy.prototype, "size", { + /** + * Measures the size of `chunk` by returning the value of its `byteLength` property. + */ + get: function () { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('size'); + } + return byteLengthSizeFunction; + }, + enumerable: false, + configurable: true + }); + return ByteLengthQueuingStrategy; + }()); + Object.defineProperties(ByteLengthQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ByteLengthQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'ByteLengthQueuingStrategy', + configurable: true + }); + } + // Helper functions for the ByteLengthQueuingStrategy. + function byteLengthBrandCheckException(name) { + return new TypeError("ByteLengthQueuingStrategy.prototype.".concat(name, " can only be used on a ByteLengthQueuingStrategy")); + } + function IsByteLengthQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof ByteLengthQueuingStrategy; + } + + // The size function must not have a prototype property nor be a constructor + var countSizeFunction = function () { + return 1; + }; + setFunctionName(countSizeFunction, 'size'); + /** + * A queuing strategy that counts the number of chunks. + * + * @public + */ + var CountQueuingStrategy = /** @class */ (function () { + function CountQueuingStrategy(options) { + assertRequiredArgument(options, 1, 'CountQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._countQueuingStrategyHighWaterMark = options.highWaterMark; + } + Object.defineProperty(CountQueuingStrategy.prototype, "highWaterMark", { + /** + * Returns the high water mark provided to the constructor. + */ + get: function () { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('highWaterMark'); + } + return this._countQueuingStrategyHighWaterMark; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(CountQueuingStrategy.prototype, "size", { + /** + * Measures the size of `chunk` by always returning 1. + * This ensures that the total queue size is a count of the number of chunks in the queue. + */ + get: function () { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('size'); + } + return countSizeFunction; + }, + enumerable: false, + configurable: true + }); + return CountQueuingStrategy; + }()); + Object.defineProperties(CountQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(CountQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'CountQueuingStrategy', + configurable: true + }); + } + // Helper functions for the CountQueuingStrategy. + function countBrandCheckException(name) { + return new TypeError("CountQueuingStrategy.prototype.".concat(name, " can only be used on a CountQueuingStrategy")); + } + function IsCountQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof CountQueuingStrategy; + } + + function convertTransformer(original, context) { + assertDictionary(original, context); + var cancel = original === null || original === void 0 ? void 0 : original.cancel; + var flush = original === null || original === void 0 ? void 0 : original.flush; + var readableType = original === null || original === void 0 ? void 0 : original.readableType; + var start = original === null || original === void 0 ? void 0 : original.start; + var transform = original === null || original === void 0 ? void 0 : original.transform; + var writableType = original === null || original === void 0 ? void 0 : original.writableType; + return { + cancel: cancel === undefined ? + undefined : + convertTransformerCancelCallback(cancel, original, "".concat(context, " has member 'cancel' that")), + flush: flush === undefined ? + undefined : + convertTransformerFlushCallback(flush, original, "".concat(context, " has member 'flush' that")), + readableType: readableType, + start: start === undefined ? + undefined : + convertTransformerStartCallback(start, original, "".concat(context, " has member 'start' that")), + transform: transform === undefined ? + undefined : + convertTransformerTransformCallback(transform, original, "".concat(context, " has member 'transform' that")), + writableType: writableType + }; + } + function convertTransformerFlushCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return promiseCall(fn, original, [controller]); }; + } + function convertTransformerStartCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return reflectCall(fn, original, [controller]); }; + } + function convertTransformerTransformCallback(fn, original, context) { + assertFunction(fn, context); + return function (chunk, controller) { return promiseCall(fn, original, [chunk, controller]); }; + } + function convertTransformerCancelCallback(fn, original, context) { + assertFunction(fn, context); + return function (reason) { return promiseCall(fn, original, [reason]); }; + } + + // Class TransformStream + /** + * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, + * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. + * In a manner specific to the transform stream in question, writes to the writable side result in new data being + * made available for reading from the readable side. + * + * @public + */ + var TransformStream = /** @class */ (function () { + function TransformStream(rawTransformer, rawWritableStrategy, rawReadableStrategy) { + if (rawTransformer === void 0) { rawTransformer = {}; } + if (rawWritableStrategy === void 0) { rawWritableStrategy = {}; } + if (rawReadableStrategy === void 0) { rawReadableStrategy = {}; } + if (rawTransformer === undefined) { + rawTransformer = null; + } + var writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter'); + var readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter'); + var transformer = convertTransformer(rawTransformer, 'First parameter'); + if (transformer.readableType !== undefined) { + throw new RangeError('Invalid readableType specified'); + } + if (transformer.writableType !== undefined) { + throw new RangeError('Invalid writableType specified'); + } + var readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); + var readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); + var writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); + var writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); + var startPromise_resolve; + var startPromise = newPromise(function (resolve) { + startPromise_resolve = resolve; + }); + InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); + if (transformer.start !== undefined) { + startPromise_resolve(transformer.start(this._transformStreamController)); + } + else { + startPromise_resolve(undefined); + } + } + Object.defineProperty(TransformStream.prototype, "readable", { + /** + * The readable side of the transform stream. + */ + get: function () { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('readable'); + } + return this._readable; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TransformStream.prototype, "writable", { + /** + * The writable side of the transform stream. + */ + get: function () { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('writable'); + } + return this._writable; + }, + enumerable: false, + configurable: true + }); + return TransformStream; + }()); + Object.defineProperties(TransformStream.prototype, { + readable: { enumerable: true }, + writable: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStream.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStream', + configurable: true + }); + } + function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { + function startAlgorithm() { + return startPromise; + } + function writeAlgorithm(chunk) { + return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); + } + function abortAlgorithm(reason) { + return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); + } + function closeAlgorithm() { + return TransformStreamDefaultSinkCloseAlgorithm(stream); + } + stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); + function pullAlgorithm() { + return TransformStreamDefaultSourcePullAlgorithm(stream); + } + function cancelAlgorithm(reason) { + return TransformStreamDefaultSourceCancelAlgorithm(stream, reason); + } + stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure. + stream._backpressure = undefined; + stream._backpressureChangePromise = undefined; + stream._backpressureChangePromise_resolve = undefined; + TransformStreamSetBackpressure(stream, true); + stream._transformStreamController = undefined; + } + function IsTransformStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) { + return false; + } + return x instanceof TransformStream; + } + // This is a no-op if both sides are already errored. + function TransformStreamError(stream, e) { + ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e); + TransformStreamErrorWritableAndUnblockWrite(stream, e); + } + function TransformStreamErrorWritableAndUnblockWrite(stream, e) { + TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); + WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e); + TransformStreamUnblockWrite(stream); + } + function TransformStreamUnblockWrite(stream) { + if (stream._backpressure) { + // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure() + // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time + // _backpressure is set. + TransformStreamSetBackpressure(stream, false); + } + } + function TransformStreamSetBackpressure(stream, backpressure) { + // Passes also when called during construction. + if (stream._backpressureChangePromise !== undefined) { + stream._backpressureChangePromise_resolve(); + } + stream._backpressureChangePromise = newPromise(function (resolve) { + stream._backpressureChangePromise_resolve = resolve; + }); + stream._backpressure = backpressure; + } + // Class TransformStreamDefaultController + /** + * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. + * + * @public + */ + var TransformStreamDefaultController = /** @class */ (function () { + function TransformStreamDefaultController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(TransformStreamDefaultController.prototype, "desiredSize", { + /** + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. + */ + get: function () { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('desiredSize'); + } + var readableController = this._controlledTransformStream._readable._readableStreamController; + return ReadableStreamDefaultControllerGetDesiredSize(readableController); + }, + enumerable: false, + configurable: true + }); + TransformStreamDefaultController.prototype.enqueue = function (chunk) { + if (chunk === void 0) { chunk = undefined; } + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('enqueue'); + } + TransformStreamDefaultControllerEnqueue(this, chunk); + }; + /** + * Errors both the readable side and the writable side of the controlled transform stream, making all future + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. + */ + TransformStreamDefaultController.prototype.error = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('error'); + } + TransformStreamDefaultControllerError(this, reason); + }; + /** + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the + * transformer only needs to consume a portion of the chunks written to the writable side. + */ + TransformStreamDefaultController.prototype.terminate = function () { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('terminate'); + } + TransformStreamDefaultControllerTerminate(this); + }; + return TransformStreamDefaultController; + }()); + Object.defineProperties(TransformStreamDefaultController.prototype, { + enqueue: { enumerable: true }, + error: { enumerable: true }, + terminate: { enumerable: true }, + desiredSize: { enumerable: true } + }); + setFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue'); + setFunctionName(TransformStreamDefaultController.prototype.error, 'error'); + setFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStreamDefaultController', + configurable: true + }); + } + // Transform Stream Default Controller Abstract Operations + function IsTransformStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) { + return false; + } + return x instanceof TransformStreamDefaultController; + } + function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm) { + controller._controlledTransformStream = stream; + stream._transformStreamController = controller; + controller._transformAlgorithm = transformAlgorithm; + controller._flushAlgorithm = flushAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._finishPromise = undefined; + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; + } + function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { + var controller = Object.create(TransformStreamDefaultController.prototype); + var transformAlgorithm; + var flushAlgorithm; + var cancelAlgorithm; + if (transformer.transform !== undefined) { + transformAlgorithm = function (chunk) { return transformer.transform(chunk, controller); }; + } + else { + transformAlgorithm = function (chunk) { + try { + TransformStreamDefaultControllerEnqueue(controller, chunk); + return promiseResolvedWith(undefined); + } + catch (transformResultE) { + return promiseRejectedWith(transformResultE); + } + }; + } + if (transformer.flush !== undefined) { + flushAlgorithm = function () { return transformer.flush(controller); }; + } + else { + flushAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + if (transformer.cancel !== undefined) { + cancelAlgorithm = function (reason) { return transformer.cancel(reason); }; + } + else { + cancelAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm); + } + function TransformStreamDefaultControllerClearAlgorithms(controller) { + controller._transformAlgorithm = undefined; + controller._flushAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + } + function TransformStreamDefaultControllerEnqueue(controller, chunk) { + var stream = controller._controlledTransformStream; + var readableController = stream._readable._readableStreamController; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { + throw new TypeError('Readable side is not in a state that permits enqueue'); + } + // We throttle transform invocations based on the backpressure of the ReadableStream, but we still + // accept TransformStreamDefaultControllerEnqueue() calls. + try { + ReadableStreamDefaultControllerEnqueue(readableController, chunk); + } + catch (e) { + // This happens when readableStrategy.size() throws. + TransformStreamErrorWritableAndUnblockWrite(stream, e); + throw stream._readable._storedError; + } + var backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); + if (backpressure !== stream._backpressure) { + TransformStreamSetBackpressure(stream, true); + } + } + function TransformStreamDefaultControllerError(controller, e) { + TransformStreamError(controller._controlledTransformStream, e); + } + function TransformStreamDefaultControllerPerformTransform(controller, chunk) { + var transformPromise = controller._transformAlgorithm(chunk); + return transformPromiseWith(transformPromise, undefined, function (r) { + TransformStreamError(controller._controlledTransformStream, r); + throw r; + }); + } + function TransformStreamDefaultControllerTerminate(controller) { + var stream = controller._controlledTransformStream; + var readableController = stream._readable._readableStreamController; + ReadableStreamDefaultControllerClose(readableController); + var error = new TypeError('TransformStream terminated'); + TransformStreamErrorWritableAndUnblockWrite(stream, error); + } + // TransformStreamDefaultSink Algorithms + function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { + var controller = stream._transformStreamController; + if (stream._backpressure) { + var backpressureChangePromise = stream._backpressureChangePromise; + return transformPromiseWith(backpressureChangePromise, function () { + var writable = stream._writable; + var state = writable._state; + if (state === 'erroring') { + throw writable._storedError; + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + }); + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + } + function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { + var controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + var readable = stream._readable; + // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally, + // we don't run the _cancelAlgorithm again. + controller._finishPromise = newPromise(function (resolve, reject) { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + var cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, function () { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerError(readable._readableStreamController, reason); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, function (r) { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; + } + function TransformStreamDefaultSinkCloseAlgorithm(stream) { + var controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + var readable = stream._readable; + // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally, + // we don't also run the _cancelAlgorithm. + controller._finishPromise = newPromise(function (resolve, reject) { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + var flushPromise = controller._flushAlgorithm(); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(flushPromise, function () { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerClose(readable._readableStreamController); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, function (r) { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; + } + // TransformStreamDefaultSource Algorithms + function TransformStreamDefaultSourcePullAlgorithm(stream) { + // Invariant. Enforced by the promises returned by start() and pull(). + TransformStreamSetBackpressure(stream, false); + // Prevent the next pull() call until there is backpressure. + return stream._backpressureChangePromise; + } + function TransformStreamDefaultSourceCancelAlgorithm(stream, reason) { + var controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._writable cannot change after construction, so caching it across a call to user code is safe. + var writable = stream._writable; + // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or + // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the + // _flushAlgorithm. + controller._finishPromise = newPromise(function (resolve, reject) { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + var cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, function () { + if (writable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, writable._storedError); + } + else { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, function (r) { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; + } + // Helper functions for the TransformStreamDefaultController. + function defaultControllerBrandCheckException(name) { + return new TypeError("TransformStreamDefaultController.prototype.".concat(name, " can only be used on a TransformStreamDefaultController")); + } + function defaultControllerFinishPromiseResolve(controller) { + if (controller._finishPromise_resolve === undefined) { + return; + } + controller._finishPromise_resolve(); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; + } + function defaultControllerFinishPromiseReject(controller, reason) { + if (controller._finishPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(controller._finishPromise); + controller._finishPromise_reject(reason); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; + } + // Helper functions for the TransformStream. + function streamBrandCheckException(name) { + return new TypeError("TransformStream.prototype.".concat(name, " can only be used on a TransformStream")); + } + + var exports$1 = { + ReadableStream: ReadableStream, + ReadableStreamDefaultController: ReadableStreamDefaultController, + ReadableByteStreamController: ReadableByteStreamController, + ReadableStreamBYOBRequest: ReadableStreamBYOBRequest, + ReadableStreamDefaultReader: ReadableStreamDefaultReader, + ReadableStreamBYOBReader: ReadableStreamBYOBReader, + WritableStream: WritableStream, + WritableStreamDefaultController: WritableStreamDefaultController, + WritableStreamDefaultWriter: WritableStreamDefaultWriter, + ByteLengthQueuingStrategy: ByteLengthQueuingStrategy, + CountQueuingStrategy: CountQueuingStrategy, + TransformStream: TransformStream, + TransformStreamDefaultController: TransformStreamDefaultController + }; + // Add classes to global scope + if (typeof globals !== 'undefined') { + for (var prop in exports$1) { + if (Object.prototype.hasOwnProperty.call(exports$1, prop)) { + Object.defineProperty(globals, prop, { + value: exports$1[prop], + writable: true, + configurable: true + }); + } + } + } + + exports.ByteLengthQueuingStrategy = ByteLengthQueuingStrategy; + exports.CountQueuingStrategy = CountQueuingStrategy; + exports.ReadableByteStreamController = ReadableByteStreamController; + exports.ReadableStream = ReadableStream; + exports.ReadableStreamBYOBReader = ReadableStreamBYOBReader; + exports.ReadableStreamBYOBRequest = ReadableStreamBYOBRequest; + exports.ReadableStreamDefaultController = ReadableStreamDefaultController; + exports.ReadableStreamDefaultReader = ReadableStreamDefaultReader; + exports.TransformStream = TransformStream; + exports.TransformStreamDefaultController = TransformStreamDefaultController; + exports.WritableStream = WritableStream; + exports.WritableStreamDefaultController = WritableStreamDefaultController; + exports.WritableStreamDefaultWriter = WritableStreamDefaultWriter; + +})); +//# sourceMappingURL=polyfill.js.map diff --git a/backend/node_modules/web-streams-polyfill/dist/polyfill.js.map b/backend/node_modules/web-streams-polyfill/dist/polyfill.js.map new file mode 100644 index 0000000000000000000000000000000000000000..d4aaa7370cedfb7c82490b593b8e4d3dda6841d1 --- /dev/null +++ b/backend/node_modules/web-streams-polyfill/dist/polyfill.js.map @@ -0,0 +1 @@ +{"version":3,"file":"polyfill.js","sources":["../src/stub/symbol.ts","../node_modules/tslib/tslib.es6.js","../src/utils.ts","../src/lib/helpers/miscellaneous.ts","../src/lib/helpers/webidl.ts","../src/lib/simple-queue.ts","../src/lib/abstract-ops/internal-methods.ts","../src/lib/readable-stream/generic-reader.ts","../src/stub/number-isfinite.ts","../src/stub/math-trunc.ts","../src/lib/validators/basic.ts","../src/lib/validators/readable-stream.ts","../src/lib/readable-stream/default-reader.ts","../src/lib/abstract-ops/ecmascript.ts","../src/target/es5/stub/async-iterator-prototype.ts","../src/lib/readable-stream/async-iterator.ts","../src/stub/number-isnan.ts","../src/lib/abstract-ops/miscellaneous.ts","../src/lib/abstract-ops/queue-with-sizes.ts","../src/lib/helpers/array-buffer-view.ts","../src/lib/readable-stream/byte-stream-controller.ts","../src/lib/validators/reader-options.ts","../src/lib/readable-stream/byob-reader.ts","../src/lib/abstract-ops/queuing-strategy.ts","../src/lib/validators/queuing-strategy.ts","../src/lib/validators/underlying-sink.ts","../src/lib/validators/writable-stream.ts","../src/lib/abort-signal.ts","../src/lib/writable-stream.ts","../src/globals.ts","../src/stub/dom-exception.ts","../src/lib/readable-stream/pipe.ts","../src/lib/readable-stream/default-controller.ts","../src/lib/readable-stream/tee.ts","../src/lib/readable-stream/readable-stream-like.ts","../src/lib/readable-stream/from.ts","../src/lib/validators/underlying-source.ts","../src/lib/validators/iterator-options.ts","../src/lib/validators/pipe-options.ts","../src/lib/validators/readable-writable-pair.ts","../src/lib/readable-stream.ts","../src/lib/validators/queuing-strategy-init.ts","../src/lib/byte-length-queuing-strategy.ts","../src/lib/count-queuing-strategy.ts","../src/lib/validators/transformer.ts","../src/lib/transform-stream.ts","../src/polyfill.ts"],"sourcesContent":["/// \n\nconst SymbolPolyfill: (description?: string) => symbol =\n typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ?\n Symbol :\n description => `Symbol(${description})` as any as symbol;\n\nexport default SymbolPolyfill;\n","/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise, SuppressedError, Symbol */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\r\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\r\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\r\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\r\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\r\n var _, done = false;\r\n for (var i = decorators.length - 1; i >= 0; i--) {\r\n var context = {};\r\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\r\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\r\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\r\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\r\n if (kind === \"accessor\") {\r\n if (result === void 0) continue;\r\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\r\n if (_ = accept(result.get)) descriptor.get = _;\r\n if (_ = accept(result.set)) descriptor.set = _;\r\n if (_ = accept(result.init)) initializers.unshift(_);\r\n }\r\n else if (_ = accept(result)) {\r\n if (kind === \"field\") initializers.unshift(_);\r\n else descriptor[key] = _;\r\n }\r\n }\r\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\r\n done = true;\r\n};\r\n\r\nexport function __runInitializers(thisArg, initializers, value) {\r\n var useValue = arguments.length > 2;\r\n for (var i = 0; i < initializers.length; i++) {\r\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\r\n }\r\n return useValue ? value : void 0;\r\n};\r\n\r\nexport function __propKey(x) {\r\n return typeof x === \"symbol\" ? x : \"\".concat(x);\r\n};\r\n\r\nexport function __setFunctionName(f, name, prefix) {\r\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\r\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\r\n};\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n var desc = Object.getOwnPropertyDescriptor(m, k);\r\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\r\n desc = { enumerable: true, get: function() { return m[k]; } };\r\n }\r\n Object.defineProperty(o, k2, desc);\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\nexport function __classPrivateFieldIn(state, receiver) {\r\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\r\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\r\n}\r\n\r\nexport function __addDisposableResource(env, value, async) {\r\n if (value !== null && value !== void 0) {\r\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\r\n var dispose;\r\n if (async) {\r\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\r\n dispose = value[Symbol.asyncDispose];\r\n }\r\n if (dispose === void 0) {\r\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\r\n dispose = value[Symbol.dispose];\r\n }\r\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\r\n env.stack.push({ value: value, dispose: dispose, async: async });\r\n }\r\n else if (async) {\r\n env.stack.push({ async: true });\r\n }\r\n return value;\r\n}\r\n\r\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n};\r\n\r\nexport function __disposeResources(env) {\r\n function fail(e) {\r\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\r\n env.hasError = true;\r\n }\r\n function next() {\r\n while (env.stack.length) {\r\n var rec = env.stack.pop();\r\n try {\r\n var result = rec.dispose && rec.dispose.call(rec.value);\r\n if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\r\n }\r\n catch (e) {\r\n fail(e);\r\n }\r\n }\r\n if (env.hasError) throw env.error;\r\n }\r\n return next();\r\n}\r\n\r\nexport default {\r\n __extends: __extends,\r\n __assign: __assign,\r\n __rest: __rest,\r\n __decorate: __decorate,\r\n __param: __param,\r\n __metadata: __metadata,\r\n __awaiter: __awaiter,\r\n __generator: __generator,\r\n __createBinding: __createBinding,\r\n __exportStar: __exportStar,\r\n __values: __values,\r\n __read: __read,\r\n __spread: __spread,\r\n __spreadArrays: __spreadArrays,\r\n __spreadArray: __spreadArray,\r\n __await: __await,\r\n __asyncGenerator: __asyncGenerator,\r\n __asyncDelegator: __asyncDelegator,\r\n __asyncValues: __asyncValues,\r\n __makeTemplateObject: __makeTemplateObject,\r\n __importStar: __importStar,\r\n __importDefault: __importDefault,\r\n __classPrivateFieldGet: __classPrivateFieldGet,\r\n __classPrivateFieldSet: __classPrivateFieldSet,\r\n __classPrivateFieldIn: __classPrivateFieldIn,\r\n __addDisposableResource: __addDisposableResource,\r\n __disposeResources: __disposeResources,\r\n};\r\n","export function noop(): undefined {\n return undefined;\n}\n","import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n\nexport function setFunctionName(fn: Function, name: string): void {\n try {\n Object.defineProperty(fn, 'name', {\n value: name,\n configurable: true\n });\n } catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n }\n}\n","import { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\n// https://webidl.spec.whatwg.org/#a-new-promise\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-resolved-with\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return newPromise(resolve => resolve(value));\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-rejected-with\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\n// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned\n// from that handler. To prevent this, return null instead of void from all handlers.\n// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => null | PromiseLike,\n onRejected?: (reason: any) => null | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => null | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => null | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nlet _queueMicrotask: (callback: () => void) => void = callback => {\n if (typeof queueMicrotask === 'function') {\n _queueMicrotask = queueMicrotask;\n } else {\n const resolvedPromise = promiseResolvedWith(undefined);\n _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb);\n }\n return _queueMicrotask(callback);\n};\n\nexport { _queueMicrotask as queueMicrotask };\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n","import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n","export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\nexport const ReleaseSteps = Symbol('[[ReleaseSteps]]');\n","import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, type ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\nimport { ReleaseSteps } from '../abstract-ops/internal-methods';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n assert(stream._reader === reader);\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n stream._readableStreamController[ReleaseSteps]();\n\n stream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n","import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n","import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamDefaultReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamDefaultReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\nexport function ReadableStreamDefaultReaderRelease(reader: ReadableStreamDefaultReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n}\n\nexport function ReadableStreamDefaultReaderErrorReadRequests(reader: ReadableStreamDefaultReader, e: any) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n","import { reflectCall } from 'lib/helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport assert from '../../stub/assert';\n\ndeclare global {\n interface ArrayBuffer {\n readonly detached: boolean;\n\n transfer(): ArrayBuffer;\n }\n\n function structuredClone(value: T, options: { transfer: ArrayBuffer[] }): T;\n}\n\nexport function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\nexport let TransferArrayBuffer = (O: ArrayBuffer): ArrayBuffer => {\n if (typeof O.transfer === 'function') {\n TransferArrayBuffer = buffer => buffer.transfer();\n } else if (typeof structuredClone === 'function') {\n TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] });\n } else {\n // Not implemented correctly\n TransferArrayBuffer = buffer => buffer;\n }\n return TransferArrayBuffer(O);\n};\n\nexport function CanTransferArrayBuffer(O: ArrayBuffer): boolean {\n return !IsDetachedBuffer(O);\n}\n\nexport let IsDetachedBuffer = (O: ArrayBuffer): boolean => {\n if (typeof O.detached === 'boolean') {\n IsDetachedBuffer = buffer => buffer.detached;\n } else {\n // Not implemented correctly\n IsDetachedBuffer = buffer => buffer.byteLength === 0;\n }\n return IsDetachedBuffer(O);\n};\n\nexport function ArrayBufferSlice(buffer: ArrayBuffer, begin: number, end: number): ArrayBuffer {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n\nexport type MethodName = {\n [P in keyof T]: T[P] extends Function | undefined ? P : never;\n}[keyof T];\n\nexport function GetMethod>(receiver: T, prop: K): T[K] | undefined {\n const func = receiver[prop];\n if (func === undefined || func === null) {\n return undefined;\n }\n if (typeof func !== 'function') {\n throw new TypeError(`${String(prop)} is not a function`);\n }\n return func;\n}\n\nexport interface SyncIteratorRecord {\n iterator: Iterator,\n nextMethod: Iterator['next'],\n done: boolean;\n}\n\nexport interface AsyncIteratorRecord {\n iterator: AsyncIterator,\n nextMethod: AsyncIterator['next'],\n done: boolean;\n}\n\nexport type SyncOrAsyncIteratorRecord = SyncIteratorRecord | AsyncIteratorRecord;\n\nexport function CreateAsyncFromSyncIterator(syncIteratorRecord: SyncIteratorRecord): AsyncIteratorRecord {\n // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%,\n // we use yield* inside an async generator function to achieve the same result.\n\n // Wrap the sync iterator inside a sync iterable, so we can use it with yield*.\n const syncIterable = {\n [Symbol.iterator]: () => syncIteratorRecord.iterator\n };\n // Create an async generator function and immediately invoke it.\n const asyncIterator = (async function* () {\n return yield* syncIterable;\n }());\n // Return as an async iterator record.\n const nextMethod = asyncIterator.next;\n return { iterator: asyncIterator, nextMethod, done: false };\n}\n\n// Aligns with core-js/modules/es.symbol.async-iterator.js\nexport const SymbolAsyncIterator: (typeof Symbol)['asyncIterator'] =\n Symbol.asyncIterator ??\n Symbol.for?.('Symbol.asyncIterator') ??\n '@@asyncIterator';\n\nexport type SyncOrAsyncIterable = Iterable | AsyncIterable;\nexport type SyncOrAsyncIteratorMethod = () => (Iterator | AsyncIterator);\n\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint: 'async',\n method?: SyncOrAsyncIteratorMethod\n): AsyncIteratorRecord;\nfunction GetIterator(\n obj: Iterable,\n hint: 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncIteratorRecord;\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint = 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncOrAsyncIteratorRecord {\n assert(hint === 'sync' || hint === 'async');\n if (method === undefined) {\n if (hint === 'async') {\n method = GetMethod(obj as AsyncIterable, SymbolAsyncIterator);\n if (method === undefined) {\n const syncMethod = GetMethod(obj as Iterable, Symbol.iterator);\n const syncIteratorRecord = GetIterator(obj as Iterable, 'sync', syncMethod);\n return CreateAsyncFromSyncIterator(syncIteratorRecord);\n }\n } else {\n method = GetMethod(obj as Iterable, Symbol.iterator);\n }\n }\n if (method === undefined) {\n throw new TypeError('The object is not iterable');\n }\n const iterator = reflectCall(method, obj, []);\n if (!typeIsObject(iterator)) {\n throw new TypeError('The iterator method must return an object');\n }\n const nextMethod = iterator.next;\n return { iterator, nextMethod, done: false } as SyncOrAsyncIteratorRecord;\n}\n\nexport { GetIterator };\n\nexport function IteratorNext(iteratorRecord: AsyncIteratorRecord): Promise> {\n const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []);\n if (!typeIsObject(result)) {\n throw new TypeError('The iterator.next() method must return an object');\n }\n return result;\n}\n\nexport function IteratorComplete(\n iterResult: IteratorResult\n): iterResult is IteratorReturnResult {\n assert(typeIsObject(iterResult));\n return Boolean(iterResult.done);\n}\n\nexport function IteratorValue(iterResult: IteratorYieldResult): T {\n assert(typeIsObject(iterResult));\n return iterResult.value;\n}\n","/// \n\nimport { SymbolAsyncIterator } from '../../../lib/abstract-ops/ecmascript';\n\n// We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it.\nexport const AsyncIteratorPrototype: AsyncIterable = {\n // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( )\n // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator\n [SymbolAsyncIterator](this: AsyncIterator) {\n return this;\n }\n};\nObject.defineProperty(AsyncIteratorPrototype, SymbolAsyncIterator, { enumerable: false });\n","/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadableStreamDefaultReadResult,\n type ReadRequest\n} from './default-reader';\nimport { ReadableStreamReaderGenericCancel, ReadableStreamReaderGenericRelease } from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterableIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ninterface ReadableStreamAsyncIteratorInstance extends ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nObject.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n","import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: NonShared): NonShared {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer) as NonShared;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n","export type TypedArray =\n | Int8Array\n | Uint8Array\n | Uint8ClampedArray\n | Int16Array\n | Uint16Array\n | Int32Array\n | Uint32Array\n | Float32Array\n | Float64Array;\n\nexport type NonShared = T & {\n buffer: ArrayBuffer;\n}\n\nexport interface ArrayBufferViewConstructor {\n new(buffer: ArrayBuffer, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n}\n\nexport interface TypedArrayConstructor extends ArrayBufferViewConstructor {\n readonly BYTES_PER_ELEMENT: number;\n}\n\nexport type DataViewConstructor = ArrayBufferViewConstructor;\n\nfunction isDataViewConstructor(ctor: Function): ctor is DataViewConstructor {\n return ctor === DataView;\n}\n\nexport function isDataView(view: ArrayBufferView): view is DataView {\n return isDataViewConstructor(view.constructor);\n}\n\nexport function arrayBufferViewElementSize(ctor: ArrayBufferViewConstructor): number {\n if (isDataViewConstructor(ctor)) {\n return 1;\n }\n return (ctor as unknown as TypedArrayConstructor).BYTES_PER_ELEMENT;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n IsReadableStreamDefaultReader,\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n type ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n type ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n type ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport type { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\nimport {\n type ArrayBufferViewConstructor,\n arrayBufferViewElementSize,\n type NonShared,\n type TypedArrayConstructor\n} from '../helpers/array-buffer-view';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: NonShared | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: NonShared): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond');\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBuffer;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor = NonShared> =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: TypedArrayConstructor;\n readerType: 'default' | 'none';\n}\n\ninterface BYOBPullIntoDescriptor = NonShared> {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob' | 'none';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: NonShared): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest>): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n minimumFill: 1,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n if (this._pendingPullIntos.length > 0) {\n const firstPullInto = this._pendingPullIntos.peek();\n firstPullInto.readerType = 'none';\n\n this._pendingPullIntos = new SimpleQueue();\n this._pendingPullIntos.push(firstPullInto);\n }\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableByteStreamController.prototype.close, 'close');\nsetFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableByteStreamController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor>(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n assert(pullIntoDescriptor.readerType !== 'none');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as NonShared, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor>(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n let clonedChunk;\n try {\n clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength);\n } catch (cloneE) {\n ReadableByteStreamControllerError(controller, cloneE);\n throw cloneE;\n }\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength);\n}\n\nfunction ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.readerType === 'none');\n if (firstDescriptor.bytesFilled > 0) {\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n firstDescriptor.buffer,\n firstDescriptor.byteOffset,\n firstDescriptor.bytesFilled\n );\n }\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize;\n const maxAlignedBytes = maxBytesFilled - remainderBytes;\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n assert(pullIntoDescriptor.readerType !== 'none');\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nfunction ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller: ReadableByteStreamController) {\n const reader = controller._controlledReadableByteStream._reader;\n assert(IsReadableStreamDefaultReader(reader));\n while (reader._readRequests.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n const readRequest = reader._readRequests.shift();\n ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest);\n }\n}\n\nexport function ReadableByteStreamControllerPullInto>(\n controller: ReadableByteStreamController,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n const elementSize = arrayBufferViewElementSize(ctor);\n\n const { byteOffset, byteLength } = view;\n\n const minimumFill = min * elementSize;\n assert(minimumFill >= elementSize && minimumFill <= byteLength);\n assert(minimumFill % elementSize === 0);\n\n let buffer: ArrayBuffer;\n try {\n buffer = TransferArrayBuffer(view.buffer);\n } catch (e) {\n readIntoRequest._errorSteps(e);\n return;\n }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset,\n byteLength,\n bytesFilled: 0,\n minimumFill,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled % firstDescriptor.elementSize === 0);\n\n if (firstDescriptor.readerType === 'none') {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n return;\n }\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) {\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n pullIntoDescriptor.buffer,\n end - remainderSize,\n remainderSize\n );\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(\n controller: ReadableByteStreamController,\n chunk: NonShared\n) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const { buffer, byteOffset, byteLength } = chunk;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n if (firstPendingPullInto.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto);\n }\n }\n\n if (ReadableStreamHasDefaultReader(stream)) {\n ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller);\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView as NonShared, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerFillReadRequestFromQueue(\n controller: ReadableByteStreamController,\n readRequest: ReadRequest>\n) {\n assert(controller._queueTotalSize > 0);\n\n const entry = controller._queue.shift();\n controller._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n readRequest._chunkSteps(view as NonShared);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view as NonShared);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: NonShared) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: NonShared) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n","import { assertDictionary, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n\nexport function convertByobReadOptions(\n options: ReadableStreamBYOBReaderReadOptions | null | undefined,\n context: string\n): ValidatedReadableStreamBYOBReaderReadOptions {\n assertDictionary(options, context);\n const min = options?.min ?? 1;\n return {\n min: convertUnsignedLongLongWithEnforceRange(\n min,\n `${context} has member 'min' that`\n )\n };\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, type ReadableByteStream, type ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from './reader-options';\nimport { convertByobReadOptions } from '../validators/reader-options';\nimport { isDataView, type NonShared, type TypedArray } from '../helpers/array-buffer-view';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream as ReadableStream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest>(\n stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest\n): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest> {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(\n view: T,\n options?: ReadableStreamBYOBReaderReadOptions\n ): Promise>;\n read>(\n view: T,\n rawOptions: ReadableStreamBYOBReaderReadOptions | null | undefined = {}\n ): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n let options: ValidatedReadableStreamBYOBReaderReadOptions;\n try {\n options = convertByobReadOptions(rawOptions, 'options');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const min = options.min;\n if (min === 0) {\n return promiseRejectedWith(new TypeError('options.min must be greater than 0'));\n }\n if (!isDataView(view)) {\n if (min > (view as unknown as TypedArray).length) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s length'));\n }\n } else if (min > view.byteLength) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s byteLength'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamBYOBReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamBYOBReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead>(\n reader: ReadableStreamBYOBReader,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n min,\n readIntoRequest\n );\n }\n}\n\nexport function ReadableStreamBYOBReaderRelease(reader: ReadableStreamBYOBReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n}\n\nexport function ReadableStreamBYOBReaderErrorReadIntoRequests(reader: ReadableStreamBYOBReader, e: any) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n","/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * If aborted, returns the reason for aborting.\n */\n readonly reason?: any;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(reason?: any): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n type QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { type AbortController, type AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(WritableStream.prototype.abort, 'abort');\nsetFunctionName(WritableStream.prototype.close, 'close');\nsetFunctionName(WritableStream.prototype.getWriter, 'getWriter');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight\n};\n\nexport type {\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort(reason);\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nsetFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort');\nsetFunctionName(WritableStreamDefaultWriter.prototype.close, 'close');\nsetFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock');\nsetFunctionName(WritableStreamDefaultWriter.prototype.write, 'write');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n return null;\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let writeAlgorithm: (chunk: W) => Promise;\n let closeAlgorithm: () => Promise;\n let abortAlgorithm: (reason: any) => Promise;\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n } else {\n writeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n } else {\n closeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n } else {\n abortAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n return null;\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n","/// \n\nfunction getGlobals(): typeof globalThis | undefined {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n } else if (typeof self !== 'undefined') {\n return self;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n","/// \nimport { globals } from '../globals';\nimport { setFunctionName } from '../lib/helpers/miscellaneous';\n\ninterface DOMException extends Error {\n name: string;\n message: string;\n}\n\ntype DOMExceptionConstructor = new (message?: string, name?: string) => DOMException;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n if ((ctor as DOMExceptionConstructor).name !== 'DOMException') {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Support:\n * - Web browsers\n * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87)\n */\nfunction getFromGlobal(): DOMExceptionConstructor | undefined {\n const ctor = globals?.DOMException;\n return isDOMExceptionConstructor(ctor) ? ctor : undefined;\n}\n\n/**\n * Support:\n * - All platforms\n */\nfunction createPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line @typescript-eslint/no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n setFunctionName(ctor, 'DOMException');\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nconst DOMException: DOMExceptionConstructor = getFromGlobal() || createPolyfill();\n\nexport { DOMException };\n","import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n return null;\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => null) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => null) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest(): null {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n return null;\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any): null {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n\n return null;\n }\n });\n}\n","import type { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, type QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n type ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport type { ValidatedUnderlyingSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n // Do nothing.\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultController.prototype.close, 'close');\nsetFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableStreamDefaultController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n","import {\n CreateReadableByteStream,\n CreateReadableStream,\n type DefaultReadableStream,\n IsReadableStream,\n type ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n type ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n type ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(\n stream: ReadableStream,\n cloneForBranch2: boolean\n): [DefaultReadableStream, DefaultReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: DefaultReadableStream;\n let branch2: DefaultReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader> = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader>) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return null;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: NonShared, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader>(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n","import { typeIsObject } from '../helpers/miscellaneous';\nimport type { ReadableStreamDefaultReadResult } from './default-reader';\n\n/**\n * A common interface for a `ReadadableStream` implementation.\n *\n * @public\n */\nexport interface ReadableStreamLike {\n readonly locked: boolean;\n\n getReader(): ReadableStreamDefaultReaderLike;\n}\n\n/**\n * A common interface for a `ReadableStreamDefaultReader` implementation.\n *\n * @public\n */\nexport interface ReadableStreamDefaultReaderLike {\n readonly closed: Promise;\n\n cancel(reason?: any): Promise;\n\n read(): Promise>;\n\n releaseLock(): void;\n}\n\nexport function isReadableStreamLike(stream: unknown): stream is ReadableStreamLike {\n return typeIsObject(stream) && typeof (stream as ReadableStreamLike).getReader !== 'undefined';\n}\n","import { CreateReadableStream, type DefaultReadableStream } from '../readable-stream';\nimport {\n isReadableStreamLike,\n type ReadableStreamDefaultReaderLike,\n type ReadableStreamLike\n} from './readable-stream-like';\nimport { ReadableStreamDefaultControllerClose, ReadableStreamDefaultControllerEnqueue } from './default-controller';\nimport { GetIterator, GetMethod, IteratorComplete, IteratorNext, IteratorValue } from '../abstract-ops/ecmascript';\nimport { promiseRejectedWith, promiseResolvedWith, reflectCall, transformPromiseWith } from '../helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { noop } from '../../utils';\n\nexport function ReadableStreamFrom(\n source: Iterable | AsyncIterable | ReadableStreamLike\n): DefaultReadableStream {\n if (isReadableStreamLike(source)) {\n return ReadableStreamFromDefaultReader(source.getReader());\n }\n return ReadableStreamFromIterable(source);\n}\n\nexport function ReadableStreamFromIterable(asyncIterable: Iterable | AsyncIterable): DefaultReadableStream {\n let stream: DefaultReadableStream;\n const iteratorRecord = GetIterator(asyncIterable, 'async');\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let nextResult;\n try {\n nextResult = IteratorNext(iteratorRecord);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const nextPromise = promiseResolvedWith(nextResult);\n return transformPromiseWith(nextPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object');\n }\n const done = IteratorComplete(iterResult);\n if (done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = IteratorValue(iterResult);\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n const iterator = iteratorRecord.iterator;\n let returnMethod: (typeof iterator)['return'] | undefined;\n try {\n returnMethod = GetMethod(iterator, 'return');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n if (returnMethod === undefined) {\n return promiseResolvedWith(undefined);\n }\n let returnResult: IteratorResult | Promise>;\n try {\n returnResult = reflectCall(returnMethod, iterator, [reason]);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const returnPromise = promiseResolvedWith(returnResult);\n return transformPromiseWith(returnPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object');\n }\n return undefined;\n });\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n\nexport function ReadableStreamFromDefaultReader(\n reader: ReadableStreamDefaultReaderLike\n): DefaultReadableStream {\n let stream: DefaultReadableStream;\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let readPromise;\n try {\n readPromise = reader.read();\n } catch (e) {\n return promiseRejectedWith(e);\n }\n return transformPromiseWith(readPromise, readResult => {\n if (!typeIsObject(readResult)) {\n throw new TypeError('The promise returned by the reader.read() method must fulfill with an object');\n }\n if (readResult.done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = readResult.value;\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n try {\n return promiseResolvedWith(reader.cancel(reason));\n } catch (e) {\n return promiseRejectedWith(e);\n }\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n","import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n","import { assertDictionary } from './basic';\nimport type {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n","import { assertDictionary } from './basic';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n","import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n","import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, type ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderErrorReadRequests,\n type ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReaderErrorReadIntoRequests,\n type ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { ReadableStreamFrom } from './readable-stream/from';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport type {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList, SymbolAsyncIterator } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions\n} from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport type { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport type { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\nimport type { ReadableStreamDefaultReaderLike, ReadableStreamLike } from './readable-stream/readable-stream-like';\nimport type { NonShared } from './helpers/array-buffer-view';\n\nexport type DefaultReadableStream = ReadableStream & {\n _readableStreamController: ReadableStreamDefaultController\n};\n\nexport type ReadableByteStream = ReadableStream> & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream implements AsyncIterable {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n\n [SymbolAsyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator {\n // Stub implementation, overridden below\n return this.values(options);\n }\n\n /**\n * Creates a new ReadableStream wrapping the provided iterable or async iterable.\n *\n * This can be used to adapt various kinds of objects into a readable stream,\n * such as an array, an async generator, or a Node.js readable stream.\n */\n static from(asyncIterable: Iterable | AsyncIterable | ReadableStreamLike): ReadableStream {\n return ReadableStreamFrom(asyncIterable);\n }\n}\n\nObject.defineProperties(ReadableStream, {\n from: { enumerable: true }\n});\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(ReadableStream.from, 'from');\nsetFunctionName(ReadableStream.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStream.prototype.getReader, 'getReader');\nsetFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough');\nsetFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo');\nsetFunctionName(ReadableStream.prototype.tee, 'tee');\nsetFunctionName(ReadableStream.prototype.values, 'values');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nObject.defineProperty(ReadableStream.prototype, SymbolAsyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n});\n\nexport type {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n ReadableStreamBYOBReaderReadOptions,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions,\n ReadableStreamLike,\n ReadableStreamDefaultReaderLike\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1\n): DefaultReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: DefaultReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n","import type { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\nsetFunctionName(byteLengthSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\nsetFunctionName(countSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const cancel = original?.cancel;\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n cancel: cancel === undefined ?\n undefined :\n convertTransformerCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n\nfunction convertTransformerCancelCallback(\n fn: TransformerCancelCallback,\n original: Transformer,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith,\n uponPromise\n} from './helpers/webidl';\nimport { CreateReadableStream, type DefaultReadableStream, ReadableStream } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: DefaultReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport type {\n Transformer,\n TransformerCancelCallback,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSourceCancelAlgorithm(stream, reason);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n TransformStreamUnblockWrite(stream);\n}\n\nfunction TransformStreamUnblockWrite(stream: TransformStream) {\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _finishPromise: Promise | undefined;\n /** @internal */\n _finishPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _finishPromise_reject?: (reason: any) => void;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n /** @internal */\n _cancelAlgorithm: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(TransformStreamDefaultController.prototype.error, 'error');\nsetFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._finishPromise = undefined;\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm: (chunk: I) => Promise;\n let flushAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n } else {\n transformAlgorithm = chunk => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n }\n\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n } else {\n flushAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n if (transformer.cancel !== undefined) {\n cancelAlgorithm = reason => transformer.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally,\n // we don't run the _cancelAlgorithm again.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerError(readable._readableStreamController, reason);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally,\n // we don't also run the _cancelAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(flushPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerClose(readable._readableStreamController);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\nfunction TransformStreamDefaultSourceCancelAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._writable cannot change after construction, so caching it across a call to user code is safe.\n const writable = stream._writable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or\n // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the\n // _flushAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (writable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, writable._storedError);\n } else {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\nexport function defaultControllerFinishPromiseResolve(controller: TransformStreamDefaultController) {\n if (controller._finishPromise_resolve === undefined) {\n return;\n }\n\n controller._finishPromise_resolve();\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nexport function defaultControllerFinishPromiseReject(controller: TransformStreamDefaultController, reason: any) {\n if (controller._finishPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(controller._finishPromise!);\n controller._finishPromise_reject(reason);\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n","import {\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n ReadableByteStreamController,\n ReadableStream,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultController,\n ReadableStreamDefaultReader,\n TransformStream,\n TransformStreamDefaultController,\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter\n} from './ponyfill';\nimport { globals } from './globals';\n\n// Export\nexport * from './ponyfill';\n\nconst exports = {\n ReadableStream,\n ReadableStreamDefaultController,\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader,\n\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter,\n\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n\n TransformStream,\n TransformStreamDefaultController\n};\n\n// Add classes to global scope\nif (typeof globals !== 'undefined') {\n for (const prop in exports) {\n if (Object.prototype.hasOwnProperty.call(exports, prop)) {\n Object.defineProperty(globals, prop, {\n value: exports[prop as (keyof typeof exports)],\n writable: true,\n configurable: true\n });\n }\n }\n}\n"],"names":["Symbol","_a","queueMicrotask","streamBrandCheckException","defaultControllerBrandCheckException","exports"],"mappings":";;;;;;;;;;;;;IAAA;IAEA,IAAM,cAAc,GAClB,OAAO,MAAM,KAAK,UAAU,IAAI,OAAO,MAAM,CAAC,QAAQ,KAAK,QAAQ;IACjE,IAAA,MAAM;QACN,UAAA,WAAW,IAAI,OAAA,SAAA,CAAA,MAAA,CAAU,WAAW,EAAoB,GAAA,CAAA,CAAA,EAAA;;ICL5D;IACA;AACA;IACA;IACA;AACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;AACA;AA4GA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AS,yBAAyB,CAAC,IAAY,EAAA;IAC7C,IAAA,OAAO,IAAI,SAAS,CAClB,oCAA6B,IAAI,EAAA,wCAAA,CAAwC,CAAC,CAAC;IAC/E;;ICzoBA,IAAMK,SAAO,GAAG;IACd,IAAA,cAAc,EAAA,cAAA;IACd,IAAA,+BAA+B,EAAA,+BAAA;IAC/B,IAAA,4BAA4B,EAAA,4BAAA;IAC5B,IAAA,yBAAyB,EAAA,yBAAA;IACzB,IAAA,2BAA2B,EAAA,2BAAA;IAC3B,IAAA,wBAAwB,EAAA,wBAAA;IAExB,IAAA,cAAc,EAAA,cAAA;IACd,IAAA,+BAA+B,EAAA,+BAAA;IAC/B,IAAA,2BAA2B,EAAA,2BAAA;IAE3B,IAAA,yBAAyB,EAAA,yBAAA;IACzB,IAAA,oBAAoB,EAAA,oBAAA;IAEpB,IAAA,eAAe,EAAA,eAAA;IACf,IAAA,gCAAgC,EAAA,gCAAA;KACjC,CAAC;IAEF;IACA,IAAI,OAAO,OAAO,KAAK,WAAW,EAAE;IAClC,IAAA,KAAK,IAAM,IAAI,IAAIA,SAAO,EAAE;IAC1B,QAAA,IAAI,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAACA,SAAO,EAAE,IAAI,CAAC,EAAE;IACvD,YAAA,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,IAAI,EAAE;IACnC,gBAAA,KAAK,EAAEA,SAAO,CAAC,IAA8B,CAAC;IAC9C,gBAAA,QAAQ,EAAE,IAAI;IACd,gBAAA,YAAY,EAAE,IAAI;IACnB,aAAA,CAAC,CAAC;aACJ;SACF;IACH;;;;;;;;;;;;;;;;;;;;","x_google_ignoreList":[1]} \ No newline at end of file diff --git a/backend/node_modules/web-streams-polyfill/dist/polyfill.min.js b/backend/node_modules/web-streams-polyfill/dist/polyfill.min.js new file mode 100644 index 0000000000000000000000000000000000000000..9dd92121579268ba4be6e5185dd0d30495fe9af6 --- /dev/null +++ b/backend/node_modules/web-streams-polyfill/dist/polyfill.min.js @@ -0,0 +1,9 @@ +/** + * @license + * web-streams-polyfill v3.3.3 + * Copyright 2024 Mattias Buelens, Diwank Singh Tomer and other contributors. + * This code is released under the MIT license. + * SPDX-License-Identifier: MIT + */ +!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports):"function"==typeof define&&define.amd?define(["exports"],r):r((e="undefined"!=typeof globalThis?globalThis:e||self).WebStreamsPolyfill={})}(this,(function(e){"use strict";var r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol:function(e){return"Symbol(".concat(e,")")};function t(e,r){var t,n,o,a,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return a={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function u(u){return function(l){return function(u){if(t)throw new TypeError("Generator is already executing.");for(;a&&(a=0,u[0]&&(i=0)),i;)try{if(t=1,n&&(o=2&u[0]?n.return:u[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,u[1])).done)return o;switch(n=0,o&&(u=[2&u[0],o.value]),u[0]){case 0:case 1:o=u;break;case 4:return i.label++,{value:u[1],done:!1};case 5:i.label++,n=u[1],u=[0];continue;case 7:u=i.ops.pop(),i.trys.pop();continue;default:if(!(o=i.trys,(o=o.length>0&&o[o.length-1])||6!==u[0]&&2!==u[0])){i=0;continue}if(3===u[0]&&(!o||u[1]>o[0]&&u[1]=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(r?"Object is not iterable.":"Symbol.iterator is not defined.")}function o(e){return this instanceof o?(this.v=e,this):new o(e)}function a(e,r,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n,a=t.apply(e,r||[]),i=[];return n={},u("next"),u("throw"),u("return"),n[Symbol.asyncIterator]=function(){return this},n;function u(e){a[e]&&(n[e]=function(r){return new Promise((function(t,n){i.push([e,r,t,n])>1||l(e,r)}))})}function l(e,r){try{(t=a[e](r)).value instanceof o?Promise.resolve(t.value.v).then(s,c):f(i[0][2],t)}catch(e){f(i[0][3],e)}var t}function s(e){l("next",e)}function c(e){l("throw",e)}function f(e,r){e(r),i.shift(),i.length&&l(i[0][0],i[0][1])}}function i(e){var r,t;return r={},n("next"),n("throw",(function(e){throw e})),n("return"),r[Symbol.iterator]=function(){return this},r;function n(n,a){r[n]=e[n]?function(r){return(t=!t)?{value:o(e[n](r)),done:!1}:a?a(r):r}:a}}function u(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r,t=e[Symbol.asyncIterator];return t?t.call(e):(e=n(e),r={},o("next"),o("throw"),o("return"),r[Symbol.asyncIterator]=function(){return this},r);function o(t){r[t]=e[t]&&function(r){return new Promise((function(n,o){(function(e,r,t,n){Promise.resolve(n).then((function(r){e({value:r,done:t})}),r)})(n,o,(r=e[t](r)).done,r.value)}))}}}function l(){}function s(e){return"object"==typeof e&&null!==e||"function"==typeof e}"function"==typeof SuppressedError&&SuppressedError;var c=l;function f(e,r){try{Object.defineProperty(e,"name",{value:r,configurable:!0})}catch(e){}}var d=Promise,b=Promise.prototype.then,p=Promise.reject.bind(d);function h(e){return new d(e)}function m(e){return h((function(r){return r(e)}))}function _(e){return p(e)}function y(e,r,t){return b.call(e,r,t)}function v(e,r,t){y(y(e,r,t),void 0,c)}function g(e,r){v(e,r)}function S(e,r){v(e,void 0,r)}function w(e,r,t){return y(e,r,t)}function R(e){y(e,void 0,c)}var T=function(e){if("function"==typeof queueMicrotask)T=queueMicrotask;else{var r=m(void 0);T=function(e){return y(r,e)}}return T(e)};function P(e,r,t){if("function"!=typeof e)throw new TypeError("Argument is not a function");return Function.prototype.apply.call(e,r,t)}function C(e,r,t){try{return m(P(e,r,t))}catch(e){return _(e)}}var q=function(){function e(){this._cursor=0,this._size=0,this._front={_elements:[],_next:void 0},this._back=this._front,this._cursor=0,this._size=0}return Object.defineProperty(e.prototype,"length",{get:function(){return this._size},enumerable:!1,configurable:!0}),e.prototype.push=function(e){var r=this._back,t=r;16383===r._elements.length&&(t={_elements:[],_next:void 0}),r._elements.push(e),t!==r&&(this._back=t,r._next=t),++this._size},e.prototype.shift=function(){var e=this._front,r=e,t=this._cursor,n=t+1,o=e._elements,a=o[t];return 16384===n&&(r=e._next,n=0),--this._size,this._cursor=n,e!==r&&(this._front=r),o[t]=void 0,a},e.prototype.forEach=function(e){for(var r=this._cursor,t=this._front,n=t._elements;!(r===n.length&&void 0===t._next||r===n.length&&(r=0,0===(n=(t=t._next)._elements).length));)e(n[r]),++r},e.prototype.peek=function(){var e=this._front,r=this._cursor;return e._elements[r]},e}(),E=r("[[AbortSteps]]"),O=r("[[ErrorSteps]]"),W=r("[[CancelSteps]]"),j=r("[[PullSteps]]"),B=r("[[ReleaseSteps]]");function k(e,r){e._ownerReadableStream=r,r._reader=e,"readable"===r._state?D(e):"closed"===r._state?function(e){D(e),M(e)}(e):L(e,r._storedError)}function A(e,r){return Vt(e._ownerReadableStream,r)}function z(e){var r=e._ownerReadableStream;"readable"===r._state?F(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):function(e,r){L(e,r)}(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),r._readableStreamController[B](),r._reader=void 0,e._ownerReadableStream=void 0}function I(e){return new TypeError("Cannot "+e+" a stream using a released reader")}function D(e){e._closedPromise=h((function(r,t){e._closedPromise_resolve=r,e._closedPromise_reject=t}))}function L(e,r){D(e),F(e,r)}function F(e,r){void 0!==e._closedPromise_reject&&(R(e._closedPromise),e._closedPromise_reject(r),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}function M(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}var x=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},Y=Math.trunc||function(e){return e<0?Math.ceil(e):Math.floor(e)};function Q(e,r){if(void 0!==e&&("object"!=typeof(t=e)&&"function"!=typeof t))throw new TypeError("".concat(r," is not an object."));var t}function N(e,r){if("function"!=typeof e)throw new TypeError("".concat(r," is not a function."))}function H(e,r){if(!function(e){return"object"==typeof e&&null!==e||"function"==typeof e}(e))throw new TypeError("".concat(r," is not an object."))}function V(e,r,t){if(void 0===e)throw new TypeError("Parameter ".concat(r," is required in '").concat(t,"'."))}function U(e,r,t){if(void 0===e)throw new TypeError("".concat(r," is required in '").concat(t,"'."))}function G(e){return Number(e)}function X(e){return 0===e?0:e}function J(e,r){var t=Number.MAX_SAFE_INTEGER,n=Number(e);if(n=X(n),!x(n))throw new TypeError("".concat(r," is not a finite number"));if((n=function(e){return X(Y(e))}(n))<0||n>t)throw new TypeError("".concat(r," is outside the accepted range of ").concat(0," to ").concat(t,", inclusive"));return x(n)&&0!==n?n:0}function K(e,r){if(!Nt(e))throw new TypeError("".concat(r," is not a ReadableStream."))}function Z(e){return new ie(e)}function $(e,r){e._reader._readRequests.push(r)}function ee(e,r,t){var n=e._reader._readRequests.shift();t?n._closeSteps():n._chunkSteps(r)}function re(e){return e._reader._readRequests.length}function te(e){var r=e._reader;return void 0!==r&&!!ue(r)}var ne,oe,ae,ie=function(){function ReadableStreamDefaultReader(e){if(V(e,1,"ReadableStreamDefaultReader"),K(e,"First parameter"),Ht(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");k(this,e),this._readRequests=new q}return Object.defineProperty(ReadableStreamDefaultReader.prototype,"closed",{get:function(){return ue(this)?this._closedPromise:_(ce("closed"))},enumerable:!1,configurable:!0}),ReadableStreamDefaultReader.prototype.cancel=function(e){return void 0===e&&(e=void 0),ue(this)?void 0===this._ownerReadableStream?_(I("cancel")):A(this,e):_(ce("cancel"))},ReadableStreamDefaultReader.prototype.read=function(){if(!ue(this))return _(ce("read"));if(void 0===this._ownerReadableStream)return _(I("read from"));var e,r,t=h((function(t,n){e=t,r=n}));return le(this,{_chunkSteps:function(r){return e({value:r,done:!1})},_closeSteps:function(){return e({value:void 0,done:!0})},_errorSteps:function(e){return r(e)}}),t},ReadableStreamDefaultReader.prototype.releaseLock=function(){if(!ue(this))throw ce("releaseLock");void 0!==this._ownerReadableStream&&function(e){z(e);var r=new TypeError("Reader was released");se(e,r)}(this)},ReadableStreamDefaultReader}();function ue(e){return!!s(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readRequests")&&e instanceof ie)}function le(e,r){var t=e._ownerReadableStream;t._disturbed=!0,"closed"===t._state?r._closeSteps():"errored"===t._state?r._errorSteps(t._storedError):t._readableStreamController[j](r)}function se(e,r){var t=e._readRequests;e._readRequests=new q,t.forEach((function(e){e._errorSteps(r)}))}function ce(e){return new TypeError("ReadableStreamDefaultReader.prototype.".concat(e," can only be used on a ReadableStreamDefaultReader"))}function fe(e){return e.slice()}function de(e,r,t,n,o){new Uint8Array(e).set(new Uint8Array(t,n,o),r)}Object.defineProperties(ie.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),f(ie.prototype.cancel,"cancel"),f(ie.prototype.read,"read"),f(ie.prototype.releaseLock,"releaseLock"),"symbol"==typeof r.toStringTag&&Object.defineProperty(ie.prototype,r.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0});var be=function(e){return(be="function"==typeof e.transfer?function(e){return e.transfer()}:"function"==typeof structuredClone?function(e){return structuredClone(e,{transfer:[e]})}:function(e){return e})(e)},pe=function(e){return(pe="boolean"==typeof e.detached?function(e){return e.detached}:function(e){return 0===e.byteLength})(e)};function he(e,r,t){if(e.slice)return e.slice(r,t);var n=t-r,o=new ArrayBuffer(n);return de(o,0,e,r,n),o}function me(e,r){var t=e[r];if(null!=t){if("function"!=typeof t)throw new TypeError("".concat(String(r)," is not a function"));return t}}var _e,ye=null!==(ae=null!==(ne=r.asyncIterator)&&void 0!==ne?ne:null===(oe=r.for)||void 0===oe?void 0:oe.call(r,"Symbol.asyncIterator"))&&void 0!==ae?ae:"@@asyncIterator";function ve(e,l,c){if(void 0===l&&(l="sync"),void 0===c)if("async"===l){if(void 0===(c=me(e,ye)))return function(e){var l,s=((l={})[r.iterator]=function(){return e.iterator},l),c=function(){return a(this,arguments,(function(){return t(this,(function(e){switch(e.label){case 0:return[5,n(i(u(s)))];case 1:case 2:return[4,o.apply(void 0,[e.sent()])];case 3:return[2,e.sent()]}}))}))}();return{iterator:c,nextMethod:c.next,done:!1}}(ve(e,"sync",me(e,r.iterator)))}else c=me(e,r.iterator);if(void 0===c)throw new TypeError("The object is not iterable");var f=P(c,e,[]);if(!s(f))throw new TypeError("The iterator method must return an object");return{iterator:f,nextMethod:f.next,done:!1}}var ge=((_e={})[ye]=function(){return this},_e);Object.defineProperty(ge,ye,{enumerable:!1});var Se=function(){function e(e,r){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=e,this._preventCancel=r}return e.prototype.next=function(){var e=this,r=function(){return e._nextSteps()};return this._ongoingPromise=this._ongoingPromise?w(this._ongoingPromise,r,r):r(),this._ongoingPromise},e.prototype.return=function(e){var r=this,t=function(){return r._returnSteps(e)};return this._ongoingPromise?w(this._ongoingPromise,t,t):t()},e.prototype._nextSteps=function(){var e=this;if(this._isFinished)return Promise.resolve({value:void 0,done:!0});var r,t,n=this._reader,o=h((function(e,n){r=e,t=n}));return le(n,{_chunkSteps:function(t){e._ongoingPromise=void 0,T((function(){return r({value:t,done:!1})}))},_closeSteps:function(){e._ongoingPromise=void 0,e._isFinished=!0,z(n),r({value:void 0,done:!0})},_errorSteps:function(r){e._ongoingPromise=void 0,e._isFinished=!0,z(n),t(r)}}),o},e.prototype._returnSteps=function(e){if(this._isFinished)return Promise.resolve({value:e,done:!0});this._isFinished=!0;var r=this._reader;if(!this._preventCancel){var t=A(r,e);return z(r),w(t,(function(){return{value:e,done:!0}}))}return z(r),m({value:e,done:!0})},e}(),we={next:function(){return Re(this)?this._asyncIteratorImpl.next():_(Te("next"))},return:function(e){return Re(this)?this._asyncIteratorImpl.return(e):_(Te("return"))}};function Re(e){if(!s(e))return!1;if(!Object.prototype.hasOwnProperty.call(e,"_asyncIteratorImpl"))return!1;try{return e._asyncIteratorImpl instanceof Se}catch(e){return!1}}function Te(e){return new TypeError("ReadableStreamAsyncIterator.".concat(e," can only be used on a ReadableSteamAsyncIterator"))}Object.setPrototypeOf(we,ge);var Pe=Number.isNaN||function(e){return e!=e};function Ce(e){var r=he(e.buffer,e.byteOffset,e.byteOffset+e.byteLength);return new Uint8Array(r)}function qe(e){var r=e._queue.shift();return e._queueTotalSize-=r.size,e._queueTotalSize<0&&(e._queueTotalSize=0),r.value}function Ee(e,r,t){if("number"!=typeof(n=t)||Pe(n)||n<0||t===1/0)throw new RangeError("Size must be a finite, non-NaN, non-negative number.");var n;e._queue.push({value:r,size:t}),e._queueTotalSize+=t}function Oe(e){e._queue=new q,e._queueTotalSize=0}function We(e){return e===DataView}var je=function(){function ReadableStreamBYOBRequest(){throw new TypeError("Illegal constructor")}return Object.defineProperty(ReadableStreamBYOBRequest.prototype,"view",{get:function(){if(!Ae(this))throw ir("view");return this._view},enumerable:!1,configurable:!0}),ReadableStreamBYOBRequest.prototype.respond=function(e){if(!Ae(this))throw ir("respond");if(V(e,1,"respond"),e=J(e,"First parameter"),void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");if(pe(this._view.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be used as a response");nr(this._associatedReadableByteStreamController,e)},ReadableStreamBYOBRequest.prototype.respondWithNewView=function(e){if(!Ae(this))throw ir("respondWithNewView");if(V(e,1,"respondWithNewView"),!ArrayBuffer.isView(e))throw new TypeError("You can only respond with array buffer views");if(void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");if(pe(e.buffer))throw new TypeError("The given view's buffer has been detached and so cannot be used as a response");or(this._associatedReadableByteStreamController,e)},ReadableStreamBYOBRequest}();Object.defineProperties(je.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),f(je.prototype.respond,"respond"),f(je.prototype.respondWithNewView,"respondWithNewView"),"symbol"==typeof r.toStringTag&&Object.defineProperty(je.prototype,r.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});var Be=function(){function ReadableByteStreamController(){throw new TypeError("Illegal constructor")}return Object.defineProperty(ReadableByteStreamController.prototype,"byobRequest",{get:function(){if(!ke(this))throw ur("byobRequest");return rr(this)},enumerable:!1,configurable:!0}),Object.defineProperty(ReadableByteStreamController.prototype,"desiredSize",{get:function(){if(!ke(this))throw ur("desiredSize");return tr(this)},enumerable:!1,configurable:!0}),ReadableByteStreamController.prototype.close=function(){if(!ke(this))throw ur("close");if(this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");var e=this._controlledReadableByteStream._state;if("readable"!==e)throw new TypeError("The stream (in ".concat(e," state) is not in the readable state and cannot be closed"));Ke(this)},ReadableByteStreamController.prototype.enqueue=function(e){if(!ke(this))throw ur("enqueue");if(V(e,1,"enqueue"),!ArrayBuffer.isView(e))throw new TypeError("chunk must be an array buffer view");if(0===e.byteLength)throw new TypeError("chunk must have non-zero byteLength");if(0===e.buffer.byteLength)throw new TypeError("chunk's buffer must have non-zero byteLength");if(this._closeRequested)throw new TypeError("stream is closed or draining");var r=this._controlledReadableByteStream._state;if("readable"!==r)throw new TypeError("The stream (in ".concat(r," state) is not in the readable state and cannot be enqueued to"));Ze(this,e)},ReadableByteStreamController.prototype.error=function(e){if(void 0===e&&(e=void 0),!ke(this))throw ur("error");$e(this,e)},ReadableByteStreamController.prototype[W]=function(e){Ie(this),Oe(this);var r=this._cancelAlgorithm(e);return Je(this),r},ReadableByteStreamController.prototype[j]=function(e){var r=this._controlledReadableByteStream;if(this._queueTotalSize>0)er(this,e);else{var t=this._autoAllocateChunkSize;if(void 0!==t){var n=void 0;try{n=new ArrayBuffer(t)}catch(r){return void e._errorSteps(r)}var o={buffer:n,bufferByteLength:t,byteOffset:0,byteLength:t,bytesFilled:0,minimumFill:1,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(o)}$(r,e),ze(this)}},ReadableByteStreamController.prototype[B]=function(){if(this._pendingPullIntos.length>0){var e=this._pendingPullIntos.peek();e.readerType="none",this._pendingPullIntos=new q,this._pendingPullIntos.push(e)}},ReadableByteStreamController}();function ke(e){return!!s(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableByteStream")&&e instanceof Be)}function Ae(e){return!!s(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_associatedReadableByteStreamController")&&e instanceof je)}function ze(e){var r=function(e){var r=e._controlledReadableByteStream;if("readable"!==r._state)return!1;if(e._closeRequested)return!1;if(!e._started)return!1;if(te(r)&&re(r)>0)return!0;if(dr(r)&&fr(r)>0)return!0;var t=tr(e);if(t>0)return!0;return!1}(e);r&&(e._pulling?e._pullAgain=!0:(e._pulling=!0,v(e._pullAlgorithm(),(function(){return e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,ze(e)),null}),(function(r){return $e(e,r),null}))))}function Ie(e){He(e),e._pendingPullIntos=new q}function De(e,r){var t=!1;"closed"===e._state&&(t=!0);var n=Le(r);"default"===r.readerType?ee(e,n,t):function(e,r,t){var n=e._reader,o=n._readIntoRequests.shift();t?o._closeSteps(r):o._chunkSteps(r)}(e,n,t)}function Le(e){var r=e.bytesFilled,t=e.elementSize;return new e.viewConstructor(e.buffer,e.byteOffset,r/t)}function Fe(e,r,t,n){e._queue.push({buffer:r,byteOffset:t,byteLength:n}),e._queueTotalSize+=n}function Me(e,r,t,n){var o;try{o=he(r,t,t+n)}catch(r){throw $e(e,r),r}Fe(e,o,0,n)}function xe(e,r){r.bytesFilled>0&&Me(e,r.buffer,r.byteOffset,r.bytesFilled),Xe(e)}function Ye(e,r){var t=Math.min(e._queueTotalSize,r.byteLength-r.bytesFilled),n=r.bytesFilled+t,o=t,a=!1,i=n-n%r.elementSize;i>=r.minimumFill&&(o=i-r.bytesFilled,a=!0);for(var u=e._queue;o>0;){var l=u.peek(),s=Math.min(o,l.byteLength),c=r.byteOffset+r.bytesFilled;de(r.buffer,c,l.buffer,l.byteOffset,s),l.byteLength===s?u.shift():(l.byteOffset+=s,l.byteLength-=s),e._queueTotalSize-=s,Qe(e,s,r),o-=s}return a}function Qe(e,r,t){t.bytesFilled+=r}function Ne(e){0===e._queueTotalSize&&e._closeRequested?(Je(e),Ut(e._controlledReadableByteStream)):ze(e)}function He(e){null!==e._byobRequest&&(e._byobRequest._associatedReadableByteStreamController=void 0,e._byobRequest._view=null,e._byobRequest=null)}function Ve(e){for(;e._pendingPullIntos.length>0;){if(0===e._queueTotalSize)return;var r=e._pendingPullIntos.peek();Ye(e,r)&&(Xe(e),De(e._controlledReadableByteStream,r))}}function Ue(e,r,t,n){var o,a=e._controlledReadableByteStream,i=r.constructor,u=function(e){return We(e)?1:e.BYTES_PER_ELEMENT}(i),l=r.byteOffset,s=r.byteLength,c=t*u;try{o=be(r.buffer)}catch(b){return void n._errorSteps(b)}var f={buffer:o,bufferByteLength:o.byteLength,byteOffset:l,byteLength:s,bytesFilled:0,minimumFill:c,elementSize:u,viewConstructor:i,readerType:"byob"};if(e._pendingPullIntos.length>0)return e._pendingPullIntos.push(f),void cr(a,n);if("closed"!==a._state){if(e._queueTotalSize>0){if(Ye(e,f)){var d=Le(f);return Ne(e),void n._chunkSteps(d)}if(e._closeRequested){var b=new TypeError("Insufficient bytes to fill elements in the given buffer");return $e(e,b),void n._errorSteps(b)}}e._pendingPullIntos.push(f),cr(a,n),ze(e)}else{var p=new i(f.buffer,f.byteOffset,0);n._closeSteps(p)}}function Ge(e,r){var t=e._pendingPullIntos.peek();He(e),"closed"===e._controlledReadableByteStream._state?function(e,r){"none"===r.readerType&&Xe(e);var t=e._controlledReadableByteStream;if(dr(t))for(;fr(t)>0;)De(t,Xe(e))}(e,t):function(e,r,t){if(Qe(0,r,t),"none"===t.readerType)return xe(e,t),void Ve(e);if(!(t.bytesFilled0){var o=t.byteOffset+t.bytesFilled;Me(e,t.buffer,o-n,n)}t.bytesFilled-=n,De(e._controlledReadableByteStream,t),Ve(e)}}(e,r,t),ze(e)}function Xe(e){return e._pendingPullIntos.shift()}function Je(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0}function Ke(e){var r=e._controlledReadableByteStream;if(!e._closeRequested&&"readable"===r._state)if(e._queueTotalSize>0)e._closeRequested=!0;else{if(e._pendingPullIntos.length>0){var t=e._pendingPullIntos.peek();if(t.bytesFilled%t.elementSize!=0){var n=new TypeError("Insufficient bytes to fill elements in the given buffer");throw $e(e,n),n}}Je(e),Ut(r)}}function Ze(e,r){var t=e._controlledReadableByteStream;if(!e._closeRequested&&"readable"===t._state){var n=r.buffer,o=r.byteOffset,a=r.byteLength;if(pe(n))throw new TypeError("chunk's buffer is detached and so cannot be enqueued");var i=be(n);if(e._pendingPullIntos.length>0){var u=e._pendingPullIntos.peek();if(pe(u.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be filled with an enqueued chunk");He(e),u.buffer=be(u.buffer),"none"===u.readerType&&xe(e,u)}if(te(t))if(function(e){for(var r=e._controlledReadableByteStream._reader;r._readRequests.length>0;){if(0===e._queueTotalSize)return;er(e,r._readRequests.shift())}}(e),0===re(t))Fe(e,i,o,a);else e._pendingPullIntos.length>0&&Xe(e),ee(t,new Uint8Array(i,o,a),!1);else dr(t)?(Fe(e,i,o,a),Ve(e)):Fe(e,i,o,a);ze(e)}}function $e(e,r){var t=e._controlledReadableByteStream;"readable"===t._state&&(Ie(e),Oe(e),Je(e),Gt(t,r))}function er(e,r){var t=e._queue.shift();e._queueTotalSize-=t.byteLength,Ne(e);var n=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);r._chunkSteps(n)}function rr(e){if(null===e._byobRequest&&e._pendingPullIntos.length>0){var r=e._pendingPullIntos.peek(),t=new Uint8Array(r.buffer,r.byteOffset+r.bytesFilled,r.byteLength-r.bytesFilled),n=Object.create(je.prototype);!function(e,r,t){e._associatedReadableByteStreamController=r,e._view=t}(n,e,t),e._byobRequest=n}return e._byobRequest}function tr(e){var r=e._controlledReadableByteStream._state;return"errored"===r?null:"closed"===r?0:e._strategyHWM-e._queueTotalSize}function nr(e,r){var t=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==r)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream")}else{if(0===r)throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");if(t.bytesFilled+r>t.byteLength)throw new RangeError("bytesWritten out of range")}t.buffer=be(t.buffer),Ge(e,r)}function or(e,r){var t=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==r.byteLength)throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream")}else if(0===r.byteLength)throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");if(t.byteOffset+t.bytesFilled!==r.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(t.bufferByteLength!==r.buffer.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");if(t.bytesFilled+r.byteLength>t.byteLength)throw new RangeError("The region specified by view is larger than byobRequest");var n=r.byteLength;t.buffer=be(r.buffer),Ge(e,n)}function ar(e,r,t,n,o,a,i){r._controlledReadableByteStream=e,r._pullAgain=!1,r._pulling=!1,r._byobRequest=null,r._queue=r._queueTotalSize=void 0,Oe(r),r._closeRequested=!1,r._started=!1,r._strategyHWM=a,r._pullAlgorithm=n,r._cancelAlgorithm=o,r._autoAllocateChunkSize=i,r._pendingPullIntos=new q,e._readableStreamController=r,v(m(t()),(function(){return r._started=!0,ze(r),null}),(function(e){return $e(r,e),null}))}function ir(e){return new TypeError("ReadableStreamBYOBRequest.prototype.".concat(e," can only be used on a ReadableStreamBYOBRequest"))}function ur(e){return new TypeError("ReadableByteStreamController.prototype.".concat(e," can only be used on a ReadableByteStreamController"))}function lr(e,r){if("byob"!==(e="".concat(e)))throw new TypeError("".concat(r," '").concat(e,"' is not a valid enumeration value for ReadableStreamReaderMode"));return e}function sr(e){return new br(e)}function cr(e,r){e._reader._readIntoRequests.push(r)}function fr(e){return e._reader._readIntoRequests.length}function dr(e){var r=e._reader;return void 0!==r&&!!pr(r)}Object.defineProperties(Be.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),f(Be.prototype.close,"close"),f(Be.prototype.enqueue,"enqueue"),f(Be.prototype.error,"error"),"symbol"==typeof r.toStringTag&&Object.defineProperty(Be.prototype,r.toStringTag,{value:"ReadableByteStreamController",configurable:!0});var br=function(){function ReadableStreamBYOBReader(e){if(V(e,1,"ReadableStreamBYOBReader"),K(e,"First parameter"),Ht(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!ke(e._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");k(this,e),this._readIntoRequests=new q}return Object.defineProperty(ReadableStreamBYOBReader.prototype,"closed",{get:function(){return pr(this)?this._closedPromise:_(_r("closed"))},enumerable:!1,configurable:!0}),ReadableStreamBYOBReader.prototype.cancel=function(e){return void 0===e&&(e=void 0),pr(this)?void 0===this._ownerReadableStream?_(I("cancel")):A(this,e):_(_r("cancel"))},ReadableStreamBYOBReader.prototype.read=function(e,r){if(void 0===r&&(r={}),!pr(this))return _(_r("read"));if(!ArrayBuffer.isView(e))return _(new TypeError("view must be an array buffer view"));if(0===e.byteLength)return _(new TypeError("view must have non-zero byteLength"));if(0===e.buffer.byteLength)return _(new TypeError("view's buffer must have non-zero byteLength"));if(pe(e.buffer))return _(new TypeError("view's buffer has been detached"));var t;try{t=function(e,r){var t;return Q(e,r),{min:J(null!==(t=null==e?void 0:e.min)&&void 0!==t?t:1,"".concat(r," has member 'min' that"))}}(r,"options")}catch(e){return _(e)}var n,o,a=t.min;if(0===a)return _(new TypeError("options.min must be greater than 0"));if(function(e){return We(e.constructor)}(e)){if(a>e.byteLength)return _(new RangeError("options.min must be less than or equal to view's byteLength"))}else if(a>e.length)return _(new RangeError("options.min must be less than or equal to view's length"));if(void 0===this._ownerReadableStream)return _(I("read from"));var i=h((function(e,r){n=e,o=r}));return hr(this,e,a,{_chunkSteps:function(e){return n({value:e,done:!1})},_closeSteps:function(e){return n({value:e,done:!0})},_errorSteps:function(e){return o(e)}}),i},ReadableStreamBYOBReader.prototype.releaseLock=function(){if(!pr(this))throw _r("releaseLock");void 0!==this._ownerReadableStream&&function(e){z(e);var r=new TypeError("Reader was released");mr(e,r)}(this)},ReadableStreamBYOBReader}();function pr(e){return!!s(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readIntoRequests")&&e instanceof br)}function hr(e,r,t,n){var o=e._ownerReadableStream;o._disturbed=!0,"errored"===o._state?n._errorSteps(o._storedError):Ue(o._readableStreamController,r,t,n)}function mr(e,r){var t=e._readIntoRequests;e._readIntoRequests=new q,t.forEach((function(e){e._errorSteps(r)}))}function _r(e){return new TypeError("ReadableStreamBYOBReader.prototype.".concat(e," can only be used on a ReadableStreamBYOBReader"))}function yr(e,r){var t=e.highWaterMark;if(void 0===t)return r;if(Pe(t)||t<0)throw new RangeError("Invalid highWaterMark");return t}function vr(e){var r=e.size;return r||function(){return 1}}function gr(e,r){Q(e,r);var t=null==e?void 0:e.highWaterMark,n=null==e?void 0:e.size;return{highWaterMark:void 0===t?void 0:G(t),size:void 0===n?void 0:Sr(n,"".concat(r," has member 'size' that"))}}function Sr(e,r){return N(e,r),function(r){return G(e(r))}}function wr(e,r,t){return N(e,t),function(t){return C(e,r,[t])}}function Rr(e,r,t){return N(e,t),function(){return C(e,r,[])}}function Tr(e,r,t){return N(e,t),function(t){return P(e,r,[t])}}function Pr(e,r,t){return N(e,t),function(t,n){return C(e,r,[t,n])}}function Cr(e,r){if(!jr(e))throw new TypeError("".concat(r," is not a WritableStream."))}Object.defineProperties(br.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),f(br.prototype.cancel,"cancel"),f(br.prototype.read,"read"),f(br.prototype.releaseLock,"releaseLock"),"symbol"==typeof r.toStringTag&&Object.defineProperty(br.prototype,r.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});var qr="function"==typeof AbortController;var Er=function(){function WritableStream(e,r){void 0===e&&(e={}),void 0===r&&(r={}),void 0===e?e=null:H(e,"First parameter");var t=gr(r,"Second parameter"),n=function(e,r){Q(e,r);var t=null==e?void 0:e.abort,n=null==e?void 0:e.close,o=null==e?void 0:e.start,a=null==e?void 0:e.type,i=null==e?void 0:e.write;return{abort:void 0===t?void 0:wr(t,e,"".concat(r," has member 'abort' that")),close:void 0===n?void 0:Rr(n,e,"".concat(r," has member 'close' that")),start:void 0===o?void 0:Tr(o,e,"".concat(r," has member 'start' that")),write:void 0===i?void 0:Pr(i,e,"".concat(r," has member 'write' that")),type:a}}(e,"First parameter");if(Wr(this),void 0!==n.type)throw new RangeError("Invalid type is specified");var o=vr(t);!function(e,r,t,n){var o,a,i,u,l=Object.create(Xr.prototype);o=void 0!==r.start?function(){return r.start(l)}:function(){};a=void 0!==r.write?function(e){return r.write(e,l)}:function(){return m(void 0)};i=void 0!==r.close?function(){return r.close()}:function(){return m(void 0)};u=void 0!==r.abort?function(e){return r.abort(e)}:function(){return m(void 0)};Kr(e,l,o,a,i,u,t,n)}(this,n,yr(t,1),o)}return Object.defineProperty(WritableStream.prototype,"locked",{get:function(){if(!jr(this))throw ot("locked");return Br(this)},enumerable:!1,configurable:!0}),WritableStream.prototype.abort=function(e){return void 0===e&&(e=void 0),jr(this)?Br(this)?_(new TypeError("Cannot abort a stream that already has a writer")):kr(this,e):_(ot("abort"))},WritableStream.prototype.close=function(){return jr(this)?Br(this)?_(new TypeError("Cannot close a stream that already has a writer")):Lr(this)?_(new TypeError("Cannot close an already-closing stream")):Ar(this):_(ot("close"))},WritableStream.prototype.getWriter=function(){if(!jr(this))throw ot("getWriter");return Or(this)},WritableStream}();function Or(e){return new xr(e)}function Wr(e){e._state="writable",e._storedError=void 0,e._writer=void 0,e._writableStreamController=void 0,e._writeRequests=new q,e._inFlightWriteRequest=void 0,e._closeRequest=void 0,e._inFlightCloseRequest=void 0,e._pendingAbortRequest=void 0,e._backpressure=!1}function jr(e){return!!s(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_writableStreamController")&&e instanceof Er)}function Br(e){return void 0!==e._writer}function kr(e,r){var t;if("closed"===e._state||"errored"===e._state)return m(void 0);e._writableStreamController._abortReason=r,null===(t=e._writableStreamController._abortController)||void 0===t||t.abort(r);var n=e._state;if("closed"===n||"errored"===n)return m(void 0);if(void 0!==e._pendingAbortRequest)return e._pendingAbortRequest._promise;var o=!1;"erroring"===n&&(o=!0,r=void 0);var a=h((function(t,n){e._pendingAbortRequest={_promise:void 0,_resolve:t,_reject:n,_reason:r,_wasAlreadyErroring:o}}));return e._pendingAbortRequest._promise=a,o||Ir(e,r),a}function Ar(e){var r=e._state;if("closed"===r||"errored"===r)return _(new TypeError("The stream (in ".concat(r," state) is not in the writable state and cannot be closed")));var t,n=h((function(r,t){var n={_resolve:r,_reject:t};e._closeRequest=n})),o=e._writer;return void 0!==o&&e._backpressure&&"writable"===r&&mt(o),Ee(t=e._writableStreamController,Gr,0),et(t),n}function zr(e,r){"writable"!==e._state?Dr(e):Ir(e,r)}function Ir(e,r){var t=e._writableStreamController;e._state="erroring",e._storedError=r;var n=e._writer;void 0!==n&&Hr(n,r),!function(e){if(void 0===e._inFlightWriteRequest&&void 0===e._inFlightCloseRequest)return!1;return!0}(e)&&t._started&&Dr(e)}function Dr(e){e._state="errored",e._writableStreamController[O]();var r=e._storedError;if(e._writeRequests.forEach((function(e){e._reject(r)})),e._writeRequests=new q,void 0!==e._pendingAbortRequest){var t=e._pendingAbortRequest;if(e._pendingAbortRequest=void 0,t._wasAlreadyErroring)return t._reject(r),void Fr(e);v(e._writableStreamController[E](t._reason),(function(){return t._resolve(),Fr(e),null}),(function(r){return t._reject(r),Fr(e),null}))}else Fr(e)}function Lr(e){return void 0!==e._closeRequest||void 0!==e._inFlightCloseRequest}function Fr(e){void 0!==e._closeRequest&&(e._closeRequest._reject(e._storedError),e._closeRequest=void 0);var r=e._writer;void 0!==r&&ct(r,e._storedError)}function Mr(e,r){var t=e._writer;void 0!==t&&r!==e._backpressure&&(r?function(e){dt(e)}(t):mt(t)),e._backpressure=r}Object.defineProperties(Er.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),f(Er.prototype.abort,"abort"),f(Er.prototype.close,"close"),f(Er.prototype.getWriter,"getWriter"),"symbol"==typeof r.toStringTag&&Object.defineProperty(Er.prototype,r.toStringTag,{value:"WritableStream",configurable:!0});var xr=function(){function WritableStreamDefaultWriter(e){if(V(e,1,"WritableStreamDefaultWriter"),Cr(e,"First parameter"),Br(e))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=e,e._writer=this;var r,t=e._state;if("writable"===t)!Lr(e)&&e._backpressure?dt(this):pt(this),lt(this);else if("erroring"===t)bt(this,e._storedError),lt(this);else if("closed"===t)pt(this),lt(r=this),ft(r);else{var n=e._storedError;bt(this,n),st(this,n)}}return Object.defineProperty(WritableStreamDefaultWriter.prototype,"closed",{get:function(){return Yr(this)?this._closedPromise:_(it("closed"))},enumerable:!1,configurable:!0}),Object.defineProperty(WritableStreamDefaultWriter.prototype,"desiredSize",{get:function(){if(!Yr(this))throw it("desiredSize");if(void 0===this._ownerWritableStream)throw ut("desiredSize");return function(e){var r=e._ownerWritableStream,t=r._state;if("errored"===t||"erroring"===t)return null;if("closed"===t)return 0;return $r(r._writableStreamController)}(this)},enumerable:!1,configurable:!0}),Object.defineProperty(WritableStreamDefaultWriter.prototype,"ready",{get:function(){return Yr(this)?this._readyPromise:_(it("ready"))},enumerable:!1,configurable:!0}),WritableStreamDefaultWriter.prototype.abort=function(e){return void 0===e&&(e=void 0),Yr(this)?void 0===this._ownerWritableStream?_(ut("abort")):function(e,r){return kr(e._ownerWritableStream,r)}(this,e):_(it("abort"))},WritableStreamDefaultWriter.prototype.close=function(){if(!Yr(this))return _(it("close"));var e=this._ownerWritableStream;return void 0===e?_(ut("close")):Lr(e)?_(new TypeError("Cannot close an already-closing stream")):Qr(this)},WritableStreamDefaultWriter.prototype.releaseLock=function(){if(!Yr(this))throw it("releaseLock");void 0!==this._ownerWritableStream&&Vr(this)},WritableStreamDefaultWriter.prototype.write=function(e){return void 0===e&&(e=void 0),Yr(this)?void 0===this._ownerWritableStream?_(ut("write to")):Ur(this,e):_(it("write"))},WritableStreamDefaultWriter}();function Yr(e){return!!s(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_ownerWritableStream")&&e instanceof xr)}function Qr(e){return Ar(e._ownerWritableStream)}function Nr(e,r){"pending"===e._closedPromiseState?ct(e,r):function(e,r){st(e,r)}(e,r)}function Hr(e,r){"pending"===e._readyPromiseState?ht(e,r):function(e,r){bt(e,r)}(e,r)}function Vr(e){var r=e._ownerWritableStream,t=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");Hr(e,t),Nr(e,t),r._writer=void 0,e._ownerWritableStream=void 0}function Ur(e,r){var t=e._ownerWritableStream,n=t._writableStreamController,o=function(e,r){try{return e._strategySizeAlgorithm(r)}catch(r){return rt(e,r),1}}(n,r);if(t!==e._ownerWritableStream)return _(ut("write to"));var a=t._state;if("errored"===a)return _(t._storedError);if(Lr(t)||"closed"===a)return _(new TypeError("The stream is closing or closed and cannot be written to"));if("erroring"===a)return _(t._storedError);var i=function(e){return h((function(r,t){var n={_resolve:r,_reject:t};e._writeRequests.push(n)}))}(t);return function(e,r,t){try{Ee(e,r,t)}catch(r){return void rt(e,r)}var n=e._controlledWritableStream;if(!Lr(n)&&"writable"===n._state){Mr(n,tt(e))}et(e)}(n,r,o),i}Object.defineProperties(xr.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),f(xr.prototype.abort,"abort"),f(xr.prototype.close,"close"),f(xr.prototype.releaseLock,"releaseLock"),f(xr.prototype.write,"write"),"symbol"==typeof r.toStringTag&&Object.defineProperty(xr.prototype,r.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});var Gr={},Xr=function(){function WritableStreamDefaultController(){throw new TypeError("Illegal constructor")}return Object.defineProperty(WritableStreamDefaultController.prototype,"abortReason",{get:function(){if(!Jr(this))throw at("abortReason");return this._abortReason},enumerable:!1,configurable:!0}),Object.defineProperty(WritableStreamDefaultController.prototype,"signal",{get:function(){if(!Jr(this))throw at("signal");if(void 0===this._abortController)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal},enumerable:!1,configurable:!0}),WritableStreamDefaultController.prototype.error=function(e){if(void 0===e&&(e=void 0),!Jr(this))throw at("error");"writable"===this._controlledWritableStream._state&&nt(this,e)},WritableStreamDefaultController.prototype[E]=function(e){var r=this._abortAlgorithm(e);return Zr(this),r},WritableStreamDefaultController.prototype[O]=function(){Oe(this)},WritableStreamDefaultController}();function Jr(e){return!!s(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledWritableStream")&&e instanceof Xr)}function Kr(e,r,t,n,o,a,i,u){r._controlledWritableStream=e,e._writableStreamController=r,r._queue=void 0,r._queueTotalSize=void 0,Oe(r),r._abortReason=void 0,r._abortController=function(){if(qr)return new AbortController}(),r._started=!1,r._strategySizeAlgorithm=u,r._strategyHWM=i,r._writeAlgorithm=n,r._closeAlgorithm=o,r._abortAlgorithm=a;var l=tt(r);Mr(e,l),v(m(t()),(function(){return r._started=!0,et(r),null}),(function(t){return r._started=!0,zr(e,t),null}))}function Zr(e){e._writeAlgorithm=void 0,e._closeAlgorithm=void 0,e._abortAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function $r(e){return e._strategyHWM-e._queueTotalSize}function et(e){var r=e._controlledWritableStream;if(e._started&&void 0===r._inFlightWriteRequest)if("erroring"!==r._state){if(0!==e._queue.length){var t=e._queue.peek().value;t===Gr?function(e){var r=e._controlledWritableStream;(function(e){e._inFlightCloseRequest=e._closeRequest,e._closeRequest=void 0})(r),qe(e);var t=e._closeAlgorithm();Zr(e),v(t,(function(){return function(e){e._inFlightCloseRequest._resolve(void 0),e._inFlightCloseRequest=void 0,"erroring"===e._state&&(e._storedError=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._resolve(),e._pendingAbortRequest=void 0)),e._state="closed";var r=e._writer;void 0!==r&&ft(r)}(r),null}),(function(e){return function(e,r){e._inFlightCloseRequest._reject(r),e._inFlightCloseRequest=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._reject(r),e._pendingAbortRequest=void 0),zr(e,r)}(r,e),null}))}(e):function(e,r){var t=e._controlledWritableStream;!function(e){e._inFlightWriteRequest=e._writeRequests.shift()}(t);var n=e._writeAlgorithm(r);v(n,(function(){!function(e){e._inFlightWriteRequest._resolve(void 0),e._inFlightWriteRequest=void 0}(t);var r=t._state;if(qe(e),!Lr(t)&&"writable"===r){var n=tt(e);Mr(t,n)}return et(e),null}),(function(r){return"writable"===t._state&&Zr(e),function(e,r){e._inFlightWriteRequest._reject(r),e._inFlightWriteRequest=void 0,zr(e,r)}(t,r),null}))}(e,t)}}else Dr(r)}function rt(e,r){"writable"===e._controlledWritableStream._state&&nt(e,r)}function tt(e){return $r(e)<=0}function nt(e,r){var t=e._controlledWritableStream;Zr(e),Ir(t,r)}function ot(e){return new TypeError("WritableStream.prototype.".concat(e," can only be used on a WritableStream"))}function at(e){return new TypeError("WritableStreamDefaultController.prototype.".concat(e," can only be used on a WritableStreamDefaultController"))}function it(e){return new TypeError("WritableStreamDefaultWriter.prototype.".concat(e," can only be used on a WritableStreamDefaultWriter"))}function ut(e){return new TypeError("Cannot "+e+" a stream using a released writer")}function lt(e){e._closedPromise=h((function(r,t){e._closedPromise_resolve=r,e._closedPromise_reject=t,e._closedPromiseState="pending"}))}function st(e,r){lt(e),ct(e,r)}function ct(e,r){void 0!==e._closedPromise_reject&&(R(e._closedPromise),e._closedPromise_reject(r),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="rejected")}function ft(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="resolved")}function dt(e){e._readyPromise=h((function(r,t){e._readyPromise_resolve=r,e._readyPromise_reject=t})),e._readyPromiseState="pending"}function bt(e,r){dt(e),ht(e,r)}function pt(e){dt(e),mt(e)}function ht(e,r){void 0!==e._readyPromise_reject&&(R(e._readyPromise),e._readyPromise_reject(r),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="rejected")}function mt(e){void 0!==e._readyPromise_resolve&&(e._readyPromise_resolve(void 0),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="fulfilled")}Object.defineProperties(Xr.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),"symbol"==typeof r.toStringTag&&Object.defineProperty(Xr.prototype,r.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});var _t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof global?global:void 0;var yt,vt=(function(e){if("function"!=typeof e&&"object"!=typeof e)return!1;if("DOMException"!==e.name)return!1;try{return new e,!0}catch(e){return!1}}(yt=null==_t?void 0:_t.DOMException)?yt:void 0)||function(){var e=function(e,r){this.message=e||"",this.name=r||"Error",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)};return f(e,"DOMException"),e.prototype=Object.create(Error.prototype),Object.defineProperty(e.prototype,"constructor",{value:e,writable:!0,configurable:!0}),e}();function gt(e,r,t,n,o,a){var i=Z(e),u=Or(r);e._disturbed=!0;var s=!1,c=m(void 0);return h((function(f,d){var b,p,w,T;if(void 0!==a){if(b=function(){var t=void 0!==a.reason?a.reason:new vt("Aborted","AbortError"),i=[];n||i.push((function(){return"writable"===r._state?kr(r,t):m(void 0)})),o||i.push((function(){return"readable"===e._state?Vt(e,t):m(void 0)})),E((function(){return Promise.all(i.map((function(e){return e()})))}),!0,t)},a.aborted)return void b();a.addEventListener("abort",b)}if(q(e,i._closedPromise,(function(e){return n?O(!0,e):E((function(){return kr(r,e)}),!0,e),null})),q(r,u._closedPromise,(function(r){return o?O(!0,r):E((function(){return Vt(e,r)}),!0,r),null})),p=e,w=i._closedPromise,T=function(){return t?O():E((function(){return function(e){var r=e._ownerWritableStream,t=r._state;return Lr(r)||"closed"===t?m(void 0):"errored"===t?_(r._storedError):Qr(e)}(u)})),null},"closed"===p._state?T():g(w,T),Lr(r)||"closed"===r._state){var P=new TypeError("the destination writable stream closed before all data could be piped to it");o?O(!0,P):E((function(){return Vt(e,P)}),!0,P)}function C(){var e=c;return y(c,(function(){return e!==c?C():void 0}))}function q(e,r,t){"errored"===e._state?t(e._storedError):S(r,t)}function E(e,t,n){function o(){return v(e(),(function(){return W(t,n)}),(function(e){return W(!0,e)})),null}s||(s=!0,"writable"!==r._state||Lr(r)?o():g(C(),o))}function O(e,t){s||(s=!0,"writable"!==r._state||Lr(r)?W(e,t):g(C(),(function(){return W(e,t)})))}function W(e,r){return Vr(u),z(i),void 0!==a&&a.removeEventListener("abort",b),e?d(r):f(void 0),null}R(h((function(e,r){!function t(n){n?e():y(s?m(!0):y(u._readyPromise,(function(){return h((function(e,r){le(i,{_chunkSteps:function(r){c=y(Ur(u,r),void 0,l),e(!1)},_closeSteps:function(){return e(!0)},_errorSteps:r})}))})),t,r)}(!1)})))}))}var St=function(){function ReadableStreamDefaultController(){throw new TypeError("Illegal constructor")}return Object.defineProperty(ReadableStreamDefaultController.prototype,"desiredSize",{get:function(){if(!wt(this))throw Bt("desiredSize");return Ot(this)},enumerable:!1,configurable:!0}),ReadableStreamDefaultController.prototype.close=function(){if(!wt(this))throw Bt("close");if(!Wt(this))throw new TypeError("The stream is not in a state that permits close");Ct(this)},ReadableStreamDefaultController.prototype.enqueue=function(e){if(void 0===e&&(e=void 0),!wt(this))throw Bt("enqueue");if(!Wt(this))throw new TypeError("The stream is not in a state that permits enqueue");return qt(this,e)},ReadableStreamDefaultController.prototype.error=function(e){if(void 0===e&&(e=void 0),!wt(this))throw Bt("error");Et(this,e)},ReadableStreamDefaultController.prototype[W]=function(e){Oe(this);var r=this._cancelAlgorithm(e);return Pt(this),r},ReadableStreamDefaultController.prototype[j]=function(e){var r=this._controlledReadableStream;if(this._queue.length>0){var t=qe(this);this._closeRequested&&0===this._queue.length?(Pt(this),Ut(r)):Rt(this),e._chunkSteps(t)}else $(r,e),Rt(this)},ReadableStreamDefaultController.prototype[B]=function(){},ReadableStreamDefaultController}();function wt(e){return!!s(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableStream")&&e instanceof St)}function Rt(e){Tt(e)&&(e._pulling?e._pullAgain=!0:(e._pulling=!0,v(e._pullAlgorithm(),(function(){return e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,Rt(e)),null}),(function(r){return Et(e,r),null}))))}function Tt(e){var r=e._controlledReadableStream;return!!Wt(e)&&(!!e._started&&(!!(Ht(r)&&re(r)>0)||Ot(e)>0))}function Pt(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function Ct(e){if(Wt(e)){var r=e._controlledReadableStream;e._closeRequested=!0,0===e._queue.length&&(Pt(e),Ut(r))}}function qt(e,r){if(Wt(e)){var t=e._controlledReadableStream;if(Ht(t)&&re(t)>0)ee(t,r,!1);else{var n=void 0;try{n=e._strategySizeAlgorithm(r)}catch(r){throw Et(e,r),r}try{Ee(e,r,n)}catch(r){throw Et(e,r),r}}Rt(e)}}function Et(e,r){var t=e._controlledReadableStream;"readable"===t._state&&(Oe(e),Pt(e),Gt(t,r))}function Ot(e){var r=e._controlledReadableStream._state;return"errored"===r?null:"closed"===r?0:e._strategyHWM-e._queueTotalSize}function Wt(e){var r=e._controlledReadableStream._state;return!e._closeRequested&&"readable"===r}function jt(e,r,t,n,o,a,i){r._controlledReadableStream=e,r._queue=void 0,r._queueTotalSize=void 0,Oe(r),r._started=!1,r._closeRequested=!1,r._pullAgain=!1,r._pulling=!1,r._strategySizeAlgorithm=i,r._strategyHWM=a,r._pullAlgorithm=n,r._cancelAlgorithm=o,e._readableStreamController=r,v(m(t()),(function(){return r._started=!0,Rt(r),null}),(function(e){return Et(r,e),null}))}function Bt(e){return new TypeError("ReadableStreamDefaultController.prototype.".concat(e," can only be used on a ReadableStreamDefaultController"))}function kt(e,r){return ke(e._readableStreamController)?function(e){var r,t,n,o,a,i=Z(e),u=!1,l=!1,s=!1,c=!1,f=!1,d=h((function(e){a=e}));function b(e){S(e._closedPromise,(function(r){return e!==i||($e(n._readableStreamController,r),$e(o._readableStreamController,r),c&&f||a(void 0)),null}))}function p(){pr(i)&&(z(i),b(i=Z(e))),le(i,{_chunkSteps:function(r){T((function(){l=!1,s=!1;var t=r,i=r;if(!c&&!f)try{i=Ce(r)}catch(r){return $e(n._readableStreamController,r),$e(o._readableStreamController,r),void a(Vt(e,r))}c||Ze(n._readableStreamController,t),f||Ze(o._readableStreamController,i),u=!1,l?y():s&&v()}))},_closeSteps:function(){u=!1,c||Ke(n._readableStreamController),f||Ke(o._readableStreamController),n._readableStreamController._pendingPullIntos.length>0&&nr(n._readableStreamController,0),o._readableStreamController._pendingPullIntos.length>0&&nr(o._readableStreamController,0),c&&f||a(void 0)},_errorSteps:function(){u=!1}})}function _(r,t){ue(i)&&(z(i),b(i=sr(e)));var d=t?o:n,p=t?n:o;hr(i,r,1,{_chunkSteps:function(r){T((function(){l=!1,s=!1;var n=t?f:c;if(t?c:f)n||or(d._readableStreamController,r);else{var o=void 0;try{o=Ce(r)}catch(r){return $e(d._readableStreamController,r),$e(p._readableStreamController,r),void a(Vt(e,r))}n||or(d._readableStreamController,r),Ze(p._readableStreamController,o)}u=!1,l?y():s&&v()}))},_closeSteps:function(e){u=!1;var r=t?f:c,n=t?c:f;r||Ke(d._readableStreamController),n||Ke(p._readableStreamController),void 0!==e&&(r||or(d._readableStreamController,e),!n&&p._readableStreamController._pendingPullIntos.length>0&&nr(p._readableStreamController,0)),r&&n||a(void 0)},_errorSteps:function(){u=!1}})}function y(){if(u)return l=!0,m(void 0);u=!0;var e=rr(n._readableStreamController);return null===e?p():_(e._view,!1),m(void 0)}function v(){if(u)return s=!0,m(void 0);u=!0;var e=rr(o._readableStreamController);return null===e?p():_(e._view,!0),m(void 0)}function g(n){if(c=!0,r=n,f){var o=fe([r,t]),i=Vt(e,o);a(i)}return d}function w(n){if(f=!0,t=n,c){var o=fe([r,t]),i=Vt(e,o);a(i)}return d}function R(){}return n=Yt(R,y,g),o=Yt(R,v,w),b(i),[n,o]}(e):function(e,r){var t,n,o,a,i,u=Z(e),l=!1,s=!1,c=!1,f=!1,d=h((function(e){i=e}));function b(){return l?(s=!0,m(void 0)):(l=!0,le(u,{_chunkSteps:function(e){T((function(){s=!1;var r=e,t=e;c||qt(o._readableStreamController,r),f||qt(a._readableStreamController,t),l=!1,s&&b()}))},_closeSteps:function(){l=!1,c||Ct(o._readableStreamController),f||Ct(a._readableStreamController),c&&f||i(void 0)},_errorSteps:function(){l=!1}}),m(void 0))}function p(r){if(c=!0,t=r,f){var o=fe([t,n]),a=Vt(e,o);i(a)}return d}function _(r){if(f=!0,n=r,c){var o=fe([t,n]),a=Vt(e,o);i(a)}return d}function y(){}return o=xt(y,b,p),a=xt(y,b,_),S(u._closedPromise,(function(e){return Et(o._readableStreamController,e),Et(a._readableStreamController,e),c&&f||i(void 0),null})),[o,a]}(e)}function At(e){return s(r=e)&&void 0!==r.getReader?function(e){var r;function t(){var t;try{t=e.read()}catch(e){return _(e)}return w(t,(function(e){if(!s(e))throw new TypeError("The promise returned by the reader.read() method must fulfill with an object");if(e.done)Ct(r._readableStreamController);else{var t=e.value;qt(r._readableStreamController,t)}}))}function n(r){try{return m(e.cancel(r))}catch(e){return _(e)}}return r=xt(l,t,n,0),r}(e.getReader()):function(e){var r,t=ve(e,"async");function n(){var e;try{e=function(e){var r=P(e.nextMethod,e.iterator,[]);if(!s(r))throw new TypeError("The iterator.next() method must return an object");return r}(t)}catch(e){return _(e)}return w(m(e),(function(e){if(!s(e))throw new TypeError("The promise returned by the iterator.next() method must fulfill with an object");var t=function(e){return Boolean(e.done)}(e);if(t)Ct(r._readableStreamController);else{var n=function(e){return e.value}(e);qt(r._readableStreamController,n)}}))}function o(e){var r,n,o=t.iterator;try{r=me(o,"return")}catch(e){return _(e)}if(void 0===r)return m(void 0);try{n=P(r,o,[e])}catch(e){return _(e)}return w(m(n),(function(e){if(!s(e))throw new TypeError("The promise returned by the iterator.return() method must fulfill with an object")}))}return r=xt(l,n,o,0),r}(e);var r}function zt(e,r,t){return N(e,t),function(t){return C(e,r,[t])}}function It(e,r,t){return N(e,t),function(t){return C(e,r,[t])}}function Dt(e,r,t){return N(e,t),function(t){return P(e,r,[t])}}function Lt(e,r){if("bytes"!==(e="".concat(e)))throw new TypeError("".concat(r," '").concat(e,"' is not a valid enumeration value for ReadableStreamType"));return e}function Ft(e,r){Q(e,r);var t=null==e?void 0:e.preventAbort,n=null==e?void 0:e.preventCancel,o=null==e?void 0:e.preventClose,a=null==e?void 0:e.signal;return void 0!==a&&function(e,r){if(!function(e){if("object"!=typeof e||null===e)return!1;try{return"boolean"==typeof e.aborted}catch(e){return!1}}(e))throw new TypeError("".concat(r," is not an AbortSignal."))}(a,"".concat(r," has member 'signal' that")),{preventAbort:Boolean(t),preventCancel:Boolean(n),preventClose:Boolean(o),signal:a}}Object.defineProperties(St.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),f(St.prototype.close,"close"),f(St.prototype.enqueue,"enqueue"),f(St.prototype.error,"error"),"symbol"==typeof r.toStringTag&&Object.defineProperty(St.prototype,r.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});var Mt=function(){function ReadableStream(e,r){void 0===e&&(e={}),void 0===r&&(r={}),void 0===e?e=null:H(e,"First parameter");var t=gr(r,"Second parameter"),n=function(e,r){Q(e,r);var t=e,n=null==t?void 0:t.autoAllocateChunkSize,o=null==t?void 0:t.cancel,a=null==t?void 0:t.pull,i=null==t?void 0:t.start,u=null==t?void 0:t.type;return{autoAllocateChunkSize:void 0===n?void 0:J(n,"".concat(r," has member 'autoAllocateChunkSize' that")),cancel:void 0===o?void 0:zt(o,t,"".concat(r," has member 'cancel' that")),pull:void 0===a?void 0:It(a,t,"".concat(r," has member 'pull' that")),start:void 0===i?void 0:Dt(i,t,"".concat(r," has member 'start' that")),type:void 0===u?void 0:Lt(u,"".concat(r," has member 'type' that"))}}(e,"First parameter");if(Qt(this),"bytes"===n.type){if(void 0!==t.size)throw new RangeError("The strategy for a byte stream cannot have a size function");!function(e,r,t){var n,o,a,i=Object.create(Be.prototype);n=void 0!==r.start?function(){return r.start(i)}:function(){},o=void 0!==r.pull?function(){return r.pull(i)}:function(){return m(void 0)},a=void 0!==r.cancel?function(e){return r.cancel(e)}:function(){return m(void 0)};var u=r.autoAllocateChunkSize;if(0===u)throw new TypeError("autoAllocateChunkSize must be greater than 0");ar(e,i,n,o,a,t,u)}(this,n,yr(t,0))}else{var o=vr(t);!function(e,r,t,n){var o,a,i,u=Object.create(St.prototype);o=void 0!==r.start?function(){return r.start(u)}:function(){},a=void 0!==r.pull?function(){return r.pull(u)}:function(){return m(void 0)},i=void 0!==r.cancel?function(e){return r.cancel(e)}:function(){return m(void 0)},jt(e,u,o,a,i,t,n)}(this,n,yr(t,1),o)}}return Object.defineProperty(ReadableStream.prototype,"locked",{get:function(){if(!Nt(this))throw Xt("locked");return Ht(this)},enumerable:!1,configurable:!0}),ReadableStream.prototype.cancel=function(e){return void 0===e&&(e=void 0),Nt(this)?Ht(this)?_(new TypeError("Cannot cancel a stream that already has a reader")):Vt(this,e):_(Xt("cancel"))},ReadableStream.prototype.getReader=function(e){if(void 0===e&&(e=void 0),!Nt(this))throw Xt("getReader");return void 0===function(e,r){Q(e,r);var t=null==e?void 0:e.mode;return{mode:void 0===t?void 0:lr(t,"".concat(r," has member 'mode' that"))}}(e,"First parameter").mode?Z(this):sr(this)},ReadableStream.prototype.pipeThrough=function(e,r){if(void 0===r&&(r={}),!Nt(this))throw Xt("pipeThrough");V(e,1,"pipeThrough");var t=function(e,r){Q(e,r);var t=null==e?void 0:e.readable;U(t,"readable","ReadableWritablePair"),K(t,"".concat(r," has member 'readable' that"));var n=null==e?void 0:e.writable;return U(n,"writable","ReadableWritablePair"),Cr(n,"".concat(r," has member 'writable' that")),{readable:t,writable:n}}(e,"First parameter"),n=Ft(r,"Second parameter");if(Ht(this))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(Br(t.writable))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");return R(gt(this,t.writable,n.preventClose,n.preventAbort,n.preventCancel,n.signal)),t.readable},ReadableStream.prototype.pipeTo=function(e,r){if(void 0===r&&(r={}),!Nt(this))return _(Xt("pipeTo"));if(void 0===e)return _("Parameter 1 is required in 'pipeTo'.");if(!jr(e))return _(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));var t;try{t=Ft(r,"Second parameter")}catch(e){return _(e)}return Ht(this)?_(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):Br(e)?_(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):gt(this,e,t.preventClose,t.preventAbort,t.preventCancel,t.signal)},ReadableStream.prototype.tee=function(){if(!Nt(this))throw Xt("tee");return fe(kt(this))},ReadableStream.prototype.values=function(e){if(void 0===e&&(e=void 0),!Nt(this))throw Xt("values");var r,t,n,o,a,i=function(e,r){Q(e,r);var t=null==e?void 0:e.preventCancel;return{preventCancel:Boolean(t)}}(e,"First parameter");return r=this,t=i.preventCancel,n=Z(r),o=new Se(n,t),(a=Object.create(we))._asyncIteratorImpl=o,a},ReadableStream.prototype[ye]=function(e){return this.values(e)},ReadableStream.from=function(e){return At(e)},ReadableStream}();function xt(e,r,t,n,o){void 0===n&&(n=1),void 0===o&&(o=function(){return 1});var a=Object.create(Mt.prototype);return Qt(a),jt(a,Object.create(St.prototype),e,r,t,n,o),a}function Yt(e,r,t){var n=Object.create(Mt.prototype);return Qt(n),ar(n,Object.create(Be.prototype),e,r,t,0,void 0),n}function Qt(e){e._state="readable",e._reader=void 0,e._storedError=void 0,e._disturbed=!1}function Nt(e){return!!s(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readableStreamController")&&e instanceof Mt)}function Ht(e){return void 0!==e._reader}function Vt(e,r){if(e._disturbed=!0,"closed"===e._state)return m(void 0);if("errored"===e._state)return _(e._storedError);Ut(e);var t=e._reader;if(void 0!==t&&pr(t)){var n=t._readIntoRequests;t._readIntoRequests=new q,n.forEach((function(e){e._closeSteps(void 0)}))}return w(e._readableStreamController[W](r),l)}function Ut(e){e._state="closed";var r=e._reader;if(void 0!==r&&(M(r),ue(r))){var t=r._readRequests;r._readRequests=new q,t.forEach((function(e){e._closeSteps()}))}}function Gt(e,r){e._state="errored",e._storedError=r;var t=e._reader;void 0!==t&&(F(t,r),ue(t)?se(t,r):mr(t,r))}function Xt(e){return new TypeError("ReadableStream.prototype.".concat(e," can only be used on a ReadableStream"))}function Jt(e,r){Q(e,r);var t=null==e?void 0:e.highWaterMark;return U(t,"highWaterMark","QueuingStrategyInit"),{highWaterMark:G(t)}}Object.defineProperties(Mt,{from:{enumerable:!0}}),Object.defineProperties(Mt.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),f(Mt.from,"from"),f(Mt.prototype.cancel,"cancel"),f(Mt.prototype.getReader,"getReader"),f(Mt.prototype.pipeThrough,"pipeThrough"),f(Mt.prototype.pipeTo,"pipeTo"),f(Mt.prototype.tee,"tee"),f(Mt.prototype.values,"values"),"symbol"==typeof r.toStringTag&&Object.defineProperty(Mt.prototype,r.toStringTag,{value:"ReadableStream",configurable:!0}),Object.defineProperty(Mt.prototype,ye,{value:Mt.prototype.values,writable:!0,configurable:!0});var Kt=function(e){return e.byteLength};f(Kt,"size");var Zt=function(){function ByteLengthQueuingStrategy(e){V(e,1,"ByteLengthQueuingStrategy"),e=Jt(e,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=e.highWaterMark}return Object.defineProperty(ByteLengthQueuingStrategy.prototype,"highWaterMark",{get:function(){if(!en(this))throw $t("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark},enumerable:!1,configurable:!0}),Object.defineProperty(ByteLengthQueuingStrategy.prototype,"size",{get:function(){if(!en(this))throw $t("size");return Kt},enumerable:!1,configurable:!0}),ByteLengthQueuingStrategy}();function $t(e){return new TypeError("ByteLengthQueuingStrategy.prototype.".concat(e," can only be used on a ByteLengthQueuingStrategy"))}function en(e){return!!s(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_byteLengthQueuingStrategyHighWaterMark")&&e instanceof Zt)}Object.defineProperties(Zt.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof r.toStringTag&&Object.defineProperty(Zt.prototype,r.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});var rn=function(){return 1};f(rn,"size");var tn=function(){function CountQueuingStrategy(e){V(e,1,"CountQueuingStrategy"),e=Jt(e,"First parameter"),this._countQueuingStrategyHighWaterMark=e.highWaterMark}return Object.defineProperty(CountQueuingStrategy.prototype,"highWaterMark",{get:function(){if(!on(this))throw nn("highWaterMark");return this._countQueuingStrategyHighWaterMark},enumerable:!1,configurable:!0}),Object.defineProperty(CountQueuingStrategy.prototype,"size",{get:function(){if(!on(this))throw nn("size");return rn},enumerable:!1,configurable:!0}),CountQueuingStrategy}();function nn(e){return new TypeError("CountQueuingStrategy.prototype.".concat(e," can only be used on a CountQueuingStrategy"))}function on(e){return!!s(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_countQueuingStrategyHighWaterMark")&&e instanceof tn)}function an(e,r,t){return N(e,t),function(t){return C(e,r,[t])}}function un(e,r,t){return N(e,t),function(t){return P(e,r,[t])}}function ln(e,r,t){return N(e,t),function(t,n){return C(e,r,[t,n])}}function sn(e,r,t){return N(e,t),function(t){return C(e,r,[t])}}Object.defineProperties(tn.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof r.toStringTag&&Object.defineProperty(tn.prototype,r.toStringTag,{value:"CountQueuingStrategy",configurable:!0});var cn=function(){function TransformStream(e,r,t){void 0===e&&(e={}),void 0===r&&(r={}),void 0===t&&(t={}),void 0===e&&(e=null);var n=gr(r,"Second parameter"),o=gr(t,"Third parameter"),a=function(e,r){Q(e,r);var t=null==e?void 0:e.cancel,n=null==e?void 0:e.flush,o=null==e?void 0:e.readableType,a=null==e?void 0:e.start,i=null==e?void 0:e.transform,u=null==e?void 0:e.writableType;return{cancel:void 0===t?void 0:sn(t,e,"".concat(r," has member 'cancel' that")),flush:void 0===n?void 0:an(n,e,"".concat(r," has member 'flush' that")),readableType:o,start:void 0===a?void 0:un(a,e,"".concat(r," has member 'start' that")),transform:void 0===i?void 0:ln(i,e,"".concat(r," has member 'transform' that")),writableType:u}}(e,"First parameter");if(void 0!==a.readableType)throw new RangeError("Invalid readableType specified");if(void 0!==a.writableType)throw new RangeError("Invalid writableType specified");var i,u=yr(o,0),l=vr(o),s=yr(n,1),c=vr(n);!function(e,r,t,n,o,a){function i(){return r}function u(r){return function(e,r){var t=e._transformStreamController;if(e._backpressure){return w(e._backpressureChangePromise,(function(){var n=e._writable;if("erroring"===n._state)throw n._storedError;return gn(t,r)}))}return gn(t,r)}(e,r)}function l(r){return function(e,r){var t=e._transformStreamController;if(void 0!==t._finishPromise)return t._finishPromise;var n=e._readable;t._finishPromise=h((function(e,r){t._finishPromise_resolve=e,t._finishPromise_reject=r}));var o=t._cancelAlgorithm(r);return yn(t),v(o,(function(){return"errored"===n._state?Rn(t,n._storedError):(Et(n._readableStreamController,r),wn(t)),null}),(function(e){return Et(n._readableStreamController,e),Rn(t,e),null})),t._finishPromise}(e,r)}function s(){return function(e){var r=e._transformStreamController;if(void 0!==r._finishPromise)return r._finishPromise;var t=e._readable;r._finishPromise=h((function(e,t){r._finishPromise_resolve=e,r._finishPromise_reject=t}));var n=r._flushAlgorithm();return yn(r),v(n,(function(){return"errored"===t._state?Rn(r,t._storedError):(Ct(t._readableStreamController),wn(r)),null}),(function(e){return Et(t._readableStreamController,e),Rn(r,e),null})),r._finishPromise}(e)}function c(){return function(e){return hn(e,!1),e._backpressureChangePromise}(e)}function f(r){return function(e,r){var t=e._transformStreamController;if(void 0!==t._finishPromise)return t._finishPromise;var n=e._writable;t._finishPromise=h((function(e,r){t._finishPromise_resolve=e,t._finishPromise_reject=r}));var o=t._cancelAlgorithm(r);return yn(t),v(o,(function(){return"errored"===n._state?Rn(t,n._storedError):(rt(n._writableStreamController,r),pn(e),wn(t)),null}),(function(r){return rt(n._writableStreamController,r),pn(e),Rn(t,r),null})),t._finishPromise}(e,r)}e._writable=function(e,r,t,n,o,a){void 0===o&&(o=1),void 0===a&&(a=function(){return 1});var i=Object.create(Er.prototype);return Wr(i),Kr(i,Object.create(Xr.prototype),e,r,t,n,o,a),i}(i,u,s,l,t,n),e._readable=xt(i,c,f,o,a),e._backpressure=void 0,e._backpressureChangePromise=void 0,e._backpressureChangePromise_resolve=void 0,hn(e,!0),e._transformStreamController=void 0}(this,h((function(e){i=e})),s,c,u,l),function(e,r){var t,n,o,a=Object.create(mn.prototype);t=void 0!==r.transform?function(e){return r.transform(e,a)}:function(e){try{return vn(a,e),m(void 0)}catch(e){return _(e)}};n=void 0!==r.flush?function(){return r.flush(a)}:function(){return m(void 0)};o=void 0!==r.cancel?function(e){return r.cancel(e)}:function(){return m(void 0)};!function(e,r,t,n,o){r._controlledTransformStream=e,e._transformStreamController=r,r._transformAlgorithm=t,r._flushAlgorithm=n,r._cancelAlgorithm=o,r._finishPromise=void 0,r._finishPromise_resolve=void 0,r._finishPromise_reject=void 0}(e,a,t,n,o)}(this,a),void 0!==a.start?i(a.start(this._transformStreamController)):i(void 0)}return Object.defineProperty(TransformStream.prototype,"readable",{get:function(){if(!fn(this))throw Tn("readable");return this._readable},enumerable:!1,configurable:!0}),Object.defineProperty(TransformStream.prototype,"writable",{get:function(){if(!fn(this))throw Tn("writable");return this._writable},enumerable:!1,configurable:!0}),TransformStream}();function fn(e){return!!s(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_transformStreamController")&&e instanceof cn)}function dn(e,r){Et(e._readable._readableStreamController,r),bn(e,r)}function bn(e,r){yn(e._transformStreamController),rt(e._writable._writableStreamController,r),pn(e)}function pn(e){e._backpressure&&hn(e,!1)}function hn(e,r){void 0!==e._backpressureChangePromise&&e._backpressureChangePromise_resolve(),e._backpressureChangePromise=h((function(r){e._backpressureChangePromise_resolve=r})),e._backpressure=r}Object.defineProperties(cn.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),"symbol"==typeof r.toStringTag&&Object.defineProperty(cn.prototype,r.toStringTag,{value:"TransformStream",configurable:!0});var mn=function(){function TransformStreamDefaultController(){throw new TypeError("Illegal constructor")}return Object.defineProperty(TransformStreamDefaultController.prototype,"desiredSize",{get:function(){if(!_n(this))throw Sn("desiredSize");return Ot(this._controlledTransformStream._readable._readableStreamController)},enumerable:!1,configurable:!0}),TransformStreamDefaultController.prototype.enqueue=function(e){if(void 0===e&&(e=void 0),!_n(this))throw Sn("enqueue");vn(this,e)},TransformStreamDefaultController.prototype.error=function(e){if(void 0===e&&(e=void 0),!_n(this))throw Sn("error");var r;r=e,dn(this._controlledTransformStream,r)},TransformStreamDefaultController.prototype.terminate=function(){if(!_n(this))throw Sn("terminate");!function(e){var r=e._controlledTransformStream;Ct(r._readable._readableStreamController);var t=new TypeError("TransformStream terminated");bn(r,t)}(this)},TransformStreamDefaultController}();function _n(e){return!!s(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledTransformStream")&&e instanceof mn)}function yn(e){e._transformAlgorithm=void 0,e._flushAlgorithm=void 0,e._cancelAlgorithm=void 0}function vn(e,r){var t=e._controlledTransformStream,n=t._readable._readableStreamController;if(!Wt(n))throw new TypeError("Readable side is not in a state that permits enqueue");try{qt(n,r)}catch(e){throw bn(t,e),t._readable._storedError}var o=function(e){return!Tt(e)}(n);o!==t._backpressure&&hn(t,!0)}function gn(e,r){return w(e._transformAlgorithm(r),void 0,(function(r){throw dn(e._controlledTransformStream,r),r}))}function Sn(e){return new TypeError("TransformStreamDefaultController.prototype.".concat(e," can only be used on a TransformStreamDefaultController"))}function wn(e){void 0!==e._finishPromise_resolve&&(e._finishPromise_resolve(),e._finishPromise_resolve=void 0,e._finishPromise_reject=void 0)}function Rn(e,r){void 0!==e._finishPromise_reject&&(R(e._finishPromise),e._finishPromise_reject(r),e._finishPromise_resolve=void 0,e._finishPromise_reject=void 0)}function Tn(e){return new TypeError("TransformStream.prototype.".concat(e," can only be used on a TransformStream"))}Object.defineProperties(mn.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),f(mn.prototype.enqueue,"enqueue"),f(mn.prototype.error,"error"),f(mn.prototype.terminate,"terminate"),"symbol"==typeof r.toStringTag&&Object.defineProperty(mn.prototype,r.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});var Pn={ReadableStream:Mt,ReadableStreamDefaultController:St,ReadableByteStreamController:Be,ReadableStreamBYOBRequest:je,ReadableStreamDefaultReader:ie,ReadableStreamBYOBReader:br,WritableStream:Er,WritableStreamDefaultController:Xr,WritableStreamDefaultWriter:xr,ByteLengthQueuingStrategy:Zt,CountQueuingStrategy:tn,TransformStream:cn,TransformStreamDefaultController:mn};if(void 0!==_t)for(var Cn in Pn)Object.prototype.hasOwnProperty.call(Pn,Cn)&&Object.defineProperty(_t,Cn,{value:Pn[Cn],writable:!0,configurable:!0});e.ByteLengthQueuingStrategy=Zt,e.CountQueuingStrategy=tn,e.ReadableByteStreamController=Be,e.ReadableStream=Mt,e.ReadableStreamBYOBReader=br,e.ReadableStreamBYOBRequest=je,e.ReadableStreamDefaultController=St,e.ReadableStreamDefaultReader=ie,e.TransformStream=cn,e.TransformStreamDefaultController=mn,e.WritableStream=Er,e.WritableStreamDefaultController=Xr,e.WritableStreamDefaultWriter=xr})); +//# sourceMappingURL=polyfill.min.js.map diff --git a/backend/node_modules/web-streams-polyfill/dist/polyfill.min.js.map b/backend/node_modules/web-streams-polyfill/dist/polyfill.min.js.map new file mode 100644 index 0000000000000000000000000000000000000000..8cd66dc1197447188e6f6efd6dcf2ea92dc6a4d1 --- /dev/null +++ b/backend/node_modules/web-streams-polyfill/dist/polyfill.min.js.map @@ -0,0 +1 @@ +{"version":3,"file":"polyfill.min.js","sources":["../src/stub/symbol.ts","../node_modules/tslib/tslib.es6.js","../src/utils.ts","../src/lib/helpers/miscellaneous.ts","../src/lib/helpers/webidl.ts","../src/lib/simple-queue.ts","../src/lib/abstract-ops/internal-methods.ts","../src/lib/readable-stream/generic-reader.ts","../src/stub/number-isfinite.ts","../src/stub/math-trunc.ts","../src/lib/validators/basic.ts","../src/lib/validators/readable-stream.ts","../src/lib/readable-stream/default-reader.ts","../src/lib/abstract-ops/ecmascript.ts","../src/target/es5/stub/async-iterator-prototype.ts","../src/lib/readable-stream/async-iterator.ts","../src/stub/number-isnan.ts","../src/lib/abstract-ops/miscellaneous.ts","../src/lib/abstract-ops/queue-with-sizes.ts","../src/lib/helpers/array-buffer-view.ts","../src/lib/readable-stream/byte-stream-controller.ts","../src/lib/readable-stream/byob-reader.ts","../src/lib/validators/reader-options.ts","../src/lib/abstract-ops/queuing-strategy.ts","../src/lib/validators/queuing-strategy.ts","../src/lib/validators/underlying-sink.ts","../src/lib/validators/writable-stream.ts","../src/lib/abort-signal.ts","../src/lib/writable-stream.ts","../src/globals.ts","../src/stub/dom-exception.ts","../src/lib/readable-stream/pipe.ts","../src/lib/readable-stream/default-controller.ts","../src/lib/readable-stream/tee.ts","../src/lib/readable-stream/from.ts","../src/lib/readable-stream/readable-stream-like.ts","../src/lib/validators/underlying-source.ts","../src/lib/validators/pipe-options.ts","../src/lib/readable-stream.ts","../src/lib/validators/readable-writable-pair.ts","../src/lib/validators/iterator-options.ts","../src/lib/validators/queuing-strategy-init.ts","../src/lib/byte-length-queuing-strategy.ts","../src/lib/count-queuing-strategy.ts","../src/lib/validators/transformer.ts","../src/lib/transform-stream.ts","../src/polyfill.ts"],"sourcesContent":["/// \n\nconst SymbolPolyfill: (description?: string) => symbol =\n typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ?\n Symbol :\n description => `Symbol(${description})` as any as symbol;\n\nexport default SymbolPolyfill;\n","/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise, SuppressedError, Symbol */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\r\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\r\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\r\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\r\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\r\n var _, done = false;\r\n for (var i = decorators.length - 1; i >= 0; i--) {\r\n var context = {};\r\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\r\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\r\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\r\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\r\n if (kind === \"accessor\") {\r\n if (result === void 0) continue;\r\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\r\n if (_ = accept(result.get)) descriptor.get = _;\r\n if (_ = accept(result.set)) descriptor.set = _;\r\n if (_ = accept(result.init)) initializers.unshift(_);\r\n }\r\n else if (_ = accept(result)) {\r\n if (kind === \"field\") initializers.unshift(_);\r\n else descriptor[key] = _;\r\n }\r\n }\r\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\r\n done = true;\r\n};\r\n\r\nexport function __runInitializers(thisArg, initializers, value) {\r\n var useValue = arguments.length > 2;\r\n for (var i = 0; i < initializers.length; i++) {\r\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\r\n }\r\n return useValue ? value : void 0;\r\n};\r\n\r\nexport function __propKey(x) {\r\n return typeof x === \"symbol\" ? x : \"\".concat(x);\r\n};\r\n\r\nexport function __setFunctionName(f, name, prefix) {\r\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\r\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\r\n};\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n var desc = Object.getOwnPropertyDescriptor(m, k);\r\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\r\n desc = { enumerable: true, get: function() { return m[k]; } };\r\n }\r\n Object.defineProperty(o, k2, desc);\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\nexport function __classPrivateFieldIn(state, receiver) {\r\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\r\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\r\n}\r\n\r\nexport function __addDisposableResource(env, value, async) {\r\n if (value !== null && value !== void 0) {\r\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\r\n var dispose;\r\n if (async) {\r\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\r\n dispose = value[Symbol.asyncDispose];\r\n }\r\n if (dispose === void 0) {\r\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\r\n dispose = value[Symbol.dispose];\r\n }\r\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\r\n env.stack.push({ value: value, dispose: dispose, async: async });\r\n }\r\n else if (async) {\r\n env.stack.push({ async: true });\r\n }\r\n return value;\r\n}\r\n\r\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n};\r\n\r\nexport function __disposeResources(env) {\r\n function fail(e) {\r\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\r\n env.hasError = true;\r\n }\r\n function next() {\r\n while (env.stack.length) {\r\n var rec = env.stack.pop();\r\n try {\r\n var result = rec.dispose && rec.dispose.call(rec.value);\r\n if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\r\n }\r\n catch (e) {\r\n fail(e);\r\n }\r\n }\r\n if (env.hasError) throw env.error;\r\n }\r\n return next();\r\n}\r\n\r\nexport default {\r\n __extends: __extends,\r\n __assign: __assign,\r\n __rest: __rest,\r\n __decorate: __decorate,\r\n __param: __param,\r\n __metadata: __metadata,\r\n __awaiter: __awaiter,\r\n __generator: __generator,\r\n __createBinding: __createBinding,\r\n __exportStar: __exportStar,\r\n __values: __values,\r\n __read: __read,\r\n __spread: __spread,\r\n __spreadArrays: __spreadArrays,\r\n __spreadArray: __spreadArray,\r\n __await: __await,\r\n __asyncGenerator: __asyncGenerator,\r\n __asyncDelegator: __asyncDelegator,\r\n __asyncValues: __asyncValues,\r\n __makeTemplateObject: __makeTemplateObject,\r\n __importStar: __importStar,\r\n __importDefault: __importDefault,\r\n __classPrivateFieldGet: __classPrivateFieldGet,\r\n __classPrivateFieldSet: __classPrivateFieldSet,\r\n __classPrivateFieldIn: __classPrivateFieldIn,\r\n __addDisposableResource: __addDisposableResource,\r\n __disposeResources: __disposeResources,\r\n};\r\n","export function noop(): undefined {\n return undefined;\n}\n","import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n\nexport function setFunctionName(fn: Function, name: string): void {\n try {\n Object.defineProperty(fn, 'name', {\n value: name,\n configurable: true\n });\n } catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n }\n}\n","import { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\n// https://webidl.spec.whatwg.org/#a-new-promise\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-resolved-with\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return newPromise(resolve => resolve(value));\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-rejected-with\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\n// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned\n// from that handler. To prevent this, return null instead of void from all handlers.\n// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => null | PromiseLike,\n onRejected?: (reason: any) => null | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => null | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => null | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nlet _queueMicrotask: (callback: () => void) => void = callback => {\n if (typeof queueMicrotask === 'function') {\n _queueMicrotask = queueMicrotask;\n } else {\n const resolvedPromise = promiseResolvedWith(undefined);\n _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb);\n }\n return _queueMicrotask(callback);\n};\n\nexport { _queueMicrotask as queueMicrotask };\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n","import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n","export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\nexport const ReleaseSteps = Symbol('[[ReleaseSteps]]');\n","import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, type ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\nimport { ReleaseSteps } from '../abstract-ops/internal-methods';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n assert(stream._reader === reader);\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n stream._readableStreamController[ReleaseSteps]();\n\n stream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n","import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n","import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamDefaultReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamDefaultReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\nexport function ReadableStreamDefaultReaderRelease(reader: ReadableStreamDefaultReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n}\n\nexport function ReadableStreamDefaultReaderErrorReadRequests(reader: ReadableStreamDefaultReader, e: any) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n","import { reflectCall } from 'lib/helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport assert from '../../stub/assert';\n\ndeclare global {\n interface ArrayBuffer {\n readonly detached: boolean;\n\n transfer(): ArrayBuffer;\n }\n\n function structuredClone(value: T, options: { transfer: ArrayBuffer[] }): T;\n}\n\nexport function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\nexport let TransferArrayBuffer = (O: ArrayBuffer): ArrayBuffer => {\n if (typeof O.transfer === 'function') {\n TransferArrayBuffer = buffer => buffer.transfer();\n } else if (typeof structuredClone === 'function') {\n TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] });\n } else {\n // Not implemented correctly\n TransferArrayBuffer = buffer => buffer;\n }\n return TransferArrayBuffer(O);\n};\n\nexport function CanTransferArrayBuffer(O: ArrayBuffer): boolean {\n return !IsDetachedBuffer(O);\n}\n\nexport let IsDetachedBuffer = (O: ArrayBuffer): boolean => {\n if (typeof O.detached === 'boolean') {\n IsDetachedBuffer = buffer => buffer.detached;\n } else {\n // Not implemented correctly\n IsDetachedBuffer = buffer => buffer.byteLength === 0;\n }\n return IsDetachedBuffer(O);\n};\n\nexport function ArrayBufferSlice(buffer: ArrayBuffer, begin: number, end: number): ArrayBuffer {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n\nexport type MethodName = {\n [P in keyof T]: T[P] extends Function | undefined ? P : never;\n}[keyof T];\n\nexport function GetMethod>(receiver: T, prop: K): T[K] | undefined {\n const func = receiver[prop];\n if (func === undefined || func === null) {\n return undefined;\n }\n if (typeof func !== 'function') {\n throw new TypeError(`${String(prop)} is not a function`);\n }\n return func;\n}\n\nexport interface SyncIteratorRecord {\n iterator: Iterator,\n nextMethod: Iterator['next'],\n done: boolean;\n}\n\nexport interface AsyncIteratorRecord {\n iterator: AsyncIterator,\n nextMethod: AsyncIterator['next'],\n done: boolean;\n}\n\nexport type SyncOrAsyncIteratorRecord = SyncIteratorRecord | AsyncIteratorRecord;\n\nexport function CreateAsyncFromSyncIterator(syncIteratorRecord: SyncIteratorRecord): AsyncIteratorRecord {\n // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%,\n // we use yield* inside an async generator function to achieve the same result.\n\n // Wrap the sync iterator inside a sync iterable, so we can use it with yield*.\n const syncIterable = {\n [Symbol.iterator]: () => syncIteratorRecord.iterator\n };\n // Create an async generator function and immediately invoke it.\n const asyncIterator = (async function* () {\n return yield* syncIterable;\n }());\n // Return as an async iterator record.\n const nextMethod = asyncIterator.next;\n return { iterator: asyncIterator, nextMethod, done: false };\n}\n\n// Aligns with core-js/modules/es.symbol.async-iterator.js\nexport const SymbolAsyncIterator: (typeof Symbol)['asyncIterator'] =\n Symbol.asyncIterator ??\n Symbol.for?.('Symbol.asyncIterator') ??\n '@@asyncIterator';\n\nexport type SyncOrAsyncIterable = Iterable | AsyncIterable;\nexport type SyncOrAsyncIteratorMethod = () => (Iterator | AsyncIterator);\n\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint: 'async',\n method?: SyncOrAsyncIteratorMethod\n): AsyncIteratorRecord;\nfunction GetIterator(\n obj: Iterable,\n hint: 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncIteratorRecord;\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint = 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncOrAsyncIteratorRecord {\n assert(hint === 'sync' || hint === 'async');\n if (method === undefined) {\n if (hint === 'async') {\n method = GetMethod(obj as AsyncIterable, SymbolAsyncIterator);\n if (method === undefined) {\n const syncMethod = GetMethod(obj as Iterable, Symbol.iterator);\n const syncIteratorRecord = GetIterator(obj as Iterable, 'sync', syncMethod);\n return CreateAsyncFromSyncIterator(syncIteratorRecord);\n }\n } else {\n method = GetMethod(obj as Iterable, Symbol.iterator);\n }\n }\n if (method === undefined) {\n throw new TypeError('The object is not iterable');\n }\n const iterator = reflectCall(method, obj, []);\n if (!typeIsObject(iterator)) {\n throw new TypeError('The iterator method must return an object');\n }\n const nextMethod = iterator.next;\n return { iterator, nextMethod, done: false } as SyncOrAsyncIteratorRecord;\n}\n\nexport { GetIterator };\n\nexport function IteratorNext(iteratorRecord: AsyncIteratorRecord): Promise> {\n const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []);\n if (!typeIsObject(result)) {\n throw new TypeError('The iterator.next() method must return an object');\n }\n return result;\n}\n\nexport function IteratorComplete(\n iterResult: IteratorResult\n): iterResult is IteratorReturnResult {\n assert(typeIsObject(iterResult));\n return Boolean(iterResult.done);\n}\n\nexport function IteratorValue(iterResult: IteratorYieldResult): T {\n assert(typeIsObject(iterResult));\n return iterResult.value;\n}\n","/// \n\nimport { SymbolAsyncIterator } from '../../../lib/abstract-ops/ecmascript';\n\n// We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it.\nexport const AsyncIteratorPrototype: AsyncIterable = {\n // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( )\n // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator\n [SymbolAsyncIterator](this: AsyncIterator) {\n return this;\n }\n};\nObject.defineProperty(AsyncIteratorPrototype, SymbolAsyncIterator, { enumerable: false });\n","/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadableStreamDefaultReadResult,\n type ReadRequest\n} from './default-reader';\nimport { ReadableStreamReaderGenericCancel, ReadableStreamReaderGenericRelease } from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterableIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ninterface ReadableStreamAsyncIteratorInstance extends ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nObject.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n","import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: NonShared): NonShared {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer) as NonShared;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n","export type TypedArray =\n | Int8Array\n | Uint8Array\n | Uint8ClampedArray\n | Int16Array\n | Uint16Array\n | Int32Array\n | Uint32Array\n | Float32Array\n | Float64Array;\n\nexport type NonShared = T & {\n buffer: ArrayBuffer;\n}\n\nexport interface ArrayBufferViewConstructor {\n new(buffer: ArrayBuffer, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n}\n\nexport interface TypedArrayConstructor extends ArrayBufferViewConstructor {\n readonly BYTES_PER_ELEMENT: number;\n}\n\nexport type DataViewConstructor = ArrayBufferViewConstructor;\n\nfunction isDataViewConstructor(ctor: Function): ctor is DataViewConstructor {\n return ctor === DataView;\n}\n\nexport function isDataView(view: ArrayBufferView): view is DataView {\n return isDataViewConstructor(view.constructor);\n}\n\nexport function arrayBufferViewElementSize(ctor: ArrayBufferViewConstructor): number {\n if (isDataViewConstructor(ctor)) {\n return 1;\n }\n return (ctor as unknown as TypedArrayConstructor).BYTES_PER_ELEMENT;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n IsReadableStreamDefaultReader,\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n type ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n type ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n type ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport type { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\nimport {\n type ArrayBufferViewConstructor,\n arrayBufferViewElementSize,\n type NonShared,\n type TypedArrayConstructor\n} from '../helpers/array-buffer-view';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: NonShared | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: NonShared): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond');\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBuffer;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor = NonShared> =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: TypedArrayConstructor;\n readerType: 'default' | 'none';\n}\n\ninterface BYOBPullIntoDescriptor = NonShared> {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob' | 'none';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: NonShared): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest>): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n minimumFill: 1,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n if (this._pendingPullIntos.length > 0) {\n const firstPullInto = this._pendingPullIntos.peek();\n firstPullInto.readerType = 'none';\n\n this._pendingPullIntos = new SimpleQueue();\n this._pendingPullIntos.push(firstPullInto);\n }\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableByteStreamController.prototype.close, 'close');\nsetFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableByteStreamController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor>(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n assert(pullIntoDescriptor.readerType !== 'none');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as NonShared, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor>(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n let clonedChunk;\n try {\n clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength);\n } catch (cloneE) {\n ReadableByteStreamControllerError(controller, cloneE);\n throw cloneE;\n }\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength);\n}\n\nfunction ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.readerType === 'none');\n if (firstDescriptor.bytesFilled > 0) {\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n firstDescriptor.buffer,\n firstDescriptor.byteOffset,\n firstDescriptor.bytesFilled\n );\n }\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize;\n const maxAlignedBytes = maxBytesFilled - remainderBytes;\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n assert(pullIntoDescriptor.readerType !== 'none');\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nfunction ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller: ReadableByteStreamController) {\n const reader = controller._controlledReadableByteStream._reader;\n assert(IsReadableStreamDefaultReader(reader));\n while (reader._readRequests.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n const readRequest = reader._readRequests.shift();\n ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest);\n }\n}\n\nexport function ReadableByteStreamControllerPullInto>(\n controller: ReadableByteStreamController,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n const elementSize = arrayBufferViewElementSize(ctor);\n\n const { byteOffset, byteLength } = view;\n\n const minimumFill = min * elementSize;\n assert(minimumFill >= elementSize && minimumFill <= byteLength);\n assert(minimumFill % elementSize === 0);\n\n let buffer: ArrayBuffer;\n try {\n buffer = TransferArrayBuffer(view.buffer);\n } catch (e) {\n readIntoRequest._errorSteps(e);\n return;\n }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset,\n byteLength,\n bytesFilled: 0,\n minimumFill,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled % firstDescriptor.elementSize === 0);\n\n if (firstDescriptor.readerType === 'none') {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n return;\n }\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) {\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n pullIntoDescriptor.buffer,\n end - remainderSize,\n remainderSize\n );\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(\n controller: ReadableByteStreamController,\n chunk: NonShared\n) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const { buffer, byteOffset, byteLength } = chunk;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n if (firstPendingPullInto.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto);\n }\n }\n\n if (ReadableStreamHasDefaultReader(stream)) {\n ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller);\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView as NonShared, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerFillReadRequestFromQueue(\n controller: ReadableByteStreamController,\n readRequest: ReadRequest>\n) {\n assert(controller._queueTotalSize > 0);\n\n const entry = controller._queue.shift();\n controller._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n readRequest._chunkSteps(view as NonShared);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view as NonShared);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: NonShared) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: NonShared) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, type ReadableByteStream, type ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from './reader-options';\nimport { convertByobReadOptions } from '../validators/reader-options';\nimport { isDataView, type NonShared, type TypedArray } from '../helpers/array-buffer-view';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream as ReadableStream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest>(\n stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest\n): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest> {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(\n view: T,\n options?: ReadableStreamBYOBReaderReadOptions\n ): Promise>;\n read>(\n view: T,\n rawOptions: ReadableStreamBYOBReaderReadOptions | null | undefined = {}\n ): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n let options: ValidatedReadableStreamBYOBReaderReadOptions;\n try {\n options = convertByobReadOptions(rawOptions, 'options');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const min = options.min;\n if (min === 0) {\n return promiseRejectedWith(new TypeError('options.min must be greater than 0'));\n }\n if (!isDataView(view)) {\n if (min > (view as unknown as TypedArray).length) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s length'));\n }\n } else if (min > view.byteLength) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s byteLength'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamBYOBReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamBYOBReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead>(\n reader: ReadableStreamBYOBReader,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n min,\n readIntoRequest\n );\n }\n}\n\nexport function ReadableStreamBYOBReaderRelease(reader: ReadableStreamBYOBReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n}\n\nexport function ReadableStreamBYOBReaderErrorReadIntoRequests(reader: ReadableStreamBYOBReader, e: any) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n","import { assertDictionary, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n\nexport function convertByobReadOptions(\n options: ReadableStreamBYOBReaderReadOptions | null | undefined,\n context: string\n): ValidatedReadableStreamBYOBReaderReadOptions {\n assertDictionary(options, context);\n const min = options?.min ?? 1;\n return {\n min: convertUnsignedLongLongWithEnforceRange(\n min,\n `${context} has member 'min' that`\n )\n };\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n","/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * If aborted, returns the reason for aborting.\n */\n readonly reason?: any;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(reason?: any): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n type QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { type AbortController, type AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(WritableStream.prototype.abort, 'abort');\nsetFunctionName(WritableStream.prototype.close, 'close');\nsetFunctionName(WritableStream.prototype.getWriter, 'getWriter');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight\n};\n\nexport type {\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort(reason);\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nsetFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort');\nsetFunctionName(WritableStreamDefaultWriter.prototype.close, 'close');\nsetFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock');\nsetFunctionName(WritableStreamDefaultWriter.prototype.write, 'write');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n return null;\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let writeAlgorithm: (chunk: W) => Promise;\n let closeAlgorithm: () => Promise;\n let abortAlgorithm: (reason: any) => Promise;\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n } else {\n writeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n } else {\n closeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n } else {\n abortAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n return null;\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n","/// \n\nfunction getGlobals(): typeof globalThis | undefined {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n } else if (typeof self !== 'undefined') {\n return self;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n","/// \nimport { globals } from '../globals';\nimport { setFunctionName } from '../lib/helpers/miscellaneous';\n\ninterface DOMException extends Error {\n name: string;\n message: string;\n}\n\ntype DOMExceptionConstructor = new (message?: string, name?: string) => DOMException;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n if ((ctor as DOMExceptionConstructor).name !== 'DOMException') {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Support:\n * - Web browsers\n * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87)\n */\nfunction getFromGlobal(): DOMExceptionConstructor | undefined {\n const ctor = globals?.DOMException;\n return isDOMExceptionConstructor(ctor) ? ctor : undefined;\n}\n\n/**\n * Support:\n * - All platforms\n */\nfunction createPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line @typescript-eslint/no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n setFunctionName(ctor, 'DOMException');\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nconst DOMException: DOMExceptionConstructor = getFromGlobal() || createPolyfill();\n\nexport { DOMException };\n","import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n return null;\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => null) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => null) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest(): null {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n return null;\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any): null {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n\n return null;\n }\n });\n}\n","import type { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, type QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n type ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport type { ValidatedUnderlyingSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n // Do nothing.\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultController.prototype.close, 'close');\nsetFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableStreamDefaultController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n","import {\n CreateReadableByteStream,\n CreateReadableStream,\n type DefaultReadableStream,\n IsReadableStream,\n type ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n type ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n type ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(\n stream: ReadableStream,\n cloneForBranch2: boolean\n): [DefaultReadableStream, DefaultReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: DefaultReadableStream;\n let branch2: DefaultReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader> = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader>) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return null;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: NonShared, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader>(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n","import { CreateReadableStream, type DefaultReadableStream } from '../readable-stream';\nimport {\n isReadableStreamLike,\n type ReadableStreamDefaultReaderLike,\n type ReadableStreamLike\n} from './readable-stream-like';\nimport { ReadableStreamDefaultControllerClose, ReadableStreamDefaultControllerEnqueue } from './default-controller';\nimport { GetIterator, GetMethod, IteratorComplete, IteratorNext, IteratorValue } from '../abstract-ops/ecmascript';\nimport { promiseRejectedWith, promiseResolvedWith, reflectCall, transformPromiseWith } from '../helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { noop } from '../../utils';\n\nexport function ReadableStreamFrom(\n source: Iterable | AsyncIterable | ReadableStreamLike\n): DefaultReadableStream {\n if (isReadableStreamLike(source)) {\n return ReadableStreamFromDefaultReader(source.getReader());\n }\n return ReadableStreamFromIterable(source);\n}\n\nexport function ReadableStreamFromIterable(asyncIterable: Iterable | AsyncIterable): DefaultReadableStream {\n let stream: DefaultReadableStream;\n const iteratorRecord = GetIterator(asyncIterable, 'async');\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let nextResult;\n try {\n nextResult = IteratorNext(iteratorRecord);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const nextPromise = promiseResolvedWith(nextResult);\n return transformPromiseWith(nextPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object');\n }\n const done = IteratorComplete(iterResult);\n if (done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = IteratorValue(iterResult);\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n const iterator = iteratorRecord.iterator;\n let returnMethod: (typeof iterator)['return'] | undefined;\n try {\n returnMethod = GetMethod(iterator, 'return');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n if (returnMethod === undefined) {\n return promiseResolvedWith(undefined);\n }\n let returnResult: IteratorResult | Promise>;\n try {\n returnResult = reflectCall(returnMethod, iterator, [reason]);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const returnPromise = promiseResolvedWith(returnResult);\n return transformPromiseWith(returnPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object');\n }\n return undefined;\n });\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n\nexport function ReadableStreamFromDefaultReader(\n reader: ReadableStreamDefaultReaderLike\n): DefaultReadableStream {\n let stream: DefaultReadableStream;\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let readPromise;\n try {\n readPromise = reader.read();\n } catch (e) {\n return promiseRejectedWith(e);\n }\n return transformPromiseWith(readPromise, readResult => {\n if (!typeIsObject(readResult)) {\n throw new TypeError('The promise returned by the reader.read() method must fulfill with an object');\n }\n if (readResult.done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = readResult.value;\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n try {\n return promiseResolvedWith(reader.cancel(reason));\n } catch (e) {\n return promiseRejectedWith(e);\n }\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n","import { typeIsObject } from '../helpers/miscellaneous';\nimport type { ReadableStreamDefaultReadResult } from './default-reader';\n\n/**\n * A common interface for a `ReadadableStream` implementation.\n *\n * @public\n */\nexport interface ReadableStreamLike {\n readonly locked: boolean;\n\n getReader(): ReadableStreamDefaultReaderLike;\n}\n\n/**\n * A common interface for a `ReadableStreamDefaultReader` implementation.\n *\n * @public\n */\nexport interface ReadableStreamDefaultReaderLike {\n readonly closed: Promise;\n\n cancel(reason?: any): Promise;\n\n read(): Promise>;\n\n releaseLock(): void;\n}\n\nexport function isReadableStreamLike(stream: unknown): stream is ReadableStreamLike {\n return typeIsObject(stream) && typeof (stream as ReadableStreamLike).getReader !== 'undefined';\n}\n","import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n","import { assertDictionary } from './basic';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n","import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, type ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderErrorReadRequests,\n type ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReaderErrorReadIntoRequests,\n type ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { ReadableStreamFrom } from './readable-stream/from';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport type {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList, SymbolAsyncIterator } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions\n} from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport type { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport type { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\nimport type { ReadableStreamDefaultReaderLike, ReadableStreamLike } from './readable-stream/readable-stream-like';\nimport type { NonShared } from './helpers/array-buffer-view';\n\nexport type DefaultReadableStream = ReadableStream & {\n _readableStreamController: ReadableStreamDefaultController\n};\n\nexport type ReadableByteStream = ReadableStream> & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream implements AsyncIterable {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n\n [SymbolAsyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator {\n // Stub implementation, overridden below\n return this.values(options);\n }\n\n /**\n * Creates a new ReadableStream wrapping the provided iterable or async iterable.\n *\n * This can be used to adapt various kinds of objects into a readable stream,\n * such as an array, an async generator, or a Node.js readable stream.\n */\n static from(asyncIterable: Iterable | AsyncIterable | ReadableStreamLike): ReadableStream {\n return ReadableStreamFrom(asyncIterable);\n }\n}\n\nObject.defineProperties(ReadableStream, {\n from: { enumerable: true }\n});\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(ReadableStream.from, 'from');\nsetFunctionName(ReadableStream.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStream.prototype.getReader, 'getReader');\nsetFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough');\nsetFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo');\nsetFunctionName(ReadableStream.prototype.tee, 'tee');\nsetFunctionName(ReadableStream.prototype.values, 'values');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nObject.defineProperty(ReadableStream.prototype, SymbolAsyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n});\n\nexport type {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n ReadableStreamBYOBReaderReadOptions,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions,\n ReadableStreamLike,\n ReadableStreamDefaultReaderLike\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1\n): DefaultReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: DefaultReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n","import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n","import { assertDictionary } from './basic';\nimport type {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n","import type { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\nsetFunctionName(byteLengthSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\nsetFunctionName(countSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const cancel = original?.cancel;\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n cancel: cancel === undefined ?\n undefined :\n convertTransformerCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n\nfunction convertTransformerCancelCallback(\n fn: TransformerCancelCallback,\n original: Transformer,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith,\n uponPromise\n} from './helpers/webidl';\nimport { CreateReadableStream, type DefaultReadableStream, ReadableStream } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: DefaultReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport type {\n Transformer,\n TransformerCancelCallback,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSourceCancelAlgorithm(stream, reason);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n TransformStreamUnblockWrite(stream);\n}\n\nfunction TransformStreamUnblockWrite(stream: TransformStream) {\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _finishPromise: Promise | undefined;\n /** @internal */\n _finishPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _finishPromise_reject?: (reason: any) => void;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n /** @internal */\n _cancelAlgorithm: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(TransformStreamDefaultController.prototype.error, 'error');\nsetFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._finishPromise = undefined;\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm: (chunk: I) => Promise;\n let flushAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n } else {\n transformAlgorithm = chunk => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n }\n\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n } else {\n flushAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n if (transformer.cancel !== undefined) {\n cancelAlgorithm = reason => transformer.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally,\n // we don't run the _cancelAlgorithm again.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerError(readable._readableStreamController, reason);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally,\n // we don't also run the _cancelAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(flushPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerClose(readable._readableStreamController);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\nfunction TransformStreamDefaultSourceCancelAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._writable cannot change after construction, so caching it across a call to user code is safe.\n const writable = stream._writable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or\n // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the\n // _flushAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (writable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, writable._storedError);\n } else {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\nexport function defaultControllerFinishPromiseResolve(controller: TransformStreamDefaultController) {\n if (controller._finishPromise_resolve === undefined) {\n return;\n }\n\n controller._finishPromise_resolve();\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nexport function defaultControllerFinishPromiseReject(controller: TransformStreamDefaultController, reason: any) {\n if (controller._finishPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(controller._finishPromise!);\n controller._finishPromise_reject(reason);\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n","import {\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n ReadableByteStreamController,\n ReadableStream,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultController,\n ReadableStreamDefaultReader,\n TransformStream,\n TransformStreamDefaultController,\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter\n} from './ponyfill';\nimport { globals } from './globals';\n\n// Export\nexport * from './ponyfill';\n\nconst exports = {\n ReadableStream,\n ReadableStreamDefaultController,\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader,\n\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter,\n\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n\n TransformStream,\n TransformStreamDefaultController\n};\n\n// Add classes to global scope\nif (typeof globals !== 'undefined') {\n for (const prop in exports) {\n if (Object.prototype.hasOwnProperty.call(exports, prop)) {\n Object.defineProperty(globals, prop, {\n value: exports[prop as (keyof typeof exports)],\n writable: true,\n configurable: true\n });\n }\n }\n}\n"],"names":["SymbolPolyfill","Symbol","iterator","description","concat","__generator","thisArg","body","f","y","t","g","_","label","sent","trys","ops","next","verb","throw","return","this","n","v","op","TypeError","call","done","value","pop","length","push","e","step","__values","o","s","m","i","__await","__asyncGenerator","_arguments","generator","asyncIterator","apply","q","Promise","a","b","resume","r","resolve","then","fulfill","reject","settle","shift","__asyncDelegator","p","__asyncValues","d","noop","typeIsObject","x","SuppressedError","rethrowAssertionErrorRejection","setFunctionName","fn","name","Object","defineProperty","configurable","_a","originalPromise","originalPromiseThen","prototype","originalPromiseReject","bind","newPromise","executor","promiseResolvedWith","promiseRejectedWith","reason","PerformPromiseThen","promise","onFulfilled","onRejected","uponPromise","undefined","uponFulfillment","uponRejection","transformPromiseWith","fulfillmentHandler","rejectionHandler","setPromiseIsHandledToTrue","_queueMicrotask","callback","queueMicrotask","resolvedPromise_1","cb","reflectCall","F","V","args","Function","promiseCall","SimpleQueue","_cursor","_size","_front","_elements","_next","_back","get","element","oldBack","newBack","QUEUE_MAX_ARRAY_SIZE","oldFront","newFront","oldCursor","newCursor","elements","forEach","node","peek","front","cursor","AbortSteps","ErrorSteps","CancelSteps","PullSteps","ReleaseSteps","ReadableStreamReaderGenericInitialize","reader","stream","_ownerReadableStream","_reader","_state","defaultReaderClosedPromiseInitialize","defaultReaderClosedPromiseResolve","defaultReaderClosedPromiseInitializeAsResolved","defaultReaderClosedPromiseInitializeAsRejected","_storedError","ReadableStreamReaderGenericCancel","ReadableStreamCancel","ReadableStreamReaderGenericRelease","defaultReaderClosedPromiseReject","defaultReaderClosedPromiseResetToRejected","_readableStreamController","readerLockException","_closedPromise","_closedPromise_resolve","_closedPromise_reject","NumberIsFinite","Number","isFinite","MathTrunc","Math","trunc","ceil","floor","assertDictionary","obj","context","assertFunction","assertObject","isObject","assertRequiredArgument","position","assertRequiredField","field","convertUnrestrictedDouble","censorNegativeZero","convertUnsignedLongLongWithEnforceRange","upperBound","MAX_SAFE_INTEGER","integerPart","assertReadableStream","IsReadableStream","AcquireReadableStreamDefaultReader","ReadableStreamDefaultReader","ReadableStreamAddReadRequest","readRequest","_readRequests","ReadableStreamFulfillReadRequest","chunk","_closeSteps","_chunkSteps","ReadableStreamGetNumReadRequests","ReadableStreamHasDefaultReader","IsReadableStreamDefaultReader","IsReadableStreamLocked","defaultReaderBrandCheckException","cancel","read","resolvePromise","rejectPromise","ReadableStreamDefaultReaderRead","_errorSteps","releaseLock","ReadableStreamDefaultReaderErrorReadRequests","ReadableStreamDefaultReaderRelease","hasOwnProperty","_disturbed","readRequests","CreateArrayFromList","slice","CopyDataBlockBytes","dest","destOffset","src","srcOffset","Uint8Array","set","defineProperties","enumerable","closed","toStringTag","TransferArrayBuffer","O","transfer","buffer","structuredClone","IsDetachedBuffer","detached","byteLength","ArrayBufferSlice","begin","end","ArrayBuffer","GetMethod","receiver","prop","func","String","SymbolAsyncIterator","_c","_b","for","GetIterator","hint","method","syncIteratorRecord","syncIterable","nextMethod","CreateAsyncFromSyncIterator","AsyncIteratorPrototype","ReadableStreamAsyncIteratorImpl","preventCancel","_ongoingPromise","_isFinished","_preventCancel","_this","nextSteps","_nextSteps","returnSteps","_returnSteps","result","ReadableStreamAsyncIteratorPrototype","IsReadableStreamAsyncIterator","_asyncIteratorImpl","streamAsyncIteratorBrandCheckException","setPrototypeOf","NumberIsNaN","isNaN","CloneAsUint8Array","byteOffset","DequeueValue","container","pair","_queue","_queueTotalSize","size","EnqueueValueWithSize","Infinity","RangeError","ResetQueue","isDataViewConstructor","ctor","DataView","ReadableStreamBYOBRequest","IsReadableStreamBYOBRequest","byobRequestBrandCheckException","_view","respond","bytesWritten","_associatedReadableByteStreamController","ReadableByteStreamControllerRespond","respondWithNewView","view","isView","ReadableByteStreamControllerRespondWithNewView","ReadableByteStreamController","IsReadableByteStreamController","byteStreamControllerBrandCheckException","ReadableByteStreamControllerGetBYOBRequest","ReadableByteStreamControllerGetDesiredSize","close","_closeRequested","state","_controlledReadableByteStream","ReadableByteStreamControllerClose","enqueue","ReadableByteStreamControllerEnqueue","error","ReadableByteStreamControllerError","ReadableByteStreamControllerClearPendingPullIntos","_cancelAlgorithm","ReadableByteStreamControllerClearAlgorithms","ReadableByteStreamControllerFillReadRequestFromQueue","autoAllocateChunkSize","_autoAllocateChunkSize","bufferE","pullIntoDescriptor","bufferByteLength","bytesFilled","minimumFill","elementSize","viewConstructor","readerType","_pendingPullIntos","ReadableByteStreamControllerCallPullIfNeeded","firstPullInto","controller","shouldPull","_started","ReadableStreamHasBYOBReader","ReadableStreamGetNumReadIntoRequests","desiredSize","ReadableByteStreamControllerShouldCallPull","_pulling","_pullAgain","_pullAlgorithm","ReadableByteStreamControllerInvalidateBYOBRequest","ReadableByteStreamControllerCommitPullIntoDescriptor","filledView","ReadableByteStreamControllerConvertPullIntoDescriptor","readIntoRequest","_readIntoRequests","ReadableStreamFulfillReadIntoRequest","ReadableByteStreamControllerEnqueueChunkToQueue","ReadableByteStreamControllerEnqueueClonedChunkToQueue","clonedChunk","cloneE","ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue","firstDescriptor","ReadableByteStreamControllerShiftPendingPullInto","ReadableByteStreamControllerFillPullIntoDescriptorFromQueue","maxBytesToCopy","min","maxBytesFilled","totalBytesToCopyRemaining","ready","maxAlignedBytes","queue","headOfQueue","bytesToCopy","destStart","ReadableByteStreamControllerFillHeadPullIntoDescriptor","ReadableByteStreamControllerHandleQueueDrain","ReadableStreamClose","_byobRequest","ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue","ReadableByteStreamControllerPullInto","constructor","BYTES_PER_ELEMENT","arrayBufferViewElementSize","ReadableStreamAddReadIntoRequest","emptyView","ReadableByteStreamControllerRespondInternal","ReadableByteStreamControllerRespondInClosedState","remainderSize","ReadableByteStreamControllerRespondInReadableState","firstPendingPullInto","transferredBuffer","ReadableByteStreamControllerProcessReadRequestsUsingQueue","ReadableStreamError","entry","byobRequest","create","request","SetUpReadableStreamBYOBRequest","_strategyHWM","viewByteLength","SetUpReadableByteStreamController","startAlgorithm","pullAlgorithm","cancelAlgorithm","highWaterMark","convertReadableStreamReaderMode","mode","AcquireReadableStreamBYOBReader","ReadableStreamBYOBReader","IsReadableStreamBYOBReader","byobReaderBrandCheckException","rawOptions","options","convertByobReadOptions","isDataView","ReadableStreamBYOBReaderRead","ReadableStreamBYOBReaderErrorReadIntoRequests","ReadableStreamBYOBReaderRelease","readIntoRequests","ExtractHighWaterMark","strategy","defaultHWM","ExtractSizeAlgorithm","convertQueuingStrategy","init","convertQueuingStrategySize","convertUnderlyingSinkAbortCallback","original","convertUnderlyingSinkCloseCallback","convertUnderlyingSinkStartCallback","convertUnderlyingSinkWriteCallback","assertWritableStream","IsWritableStream","supportsAbortController","AbortController","WritableStream","rawUnderlyingSink","rawStrategy","underlyingSink","abort","start","type","write","convertUnderlyingSink","InitializeWritableStream","sizeAlgorithm","writeAlgorithm","closeAlgorithm","abortAlgorithm","WritableStreamDefaultController","SetUpWritableStreamDefaultController","SetUpWritableStreamDefaultControllerFromUnderlyingSink","streamBrandCheckException","IsWritableStreamLocked","WritableStreamAbort","WritableStreamCloseQueuedOrInFlight","WritableStreamClose","getWriter","AcquireWritableStreamDefaultWriter","WritableStreamDefaultWriter","_writer","_writableStreamController","_writeRequests","_inFlightWriteRequest","_closeRequest","_inFlightCloseRequest","_pendingAbortRequest","_backpressure","_abortReason","_abortController","_promise","wasAlreadyErroring","_resolve","_reject","_reason","_wasAlreadyErroring","WritableStreamStartErroring","closeRequest","writer","defaultWriterReadyPromiseResolve","closeSentinel","WritableStreamDefaultControllerAdvanceQueueIfNeeded","WritableStreamDealWithRejection","WritableStreamFinishErroring","WritableStreamDefaultWriterEnsureReadyPromiseRejected","WritableStreamHasOperationMarkedInFlight","storedError","writeRequest","abortRequest","WritableStreamRejectCloseAndClosedPromiseIfNeeded","defaultWriterClosedPromiseReject","WritableStreamUpdateBackpressure","backpressure","defaultWriterReadyPromiseInitialize","defaultWriterReadyPromiseReset","locked","_ownerWritableStream","defaultWriterReadyPromiseInitializeAsResolved","defaultWriterClosedPromiseInitialize","defaultWriterReadyPromiseInitializeAsRejected","defaultWriterClosedPromiseResolve","defaultWriterClosedPromiseInitializeAsRejected","IsWritableStreamDefaultWriter","defaultWriterBrandCheckException","defaultWriterLockException","WritableStreamDefaultControllerGetDesiredSize","WritableStreamDefaultWriterGetDesiredSize","_readyPromise","WritableStreamDefaultWriterAbort","WritableStreamDefaultWriterClose","WritableStreamDefaultWriterRelease","WritableStreamDefaultWriterWrite","WritableStreamDefaultWriterEnsureClosedPromiseRejected","_closedPromiseState","defaultWriterClosedPromiseResetToRejected","_readyPromiseState","defaultWriterReadyPromiseReject","defaultWriterReadyPromiseResetToRejected","releasedError","chunkSize","_strategySizeAlgorithm","chunkSizeE","WritableStreamDefaultControllerErrorIfNeeded","WritableStreamDefaultControllerGetChunkSize","WritableStreamAddWriteRequest","enqueueE","_controlledWritableStream","WritableStreamDefaultControllerGetBackpressure","WritableStreamDefaultControllerWrite","IsWritableStreamDefaultController","defaultControllerBrandCheckException","signal","WritableStreamDefaultControllerError","_abortAlgorithm","WritableStreamDefaultControllerClearAlgorithms","createAbortController","_writeAlgorithm","_closeAlgorithm","WritableStreamMarkCloseRequestInFlight","sinkClosePromise","WritableStreamFinishInFlightClose","WritableStreamFinishInFlightCloseWithError","WritableStreamDefaultControllerProcessClose","WritableStreamMarkFirstWriteRequestInFlight","sinkWritePromise","WritableStreamFinishInFlightWrite","WritableStreamFinishInFlightWriteWithError","WritableStreamDefaultControllerProcessWrite","_readyPromise_resolve","_readyPromise_reject","abortReason","globals","globalThis","self","global","DOMException","isDOMExceptionConstructor","message","Error","captureStackTrace","writable","createPolyfill","ReadableStreamPipeTo","source","preventClose","preventAbort","shuttingDown","currentWrite","action","actions","shutdownWithAction","all","map","aborted","addEventListener","isOrBecomesErrored","shutdown","WritableStreamDefaultWriterCloseWithErrorPropagation","destClosed_1","waitForWritesToFinish","oldCurrentWrite","originalIsError","originalError","doTheRest","finalize","newError","isError","removeEventListener","resolveLoop","rejectLoop","resolveRead","rejectRead","ReadableStreamDefaultController","IsReadableStreamDefaultController","ReadableStreamDefaultControllerGetDesiredSize","ReadableStreamDefaultControllerCanCloseOrEnqueue","ReadableStreamDefaultControllerClose","ReadableStreamDefaultControllerEnqueue","ReadableStreamDefaultControllerError","ReadableStreamDefaultControllerClearAlgorithms","_controlledReadableStream","ReadableStreamDefaultControllerCallPullIfNeeded","ReadableStreamDefaultControllerShouldCallPull","SetUpReadableStreamDefaultController","ReadableStreamTee","cloneForBranch2","reason1","reason2","branch1","branch2","resolveCancelPromise","reading","readAgainForBranch1","readAgainForBranch2","canceled1","canceled2","cancelPromise","forwardReaderError","thisReader","pullWithDefaultReader","chunk1","chunk2","pull1Algorithm","pull2Algorithm","pullWithBYOBReader","forBranch2","byobBranch","otherBranch","byobCanceled","otherCanceled","cancel1Algorithm","compositeReason","cancelResult","cancel2Algorithm","CreateReadableByteStream","ReadableByteStreamTee","readAgain","CreateReadableStream","ReadableStreamDefaultTee","ReadableStreamFrom","getReader","readPromise","readResult","ReadableStreamFromDefaultReader","asyncIterable","iteratorRecord","nextResult","IteratorNext","iterResult","Boolean","IteratorComplete","IteratorValue","returnMethod","returnResult","ReadableStreamFromIterable","convertUnderlyingSourceCancelCallback","convertUnderlyingSourcePullCallback","convertUnderlyingSourceStartCallback","convertReadableStreamType","convertPipeOptions","isAbortSignal","assertAbortSignal","ReadableStream","rawUnderlyingSource","underlyingSource","pull","convertUnderlyingDefaultOrByteSource","InitializeReadableStream","underlyingByteSource","SetUpReadableByteStreamControllerFromUnderlyingSource","SetUpReadableStreamDefaultControllerFromUnderlyingSource","convertReaderOptions","pipeThrough","rawTransform","transform","readable","convertReadableWritablePair","pipeTo","destination","tee","values","impl","convertIteratorOptions","from","convertQueuingStrategyInit","byteLengthSizeFunction","ByteLengthQueuingStrategy","_byteLengthQueuingStrategyHighWaterMark","IsByteLengthQueuingStrategy","byteLengthBrandCheckException","countSizeFunction","CountQueuingStrategy","_countQueuingStrategyHighWaterMark","IsCountQueuingStrategy","countBrandCheckException","convertTransformerFlushCallback","convertTransformerStartCallback","convertTransformerTransformCallback","convertTransformerCancelCallback","TransformStream","rawTransformer","rawWritableStrategy","rawReadableStrategy","writableStrategy","readableStrategy","transformer","flush","readableType","writableType","convertTransformer","startPromise_resolve","readableHighWaterMark","readableSizeAlgorithm","writableHighWaterMark","writableSizeAlgorithm","startPromise","_transformStreamController","_backpressureChangePromise","_writable","TransformStreamDefaultControllerPerformTransform","TransformStreamDefaultSinkWriteAlgorithm","_finishPromise","_readable","_finishPromise_resolve","_finishPromise_reject","TransformStreamDefaultControllerClearAlgorithms","defaultControllerFinishPromiseReject","defaultControllerFinishPromiseResolve","TransformStreamDefaultSinkAbortAlgorithm","flushPromise","_flushAlgorithm","TransformStreamDefaultSinkCloseAlgorithm","TransformStreamSetBackpressure","TransformStreamDefaultSourcePullAlgorithm","TransformStreamUnblockWrite","TransformStreamDefaultSourceCancelAlgorithm","CreateWritableStream","_backpressureChangePromise_resolve","InitializeTransformStream","transformAlgorithm","flushAlgorithm","TransformStreamDefaultController","TransformStreamDefaultControllerEnqueue","transformResultE","_controlledTransformStream","_transformAlgorithm","SetUpTransformStreamDefaultController","SetUpTransformStreamDefaultControllerFromTransformer","IsTransformStream","TransformStreamError","TransformStreamErrorWritableAndUnblockWrite","IsTransformStreamDefaultController","terminate","TransformStreamDefaultControllerTerminate","readableController","ReadableStreamDefaultControllerHasBackpressure","exports"],"mappings":";;;;;;;0PAEA,IAAMA,EACc,mBAAXC,QAAoD,iBAApBA,OAAOC,SAC5CD,OACA,SAAAE,GAAe,MAAA,UAAAC,OAAUD,EAA+B,IAAA,ECuHrD,SAASE,EAAYC,EAASC,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E7O,EAAgBopB,GAAiC3oB,UAAUsO,MAAO,SAClE/O,EAAgBopB,GAAiC3oB,UAAUspB,UAAW,aACpC,iBAAvBhuB,EAAOyN,aAChBrJ,OAAOC,eAAegpB,GAAiC3oB,UAAW1E,EAAOyN,YAAa,CACpF9L,MAAO,mCACP2C,cAAc,IClVlB,IAAM8pB,GAAU,CACd9F,eAAcA,GACdtE,gCAA+BA,GAC/B5R,6BAA4BA,GAC5BZ,0BAAyBA,GACzBpG,4BAA2BA,GAC3BoN,yBAAwBA,GAExB2B,eAAcA,GACdc,gCAA+BA,GAC/BU,4BAA2BA,GAE3BmO,0BAAyBA,GACzBK,qBAAoBA,GAEpBQ,gBAAeA,GACf0C,iCAAgCA,IAIlC,QAAuB,IAAZ9L,GACT,IAAK,IAAM/S,MAAQ4f,GACbhqB,OAAOM,UAAUgI,eAAejL,KAAK2sB,GAAS5f,KAChDpK,OAAOC,eAAekd,GAAS/S,GAAM,CACnC7M,MAAOysB,GAAQ5f,IACfwT,UAAU,EACV1d,cAAc","x_google_ignoreList":[1]} \ No newline at end of file diff --git a/backend/node_modules/web-streams-polyfill/dist/polyfill.mjs b/backend/node_modules/web-streams-polyfill/dist/polyfill.mjs new file mode 100644 index 0000000000000000000000000000000000000000..f1dab863adbbc20493987282f0496b269870c46f --- /dev/null +++ b/backend/node_modules/web-streams-polyfill/dist/polyfill.mjs @@ -0,0 +1,4991 @@ +/** + * @license + * web-streams-polyfill v3.3.3 + * Copyright 2024 Mattias Buelens, Diwank Singh Tomer and other contributors. + * This code is released under the MIT license. + * SPDX-License-Identifier: MIT + */ +/// +var SymbolPolyfill = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? + Symbol : + function (description) { return "Symbol(".concat(description, ")"); }; + +/****************************************************************************** +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 */ + + +function __generator(thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (g && (g = 0, op[0] && (_ = 0)), _) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +} + +function __values(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); +} + +function __await(v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); +} + +function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } +} + +function __asyncDelegator(o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } +} + +function __asyncValues(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } +} + +typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; +}; + +function noop() { + return undefined; +} + +function typeIsObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; +} +var rethrowAssertionErrorRejection = noop; +function setFunctionName(fn, name) { + try { + Object.defineProperty(fn, 'name', { + value: name, + configurable: true + }); + } + catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility + } +} + +var originalPromise = Promise; +var originalPromiseThen = Promise.prototype.then; +var originalPromiseReject = Promise.reject.bind(originalPromise); +// https://webidl.spec.whatwg.org/#a-new-promise +function newPromise(executor) { + return new originalPromise(executor); +} +// https://webidl.spec.whatwg.org/#a-promise-resolved-with +function promiseResolvedWith(value) { + return newPromise(function (resolve) { return resolve(value); }); +} +// https://webidl.spec.whatwg.org/#a-promise-rejected-with +function promiseRejectedWith(reason) { + return originalPromiseReject(reason); +} +function PerformPromiseThen(promise, onFulfilled, onRejected) { + // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an + // approximation. + return originalPromiseThen.call(promise, onFulfilled, onRejected); +} +// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned +// from that handler. To prevent this, return null instead of void from all handlers. +// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it +function uponPromise(promise, onFulfilled, onRejected) { + PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection); +} +function uponFulfillment(promise, onFulfilled) { + uponPromise(promise, onFulfilled); +} +function uponRejection(promise, onRejected) { + uponPromise(promise, undefined, onRejected); +} +function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { + return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); +} +function setPromiseIsHandledToTrue(promise) { + PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection); +} +var _queueMicrotask = function (callback) { + if (typeof queueMicrotask === 'function') { + _queueMicrotask = queueMicrotask; + } + else { + var resolvedPromise_1 = promiseResolvedWith(undefined); + _queueMicrotask = function (cb) { return PerformPromiseThen(resolvedPromise_1, cb); }; + } + return _queueMicrotask(callback); +}; +function reflectCall(F, V, args) { + if (typeof F !== 'function') { + throw new TypeError('Argument is not a function'); + } + return Function.prototype.apply.call(F, V, args); +} +function promiseCall(F, V, args) { + try { + return promiseResolvedWith(reflectCall(F, V, args)); + } + catch (value) { + return promiseRejectedWith(value); + } +} + +// Original from Chromium +// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js +var QUEUE_MAX_ARRAY_SIZE = 16384; +/** + * Simple queue structure. + * + * Avoids scalability issues with using a packed array directly by using + * multiple arrays in a linked list and keeping the array size bounded. + */ +var SimpleQueue = /** @class */ (function () { + function SimpleQueue() { + this._cursor = 0; + this._size = 0; + // _front and _back are always defined. + this._front = { + _elements: [], + _next: undefined + }; + this._back = this._front; + // The cursor is used to avoid calling Array.shift(). + // It contains the index of the front element of the array inside the + // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE). + this._cursor = 0; + // When there is only one node, size === elements.length - cursor. + this._size = 0; + } + Object.defineProperty(SimpleQueue.prototype, "length", { + get: function () { + return this._size; + }, + enumerable: false, + configurable: true + }); + // For exception safety, this method is structured in order: + // 1. Read state + // 2. Calculate required state mutations + // 3. Perform state mutations + SimpleQueue.prototype.push = function (element) { + var oldBack = this._back; + var newBack = oldBack; + if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { + newBack = { + _elements: [], + _next: undefined + }; + } + // push() is the mutation most likely to throw an exception, so it + // goes first. + oldBack._elements.push(element); + if (newBack !== oldBack) { + this._back = newBack; + oldBack._next = newBack; + } + ++this._size; + }; + // Like push(), shift() follows the read -> calculate -> mutate pattern for + // exception safety. + SimpleQueue.prototype.shift = function () { // must not be called on an empty queue + var oldFront = this._front; + var newFront = oldFront; + var oldCursor = this._cursor; + var newCursor = oldCursor + 1; + var elements = oldFront._elements; + var element = elements[oldCursor]; + if (newCursor === QUEUE_MAX_ARRAY_SIZE) { + newFront = oldFront._next; + newCursor = 0; + } + // No mutations before this point. + --this._size; + this._cursor = newCursor; + if (oldFront !== newFront) { + this._front = newFront; + } + // Permit shifted element to be garbage collected. + elements[oldCursor] = undefined; + return element; + }; + // The tricky thing about forEach() is that it can be called + // re-entrantly. The queue may be mutated inside the callback. It is easy to + // see that push() within the callback has no negative effects since the end + // of the queue is checked for on every iteration. If shift() is called + // repeatedly within the callback then the next iteration may return an + // element that has been removed. In this case the callback will be called + // with undefined values until we either "catch up" with elements that still + // exist or reach the back of the queue. + SimpleQueue.prototype.forEach = function (callback) { + var i = this._cursor; + var node = this._front; + var elements = node._elements; + while (i !== elements.length || node._next !== undefined) { + if (i === elements.length) { + node = node._next; + elements = node._elements; + i = 0; + if (elements.length === 0) { + break; + } + } + callback(elements[i]); + ++i; + } + }; + // Return the element that would be returned if shift() was called now, + // without modifying the queue. + SimpleQueue.prototype.peek = function () { // must not be called on an empty queue + var front = this._front; + var cursor = this._cursor; + return front._elements[cursor]; + }; + return SimpleQueue; +}()); + +var AbortSteps = SymbolPolyfill('[[AbortSteps]]'); +var ErrorSteps = SymbolPolyfill('[[ErrorSteps]]'); +var CancelSteps = SymbolPolyfill('[[CancelSteps]]'); +var PullSteps = SymbolPolyfill('[[PullSteps]]'); +var ReleaseSteps = SymbolPolyfill('[[ReleaseSteps]]'); + +function ReadableStreamReaderGenericInitialize(reader, stream) { + reader._ownerReadableStream = stream; + stream._reader = reader; + if (stream._state === 'readable') { + defaultReaderClosedPromiseInitialize(reader); + } + else if (stream._state === 'closed') { + defaultReaderClosedPromiseInitializeAsResolved(reader); + } + else { + defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); + } +} +// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state +// check. +function ReadableStreamReaderGenericCancel(reader, reason) { + var stream = reader._ownerReadableStream; + return ReadableStreamCancel(stream, reason); +} +function ReadableStreamReaderGenericRelease(reader) { + var stream = reader._ownerReadableStream; + if (stream._state === 'readable') { + defaultReaderClosedPromiseReject(reader, new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")); + } + else { + defaultReaderClosedPromiseResetToRejected(reader, new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")); + } + stream._readableStreamController[ReleaseSteps](); + stream._reader = undefined; + reader._ownerReadableStream = undefined; +} +// Helper functions for the readers. +function readerLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released reader'); +} +// Helper functions for the ReadableStreamDefaultReader. +function defaultReaderClosedPromiseInitialize(reader) { + reader._closedPromise = newPromise(function (resolve, reject) { + reader._closedPromise_resolve = resolve; + reader._closedPromise_reject = reject; + }); +} +function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseReject(reader, reason); +} +function defaultReaderClosedPromiseInitializeAsResolved(reader) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseResolve(reader); +} +function defaultReaderClosedPromiseReject(reader, reason) { + if (reader._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(reader._closedPromise); + reader._closedPromise_reject(reason); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; +} +function defaultReaderClosedPromiseResetToRejected(reader, reason) { + defaultReaderClosedPromiseInitializeAsRejected(reader, reason); +} +function defaultReaderClosedPromiseResolve(reader) { + if (reader._closedPromise_resolve === undefined) { + return; + } + reader._closedPromise_resolve(undefined); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; +} + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill +var NumberIsFinite = Number.isFinite || function (x) { + return typeof x === 'number' && isFinite(x); +}; + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill +var MathTrunc = Math.trunc || function (v) { + return v < 0 ? Math.ceil(v) : Math.floor(v); +}; + +// https://heycam.github.io/webidl/#idl-dictionaries +function isDictionary(x) { + return typeof x === 'object' || typeof x === 'function'; +} +function assertDictionary(obj, context) { + if (obj !== undefined && !isDictionary(obj)) { + throw new TypeError("".concat(context, " is not an object.")); + } +} +// https://heycam.github.io/webidl/#idl-callback-functions +function assertFunction(x, context) { + if (typeof x !== 'function') { + throw new TypeError("".concat(context, " is not a function.")); + } +} +// https://heycam.github.io/webidl/#idl-object +function isObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; +} +function assertObject(x, context) { + if (!isObject(x)) { + throw new TypeError("".concat(context, " is not an object.")); + } +} +function assertRequiredArgument(x, position, context) { + if (x === undefined) { + throw new TypeError("Parameter ".concat(position, " is required in '").concat(context, "'.")); + } +} +function assertRequiredField(x, field, context) { + if (x === undefined) { + throw new TypeError("".concat(field, " is required in '").concat(context, "'.")); + } +} +// https://heycam.github.io/webidl/#idl-unrestricted-double +function convertUnrestrictedDouble(value) { + return Number(value); +} +function censorNegativeZero(x) { + return x === 0 ? 0 : x; +} +function integerPart(x) { + return censorNegativeZero(MathTrunc(x)); +} +// https://heycam.github.io/webidl/#idl-unsigned-long-long +function convertUnsignedLongLongWithEnforceRange(value, context) { + var lowerBound = 0; + var upperBound = Number.MAX_SAFE_INTEGER; + var x = Number(value); + x = censorNegativeZero(x); + if (!NumberIsFinite(x)) { + throw new TypeError("".concat(context, " is not a finite number")); + } + x = integerPart(x); + if (x < lowerBound || x > upperBound) { + throw new TypeError("".concat(context, " is outside the accepted range of ").concat(lowerBound, " to ").concat(upperBound, ", inclusive")); + } + if (!NumberIsFinite(x) || x === 0) { + return 0; + } + // TODO Use BigInt if supported? + // let xBigInt = BigInt(integerPart(x)); + // xBigInt = BigInt.asUintN(64, xBigInt); + // return Number(xBigInt); + return x; +} + +function assertReadableStream(x, context) { + if (!IsReadableStream(x)) { + throw new TypeError("".concat(context, " is not a ReadableStream.")); + } +} + +// Abstract operations for the ReadableStream. +function AcquireReadableStreamDefaultReader(stream) { + return new ReadableStreamDefaultReader(stream); +} +// ReadableStream API exposed for controllers. +function ReadableStreamAddReadRequest(stream, readRequest) { + stream._reader._readRequests.push(readRequest); +} +function ReadableStreamFulfillReadRequest(stream, chunk, done) { + var reader = stream._reader; + var readRequest = reader._readRequests.shift(); + if (done) { + readRequest._closeSteps(); + } + else { + readRequest._chunkSteps(chunk); + } +} +function ReadableStreamGetNumReadRequests(stream) { + return stream._reader._readRequests.length; +} +function ReadableStreamHasDefaultReader(stream) { + var reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamDefaultReader(reader)) { + return false; + } + return true; +} +/** + * A default reader vended by a {@link ReadableStream}. + * + * @public + */ +var ReadableStreamDefaultReader = /** @class */ (function () { + function ReadableStreamDefaultReader(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readRequests = new SimpleQueue(); + } + Object.defineProperty(ReadableStreamDefaultReader.prototype, "closed", { + /** + * Returns a promise that will be fulfilled when the stream becomes closed, + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + */ + get: function () { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('closed')); + } + return this._closedPromise; + }, + enumerable: false, + configurable: true + }); + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + ReadableStreamDefaultReader.prototype.cancel = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + }; + /** + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + ReadableStreamDefaultReader.prototype.read = function () { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('read')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + var resolvePromise; + var rejectPromise; + var promise = newPromise(function (resolve, reject) { + resolvePromise = resolve; + rejectPromise = reject; + }); + var readRequest = { + _chunkSteps: function (chunk) { return resolvePromise({ value: chunk, done: false }); }, + _closeSteps: function () { return resolvePromise({ value: undefined, done: true }); }, + _errorSteps: function (e) { return rejectPromise(e); } + }; + ReadableStreamDefaultReaderRead(this, readRequest); + return promise; + }; + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + ReadableStreamDefaultReader.prototype.releaseLock = function () { + if (!IsReadableStreamDefaultReader(this)) { + throw defaultReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamDefaultReaderRelease(this); + }; + return ReadableStreamDefaultReader; +}()); +Object.defineProperties(ReadableStreamDefaultReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } +}); +setFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel'); +setFunctionName(ReadableStreamDefaultReader.prototype.read, 'read'); +setFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultReader', + configurable: true + }); +} +// Abstract operations for the readers. +function IsReadableStreamDefaultReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) { + return false; + } + return x instanceof ReadableStreamDefaultReader; +} +function ReadableStreamDefaultReaderRead(reader, readRequest) { + var stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'closed') { + readRequest._closeSteps(); + } + else if (stream._state === 'errored') { + readRequest._errorSteps(stream._storedError); + } + else { + stream._readableStreamController[PullSteps](readRequest); + } +} +function ReadableStreamDefaultReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + var e = new TypeError('Reader was released'); + ReadableStreamDefaultReaderErrorReadRequests(reader, e); +} +function ReadableStreamDefaultReaderErrorReadRequests(reader, e) { + var readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(function (readRequest) { + readRequest._errorSteps(e); + }); +} +// Helper functions for the ReadableStreamDefaultReader. +function defaultReaderBrandCheckException(name) { + return new TypeError("ReadableStreamDefaultReader.prototype.".concat(name, " can only be used on a ReadableStreamDefaultReader")); +} + +var _a$1, _b, _c; +function CreateArrayFromList(elements) { + // We use arrays to represent lists, so this is basically a no-op. + // Do a slice though just in case we happen to depend on the unique-ness. + return elements.slice(); +} +function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { + new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); +} +var TransferArrayBuffer = function (O) { + if (typeof O.transfer === 'function') { + TransferArrayBuffer = function (buffer) { return buffer.transfer(); }; + } + else if (typeof structuredClone === 'function') { + TransferArrayBuffer = function (buffer) { return structuredClone(buffer, { transfer: [buffer] }); }; + } + else { + // Not implemented correctly + TransferArrayBuffer = function (buffer) { return buffer; }; + } + return TransferArrayBuffer(O); +}; +var IsDetachedBuffer = function (O) { + if (typeof O.detached === 'boolean') { + IsDetachedBuffer = function (buffer) { return buffer.detached; }; + } + else { + // Not implemented correctly + IsDetachedBuffer = function (buffer) { return buffer.byteLength === 0; }; + } + return IsDetachedBuffer(O); +}; +function ArrayBufferSlice(buffer, begin, end) { + // ArrayBuffer.prototype.slice is not available on IE10 + // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice + if (buffer.slice) { + return buffer.slice(begin, end); + } + var length = end - begin; + var slice = new ArrayBuffer(length); + CopyDataBlockBytes(slice, 0, buffer, begin, length); + return slice; +} +function GetMethod(receiver, prop) { + var func = receiver[prop]; + if (func === undefined || func === null) { + return undefined; + } + if (typeof func !== 'function') { + throw new TypeError("".concat(String(prop), " is not a function")); + } + return func; +} +function CreateAsyncFromSyncIterator(syncIteratorRecord) { + // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%, + // we use yield* inside an async generator function to achieve the same result. + var _a; + // Wrap the sync iterator inside a sync iterable, so we can use it with yield*. + var syncIterable = (_a = {}, + _a[SymbolPolyfill.iterator] = function () { return syncIteratorRecord.iterator; }, + _a); + // Create an async generator function and immediately invoke it. + var asyncIterator = (function () { + return __asyncGenerator(this, arguments, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [5 /*yield**/, __values(__asyncDelegator(__asyncValues(syncIterable)))]; + case 1: return [4 /*yield*/, __await.apply(void 0, [_a.sent()])]; + case 2: return [4 /*yield*/, __await.apply(void 0, [_a.sent()])]; + case 3: return [2 /*return*/, _a.sent()]; + } + }); + }); + }()); + // Return as an async iterator record. + var nextMethod = asyncIterator.next; + return { iterator: asyncIterator, nextMethod: nextMethod, done: false }; +} +// Aligns with core-js/modules/es.symbol.async-iterator.js +var SymbolAsyncIterator = (_c = (_a$1 = SymbolPolyfill.asyncIterator) !== null && _a$1 !== void 0 ? _a$1 : (_b = SymbolPolyfill.for) === null || _b === void 0 ? void 0 : _b.call(SymbolPolyfill, 'Symbol.asyncIterator')) !== null && _c !== void 0 ? _c : '@@asyncIterator'; +function GetIterator(obj, hint, method) { + if (hint === void 0) { hint = 'sync'; } + if (method === undefined) { + if (hint === 'async') { + method = GetMethod(obj, SymbolAsyncIterator); + if (method === undefined) { + var syncMethod = GetMethod(obj, SymbolPolyfill.iterator); + var syncIteratorRecord = GetIterator(obj, 'sync', syncMethod); + return CreateAsyncFromSyncIterator(syncIteratorRecord); + } + } + else { + method = GetMethod(obj, SymbolPolyfill.iterator); + } + } + if (method === undefined) { + throw new TypeError('The object is not iterable'); + } + var iterator = reflectCall(method, obj, []); + if (!typeIsObject(iterator)) { + throw new TypeError('The iterator method must return an object'); + } + var nextMethod = iterator.next; + return { iterator: iterator, nextMethod: nextMethod, done: false }; +} +function IteratorNext(iteratorRecord) { + var result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []); + if (!typeIsObject(result)) { + throw new TypeError('The iterator.next() method must return an object'); + } + return result; +} +function IteratorComplete(iterResult) { + return Boolean(iterResult.done); +} +function IteratorValue(iterResult) { + return iterResult.value; +} + +/// +var _a; +// We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it. +var AsyncIteratorPrototype = (_a = {}, + // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( ) + // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator + _a[SymbolAsyncIterator] = function () { + return this; + }, + _a); +Object.defineProperty(AsyncIteratorPrototype, SymbolAsyncIterator, { enumerable: false }); + +/// +var ReadableStreamAsyncIteratorImpl = /** @class */ (function () { + function ReadableStreamAsyncIteratorImpl(reader, preventCancel) { + this._ongoingPromise = undefined; + this._isFinished = false; + this._reader = reader; + this._preventCancel = preventCancel; + } + ReadableStreamAsyncIteratorImpl.prototype.next = function () { + var _this = this; + var nextSteps = function () { return _this._nextSteps(); }; + this._ongoingPromise = this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : + nextSteps(); + return this._ongoingPromise; + }; + ReadableStreamAsyncIteratorImpl.prototype.return = function (value) { + var _this = this; + var returnSteps = function () { return _this._returnSteps(value); }; + return this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : + returnSteps(); + }; + ReadableStreamAsyncIteratorImpl.prototype._nextSteps = function () { + var _this = this; + if (this._isFinished) { + return Promise.resolve({ value: undefined, done: true }); + } + var reader = this._reader; + var resolvePromise; + var rejectPromise; + var promise = newPromise(function (resolve, reject) { + resolvePromise = resolve; + rejectPromise = reject; + }); + var readRequest = { + _chunkSteps: function (chunk) { + _this._ongoingPromise = undefined; + // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test. + // FIXME Is this a bug in the specification, or in the test? + _queueMicrotask(function () { return resolvePromise({ value: chunk, done: false }); }); + }, + _closeSteps: function () { + _this._ongoingPromise = undefined; + _this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + resolvePromise({ value: undefined, done: true }); + }, + _errorSteps: function (reason) { + _this._ongoingPromise = undefined; + _this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + rejectPromise(reason); + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promise; + }; + ReadableStreamAsyncIteratorImpl.prototype._returnSteps = function (value) { + if (this._isFinished) { + return Promise.resolve({ value: value, done: true }); + } + this._isFinished = true; + var reader = this._reader; + if (!this._preventCancel) { + var result = ReadableStreamReaderGenericCancel(reader, value); + ReadableStreamReaderGenericRelease(reader); + return transformPromiseWith(result, function () { return ({ value: value, done: true }); }); + } + ReadableStreamReaderGenericRelease(reader); + return promiseResolvedWith({ value: value, done: true }); + }; + return ReadableStreamAsyncIteratorImpl; +}()); +var ReadableStreamAsyncIteratorPrototype = { + next: function () { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next')); + } + return this._asyncIteratorImpl.next(); + }, + return: function (value) { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return')); + } + return this._asyncIteratorImpl.return(value); + } +}; +Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); +// Abstract operations for the ReadableStream. +function AcquireReadableStreamAsyncIterator(stream, preventCancel) { + var reader = AcquireReadableStreamDefaultReader(stream); + var impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); + var iterator = Object.create(ReadableStreamAsyncIteratorPrototype); + iterator._asyncIteratorImpl = impl; + return iterator; +} +function IsReadableStreamAsyncIterator(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) { + return false; + } + try { + // noinspection SuspiciousTypeOfGuard + return x._asyncIteratorImpl instanceof + ReadableStreamAsyncIteratorImpl; + } + catch (_a) { + return false; + } +} +// Helper functions for the ReadableStream. +function streamAsyncIteratorBrandCheckException(name) { + return new TypeError("ReadableStreamAsyncIterator.".concat(name, " can only be used on a ReadableSteamAsyncIterator")); +} + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill +var NumberIsNaN = Number.isNaN || function (x) { + // eslint-disable-next-line no-self-compare + return x !== x; +}; + +function IsNonNegativeNumber(v) { + if (typeof v !== 'number') { + return false; + } + if (NumberIsNaN(v)) { + return false; + } + if (v < 0) { + return false; + } + return true; +} +function CloneAsUint8Array(O) { + var buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength); + return new Uint8Array(buffer); +} + +function DequeueValue(container) { + var pair = container._queue.shift(); + container._queueTotalSize -= pair.size; + if (container._queueTotalSize < 0) { + container._queueTotalSize = 0; + } + return pair.value; +} +function EnqueueValueWithSize(container, value, size) { + if (!IsNonNegativeNumber(size) || size === Infinity) { + throw new RangeError('Size must be a finite, non-NaN, non-negative number.'); + } + container._queue.push({ value: value, size: size }); + container._queueTotalSize += size; +} +function PeekQueueValue(container) { + var pair = container._queue.peek(); + return pair.value; +} +function ResetQueue(container) { + container._queue = new SimpleQueue(); + container._queueTotalSize = 0; +} + +function isDataViewConstructor(ctor) { + return ctor === DataView; +} +function isDataView(view) { + return isDataViewConstructor(view.constructor); +} +function arrayBufferViewElementSize(ctor) { + if (isDataViewConstructor(ctor)) { + return 1; + } + return ctor.BYTES_PER_ELEMENT; +} + +/** + * A pull-into request in a {@link ReadableByteStreamController}. + * + * @public + */ +var ReadableStreamBYOBRequest = /** @class */ (function () { + function ReadableStreamBYOBRequest() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(ReadableStreamBYOBRequest.prototype, "view", { + /** + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. + */ + get: function () { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('view'); + } + return this._view; + }, + enumerable: false, + configurable: true + }); + ReadableStreamBYOBRequest.prototype.respond = function (bytesWritten) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respond'); + } + assertRequiredArgument(bytesWritten, 1, 'respond'); + bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter'); + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(this._view.buffer)) { + throw new TypeError("The BYOB request's buffer has been detached and so cannot be used as a response"); + } + ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); + }; + ReadableStreamBYOBRequest.prototype.respondWithNewView = function (view) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respondWithNewView'); + } + assertRequiredArgument(view, 1, 'respondWithNewView'); + if (!ArrayBuffer.isView(view)) { + throw new TypeError('You can only respond with array buffer views'); + } + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(view.buffer)) { + throw new TypeError('The given view\'s buffer has been detached and so cannot be used as a response'); + } + ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); + }; + return ReadableStreamBYOBRequest; +}()); +Object.defineProperties(ReadableStreamBYOBRequest.prototype, { + respond: { enumerable: true }, + respondWithNewView: { enumerable: true }, + view: { enumerable: true } +}); +setFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond'); +setFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBRequest', + configurable: true + }); +} +/** + * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. + * + * @public + */ +var ReadableByteStreamController = /** @class */ (function () { + function ReadableByteStreamController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(ReadableByteStreamController.prototype, "byobRequest", { + /** + * Returns the current BYOB pull request, or `null` if there isn't one. + */ + get: function () { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('byobRequest'); + } + return ReadableByteStreamControllerGetBYOBRequest(this); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ReadableByteStreamController.prototype, "desiredSize", { + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + */ + get: function () { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('desiredSize'); + } + return ReadableByteStreamControllerGetDesiredSize(this); + }, + enumerable: false, + configurable: true + }); + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + ReadableByteStreamController.prototype.close = function () { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('close'); + } + if (this._closeRequested) { + throw new TypeError('The stream has already been closed; do not close it again!'); + } + var state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError("The stream (in ".concat(state, " state) is not in the readable state and cannot be closed")); + } + ReadableByteStreamControllerClose(this); + }; + ReadableByteStreamController.prototype.enqueue = function (chunk) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('enqueue'); + } + assertRequiredArgument(chunk, 1, 'enqueue'); + if (!ArrayBuffer.isView(chunk)) { + throw new TypeError('chunk must be an array buffer view'); + } + if (chunk.byteLength === 0) { + throw new TypeError('chunk must have non-zero byteLength'); + } + if (chunk.buffer.byteLength === 0) { + throw new TypeError("chunk's buffer must have non-zero byteLength"); + } + if (this._closeRequested) { + throw new TypeError('stream is closed or draining'); + } + var state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError("The stream (in ".concat(state, " state) is not in the readable state and cannot be enqueued to")); + } + ReadableByteStreamControllerEnqueue(this, chunk); + }; + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + ReadableByteStreamController.prototype.error = function (e) { + if (e === void 0) { e = undefined; } + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('error'); + } + ReadableByteStreamControllerError(this, e); + }; + /** @internal */ + ReadableByteStreamController.prototype[CancelSteps] = function (reason) { + ReadableByteStreamControllerClearPendingPullIntos(this); + ResetQueue(this); + var result = this._cancelAlgorithm(reason); + ReadableByteStreamControllerClearAlgorithms(this); + return result; + }; + /** @internal */ + ReadableByteStreamController.prototype[PullSteps] = function (readRequest) { + var stream = this._controlledReadableByteStream; + if (this._queueTotalSize > 0) { + ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest); + return; + } + var autoAllocateChunkSize = this._autoAllocateChunkSize; + if (autoAllocateChunkSize !== undefined) { + var buffer = void 0; + try { + buffer = new ArrayBuffer(autoAllocateChunkSize); + } + catch (bufferE) { + readRequest._errorSteps(bufferE); + return; + } + var pullIntoDescriptor = { + buffer: buffer, + bufferByteLength: autoAllocateChunkSize, + byteOffset: 0, + byteLength: autoAllocateChunkSize, + bytesFilled: 0, + minimumFill: 1, + elementSize: 1, + viewConstructor: Uint8Array, + readerType: 'default' + }; + this._pendingPullIntos.push(pullIntoDescriptor); + } + ReadableStreamAddReadRequest(stream, readRequest); + ReadableByteStreamControllerCallPullIfNeeded(this); + }; + /** @internal */ + ReadableByteStreamController.prototype[ReleaseSteps] = function () { + if (this._pendingPullIntos.length > 0) { + var firstPullInto = this._pendingPullIntos.peek(); + firstPullInto.readerType = 'none'; + this._pendingPullIntos = new SimpleQueue(); + this._pendingPullIntos.push(firstPullInto); + } + }; + return ReadableByteStreamController; +}()); +Object.defineProperties(ReadableByteStreamController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + byobRequest: { enumerable: true }, + desiredSize: { enumerable: true } +}); +setFunctionName(ReadableByteStreamController.prototype.close, 'close'); +setFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue'); +setFunctionName(ReadableByteStreamController.prototype.error, 'error'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableByteStreamController', + configurable: true + }); +} +// Abstract operations for the ReadableByteStreamController. +function IsReadableByteStreamController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) { + return false; + } + return x instanceof ReadableByteStreamController; +} +function IsReadableStreamBYOBRequest(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) { + return false; + } + return x instanceof ReadableStreamBYOBRequest; +} +function ReadableByteStreamControllerCallPullIfNeeded(controller) { + var shouldPull = ReadableByteStreamControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + // TODO: Test controller argument + var pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, function () { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + return null; + }, function (e) { + ReadableByteStreamControllerError(controller, e); + return null; + }); +} +function ReadableByteStreamControllerClearPendingPullIntos(controller) { + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + controller._pendingPullIntos = new SimpleQueue(); +} +function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { + var done = false; + if (stream._state === 'closed') { + done = true; + } + var filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'default') { + ReadableStreamFulfillReadRequest(stream, filledView, done); + } + else { + ReadableStreamFulfillReadIntoRequest(stream, filledView, done); + } +} +function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { + var bytesFilled = pullIntoDescriptor.bytesFilled; + var elementSize = pullIntoDescriptor.elementSize; + return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); +} +function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { + controller._queue.push({ buffer: buffer, byteOffset: byteOffset, byteLength: byteLength }); + controller._queueTotalSize += byteLength; +} +function ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, buffer, byteOffset, byteLength) { + var clonedChunk; + try { + clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength); + } + catch (cloneE) { + ReadableByteStreamControllerError(controller, cloneE); + throw cloneE; + } + ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength); +} +function ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstDescriptor) { + if (firstDescriptor.bytesFilled > 0) { + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, firstDescriptor.buffer, firstDescriptor.byteOffset, firstDescriptor.bytesFilled); + } + ReadableByteStreamControllerShiftPendingPullInto(controller); +} +function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { + var maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); + var maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; + var totalBytesToCopyRemaining = maxBytesToCopy; + var ready = false; + var remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize; + var maxAlignedBytes = maxBytesFilled - remainderBytes; + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) { + totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; + ready = true; + } + var queue = controller._queue; + while (totalBytesToCopyRemaining > 0) { + var headOfQueue = queue.peek(); + var bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); + var destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); + if (headOfQueue.byteLength === bytesToCopy) { + queue.shift(); + } + else { + headOfQueue.byteOffset += bytesToCopy; + headOfQueue.byteLength -= bytesToCopy; + } + controller._queueTotalSize -= bytesToCopy; + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); + totalBytesToCopyRemaining -= bytesToCopy; + } + return ready; +} +function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { + pullIntoDescriptor.bytesFilled += size; +} +function ReadableByteStreamControllerHandleQueueDrain(controller) { + if (controller._queueTotalSize === 0 && controller._closeRequested) { + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(controller._controlledReadableByteStream); + } + else { + ReadableByteStreamControllerCallPullIfNeeded(controller); + } +} +function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { + if (controller._byobRequest === null) { + return; + } + controller._byobRequest._associatedReadableByteStreamController = undefined; + controller._byobRequest._view = null; + controller._byobRequest = null; +} +function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { + while (controller._pendingPullIntos.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + var pullIntoDescriptor = controller._pendingPullIntos.peek(); + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + } + } +} +function ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller) { + var reader = controller._controlledReadableByteStream._reader; + while (reader._readRequests.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + var readRequest = reader._readRequests.shift(); + ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest); + } +} +function ReadableByteStreamControllerPullInto(controller, view, min, readIntoRequest) { + var stream = controller._controlledReadableByteStream; + var ctor = view.constructor; + var elementSize = arrayBufferViewElementSize(ctor); + var byteOffset = view.byteOffset, byteLength = view.byteLength; + var minimumFill = min * elementSize; + var buffer; + try { + buffer = TransferArrayBuffer(view.buffer); + } + catch (e) { + readIntoRequest._errorSteps(e); + return; + } + var pullIntoDescriptor = { + buffer: buffer, + bufferByteLength: buffer.byteLength, + byteOffset: byteOffset, + byteLength: byteLength, + bytesFilled: 0, + minimumFill: minimumFill, + elementSize: elementSize, + viewConstructor: ctor, + readerType: 'byob' + }; + if (controller._pendingPullIntos.length > 0) { + controller._pendingPullIntos.push(pullIntoDescriptor); + // No ReadableByteStreamControllerCallPullIfNeeded() call since: + // - No change happens on desiredSize + // - The source has already been notified of that there's at least 1 pending read(view) + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + return; + } + if (stream._state === 'closed') { + var emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); + readIntoRequest._closeSteps(emptyView); + return; + } + if (controller._queueTotalSize > 0) { + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + var filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + ReadableByteStreamControllerHandleQueueDrain(controller); + readIntoRequest._chunkSteps(filledView); + return; + } + if (controller._closeRequested) { + var e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + readIntoRequest._errorSteps(e); + return; + } + } + controller._pendingPullIntos.push(pullIntoDescriptor); + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { + if (firstDescriptor.readerType === 'none') { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + var stream = controller._controlledReadableByteStream; + if (ReadableStreamHasBYOBReader(stream)) { + while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { + var pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); + } + } +} +function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + return; + } + if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) { + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + return; + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + var remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; + if (remainderSize > 0) { + var end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor.buffer, end - remainderSize, remainderSize); + } + pullIntoDescriptor.bytesFilled -= remainderSize; + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); +} +function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { + var firstDescriptor = controller._pendingPullIntos.peek(); + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + var state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor); + } + else { + ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerShiftPendingPullInto(controller) { + var descriptor = controller._pendingPullIntos.shift(); + return descriptor; +} +function ReadableByteStreamControllerShouldCallPull(controller) { + var stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return false; + } + if (controller._closeRequested) { + return false; + } + if (!controller._started) { + return false; + } + if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { + return true; + } + var desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; +} +function ReadableByteStreamControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; +} +// A client of ReadableByteStreamController may use these functions directly to bypass state check. +function ReadableByteStreamControllerClose(controller) { + var stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + if (controller._queueTotalSize > 0) { + controller._closeRequested = true; + return; + } + if (controller._pendingPullIntos.length > 0) { + var firstPendingPullInto = controller._pendingPullIntos.peek(); + if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) { + var e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + throw e; + } + } + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(stream); +} +function ReadableByteStreamControllerEnqueue(controller, chunk) { + var stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + var buffer = chunk.buffer, byteOffset = chunk.byteOffset, byteLength = chunk.byteLength; + if (IsDetachedBuffer(buffer)) { + throw new TypeError('chunk\'s buffer is detached and so cannot be enqueued'); + } + var transferredBuffer = TransferArrayBuffer(buffer); + if (controller._pendingPullIntos.length > 0) { + var firstPendingPullInto = controller._pendingPullIntos.peek(); + if (IsDetachedBuffer(firstPendingPullInto.buffer)) { + throw new TypeError('The BYOB request\'s buffer has been detached and so cannot be filled with an enqueued chunk'); + } + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer); + if (firstPendingPullInto.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto); + } + } + if (ReadableStreamHasDefaultReader(stream)) { + ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller); + if (ReadableStreamGetNumReadRequests(stream) === 0) { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + else { + if (controller._pendingPullIntos.length > 0) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + var transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); + ReadableStreamFulfillReadRequest(stream, transferredView, false); + } + } + else if (ReadableStreamHasBYOBReader(stream)) { + // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully. + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + else { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerError(controller, e) { + var stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return; + } + ReadableByteStreamControllerClearPendingPullIntos(controller); + ResetQueue(controller); + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); +} +function ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest) { + var entry = controller._queue.shift(); + controller._queueTotalSize -= entry.byteLength; + ReadableByteStreamControllerHandleQueueDrain(controller); + var view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); + readRequest._chunkSteps(view); +} +function ReadableByteStreamControllerGetBYOBRequest(controller) { + if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) { + var firstDescriptor = controller._pendingPullIntos.peek(); + var view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); + var byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); + SetUpReadableStreamBYOBRequest(byobRequest, controller, view); + controller._byobRequest = byobRequest; + } + return controller._byobRequest; +} +function ReadableByteStreamControllerGetDesiredSize(controller) { + var state = controller._controlledReadableByteStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; +} +function ReadableByteStreamControllerRespond(controller, bytesWritten) { + var firstDescriptor = controller._pendingPullIntos.peek(); + var state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (bytesWritten !== 0) { + throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream'); + } + } + else { + if (bytesWritten === 0) { + throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream'); + } + if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) { + throw new RangeError('bytesWritten out of range'); + } + } + firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); + ReadableByteStreamControllerRespondInternal(controller, bytesWritten); +} +function ReadableByteStreamControllerRespondWithNewView(controller, view) { + var firstDescriptor = controller._pendingPullIntos.peek(); + var state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (view.byteLength !== 0) { + throw new TypeError('The view\'s length must be 0 when calling respondWithNewView() on a closed stream'); + } + } + else { + if (view.byteLength === 0) { + throw new TypeError('The view\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'); + } + } + if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { + throw new RangeError('The region specified by view does not match byobRequest'); + } + if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) { + throw new RangeError('The buffer of view has different capacity than byobRequest'); + } + if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) { + throw new RangeError('The region specified by view is larger than byobRequest'); + } + var viewByteLength = view.byteLength; + firstDescriptor.buffer = TransferArrayBuffer(view.buffer); + ReadableByteStreamControllerRespondInternal(controller, viewByteLength); +} +function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { + controller._controlledReadableByteStream = stream; + controller._pullAgain = false; + controller._pulling = false; + controller._byobRequest = null; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._closeRequested = false; + controller._started = false; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._autoAllocateChunkSize = autoAllocateChunkSize; + controller._pendingPullIntos = new SimpleQueue(); + stream._readableStreamController = controller; + var startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), function () { + controller._started = true; + ReadableByteStreamControllerCallPullIfNeeded(controller); + return null; + }, function (r) { + ReadableByteStreamControllerError(controller, r); + return null; + }); +} +function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { + var controller = Object.create(ReadableByteStreamController.prototype); + var startAlgorithm; + var pullAlgorithm; + var cancelAlgorithm; + if (underlyingByteSource.start !== undefined) { + startAlgorithm = function () { return underlyingByteSource.start(controller); }; + } + else { + startAlgorithm = function () { return undefined; }; + } + if (underlyingByteSource.pull !== undefined) { + pullAlgorithm = function () { return underlyingByteSource.pull(controller); }; + } + else { + pullAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + if (underlyingByteSource.cancel !== undefined) { + cancelAlgorithm = function (reason) { return underlyingByteSource.cancel(reason); }; + } + else { + cancelAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + var autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; + if (autoAllocateChunkSize === 0) { + throw new TypeError('autoAllocateChunkSize must be greater than 0'); + } + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); +} +function SetUpReadableStreamBYOBRequest(request, controller, view) { + request._associatedReadableByteStreamController = controller; + request._view = view; +} +// Helper functions for the ReadableStreamBYOBRequest. +function byobRequestBrandCheckException(name) { + return new TypeError("ReadableStreamBYOBRequest.prototype.".concat(name, " can only be used on a ReadableStreamBYOBRequest")); +} +// Helper functions for the ReadableByteStreamController. +function byteStreamControllerBrandCheckException(name) { + return new TypeError("ReadableByteStreamController.prototype.".concat(name, " can only be used on a ReadableByteStreamController")); +} + +function convertReaderOptions(options, context) { + assertDictionary(options, context); + var mode = options === null || options === void 0 ? void 0 : options.mode; + return { + mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, "".concat(context, " has member 'mode' that")) + }; +} +function convertReadableStreamReaderMode(mode, context) { + mode = "".concat(mode); + if (mode !== 'byob') { + throw new TypeError("".concat(context, " '").concat(mode, "' is not a valid enumeration value for ReadableStreamReaderMode")); + } + return mode; +} +function convertByobReadOptions(options, context) { + var _a; + assertDictionary(options, context); + var min = (_a = options === null || options === void 0 ? void 0 : options.min) !== null && _a !== void 0 ? _a : 1; + return { + min: convertUnsignedLongLongWithEnforceRange(min, "".concat(context, " has member 'min' that")) + }; +} + +// Abstract operations for the ReadableStream. +function AcquireReadableStreamBYOBReader(stream) { + return new ReadableStreamBYOBReader(stream); +} +// ReadableStream API exposed for controllers. +function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { + stream._reader._readIntoRequests.push(readIntoRequest); +} +function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { + var reader = stream._reader; + var readIntoRequest = reader._readIntoRequests.shift(); + if (done) { + readIntoRequest._closeSteps(chunk); + } + else { + readIntoRequest._chunkSteps(chunk); + } +} +function ReadableStreamGetNumReadIntoRequests(stream) { + return stream._reader._readIntoRequests.length; +} +function ReadableStreamHasBYOBReader(stream) { + var reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamBYOBReader(reader)) { + return false; + } + return true; +} +/** + * A BYOB reader vended by a {@link ReadableStream}. + * + * @public + */ +var ReadableStreamBYOBReader = /** @class */ (function () { + function ReadableStreamBYOBReader(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + if (!IsReadableByteStreamController(stream._readableStreamController)) { + throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' + + 'source'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readIntoRequests = new SimpleQueue(); + } + Object.defineProperty(ReadableStreamBYOBReader.prototype, "closed", { + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the reader's lock is released before the stream finishes closing. + */ + get: function () { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('closed')); + } + return this._closedPromise; + }, + enumerable: false, + configurable: true + }); + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + ReadableStreamBYOBReader.prototype.cancel = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + }; + ReadableStreamBYOBReader.prototype.read = function (view, rawOptions) { + if (rawOptions === void 0) { rawOptions = {}; } + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('read')); + } + if (!ArrayBuffer.isView(view)) { + return promiseRejectedWith(new TypeError('view must be an array buffer view')); + } + if (view.byteLength === 0) { + return promiseRejectedWith(new TypeError('view must have non-zero byteLength')); + } + if (view.buffer.byteLength === 0) { + return promiseRejectedWith(new TypeError("view's buffer must have non-zero byteLength")); + } + if (IsDetachedBuffer(view.buffer)) { + return promiseRejectedWith(new TypeError('view\'s buffer has been detached')); + } + var options; + try { + options = convertByobReadOptions(rawOptions, 'options'); + } + catch (e) { + return promiseRejectedWith(e); + } + var min = options.min; + if (min === 0) { + return promiseRejectedWith(new TypeError('options.min must be greater than 0')); + } + if (!isDataView(view)) { + if (min > view.length) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s length')); + } + } + else if (min > view.byteLength) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s byteLength')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + var resolvePromise; + var rejectPromise; + var promise = newPromise(function (resolve, reject) { + resolvePromise = resolve; + rejectPromise = reject; + }); + var readIntoRequest = { + _chunkSteps: function (chunk) { return resolvePromise({ value: chunk, done: false }); }, + _closeSteps: function (chunk) { return resolvePromise({ value: chunk, done: true }); }, + _errorSteps: function (e) { return rejectPromise(e); } + }; + ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest); + return promise; + }; + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + ReadableStreamBYOBReader.prototype.releaseLock = function () { + if (!IsReadableStreamBYOBReader(this)) { + throw byobReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamBYOBReaderRelease(this); + }; + return ReadableStreamBYOBReader; +}()); +Object.defineProperties(ReadableStreamBYOBReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } +}); +setFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel'); +setFunctionName(ReadableStreamBYOBReader.prototype.read, 'read'); +setFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBReader', + configurable: true + }); +} +// Abstract operations for the readers. +function IsReadableStreamBYOBReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) { + return false; + } + return x instanceof ReadableStreamBYOBReader; +} +function ReadableStreamBYOBReaderRead(reader, view, min, readIntoRequest) { + var stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'errored') { + readIntoRequest._errorSteps(stream._storedError); + } + else { + ReadableByteStreamControllerPullInto(stream._readableStreamController, view, min, readIntoRequest); + } +} +function ReadableStreamBYOBReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + var e = new TypeError('Reader was released'); + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); +} +function ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e) { + var readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(function (readIntoRequest) { + readIntoRequest._errorSteps(e); + }); +} +// Helper functions for the ReadableStreamBYOBReader. +function byobReaderBrandCheckException(name) { + return new TypeError("ReadableStreamBYOBReader.prototype.".concat(name, " can only be used on a ReadableStreamBYOBReader")); +} + +function ExtractHighWaterMark(strategy, defaultHWM) { + var highWaterMark = strategy.highWaterMark; + if (highWaterMark === undefined) { + return defaultHWM; + } + if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { + throw new RangeError('Invalid highWaterMark'); + } + return highWaterMark; +} +function ExtractSizeAlgorithm(strategy) { + var size = strategy.size; + if (!size) { + return function () { return 1; }; + } + return size; +} + +function convertQueuingStrategy(init, context) { + assertDictionary(init, context); + var highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + var size = init === null || init === void 0 ? void 0 : init.size; + return { + highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark), + size: size === undefined ? undefined : convertQueuingStrategySize(size, "".concat(context, " has member 'size' that")) + }; +} +function convertQueuingStrategySize(fn, context) { + assertFunction(fn, context); + return function (chunk) { return convertUnrestrictedDouble(fn(chunk)); }; +} + +function convertUnderlyingSink(original, context) { + assertDictionary(original, context); + var abort = original === null || original === void 0 ? void 0 : original.abort; + var close = original === null || original === void 0 ? void 0 : original.close; + var start = original === null || original === void 0 ? void 0 : original.start; + var type = original === null || original === void 0 ? void 0 : original.type; + var write = original === null || original === void 0 ? void 0 : original.write; + return { + abort: abort === undefined ? + undefined : + convertUnderlyingSinkAbortCallback(abort, original, "".concat(context, " has member 'abort' that")), + close: close === undefined ? + undefined : + convertUnderlyingSinkCloseCallback(close, original, "".concat(context, " has member 'close' that")), + start: start === undefined ? + undefined : + convertUnderlyingSinkStartCallback(start, original, "".concat(context, " has member 'start' that")), + write: write === undefined ? + undefined : + convertUnderlyingSinkWriteCallback(write, original, "".concat(context, " has member 'write' that")), + type: type + }; +} +function convertUnderlyingSinkAbortCallback(fn, original, context) { + assertFunction(fn, context); + return function (reason) { return promiseCall(fn, original, [reason]); }; +} +function convertUnderlyingSinkCloseCallback(fn, original, context) { + assertFunction(fn, context); + return function () { return promiseCall(fn, original, []); }; +} +function convertUnderlyingSinkStartCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return reflectCall(fn, original, [controller]); }; +} +function convertUnderlyingSinkWriteCallback(fn, original, context) { + assertFunction(fn, context); + return function (chunk, controller) { return promiseCall(fn, original, [chunk, controller]); }; +} + +function assertWritableStream(x, context) { + if (!IsWritableStream(x)) { + throw new TypeError("".concat(context, " is not a WritableStream.")); + } +} + +function isAbortSignal(value) { + if (typeof value !== 'object' || value === null) { + return false; + } + try { + return typeof value.aborted === 'boolean'; + } + catch (_a) { + // AbortSignal.prototype.aborted throws if its brand check fails + return false; + } +} +var supportsAbortController = typeof AbortController === 'function'; +/** + * Construct a new AbortController, if supported by the platform. + * + * @internal + */ +function createAbortController() { + if (supportsAbortController) { + return new AbortController(); + } + return undefined; +} + +/** + * A writable stream represents a destination for data, into which you can write. + * + * @public + */ +var WritableStream = /** @class */ (function () { + function WritableStream(rawUnderlyingSink, rawStrategy) { + if (rawUnderlyingSink === void 0) { rawUnderlyingSink = {}; } + if (rawStrategy === void 0) { rawStrategy = {}; } + if (rawUnderlyingSink === undefined) { + rawUnderlyingSink = null; + } + else { + assertObject(rawUnderlyingSink, 'First parameter'); + } + var strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + var underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter'); + InitializeWritableStream(this); + var type = underlyingSink.type; + if (type !== undefined) { + throw new RangeError('Invalid type is specified'); + } + var sizeAlgorithm = ExtractSizeAlgorithm(strategy); + var highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); + } + Object.defineProperty(WritableStream.prototype, "locked", { + /** + * Returns whether or not the writable stream is locked to a writer. + */ + get: function () { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('locked'); + } + return IsWritableStreamLocked(this); + }, + enumerable: false, + configurable: true + }); + /** + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort + * mechanism of the underlying sink. + * + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel + * the stream) if the stream is currently locked. + */ + WritableStream.prototype.abort = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('abort')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer')); + } + return WritableStreamAbort(this, reason); + }; + /** + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its + * close behavior. During this time any further attempts to write will fail (without erroring the stream). + * + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + */ + WritableStream.prototype.close = function () { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('close')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer')); + } + if (WritableStreamCloseQueuedOrInFlight(this)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamClose(this); + }; + /** + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream + * is locked, no other writer can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at + * the same time, which would cause the resulting written data to be unpredictable and probably useless. + */ + WritableStream.prototype.getWriter = function () { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('getWriter'); + } + return AcquireWritableStreamDefaultWriter(this); + }; + return WritableStream; +}()); +Object.defineProperties(WritableStream.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + getWriter: { enumerable: true }, + locked: { enumerable: true } +}); +setFunctionName(WritableStream.prototype.abort, 'abort'); +setFunctionName(WritableStream.prototype.close, 'close'); +setFunctionName(WritableStream.prototype.getWriter, 'getWriter'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStream', + configurable: true + }); +} +// Abstract operations for the WritableStream. +function AcquireWritableStreamDefaultWriter(stream) { + return new WritableStreamDefaultWriter(stream); +} +// Throws if and only if startAlgorithm throws. +function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + if (highWaterMark === void 0) { highWaterMark = 1; } + if (sizeAlgorithm === void 0) { sizeAlgorithm = function () { return 1; }; } + var stream = Object.create(WritableStream.prototype); + InitializeWritableStream(stream); + var controller = Object.create(WritableStreamDefaultController.prototype); + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + return stream; +} +function InitializeWritableStream(stream) { + stream._state = 'writable'; + // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is + // 'erroring' or 'errored'. May be set to an undefined value. + stream._storedError = undefined; + stream._writer = undefined; + // Initialize to undefined first because the constructor of the controller checks this + // variable to validate the caller. + stream._writableStreamController = undefined; + // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data + // producer without waiting for the queued writes to finish. + stream._writeRequests = new SimpleQueue(); + // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents + // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here. + stream._inFlightWriteRequest = undefined; + // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer + // has been detached. + stream._closeRequest = undefined; + // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it + // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here. + stream._inFlightCloseRequest = undefined; + // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached. + stream._pendingAbortRequest = undefined; + // The backpressure signal set by the controller. + stream._backpressure = false; +} +function IsWritableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) { + return false; + } + return x instanceof WritableStream; +} +function IsWritableStreamLocked(stream) { + if (stream._writer === undefined) { + return false; + } + return true; +} +function WritableStreamAbort(stream, reason) { + var _a; + if (stream._state === 'closed' || stream._state === 'errored') { + return promiseResolvedWith(undefined); + } + stream._writableStreamController._abortReason = reason; + (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort(reason); + // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring', + // but it doesn't know that signaling abort runs author code that might have changed the state. + // Widen the type again by casting to WritableStreamState. + var state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseResolvedWith(undefined); + } + if (stream._pendingAbortRequest !== undefined) { + return stream._pendingAbortRequest._promise; + } + var wasAlreadyErroring = false; + if (state === 'erroring') { + wasAlreadyErroring = true; + // reason will not be used, so don't keep a reference to it. + reason = undefined; + } + var promise = newPromise(function (resolve, reject) { + stream._pendingAbortRequest = { + _promise: undefined, + _resolve: resolve, + _reject: reject, + _reason: reason, + _wasAlreadyErroring: wasAlreadyErroring + }; + }); + stream._pendingAbortRequest._promise = promise; + if (!wasAlreadyErroring) { + WritableStreamStartErroring(stream, reason); + } + return promise; +} +function WritableStreamClose(stream) { + var state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseRejectedWith(new TypeError("The stream (in ".concat(state, " state) is not in the writable state and cannot be closed"))); + } + var promise = newPromise(function (resolve, reject) { + var closeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._closeRequest = closeRequest; + }); + var writer = stream._writer; + if (writer !== undefined && stream._backpressure && state === 'writable') { + defaultWriterReadyPromiseResolve(writer); + } + WritableStreamDefaultControllerClose(stream._writableStreamController); + return promise; +} +// WritableStream API exposed for controllers. +function WritableStreamAddWriteRequest(stream) { + var promise = newPromise(function (resolve, reject) { + var writeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._writeRequests.push(writeRequest); + }); + return promise; +} +function WritableStreamDealWithRejection(stream, error) { + var state = stream._state; + if (state === 'writable') { + WritableStreamStartErroring(stream, error); + return; + } + WritableStreamFinishErroring(stream); +} +function WritableStreamStartErroring(stream, reason) { + var controller = stream._writableStreamController; + stream._state = 'erroring'; + stream._storedError = reason; + var writer = stream._writer; + if (writer !== undefined) { + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); + } + if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { + WritableStreamFinishErroring(stream); + } +} +function WritableStreamFinishErroring(stream) { + stream._state = 'errored'; + stream._writableStreamController[ErrorSteps](); + var storedError = stream._storedError; + stream._writeRequests.forEach(function (writeRequest) { + writeRequest._reject(storedError); + }); + stream._writeRequests = new SimpleQueue(); + if (stream._pendingAbortRequest === undefined) { + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + var abortRequest = stream._pendingAbortRequest; + stream._pendingAbortRequest = undefined; + if (abortRequest._wasAlreadyErroring) { + abortRequest._reject(storedError); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + var promise = stream._writableStreamController[AbortSteps](abortRequest._reason); + uponPromise(promise, function () { + abortRequest._resolve(); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }, function (reason) { + abortRequest._reject(reason); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }); +} +function WritableStreamFinishInFlightWrite(stream) { + stream._inFlightWriteRequest._resolve(undefined); + stream._inFlightWriteRequest = undefined; +} +function WritableStreamFinishInFlightWriteWithError(stream, error) { + stream._inFlightWriteRequest._reject(error); + stream._inFlightWriteRequest = undefined; + WritableStreamDealWithRejection(stream, error); +} +function WritableStreamFinishInFlightClose(stream) { + stream._inFlightCloseRequest._resolve(undefined); + stream._inFlightCloseRequest = undefined; + var state = stream._state; + if (state === 'erroring') { + // The error was too late to do anything, so it is ignored. + stream._storedError = undefined; + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._resolve(); + stream._pendingAbortRequest = undefined; + } + } + stream._state = 'closed'; + var writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseResolve(writer); + } +} +function WritableStreamFinishInFlightCloseWithError(stream, error) { + stream._inFlightCloseRequest._reject(error); + stream._inFlightCloseRequest = undefined; + // Never execute sink abort() after sink close(). + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._reject(error); + stream._pendingAbortRequest = undefined; + } + WritableStreamDealWithRejection(stream, error); +} +// TODO(ricea): Fix alphabetical order. +function WritableStreamCloseQueuedOrInFlight(stream) { + if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; +} +function WritableStreamHasOperationMarkedInFlight(stream) { + if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; +} +function WritableStreamMarkCloseRequestInFlight(stream) { + stream._inFlightCloseRequest = stream._closeRequest; + stream._closeRequest = undefined; +} +function WritableStreamMarkFirstWriteRequestInFlight(stream) { + stream._inFlightWriteRequest = stream._writeRequests.shift(); +} +function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { + if (stream._closeRequest !== undefined) { + stream._closeRequest._reject(stream._storedError); + stream._closeRequest = undefined; + } + var writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseReject(writer, stream._storedError); + } +} +function WritableStreamUpdateBackpressure(stream, backpressure) { + var writer = stream._writer; + if (writer !== undefined && backpressure !== stream._backpressure) { + if (backpressure) { + defaultWriterReadyPromiseReset(writer); + } + else { + defaultWriterReadyPromiseResolve(writer); + } + } + stream._backpressure = backpressure; +} +/** + * A default writer vended by a {@link WritableStream}. + * + * @public + */ +var WritableStreamDefaultWriter = /** @class */ (function () { + function WritableStreamDefaultWriter(stream) { + assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter'); + assertWritableStream(stream, 'First parameter'); + if (IsWritableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive writing by another writer'); + } + this._ownerWritableStream = stream; + stream._writer = this; + var state = stream._state; + if (state === 'writable') { + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { + defaultWriterReadyPromiseInitialize(this); + } + else { + defaultWriterReadyPromiseInitializeAsResolved(this); + } + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'erroring') { + defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'closed') { + defaultWriterReadyPromiseInitializeAsResolved(this); + defaultWriterClosedPromiseInitializeAsResolved(this); + } + else { + var storedError = stream._storedError; + defaultWriterReadyPromiseInitializeAsRejected(this, storedError); + defaultWriterClosedPromiseInitializeAsRejected(this, storedError); + } + } + Object.defineProperty(WritableStreamDefaultWriter.prototype, "closed", { + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the writer’s lock is released before the stream finishes closing. + */ + get: function () { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('closed')); + } + return this._closedPromise; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(WritableStreamDefaultWriter.prototype, "desiredSize", { + /** + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. + * A producer can use this information to determine the right amount of data to write. + * + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when + * the writer’s lock is released. + */ + get: function () { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('desiredSize'); + } + if (this._ownerWritableStream === undefined) { + throw defaultWriterLockException('desiredSize'); + } + return WritableStreamDefaultWriterGetDesiredSize(this); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(WritableStreamDefaultWriter.prototype, "ready", { + /** + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips + * back to zero or below, the getter will return a new promise that stays pending until the next transition. + * + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become + * rejected. + */ + get: function () { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('ready')); + } + return this._readyPromise; + }, + enumerable: false, + configurable: true + }); + /** + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + */ + WritableStreamDefaultWriter.prototype.abort = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('abort')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('abort')); + } + return WritableStreamDefaultWriterAbort(this, reason); + }; + /** + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + */ + WritableStreamDefaultWriter.prototype.close = function () { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('close')); + } + var stream = this._ownerWritableStream; + if (stream === undefined) { + return promiseRejectedWith(defaultWriterLockException('close')); + } + if (WritableStreamCloseQueuedOrInFlight(stream)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamDefaultWriterClose(this); + }; + /** + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from + * now on; otherwise, the writer will appear closed. + * + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents + * other producers from writing in an interleaved manner. + */ + WritableStreamDefaultWriter.prototype.releaseLock = function () { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('releaseLock'); + } + var stream = this._ownerWritableStream; + if (stream === undefined) { + return; + } + WritableStreamDefaultWriterRelease(this); + }; + WritableStreamDefaultWriter.prototype.write = function (chunk) { + if (chunk === void 0) { chunk = undefined; } + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('write')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + return WritableStreamDefaultWriterWrite(this, chunk); + }; + return WritableStreamDefaultWriter; +}()); +Object.defineProperties(WritableStreamDefaultWriter.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + releaseLock: { enumerable: true }, + write: { enumerable: true }, + closed: { enumerable: true }, + desiredSize: { enumerable: true }, + ready: { enumerable: true } +}); +setFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort'); +setFunctionName(WritableStreamDefaultWriter.prototype.close, 'close'); +setFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock'); +setFunctionName(WritableStreamDefaultWriter.prototype.write, 'write'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultWriter', + configurable: true + }); +} +// Abstract operations for the WritableStreamDefaultWriter. +function IsWritableStreamDefaultWriter(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultWriter; +} +// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check. +function WritableStreamDefaultWriterAbort(writer, reason) { + var stream = writer._ownerWritableStream; + return WritableStreamAbort(stream, reason); +} +function WritableStreamDefaultWriterClose(writer) { + var stream = writer._ownerWritableStream; + return WritableStreamClose(stream); +} +function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { + var stream = writer._ownerWritableStream; + var state = stream._state; + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseResolvedWith(undefined); + } + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + return WritableStreamDefaultWriterClose(writer); +} +function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { + if (writer._closedPromiseState === 'pending') { + defaultWriterClosedPromiseReject(writer, error); + } + else { + defaultWriterClosedPromiseResetToRejected(writer, error); + } +} +function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { + if (writer._readyPromiseState === 'pending') { + defaultWriterReadyPromiseReject(writer, error); + } + else { + defaultWriterReadyPromiseResetToRejected(writer, error); + } +} +function WritableStreamDefaultWriterGetDesiredSize(writer) { + var stream = writer._ownerWritableStream; + var state = stream._state; + if (state === 'errored' || state === 'erroring') { + return null; + } + if (state === 'closed') { + return 0; + } + return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); +} +function WritableStreamDefaultWriterRelease(writer) { + var stream = writer._ownerWritableStream; + var releasedError = new TypeError("Writer was released and can no longer be used to monitor the stream's closedness"); + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); + // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not + // rejected until afterwards. This means that simply testing state will not work. + WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); + stream._writer = undefined; + writer._ownerWritableStream = undefined; +} +function WritableStreamDefaultWriterWrite(writer, chunk) { + var stream = writer._ownerWritableStream; + var controller = stream._writableStreamController; + var chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); + if (stream !== writer._ownerWritableStream) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + var state = stream._state; + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to')); + } + if (state === 'erroring') { + return promiseRejectedWith(stream._storedError); + } + var promise = WritableStreamAddWriteRequest(stream); + WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); + return promise; +} +var closeSentinel = {}; +/** + * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. + * + * @public + */ +var WritableStreamDefaultController = /** @class */ (function () { + function WritableStreamDefaultController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(WritableStreamDefaultController.prototype, "abortReason", { + /** + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. + * + * @deprecated + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. + */ + get: function () { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('abortReason'); + } + return this._abortReason; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(WritableStreamDefaultController.prototype, "signal", { + /** + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. + */ + get: function () { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('signal'); + } + if (this._abortController === undefined) { + // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`. + // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill, + // so instead we only implement support for `signal` if we find a global `AbortController` constructor. + throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported'); + } + return this._abortController.signal; + }, + enumerable: false, + configurable: true + }); + /** + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. + * + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the + * normal lifecycle of interactions with the underlying sink. + */ + WritableStreamDefaultController.prototype.error = function (e) { + if (e === void 0) { e = undefined; } + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('error'); + } + var state = this._controlledWritableStream._state; + if (state !== 'writable') { + // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so + // just treat it as a no-op. + return; + } + WritableStreamDefaultControllerError(this, e); + }; + /** @internal */ + WritableStreamDefaultController.prototype[AbortSteps] = function (reason) { + var result = this._abortAlgorithm(reason); + WritableStreamDefaultControllerClearAlgorithms(this); + return result; + }; + /** @internal */ + WritableStreamDefaultController.prototype[ErrorSteps] = function () { + ResetQueue(this); + }; + return WritableStreamDefaultController; +}()); +Object.defineProperties(WritableStreamDefaultController.prototype, { + abortReason: { enumerable: true }, + signal: { enumerable: true }, + error: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultController', + configurable: true + }); +} +// Abstract operations implementing interface required by the WritableStream. +function IsWritableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultController; +} +function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledWritableStream = stream; + stream._writableStreamController = controller; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._abortReason = undefined; + controller._abortController = createAbortController(); + controller._started = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._writeAlgorithm = writeAlgorithm; + controller._closeAlgorithm = closeAlgorithm; + controller._abortAlgorithm = abortAlgorithm; + var backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + var startResult = startAlgorithm(); + var startPromise = promiseResolvedWith(startResult); + uponPromise(startPromise, function () { + controller._started = true; + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, function (r) { + controller._started = true; + WritableStreamDealWithRejection(stream, r); + return null; + }); +} +function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { + var controller = Object.create(WritableStreamDefaultController.prototype); + var startAlgorithm; + var writeAlgorithm; + var closeAlgorithm; + var abortAlgorithm; + if (underlyingSink.start !== undefined) { + startAlgorithm = function () { return underlyingSink.start(controller); }; + } + else { + startAlgorithm = function () { return undefined; }; + } + if (underlyingSink.write !== undefined) { + writeAlgorithm = function (chunk) { return underlyingSink.write(chunk, controller); }; + } + else { + writeAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + if (underlyingSink.close !== undefined) { + closeAlgorithm = function () { return underlyingSink.close(); }; + } + else { + closeAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + if (underlyingSink.abort !== undefined) { + abortAlgorithm = function (reason) { return underlyingSink.abort(reason); }; + } + else { + abortAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); +} +// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls. +function WritableStreamDefaultControllerClearAlgorithms(controller) { + controller._writeAlgorithm = undefined; + controller._closeAlgorithm = undefined; + controller._abortAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; +} +function WritableStreamDefaultControllerClose(controller) { + EnqueueValueWithSize(controller, closeSentinel, 0); + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); +} +function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { + try { + return controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); + return 1; + } +} +function WritableStreamDefaultControllerGetDesiredSize(controller) { + return controller._strategyHWM - controller._queueTotalSize; +} +function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); + return; + } + var stream = controller._controlledWritableStream; + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') { + var backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); +} +// Abstract operations for the WritableStreamDefaultController. +function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { + var stream = controller._controlledWritableStream; + if (!controller._started) { + return; + } + if (stream._inFlightWriteRequest !== undefined) { + return; + } + var state = stream._state; + if (state === 'erroring') { + WritableStreamFinishErroring(stream); + return; + } + if (controller._queue.length === 0) { + return; + } + var value = PeekQueueValue(controller); + if (value === closeSentinel) { + WritableStreamDefaultControllerProcessClose(controller); + } + else { + WritableStreamDefaultControllerProcessWrite(controller, value); + } +} +function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { + if (controller._controlledWritableStream._state === 'writable') { + WritableStreamDefaultControllerError(controller, error); + } +} +function WritableStreamDefaultControllerProcessClose(controller) { + var stream = controller._controlledWritableStream; + WritableStreamMarkCloseRequestInFlight(stream); + DequeueValue(controller); + var sinkClosePromise = controller._closeAlgorithm(); + WritableStreamDefaultControllerClearAlgorithms(controller); + uponPromise(sinkClosePromise, function () { + WritableStreamFinishInFlightClose(stream); + return null; + }, function (reason) { + WritableStreamFinishInFlightCloseWithError(stream, reason); + return null; + }); +} +function WritableStreamDefaultControllerProcessWrite(controller, chunk) { + var stream = controller._controlledWritableStream; + WritableStreamMarkFirstWriteRequestInFlight(stream); + var sinkWritePromise = controller._writeAlgorithm(chunk); + uponPromise(sinkWritePromise, function () { + WritableStreamFinishInFlightWrite(stream); + var state = stream._state; + DequeueValue(controller); + if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') { + var backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, function (reason) { + if (stream._state === 'writable') { + WritableStreamDefaultControllerClearAlgorithms(controller); + } + WritableStreamFinishInFlightWriteWithError(stream, reason); + return null; + }); +} +function WritableStreamDefaultControllerGetBackpressure(controller) { + var desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); + return desiredSize <= 0; +} +// A client of WritableStreamDefaultController may use these functions directly to bypass state check. +function WritableStreamDefaultControllerError(controller, error) { + var stream = controller._controlledWritableStream; + WritableStreamDefaultControllerClearAlgorithms(controller); + WritableStreamStartErroring(stream, error); +} +// Helper functions for the WritableStream. +function streamBrandCheckException$2(name) { + return new TypeError("WritableStream.prototype.".concat(name, " can only be used on a WritableStream")); +} +// Helper functions for the WritableStreamDefaultController. +function defaultControllerBrandCheckException$2(name) { + return new TypeError("WritableStreamDefaultController.prototype.".concat(name, " can only be used on a WritableStreamDefaultController")); +} +// Helper functions for the WritableStreamDefaultWriter. +function defaultWriterBrandCheckException(name) { + return new TypeError("WritableStreamDefaultWriter.prototype.".concat(name, " can only be used on a WritableStreamDefaultWriter")); +} +function defaultWriterLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released writer'); +} +function defaultWriterClosedPromiseInitialize(writer) { + writer._closedPromise = newPromise(function (resolve, reject) { + writer._closedPromise_resolve = resolve; + writer._closedPromise_reject = reject; + writer._closedPromiseState = 'pending'; + }); +} +function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseReject(writer, reason); +} +function defaultWriterClosedPromiseInitializeAsResolved(writer) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseResolve(writer); +} +function defaultWriterClosedPromiseReject(writer, reason) { + if (writer._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._closedPromise); + writer._closedPromise_reject(reason); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'rejected'; +} +function defaultWriterClosedPromiseResetToRejected(writer, reason) { + defaultWriterClosedPromiseInitializeAsRejected(writer, reason); +} +function defaultWriterClosedPromiseResolve(writer) { + if (writer._closedPromise_resolve === undefined) { + return; + } + writer._closedPromise_resolve(undefined); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'resolved'; +} +function defaultWriterReadyPromiseInitialize(writer) { + writer._readyPromise = newPromise(function (resolve, reject) { + writer._readyPromise_resolve = resolve; + writer._readyPromise_reject = reject; + }); + writer._readyPromiseState = 'pending'; +} +function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseReject(writer, reason); +} +function defaultWriterReadyPromiseInitializeAsResolved(writer) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseResolve(writer); +} +function defaultWriterReadyPromiseReject(writer, reason) { + if (writer._readyPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._readyPromise); + writer._readyPromise_reject(reason); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'rejected'; +} +function defaultWriterReadyPromiseReset(writer) { + defaultWriterReadyPromiseInitialize(writer); +} +function defaultWriterReadyPromiseResetToRejected(writer, reason) { + defaultWriterReadyPromiseInitializeAsRejected(writer, reason); +} +function defaultWriterReadyPromiseResolve(writer) { + if (writer._readyPromise_resolve === undefined) { + return; + } + writer._readyPromise_resolve(undefined); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'fulfilled'; +} + +/// +function getGlobals() { + if (typeof globalThis !== 'undefined') { + return globalThis; + } + else if (typeof self !== 'undefined') { + return self; + } + else if (typeof global !== 'undefined') { + return global; + } + return undefined; +} +var globals = getGlobals(); + +/// +function isDOMExceptionConstructor(ctor) { + if (!(typeof ctor === 'function' || typeof ctor === 'object')) { + return false; + } + if (ctor.name !== 'DOMException') { + return false; + } + try { + new ctor(); + return true; + } + catch (_a) { + return false; + } +} +/** + * Support: + * - Web browsers + * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87) + */ +function getFromGlobal() { + var ctor = globals === null || globals === void 0 ? void 0 : globals.DOMException; + return isDOMExceptionConstructor(ctor) ? ctor : undefined; +} +/** + * Support: + * - All platforms + */ +function createPolyfill() { + // eslint-disable-next-line @typescript-eslint/no-shadow + var ctor = function DOMException(message, name) { + this.message = message || ''; + this.name = name || 'Error'; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + }; + setFunctionName(ctor, 'DOMException'); + ctor.prototype = Object.create(Error.prototype); + Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true }); + return ctor; +} +// eslint-disable-next-line @typescript-eslint/no-redeclare +var DOMException = getFromGlobal() || createPolyfill(); + +function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { + var reader = AcquireReadableStreamDefaultReader(source); + var writer = AcquireWritableStreamDefaultWriter(dest); + source._disturbed = true; + var shuttingDown = false; + // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown. + var currentWrite = promiseResolvedWith(undefined); + return newPromise(function (resolve, reject) { + var abortAlgorithm; + if (signal !== undefined) { + abortAlgorithm = function () { + var error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError'); + var actions = []; + if (!preventAbort) { + actions.push(function () { + if (dest._state === 'writable') { + return WritableStreamAbort(dest, error); + } + return promiseResolvedWith(undefined); + }); + } + if (!preventCancel) { + actions.push(function () { + if (source._state === 'readable') { + return ReadableStreamCancel(source, error); + } + return promiseResolvedWith(undefined); + }); + } + shutdownWithAction(function () { return Promise.all(actions.map(function (action) { return action(); })); }, true, error); + }; + if (signal.aborted) { + abortAlgorithm(); + return; + } + signal.addEventListener('abort', abortAlgorithm); + } + // Using reader and writer, read all chunks from this and write them to dest + // - Backpressure must be enforced + // - Shutdown must stop all activity + function pipeLoop() { + return newPromise(function (resolveLoop, rejectLoop) { + function next(done) { + if (done) { + resolveLoop(); + } + else { + // Use `PerformPromiseThen` instead of `uponPromise` to avoid + // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers + PerformPromiseThen(pipeStep(), next, rejectLoop); + } + } + next(false); + }); + } + function pipeStep() { + if (shuttingDown) { + return promiseResolvedWith(true); + } + return PerformPromiseThen(writer._readyPromise, function () { + return newPromise(function (resolveRead, rejectRead) { + ReadableStreamDefaultReaderRead(reader, { + _chunkSteps: function (chunk) { + currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop); + resolveRead(false); + }, + _closeSteps: function () { return resolveRead(true); }, + _errorSteps: rejectRead + }); + }); + }); + } + // Errors must be propagated forward + isOrBecomesErrored(source, reader._closedPromise, function (storedError) { + if (!preventAbort) { + shutdownWithAction(function () { return WritableStreamAbort(dest, storedError); }, true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Errors must be propagated backward + isOrBecomesErrored(dest, writer._closedPromise, function (storedError) { + if (!preventCancel) { + shutdownWithAction(function () { return ReadableStreamCancel(source, storedError); }, true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Closing must be propagated forward + isOrBecomesClosed(source, reader._closedPromise, function () { + if (!preventClose) { + shutdownWithAction(function () { return WritableStreamDefaultWriterCloseWithErrorPropagation(writer); }); + } + else { + shutdown(); + } + return null; + }); + // Closing must be propagated backward + if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') { + var destClosed_1 = new TypeError('the destination writable stream closed before all data could be piped to it'); + if (!preventCancel) { + shutdownWithAction(function () { return ReadableStreamCancel(source, destClosed_1); }, true, destClosed_1); + } + else { + shutdown(true, destClosed_1); + } + } + setPromiseIsHandledToTrue(pipeLoop()); + function waitForWritesToFinish() { + // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait + // for that too. + var oldCurrentWrite = currentWrite; + return PerformPromiseThen(currentWrite, function () { return oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined; }); + } + function isOrBecomesErrored(stream, promise, action) { + if (stream._state === 'errored') { + action(stream._storedError); + } + else { + uponRejection(promise, action); + } + } + function isOrBecomesClosed(stream, promise, action) { + if (stream._state === 'closed') { + action(); + } + else { + uponFulfillment(promise, action); + } + } + function shutdownWithAction(action, originalIsError, originalError) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), doTheRest); + } + else { + doTheRest(); + } + function doTheRest() { + uponPromise(action(), function () { return finalize(originalIsError, originalError); }, function (newError) { return finalize(true, newError); }); + return null; + } + } + function shutdown(isError, error) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), function () { return finalize(isError, error); }); + } + else { + finalize(isError, error); + } + } + function finalize(isError, error) { + WritableStreamDefaultWriterRelease(writer); + ReadableStreamReaderGenericRelease(reader); + if (signal !== undefined) { + signal.removeEventListener('abort', abortAlgorithm); + } + if (isError) { + reject(error); + } + else { + resolve(undefined); + } + return null; + } + }); +} + +/** + * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. + * + * @public + */ +var ReadableStreamDefaultController = /** @class */ (function () { + function ReadableStreamDefaultController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(ReadableStreamDefaultController.prototype, "desiredSize", { + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + */ + get: function () { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('desiredSize'); + } + return ReadableStreamDefaultControllerGetDesiredSize(this); + }, + enumerable: false, + configurable: true + }); + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + ReadableStreamDefaultController.prototype.close = function () { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('close'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits close'); + } + ReadableStreamDefaultControllerClose(this); + }; + ReadableStreamDefaultController.prototype.enqueue = function (chunk) { + if (chunk === void 0) { chunk = undefined; } + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('enqueue'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits enqueue'); + } + return ReadableStreamDefaultControllerEnqueue(this, chunk); + }; + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + ReadableStreamDefaultController.prototype.error = function (e) { + if (e === void 0) { e = undefined; } + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('error'); + } + ReadableStreamDefaultControllerError(this, e); + }; + /** @internal */ + ReadableStreamDefaultController.prototype[CancelSteps] = function (reason) { + ResetQueue(this); + var result = this._cancelAlgorithm(reason); + ReadableStreamDefaultControllerClearAlgorithms(this); + return result; + }; + /** @internal */ + ReadableStreamDefaultController.prototype[PullSteps] = function (readRequest) { + var stream = this._controlledReadableStream; + if (this._queue.length > 0) { + var chunk = DequeueValue(this); + if (this._closeRequested && this._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(this); + ReadableStreamClose(stream); + } + else { + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + readRequest._chunkSteps(chunk); + } + else { + ReadableStreamAddReadRequest(stream, readRequest); + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + }; + /** @internal */ + ReadableStreamDefaultController.prototype[ReleaseSteps] = function () { + // Do nothing. + }; + return ReadableStreamDefaultController; +}()); +Object.defineProperties(ReadableStreamDefaultController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + desiredSize: { enumerable: true } +}); +setFunctionName(ReadableStreamDefaultController.prototype.close, 'close'); +setFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue'); +setFunctionName(ReadableStreamDefaultController.prototype.error, 'error'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultController', + configurable: true + }); +} +// Abstract operations for the ReadableStreamDefaultController. +function IsReadableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) { + return false; + } + return x instanceof ReadableStreamDefaultController; +} +function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { + var shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + var pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, function () { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + return null; + }, function (e) { + ReadableStreamDefaultControllerError(controller, e); + return null; + }); +} +function ReadableStreamDefaultControllerShouldCallPull(controller) { + var stream = controller._controlledReadableStream; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return false; + } + if (!controller._started) { + return false; + } + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + var desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; +} +function ReadableStreamDefaultControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; +} +// A client of ReadableStreamDefaultController may use these functions directly to bypass state check. +function ReadableStreamDefaultControllerClose(controller) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + var stream = controller._controlledReadableStream; + controller._closeRequested = true; + if (controller._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } +} +function ReadableStreamDefaultControllerEnqueue(controller, chunk) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + var stream = controller._controlledReadableStream; + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + ReadableStreamFulfillReadRequest(stream, chunk, false); + } + else { + var chunkSize = void 0; + try { + chunkSize = controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + ReadableStreamDefaultControllerError(controller, chunkSizeE); + throw chunkSizeE; + } + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + ReadableStreamDefaultControllerError(controller, enqueueE); + throw enqueueE; + } + } + ReadableStreamDefaultControllerCallPullIfNeeded(controller); +} +function ReadableStreamDefaultControllerError(controller, e) { + var stream = controller._controlledReadableStream; + if (stream._state !== 'readable') { + return; + } + ResetQueue(controller); + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); +} +function ReadableStreamDefaultControllerGetDesiredSize(controller) { + var state = controller._controlledReadableStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; +} +// This is used in the implementation of TransformStream. +function ReadableStreamDefaultControllerHasBackpressure(controller) { + if (ReadableStreamDefaultControllerShouldCallPull(controller)) { + return false; + } + return true; +} +function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { + var state = controller._controlledReadableStream._state; + if (!controller._closeRequested && state === 'readable') { + return true; + } + return false; +} +function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledReadableStream = stream; + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._started = false; + controller._closeRequested = false; + controller._pullAgain = false; + controller._pulling = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + stream._readableStreamController = controller; + var startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), function () { + controller._started = true; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + return null; + }, function (r) { + ReadableStreamDefaultControllerError(controller, r); + return null; + }); +} +function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { + var controller = Object.create(ReadableStreamDefaultController.prototype); + var startAlgorithm; + var pullAlgorithm; + var cancelAlgorithm; + if (underlyingSource.start !== undefined) { + startAlgorithm = function () { return underlyingSource.start(controller); }; + } + else { + startAlgorithm = function () { return undefined; }; + } + if (underlyingSource.pull !== undefined) { + pullAlgorithm = function () { return underlyingSource.pull(controller); }; + } + else { + pullAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + if (underlyingSource.cancel !== undefined) { + cancelAlgorithm = function (reason) { return underlyingSource.cancel(reason); }; + } + else { + cancelAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); +} +// Helper functions for the ReadableStreamDefaultController. +function defaultControllerBrandCheckException$1(name) { + return new TypeError("ReadableStreamDefaultController.prototype.".concat(name, " can only be used on a ReadableStreamDefaultController")); +} + +function ReadableStreamTee(stream, cloneForBranch2) { + if (IsReadableByteStreamController(stream._readableStreamController)) { + return ReadableByteStreamTee(stream); + } + return ReadableStreamDefaultTee(stream); +} +function ReadableStreamDefaultTee(stream, cloneForBranch2) { + var reader = AcquireReadableStreamDefaultReader(stream); + var reading = false; + var readAgain = false; + var canceled1 = false; + var canceled2 = false; + var reason1; + var reason2; + var branch1; + var branch2; + var resolveCancelPromise; + var cancelPromise = newPromise(function (resolve) { + resolveCancelPromise = resolve; + }); + function pullAlgorithm() { + if (reading) { + readAgain = true; + return promiseResolvedWith(undefined); + } + reading = true; + var readRequest = { + _chunkSteps: function (chunk) { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(function () { + readAgain = false; + var chunk1 = chunk; + var chunk2 = chunk; + // There is no way to access the cloning code right now in the reference implementation. + // If we add one then we'll need an implementation for serializable objects. + // if (!canceled2 && cloneForBranch2) { + // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2)); + // } + if (!canceled1) { + ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgain) { + pullAlgorithm(); + } + }); + }, + _closeSteps: function () { + reading = false; + if (!canceled1) { + ReadableStreamDefaultControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableStreamDefaultControllerClose(branch2._readableStreamController); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: function () { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + // do nothing + } + branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); + branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); + uponRejection(reader._closedPromise, function (r) { + ReadableStreamDefaultControllerError(branch1._readableStreamController, r); + ReadableStreamDefaultControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + return [branch1, branch2]; +} +function ReadableByteStreamTee(stream) { + var reader = AcquireReadableStreamDefaultReader(stream); + var reading = false; + var readAgainForBranch1 = false; + var readAgainForBranch2 = false; + var canceled1 = false; + var canceled2 = false; + var reason1; + var reason2; + var branch1; + var branch2; + var resolveCancelPromise; + var cancelPromise = newPromise(function (resolve) { + resolveCancelPromise = resolve; + }); + function forwardReaderError(thisReader) { + uponRejection(thisReader._closedPromise, function (r) { + if (thisReader !== reader) { + return null; + } + ReadableByteStreamControllerError(branch1._readableStreamController, r); + ReadableByteStreamControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + } + function pullWithDefaultReader() { + if (IsReadableStreamBYOBReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamDefaultReader(stream); + forwardReaderError(reader); + } + var readRequest = { + _chunkSteps: function (chunk) { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(function () { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + var chunk1 = chunk; + var chunk2 = chunk; + if (!canceled1 && !canceled2) { + try { + chunk2 = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(branch1._readableStreamController, cloneE); + ReadableByteStreamControllerError(branch2._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + } + if (!canceled1) { + ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: function () { + reading = false; + if (!canceled1) { + ReadableByteStreamControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableByteStreamControllerClose(branch2._readableStreamController); + } + if (branch1._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch1._readableStreamController, 0); + } + if (branch2._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch2._readableStreamController, 0); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: function () { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + } + function pullWithBYOBReader(view, forBranch2) { + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamBYOBReader(stream); + forwardReaderError(reader); + } + var byobBranch = forBranch2 ? branch2 : branch1; + var otherBranch = forBranch2 ? branch1 : branch2; + var readIntoRequest = { + _chunkSteps: function (chunk) { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(function () { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + var byobCanceled = forBranch2 ? canceled2 : canceled1; + var otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!otherCanceled) { + var clonedChunk = void 0; + try { + clonedChunk = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE); + ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk); + } + else if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: function (chunk) { + reading = false; + var byobCanceled = forBranch2 ? canceled2 : canceled1; + var otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!byobCanceled) { + ReadableByteStreamControllerClose(byobBranch._readableStreamController); + } + if (!otherCanceled) { + ReadableByteStreamControllerClose(otherBranch._readableStreamController); + } + if (chunk !== undefined) { + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0); + } + } + if (!byobCanceled || !otherCanceled) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: function () { + reading = false; + } + }; + ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest); + } + function pull1Algorithm() { + if (reading) { + readAgainForBranch1 = true; + return promiseResolvedWith(undefined); + } + reading = true; + var byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, false); + } + return promiseResolvedWith(undefined); + } + function pull2Algorithm() { + if (reading) { + readAgainForBranch2 = true; + return promiseResolvedWith(undefined); + } + reading = true; + var byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, true); + } + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + return; + } + branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm); + branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm); + forwardReaderError(reader); + return [branch1, branch2]; +} + +function isReadableStreamLike(stream) { + return typeIsObject(stream) && typeof stream.getReader !== 'undefined'; +} + +function ReadableStreamFrom(source) { + if (isReadableStreamLike(source)) { + return ReadableStreamFromDefaultReader(source.getReader()); + } + return ReadableStreamFromIterable(source); +} +function ReadableStreamFromIterable(asyncIterable) { + var stream; + var iteratorRecord = GetIterator(asyncIterable, 'async'); + var startAlgorithm = noop; + function pullAlgorithm() { + var nextResult; + try { + nextResult = IteratorNext(iteratorRecord); + } + catch (e) { + return promiseRejectedWith(e); + } + var nextPromise = promiseResolvedWith(nextResult); + return transformPromiseWith(nextPromise, function (iterResult) { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object'); + } + var done = IteratorComplete(iterResult); + if (done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + var value = IteratorValue(iterResult); + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + var iterator = iteratorRecord.iterator; + var returnMethod; + try { + returnMethod = GetMethod(iterator, 'return'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (returnMethod === undefined) { + return promiseResolvedWith(undefined); + } + var returnResult; + try { + returnResult = reflectCall(returnMethod, iterator, [reason]); + } + catch (e) { + return promiseRejectedWith(e); + } + var returnPromise = promiseResolvedWith(returnResult); + return transformPromiseWith(returnPromise, function (iterResult) { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object'); + } + return undefined; + }); + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; +} +function ReadableStreamFromDefaultReader(reader) { + var stream; + var startAlgorithm = noop; + function pullAlgorithm() { + var readPromise; + try { + readPromise = reader.read(); + } + catch (e) { + return promiseRejectedWith(e); + } + return transformPromiseWith(readPromise, function (readResult) { + if (!typeIsObject(readResult)) { + throw new TypeError('The promise returned by the reader.read() method must fulfill with an object'); + } + if (readResult.done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + var value = readResult.value; + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + try { + return promiseResolvedWith(reader.cancel(reason)); + } + catch (e) { + return promiseRejectedWith(e); + } + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; +} + +function convertUnderlyingDefaultOrByteSource(source, context) { + assertDictionary(source, context); + var original = source; + var autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; + var cancel = original === null || original === void 0 ? void 0 : original.cancel; + var pull = original === null || original === void 0 ? void 0 : original.pull; + var start = original === null || original === void 0 ? void 0 : original.start; + var type = original === null || original === void 0 ? void 0 : original.type; + return { + autoAllocateChunkSize: autoAllocateChunkSize === undefined ? + undefined : + convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, "".concat(context, " has member 'autoAllocateChunkSize' that")), + cancel: cancel === undefined ? + undefined : + convertUnderlyingSourceCancelCallback(cancel, original, "".concat(context, " has member 'cancel' that")), + pull: pull === undefined ? + undefined : + convertUnderlyingSourcePullCallback(pull, original, "".concat(context, " has member 'pull' that")), + start: start === undefined ? + undefined : + convertUnderlyingSourceStartCallback(start, original, "".concat(context, " has member 'start' that")), + type: type === undefined ? undefined : convertReadableStreamType(type, "".concat(context, " has member 'type' that")) + }; +} +function convertUnderlyingSourceCancelCallback(fn, original, context) { + assertFunction(fn, context); + return function (reason) { return promiseCall(fn, original, [reason]); }; +} +function convertUnderlyingSourcePullCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return promiseCall(fn, original, [controller]); }; +} +function convertUnderlyingSourceStartCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return reflectCall(fn, original, [controller]); }; +} +function convertReadableStreamType(type, context) { + type = "".concat(type); + if (type !== 'bytes') { + throw new TypeError("".concat(context, " '").concat(type, "' is not a valid enumeration value for ReadableStreamType")); + } + return type; +} + +function convertIteratorOptions(options, context) { + assertDictionary(options, context); + var preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + return { preventCancel: Boolean(preventCancel) }; +} + +function convertPipeOptions(options, context) { + assertDictionary(options, context); + var preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort; + var preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + var preventClose = options === null || options === void 0 ? void 0 : options.preventClose; + var signal = options === null || options === void 0 ? void 0 : options.signal; + if (signal !== undefined) { + assertAbortSignal(signal, "".concat(context, " has member 'signal' that")); + } + return { + preventAbort: Boolean(preventAbort), + preventCancel: Boolean(preventCancel), + preventClose: Boolean(preventClose), + signal: signal + }; +} +function assertAbortSignal(signal, context) { + if (!isAbortSignal(signal)) { + throw new TypeError("".concat(context, " is not an AbortSignal.")); + } +} + +function convertReadableWritablePair(pair, context) { + assertDictionary(pair, context); + var readable = pair === null || pair === void 0 ? void 0 : pair.readable; + assertRequiredField(readable, 'readable', 'ReadableWritablePair'); + assertReadableStream(readable, "".concat(context, " has member 'readable' that")); + var writable = pair === null || pair === void 0 ? void 0 : pair.writable; + assertRequiredField(writable, 'writable', 'ReadableWritablePair'); + assertWritableStream(writable, "".concat(context, " has member 'writable' that")); + return { readable: readable, writable: writable }; +} + +/** + * A readable stream represents a source of data, from which you can read. + * + * @public + */ +var ReadableStream = /** @class */ (function () { + function ReadableStream(rawUnderlyingSource, rawStrategy) { + if (rawUnderlyingSource === void 0) { rawUnderlyingSource = {}; } + if (rawStrategy === void 0) { rawStrategy = {}; } + if (rawUnderlyingSource === undefined) { + rawUnderlyingSource = null; + } + else { + assertObject(rawUnderlyingSource, 'First parameter'); + } + var strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + var underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter'); + InitializeReadableStream(this); + if (underlyingSource.type === 'bytes') { + if (strategy.size !== undefined) { + throw new RangeError('The strategy for a byte stream cannot have a size function'); + } + var highWaterMark = ExtractHighWaterMark(strategy, 0); + SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); + } + else { + var sizeAlgorithm = ExtractSizeAlgorithm(strategy); + var highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); + } + } + Object.defineProperty(ReadableStream.prototype, "locked", { + /** + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. + */ + get: function () { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('locked'); + } + return IsReadableStreamLocked(this); + }, + enumerable: false, + configurable: true + }); + /** + * Cancels the stream, signaling a loss of interest in the stream by a consumer. + * + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} + * method, which might or might not use it. + */ + ReadableStream.prototype.cancel = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('cancel')); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader')); + } + return ReadableStreamCancel(this, reason); + }; + ReadableStream.prototype.getReader = function (rawOptions) { + if (rawOptions === void 0) { rawOptions = undefined; } + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('getReader'); + } + var options = convertReaderOptions(rawOptions, 'First parameter'); + if (options.mode === undefined) { + return AcquireReadableStreamDefaultReader(this); + } + return AcquireReadableStreamBYOBReader(this); + }; + ReadableStream.prototype.pipeThrough = function (rawTransform, rawOptions) { + if (rawOptions === void 0) { rawOptions = {}; } + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('pipeThrough'); + } + assertRequiredArgument(rawTransform, 1, 'pipeThrough'); + var transform = convertReadableWritablePair(rawTransform, 'First parameter'); + var options = convertPipeOptions(rawOptions, 'Second parameter'); + if (IsReadableStreamLocked(this)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream'); + } + if (IsWritableStreamLocked(transform.writable)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream'); + } + var promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + setPromiseIsHandledToTrue(promise); + return transform.readable; + }; + ReadableStream.prototype.pipeTo = function (destination, rawOptions) { + if (rawOptions === void 0) { rawOptions = {}; } + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('pipeTo')); + } + if (destination === undefined) { + return promiseRejectedWith("Parameter 1 is required in 'pipeTo'."); + } + if (!IsWritableStream(destination)) { + return promiseRejectedWith(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream")); + } + var options; + try { + options = convertPipeOptions(rawOptions, 'Second parameter'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')); + } + if (IsWritableStreamLocked(destination)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')); + } + return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + }; + /** + * Tees this readable stream, returning a two-element array containing the two resulting branches as + * new {@link ReadableStream} instances. + * + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be + * propagated to the stream's underlying source. + * + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, + * this could allow interference between the two branches. + */ + ReadableStream.prototype.tee = function () { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('tee'); + } + var branches = ReadableStreamTee(this); + return CreateArrayFromList(branches); + }; + ReadableStream.prototype.values = function (rawOptions) { + if (rawOptions === void 0) { rawOptions = undefined; } + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('values'); + } + var options = convertIteratorOptions(rawOptions, 'First parameter'); + return AcquireReadableStreamAsyncIterator(this, options.preventCancel); + }; + ReadableStream.prototype[SymbolAsyncIterator] = function (options) { + // Stub implementation, overridden below + return this.values(options); + }; + /** + * Creates a new ReadableStream wrapping the provided iterable or async iterable. + * + * This can be used to adapt various kinds of objects into a readable stream, + * such as an array, an async generator, or a Node.js readable stream. + */ + ReadableStream.from = function (asyncIterable) { + return ReadableStreamFrom(asyncIterable); + }; + return ReadableStream; +}()); +Object.defineProperties(ReadableStream, { + from: { enumerable: true } +}); +Object.defineProperties(ReadableStream.prototype, { + cancel: { enumerable: true }, + getReader: { enumerable: true }, + pipeThrough: { enumerable: true }, + pipeTo: { enumerable: true }, + tee: { enumerable: true }, + values: { enumerable: true }, + locked: { enumerable: true } +}); +setFunctionName(ReadableStream.from, 'from'); +setFunctionName(ReadableStream.prototype.cancel, 'cancel'); +setFunctionName(ReadableStream.prototype.getReader, 'getReader'); +setFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough'); +setFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo'); +setFunctionName(ReadableStream.prototype.tee, 'tee'); +setFunctionName(ReadableStream.prototype.values, 'values'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStream', + configurable: true + }); +} +Object.defineProperty(ReadableStream.prototype, SymbolAsyncIterator, { + value: ReadableStream.prototype.values, + writable: true, + configurable: true +}); +// Abstract operations for the ReadableStream. +// Throws if and only if startAlgorithm throws. +function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + if (highWaterMark === void 0) { highWaterMark = 1; } + if (sizeAlgorithm === void 0) { sizeAlgorithm = function () { return 1; }; } + var stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + var controller = Object.create(ReadableStreamDefaultController.prototype); + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + return stream; +} +// Throws if and only if startAlgorithm throws. +function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) { + var stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + var controller = Object.create(ReadableByteStreamController.prototype); + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined); + return stream; +} +function InitializeReadableStream(stream) { + stream._state = 'readable'; + stream._reader = undefined; + stream._storedError = undefined; + stream._disturbed = false; +} +function IsReadableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) { + return false; + } + return x instanceof ReadableStream; +} +function IsReadableStreamLocked(stream) { + if (stream._reader === undefined) { + return false; + } + return true; +} +// ReadableStream API exposed for controllers. +function ReadableStreamCancel(stream, reason) { + stream._disturbed = true; + if (stream._state === 'closed') { + return promiseResolvedWith(undefined); + } + if (stream._state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + ReadableStreamClose(stream); + var reader = stream._reader; + if (reader !== undefined && IsReadableStreamBYOBReader(reader)) { + var readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(function (readIntoRequest) { + readIntoRequest._closeSteps(undefined); + }); + } + var sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); + return transformPromiseWith(sourceCancelPromise, noop); +} +function ReadableStreamClose(stream) { + stream._state = 'closed'; + var reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseResolve(reader); + if (IsReadableStreamDefaultReader(reader)) { + var readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(function (readRequest) { + readRequest._closeSteps(); + }); + } +} +function ReadableStreamError(stream, e) { + stream._state = 'errored'; + stream._storedError = e; + var reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseReject(reader, e); + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamDefaultReaderErrorReadRequests(reader, e); + } + else { + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); + } +} +// Helper functions for the ReadableStream. +function streamBrandCheckException$1(name) { + return new TypeError("ReadableStream.prototype.".concat(name, " can only be used on a ReadableStream")); +} + +function convertQueuingStrategyInit(init, context) { + assertDictionary(init, context); + var highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit'); + return { + highWaterMark: convertUnrestrictedDouble(highWaterMark) + }; +} + +// The size function must not have a prototype property nor be a constructor +var byteLengthSizeFunction = function (chunk) { + return chunk.byteLength; +}; +setFunctionName(byteLengthSizeFunction, 'size'); +/** + * A queuing strategy that counts the number of bytes in each chunk. + * + * @public + */ +var ByteLengthQueuingStrategy = /** @class */ (function () { + function ByteLengthQueuingStrategy(options) { + assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; + } + Object.defineProperty(ByteLengthQueuingStrategy.prototype, "highWaterMark", { + /** + * Returns the high water mark provided to the constructor. + */ + get: function () { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('highWaterMark'); + } + return this._byteLengthQueuingStrategyHighWaterMark; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ByteLengthQueuingStrategy.prototype, "size", { + /** + * Measures the size of `chunk` by returning the value of its `byteLength` property. + */ + get: function () { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('size'); + } + return byteLengthSizeFunction; + }, + enumerable: false, + configurable: true + }); + return ByteLengthQueuingStrategy; +}()); +Object.defineProperties(ByteLengthQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ByteLengthQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'ByteLengthQueuingStrategy', + configurable: true + }); +} +// Helper functions for the ByteLengthQueuingStrategy. +function byteLengthBrandCheckException(name) { + return new TypeError("ByteLengthQueuingStrategy.prototype.".concat(name, " can only be used on a ByteLengthQueuingStrategy")); +} +function IsByteLengthQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof ByteLengthQueuingStrategy; +} + +// The size function must not have a prototype property nor be a constructor +var countSizeFunction = function () { + return 1; +}; +setFunctionName(countSizeFunction, 'size'); +/** + * A queuing strategy that counts the number of chunks. + * + * @public + */ +var CountQueuingStrategy = /** @class */ (function () { + function CountQueuingStrategy(options) { + assertRequiredArgument(options, 1, 'CountQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._countQueuingStrategyHighWaterMark = options.highWaterMark; + } + Object.defineProperty(CountQueuingStrategy.prototype, "highWaterMark", { + /** + * Returns the high water mark provided to the constructor. + */ + get: function () { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('highWaterMark'); + } + return this._countQueuingStrategyHighWaterMark; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(CountQueuingStrategy.prototype, "size", { + /** + * Measures the size of `chunk` by always returning 1. + * This ensures that the total queue size is a count of the number of chunks in the queue. + */ + get: function () { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('size'); + } + return countSizeFunction; + }, + enumerable: false, + configurable: true + }); + return CountQueuingStrategy; +}()); +Object.defineProperties(CountQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(CountQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'CountQueuingStrategy', + configurable: true + }); +} +// Helper functions for the CountQueuingStrategy. +function countBrandCheckException(name) { + return new TypeError("CountQueuingStrategy.prototype.".concat(name, " can only be used on a CountQueuingStrategy")); +} +function IsCountQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof CountQueuingStrategy; +} + +function convertTransformer(original, context) { + assertDictionary(original, context); + var cancel = original === null || original === void 0 ? void 0 : original.cancel; + var flush = original === null || original === void 0 ? void 0 : original.flush; + var readableType = original === null || original === void 0 ? void 0 : original.readableType; + var start = original === null || original === void 0 ? void 0 : original.start; + var transform = original === null || original === void 0 ? void 0 : original.transform; + var writableType = original === null || original === void 0 ? void 0 : original.writableType; + return { + cancel: cancel === undefined ? + undefined : + convertTransformerCancelCallback(cancel, original, "".concat(context, " has member 'cancel' that")), + flush: flush === undefined ? + undefined : + convertTransformerFlushCallback(flush, original, "".concat(context, " has member 'flush' that")), + readableType: readableType, + start: start === undefined ? + undefined : + convertTransformerStartCallback(start, original, "".concat(context, " has member 'start' that")), + transform: transform === undefined ? + undefined : + convertTransformerTransformCallback(transform, original, "".concat(context, " has member 'transform' that")), + writableType: writableType + }; +} +function convertTransformerFlushCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return promiseCall(fn, original, [controller]); }; +} +function convertTransformerStartCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return reflectCall(fn, original, [controller]); }; +} +function convertTransformerTransformCallback(fn, original, context) { + assertFunction(fn, context); + return function (chunk, controller) { return promiseCall(fn, original, [chunk, controller]); }; +} +function convertTransformerCancelCallback(fn, original, context) { + assertFunction(fn, context); + return function (reason) { return promiseCall(fn, original, [reason]); }; +} + +// Class TransformStream +/** + * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, + * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. + * In a manner specific to the transform stream in question, writes to the writable side result in new data being + * made available for reading from the readable side. + * + * @public + */ +var TransformStream = /** @class */ (function () { + function TransformStream(rawTransformer, rawWritableStrategy, rawReadableStrategy) { + if (rawTransformer === void 0) { rawTransformer = {}; } + if (rawWritableStrategy === void 0) { rawWritableStrategy = {}; } + if (rawReadableStrategy === void 0) { rawReadableStrategy = {}; } + if (rawTransformer === undefined) { + rawTransformer = null; + } + var writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter'); + var readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter'); + var transformer = convertTransformer(rawTransformer, 'First parameter'); + if (transformer.readableType !== undefined) { + throw new RangeError('Invalid readableType specified'); + } + if (transformer.writableType !== undefined) { + throw new RangeError('Invalid writableType specified'); + } + var readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); + var readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); + var writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); + var writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); + var startPromise_resolve; + var startPromise = newPromise(function (resolve) { + startPromise_resolve = resolve; + }); + InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); + if (transformer.start !== undefined) { + startPromise_resolve(transformer.start(this._transformStreamController)); + } + else { + startPromise_resolve(undefined); + } + } + Object.defineProperty(TransformStream.prototype, "readable", { + /** + * The readable side of the transform stream. + */ + get: function () { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('readable'); + } + return this._readable; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TransformStream.prototype, "writable", { + /** + * The writable side of the transform stream. + */ + get: function () { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('writable'); + } + return this._writable; + }, + enumerable: false, + configurable: true + }); + return TransformStream; +}()); +Object.defineProperties(TransformStream.prototype, { + readable: { enumerable: true }, + writable: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStream.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStream', + configurable: true + }); +} +function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { + function startAlgorithm() { + return startPromise; + } + function writeAlgorithm(chunk) { + return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); + } + function abortAlgorithm(reason) { + return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); + } + function closeAlgorithm() { + return TransformStreamDefaultSinkCloseAlgorithm(stream); + } + stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); + function pullAlgorithm() { + return TransformStreamDefaultSourcePullAlgorithm(stream); + } + function cancelAlgorithm(reason) { + return TransformStreamDefaultSourceCancelAlgorithm(stream, reason); + } + stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure. + stream._backpressure = undefined; + stream._backpressureChangePromise = undefined; + stream._backpressureChangePromise_resolve = undefined; + TransformStreamSetBackpressure(stream, true); + stream._transformStreamController = undefined; +} +function IsTransformStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) { + return false; + } + return x instanceof TransformStream; +} +// This is a no-op if both sides are already errored. +function TransformStreamError(stream, e) { + ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e); + TransformStreamErrorWritableAndUnblockWrite(stream, e); +} +function TransformStreamErrorWritableAndUnblockWrite(stream, e) { + TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); + WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e); + TransformStreamUnblockWrite(stream); +} +function TransformStreamUnblockWrite(stream) { + if (stream._backpressure) { + // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure() + // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time + // _backpressure is set. + TransformStreamSetBackpressure(stream, false); + } +} +function TransformStreamSetBackpressure(stream, backpressure) { + // Passes also when called during construction. + if (stream._backpressureChangePromise !== undefined) { + stream._backpressureChangePromise_resolve(); + } + stream._backpressureChangePromise = newPromise(function (resolve) { + stream._backpressureChangePromise_resolve = resolve; + }); + stream._backpressure = backpressure; +} +// Class TransformStreamDefaultController +/** + * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. + * + * @public + */ +var TransformStreamDefaultController = /** @class */ (function () { + function TransformStreamDefaultController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(TransformStreamDefaultController.prototype, "desiredSize", { + /** + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. + */ + get: function () { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('desiredSize'); + } + var readableController = this._controlledTransformStream._readable._readableStreamController; + return ReadableStreamDefaultControllerGetDesiredSize(readableController); + }, + enumerable: false, + configurable: true + }); + TransformStreamDefaultController.prototype.enqueue = function (chunk) { + if (chunk === void 0) { chunk = undefined; } + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('enqueue'); + } + TransformStreamDefaultControllerEnqueue(this, chunk); + }; + /** + * Errors both the readable side and the writable side of the controlled transform stream, making all future + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. + */ + TransformStreamDefaultController.prototype.error = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('error'); + } + TransformStreamDefaultControllerError(this, reason); + }; + /** + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the + * transformer only needs to consume a portion of the chunks written to the writable side. + */ + TransformStreamDefaultController.prototype.terminate = function () { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('terminate'); + } + TransformStreamDefaultControllerTerminate(this); + }; + return TransformStreamDefaultController; +}()); +Object.defineProperties(TransformStreamDefaultController.prototype, { + enqueue: { enumerable: true }, + error: { enumerable: true }, + terminate: { enumerable: true }, + desiredSize: { enumerable: true } +}); +setFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue'); +setFunctionName(TransformStreamDefaultController.prototype.error, 'error'); +setFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStreamDefaultController', + configurable: true + }); +} +// Transform Stream Default Controller Abstract Operations +function IsTransformStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) { + return false; + } + return x instanceof TransformStreamDefaultController; +} +function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm) { + controller._controlledTransformStream = stream; + stream._transformStreamController = controller; + controller._transformAlgorithm = transformAlgorithm; + controller._flushAlgorithm = flushAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._finishPromise = undefined; + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; +} +function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { + var controller = Object.create(TransformStreamDefaultController.prototype); + var transformAlgorithm; + var flushAlgorithm; + var cancelAlgorithm; + if (transformer.transform !== undefined) { + transformAlgorithm = function (chunk) { return transformer.transform(chunk, controller); }; + } + else { + transformAlgorithm = function (chunk) { + try { + TransformStreamDefaultControllerEnqueue(controller, chunk); + return promiseResolvedWith(undefined); + } + catch (transformResultE) { + return promiseRejectedWith(transformResultE); + } + }; + } + if (transformer.flush !== undefined) { + flushAlgorithm = function () { return transformer.flush(controller); }; + } + else { + flushAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + if (transformer.cancel !== undefined) { + cancelAlgorithm = function (reason) { return transformer.cancel(reason); }; + } + else { + cancelAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm); +} +function TransformStreamDefaultControllerClearAlgorithms(controller) { + controller._transformAlgorithm = undefined; + controller._flushAlgorithm = undefined; + controller._cancelAlgorithm = undefined; +} +function TransformStreamDefaultControllerEnqueue(controller, chunk) { + var stream = controller._controlledTransformStream; + var readableController = stream._readable._readableStreamController; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { + throw new TypeError('Readable side is not in a state that permits enqueue'); + } + // We throttle transform invocations based on the backpressure of the ReadableStream, but we still + // accept TransformStreamDefaultControllerEnqueue() calls. + try { + ReadableStreamDefaultControllerEnqueue(readableController, chunk); + } + catch (e) { + // This happens when readableStrategy.size() throws. + TransformStreamErrorWritableAndUnblockWrite(stream, e); + throw stream._readable._storedError; + } + var backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); + if (backpressure !== stream._backpressure) { + TransformStreamSetBackpressure(stream, true); + } +} +function TransformStreamDefaultControllerError(controller, e) { + TransformStreamError(controller._controlledTransformStream, e); +} +function TransformStreamDefaultControllerPerformTransform(controller, chunk) { + var transformPromise = controller._transformAlgorithm(chunk); + return transformPromiseWith(transformPromise, undefined, function (r) { + TransformStreamError(controller._controlledTransformStream, r); + throw r; + }); +} +function TransformStreamDefaultControllerTerminate(controller) { + var stream = controller._controlledTransformStream; + var readableController = stream._readable._readableStreamController; + ReadableStreamDefaultControllerClose(readableController); + var error = new TypeError('TransformStream terminated'); + TransformStreamErrorWritableAndUnblockWrite(stream, error); +} +// TransformStreamDefaultSink Algorithms +function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { + var controller = stream._transformStreamController; + if (stream._backpressure) { + var backpressureChangePromise = stream._backpressureChangePromise; + return transformPromiseWith(backpressureChangePromise, function () { + var writable = stream._writable; + var state = writable._state; + if (state === 'erroring') { + throw writable._storedError; + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + }); + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); +} +function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { + var controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + var readable = stream._readable; + // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally, + // we don't run the _cancelAlgorithm again. + controller._finishPromise = newPromise(function (resolve, reject) { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + var cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, function () { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerError(readable._readableStreamController, reason); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, function (r) { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; +} +function TransformStreamDefaultSinkCloseAlgorithm(stream) { + var controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + var readable = stream._readable; + // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally, + // we don't also run the _cancelAlgorithm. + controller._finishPromise = newPromise(function (resolve, reject) { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + var flushPromise = controller._flushAlgorithm(); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(flushPromise, function () { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerClose(readable._readableStreamController); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, function (r) { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; +} +// TransformStreamDefaultSource Algorithms +function TransformStreamDefaultSourcePullAlgorithm(stream) { + // Invariant. Enforced by the promises returned by start() and pull(). + TransformStreamSetBackpressure(stream, false); + // Prevent the next pull() call until there is backpressure. + return stream._backpressureChangePromise; +} +function TransformStreamDefaultSourceCancelAlgorithm(stream, reason) { + var controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._writable cannot change after construction, so caching it across a call to user code is safe. + var writable = stream._writable; + // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or + // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the + // _flushAlgorithm. + controller._finishPromise = newPromise(function (resolve, reject) { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + var cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, function () { + if (writable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, writable._storedError); + } + else { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, function (r) { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; +} +// Helper functions for the TransformStreamDefaultController. +function defaultControllerBrandCheckException(name) { + return new TypeError("TransformStreamDefaultController.prototype.".concat(name, " can only be used on a TransformStreamDefaultController")); +} +function defaultControllerFinishPromiseResolve(controller) { + if (controller._finishPromise_resolve === undefined) { + return; + } + controller._finishPromise_resolve(); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; +} +function defaultControllerFinishPromiseReject(controller, reason) { + if (controller._finishPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(controller._finishPromise); + controller._finishPromise_reject(reason); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; +} +// Helper functions for the TransformStream. +function streamBrandCheckException(name) { + return new TypeError("TransformStream.prototype.".concat(name, " can only be used on a TransformStream")); +} + +var exports = { + ReadableStream: ReadableStream, + ReadableStreamDefaultController: ReadableStreamDefaultController, + ReadableByteStreamController: ReadableByteStreamController, + ReadableStreamBYOBRequest: ReadableStreamBYOBRequest, + ReadableStreamDefaultReader: ReadableStreamDefaultReader, + ReadableStreamBYOBReader: ReadableStreamBYOBReader, + WritableStream: WritableStream, + WritableStreamDefaultController: WritableStreamDefaultController, + WritableStreamDefaultWriter: WritableStreamDefaultWriter, + ByteLengthQueuingStrategy: ByteLengthQueuingStrategy, + CountQueuingStrategy: CountQueuingStrategy, + TransformStream: TransformStream, + TransformStreamDefaultController: TransformStreamDefaultController +}; +// Add classes to global scope +if (typeof globals !== 'undefined') { + for (var prop in exports) { + if (Object.prototype.hasOwnProperty.call(exports, prop)) { + Object.defineProperty(globals, prop, { + value: exports[prop], + writable: true, + configurable: true + }); + } + } +} + +export { ByteLengthQueuingStrategy, CountQueuingStrategy, ReadableByteStreamController, ReadableStream, ReadableStreamBYOBReader, ReadableStreamBYOBRequest, ReadableStreamDefaultController, ReadableStreamDefaultReader, TransformStream, TransformStreamDefaultController, WritableStream, WritableStreamDefaultController, WritableStreamDefaultWriter }; +//# sourceMappingURL=polyfill.mjs.map diff --git a/backend/node_modules/web-streams-polyfill/dist/polyfill.mjs.map b/backend/node_modules/web-streams-polyfill/dist/polyfill.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..a8b2b082f9bd2b4282b8b7aae9a1ec82257567e3 --- /dev/null +++ b/backend/node_modules/web-streams-polyfill/dist/polyfill.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"polyfill.mjs","sources":["../src/stub/symbol.ts","../node_modules/tslib/tslib.es6.js","../src/utils.ts","../src/lib/helpers/miscellaneous.ts","../src/lib/helpers/webidl.ts","../src/lib/simple-queue.ts","../src/lib/abstract-ops/internal-methods.ts","../src/lib/readable-stream/generic-reader.ts","../src/stub/number-isfinite.ts","../src/stub/math-trunc.ts","../src/lib/validators/basic.ts","../src/lib/validators/readable-stream.ts","../src/lib/readable-stream/default-reader.ts","../src/lib/abstract-ops/ecmascript.ts","../src/target/es5/stub/async-iterator-prototype.ts","../src/lib/readable-stream/async-iterator.ts","../src/stub/number-isnan.ts","../src/lib/abstract-ops/miscellaneous.ts","../src/lib/abstract-ops/queue-with-sizes.ts","../src/lib/helpers/array-buffer-view.ts","../src/lib/readable-stream/byte-stream-controller.ts","../src/lib/validators/reader-options.ts","../src/lib/readable-stream/byob-reader.ts","../src/lib/abstract-ops/queuing-strategy.ts","../src/lib/validators/queuing-strategy.ts","../src/lib/validators/underlying-sink.ts","../src/lib/validators/writable-stream.ts","../src/lib/abort-signal.ts","../src/lib/writable-stream.ts","../src/globals.ts","../src/stub/dom-exception.ts","../src/lib/readable-stream/pipe.ts","../src/lib/readable-stream/default-controller.ts","../src/lib/readable-stream/tee.ts","../src/lib/readable-stream/readable-stream-like.ts","../src/lib/readable-stream/from.ts","../src/lib/validators/underlying-source.ts","../src/lib/validators/iterator-options.ts","../src/lib/validators/pipe-options.ts","../src/lib/validators/readable-writable-pair.ts","../src/lib/readable-stream.ts","../src/lib/validators/queuing-strategy-init.ts","../src/lib/byte-length-queuing-strategy.ts","../src/lib/count-queuing-strategy.ts","../src/lib/validators/transformer.ts","../src/lib/transform-stream.ts","../src/polyfill.ts"],"sourcesContent":["/// \n\nconst SymbolPolyfill: (description?: string) => symbol =\n typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ?\n Symbol :\n description => `Symbol(${description})` as any as symbol;\n\nexport default SymbolPolyfill;\n","/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise, SuppressedError, Symbol */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\r\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\r\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\r\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\r\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\r\n var _, done = false;\r\n for (var i = decorators.length - 1; i >= 0; i--) {\r\n var context = {};\r\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\r\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\r\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\r\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\r\n if (kind === \"accessor\") {\r\n if (result === void 0) continue;\r\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\r\n if (_ = accept(result.get)) descriptor.get = _;\r\n if (_ = accept(result.set)) descriptor.set = _;\r\n if (_ = accept(result.init)) initializers.unshift(_);\r\n }\r\n else if (_ = accept(result)) {\r\n if (kind === \"field\") initializers.unshift(_);\r\n else descriptor[key] = _;\r\n }\r\n }\r\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\r\n done = true;\r\n};\r\n\r\nexport function __runInitializers(thisArg, initializers, value) {\r\n var useValue = arguments.length > 2;\r\n for (var i = 0; i < initializers.length; i++) {\r\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\r\n }\r\n return useValue ? value : void 0;\r\n};\r\n\r\nexport function __propKey(x) {\r\n return typeof x === \"symbol\" ? x : \"\".concat(x);\r\n};\r\n\r\nexport function __setFunctionName(f, name, prefix) {\r\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\r\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\r\n};\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n var desc = Object.getOwnPropertyDescriptor(m, k);\r\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\r\n desc = { enumerable: true, get: function() { return m[k]; } };\r\n }\r\n Object.defineProperty(o, k2, desc);\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\nexport function __classPrivateFieldIn(state, receiver) {\r\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\r\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\r\n}\r\n\r\nexport function __addDisposableResource(env, value, async) {\r\n if (value !== null && value !== void 0) {\r\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\r\n var dispose;\r\n if (async) {\r\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\r\n dispose = value[Symbol.asyncDispose];\r\n }\r\n if (dispose === void 0) {\r\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\r\n dispose = value[Symbol.dispose];\r\n }\r\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\r\n env.stack.push({ value: value, dispose: dispose, async: async });\r\n }\r\n else if (async) {\r\n env.stack.push({ async: true });\r\n }\r\n return value;\r\n}\r\n\r\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n};\r\n\r\nexport function __disposeResources(env) {\r\n function fail(e) {\r\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\r\n env.hasError = true;\r\n }\r\n function next() {\r\n while (env.stack.length) {\r\n var rec = env.stack.pop();\r\n try {\r\n var result = rec.dispose && rec.dispose.call(rec.value);\r\n if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\r\n }\r\n catch (e) {\r\n fail(e);\r\n }\r\n }\r\n if (env.hasError) throw env.error;\r\n }\r\n return next();\r\n}\r\n\r\nexport default {\r\n __extends: __extends,\r\n __assign: __assign,\r\n __rest: __rest,\r\n __decorate: __decorate,\r\n __param: __param,\r\n __metadata: __metadata,\r\n __awaiter: __awaiter,\r\n __generator: __generator,\r\n __createBinding: __createBinding,\r\n __exportStar: __exportStar,\r\n __values: __values,\r\n __read: __read,\r\n __spread: __spread,\r\n __spreadArrays: __spreadArrays,\r\n __spreadArray: __spreadArray,\r\n __await: __await,\r\n __asyncGenerator: __asyncGenerator,\r\n __asyncDelegator: __asyncDelegator,\r\n __asyncValues: __asyncValues,\r\n __makeTemplateObject: __makeTemplateObject,\r\n __importStar: __importStar,\r\n __importDefault: __importDefault,\r\n __classPrivateFieldGet: __classPrivateFieldGet,\r\n __classPrivateFieldSet: __classPrivateFieldSet,\r\n __classPrivateFieldIn: __classPrivateFieldIn,\r\n __addDisposableResource: __addDisposableResource,\r\n __disposeResources: __disposeResources,\r\n};\r\n","export function noop(): undefined {\n return undefined;\n}\n","import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n\nexport function setFunctionName(fn: Function, name: string): void {\n try {\n Object.defineProperty(fn, 'name', {\n value: name,\n configurable: true\n });\n } catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n }\n}\n","import { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\n// https://webidl.spec.whatwg.org/#a-new-promise\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-resolved-with\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return newPromise(resolve => resolve(value));\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-rejected-with\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\n// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned\n// from that handler. To prevent this, return null instead of void from all handlers.\n// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => null | PromiseLike,\n onRejected?: (reason: any) => null | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => null | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => null | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nlet _queueMicrotask: (callback: () => void) => void = callback => {\n if (typeof queueMicrotask === 'function') {\n _queueMicrotask = queueMicrotask;\n } else {\n const resolvedPromise = promiseResolvedWith(undefined);\n _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb);\n }\n return _queueMicrotask(callback);\n};\n\nexport { _queueMicrotask as queueMicrotask };\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n","import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n","export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\nexport const ReleaseSteps = Symbol('[[ReleaseSteps]]');\n","import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, type ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\nimport { ReleaseSteps } from '../abstract-ops/internal-methods';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n assert(stream._reader === reader);\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n stream._readableStreamController[ReleaseSteps]();\n\n stream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n","import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n","import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamDefaultReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamDefaultReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\nexport function ReadableStreamDefaultReaderRelease(reader: ReadableStreamDefaultReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n}\n\nexport function ReadableStreamDefaultReaderErrorReadRequests(reader: ReadableStreamDefaultReader, e: any) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n","import { reflectCall } from 'lib/helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport assert from '../../stub/assert';\n\ndeclare global {\n interface ArrayBuffer {\n readonly detached: boolean;\n\n transfer(): ArrayBuffer;\n }\n\n function structuredClone(value: T, options: { transfer: ArrayBuffer[] }): T;\n}\n\nexport function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\nexport let TransferArrayBuffer = (O: ArrayBuffer): ArrayBuffer => {\n if (typeof O.transfer === 'function') {\n TransferArrayBuffer = buffer => buffer.transfer();\n } else if (typeof structuredClone === 'function') {\n TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] });\n } else {\n // Not implemented correctly\n TransferArrayBuffer = buffer => buffer;\n }\n return TransferArrayBuffer(O);\n};\n\nexport function CanTransferArrayBuffer(O: ArrayBuffer): boolean {\n return !IsDetachedBuffer(O);\n}\n\nexport let IsDetachedBuffer = (O: ArrayBuffer): boolean => {\n if (typeof O.detached === 'boolean') {\n IsDetachedBuffer = buffer => buffer.detached;\n } else {\n // Not implemented correctly\n IsDetachedBuffer = buffer => buffer.byteLength === 0;\n }\n return IsDetachedBuffer(O);\n};\n\nexport function ArrayBufferSlice(buffer: ArrayBuffer, begin: number, end: number): ArrayBuffer {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n\nexport type MethodName = {\n [P in keyof T]: T[P] extends Function | undefined ? P : never;\n}[keyof T];\n\nexport function GetMethod>(receiver: T, prop: K): T[K] | undefined {\n const func = receiver[prop];\n if (func === undefined || func === null) {\n return undefined;\n }\n if (typeof func !== 'function') {\n throw new TypeError(`${String(prop)} is not a function`);\n }\n return func;\n}\n\nexport interface SyncIteratorRecord {\n iterator: Iterator,\n nextMethod: Iterator['next'],\n done: boolean;\n}\n\nexport interface AsyncIteratorRecord {\n iterator: AsyncIterator,\n nextMethod: AsyncIterator['next'],\n done: boolean;\n}\n\nexport type SyncOrAsyncIteratorRecord = SyncIteratorRecord | AsyncIteratorRecord;\n\nexport function CreateAsyncFromSyncIterator(syncIteratorRecord: SyncIteratorRecord): AsyncIteratorRecord {\n // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%,\n // we use yield* inside an async generator function to achieve the same result.\n\n // Wrap the sync iterator inside a sync iterable, so we can use it with yield*.\n const syncIterable = {\n [Symbol.iterator]: () => syncIteratorRecord.iterator\n };\n // Create an async generator function and immediately invoke it.\n const asyncIterator = (async function* () {\n return yield* syncIterable;\n }());\n // Return as an async iterator record.\n const nextMethod = asyncIterator.next;\n return { iterator: asyncIterator, nextMethod, done: false };\n}\n\n// Aligns with core-js/modules/es.symbol.async-iterator.js\nexport const SymbolAsyncIterator: (typeof Symbol)['asyncIterator'] =\n Symbol.asyncIterator ??\n Symbol.for?.('Symbol.asyncIterator') ??\n '@@asyncIterator';\n\nexport type SyncOrAsyncIterable = Iterable | AsyncIterable;\nexport type SyncOrAsyncIteratorMethod = () => (Iterator | AsyncIterator);\n\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint: 'async',\n method?: SyncOrAsyncIteratorMethod\n): AsyncIteratorRecord;\nfunction GetIterator(\n obj: Iterable,\n hint: 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncIteratorRecord;\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint = 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncOrAsyncIteratorRecord {\n assert(hint === 'sync' || hint === 'async');\n if (method === undefined) {\n if (hint === 'async') {\n method = GetMethod(obj as AsyncIterable, SymbolAsyncIterator);\n if (method === undefined) {\n const syncMethod = GetMethod(obj as Iterable, Symbol.iterator);\n const syncIteratorRecord = GetIterator(obj as Iterable, 'sync', syncMethod);\n return CreateAsyncFromSyncIterator(syncIteratorRecord);\n }\n } else {\n method = GetMethod(obj as Iterable, Symbol.iterator);\n }\n }\n if (method === undefined) {\n throw new TypeError('The object is not iterable');\n }\n const iterator = reflectCall(method, obj, []);\n if (!typeIsObject(iterator)) {\n throw new TypeError('The iterator method must return an object');\n }\n const nextMethod = iterator.next;\n return { iterator, nextMethod, done: false } as SyncOrAsyncIteratorRecord;\n}\n\nexport { GetIterator };\n\nexport function IteratorNext(iteratorRecord: AsyncIteratorRecord): Promise> {\n const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []);\n if (!typeIsObject(result)) {\n throw new TypeError('The iterator.next() method must return an object');\n }\n return result;\n}\n\nexport function IteratorComplete(\n iterResult: IteratorResult\n): iterResult is IteratorReturnResult {\n assert(typeIsObject(iterResult));\n return Boolean(iterResult.done);\n}\n\nexport function IteratorValue(iterResult: IteratorYieldResult): T {\n assert(typeIsObject(iterResult));\n return iterResult.value;\n}\n","/// \n\nimport { SymbolAsyncIterator } from '../../../lib/abstract-ops/ecmascript';\n\n// We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it.\nexport const AsyncIteratorPrototype: AsyncIterable = {\n // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( )\n // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator\n [SymbolAsyncIterator](this: AsyncIterator) {\n return this;\n }\n};\nObject.defineProperty(AsyncIteratorPrototype, SymbolAsyncIterator, { enumerable: false });\n","/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadableStreamDefaultReadResult,\n type ReadRequest\n} from './default-reader';\nimport { ReadableStreamReaderGenericCancel, ReadableStreamReaderGenericRelease } from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterableIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ninterface ReadableStreamAsyncIteratorInstance extends ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nObject.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n","import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: NonShared): NonShared {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer) as NonShared;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n","export type TypedArray =\n | Int8Array\n | Uint8Array\n | Uint8ClampedArray\n | Int16Array\n | Uint16Array\n | Int32Array\n | Uint32Array\n | Float32Array\n | Float64Array;\n\nexport type NonShared = T & {\n buffer: ArrayBuffer;\n}\n\nexport interface ArrayBufferViewConstructor {\n new(buffer: ArrayBuffer, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n}\n\nexport interface TypedArrayConstructor extends ArrayBufferViewConstructor {\n readonly BYTES_PER_ELEMENT: number;\n}\n\nexport type DataViewConstructor = ArrayBufferViewConstructor;\n\nfunction isDataViewConstructor(ctor: Function): ctor is DataViewConstructor {\n return ctor === DataView;\n}\n\nexport function isDataView(view: ArrayBufferView): view is DataView {\n return isDataViewConstructor(view.constructor);\n}\n\nexport function arrayBufferViewElementSize(ctor: ArrayBufferViewConstructor): number {\n if (isDataViewConstructor(ctor)) {\n return 1;\n }\n return (ctor as unknown as TypedArrayConstructor).BYTES_PER_ELEMENT;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n IsReadableStreamDefaultReader,\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n type ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n type ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n type ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport type { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\nimport {\n type ArrayBufferViewConstructor,\n arrayBufferViewElementSize,\n type NonShared,\n type TypedArrayConstructor\n} from '../helpers/array-buffer-view';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: NonShared | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: NonShared): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond');\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBuffer;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor = NonShared> =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: TypedArrayConstructor;\n readerType: 'default' | 'none';\n}\n\ninterface BYOBPullIntoDescriptor = NonShared> {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob' | 'none';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: NonShared): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest>): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n minimumFill: 1,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n if (this._pendingPullIntos.length > 0) {\n const firstPullInto = this._pendingPullIntos.peek();\n firstPullInto.readerType = 'none';\n\n this._pendingPullIntos = new SimpleQueue();\n this._pendingPullIntos.push(firstPullInto);\n }\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableByteStreamController.prototype.close, 'close');\nsetFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableByteStreamController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor>(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n assert(pullIntoDescriptor.readerType !== 'none');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as NonShared, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor>(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n let clonedChunk;\n try {\n clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength);\n } catch (cloneE) {\n ReadableByteStreamControllerError(controller, cloneE);\n throw cloneE;\n }\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength);\n}\n\nfunction ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.readerType === 'none');\n if (firstDescriptor.bytesFilled > 0) {\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n firstDescriptor.buffer,\n firstDescriptor.byteOffset,\n firstDescriptor.bytesFilled\n );\n }\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize;\n const maxAlignedBytes = maxBytesFilled - remainderBytes;\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n assert(pullIntoDescriptor.readerType !== 'none');\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nfunction ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller: ReadableByteStreamController) {\n const reader = controller._controlledReadableByteStream._reader;\n assert(IsReadableStreamDefaultReader(reader));\n while (reader._readRequests.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n const readRequest = reader._readRequests.shift();\n ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest);\n }\n}\n\nexport function ReadableByteStreamControllerPullInto>(\n controller: ReadableByteStreamController,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n const elementSize = arrayBufferViewElementSize(ctor);\n\n const { byteOffset, byteLength } = view;\n\n const minimumFill = min * elementSize;\n assert(minimumFill >= elementSize && minimumFill <= byteLength);\n assert(minimumFill % elementSize === 0);\n\n let buffer: ArrayBuffer;\n try {\n buffer = TransferArrayBuffer(view.buffer);\n } catch (e) {\n readIntoRequest._errorSteps(e);\n return;\n }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset,\n byteLength,\n bytesFilled: 0,\n minimumFill,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled % firstDescriptor.elementSize === 0);\n\n if (firstDescriptor.readerType === 'none') {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n return;\n }\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) {\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n pullIntoDescriptor.buffer,\n end - remainderSize,\n remainderSize\n );\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(\n controller: ReadableByteStreamController,\n chunk: NonShared\n) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const { buffer, byteOffset, byteLength } = chunk;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n if (firstPendingPullInto.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto);\n }\n }\n\n if (ReadableStreamHasDefaultReader(stream)) {\n ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller);\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView as NonShared, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerFillReadRequestFromQueue(\n controller: ReadableByteStreamController,\n readRequest: ReadRequest>\n) {\n assert(controller._queueTotalSize > 0);\n\n const entry = controller._queue.shift();\n controller._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n readRequest._chunkSteps(view as NonShared);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view as NonShared);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: NonShared) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: NonShared) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n","import { assertDictionary, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n\nexport function convertByobReadOptions(\n options: ReadableStreamBYOBReaderReadOptions | null | undefined,\n context: string\n): ValidatedReadableStreamBYOBReaderReadOptions {\n assertDictionary(options, context);\n const min = options?.min ?? 1;\n return {\n min: convertUnsignedLongLongWithEnforceRange(\n min,\n `${context} has member 'min' that`\n )\n };\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, type ReadableByteStream, type ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from './reader-options';\nimport { convertByobReadOptions } from '../validators/reader-options';\nimport { isDataView, type NonShared, type TypedArray } from '../helpers/array-buffer-view';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream as ReadableStream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest>(\n stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest\n): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest> {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(\n view: T,\n options?: ReadableStreamBYOBReaderReadOptions\n ): Promise>;\n read>(\n view: T,\n rawOptions: ReadableStreamBYOBReaderReadOptions | null | undefined = {}\n ): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n let options: ValidatedReadableStreamBYOBReaderReadOptions;\n try {\n options = convertByobReadOptions(rawOptions, 'options');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const min = options.min;\n if (min === 0) {\n return promiseRejectedWith(new TypeError('options.min must be greater than 0'));\n }\n if (!isDataView(view)) {\n if (min > (view as unknown as TypedArray).length) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s length'));\n }\n } else if (min > view.byteLength) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s byteLength'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamBYOBReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamBYOBReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead>(\n reader: ReadableStreamBYOBReader,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n min,\n readIntoRequest\n );\n }\n}\n\nexport function ReadableStreamBYOBReaderRelease(reader: ReadableStreamBYOBReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n}\n\nexport function ReadableStreamBYOBReaderErrorReadIntoRequests(reader: ReadableStreamBYOBReader, e: any) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n","/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * If aborted, returns the reason for aborting.\n */\n readonly reason?: any;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(reason?: any): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n type QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { type AbortController, type AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(WritableStream.prototype.abort, 'abort');\nsetFunctionName(WritableStream.prototype.close, 'close');\nsetFunctionName(WritableStream.prototype.getWriter, 'getWriter');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight\n};\n\nexport type {\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort(reason);\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nsetFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort');\nsetFunctionName(WritableStreamDefaultWriter.prototype.close, 'close');\nsetFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock');\nsetFunctionName(WritableStreamDefaultWriter.prototype.write, 'write');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n return null;\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let writeAlgorithm: (chunk: W) => Promise;\n let closeAlgorithm: () => Promise;\n let abortAlgorithm: (reason: any) => Promise;\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n } else {\n writeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n } else {\n closeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n } else {\n abortAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n return null;\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n","/// \n\nfunction getGlobals(): typeof globalThis | undefined {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n } else if (typeof self !== 'undefined') {\n return self;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n","/// \nimport { globals } from '../globals';\nimport { setFunctionName } from '../lib/helpers/miscellaneous';\n\ninterface DOMException extends Error {\n name: string;\n message: string;\n}\n\ntype DOMExceptionConstructor = new (message?: string, name?: string) => DOMException;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n if ((ctor as DOMExceptionConstructor).name !== 'DOMException') {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Support:\n * - Web browsers\n * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87)\n */\nfunction getFromGlobal(): DOMExceptionConstructor | undefined {\n const ctor = globals?.DOMException;\n return isDOMExceptionConstructor(ctor) ? ctor : undefined;\n}\n\n/**\n * Support:\n * - All platforms\n */\nfunction createPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line @typescript-eslint/no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n setFunctionName(ctor, 'DOMException');\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nconst DOMException: DOMExceptionConstructor = getFromGlobal() || createPolyfill();\n\nexport { DOMException };\n","import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n return null;\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => null) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => null) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest(): null {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n return null;\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any): null {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n\n return null;\n }\n });\n}\n","import type { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, type QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n type ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport type { ValidatedUnderlyingSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n // Do nothing.\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultController.prototype.close, 'close');\nsetFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableStreamDefaultController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n","import {\n CreateReadableByteStream,\n CreateReadableStream,\n type DefaultReadableStream,\n IsReadableStream,\n type ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n type ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n type ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(\n stream: ReadableStream,\n cloneForBranch2: boolean\n): [DefaultReadableStream, DefaultReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: DefaultReadableStream;\n let branch2: DefaultReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader> = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader>) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return null;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: NonShared, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader>(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n","import { typeIsObject } from '../helpers/miscellaneous';\nimport type { ReadableStreamDefaultReadResult } from './default-reader';\n\n/**\n * A common interface for a `ReadadableStream` implementation.\n *\n * @public\n */\nexport interface ReadableStreamLike {\n readonly locked: boolean;\n\n getReader(): ReadableStreamDefaultReaderLike;\n}\n\n/**\n * A common interface for a `ReadableStreamDefaultReader` implementation.\n *\n * @public\n */\nexport interface ReadableStreamDefaultReaderLike {\n readonly closed: Promise;\n\n cancel(reason?: any): Promise;\n\n read(): Promise>;\n\n releaseLock(): void;\n}\n\nexport function isReadableStreamLike(stream: unknown): stream is ReadableStreamLike {\n return typeIsObject(stream) && typeof (stream as ReadableStreamLike).getReader !== 'undefined';\n}\n","import { CreateReadableStream, type DefaultReadableStream } from '../readable-stream';\nimport {\n isReadableStreamLike,\n type ReadableStreamDefaultReaderLike,\n type ReadableStreamLike\n} from './readable-stream-like';\nimport { ReadableStreamDefaultControllerClose, ReadableStreamDefaultControllerEnqueue } from './default-controller';\nimport { GetIterator, GetMethod, IteratorComplete, IteratorNext, IteratorValue } from '../abstract-ops/ecmascript';\nimport { promiseRejectedWith, promiseResolvedWith, reflectCall, transformPromiseWith } from '../helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { noop } from '../../utils';\n\nexport function ReadableStreamFrom(\n source: Iterable | AsyncIterable | ReadableStreamLike\n): DefaultReadableStream {\n if (isReadableStreamLike(source)) {\n return ReadableStreamFromDefaultReader(source.getReader());\n }\n return ReadableStreamFromIterable(source);\n}\n\nexport function ReadableStreamFromIterable(asyncIterable: Iterable | AsyncIterable): DefaultReadableStream {\n let stream: DefaultReadableStream;\n const iteratorRecord = GetIterator(asyncIterable, 'async');\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let nextResult;\n try {\n nextResult = IteratorNext(iteratorRecord);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const nextPromise = promiseResolvedWith(nextResult);\n return transformPromiseWith(nextPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object');\n }\n const done = IteratorComplete(iterResult);\n if (done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = IteratorValue(iterResult);\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n const iterator = iteratorRecord.iterator;\n let returnMethod: (typeof iterator)['return'] | undefined;\n try {\n returnMethod = GetMethod(iterator, 'return');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n if (returnMethod === undefined) {\n return promiseResolvedWith(undefined);\n }\n let returnResult: IteratorResult | Promise>;\n try {\n returnResult = reflectCall(returnMethod, iterator, [reason]);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const returnPromise = promiseResolvedWith(returnResult);\n return transformPromiseWith(returnPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object');\n }\n return undefined;\n });\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n\nexport function ReadableStreamFromDefaultReader(\n reader: ReadableStreamDefaultReaderLike\n): DefaultReadableStream {\n let stream: DefaultReadableStream;\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let readPromise;\n try {\n readPromise = reader.read();\n } catch (e) {\n return promiseRejectedWith(e);\n }\n return transformPromiseWith(readPromise, readResult => {\n if (!typeIsObject(readResult)) {\n throw new TypeError('The promise returned by the reader.read() method must fulfill with an object');\n }\n if (readResult.done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = readResult.value;\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n try {\n return promiseResolvedWith(reader.cancel(reason));\n } catch (e) {\n return promiseRejectedWith(e);\n }\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n","import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n","import { assertDictionary } from './basic';\nimport type {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n","import { assertDictionary } from './basic';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n","import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n","import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, type ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderErrorReadRequests,\n type ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReaderErrorReadIntoRequests,\n type ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { ReadableStreamFrom } from './readable-stream/from';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport type {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList, SymbolAsyncIterator } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions\n} from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport type { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport type { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\nimport type { ReadableStreamDefaultReaderLike, ReadableStreamLike } from './readable-stream/readable-stream-like';\nimport type { NonShared } from './helpers/array-buffer-view';\n\nexport type DefaultReadableStream = ReadableStream & {\n _readableStreamController: ReadableStreamDefaultController\n};\n\nexport type ReadableByteStream = ReadableStream> & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream implements AsyncIterable {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n\n [SymbolAsyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator {\n // Stub implementation, overridden below\n return this.values(options);\n }\n\n /**\n * Creates a new ReadableStream wrapping the provided iterable or async iterable.\n *\n * This can be used to adapt various kinds of objects into a readable stream,\n * such as an array, an async generator, or a Node.js readable stream.\n */\n static from(asyncIterable: Iterable | AsyncIterable | ReadableStreamLike): ReadableStream {\n return ReadableStreamFrom(asyncIterable);\n }\n}\n\nObject.defineProperties(ReadableStream, {\n from: { enumerable: true }\n});\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(ReadableStream.from, 'from');\nsetFunctionName(ReadableStream.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStream.prototype.getReader, 'getReader');\nsetFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough');\nsetFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo');\nsetFunctionName(ReadableStream.prototype.tee, 'tee');\nsetFunctionName(ReadableStream.prototype.values, 'values');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nObject.defineProperty(ReadableStream.prototype, SymbolAsyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n});\n\nexport type {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n ReadableStreamBYOBReaderReadOptions,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions,\n ReadableStreamLike,\n ReadableStreamDefaultReaderLike\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1\n): DefaultReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: DefaultReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n","import type { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\nsetFunctionName(byteLengthSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\nsetFunctionName(countSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const cancel = original?.cancel;\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n cancel: cancel === undefined ?\n undefined :\n convertTransformerCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n\nfunction convertTransformerCancelCallback(\n fn: TransformerCancelCallback,\n original: Transformer,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith,\n uponPromise\n} from './helpers/webidl';\nimport { CreateReadableStream, type DefaultReadableStream, ReadableStream } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: DefaultReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport type {\n Transformer,\n TransformerCancelCallback,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSourceCancelAlgorithm(stream, reason);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n TransformStreamUnblockWrite(stream);\n}\n\nfunction TransformStreamUnblockWrite(stream: TransformStream) {\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _finishPromise: Promise | undefined;\n /** @internal */\n _finishPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _finishPromise_reject?: (reason: any) => void;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n /** @internal */\n _cancelAlgorithm: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(TransformStreamDefaultController.prototype.error, 'error');\nsetFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._finishPromise = undefined;\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm: (chunk: I) => Promise;\n let flushAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n } else {\n transformAlgorithm = chunk => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n }\n\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n } else {\n flushAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n if (transformer.cancel !== undefined) {\n cancelAlgorithm = reason => transformer.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally,\n // we don't run the _cancelAlgorithm again.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerError(readable._readableStreamController, reason);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally,\n // we don't also run the _cancelAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(flushPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerClose(readable._readableStreamController);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\nfunction TransformStreamDefaultSourceCancelAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._writable cannot change after construction, so caching it across a call to user code is safe.\n const writable = stream._writable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or\n // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the\n // _flushAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (writable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, writable._storedError);\n } else {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\nexport function defaultControllerFinishPromiseResolve(controller: TransformStreamDefaultController) {\n if (controller._finishPromise_resolve === undefined) {\n return;\n }\n\n controller._finishPromise_resolve();\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nexport function defaultControllerFinishPromiseReject(controller: TransformStreamDefaultController, reason: any) {\n if (controller._finishPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(controller._finishPromise!);\n controller._finishPromise_reject(reason);\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n","import {\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n ReadableByteStreamController,\n ReadableStream,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultController,\n ReadableStreamDefaultReader,\n TransformStream,\n TransformStreamDefaultController,\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter\n} from './ponyfill';\nimport { globals } from './globals';\n\n// Export\nexport * from './ponyfill';\n\nconst exports = {\n ReadableStream,\n ReadableStreamDefaultController,\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader,\n\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter,\n\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n\n TransformStream,\n TransformStreamDefaultController\n};\n\n// Add classes to global scope\nif (typeof globals !== 'undefined') {\n for (const prop in exports) {\n if (Object.prototype.hasOwnProperty.call(exports, prop)) {\n Object.defineProperty(globals, prop, {\n value: exports[prop as (keyof typeof exports)],\n writable: true,\n configurable: true\n });\n }\n }\n}\n"],"names":["Symbol","_a","queueMicrotask","streamBrandCheckException","defaultControllerBrandCheckException"],"mappings":";;;;;;;AAAA;AAEA,IAAM,cAAc,GAClB,OAAO,MAAM,KAAK,UAAU,IAAI,OAAO,MAAM,CAAC,QAAQ,KAAK,QAAQ;AACjE,IAAA,MAAM;IACN,UAAA,WAAW,IAAI,OAAA,SAAA,CAAA,MAAA,CAAU,WAAW,EAAoB,GAAA,CAAA,CAAA,EAAA;;ACL5D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AA4GA;AACO,SAAS,WAAW,CAAC,OAAO,EAAE,IAAI,EAAE;AAC3C,IAAI,IAAI,CAAC,GAAG,EAAE,KAAK,EAAE,CAAC,EAAE,IAAI,EAAE,WAAW,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,IAAI,EAAE,EAAE,EAAE,GAAG,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;AACrH,IAAI,OAAO,CAAC,GAAG,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,OAAO,MAAM,KAAK,UAAU,KAAK,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,GAAG,WAAW,EAAE,OAAO,IAAI,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;AAC7J,IAAI,SAAS,IAAI,CAAC,CAAC,EAAE,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ignoreList":[1]} \ No newline at end of file diff --git a/backend/node_modules/web-streams-polyfill/dist/ponyfill.es2018.js b/backend/node_modules/web-streams-polyfill/dist/ponyfill.es2018.js new file mode 100644 index 0000000000000000000000000000000000000000..75ddde26d6d27ccd89626269b85083674c789e2f --- /dev/null +++ b/backend/node_modules/web-streams-polyfill/dist/ponyfill.es2018.js @@ -0,0 +1,4737 @@ +/** + * @license + * web-streams-polyfill v3.3.3 + * Copyright 2024 Mattias Buelens, Diwank Singh Tomer and other contributors. + * This code is released under the MIT license. + * SPDX-License-Identifier: MIT + */ +(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.WebStreamsPolyfill = {})); +})(this, (function (exports) { 'use strict'; + + function noop() { + return undefined; + } + + function typeIsObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; + } + const rethrowAssertionErrorRejection = noop; + function setFunctionName(fn, name) { + try { + Object.defineProperty(fn, 'name', { + value: name, + configurable: true + }); + } + catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility + } + } + + const originalPromise = Promise; + const originalPromiseThen = Promise.prototype.then; + const originalPromiseReject = Promise.reject.bind(originalPromise); + // https://webidl.spec.whatwg.org/#a-new-promise + function newPromise(executor) { + return new originalPromise(executor); + } + // https://webidl.spec.whatwg.org/#a-promise-resolved-with + function promiseResolvedWith(value) { + return newPromise(resolve => resolve(value)); + } + // https://webidl.spec.whatwg.org/#a-promise-rejected-with + function promiseRejectedWith(reason) { + return originalPromiseReject(reason); + } + function PerformPromiseThen(promise, onFulfilled, onRejected) { + // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an + // approximation. + return originalPromiseThen.call(promise, onFulfilled, onRejected); + } + // Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned + // from that handler. To prevent this, return null instead of void from all handlers. + // http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it + function uponPromise(promise, onFulfilled, onRejected) { + PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection); + } + function uponFulfillment(promise, onFulfilled) { + uponPromise(promise, onFulfilled); + } + function uponRejection(promise, onRejected) { + uponPromise(promise, undefined, onRejected); + } + function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { + return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); + } + function setPromiseIsHandledToTrue(promise) { + PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection); + } + let _queueMicrotask = callback => { + if (typeof queueMicrotask === 'function') { + _queueMicrotask = queueMicrotask; + } + else { + const resolvedPromise = promiseResolvedWith(undefined); + _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb); + } + return _queueMicrotask(callback); + }; + function reflectCall(F, V, args) { + if (typeof F !== 'function') { + throw new TypeError('Argument is not a function'); + } + return Function.prototype.apply.call(F, V, args); + } + function promiseCall(F, V, args) { + try { + return promiseResolvedWith(reflectCall(F, V, args)); + } + catch (value) { + return promiseRejectedWith(value); + } + } + + // Original from Chromium + // https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js + const QUEUE_MAX_ARRAY_SIZE = 16384; + /** + * Simple queue structure. + * + * Avoids scalability issues with using a packed array directly by using + * multiple arrays in a linked list and keeping the array size bounded. + */ + class SimpleQueue { + constructor() { + this._cursor = 0; + this._size = 0; + // _front and _back are always defined. + this._front = { + _elements: [], + _next: undefined + }; + this._back = this._front; + // The cursor is used to avoid calling Array.shift(). + // It contains the index of the front element of the array inside the + // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE). + this._cursor = 0; + // When there is only one node, size === elements.length - cursor. + this._size = 0; + } + get length() { + return this._size; + } + // For exception safety, this method is structured in order: + // 1. Read state + // 2. Calculate required state mutations + // 3. Perform state mutations + push(element) { + const oldBack = this._back; + let newBack = oldBack; + if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { + newBack = { + _elements: [], + _next: undefined + }; + } + // push() is the mutation most likely to throw an exception, so it + // goes first. + oldBack._elements.push(element); + if (newBack !== oldBack) { + this._back = newBack; + oldBack._next = newBack; + } + ++this._size; + } + // Like push(), shift() follows the read -> calculate -> mutate pattern for + // exception safety. + shift() { // must not be called on an empty queue + const oldFront = this._front; + let newFront = oldFront; + const oldCursor = this._cursor; + let newCursor = oldCursor + 1; + const elements = oldFront._elements; + const element = elements[oldCursor]; + if (newCursor === QUEUE_MAX_ARRAY_SIZE) { + newFront = oldFront._next; + newCursor = 0; + } + // No mutations before this point. + --this._size; + this._cursor = newCursor; + if (oldFront !== newFront) { + this._front = newFront; + } + // Permit shifted element to be garbage collected. + elements[oldCursor] = undefined; + return element; + } + // The tricky thing about forEach() is that it can be called + // re-entrantly. The queue may be mutated inside the callback. It is easy to + // see that push() within the callback has no negative effects since the end + // of the queue is checked for on every iteration. If shift() is called + // repeatedly within the callback then the next iteration may return an + // element that has been removed. In this case the callback will be called + // with undefined values until we either "catch up" with elements that still + // exist or reach the back of the queue. + forEach(callback) { + let i = this._cursor; + let node = this._front; + let elements = node._elements; + while (i !== elements.length || node._next !== undefined) { + if (i === elements.length) { + node = node._next; + elements = node._elements; + i = 0; + if (elements.length === 0) { + break; + } + } + callback(elements[i]); + ++i; + } + } + // Return the element that would be returned if shift() was called now, + // without modifying the queue. + peek() { // must not be called on an empty queue + const front = this._front; + const cursor = this._cursor; + return front._elements[cursor]; + } + } + + const AbortSteps = Symbol('[[AbortSteps]]'); + const ErrorSteps = Symbol('[[ErrorSteps]]'); + const CancelSteps = Symbol('[[CancelSteps]]'); + const PullSteps = Symbol('[[PullSteps]]'); + const ReleaseSteps = Symbol('[[ReleaseSteps]]'); + + function ReadableStreamReaderGenericInitialize(reader, stream) { + reader._ownerReadableStream = stream; + stream._reader = reader; + if (stream._state === 'readable') { + defaultReaderClosedPromiseInitialize(reader); + } + else if (stream._state === 'closed') { + defaultReaderClosedPromiseInitializeAsResolved(reader); + } + else { + defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); + } + } + // A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state + // check. + function ReadableStreamReaderGenericCancel(reader, reason) { + const stream = reader._ownerReadableStream; + return ReadableStreamCancel(stream, reason); + } + function ReadableStreamReaderGenericRelease(reader) { + const stream = reader._ownerReadableStream; + if (stream._state === 'readable') { + defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + else { + defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + stream._readableStreamController[ReleaseSteps](); + stream._reader = undefined; + reader._ownerReadableStream = undefined; + } + // Helper functions for the readers. + function readerLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released reader'); + } + // Helper functions for the ReadableStreamDefaultReader. + function defaultReaderClosedPromiseInitialize(reader) { + reader._closedPromise = newPromise((resolve, reject) => { + reader._closedPromise_resolve = resolve; + reader._closedPromise_reject = reject; + }); + } + function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseReject(reader, reason); + } + function defaultReaderClosedPromiseInitializeAsResolved(reader) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseResolve(reader); + } + function defaultReaderClosedPromiseReject(reader, reason) { + if (reader._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(reader._closedPromise); + reader._closedPromise_reject(reason); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; + } + function defaultReaderClosedPromiseResetToRejected(reader, reason) { + defaultReaderClosedPromiseInitializeAsRejected(reader, reason); + } + function defaultReaderClosedPromiseResolve(reader) { + if (reader._closedPromise_resolve === undefined) { + return; + } + reader._closedPromise_resolve(undefined); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; + } + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill + const NumberIsFinite = Number.isFinite || function (x) { + return typeof x === 'number' && isFinite(x); + }; + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill + const MathTrunc = Math.trunc || function (v) { + return v < 0 ? Math.ceil(v) : Math.floor(v); + }; + + // https://heycam.github.io/webidl/#idl-dictionaries + function isDictionary(x) { + return typeof x === 'object' || typeof x === 'function'; + } + function assertDictionary(obj, context) { + if (obj !== undefined && !isDictionary(obj)) { + throw new TypeError(`${context} is not an object.`); + } + } + // https://heycam.github.io/webidl/#idl-callback-functions + function assertFunction(x, context) { + if (typeof x !== 'function') { + throw new TypeError(`${context} is not a function.`); + } + } + // https://heycam.github.io/webidl/#idl-object + function isObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; + } + function assertObject(x, context) { + if (!isObject(x)) { + throw new TypeError(`${context} is not an object.`); + } + } + function assertRequiredArgument(x, position, context) { + if (x === undefined) { + throw new TypeError(`Parameter ${position} is required in '${context}'.`); + } + } + function assertRequiredField(x, field, context) { + if (x === undefined) { + throw new TypeError(`${field} is required in '${context}'.`); + } + } + // https://heycam.github.io/webidl/#idl-unrestricted-double + function convertUnrestrictedDouble(value) { + return Number(value); + } + function censorNegativeZero(x) { + return x === 0 ? 0 : x; + } + function integerPart(x) { + return censorNegativeZero(MathTrunc(x)); + } + // https://heycam.github.io/webidl/#idl-unsigned-long-long + function convertUnsignedLongLongWithEnforceRange(value, context) { + const lowerBound = 0; + const upperBound = Number.MAX_SAFE_INTEGER; + let x = Number(value); + x = censorNegativeZero(x); + if (!NumberIsFinite(x)) { + throw new TypeError(`${context} is not a finite number`); + } + x = integerPart(x); + if (x < lowerBound || x > upperBound) { + throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`); + } + if (!NumberIsFinite(x) || x === 0) { + return 0; + } + // TODO Use BigInt if supported? + // let xBigInt = BigInt(integerPart(x)); + // xBigInt = BigInt.asUintN(64, xBigInt); + // return Number(xBigInt); + return x; + } + + function assertReadableStream(x, context) { + if (!IsReadableStream(x)) { + throw new TypeError(`${context} is not a ReadableStream.`); + } + } + + // Abstract operations for the ReadableStream. + function AcquireReadableStreamDefaultReader(stream) { + return new ReadableStreamDefaultReader(stream); + } + // ReadableStream API exposed for controllers. + function ReadableStreamAddReadRequest(stream, readRequest) { + stream._reader._readRequests.push(readRequest); + } + function ReadableStreamFulfillReadRequest(stream, chunk, done) { + const reader = stream._reader; + const readRequest = reader._readRequests.shift(); + if (done) { + readRequest._closeSteps(); + } + else { + readRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadRequests(stream) { + return stream._reader._readRequests.length; + } + function ReadableStreamHasDefaultReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamDefaultReader(reader)) { + return false; + } + return true; + } + /** + * A default reader vended by a {@link ReadableStream}. + * + * @public + */ + class ReadableStreamDefaultReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + /** + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('read')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: () => resolvePromise({ value: undefined, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamDefaultReaderRead(this, readRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamDefaultReader(this)) { + throw defaultReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamDefaultReaderRelease(this); + } + } + Object.defineProperties(ReadableStreamDefaultReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + setFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel'); + setFunctionName(ReadableStreamDefaultReader.prototype.read, 'read'); + setFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, { + value: 'ReadableStreamDefaultReader', + configurable: true + }); + } + // Abstract operations for the readers. + function IsReadableStreamDefaultReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) { + return false; + } + return x instanceof ReadableStreamDefaultReader; + } + function ReadableStreamDefaultReaderRead(reader, readRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'closed') { + readRequest._closeSteps(); + } + else if (stream._state === 'errored') { + readRequest._errorSteps(stream._storedError); + } + else { + stream._readableStreamController[PullSteps](readRequest); + } + } + function ReadableStreamDefaultReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + const e = new TypeError('Reader was released'); + ReadableStreamDefaultReaderErrorReadRequests(reader, e); + } + function ReadableStreamDefaultReaderErrorReadRequests(reader, e) { + const readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(readRequest => { + readRequest._errorSteps(e); + }); + } + // Helper functions for the ReadableStreamDefaultReader. + function defaultReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`); + } + + /// + /* eslint-disable @typescript-eslint/no-empty-function */ + const AsyncIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf(async function* () { }).prototype); + + /// + class ReadableStreamAsyncIteratorImpl { + constructor(reader, preventCancel) { + this._ongoingPromise = undefined; + this._isFinished = false; + this._reader = reader; + this._preventCancel = preventCancel; + } + next() { + const nextSteps = () => this._nextSteps(); + this._ongoingPromise = this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : + nextSteps(); + return this._ongoingPromise; + } + return(value) { + const returnSteps = () => this._returnSteps(value); + return this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : + returnSteps(); + } + _nextSteps() { + if (this._isFinished) { + return Promise.resolve({ value: undefined, done: true }); + } + const reader = this._reader; + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => { + this._ongoingPromise = undefined; + // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test. + // FIXME Is this a bug in the specification, or in the test? + _queueMicrotask(() => resolvePromise({ value: chunk, done: false })); + }, + _closeSteps: () => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + resolvePromise({ value: undefined, done: true }); + }, + _errorSteps: reason => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + rejectPromise(reason); + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promise; + } + _returnSteps(value) { + if (this._isFinished) { + return Promise.resolve({ value, done: true }); + } + this._isFinished = true; + const reader = this._reader; + if (!this._preventCancel) { + const result = ReadableStreamReaderGenericCancel(reader, value); + ReadableStreamReaderGenericRelease(reader); + return transformPromiseWith(result, () => ({ value, done: true })); + } + ReadableStreamReaderGenericRelease(reader); + return promiseResolvedWith({ value, done: true }); + } + } + const ReadableStreamAsyncIteratorPrototype = { + next() { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next')); + } + return this._asyncIteratorImpl.next(); + }, + return(value) { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return')); + } + return this._asyncIteratorImpl.return(value); + } + }; + Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); + // Abstract operations for the ReadableStream. + function AcquireReadableStreamAsyncIterator(stream, preventCancel) { + const reader = AcquireReadableStreamDefaultReader(stream); + const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); + const iterator = Object.create(ReadableStreamAsyncIteratorPrototype); + iterator._asyncIteratorImpl = impl; + return iterator; + } + function IsReadableStreamAsyncIterator(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) { + return false; + } + try { + // noinspection SuspiciousTypeOfGuard + return x._asyncIteratorImpl instanceof + ReadableStreamAsyncIteratorImpl; + } + catch (_a) { + return false; + } + } + // Helper functions for the ReadableStream. + function streamAsyncIteratorBrandCheckException(name) { + return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`); + } + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill + const NumberIsNaN = Number.isNaN || function (x) { + // eslint-disable-next-line no-self-compare + return x !== x; + }; + + var _a, _b, _c; + function CreateArrayFromList(elements) { + // We use arrays to represent lists, so this is basically a no-op. + // Do a slice though just in case we happen to depend on the unique-ness. + return elements.slice(); + } + function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { + new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); + } + let TransferArrayBuffer = (O) => { + if (typeof O.transfer === 'function') { + TransferArrayBuffer = buffer => buffer.transfer(); + } + else if (typeof structuredClone === 'function') { + TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] }); + } + else { + // Not implemented correctly + TransferArrayBuffer = buffer => buffer; + } + return TransferArrayBuffer(O); + }; + let IsDetachedBuffer = (O) => { + if (typeof O.detached === 'boolean') { + IsDetachedBuffer = buffer => buffer.detached; + } + else { + // Not implemented correctly + IsDetachedBuffer = buffer => buffer.byteLength === 0; + } + return IsDetachedBuffer(O); + }; + function ArrayBufferSlice(buffer, begin, end) { + // ArrayBuffer.prototype.slice is not available on IE10 + // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice + if (buffer.slice) { + return buffer.slice(begin, end); + } + const length = end - begin; + const slice = new ArrayBuffer(length); + CopyDataBlockBytes(slice, 0, buffer, begin, length); + return slice; + } + function GetMethod(receiver, prop) { + const func = receiver[prop]; + if (func === undefined || func === null) { + return undefined; + } + if (typeof func !== 'function') { + throw new TypeError(`${String(prop)} is not a function`); + } + return func; + } + function CreateAsyncFromSyncIterator(syncIteratorRecord) { + // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%, + // we use yield* inside an async generator function to achieve the same result. + // Wrap the sync iterator inside a sync iterable, so we can use it with yield*. + const syncIterable = { + [Symbol.iterator]: () => syncIteratorRecord.iterator + }; + // Create an async generator function and immediately invoke it. + const asyncIterator = (async function* () { + return yield* syncIterable; + }()); + // Return as an async iterator record. + const nextMethod = asyncIterator.next; + return { iterator: asyncIterator, nextMethod, done: false }; + } + // Aligns with core-js/modules/es.symbol.async-iterator.js + const SymbolAsyncIterator = (_c = (_a = Symbol.asyncIterator) !== null && _a !== void 0 ? _a : (_b = Symbol.for) === null || _b === void 0 ? void 0 : _b.call(Symbol, 'Symbol.asyncIterator')) !== null && _c !== void 0 ? _c : '@@asyncIterator'; + function GetIterator(obj, hint = 'sync', method) { + if (method === undefined) { + if (hint === 'async') { + method = GetMethod(obj, SymbolAsyncIterator); + if (method === undefined) { + const syncMethod = GetMethod(obj, Symbol.iterator); + const syncIteratorRecord = GetIterator(obj, 'sync', syncMethod); + return CreateAsyncFromSyncIterator(syncIteratorRecord); + } + } + else { + method = GetMethod(obj, Symbol.iterator); + } + } + if (method === undefined) { + throw new TypeError('The object is not iterable'); + } + const iterator = reflectCall(method, obj, []); + if (!typeIsObject(iterator)) { + throw new TypeError('The iterator method must return an object'); + } + const nextMethod = iterator.next; + return { iterator, nextMethod, done: false }; + } + function IteratorNext(iteratorRecord) { + const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []); + if (!typeIsObject(result)) { + throw new TypeError('The iterator.next() method must return an object'); + } + return result; + } + function IteratorComplete(iterResult) { + return Boolean(iterResult.done); + } + function IteratorValue(iterResult) { + return iterResult.value; + } + + function IsNonNegativeNumber(v) { + if (typeof v !== 'number') { + return false; + } + if (NumberIsNaN(v)) { + return false; + } + if (v < 0) { + return false; + } + return true; + } + function CloneAsUint8Array(O) { + const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength); + return new Uint8Array(buffer); + } + + function DequeueValue(container) { + const pair = container._queue.shift(); + container._queueTotalSize -= pair.size; + if (container._queueTotalSize < 0) { + container._queueTotalSize = 0; + } + return pair.value; + } + function EnqueueValueWithSize(container, value, size) { + if (!IsNonNegativeNumber(size) || size === Infinity) { + throw new RangeError('Size must be a finite, non-NaN, non-negative number.'); + } + container._queue.push({ value, size }); + container._queueTotalSize += size; + } + function PeekQueueValue(container) { + const pair = container._queue.peek(); + return pair.value; + } + function ResetQueue(container) { + container._queue = new SimpleQueue(); + container._queueTotalSize = 0; + } + + function isDataViewConstructor(ctor) { + return ctor === DataView; + } + function isDataView(view) { + return isDataViewConstructor(view.constructor); + } + function arrayBufferViewElementSize(ctor) { + if (isDataViewConstructor(ctor)) { + return 1; + } + return ctor.BYTES_PER_ELEMENT; + } + + /** + * A pull-into request in a {@link ReadableByteStreamController}. + * + * @public + */ + class ReadableStreamBYOBRequest { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. + */ + get view() { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('view'); + } + return this._view; + } + respond(bytesWritten) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respond'); + } + assertRequiredArgument(bytesWritten, 1, 'respond'); + bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter'); + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(this._view.buffer)) { + throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`); + } + ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); + } + respondWithNewView(view) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respondWithNewView'); + } + assertRequiredArgument(view, 1, 'respondWithNewView'); + if (!ArrayBuffer.isView(view)) { + throw new TypeError('You can only respond with array buffer views'); + } + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(view.buffer)) { + throw new TypeError('The given view\'s buffer has been detached and so cannot be used as a response'); + } + ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); + } + } + Object.defineProperties(ReadableStreamBYOBRequest.prototype, { + respond: { enumerable: true }, + respondWithNewView: { enumerable: true }, + view: { enumerable: true } + }); + setFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond'); + setFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, { + value: 'ReadableStreamBYOBRequest', + configurable: true + }); + } + /** + * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. + * + * @public + */ + class ReadableByteStreamController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the current BYOB pull request, or `null` if there isn't one. + */ + get byobRequest() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('byobRequest'); + } + return ReadableByteStreamControllerGetBYOBRequest(this); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('desiredSize'); + } + return ReadableByteStreamControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('close'); + } + if (this._closeRequested) { + throw new TypeError('The stream has already been closed; do not close it again!'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`); + } + ReadableByteStreamControllerClose(this); + } + enqueue(chunk) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('enqueue'); + } + assertRequiredArgument(chunk, 1, 'enqueue'); + if (!ArrayBuffer.isView(chunk)) { + throw new TypeError('chunk must be an array buffer view'); + } + if (chunk.byteLength === 0) { + throw new TypeError('chunk must have non-zero byteLength'); + } + if (chunk.buffer.byteLength === 0) { + throw new TypeError(`chunk's buffer must have non-zero byteLength`); + } + if (this._closeRequested) { + throw new TypeError('stream is closed or draining'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`); + } + ReadableByteStreamControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('error'); + } + ReadableByteStreamControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ReadableByteStreamControllerClearPendingPullIntos(this); + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableByteStreamControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableByteStream; + if (this._queueTotalSize > 0) { + ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest); + return; + } + const autoAllocateChunkSize = this._autoAllocateChunkSize; + if (autoAllocateChunkSize !== undefined) { + let buffer; + try { + buffer = new ArrayBuffer(autoAllocateChunkSize); + } + catch (bufferE) { + readRequest._errorSteps(bufferE); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: autoAllocateChunkSize, + byteOffset: 0, + byteLength: autoAllocateChunkSize, + bytesFilled: 0, + minimumFill: 1, + elementSize: 1, + viewConstructor: Uint8Array, + readerType: 'default' + }; + this._pendingPullIntos.push(pullIntoDescriptor); + } + ReadableStreamAddReadRequest(stream, readRequest); + ReadableByteStreamControllerCallPullIfNeeded(this); + } + /** @internal */ + [ReleaseSteps]() { + if (this._pendingPullIntos.length > 0) { + const firstPullInto = this._pendingPullIntos.peek(); + firstPullInto.readerType = 'none'; + this._pendingPullIntos = new SimpleQueue(); + this._pendingPullIntos.push(firstPullInto); + } + } + } + Object.defineProperties(ReadableByteStreamController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + byobRequest: { enumerable: true }, + desiredSize: { enumerable: true } + }); + setFunctionName(ReadableByteStreamController.prototype.close, 'close'); + setFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue'); + setFunctionName(ReadableByteStreamController.prototype.error, 'error'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, { + value: 'ReadableByteStreamController', + configurable: true + }); + } + // Abstract operations for the ReadableByteStreamController. + function IsReadableByteStreamController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) { + return false; + } + return x instanceof ReadableByteStreamController; + } + function IsReadableStreamBYOBRequest(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) { + return false; + } + return x instanceof ReadableStreamBYOBRequest; + } + function ReadableByteStreamControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableByteStreamControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + // TODO: Test controller argument + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + return null; + }, e => { + ReadableByteStreamControllerError(controller, e); + return null; + }); + } + function ReadableByteStreamControllerClearPendingPullIntos(controller) { + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + controller._pendingPullIntos = new SimpleQueue(); + } + function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { + let done = false; + if (stream._state === 'closed') { + done = true; + } + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'default') { + ReadableStreamFulfillReadRequest(stream, filledView, done); + } + else { + ReadableStreamFulfillReadIntoRequest(stream, filledView, done); + } + } + function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { + const bytesFilled = pullIntoDescriptor.bytesFilled; + const elementSize = pullIntoDescriptor.elementSize; + return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); + } + function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { + controller._queue.push({ buffer, byteOffset, byteLength }); + controller._queueTotalSize += byteLength; + } + function ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, buffer, byteOffset, byteLength) { + let clonedChunk; + try { + clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength); + } + catch (cloneE) { + ReadableByteStreamControllerError(controller, cloneE); + throw cloneE; + } + ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength); + } + function ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstDescriptor) { + if (firstDescriptor.bytesFilled > 0) { + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, firstDescriptor.buffer, firstDescriptor.byteOffset, firstDescriptor.bytesFilled); + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { + const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); + const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; + let totalBytesToCopyRemaining = maxBytesToCopy; + let ready = false; + const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize; + const maxAlignedBytes = maxBytesFilled - remainderBytes; + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) { + totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; + ready = true; + } + const queue = controller._queue; + while (totalBytesToCopyRemaining > 0) { + const headOfQueue = queue.peek(); + const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); + const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); + if (headOfQueue.byteLength === bytesToCopy) { + queue.shift(); + } + else { + headOfQueue.byteOffset += bytesToCopy; + headOfQueue.byteLength -= bytesToCopy; + } + controller._queueTotalSize -= bytesToCopy; + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); + totalBytesToCopyRemaining -= bytesToCopy; + } + return ready; + } + function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { + pullIntoDescriptor.bytesFilled += size; + } + function ReadableByteStreamControllerHandleQueueDrain(controller) { + if (controller._queueTotalSize === 0 && controller._closeRequested) { + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(controller._controlledReadableByteStream); + } + else { + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + } + function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { + if (controller._byobRequest === null) { + return; + } + controller._byobRequest._associatedReadableByteStreamController = undefined; + controller._byobRequest._view = null; + controller._byobRequest = null; + } + function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { + while (controller._pendingPullIntos.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const pullIntoDescriptor = controller._pendingPullIntos.peek(); + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller) { + const reader = controller._controlledReadableByteStream._reader; + while (reader._readRequests.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const readRequest = reader._readRequests.shift(); + ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest); + } + } + function ReadableByteStreamControllerPullInto(controller, view, min, readIntoRequest) { + const stream = controller._controlledReadableByteStream; + const ctor = view.constructor; + const elementSize = arrayBufferViewElementSize(ctor); + const { byteOffset, byteLength } = view; + const minimumFill = min * elementSize; + let buffer; + try { + buffer = TransferArrayBuffer(view.buffer); + } + catch (e) { + readIntoRequest._errorSteps(e); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: buffer.byteLength, + byteOffset, + byteLength, + bytesFilled: 0, + minimumFill, + elementSize, + viewConstructor: ctor, + readerType: 'byob' + }; + if (controller._pendingPullIntos.length > 0) { + controller._pendingPullIntos.push(pullIntoDescriptor); + // No ReadableByteStreamControllerCallPullIfNeeded() call since: + // - No change happens on desiredSize + // - The source has already been notified of that there's at least 1 pending read(view) + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + return; + } + if (stream._state === 'closed') { + const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); + readIntoRequest._closeSteps(emptyView); + return; + } + if (controller._queueTotalSize > 0) { + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + ReadableByteStreamControllerHandleQueueDrain(controller); + readIntoRequest._chunkSteps(filledView); + return; + } + if (controller._closeRequested) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + readIntoRequest._errorSteps(e); + return; + } + } + controller._pendingPullIntos.push(pullIntoDescriptor); + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { + if (firstDescriptor.readerType === 'none') { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const stream = controller._controlledReadableByteStream; + if (ReadableStreamHasBYOBReader(stream)) { + while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { + const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + return; + } + if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) { + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + return; + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; + if (remainderSize > 0) { + const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor.buffer, end - remainderSize, remainderSize); + } + pullIntoDescriptor.bytesFilled -= remainderSize; + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor); + } + else { + ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerShiftPendingPullInto(controller) { + const descriptor = controller._pendingPullIntos.shift(); + return descriptor; + } + function ReadableByteStreamControllerShouldCallPull(controller) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return false; + } + if (controller._closeRequested) { + return false; + } + if (!controller._started) { + return false; + } + if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; + } + function ReadableByteStreamControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + } + // A client of ReadableByteStreamController may use these functions directly to bypass state check. + function ReadableByteStreamControllerClose(controller) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + if (controller._queueTotalSize > 0) { + controller._closeRequested = true; + return; + } + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + throw e; + } + } + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } + function ReadableByteStreamControllerEnqueue(controller, chunk) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + const { buffer, byteOffset, byteLength } = chunk; + if (IsDetachedBuffer(buffer)) { + throw new TypeError('chunk\'s buffer is detached and so cannot be enqueued'); + } + const transferredBuffer = TransferArrayBuffer(buffer); + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (IsDetachedBuffer(firstPendingPullInto.buffer)) { + throw new TypeError('The BYOB request\'s buffer has been detached and so cannot be filled with an enqueued chunk'); + } + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer); + if (firstPendingPullInto.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto); + } + } + if (ReadableStreamHasDefaultReader(stream)) { + ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller); + if (ReadableStreamGetNumReadRequests(stream) === 0) { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + else { + if (controller._pendingPullIntos.length > 0) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); + ReadableStreamFulfillReadRequest(stream, transferredView, false); + } + } + else if (ReadableStreamHasBYOBReader(stream)) { + // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully. + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + else { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerError(controller, e) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return; + } + ReadableByteStreamControllerClearPendingPullIntos(controller); + ResetQueue(controller); + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); + } + function ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest) { + const entry = controller._queue.shift(); + controller._queueTotalSize -= entry.byteLength; + ReadableByteStreamControllerHandleQueueDrain(controller); + const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); + readRequest._chunkSteps(view); + } + function ReadableByteStreamControllerGetBYOBRequest(controller) { + if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); + const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); + SetUpReadableStreamBYOBRequest(byobRequest, controller, view); + controller._byobRequest = byobRequest; + } + return controller._byobRequest; + } + function ReadableByteStreamControllerGetDesiredSize(controller) { + const state = controller._controlledReadableByteStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; + } + function ReadableByteStreamControllerRespond(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (bytesWritten !== 0) { + throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream'); + } + } + else { + if (bytesWritten === 0) { + throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream'); + } + if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) { + throw new RangeError('bytesWritten out of range'); + } + } + firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); + ReadableByteStreamControllerRespondInternal(controller, bytesWritten); + } + function ReadableByteStreamControllerRespondWithNewView(controller, view) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (view.byteLength !== 0) { + throw new TypeError('The view\'s length must be 0 when calling respondWithNewView() on a closed stream'); + } + } + else { + if (view.byteLength === 0) { + throw new TypeError('The view\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'); + } + } + if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { + throw new RangeError('The region specified by view does not match byobRequest'); + } + if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) { + throw new RangeError('The buffer of view has different capacity than byobRequest'); + } + if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) { + throw new RangeError('The region specified by view is larger than byobRequest'); + } + const viewByteLength = view.byteLength; + firstDescriptor.buffer = TransferArrayBuffer(view.buffer); + ReadableByteStreamControllerRespondInternal(controller, viewByteLength); + } + function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { + controller._controlledReadableByteStream = stream; + controller._pullAgain = false; + controller._pulling = false; + controller._byobRequest = null; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._closeRequested = false; + controller._started = false; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._autoAllocateChunkSize = autoAllocateChunkSize; + controller._pendingPullIntos = new SimpleQueue(); + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableByteStreamControllerCallPullIfNeeded(controller); + return null; + }, r => { + ReadableByteStreamControllerError(controller, r); + return null; + }); + } + function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { + const controller = Object.create(ReadableByteStreamController.prototype); + let startAlgorithm; + let pullAlgorithm; + let cancelAlgorithm; + if (underlyingByteSource.start !== undefined) { + startAlgorithm = () => underlyingByteSource.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingByteSource.pull !== undefined) { + pullAlgorithm = () => underlyingByteSource.pull(controller); + } + else { + pullAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingByteSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingByteSource.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; + if (autoAllocateChunkSize === 0) { + throw new TypeError('autoAllocateChunkSize must be greater than 0'); + } + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); + } + function SetUpReadableStreamBYOBRequest(request, controller, view) { + request._associatedReadableByteStreamController = controller; + request._view = view; + } + // Helper functions for the ReadableStreamBYOBRequest. + function byobRequestBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`); + } + // Helper functions for the ReadableByteStreamController. + function byteStreamControllerBrandCheckException(name) { + return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`); + } + + function convertReaderOptions(options, context) { + assertDictionary(options, context); + const mode = options === null || options === void 0 ? void 0 : options.mode; + return { + mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`) + }; + } + function convertReadableStreamReaderMode(mode, context) { + mode = `${mode}`; + if (mode !== 'byob') { + throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`); + } + return mode; + } + function convertByobReadOptions(options, context) { + var _a; + assertDictionary(options, context); + const min = (_a = options === null || options === void 0 ? void 0 : options.min) !== null && _a !== void 0 ? _a : 1; + return { + min: convertUnsignedLongLongWithEnforceRange(min, `${context} has member 'min' that`) + }; + } + + // Abstract operations for the ReadableStream. + function AcquireReadableStreamBYOBReader(stream) { + return new ReadableStreamBYOBReader(stream); + } + // ReadableStream API exposed for controllers. + function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { + stream._reader._readIntoRequests.push(readIntoRequest); + } + function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { + const reader = stream._reader; + const readIntoRequest = reader._readIntoRequests.shift(); + if (done) { + readIntoRequest._closeSteps(chunk); + } + else { + readIntoRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadIntoRequests(stream) { + return stream._reader._readIntoRequests.length; + } + function ReadableStreamHasBYOBReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamBYOBReader(reader)) { + return false; + } + return true; + } + /** + * A BYOB reader vended by a {@link ReadableStream}. + * + * @public + */ + class ReadableStreamBYOBReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + if (!IsReadableByteStreamController(stream._readableStreamController)) { + throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' + + 'source'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readIntoRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + read(view, rawOptions = {}) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('read')); + } + if (!ArrayBuffer.isView(view)) { + return promiseRejectedWith(new TypeError('view must be an array buffer view')); + } + if (view.byteLength === 0) { + return promiseRejectedWith(new TypeError('view must have non-zero byteLength')); + } + if (view.buffer.byteLength === 0) { + return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`)); + } + if (IsDetachedBuffer(view.buffer)) { + return promiseRejectedWith(new TypeError('view\'s buffer has been detached')); + } + let options; + try { + options = convertByobReadOptions(rawOptions, 'options'); + } + catch (e) { + return promiseRejectedWith(e); + } + const min = options.min; + if (min === 0) { + return promiseRejectedWith(new TypeError('options.min must be greater than 0')); + } + if (!isDataView(view)) { + if (min > view.length) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s length')); + } + } + else if (min > view.byteLength) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s byteLength')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readIntoRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: chunk => resolvePromise({ value: chunk, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamBYOBReader(this)) { + throw byobReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamBYOBReaderRelease(this); + } + } + Object.defineProperties(ReadableStreamBYOBReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + setFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel'); + setFunctionName(ReadableStreamBYOBReader.prototype.read, 'read'); + setFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, { + value: 'ReadableStreamBYOBReader', + configurable: true + }); + } + // Abstract operations for the readers. + function IsReadableStreamBYOBReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) { + return false; + } + return x instanceof ReadableStreamBYOBReader; + } + function ReadableStreamBYOBReaderRead(reader, view, min, readIntoRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'errored') { + readIntoRequest._errorSteps(stream._storedError); + } + else { + ReadableByteStreamControllerPullInto(stream._readableStreamController, view, min, readIntoRequest); + } + } + function ReadableStreamBYOBReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + const e = new TypeError('Reader was released'); + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); + } + function ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e) { + const readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._errorSteps(e); + }); + } + // Helper functions for the ReadableStreamBYOBReader. + function byobReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`); + } + + function ExtractHighWaterMark(strategy, defaultHWM) { + const { highWaterMark } = strategy; + if (highWaterMark === undefined) { + return defaultHWM; + } + if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { + throw new RangeError('Invalid highWaterMark'); + } + return highWaterMark; + } + function ExtractSizeAlgorithm(strategy) { + const { size } = strategy; + if (!size) { + return () => 1; + } + return size; + } + + function convertQueuingStrategy(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + const size = init === null || init === void 0 ? void 0 : init.size; + return { + highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark), + size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`) + }; + } + function convertQueuingStrategySize(fn, context) { + assertFunction(fn, context); + return chunk => convertUnrestrictedDouble(fn(chunk)); + } + + function convertUnderlyingSink(original, context) { + assertDictionary(original, context); + const abort = original === null || original === void 0 ? void 0 : original.abort; + const close = original === null || original === void 0 ? void 0 : original.close; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + const write = original === null || original === void 0 ? void 0 : original.write; + return { + abort: abort === undefined ? + undefined : + convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`), + close: close === undefined ? + undefined : + convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`), + start: start === undefined ? + undefined : + convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`), + write: write === undefined ? + undefined : + convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`), + type + }; + } + function convertUnderlyingSinkAbortCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); + } + function convertUnderlyingSinkCloseCallback(fn, original, context) { + assertFunction(fn, context); + return () => promiseCall(fn, original, []); + } + function convertUnderlyingSinkStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertUnderlyingSinkWriteCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); + } + + function assertWritableStream(x, context) { + if (!IsWritableStream(x)) { + throw new TypeError(`${context} is not a WritableStream.`); + } + } + + function isAbortSignal(value) { + if (typeof value !== 'object' || value === null) { + return false; + } + try { + return typeof value.aborted === 'boolean'; + } + catch (_a) { + // AbortSignal.prototype.aborted throws if its brand check fails + return false; + } + } + const supportsAbortController = typeof AbortController === 'function'; + /** + * Construct a new AbortController, if supported by the platform. + * + * @internal + */ + function createAbortController() { + if (supportsAbortController) { + return new AbortController(); + } + return undefined; + } + + /** + * A writable stream represents a destination for data, into which you can write. + * + * @public + */ + class WritableStream { + constructor(rawUnderlyingSink = {}, rawStrategy = {}) { + if (rawUnderlyingSink === undefined) { + rawUnderlyingSink = null; + } + else { + assertObject(rawUnderlyingSink, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter'); + InitializeWritableStream(this); + const type = underlyingSink.type; + if (type !== undefined) { + throw new RangeError('Invalid type is specified'); + } + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); + } + /** + * Returns whether or not the writable stream is locked to a writer. + */ + get locked() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('locked'); + } + return IsWritableStreamLocked(this); + } + /** + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort + * mechanism of the underlying sink. + * + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel + * the stream) if the stream is currently locked. + */ + abort(reason = undefined) { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('abort')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer')); + } + return WritableStreamAbort(this, reason); + } + /** + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its + * close behavior. During this time any further attempts to write will fail (without erroring the stream). + * + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + */ + close() { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('close')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer')); + } + if (WritableStreamCloseQueuedOrInFlight(this)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamClose(this); + } + /** + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream + * is locked, no other writer can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at + * the same time, which would cause the resulting written data to be unpredictable and probably useless. + */ + getWriter() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('getWriter'); + } + return AcquireWritableStreamDefaultWriter(this); + } + } + Object.defineProperties(WritableStream.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + getWriter: { enumerable: true }, + locked: { enumerable: true } + }); + setFunctionName(WritableStream.prototype.abort, 'abort'); + setFunctionName(WritableStream.prototype.close, 'close'); + setFunctionName(WritableStream.prototype.getWriter, 'getWriter'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, { + value: 'WritableStream', + configurable: true + }); + } + // Abstract operations for the WritableStream. + function AcquireWritableStreamDefaultWriter(stream) { + return new WritableStreamDefaultWriter(stream); + } + // Throws if and only if startAlgorithm throws. + function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(WritableStream.prototype); + InitializeWritableStream(stream); + const controller = Object.create(WritableStreamDefaultController.prototype); + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + return stream; + } + function InitializeWritableStream(stream) { + stream._state = 'writable'; + // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is + // 'erroring' or 'errored'. May be set to an undefined value. + stream._storedError = undefined; + stream._writer = undefined; + // Initialize to undefined first because the constructor of the controller checks this + // variable to validate the caller. + stream._writableStreamController = undefined; + // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data + // producer without waiting for the queued writes to finish. + stream._writeRequests = new SimpleQueue(); + // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents + // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here. + stream._inFlightWriteRequest = undefined; + // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer + // has been detached. + stream._closeRequest = undefined; + // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it + // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here. + stream._inFlightCloseRequest = undefined; + // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached. + stream._pendingAbortRequest = undefined; + // The backpressure signal set by the controller. + stream._backpressure = false; + } + function IsWritableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) { + return false; + } + return x instanceof WritableStream; + } + function IsWritableStreamLocked(stream) { + if (stream._writer === undefined) { + return false; + } + return true; + } + function WritableStreamAbort(stream, reason) { + var _a; + if (stream._state === 'closed' || stream._state === 'errored') { + return promiseResolvedWith(undefined); + } + stream._writableStreamController._abortReason = reason; + (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort(reason); + // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring', + // but it doesn't know that signaling abort runs author code that might have changed the state. + // Widen the type again by casting to WritableStreamState. + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseResolvedWith(undefined); + } + if (stream._pendingAbortRequest !== undefined) { + return stream._pendingAbortRequest._promise; + } + let wasAlreadyErroring = false; + if (state === 'erroring') { + wasAlreadyErroring = true; + // reason will not be used, so don't keep a reference to it. + reason = undefined; + } + const promise = newPromise((resolve, reject) => { + stream._pendingAbortRequest = { + _promise: undefined, + _resolve: resolve, + _reject: reject, + _reason: reason, + _wasAlreadyErroring: wasAlreadyErroring + }; + }); + stream._pendingAbortRequest._promise = promise; + if (!wasAlreadyErroring) { + WritableStreamStartErroring(stream, reason); + } + return promise; + } + function WritableStreamClose(stream) { + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`)); + } + const promise = newPromise((resolve, reject) => { + const closeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._closeRequest = closeRequest; + }); + const writer = stream._writer; + if (writer !== undefined && stream._backpressure && state === 'writable') { + defaultWriterReadyPromiseResolve(writer); + } + WritableStreamDefaultControllerClose(stream._writableStreamController); + return promise; + } + // WritableStream API exposed for controllers. + function WritableStreamAddWriteRequest(stream) { + const promise = newPromise((resolve, reject) => { + const writeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._writeRequests.push(writeRequest); + }); + return promise; + } + function WritableStreamDealWithRejection(stream, error) { + const state = stream._state; + if (state === 'writable') { + WritableStreamStartErroring(stream, error); + return; + } + WritableStreamFinishErroring(stream); + } + function WritableStreamStartErroring(stream, reason) { + const controller = stream._writableStreamController; + stream._state = 'erroring'; + stream._storedError = reason; + const writer = stream._writer; + if (writer !== undefined) { + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); + } + if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { + WritableStreamFinishErroring(stream); + } + } + function WritableStreamFinishErroring(stream) { + stream._state = 'errored'; + stream._writableStreamController[ErrorSteps](); + const storedError = stream._storedError; + stream._writeRequests.forEach(writeRequest => { + writeRequest._reject(storedError); + }); + stream._writeRequests = new SimpleQueue(); + if (stream._pendingAbortRequest === undefined) { + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const abortRequest = stream._pendingAbortRequest; + stream._pendingAbortRequest = undefined; + if (abortRequest._wasAlreadyErroring) { + abortRequest._reject(storedError); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const promise = stream._writableStreamController[AbortSteps](abortRequest._reason); + uponPromise(promise, () => { + abortRequest._resolve(); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }, (reason) => { + abortRequest._reject(reason); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }); + } + function WritableStreamFinishInFlightWrite(stream) { + stream._inFlightWriteRequest._resolve(undefined); + stream._inFlightWriteRequest = undefined; + } + function WritableStreamFinishInFlightWriteWithError(stream, error) { + stream._inFlightWriteRequest._reject(error); + stream._inFlightWriteRequest = undefined; + WritableStreamDealWithRejection(stream, error); + } + function WritableStreamFinishInFlightClose(stream) { + stream._inFlightCloseRequest._resolve(undefined); + stream._inFlightCloseRequest = undefined; + const state = stream._state; + if (state === 'erroring') { + // The error was too late to do anything, so it is ignored. + stream._storedError = undefined; + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._resolve(); + stream._pendingAbortRequest = undefined; + } + } + stream._state = 'closed'; + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseResolve(writer); + } + } + function WritableStreamFinishInFlightCloseWithError(stream, error) { + stream._inFlightCloseRequest._reject(error); + stream._inFlightCloseRequest = undefined; + // Never execute sink abort() after sink close(). + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._reject(error); + stream._pendingAbortRequest = undefined; + } + WritableStreamDealWithRejection(stream, error); + } + // TODO(ricea): Fix alphabetical order. + function WritableStreamCloseQueuedOrInFlight(stream) { + if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; + } + function WritableStreamHasOperationMarkedInFlight(stream) { + if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; + } + function WritableStreamMarkCloseRequestInFlight(stream) { + stream._inFlightCloseRequest = stream._closeRequest; + stream._closeRequest = undefined; + } + function WritableStreamMarkFirstWriteRequestInFlight(stream) { + stream._inFlightWriteRequest = stream._writeRequests.shift(); + } + function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { + if (stream._closeRequest !== undefined) { + stream._closeRequest._reject(stream._storedError); + stream._closeRequest = undefined; + } + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseReject(writer, stream._storedError); + } + } + function WritableStreamUpdateBackpressure(stream, backpressure) { + const writer = stream._writer; + if (writer !== undefined && backpressure !== stream._backpressure) { + if (backpressure) { + defaultWriterReadyPromiseReset(writer); + } + else { + defaultWriterReadyPromiseResolve(writer); + } + } + stream._backpressure = backpressure; + } + /** + * A default writer vended by a {@link WritableStream}. + * + * @public + */ + class WritableStreamDefaultWriter { + constructor(stream) { + assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter'); + assertWritableStream(stream, 'First parameter'); + if (IsWritableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive writing by another writer'); + } + this._ownerWritableStream = stream; + stream._writer = this; + const state = stream._state; + if (state === 'writable') { + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { + defaultWriterReadyPromiseInitialize(this); + } + else { + defaultWriterReadyPromiseInitializeAsResolved(this); + } + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'erroring') { + defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'closed') { + defaultWriterReadyPromiseInitializeAsResolved(this); + defaultWriterClosedPromiseInitializeAsResolved(this); + } + else { + const storedError = stream._storedError; + defaultWriterReadyPromiseInitializeAsRejected(this, storedError); + defaultWriterClosedPromiseInitializeAsRejected(this, storedError); + } + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the writer’s lock is released before the stream finishes closing. + */ + get closed() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. + * A producer can use this information to determine the right amount of data to write. + * + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when + * the writer’s lock is released. + */ + get desiredSize() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('desiredSize'); + } + if (this._ownerWritableStream === undefined) { + throw defaultWriterLockException('desiredSize'); + } + return WritableStreamDefaultWriterGetDesiredSize(this); + } + /** + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips + * back to zero or below, the getter will return a new promise that stays pending until the next transition. + * + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become + * rejected. + */ + get ready() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('ready')); + } + return this._readyPromise; + } + /** + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + */ + abort(reason = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('abort')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('abort')); + } + return WritableStreamDefaultWriterAbort(this, reason); + } + /** + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + */ + close() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('close')); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return promiseRejectedWith(defaultWriterLockException('close')); + } + if (WritableStreamCloseQueuedOrInFlight(stream)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamDefaultWriterClose(this); + } + /** + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from + * now on; otherwise, the writer will appear closed. + * + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents + * other producers from writing in an interleaved manner. + */ + releaseLock() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('releaseLock'); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return; + } + WritableStreamDefaultWriterRelease(this); + } + write(chunk = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('write')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + return WritableStreamDefaultWriterWrite(this, chunk); + } + } + Object.defineProperties(WritableStreamDefaultWriter.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + releaseLock: { enumerable: true }, + write: { enumerable: true }, + closed: { enumerable: true }, + desiredSize: { enumerable: true }, + ready: { enumerable: true } + }); + setFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort'); + setFunctionName(WritableStreamDefaultWriter.prototype.close, 'close'); + setFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock'); + setFunctionName(WritableStreamDefaultWriter.prototype.write, 'write'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, { + value: 'WritableStreamDefaultWriter', + configurable: true + }); + } + // Abstract operations for the WritableStreamDefaultWriter. + function IsWritableStreamDefaultWriter(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultWriter; + } + // A client of WritableStreamDefaultWriter may use these functions directly to bypass state check. + function WritableStreamDefaultWriterAbort(writer, reason) { + const stream = writer._ownerWritableStream; + return WritableStreamAbort(stream, reason); + } + function WritableStreamDefaultWriterClose(writer) { + const stream = writer._ownerWritableStream; + return WritableStreamClose(stream); + } + function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseResolvedWith(undefined); + } + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + return WritableStreamDefaultWriterClose(writer); + } + function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { + if (writer._closedPromiseState === 'pending') { + defaultWriterClosedPromiseReject(writer, error); + } + else { + defaultWriterClosedPromiseResetToRejected(writer, error); + } + } + function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { + if (writer._readyPromiseState === 'pending') { + defaultWriterReadyPromiseReject(writer, error); + } + else { + defaultWriterReadyPromiseResetToRejected(writer, error); + } + } + function WritableStreamDefaultWriterGetDesiredSize(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (state === 'errored' || state === 'erroring') { + return null; + } + if (state === 'closed') { + return 0; + } + return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); + } + function WritableStreamDefaultWriterRelease(writer) { + const stream = writer._ownerWritableStream; + const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`); + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); + // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not + // rejected until afterwards. This means that simply testing state will not work. + WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); + stream._writer = undefined; + writer._ownerWritableStream = undefined; + } + function WritableStreamDefaultWriterWrite(writer, chunk) { + const stream = writer._ownerWritableStream; + const controller = stream._writableStreamController; + const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); + if (stream !== writer._ownerWritableStream) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + const state = stream._state; + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to')); + } + if (state === 'erroring') { + return promiseRejectedWith(stream._storedError); + } + const promise = WritableStreamAddWriteRequest(stream); + WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); + return promise; + } + const closeSentinel = {}; + /** + * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. + * + * @public + */ + class WritableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. + * + * @deprecated + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. + */ + get abortReason() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('abortReason'); + } + return this._abortReason; + } + /** + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. + */ + get signal() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('signal'); + } + if (this._abortController === undefined) { + // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`. + // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill, + // so instead we only implement support for `signal` if we find a global `AbortController` constructor. + throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported'); + } + return this._abortController.signal; + } + /** + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. + * + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the + * normal lifecycle of interactions with the underlying sink. + */ + error(e = undefined) { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('error'); + } + const state = this._controlledWritableStream._state; + if (state !== 'writable') { + // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so + // just treat it as a no-op. + return; + } + WritableStreamDefaultControllerError(this, e); + } + /** @internal */ + [AbortSteps](reason) { + const result = this._abortAlgorithm(reason); + WritableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [ErrorSteps]() { + ResetQueue(this); + } + } + Object.defineProperties(WritableStreamDefaultController.prototype, { + abortReason: { enumerable: true }, + signal: { enumerable: true }, + error: { enumerable: true } + }); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, { + value: 'WritableStreamDefaultController', + configurable: true + }); + } + // Abstract operations implementing interface required by the WritableStream. + function IsWritableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultController; + } + function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledWritableStream = stream; + stream._writableStreamController = controller; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._abortReason = undefined; + controller._abortController = createAbortController(); + controller._started = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._writeAlgorithm = writeAlgorithm; + controller._closeAlgorithm = closeAlgorithm; + controller._abortAlgorithm = abortAlgorithm; + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + const startResult = startAlgorithm(); + const startPromise = promiseResolvedWith(startResult); + uponPromise(startPromise, () => { + controller._started = true; + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, r => { + controller._started = true; + WritableStreamDealWithRejection(stream, r); + return null; + }); + } + function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { + const controller = Object.create(WritableStreamDefaultController.prototype); + let startAlgorithm; + let writeAlgorithm; + let closeAlgorithm; + let abortAlgorithm; + if (underlyingSink.start !== undefined) { + startAlgorithm = () => underlyingSink.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingSink.write !== undefined) { + writeAlgorithm = chunk => underlyingSink.write(chunk, controller); + } + else { + writeAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSink.close !== undefined) { + closeAlgorithm = () => underlyingSink.close(); + } + else { + closeAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSink.abort !== undefined) { + abortAlgorithm = reason => underlyingSink.abort(reason); + } + else { + abortAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + } + // ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls. + function WritableStreamDefaultControllerClearAlgorithms(controller) { + controller._writeAlgorithm = undefined; + controller._closeAlgorithm = undefined; + controller._abortAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; + } + function WritableStreamDefaultControllerClose(controller) { + EnqueueValueWithSize(controller, closeSentinel, 0); + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + } + function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { + try { + return controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); + return 1; + } + } + function WritableStreamDefaultControllerGetDesiredSize(controller) { + return controller._strategyHWM - controller._queueTotalSize; + } + function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); + return; + } + const stream = controller._controlledWritableStream; + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + } + // Abstract operations for the WritableStreamDefaultController. + function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { + const stream = controller._controlledWritableStream; + if (!controller._started) { + return; + } + if (stream._inFlightWriteRequest !== undefined) { + return; + } + const state = stream._state; + if (state === 'erroring') { + WritableStreamFinishErroring(stream); + return; + } + if (controller._queue.length === 0) { + return; + } + const value = PeekQueueValue(controller); + if (value === closeSentinel) { + WritableStreamDefaultControllerProcessClose(controller); + } + else { + WritableStreamDefaultControllerProcessWrite(controller, value); + } + } + function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { + if (controller._controlledWritableStream._state === 'writable') { + WritableStreamDefaultControllerError(controller, error); + } + } + function WritableStreamDefaultControllerProcessClose(controller) { + const stream = controller._controlledWritableStream; + WritableStreamMarkCloseRequestInFlight(stream); + DequeueValue(controller); + const sinkClosePromise = controller._closeAlgorithm(); + WritableStreamDefaultControllerClearAlgorithms(controller); + uponPromise(sinkClosePromise, () => { + WritableStreamFinishInFlightClose(stream); + return null; + }, reason => { + WritableStreamFinishInFlightCloseWithError(stream, reason); + return null; + }); + } + function WritableStreamDefaultControllerProcessWrite(controller, chunk) { + const stream = controller._controlledWritableStream; + WritableStreamMarkFirstWriteRequestInFlight(stream); + const sinkWritePromise = controller._writeAlgorithm(chunk); + uponPromise(sinkWritePromise, () => { + WritableStreamFinishInFlightWrite(stream); + const state = stream._state; + DequeueValue(controller); + if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, reason => { + if (stream._state === 'writable') { + WritableStreamDefaultControllerClearAlgorithms(controller); + } + WritableStreamFinishInFlightWriteWithError(stream, reason); + return null; + }); + } + function WritableStreamDefaultControllerGetBackpressure(controller) { + const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); + return desiredSize <= 0; + } + // A client of WritableStreamDefaultController may use these functions directly to bypass state check. + function WritableStreamDefaultControllerError(controller, error) { + const stream = controller._controlledWritableStream; + WritableStreamDefaultControllerClearAlgorithms(controller); + WritableStreamStartErroring(stream, error); + } + // Helper functions for the WritableStream. + function streamBrandCheckException$2(name) { + return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`); + } + // Helper functions for the WritableStreamDefaultController. + function defaultControllerBrandCheckException$2(name) { + return new TypeError(`WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`); + } + // Helper functions for the WritableStreamDefaultWriter. + function defaultWriterBrandCheckException(name) { + return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`); + } + function defaultWriterLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released writer'); + } + function defaultWriterClosedPromiseInitialize(writer) { + writer._closedPromise = newPromise((resolve, reject) => { + writer._closedPromise_resolve = resolve; + writer._closedPromise_reject = reject; + writer._closedPromiseState = 'pending'; + }); + } + function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseReject(writer, reason); + } + function defaultWriterClosedPromiseInitializeAsResolved(writer) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseResolve(writer); + } + function defaultWriterClosedPromiseReject(writer, reason) { + if (writer._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._closedPromise); + writer._closedPromise_reject(reason); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'rejected'; + } + function defaultWriterClosedPromiseResetToRejected(writer, reason) { + defaultWriterClosedPromiseInitializeAsRejected(writer, reason); + } + function defaultWriterClosedPromiseResolve(writer) { + if (writer._closedPromise_resolve === undefined) { + return; + } + writer._closedPromise_resolve(undefined); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'resolved'; + } + function defaultWriterReadyPromiseInitialize(writer) { + writer._readyPromise = newPromise((resolve, reject) => { + writer._readyPromise_resolve = resolve; + writer._readyPromise_reject = reject; + }); + writer._readyPromiseState = 'pending'; + } + function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseReject(writer, reason); + } + function defaultWriterReadyPromiseInitializeAsResolved(writer) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseResolve(writer); + } + function defaultWriterReadyPromiseReject(writer, reason) { + if (writer._readyPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._readyPromise); + writer._readyPromise_reject(reason); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'rejected'; + } + function defaultWriterReadyPromiseReset(writer) { + defaultWriterReadyPromiseInitialize(writer); + } + function defaultWriterReadyPromiseResetToRejected(writer, reason) { + defaultWriterReadyPromiseInitializeAsRejected(writer, reason); + } + function defaultWriterReadyPromiseResolve(writer) { + if (writer._readyPromise_resolve === undefined) { + return; + } + writer._readyPromise_resolve(undefined); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'fulfilled'; + } + + /// + function getGlobals() { + if (typeof globalThis !== 'undefined') { + return globalThis; + } + else if (typeof self !== 'undefined') { + return self; + } + else if (typeof global !== 'undefined') { + return global; + } + return undefined; + } + const globals = getGlobals(); + + /// + function isDOMExceptionConstructor(ctor) { + if (!(typeof ctor === 'function' || typeof ctor === 'object')) { + return false; + } + if (ctor.name !== 'DOMException') { + return false; + } + try { + new ctor(); + return true; + } + catch (_a) { + return false; + } + } + /** + * Support: + * - Web browsers + * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87) + */ + function getFromGlobal() { + const ctor = globals === null || globals === void 0 ? void 0 : globals.DOMException; + return isDOMExceptionConstructor(ctor) ? ctor : undefined; + } + /** + * Support: + * - All platforms + */ + function createPolyfill() { + // eslint-disable-next-line @typescript-eslint/no-shadow + const ctor = function DOMException(message, name) { + this.message = message || ''; + this.name = name || 'Error'; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + }; + setFunctionName(ctor, 'DOMException'); + ctor.prototype = Object.create(Error.prototype); + Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true }); + return ctor; + } + // eslint-disable-next-line @typescript-eslint/no-redeclare + const DOMException = getFromGlobal() || createPolyfill(); + + function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { + const reader = AcquireReadableStreamDefaultReader(source); + const writer = AcquireWritableStreamDefaultWriter(dest); + source._disturbed = true; + let shuttingDown = false; + // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown. + let currentWrite = promiseResolvedWith(undefined); + return newPromise((resolve, reject) => { + let abortAlgorithm; + if (signal !== undefined) { + abortAlgorithm = () => { + const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError'); + const actions = []; + if (!preventAbort) { + actions.push(() => { + if (dest._state === 'writable') { + return WritableStreamAbort(dest, error); + } + return promiseResolvedWith(undefined); + }); + } + if (!preventCancel) { + actions.push(() => { + if (source._state === 'readable') { + return ReadableStreamCancel(source, error); + } + return promiseResolvedWith(undefined); + }); + } + shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error); + }; + if (signal.aborted) { + abortAlgorithm(); + return; + } + signal.addEventListener('abort', abortAlgorithm); + } + // Using reader and writer, read all chunks from this and write them to dest + // - Backpressure must be enforced + // - Shutdown must stop all activity + function pipeLoop() { + return newPromise((resolveLoop, rejectLoop) => { + function next(done) { + if (done) { + resolveLoop(); + } + else { + // Use `PerformPromiseThen` instead of `uponPromise` to avoid + // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers + PerformPromiseThen(pipeStep(), next, rejectLoop); + } + } + next(false); + }); + } + function pipeStep() { + if (shuttingDown) { + return promiseResolvedWith(true); + } + return PerformPromiseThen(writer._readyPromise, () => { + return newPromise((resolveRead, rejectRead) => { + ReadableStreamDefaultReaderRead(reader, { + _chunkSteps: chunk => { + currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop); + resolveRead(false); + }, + _closeSteps: () => resolveRead(true), + _errorSteps: rejectRead + }); + }); + }); + } + // Errors must be propagated forward + isOrBecomesErrored(source, reader._closedPromise, storedError => { + if (!preventAbort) { + shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Errors must be propagated backward + isOrBecomesErrored(dest, writer._closedPromise, storedError => { + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Closing must be propagated forward + isOrBecomesClosed(source, reader._closedPromise, () => { + if (!preventClose) { + shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer)); + } + else { + shutdown(); + } + return null; + }); + // Closing must be propagated backward + if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') { + const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it'); + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed); + } + else { + shutdown(true, destClosed); + } + } + setPromiseIsHandledToTrue(pipeLoop()); + function waitForWritesToFinish() { + // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait + // for that too. + const oldCurrentWrite = currentWrite; + return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined); + } + function isOrBecomesErrored(stream, promise, action) { + if (stream._state === 'errored') { + action(stream._storedError); + } + else { + uponRejection(promise, action); + } + } + function isOrBecomesClosed(stream, promise, action) { + if (stream._state === 'closed') { + action(); + } + else { + uponFulfillment(promise, action); + } + } + function shutdownWithAction(action, originalIsError, originalError) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), doTheRest); + } + else { + doTheRest(); + } + function doTheRest() { + uponPromise(action(), () => finalize(originalIsError, originalError), newError => finalize(true, newError)); + return null; + } + } + function shutdown(isError, error) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error)); + } + else { + finalize(isError, error); + } + } + function finalize(isError, error) { + WritableStreamDefaultWriterRelease(writer); + ReadableStreamReaderGenericRelease(reader); + if (signal !== undefined) { + signal.removeEventListener('abort', abortAlgorithm); + } + if (isError) { + reject(error); + } + else { + resolve(undefined); + } + return null; + } + }); + } + + /** + * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. + * + * @public + */ + class ReadableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('desiredSize'); + } + return ReadableStreamDefaultControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('close'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits close'); + } + ReadableStreamDefaultControllerClose(this); + } + enqueue(chunk = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('enqueue'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits enqueue'); + } + return ReadableStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('error'); + } + ReadableStreamDefaultControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableStream; + if (this._queue.length > 0) { + const chunk = DequeueValue(this); + if (this._closeRequested && this._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(this); + ReadableStreamClose(stream); + } + else { + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + readRequest._chunkSteps(chunk); + } + else { + ReadableStreamAddReadRequest(stream, readRequest); + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + } + /** @internal */ + [ReleaseSteps]() { + // Do nothing. + } + } + Object.defineProperties(ReadableStreamDefaultController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + desiredSize: { enumerable: true } + }); + setFunctionName(ReadableStreamDefaultController.prototype.close, 'close'); + setFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue'); + setFunctionName(ReadableStreamDefaultController.prototype.error, 'error'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, { + value: 'ReadableStreamDefaultController', + configurable: true + }); + } + // Abstract operations for the ReadableStreamDefaultController. + function IsReadableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) { + return false; + } + return x instanceof ReadableStreamDefaultController; + } + function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + return null; + }, e => { + ReadableStreamDefaultControllerError(controller, e); + return null; + }); + } + function ReadableStreamDefaultControllerShouldCallPull(controller) { + const stream = controller._controlledReadableStream; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return false; + } + if (!controller._started) { + return false; + } + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; + } + function ReadableStreamDefaultControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; + } + // A client of ReadableStreamDefaultController may use these functions directly to bypass state check. + function ReadableStreamDefaultControllerClose(controller) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + controller._closeRequested = true; + if (controller._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } + } + function ReadableStreamDefaultControllerEnqueue(controller, chunk) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + ReadableStreamFulfillReadRequest(stream, chunk, false); + } + else { + let chunkSize; + try { + chunkSize = controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + ReadableStreamDefaultControllerError(controller, chunkSizeE); + throw chunkSizeE; + } + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + ReadableStreamDefaultControllerError(controller, enqueueE); + throw enqueueE; + } + } + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + function ReadableStreamDefaultControllerError(controller, e) { + const stream = controller._controlledReadableStream; + if (stream._state !== 'readable') { + return; + } + ResetQueue(controller); + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); + } + function ReadableStreamDefaultControllerGetDesiredSize(controller) { + const state = controller._controlledReadableStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; + } + // This is used in the implementation of TransformStream. + function ReadableStreamDefaultControllerHasBackpressure(controller) { + if (ReadableStreamDefaultControllerShouldCallPull(controller)) { + return false; + } + return true; + } + function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { + const state = controller._controlledReadableStream._state; + if (!controller._closeRequested && state === 'readable') { + return true; + } + return false; + } + function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledReadableStream = stream; + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._started = false; + controller._closeRequested = false; + controller._pullAgain = false; + controller._pulling = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + return null; + }, r => { + ReadableStreamDefaultControllerError(controller, r); + return null; + }); + } + function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { + const controller = Object.create(ReadableStreamDefaultController.prototype); + let startAlgorithm; + let pullAlgorithm; + let cancelAlgorithm; + if (underlyingSource.start !== undefined) { + startAlgorithm = () => underlyingSource.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingSource.pull !== undefined) { + pullAlgorithm = () => underlyingSource.pull(controller); + } + else { + pullAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingSource.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + } + // Helper functions for the ReadableStreamDefaultController. + function defaultControllerBrandCheckException$1(name) { + return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`); + } + + function ReadableStreamTee(stream, cloneForBranch2) { + if (IsReadableByteStreamController(stream._readableStreamController)) { + return ReadableByteStreamTee(stream); + } + return ReadableStreamDefaultTee(stream); + } + function ReadableStreamDefaultTee(stream, cloneForBranch2) { + const reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgain = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function pullAlgorithm() { + if (reading) { + readAgain = true; + return promiseResolvedWith(undefined); + } + reading = true; + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgain = false; + const chunk1 = chunk; + const chunk2 = chunk; + // There is no way to access the cloning code right now in the reference implementation. + // If we add one then we'll need an implementation for serializable objects. + // if (!canceled2 && cloneForBranch2) { + // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2)); + // } + if (!canceled1) { + ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgain) { + pullAlgorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableStreamDefaultControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableStreamDefaultControllerClose(branch2._readableStreamController); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + // do nothing + } + branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); + branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); + uponRejection(reader._closedPromise, (r) => { + ReadableStreamDefaultControllerError(branch1._readableStreamController, r); + ReadableStreamDefaultControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + return [branch1, branch2]; + } + function ReadableByteStreamTee(stream) { + let reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgainForBranch1 = false; + let readAgainForBranch2 = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function forwardReaderError(thisReader) { + uponRejection(thisReader._closedPromise, r => { + if (thisReader !== reader) { + return null; + } + ReadableByteStreamControllerError(branch1._readableStreamController, r); + ReadableByteStreamControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + } + function pullWithDefaultReader() { + if (IsReadableStreamBYOBReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamDefaultReader(stream); + forwardReaderError(reader); + } + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const chunk1 = chunk; + let chunk2 = chunk; + if (!canceled1 && !canceled2) { + try { + chunk2 = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(branch1._readableStreamController, cloneE); + ReadableByteStreamControllerError(branch2._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + } + if (!canceled1) { + ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableByteStreamControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableByteStreamControllerClose(branch2._readableStreamController); + } + if (branch1._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch1._readableStreamController, 0); + } + if (branch2._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch2._readableStreamController, 0); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + } + function pullWithBYOBReader(view, forBranch2) { + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamBYOBReader(stream); + forwardReaderError(reader); + } + const byobBranch = forBranch2 ? branch2 : branch1; + const otherBranch = forBranch2 ? branch1 : branch2; + const readIntoRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!otherCanceled) { + let clonedChunk; + try { + clonedChunk = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE); + ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk); + } + else if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: chunk => { + reading = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!byobCanceled) { + ReadableByteStreamControllerClose(byobBranch._readableStreamController); + } + if (!otherCanceled) { + ReadableByteStreamControllerClose(otherBranch._readableStreamController); + } + if (chunk !== undefined) { + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0); + } + } + if (!byobCanceled || !otherCanceled) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest); + } + function pull1Algorithm() { + if (reading) { + readAgainForBranch1 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, false); + } + return promiseResolvedWith(undefined); + } + function pull2Algorithm() { + if (reading) { + readAgainForBranch2 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, true); + } + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + return; + } + branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm); + branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm); + forwardReaderError(reader); + return [branch1, branch2]; + } + + function isReadableStreamLike(stream) { + return typeIsObject(stream) && typeof stream.getReader !== 'undefined'; + } + + function ReadableStreamFrom(source) { + if (isReadableStreamLike(source)) { + return ReadableStreamFromDefaultReader(source.getReader()); + } + return ReadableStreamFromIterable(source); + } + function ReadableStreamFromIterable(asyncIterable) { + let stream; + const iteratorRecord = GetIterator(asyncIterable, 'async'); + const startAlgorithm = noop; + function pullAlgorithm() { + let nextResult; + try { + nextResult = IteratorNext(iteratorRecord); + } + catch (e) { + return promiseRejectedWith(e); + } + const nextPromise = promiseResolvedWith(nextResult); + return transformPromiseWith(nextPromise, iterResult => { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object'); + } + const done = IteratorComplete(iterResult); + if (done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + const value = IteratorValue(iterResult); + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + const iterator = iteratorRecord.iterator; + let returnMethod; + try { + returnMethod = GetMethod(iterator, 'return'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (returnMethod === undefined) { + return promiseResolvedWith(undefined); + } + let returnResult; + try { + returnResult = reflectCall(returnMethod, iterator, [reason]); + } + catch (e) { + return promiseRejectedWith(e); + } + const returnPromise = promiseResolvedWith(returnResult); + return transformPromiseWith(returnPromise, iterResult => { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object'); + } + return undefined; + }); + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; + } + function ReadableStreamFromDefaultReader(reader) { + let stream; + const startAlgorithm = noop; + function pullAlgorithm() { + let readPromise; + try { + readPromise = reader.read(); + } + catch (e) { + return promiseRejectedWith(e); + } + return transformPromiseWith(readPromise, readResult => { + if (!typeIsObject(readResult)) { + throw new TypeError('The promise returned by the reader.read() method must fulfill with an object'); + } + if (readResult.done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + const value = readResult.value; + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + try { + return promiseResolvedWith(reader.cancel(reason)); + } + catch (e) { + return promiseRejectedWith(e); + } + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; + } + + function convertUnderlyingDefaultOrByteSource(source, context) { + assertDictionary(source, context); + const original = source; + const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; + const cancel = original === null || original === void 0 ? void 0 : original.cancel; + const pull = original === null || original === void 0 ? void 0 : original.pull; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + return { + autoAllocateChunkSize: autoAllocateChunkSize === undefined ? + undefined : + convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`), + cancel: cancel === undefined ? + undefined : + convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`), + pull: pull === undefined ? + undefined : + convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`), + start: start === undefined ? + undefined : + convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`), + type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`) + }; + } + function convertUnderlyingSourceCancelCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); + } + function convertUnderlyingSourcePullCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); + } + function convertUnderlyingSourceStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertReadableStreamType(type, context) { + type = `${type}`; + if (type !== 'bytes') { + throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`); + } + return type; + } + + function convertIteratorOptions(options, context) { + assertDictionary(options, context); + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + return { preventCancel: Boolean(preventCancel) }; + } + + function convertPipeOptions(options, context) { + assertDictionary(options, context); + const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort; + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + const preventClose = options === null || options === void 0 ? void 0 : options.preventClose; + const signal = options === null || options === void 0 ? void 0 : options.signal; + if (signal !== undefined) { + assertAbortSignal(signal, `${context} has member 'signal' that`); + } + return { + preventAbort: Boolean(preventAbort), + preventCancel: Boolean(preventCancel), + preventClose: Boolean(preventClose), + signal + }; + } + function assertAbortSignal(signal, context) { + if (!isAbortSignal(signal)) { + throw new TypeError(`${context} is not an AbortSignal.`); + } + } + + function convertReadableWritablePair(pair, context) { + assertDictionary(pair, context); + const readable = pair === null || pair === void 0 ? void 0 : pair.readable; + assertRequiredField(readable, 'readable', 'ReadableWritablePair'); + assertReadableStream(readable, `${context} has member 'readable' that`); + const writable = pair === null || pair === void 0 ? void 0 : pair.writable; + assertRequiredField(writable, 'writable', 'ReadableWritablePair'); + assertWritableStream(writable, `${context} has member 'writable' that`); + return { readable, writable }; + } + + /** + * A readable stream represents a source of data, from which you can read. + * + * @public + */ + class ReadableStream { + constructor(rawUnderlyingSource = {}, rawStrategy = {}) { + if (rawUnderlyingSource === undefined) { + rawUnderlyingSource = null; + } + else { + assertObject(rawUnderlyingSource, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter'); + InitializeReadableStream(this); + if (underlyingSource.type === 'bytes') { + if (strategy.size !== undefined) { + throw new RangeError('The strategy for a byte stream cannot have a size function'); + } + const highWaterMark = ExtractHighWaterMark(strategy, 0); + SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); + } + else { + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); + } + } + /** + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. + */ + get locked() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('locked'); + } + return IsReadableStreamLocked(this); + } + /** + * Cancels the stream, signaling a loss of interest in the stream by a consumer. + * + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} + * method, which might or might not use it. + */ + cancel(reason = undefined) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('cancel')); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader')); + } + return ReadableStreamCancel(this, reason); + } + getReader(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('getReader'); + } + const options = convertReaderOptions(rawOptions, 'First parameter'); + if (options.mode === undefined) { + return AcquireReadableStreamDefaultReader(this); + } + return AcquireReadableStreamBYOBReader(this); + } + pipeThrough(rawTransform, rawOptions = {}) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('pipeThrough'); + } + assertRequiredArgument(rawTransform, 1, 'pipeThrough'); + const transform = convertReadableWritablePair(rawTransform, 'First parameter'); + const options = convertPipeOptions(rawOptions, 'Second parameter'); + if (IsReadableStreamLocked(this)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream'); + } + if (IsWritableStreamLocked(transform.writable)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream'); + } + const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + setPromiseIsHandledToTrue(promise); + return transform.readable; + } + pipeTo(destination, rawOptions = {}) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('pipeTo')); + } + if (destination === undefined) { + return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`); + } + if (!IsWritableStream(destination)) { + return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)); + } + let options; + try { + options = convertPipeOptions(rawOptions, 'Second parameter'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')); + } + if (IsWritableStreamLocked(destination)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')); + } + return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + } + /** + * Tees this readable stream, returning a two-element array containing the two resulting branches as + * new {@link ReadableStream} instances. + * + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be + * propagated to the stream's underlying source. + * + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, + * this could allow interference between the two branches. + */ + tee() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('tee'); + } + const branches = ReadableStreamTee(this); + return CreateArrayFromList(branches); + } + values(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('values'); + } + const options = convertIteratorOptions(rawOptions, 'First parameter'); + return AcquireReadableStreamAsyncIterator(this, options.preventCancel); + } + [SymbolAsyncIterator](options) { + // Stub implementation, overridden below + return this.values(options); + } + /** + * Creates a new ReadableStream wrapping the provided iterable or async iterable. + * + * This can be used to adapt various kinds of objects into a readable stream, + * such as an array, an async generator, or a Node.js readable stream. + */ + static from(asyncIterable) { + return ReadableStreamFrom(asyncIterable); + } + } + Object.defineProperties(ReadableStream, { + from: { enumerable: true } + }); + Object.defineProperties(ReadableStream.prototype, { + cancel: { enumerable: true }, + getReader: { enumerable: true }, + pipeThrough: { enumerable: true }, + pipeTo: { enumerable: true }, + tee: { enumerable: true }, + values: { enumerable: true }, + locked: { enumerable: true } + }); + setFunctionName(ReadableStream.from, 'from'); + setFunctionName(ReadableStream.prototype.cancel, 'cancel'); + setFunctionName(ReadableStream.prototype.getReader, 'getReader'); + setFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough'); + setFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo'); + setFunctionName(ReadableStream.prototype.tee, 'tee'); + setFunctionName(ReadableStream.prototype.values, 'values'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, { + value: 'ReadableStream', + configurable: true + }); + } + Object.defineProperty(ReadableStream.prototype, SymbolAsyncIterator, { + value: ReadableStream.prototype.values, + writable: true, + configurable: true + }); + // Abstract operations for the ReadableStream. + // Throws if and only if startAlgorithm throws. + function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableStreamDefaultController.prototype); + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + return stream; + } + // Throws if and only if startAlgorithm throws. + function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableByteStreamController.prototype); + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined); + return stream; + } + function InitializeReadableStream(stream) { + stream._state = 'readable'; + stream._reader = undefined; + stream._storedError = undefined; + stream._disturbed = false; + } + function IsReadableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) { + return false; + } + return x instanceof ReadableStream; + } + function IsReadableStreamLocked(stream) { + if (stream._reader === undefined) { + return false; + } + return true; + } + // ReadableStream API exposed for controllers. + function ReadableStreamCancel(stream, reason) { + stream._disturbed = true; + if (stream._state === 'closed') { + return promiseResolvedWith(undefined); + } + if (stream._state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + ReadableStreamClose(stream); + const reader = stream._reader; + if (reader !== undefined && IsReadableStreamBYOBReader(reader)) { + const readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._closeSteps(undefined); + }); + } + const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); + return transformPromiseWith(sourceCancelPromise, noop); + } + function ReadableStreamClose(stream) { + stream._state = 'closed'; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseResolve(reader); + if (IsReadableStreamDefaultReader(reader)) { + const readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(readRequest => { + readRequest._closeSteps(); + }); + } + } + function ReadableStreamError(stream, e) { + stream._state = 'errored'; + stream._storedError = e; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseReject(reader, e); + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamDefaultReaderErrorReadRequests(reader, e); + } + else { + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); + } + } + // Helper functions for the ReadableStream. + function streamBrandCheckException$1(name) { + return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`); + } + + function convertQueuingStrategyInit(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit'); + return { + highWaterMark: convertUnrestrictedDouble(highWaterMark) + }; + } + + // The size function must not have a prototype property nor be a constructor + const byteLengthSizeFunction = (chunk) => { + return chunk.byteLength; + }; + setFunctionName(byteLengthSizeFunction, 'size'); + /** + * A queuing strategy that counts the number of bytes in each chunk. + * + * @public + */ + class ByteLengthQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('highWaterMark'); + } + return this._byteLengthQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by returning the value of its `byteLength` property. + */ + get size() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('size'); + } + return byteLengthSizeFunction; + } + } + Object.defineProperties(ByteLengthQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, { + value: 'ByteLengthQueuingStrategy', + configurable: true + }); + } + // Helper functions for the ByteLengthQueuingStrategy. + function byteLengthBrandCheckException(name) { + return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`); + } + function IsByteLengthQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof ByteLengthQueuingStrategy; + } + + // The size function must not have a prototype property nor be a constructor + const countSizeFunction = () => { + return 1; + }; + setFunctionName(countSizeFunction, 'size'); + /** + * A queuing strategy that counts the number of chunks. + * + * @public + */ + class CountQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'CountQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._countQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('highWaterMark'); + } + return this._countQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by always returning 1. + * This ensures that the total queue size is a count of the number of chunks in the queue. + */ + get size() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('size'); + } + return countSizeFunction; + } + } + Object.defineProperties(CountQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, { + value: 'CountQueuingStrategy', + configurable: true + }); + } + // Helper functions for the CountQueuingStrategy. + function countBrandCheckException(name) { + return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`); + } + function IsCountQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof CountQueuingStrategy; + } + + function convertTransformer(original, context) { + assertDictionary(original, context); + const cancel = original === null || original === void 0 ? void 0 : original.cancel; + const flush = original === null || original === void 0 ? void 0 : original.flush; + const readableType = original === null || original === void 0 ? void 0 : original.readableType; + const start = original === null || original === void 0 ? void 0 : original.start; + const transform = original === null || original === void 0 ? void 0 : original.transform; + const writableType = original === null || original === void 0 ? void 0 : original.writableType; + return { + cancel: cancel === undefined ? + undefined : + convertTransformerCancelCallback(cancel, original, `${context} has member 'cancel' that`), + flush: flush === undefined ? + undefined : + convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`), + readableType, + start: start === undefined ? + undefined : + convertTransformerStartCallback(start, original, `${context} has member 'start' that`), + transform: transform === undefined ? + undefined : + convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`), + writableType + }; + } + function convertTransformerFlushCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); + } + function convertTransformerStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertTransformerTransformCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); + } + function convertTransformerCancelCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); + } + + // Class TransformStream + /** + * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, + * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. + * In a manner specific to the transform stream in question, writes to the writable side result in new data being + * made available for reading from the readable side. + * + * @public + */ + class TransformStream { + constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) { + if (rawTransformer === undefined) { + rawTransformer = null; + } + const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter'); + const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter'); + const transformer = convertTransformer(rawTransformer, 'First parameter'); + if (transformer.readableType !== undefined) { + throw new RangeError('Invalid readableType specified'); + } + if (transformer.writableType !== undefined) { + throw new RangeError('Invalid writableType specified'); + } + const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); + const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); + const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); + const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); + let startPromise_resolve; + const startPromise = newPromise(resolve => { + startPromise_resolve = resolve; + }); + InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); + if (transformer.start !== undefined) { + startPromise_resolve(transformer.start(this._transformStreamController)); + } + else { + startPromise_resolve(undefined); + } + } + /** + * The readable side of the transform stream. + */ + get readable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('readable'); + } + return this._readable; + } + /** + * The writable side of the transform stream. + */ + get writable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('writable'); + } + return this._writable; + } + } + Object.defineProperties(TransformStream.prototype, { + readable: { enumerable: true }, + writable: { enumerable: true } + }); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, { + value: 'TransformStream', + configurable: true + }); + } + function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { + function startAlgorithm() { + return startPromise; + } + function writeAlgorithm(chunk) { + return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); + } + function abortAlgorithm(reason) { + return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); + } + function closeAlgorithm() { + return TransformStreamDefaultSinkCloseAlgorithm(stream); + } + stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); + function pullAlgorithm() { + return TransformStreamDefaultSourcePullAlgorithm(stream); + } + function cancelAlgorithm(reason) { + return TransformStreamDefaultSourceCancelAlgorithm(stream, reason); + } + stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure. + stream._backpressure = undefined; + stream._backpressureChangePromise = undefined; + stream._backpressureChangePromise_resolve = undefined; + TransformStreamSetBackpressure(stream, true); + stream._transformStreamController = undefined; + } + function IsTransformStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) { + return false; + } + return x instanceof TransformStream; + } + // This is a no-op if both sides are already errored. + function TransformStreamError(stream, e) { + ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e); + TransformStreamErrorWritableAndUnblockWrite(stream, e); + } + function TransformStreamErrorWritableAndUnblockWrite(stream, e) { + TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); + WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e); + TransformStreamUnblockWrite(stream); + } + function TransformStreamUnblockWrite(stream) { + if (stream._backpressure) { + // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure() + // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time + // _backpressure is set. + TransformStreamSetBackpressure(stream, false); + } + } + function TransformStreamSetBackpressure(stream, backpressure) { + // Passes also when called during construction. + if (stream._backpressureChangePromise !== undefined) { + stream._backpressureChangePromise_resolve(); + } + stream._backpressureChangePromise = newPromise(resolve => { + stream._backpressureChangePromise_resolve = resolve; + }); + stream._backpressure = backpressure; + } + // Class TransformStreamDefaultController + /** + * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. + * + * @public + */ + class TransformStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. + */ + get desiredSize() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('desiredSize'); + } + const readableController = this._controlledTransformStream._readable._readableStreamController; + return ReadableStreamDefaultControllerGetDesiredSize(readableController); + } + enqueue(chunk = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('enqueue'); + } + TransformStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors both the readable side and the writable side of the controlled transform stream, making all future + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. + */ + error(reason = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('error'); + } + TransformStreamDefaultControllerError(this, reason); + } + /** + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the + * transformer only needs to consume a portion of the chunks written to the writable side. + */ + terminate() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('terminate'); + } + TransformStreamDefaultControllerTerminate(this); + } + } + Object.defineProperties(TransformStreamDefaultController.prototype, { + enqueue: { enumerable: true }, + error: { enumerable: true }, + terminate: { enumerable: true }, + desiredSize: { enumerable: true } + }); + setFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue'); + setFunctionName(TransformStreamDefaultController.prototype.error, 'error'); + setFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, { + value: 'TransformStreamDefaultController', + configurable: true + }); + } + // Transform Stream Default Controller Abstract Operations + function IsTransformStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) { + return false; + } + return x instanceof TransformStreamDefaultController; + } + function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm) { + controller._controlledTransformStream = stream; + stream._transformStreamController = controller; + controller._transformAlgorithm = transformAlgorithm; + controller._flushAlgorithm = flushAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._finishPromise = undefined; + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; + } + function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { + const controller = Object.create(TransformStreamDefaultController.prototype); + let transformAlgorithm; + let flushAlgorithm; + let cancelAlgorithm; + if (transformer.transform !== undefined) { + transformAlgorithm = chunk => transformer.transform(chunk, controller); + } + else { + transformAlgorithm = chunk => { + try { + TransformStreamDefaultControllerEnqueue(controller, chunk); + return promiseResolvedWith(undefined); + } + catch (transformResultE) { + return promiseRejectedWith(transformResultE); + } + }; + } + if (transformer.flush !== undefined) { + flushAlgorithm = () => transformer.flush(controller); + } + else { + flushAlgorithm = () => promiseResolvedWith(undefined); + } + if (transformer.cancel !== undefined) { + cancelAlgorithm = reason => transformer.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm); + } + function TransformStreamDefaultControllerClearAlgorithms(controller) { + controller._transformAlgorithm = undefined; + controller._flushAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + } + function TransformStreamDefaultControllerEnqueue(controller, chunk) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { + throw new TypeError('Readable side is not in a state that permits enqueue'); + } + // We throttle transform invocations based on the backpressure of the ReadableStream, but we still + // accept TransformStreamDefaultControllerEnqueue() calls. + try { + ReadableStreamDefaultControllerEnqueue(readableController, chunk); + } + catch (e) { + // This happens when readableStrategy.size() throws. + TransformStreamErrorWritableAndUnblockWrite(stream, e); + throw stream._readable._storedError; + } + const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); + if (backpressure !== stream._backpressure) { + TransformStreamSetBackpressure(stream, true); + } + } + function TransformStreamDefaultControllerError(controller, e) { + TransformStreamError(controller._controlledTransformStream, e); + } + function TransformStreamDefaultControllerPerformTransform(controller, chunk) { + const transformPromise = controller._transformAlgorithm(chunk); + return transformPromiseWith(transformPromise, undefined, r => { + TransformStreamError(controller._controlledTransformStream, r); + throw r; + }); + } + function TransformStreamDefaultControllerTerminate(controller) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + ReadableStreamDefaultControllerClose(readableController); + const error = new TypeError('TransformStream terminated'); + TransformStreamErrorWritableAndUnblockWrite(stream, error); + } + // TransformStreamDefaultSink Algorithms + function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { + const controller = stream._transformStreamController; + if (stream._backpressure) { + const backpressureChangePromise = stream._backpressureChangePromise; + return transformPromiseWith(backpressureChangePromise, () => { + const writable = stream._writable; + const state = writable._state; + if (state === 'erroring') { + throw writable._storedError; + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + }); + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + } + function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + const readable = stream._readable; + // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally, + // we don't run the _cancelAlgorithm again. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, () => { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerError(readable._readableStreamController, reason); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; + } + function TransformStreamDefaultSinkCloseAlgorithm(stream) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + const readable = stream._readable; + // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally, + // we don't also run the _cancelAlgorithm. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const flushPromise = controller._flushAlgorithm(); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(flushPromise, () => { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerClose(readable._readableStreamController); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; + } + // TransformStreamDefaultSource Algorithms + function TransformStreamDefaultSourcePullAlgorithm(stream) { + // Invariant. Enforced by the promises returned by start() and pull(). + TransformStreamSetBackpressure(stream, false); + // Prevent the next pull() call until there is backpressure. + return stream._backpressureChangePromise; + } + function TransformStreamDefaultSourceCancelAlgorithm(stream, reason) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._writable cannot change after construction, so caching it across a call to user code is safe. + const writable = stream._writable; + // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or + // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the + // _flushAlgorithm. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, () => { + if (writable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, writable._storedError); + } + else { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; + } + // Helper functions for the TransformStreamDefaultController. + function defaultControllerBrandCheckException(name) { + return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`); + } + function defaultControllerFinishPromiseResolve(controller) { + if (controller._finishPromise_resolve === undefined) { + return; + } + controller._finishPromise_resolve(); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; + } + function defaultControllerFinishPromiseReject(controller, reason) { + if (controller._finishPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(controller._finishPromise); + controller._finishPromise_reject(reason); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; + } + // Helper functions for the TransformStream. + function streamBrandCheckException(name) { + return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`); + } + + exports.ByteLengthQueuingStrategy = ByteLengthQueuingStrategy; + exports.CountQueuingStrategy = CountQueuingStrategy; + exports.ReadableByteStreamController = ReadableByteStreamController; + exports.ReadableStream = ReadableStream; + exports.ReadableStreamBYOBReader = ReadableStreamBYOBReader; + exports.ReadableStreamBYOBRequest = ReadableStreamBYOBRequest; + exports.ReadableStreamDefaultController = ReadableStreamDefaultController; + exports.ReadableStreamDefaultReader = ReadableStreamDefaultReader; + exports.TransformStream = TransformStream; + exports.TransformStreamDefaultController = TransformStreamDefaultController; + exports.WritableStream = WritableStream; + exports.WritableStreamDefaultController = WritableStreamDefaultController; + exports.WritableStreamDefaultWriter = WritableStreamDefaultWriter; + +})); +//# sourceMappingURL=ponyfill.es2018.js.map diff --git a/backend/node_modules/web-streams-polyfill/dist/ponyfill.es2018.js.map b/backend/node_modules/web-streams-polyfill/dist/ponyfill.es2018.js.map new file mode 100644 index 0000000000000000000000000000000000000000..6d107ac85746efb8fdd14c038c9914fe9bde757d --- /dev/null +++ b/backend/node_modules/web-streams-polyfill/dist/ponyfill.es2018.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ponyfill.es2018.js","sources":["../src/utils.ts","../src/lib/helpers/miscellaneous.ts","../src/lib/helpers/webidl.ts","../src/lib/simple-queue.ts","../src/lib/abstract-ops/internal-methods.ts","../src/lib/readable-stream/generic-reader.ts","../src/stub/number-isfinite.ts","../src/stub/math-trunc.ts","../src/lib/validators/basic.ts","../src/lib/validators/readable-stream.ts","../src/lib/readable-stream/default-reader.ts","../src/target/es2018/stub/async-iterator-prototype.ts","../src/lib/readable-stream/async-iterator.ts","../src/stub/number-isnan.ts","../src/lib/abstract-ops/ecmascript.ts","../src/lib/abstract-ops/miscellaneous.ts","../src/lib/abstract-ops/queue-with-sizes.ts","../src/lib/helpers/array-buffer-view.ts","../src/lib/readable-stream/byte-stream-controller.ts","../src/lib/validators/reader-options.ts","../src/lib/readable-stream/byob-reader.ts","../src/lib/abstract-ops/queuing-strategy.ts","../src/lib/validators/queuing-strategy.ts","../src/lib/validators/underlying-sink.ts","../src/lib/validators/writable-stream.ts","../src/lib/abort-signal.ts","../src/lib/writable-stream.ts","../src/globals.ts","../src/stub/dom-exception.ts","../src/lib/readable-stream/pipe.ts","../src/lib/readable-stream/default-controller.ts","../src/lib/readable-stream/tee.ts","../src/lib/readable-stream/readable-stream-like.ts","../src/lib/readable-stream/from.ts","../src/lib/validators/underlying-source.ts","../src/lib/validators/iterator-options.ts","../src/lib/validators/pipe-options.ts","../src/lib/validators/readable-writable-pair.ts","../src/lib/readable-stream.ts","../src/lib/validators/queuing-strategy-init.ts","../src/lib/byte-length-queuing-strategy.ts","../src/lib/count-queuing-strategy.ts","../src/lib/validators/transformer.ts","../src/lib/transform-stream.ts"],"sourcesContent":["export function noop(): undefined {\n return undefined;\n}\n","import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n\nexport function setFunctionName(fn: Function, name: string): void {\n try {\n Object.defineProperty(fn, 'name', {\n value: name,\n configurable: true\n });\n } catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n }\n}\n","import { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\n// https://webidl.spec.whatwg.org/#a-new-promise\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-resolved-with\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return newPromise(resolve => resolve(value));\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-rejected-with\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\n// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned\n// from that handler. To prevent this, return null instead of void from all handlers.\n// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => null | PromiseLike,\n onRejected?: (reason: any) => null | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => null | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => null | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nlet _queueMicrotask: (callback: () => void) => void = callback => {\n if (typeof queueMicrotask === 'function') {\n _queueMicrotask = queueMicrotask;\n } else {\n const resolvedPromise = promiseResolvedWith(undefined);\n _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb);\n }\n return _queueMicrotask(callback);\n};\n\nexport { _queueMicrotask as queueMicrotask };\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n","import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n","export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\nexport const ReleaseSteps = Symbol('[[ReleaseSteps]]');\n","import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, type ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\nimport { ReleaseSteps } from '../abstract-ops/internal-methods';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n assert(stream._reader === reader);\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n stream._readableStreamController[ReleaseSteps]();\n\n stream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n","import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n","import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamDefaultReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamDefaultReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\nexport function ReadableStreamDefaultReaderRelease(reader: ReadableStreamDefaultReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n}\n\nexport function ReadableStreamDefaultReaderErrorReadRequests(reader: ReadableStreamDefaultReader, e: any) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n","/// \n\n/* eslint-disable @typescript-eslint/no-empty-function */\nexport const AsyncIteratorPrototype: AsyncIterable =\n Object.getPrototypeOf(Object.getPrototypeOf(async function* (): AsyncIterableIterator {}).prototype);\n","/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadableStreamDefaultReadResult,\n type ReadRequest\n} from './default-reader';\nimport { ReadableStreamReaderGenericCancel, ReadableStreamReaderGenericRelease } from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterableIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ninterface ReadableStreamAsyncIteratorInstance extends ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nObject.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n","import { reflectCall } from 'lib/helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport assert from '../../stub/assert';\n\ndeclare global {\n interface ArrayBuffer {\n readonly detached: boolean;\n\n transfer(): ArrayBuffer;\n }\n\n function structuredClone(value: T, options: { transfer: ArrayBuffer[] }): T;\n}\n\nexport function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\nexport let TransferArrayBuffer = (O: ArrayBuffer): ArrayBuffer => {\n if (typeof O.transfer === 'function') {\n TransferArrayBuffer = buffer => buffer.transfer();\n } else if (typeof structuredClone === 'function') {\n TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] });\n } else {\n // Not implemented correctly\n TransferArrayBuffer = buffer => buffer;\n }\n return TransferArrayBuffer(O);\n};\n\nexport function CanTransferArrayBuffer(O: ArrayBuffer): boolean {\n return !IsDetachedBuffer(O);\n}\n\nexport let IsDetachedBuffer = (O: ArrayBuffer): boolean => {\n if (typeof O.detached === 'boolean') {\n IsDetachedBuffer = buffer => buffer.detached;\n } else {\n // Not implemented correctly\n IsDetachedBuffer = buffer => buffer.byteLength === 0;\n }\n return IsDetachedBuffer(O);\n};\n\nexport function ArrayBufferSlice(buffer: ArrayBuffer, begin: number, end: number): ArrayBuffer {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n\nexport type MethodName = {\n [P in keyof T]: T[P] extends Function | undefined ? P : never;\n}[keyof T];\n\nexport function GetMethod>(receiver: T, prop: K): T[K] | undefined {\n const func = receiver[prop];\n if (func === undefined || func === null) {\n return undefined;\n }\n if (typeof func !== 'function') {\n throw new TypeError(`${String(prop)} is not a function`);\n }\n return func;\n}\n\nexport interface SyncIteratorRecord {\n iterator: Iterator,\n nextMethod: Iterator['next'],\n done: boolean;\n}\n\nexport interface AsyncIteratorRecord {\n iterator: AsyncIterator,\n nextMethod: AsyncIterator['next'],\n done: boolean;\n}\n\nexport type SyncOrAsyncIteratorRecord = SyncIteratorRecord | AsyncIteratorRecord;\n\nexport function CreateAsyncFromSyncIterator(syncIteratorRecord: SyncIteratorRecord): AsyncIteratorRecord {\n // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%,\n // we use yield* inside an async generator function to achieve the same result.\n\n // Wrap the sync iterator inside a sync iterable, so we can use it with yield*.\n const syncIterable = {\n [Symbol.iterator]: () => syncIteratorRecord.iterator\n };\n // Create an async generator function and immediately invoke it.\n const asyncIterator = (async function* () {\n return yield* syncIterable;\n }());\n // Return as an async iterator record.\n const nextMethod = asyncIterator.next;\n return { iterator: asyncIterator, nextMethod, done: false };\n}\n\n// Aligns with core-js/modules/es.symbol.async-iterator.js\nexport const SymbolAsyncIterator: (typeof Symbol)['asyncIterator'] =\n Symbol.asyncIterator ??\n Symbol.for?.('Symbol.asyncIterator') ??\n '@@asyncIterator';\n\nexport type SyncOrAsyncIterable = Iterable | AsyncIterable;\nexport type SyncOrAsyncIteratorMethod = () => (Iterator | AsyncIterator);\n\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint: 'async',\n method?: SyncOrAsyncIteratorMethod\n): AsyncIteratorRecord;\nfunction GetIterator(\n obj: Iterable,\n hint: 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncIteratorRecord;\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint = 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncOrAsyncIteratorRecord {\n assert(hint === 'sync' || hint === 'async');\n if (method === undefined) {\n if (hint === 'async') {\n method = GetMethod(obj as AsyncIterable, SymbolAsyncIterator);\n if (method === undefined) {\n const syncMethod = GetMethod(obj as Iterable, Symbol.iterator);\n const syncIteratorRecord = GetIterator(obj as Iterable, 'sync', syncMethod);\n return CreateAsyncFromSyncIterator(syncIteratorRecord);\n }\n } else {\n method = GetMethod(obj as Iterable, Symbol.iterator);\n }\n }\n if (method === undefined) {\n throw new TypeError('The object is not iterable');\n }\n const iterator = reflectCall(method, obj, []);\n if (!typeIsObject(iterator)) {\n throw new TypeError('The iterator method must return an object');\n }\n const nextMethod = iterator.next;\n return { iterator, nextMethod, done: false } as SyncOrAsyncIteratorRecord;\n}\n\nexport { GetIterator };\n\nexport function IteratorNext(iteratorRecord: AsyncIteratorRecord): Promise> {\n const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []);\n if (!typeIsObject(result)) {\n throw new TypeError('The iterator.next() method must return an object');\n }\n return result;\n}\n\nexport function IteratorComplete(\n iterResult: IteratorResult\n): iterResult is IteratorReturnResult {\n assert(typeIsObject(iterResult));\n return Boolean(iterResult.done);\n}\n\nexport function IteratorValue(iterResult: IteratorYieldResult): T {\n assert(typeIsObject(iterResult));\n return iterResult.value;\n}\n","import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: NonShared): NonShared {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer) as NonShared;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n","export type TypedArray =\n | Int8Array\n | Uint8Array\n | Uint8ClampedArray\n | Int16Array\n | Uint16Array\n | Int32Array\n | Uint32Array\n | Float32Array\n | Float64Array;\n\nexport type NonShared = T & {\n buffer: ArrayBuffer;\n}\n\nexport interface ArrayBufferViewConstructor {\n new(buffer: ArrayBuffer, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n}\n\nexport interface TypedArrayConstructor extends ArrayBufferViewConstructor {\n readonly BYTES_PER_ELEMENT: number;\n}\n\nexport type DataViewConstructor = ArrayBufferViewConstructor;\n\nfunction isDataViewConstructor(ctor: Function): ctor is DataViewConstructor {\n return ctor === DataView;\n}\n\nexport function isDataView(view: ArrayBufferView): view is DataView {\n return isDataViewConstructor(view.constructor);\n}\n\nexport function arrayBufferViewElementSize(ctor: ArrayBufferViewConstructor): number {\n if (isDataViewConstructor(ctor)) {\n return 1;\n }\n return (ctor as unknown as TypedArrayConstructor).BYTES_PER_ELEMENT;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n IsReadableStreamDefaultReader,\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n type ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n type ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n type ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport type { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\nimport {\n type ArrayBufferViewConstructor,\n arrayBufferViewElementSize,\n type NonShared,\n type TypedArrayConstructor\n} from '../helpers/array-buffer-view';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: NonShared | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: NonShared): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond');\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBuffer;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor = NonShared> =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: TypedArrayConstructor;\n readerType: 'default' | 'none';\n}\n\ninterface BYOBPullIntoDescriptor = NonShared> {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob' | 'none';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: NonShared): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest>): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n minimumFill: 1,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n if (this._pendingPullIntos.length > 0) {\n const firstPullInto = this._pendingPullIntos.peek();\n firstPullInto.readerType = 'none';\n\n this._pendingPullIntos = new SimpleQueue();\n this._pendingPullIntos.push(firstPullInto);\n }\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableByteStreamController.prototype.close, 'close');\nsetFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableByteStreamController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor>(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n assert(pullIntoDescriptor.readerType !== 'none');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as NonShared, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor>(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n let clonedChunk;\n try {\n clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength);\n } catch (cloneE) {\n ReadableByteStreamControllerError(controller, cloneE);\n throw cloneE;\n }\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength);\n}\n\nfunction ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.readerType === 'none');\n if (firstDescriptor.bytesFilled > 0) {\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n firstDescriptor.buffer,\n firstDescriptor.byteOffset,\n firstDescriptor.bytesFilled\n );\n }\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize;\n const maxAlignedBytes = maxBytesFilled - remainderBytes;\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n assert(pullIntoDescriptor.readerType !== 'none');\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nfunction ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller: ReadableByteStreamController) {\n const reader = controller._controlledReadableByteStream._reader;\n assert(IsReadableStreamDefaultReader(reader));\n while (reader._readRequests.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n const readRequest = reader._readRequests.shift();\n ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest);\n }\n}\n\nexport function ReadableByteStreamControllerPullInto>(\n controller: ReadableByteStreamController,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n const elementSize = arrayBufferViewElementSize(ctor);\n\n const { byteOffset, byteLength } = view;\n\n const minimumFill = min * elementSize;\n assert(minimumFill >= elementSize && minimumFill <= byteLength);\n assert(minimumFill % elementSize === 0);\n\n let buffer: ArrayBuffer;\n try {\n buffer = TransferArrayBuffer(view.buffer);\n } catch (e) {\n readIntoRequest._errorSteps(e);\n return;\n }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset,\n byteLength,\n bytesFilled: 0,\n minimumFill,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled % firstDescriptor.elementSize === 0);\n\n if (firstDescriptor.readerType === 'none') {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n return;\n }\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) {\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n pullIntoDescriptor.buffer,\n end - remainderSize,\n remainderSize\n );\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(\n controller: ReadableByteStreamController,\n chunk: NonShared\n) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const { buffer, byteOffset, byteLength } = chunk;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n if (firstPendingPullInto.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto);\n }\n }\n\n if (ReadableStreamHasDefaultReader(stream)) {\n ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller);\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView as NonShared, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerFillReadRequestFromQueue(\n controller: ReadableByteStreamController,\n readRequest: ReadRequest>\n) {\n assert(controller._queueTotalSize > 0);\n\n const entry = controller._queue.shift();\n controller._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n readRequest._chunkSteps(view as NonShared);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view as NonShared);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: NonShared) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: NonShared) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n","import { assertDictionary, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n\nexport function convertByobReadOptions(\n options: ReadableStreamBYOBReaderReadOptions | null | undefined,\n context: string\n): ValidatedReadableStreamBYOBReaderReadOptions {\n assertDictionary(options, context);\n const min = options?.min ?? 1;\n return {\n min: convertUnsignedLongLongWithEnforceRange(\n min,\n `${context} has member 'min' that`\n )\n };\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, type ReadableByteStream, type ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from './reader-options';\nimport { convertByobReadOptions } from '../validators/reader-options';\nimport { isDataView, type NonShared, type TypedArray } from '../helpers/array-buffer-view';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream as ReadableStream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest>(\n stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest\n): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest> {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(\n view: T,\n options?: ReadableStreamBYOBReaderReadOptions\n ): Promise>;\n read>(\n view: T,\n rawOptions: ReadableStreamBYOBReaderReadOptions | null | undefined = {}\n ): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n let options: ValidatedReadableStreamBYOBReaderReadOptions;\n try {\n options = convertByobReadOptions(rawOptions, 'options');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const min = options.min;\n if (min === 0) {\n return promiseRejectedWith(new TypeError('options.min must be greater than 0'));\n }\n if (!isDataView(view)) {\n if (min > (view as unknown as TypedArray).length) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s length'));\n }\n } else if (min > view.byteLength) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s byteLength'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamBYOBReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamBYOBReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead>(\n reader: ReadableStreamBYOBReader,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n min,\n readIntoRequest\n );\n }\n}\n\nexport function ReadableStreamBYOBReaderRelease(reader: ReadableStreamBYOBReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n}\n\nexport function ReadableStreamBYOBReaderErrorReadIntoRequests(reader: ReadableStreamBYOBReader, e: any) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n","/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * If aborted, returns the reason for aborting.\n */\n readonly reason?: any;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(reason?: any): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n type QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { type AbortController, type AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(WritableStream.prototype.abort, 'abort');\nsetFunctionName(WritableStream.prototype.close, 'close');\nsetFunctionName(WritableStream.prototype.getWriter, 'getWriter');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight\n};\n\nexport type {\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort(reason);\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nsetFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort');\nsetFunctionName(WritableStreamDefaultWriter.prototype.close, 'close');\nsetFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock');\nsetFunctionName(WritableStreamDefaultWriter.prototype.write, 'write');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n return null;\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let writeAlgorithm: (chunk: W) => Promise;\n let closeAlgorithm: () => Promise;\n let abortAlgorithm: (reason: any) => Promise;\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n } else {\n writeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n } else {\n closeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n } else {\n abortAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n return null;\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n","/// \n\nfunction getGlobals(): typeof globalThis | undefined {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n } else if (typeof self !== 'undefined') {\n return self;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n","/// \nimport { globals } from '../globals';\nimport { setFunctionName } from '../lib/helpers/miscellaneous';\n\ninterface DOMException extends Error {\n name: string;\n message: string;\n}\n\ntype DOMExceptionConstructor = new (message?: string, name?: string) => DOMException;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n if ((ctor as DOMExceptionConstructor).name !== 'DOMException') {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Support:\n * - Web browsers\n * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87)\n */\nfunction getFromGlobal(): DOMExceptionConstructor | undefined {\n const ctor = globals?.DOMException;\n return isDOMExceptionConstructor(ctor) ? ctor : undefined;\n}\n\n/**\n * Support:\n * - All platforms\n */\nfunction createPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line @typescript-eslint/no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n setFunctionName(ctor, 'DOMException');\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nconst DOMException: DOMExceptionConstructor = getFromGlobal() || createPolyfill();\n\nexport { DOMException };\n","import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n return null;\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => null) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => null) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest(): null {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n return null;\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any): null {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n\n return null;\n }\n });\n}\n","import type { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, type QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n type ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport type { ValidatedUnderlyingSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n // Do nothing.\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultController.prototype.close, 'close');\nsetFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableStreamDefaultController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n","import {\n CreateReadableByteStream,\n CreateReadableStream,\n type DefaultReadableStream,\n IsReadableStream,\n type ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n type ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n type ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(\n stream: ReadableStream,\n cloneForBranch2: boolean\n): [DefaultReadableStream, DefaultReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: DefaultReadableStream;\n let branch2: DefaultReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader> = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader>) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return null;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: NonShared, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader>(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n","import { typeIsObject } from '../helpers/miscellaneous';\nimport type { ReadableStreamDefaultReadResult } from './default-reader';\n\n/**\n * A common interface for a `ReadadableStream` implementation.\n *\n * @public\n */\nexport interface ReadableStreamLike {\n readonly locked: boolean;\n\n getReader(): ReadableStreamDefaultReaderLike;\n}\n\n/**\n * A common interface for a `ReadableStreamDefaultReader` implementation.\n *\n * @public\n */\nexport interface ReadableStreamDefaultReaderLike {\n readonly closed: Promise;\n\n cancel(reason?: any): Promise;\n\n read(): Promise>;\n\n releaseLock(): void;\n}\n\nexport function isReadableStreamLike(stream: unknown): stream is ReadableStreamLike {\n return typeIsObject(stream) && typeof (stream as ReadableStreamLike).getReader !== 'undefined';\n}\n","import { CreateReadableStream, type DefaultReadableStream } from '../readable-stream';\nimport {\n isReadableStreamLike,\n type ReadableStreamDefaultReaderLike,\n type ReadableStreamLike\n} from './readable-stream-like';\nimport { ReadableStreamDefaultControllerClose, ReadableStreamDefaultControllerEnqueue } from './default-controller';\nimport { GetIterator, GetMethod, IteratorComplete, IteratorNext, IteratorValue } from '../abstract-ops/ecmascript';\nimport { promiseRejectedWith, promiseResolvedWith, reflectCall, transformPromiseWith } from '../helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { noop } from '../../utils';\n\nexport function ReadableStreamFrom(\n source: Iterable | AsyncIterable | ReadableStreamLike\n): DefaultReadableStream {\n if (isReadableStreamLike(source)) {\n return ReadableStreamFromDefaultReader(source.getReader());\n }\n return ReadableStreamFromIterable(source);\n}\n\nexport function ReadableStreamFromIterable(asyncIterable: Iterable | AsyncIterable): DefaultReadableStream {\n let stream: DefaultReadableStream;\n const iteratorRecord = GetIterator(asyncIterable, 'async');\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let nextResult;\n try {\n nextResult = IteratorNext(iteratorRecord);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const nextPromise = promiseResolvedWith(nextResult);\n return transformPromiseWith(nextPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object');\n }\n const done = IteratorComplete(iterResult);\n if (done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = IteratorValue(iterResult);\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n const iterator = iteratorRecord.iterator;\n let returnMethod: (typeof iterator)['return'] | undefined;\n try {\n returnMethod = GetMethod(iterator, 'return');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n if (returnMethod === undefined) {\n return promiseResolvedWith(undefined);\n }\n let returnResult: IteratorResult | Promise>;\n try {\n returnResult = reflectCall(returnMethod, iterator, [reason]);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const returnPromise = promiseResolvedWith(returnResult);\n return transformPromiseWith(returnPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object');\n }\n return undefined;\n });\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n\nexport function ReadableStreamFromDefaultReader(\n reader: ReadableStreamDefaultReaderLike\n): DefaultReadableStream {\n let stream: DefaultReadableStream;\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let readPromise;\n try {\n readPromise = reader.read();\n } catch (e) {\n return promiseRejectedWith(e);\n }\n return transformPromiseWith(readPromise, readResult => {\n if (!typeIsObject(readResult)) {\n throw new TypeError('The promise returned by the reader.read() method must fulfill with an object');\n }\n if (readResult.done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = readResult.value;\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n try {\n return promiseResolvedWith(reader.cancel(reason));\n } catch (e) {\n return promiseRejectedWith(e);\n }\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n","import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n","import { assertDictionary } from './basic';\nimport type {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n","import { assertDictionary } from './basic';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n","import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n","import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, type ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderErrorReadRequests,\n type ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReaderErrorReadIntoRequests,\n type ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { ReadableStreamFrom } from './readable-stream/from';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport type {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList, SymbolAsyncIterator } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions\n} from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport type { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport type { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\nimport type { ReadableStreamDefaultReaderLike, ReadableStreamLike } from './readable-stream/readable-stream-like';\nimport type { NonShared } from './helpers/array-buffer-view';\n\nexport type DefaultReadableStream = ReadableStream & {\n _readableStreamController: ReadableStreamDefaultController\n};\n\nexport type ReadableByteStream = ReadableStream> & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream implements AsyncIterable {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n\n [SymbolAsyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator {\n // Stub implementation, overridden below\n return this.values(options);\n }\n\n /**\n * Creates a new ReadableStream wrapping the provided iterable or async iterable.\n *\n * This can be used to adapt various kinds of objects into a readable stream,\n * such as an array, an async generator, or a Node.js readable stream.\n */\n static from(asyncIterable: Iterable | AsyncIterable | ReadableStreamLike): ReadableStream {\n return ReadableStreamFrom(asyncIterable);\n }\n}\n\nObject.defineProperties(ReadableStream, {\n from: { enumerable: true }\n});\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(ReadableStream.from, 'from');\nsetFunctionName(ReadableStream.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStream.prototype.getReader, 'getReader');\nsetFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough');\nsetFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo');\nsetFunctionName(ReadableStream.prototype.tee, 'tee');\nsetFunctionName(ReadableStream.prototype.values, 'values');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nObject.defineProperty(ReadableStream.prototype, SymbolAsyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n});\n\nexport type {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n ReadableStreamBYOBReaderReadOptions,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions,\n ReadableStreamLike,\n ReadableStreamDefaultReaderLike\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1\n): DefaultReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: DefaultReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n","import type { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\nsetFunctionName(byteLengthSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\nsetFunctionName(countSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const cancel = original?.cancel;\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n cancel: cancel === undefined ?\n undefined :\n convertTransformerCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n\nfunction convertTransformerCancelCallback(\n fn: TransformerCancelCallback,\n original: Transformer,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith,\n uponPromise\n} from './helpers/webidl';\nimport { CreateReadableStream, type DefaultReadableStream, ReadableStream } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: DefaultReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport type {\n Transformer,\n TransformerCancelCallback,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSourceCancelAlgorithm(stream, reason);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n TransformStreamUnblockWrite(stream);\n}\n\nfunction TransformStreamUnblockWrite(stream: TransformStream) {\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _finishPromise: Promise | undefined;\n /** @internal */\n _finishPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _finishPromise_reject?: (reason: any) => void;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n /** @internal */\n _cancelAlgorithm: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(TransformStreamDefaultController.prototype.error, 'error');\nsetFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._finishPromise = undefined;\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm: (chunk: I) => Promise;\n let flushAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n } else {\n transformAlgorithm = chunk => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n }\n\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n } else {\n flushAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n if (transformer.cancel !== undefined) {\n cancelAlgorithm = reason => transformer.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally,\n // we don't run the _cancelAlgorithm again.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerError(readable._readableStreamController, reason);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally,\n // we don't also run the _cancelAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(flushPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerClose(readable._readableStreamController);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\nfunction TransformStreamDefaultSourceCancelAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._writable cannot change after construction, so caching it across a call to user code is safe.\n const writable = stream._writable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or\n // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the\n // _flushAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (writable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, writable._storedError);\n } else {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\nexport function defaultControllerFinishPromiseResolve(controller: TransformStreamDefaultController) {\n if (controller._finishPromise_resolve === undefined) {\n return;\n }\n\n controller._finishPromise_resolve();\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nexport function defaultControllerFinishPromiseReject(controller: TransformStreamDefaultController, reason: any) {\n if (controller._finishPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(controller._finishPromise!);\n controller._finishPromise_reject(reason);\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n"],"names":["queueMicrotask","streamBrandCheckException","defaultControllerBrandCheckException"],"mappings":";;;;;;;;;;;;;aAAgB,IAAI,GAAA;IAClB,IAAA,OAAO,SAAS,CAAC;IACnB;;ICCM,SAAU,YAAY,CAAC,CAAM,EAAA;IACjC,IAAA,OAAO,CAAC,OAAO,CAAC,KAAK,QAAQ,IAAI,CAAC,KAAK,IAAI,KAAK,OAAO,CAAC,KAAK,UAAU,CAAC;IAC1E,CAAC;IAEM,MAAM,8BAA8B,GAUrC,IAAI,CAAC;IAEK,SAAA,eAAe,CAAC,EAAY,EAAE,IAAY,EAAA;IACxD,IAAA,IAAI;IACF,QAAA,MAAM,CAAC,cAAc,CAAC,EAAE,EAAE,MAAM,EAAE;IAChC,YAAA,KAAK,EAAE,IAAI;IACX,YAAA,YAAY,EAAE,IAAI;IACnB,SAAA,CAAC,CAAC;SACJ;IAAC,IAAA,OAAA,EAAA,EAAM;;;SAGP;IACH;;IC1BA,MAAM,eAAe,GAAG,OAAO,CAAC;IAChC,MAAM,mBAAmB,GAAG,OAAO,CAAC,SAAS,CAAC,IAAI,CAAC;IACnD,MAAM,qBAAqB,GAAG,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC;IAEnE;IACM,SAAU,UAAU,CAAI,QAGrB,EAAA;IACP,IAAA,OAAO,IAAI,eAAe,CAAC,QAAQ,CAAC,CAAC;IACvC,CAAC;IAED;IACM,SAAU,mBAAmB,CAAI,KAAyB,EAAA;QAC9D,OAAO,UAAU,CAAC,OAAO,IAAI,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC;IAC/C,CAAC;IAED;IACM,SAAU,mBAAmB,CAAY,MAAW,EAAA;IACxD,IAAA,OAAO,qBAAqB,CAAC,MAAM,CAAC,CAAC;IACvC,CAAC;aAEe,kBAAkB,CAChC,OAAmB,EACnB,WAA4D,EAC5D,UAA8D,EAAA;;;QAG9D,OAAO,mBAAmB,CAAC,IAAI,CAAC,O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,SAAS,CAAC;IAC/C,CAAC;IAED;IAEA,SAAS,yBAAyB,CAAC,IAAY,EAAA;IAC7C,IAAA,OAAO,IAAI,SAAS,CAClB,6BAA6B,IAAI,CAAA,sCAAA,CAAwC,CAAC,CAAC;IAC/E;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/backend/node_modules/web-streams-polyfill/dist/ponyfill.es2018.mjs b/backend/node_modules/web-streams-polyfill/dist/ponyfill.es2018.mjs new file mode 100644 index 0000000000000000000000000000000000000000..431260f8b71b80eccabf5fb923f985240527b150 --- /dev/null +++ b/backend/node_modules/web-streams-polyfill/dist/ponyfill.es2018.mjs @@ -0,0 +1,4717 @@ +/** + * @license + * web-streams-polyfill v3.3.3 + * Copyright 2024 Mattias Buelens, Diwank Singh Tomer and other contributors. + * This code is released under the MIT license. + * SPDX-License-Identifier: MIT + */ +function noop() { + return undefined; +} + +function typeIsObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; +} +const rethrowAssertionErrorRejection = noop; +function setFunctionName(fn, name) { + try { + Object.defineProperty(fn, 'name', { + value: name, + configurable: true + }); + } + catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility + } +} + +const originalPromise = Promise; +const originalPromiseThen = Promise.prototype.then; +const originalPromiseReject = Promise.reject.bind(originalPromise); +// https://webidl.spec.whatwg.org/#a-new-promise +function newPromise(executor) { + return new originalPromise(executor); +} +// https://webidl.spec.whatwg.org/#a-promise-resolved-with +function promiseResolvedWith(value) { + return newPromise(resolve => resolve(value)); +} +// https://webidl.spec.whatwg.org/#a-promise-rejected-with +function promiseRejectedWith(reason) { + return originalPromiseReject(reason); +} +function PerformPromiseThen(promise, onFulfilled, onRejected) { + // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an + // approximation. + return originalPromiseThen.call(promise, onFulfilled, onRejected); +} +// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned +// from that handler. To prevent this, return null instead of void from all handlers. +// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it +function uponPromise(promise, onFulfilled, onRejected) { + PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection); +} +function uponFulfillment(promise, onFulfilled) { + uponPromise(promise, onFulfilled); +} +function uponRejection(promise, onRejected) { + uponPromise(promise, undefined, onRejected); +} +function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { + return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); +} +function setPromiseIsHandledToTrue(promise) { + PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection); +} +let _queueMicrotask = callback => { + if (typeof queueMicrotask === 'function') { + _queueMicrotask = queueMicrotask; + } + else { + const resolvedPromise = promiseResolvedWith(undefined); + _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb); + } + return _queueMicrotask(callback); +}; +function reflectCall(F, V, args) { + if (typeof F !== 'function') { + throw new TypeError('Argument is not a function'); + } + return Function.prototype.apply.call(F, V, args); +} +function promiseCall(F, V, args) { + try { + return promiseResolvedWith(reflectCall(F, V, args)); + } + catch (value) { + return promiseRejectedWith(value); + } +} + +// Original from Chromium +// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js +const QUEUE_MAX_ARRAY_SIZE = 16384; +/** + * Simple queue structure. + * + * Avoids scalability issues with using a packed array directly by using + * multiple arrays in a linked list and keeping the array size bounded. + */ +class SimpleQueue { + constructor() { + this._cursor = 0; + this._size = 0; + // _front and _back are always defined. + this._front = { + _elements: [], + _next: undefined + }; + this._back = this._front; + // The cursor is used to avoid calling Array.shift(). + // It contains the index of the front element of the array inside the + // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE). + this._cursor = 0; + // When there is only one node, size === elements.length - cursor. + this._size = 0; + } + get length() { + return this._size; + } + // For exception safety, this method is structured in order: + // 1. Read state + // 2. Calculate required state mutations + // 3. Perform state mutations + push(element) { + const oldBack = this._back; + let newBack = oldBack; + if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { + newBack = { + _elements: [], + _next: undefined + }; + } + // push() is the mutation most likely to throw an exception, so it + // goes first. + oldBack._elements.push(element); + if (newBack !== oldBack) { + this._back = newBack; + oldBack._next = newBack; + } + ++this._size; + } + // Like push(), shift() follows the read -> calculate -> mutate pattern for + // exception safety. + shift() { // must not be called on an empty queue + const oldFront = this._front; + let newFront = oldFront; + const oldCursor = this._cursor; + let newCursor = oldCursor + 1; + const elements = oldFront._elements; + const element = elements[oldCursor]; + if (newCursor === QUEUE_MAX_ARRAY_SIZE) { + newFront = oldFront._next; + newCursor = 0; + } + // No mutations before this point. + --this._size; + this._cursor = newCursor; + if (oldFront !== newFront) { + this._front = newFront; + } + // Permit shifted element to be garbage collected. + elements[oldCursor] = undefined; + return element; + } + // The tricky thing about forEach() is that it can be called + // re-entrantly. The queue may be mutated inside the callback. It is easy to + // see that push() within the callback has no negative effects since the end + // of the queue is checked for on every iteration. If shift() is called + // repeatedly within the callback then the next iteration may return an + // element that has been removed. In this case the callback will be called + // with undefined values until we either "catch up" with elements that still + // exist or reach the back of the queue. + forEach(callback) { + let i = this._cursor; + let node = this._front; + let elements = node._elements; + while (i !== elements.length || node._next !== undefined) { + if (i === elements.length) { + node = node._next; + elements = node._elements; + i = 0; + if (elements.length === 0) { + break; + } + } + callback(elements[i]); + ++i; + } + } + // Return the element that would be returned if shift() was called now, + // without modifying the queue. + peek() { // must not be called on an empty queue + const front = this._front; + const cursor = this._cursor; + return front._elements[cursor]; + } +} + +const AbortSteps = Symbol('[[AbortSteps]]'); +const ErrorSteps = Symbol('[[ErrorSteps]]'); +const CancelSteps = Symbol('[[CancelSteps]]'); +const PullSteps = Symbol('[[PullSteps]]'); +const ReleaseSteps = Symbol('[[ReleaseSteps]]'); + +function ReadableStreamReaderGenericInitialize(reader, stream) { + reader._ownerReadableStream = stream; + stream._reader = reader; + if (stream._state === 'readable') { + defaultReaderClosedPromiseInitialize(reader); + } + else if (stream._state === 'closed') { + defaultReaderClosedPromiseInitializeAsResolved(reader); + } + else { + defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); + } +} +// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state +// check. +function ReadableStreamReaderGenericCancel(reader, reason) { + const stream = reader._ownerReadableStream; + return ReadableStreamCancel(stream, reason); +} +function ReadableStreamReaderGenericRelease(reader) { + const stream = reader._ownerReadableStream; + if (stream._state === 'readable') { + defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + else { + defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + stream._readableStreamController[ReleaseSteps](); + stream._reader = undefined; + reader._ownerReadableStream = undefined; +} +// Helper functions for the readers. +function readerLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released reader'); +} +// Helper functions for the ReadableStreamDefaultReader. +function defaultReaderClosedPromiseInitialize(reader) { + reader._closedPromise = newPromise((resolve, reject) => { + reader._closedPromise_resolve = resolve; + reader._closedPromise_reject = reject; + }); +} +function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseReject(reader, reason); +} +function defaultReaderClosedPromiseInitializeAsResolved(reader) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseResolve(reader); +} +function defaultReaderClosedPromiseReject(reader, reason) { + if (reader._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(reader._closedPromise); + reader._closedPromise_reject(reason); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; +} +function defaultReaderClosedPromiseResetToRejected(reader, reason) { + defaultReaderClosedPromiseInitializeAsRejected(reader, reason); +} +function defaultReaderClosedPromiseResolve(reader) { + if (reader._closedPromise_resolve === undefined) { + return; + } + reader._closedPromise_resolve(undefined); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; +} + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill +const NumberIsFinite = Number.isFinite || function (x) { + return typeof x === 'number' && isFinite(x); +}; + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill +const MathTrunc = Math.trunc || function (v) { + return v < 0 ? Math.ceil(v) : Math.floor(v); +}; + +// https://heycam.github.io/webidl/#idl-dictionaries +function isDictionary(x) { + return typeof x === 'object' || typeof x === 'function'; +} +function assertDictionary(obj, context) { + if (obj !== undefined && !isDictionary(obj)) { + throw new TypeError(`${context} is not an object.`); + } +} +// https://heycam.github.io/webidl/#idl-callback-functions +function assertFunction(x, context) { + if (typeof x !== 'function') { + throw new TypeError(`${context} is not a function.`); + } +} +// https://heycam.github.io/webidl/#idl-object +function isObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; +} +function assertObject(x, context) { + if (!isObject(x)) { + throw new TypeError(`${context} is not an object.`); + } +} +function assertRequiredArgument(x, position, context) { + if (x === undefined) { + throw new TypeError(`Parameter ${position} is required in '${context}'.`); + } +} +function assertRequiredField(x, field, context) { + if (x === undefined) { + throw new TypeError(`${field} is required in '${context}'.`); + } +} +// https://heycam.github.io/webidl/#idl-unrestricted-double +function convertUnrestrictedDouble(value) { + return Number(value); +} +function censorNegativeZero(x) { + return x === 0 ? 0 : x; +} +function integerPart(x) { + return censorNegativeZero(MathTrunc(x)); +} +// https://heycam.github.io/webidl/#idl-unsigned-long-long +function convertUnsignedLongLongWithEnforceRange(value, context) { + const lowerBound = 0; + const upperBound = Number.MAX_SAFE_INTEGER; + let x = Number(value); + x = censorNegativeZero(x); + if (!NumberIsFinite(x)) { + throw new TypeError(`${context} is not a finite number`); + } + x = integerPart(x); + if (x < lowerBound || x > upperBound) { + throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`); + } + if (!NumberIsFinite(x) || x === 0) { + return 0; + } + // TODO Use BigInt if supported? + // let xBigInt = BigInt(integerPart(x)); + // xBigInt = BigInt.asUintN(64, xBigInt); + // return Number(xBigInt); + return x; +} + +function assertReadableStream(x, context) { + if (!IsReadableStream(x)) { + throw new TypeError(`${context} is not a ReadableStream.`); + } +} + +// Abstract operations for the ReadableStream. +function AcquireReadableStreamDefaultReader(stream) { + return new ReadableStreamDefaultReader(stream); +} +// ReadableStream API exposed for controllers. +function ReadableStreamAddReadRequest(stream, readRequest) { + stream._reader._readRequests.push(readRequest); +} +function ReadableStreamFulfillReadRequest(stream, chunk, done) { + const reader = stream._reader; + const readRequest = reader._readRequests.shift(); + if (done) { + readRequest._closeSteps(); + } + else { + readRequest._chunkSteps(chunk); + } +} +function ReadableStreamGetNumReadRequests(stream) { + return stream._reader._readRequests.length; +} +function ReadableStreamHasDefaultReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamDefaultReader(reader)) { + return false; + } + return true; +} +/** + * A default reader vended by a {@link ReadableStream}. + * + * @public + */ +class ReadableStreamDefaultReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + /** + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('read')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: () => resolvePromise({ value: undefined, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamDefaultReaderRead(this, readRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamDefaultReader(this)) { + throw defaultReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamDefaultReaderRelease(this); + } +} +Object.defineProperties(ReadableStreamDefaultReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } +}); +setFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel'); +setFunctionName(ReadableStreamDefaultReader.prototype.read, 'read'); +setFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, { + value: 'ReadableStreamDefaultReader', + configurable: true + }); +} +// Abstract operations for the readers. +function IsReadableStreamDefaultReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) { + return false; + } + return x instanceof ReadableStreamDefaultReader; +} +function ReadableStreamDefaultReaderRead(reader, readRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'closed') { + readRequest._closeSteps(); + } + else if (stream._state === 'errored') { + readRequest._errorSteps(stream._storedError); + } + else { + stream._readableStreamController[PullSteps](readRequest); + } +} +function ReadableStreamDefaultReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + const e = new TypeError('Reader was released'); + ReadableStreamDefaultReaderErrorReadRequests(reader, e); +} +function ReadableStreamDefaultReaderErrorReadRequests(reader, e) { + const readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(readRequest => { + readRequest._errorSteps(e); + }); +} +// Helper functions for the ReadableStreamDefaultReader. +function defaultReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`); +} + +/// +/* eslint-disable @typescript-eslint/no-empty-function */ +const AsyncIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf(async function* () { }).prototype); + +/// +class ReadableStreamAsyncIteratorImpl { + constructor(reader, preventCancel) { + this._ongoingPromise = undefined; + this._isFinished = false; + this._reader = reader; + this._preventCancel = preventCancel; + } + next() { + const nextSteps = () => this._nextSteps(); + this._ongoingPromise = this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : + nextSteps(); + return this._ongoingPromise; + } + return(value) { + const returnSteps = () => this._returnSteps(value); + return this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : + returnSteps(); + } + _nextSteps() { + if (this._isFinished) { + return Promise.resolve({ value: undefined, done: true }); + } + const reader = this._reader; + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => { + this._ongoingPromise = undefined; + // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test. + // FIXME Is this a bug in the specification, or in the test? + _queueMicrotask(() => resolvePromise({ value: chunk, done: false })); + }, + _closeSteps: () => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + resolvePromise({ value: undefined, done: true }); + }, + _errorSteps: reason => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + rejectPromise(reason); + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promise; + } + _returnSteps(value) { + if (this._isFinished) { + return Promise.resolve({ value, done: true }); + } + this._isFinished = true; + const reader = this._reader; + if (!this._preventCancel) { + const result = ReadableStreamReaderGenericCancel(reader, value); + ReadableStreamReaderGenericRelease(reader); + return transformPromiseWith(result, () => ({ value, done: true })); + } + ReadableStreamReaderGenericRelease(reader); + return promiseResolvedWith({ value, done: true }); + } +} +const ReadableStreamAsyncIteratorPrototype = { + next() { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next')); + } + return this._asyncIteratorImpl.next(); + }, + return(value) { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return')); + } + return this._asyncIteratorImpl.return(value); + } +}; +Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); +// Abstract operations for the ReadableStream. +function AcquireReadableStreamAsyncIterator(stream, preventCancel) { + const reader = AcquireReadableStreamDefaultReader(stream); + const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); + const iterator = Object.create(ReadableStreamAsyncIteratorPrototype); + iterator._asyncIteratorImpl = impl; + return iterator; +} +function IsReadableStreamAsyncIterator(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) { + return false; + } + try { + // noinspection SuspiciousTypeOfGuard + return x._asyncIteratorImpl instanceof + ReadableStreamAsyncIteratorImpl; + } + catch (_a) { + return false; + } +} +// Helper functions for the ReadableStream. +function streamAsyncIteratorBrandCheckException(name) { + return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`); +} + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill +const NumberIsNaN = Number.isNaN || function (x) { + // eslint-disable-next-line no-self-compare + return x !== x; +}; + +var _a, _b, _c; +function CreateArrayFromList(elements) { + // We use arrays to represent lists, so this is basically a no-op. + // Do a slice though just in case we happen to depend on the unique-ness. + return elements.slice(); +} +function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { + new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); +} +let TransferArrayBuffer = (O) => { + if (typeof O.transfer === 'function') { + TransferArrayBuffer = buffer => buffer.transfer(); + } + else if (typeof structuredClone === 'function') { + TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] }); + } + else { + // Not implemented correctly + TransferArrayBuffer = buffer => buffer; + } + return TransferArrayBuffer(O); +}; +let IsDetachedBuffer = (O) => { + if (typeof O.detached === 'boolean') { + IsDetachedBuffer = buffer => buffer.detached; + } + else { + // Not implemented correctly + IsDetachedBuffer = buffer => buffer.byteLength === 0; + } + return IsDetachedBuffer(O); +}; +function ArrayBufferSlice(buffer, begin, end) { + // ArrayBuffer.prototype.slice is not available on IE10 + // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice + if (buffer.slice) { + return buffer.slice(begin, end); + } + const length = end - begin; + const slice = new ArrayBuffer(length); + CopyDataBlockBytes(slice, 0, buffer, begin, length); + return slice; +} +function GetMethod(receiver, prop) { + const func = receiver[prop]; + if (func === undefined || func === null) { + return undefined; + } + if (typeof func !== 'function') { + throw new TypeError(`${String(prop)} is not a function`); + } + return func; +} +function CreateAsyncFromSyncIterator(syncIteratorRecord) { + // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%, + // we use yield* inside an async generator function to achieve the same result. + // Wrap the sync iterator inside a sync iterable, so we can use it with yield*. + const syncIterable = { + [Symbol.iterator]: () => syncIteratorRecord.iterator + }; + // Create an async generator function and immediately invoke it. + const asyncIterator = (async function* () { + return yield* syncIterable; + }()); + // Return as an async iterator record. + const nextMethod = asyncIterator.next; + return { iterator: asyncIterator, nextMethod, done: false }; +} +// Aligns with core-js/modules/es.symbol.async-iterator.js +const SymbolAsyncIterator = (_c = (_a = Symbol.asyncIterator) !== null && _a !== void 0 ? _a : (_b = Symbol.for) === null || _b === void 0 ? void 0 : _b.call(Symbol, 'Symbol.asyncIterator')) !== null && _c !== void 0 ? _c : '@@asyncIterator'; +function GetIterator(obj, hint = 'sync', method) { + if (method === undefined) { + if (hint === 'async') { + method = GetMethod(obj, SymbolAsyncIterator); + if (method === undefined) { + const syncMethod = GetMethod(obj, Symbol.iterator); + const syncIteratorRecord = GetIterator(obj, 'sync', syncMethod); + return CreateAsyncFromSyncIterator(syncIteratorRecord); + } + } + else { + method = GetMethod(obj, Symbol.iterator); + } + } + if (method === undefined) { + throw new TypeError('The object is not iterable'); + } + const iterator = reflectCall(method, obj, []); + if (!typeIsObject(iterator)) { + throw new TypeError('The iterator method must return an object'); + } + const nextMethod = iterator.next; + return { iterator, nextMethod, done: false }; +} +function IteratorNext(iteratorRecord) { + const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []); + if (!typeIsObject(result)) { + throw new TypeError('The iterator.next() method must return an object'); + } + return result; +} +function IteratorComplete(iterResult) { + return Boolean(iterResult.done); +} +function IteratorValue(iterResult) { + return iterResult.value; +} + +function IsNonNegativeNumber(v) { + if (typeof v !== 'number') { + return false; + } + if (NumberIsNaN(v)) { + return false; + } + if (v < 0) { + return false; + } + return true; +} +function CloneAsUint8Array(O) { + const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength); + return new Uint8Array(buffer); +} + +function DequeueValue(container) { + const pair = container._queue.shift(); + container._queueTotalSize -= pair.size; + if (container._queueTotalSize < 0) { + container._queueTotalSize = 0; + } + return pair.value; +} +function EnqueueValueWithSize(container, value, size) { + if (!IsNonNegativeNumber(size) || size === Infinity) { + throw new RangeError('Size must be a finite, non-NaN, non-negative number.'); + } + container._queue.push({ value, size }); + container._queueTotalSize += size; +} +function PeekQueueValue(container) { + const pair = container._queue.peek(); + return pair.value; +} +function ResetQueue(container) { + container._queue = new SimpleQueue(); + container._queueTotalSize = 0; +} + +function isDataViewConstructor(ctor) { + return ctor === DataView; +} +function isDataView(view) { + return isDataViewConstructor(view.constructor); +} +function arrayBufferViewElementSize(ctor) { + if (isDataViewConstructor(ctor)) { + return 1; + } + return ctor.BYTES_PER_ELEMENT; +} + +/** + * A pull-into request in a {@link ReadableByteStreamController}. + * + * @public + */ +class ReadableStreamBYOBRequest { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. + */ + get view() { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('view'); + } + return this._view; + } + respond(bytesWritten) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respond'); + } + assertRequiredArgument(bytesWritten, 1, 'respond'); + bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter'); + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(this._view.buffer)) { + throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`); + } + ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); + } + respondWithNewView(view) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respondWithNewView'); + } + assertRequiredArgument(view, 1, 'respondWithNewView'); + if (!ArrayBuffer.isView(view)) { + throw new TypeError('You can only respond with array buffer views'); + } + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(view.buffer)) { + throw new TypeError('The given view\'s buffer has been detached and so cannot be used as a response'); + } + ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); + } +} +Object.defineProperties(ReadableStreamBYOBRequest.prototype, { + respond: { enumerable: true }, + respondWithNewView: { enumerable: true }, + view: { enumerable: true } +}); +setFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond'); +setFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, { + value: 'ReadableStreamBYOBRequest', + configurable: true + }); +} +/** + * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. + * + * @public + */ +class ReadableByteStreamController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the current BYOB pull request, or `null` if there isn't one. + */ + get byobRequest() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('byobRequest'); + } + return ReadableByteStreamControllerGetBYOBRequest(this); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('desiredSize'); + } + return ReadableByteStreamControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('close'); + } + if (this._closeRequested) { + throw new TypeError('The stream has already been closed; do not close it again!'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`); + } + ReadableByteStreamControllerClose(this); + } + enqueue(chunk) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('enqueue'); + } + assertRequiredArgument(chunk, 1, 'enqueue'); + if (!ArrayBuffer.isView(chunk)) { + throw new TypeError('chunk must be an array buffer view'); + } + if (chunk.byteLength === 0) { + throw new TypeError('chunk must have non-zero byteLength'); + } + if (chunk.buffer.byteLength === 0) { + throw new TypeError(`chunk's buffer must have non-zero byteLength`); + } + if (this._closeRequested) { + throw new TypeError('stream is closed or draining'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`); + } + ReadableByteStreamControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('error'); + } + ReadableByteStreamControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ReadableByteStreamControllerClearPendingPullIntos(this); + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableByteStreamControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableByteStream; + if (this._queueTotalSize > 0) { + ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest); + return; + } + const autoAllocateChunkSize = this._autoAllocateChunkSize; + if (autoAllocateChunkSize !== undefined) { + let buffer; + try { + buffer = new ArrayBuffer(autoAllocateChunkSize); + } + catch (bufferE) { + readRequest._errorSteps(bufferE); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: autoAllocateChunkSize, + byteOffset: 0, + byteLength: autoAllocateChunkSize, + bytesFilled: 0, + minimumFill: 1, + elementSize: 1, + viewConstructor: Uint8Array, + readerType: 'default' + }; + this._pendingPullIntos.push(pullIntoDescriptor); + } + ReadableStreamAddReadRequest(stream, readRequest); + ReadableByteStreamControllerCallPullIfNeeded(this); + } + /** @internal */ + [ReleaseSteps]() { + if (this._pendingPullIntos.length > 0) { + const firstPullInto = this._pendingPullIntos.peek(); + firstPullInto.readerType = 'none'; + this._pendingPullIntos = new SimpleQueue(); + this._pendingPullIntos.push(firstPullInto); + } + } +} +Object.defineProperties(ReadableByteStreamController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + byobRequest: { enumerable: true }, + desiredSize: { enumerable: true } +}); +setFunctionName(ReadableByteStreamController.prototype.close, 'close'); +setFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue'); +setFunctionName(ReadableByteStreamController.prototype.error, 'error'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, { + value: 'ReadableByteStreamController', + configurable: true + }); +} +// Abstract operations for the ReadableByteStreamController. +function IsReadableByteStreamController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) { + return false; + } + return x instanceof ReadableByteStreamController; +} +function IsReadableStreamBYOBRequest(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) { + return false; + } + return x instanceof ReadableStreamBYOBRequest; +} +function ReadableByteStreamControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableByteStreamControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + // TODO: Test controller argument + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + return null; + }, e => { + ReadableByteStreamControllerError(controller, e); + return null; + }); +} +function ReadableByteStreamControllerClearPendingPullIntos(controller) { + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + controller._pendingPullIntos = new SimpleQueue(); +} +function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { + let done = false; + if (stream._state === 'closed') { + done = true; + } + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'default') { + ReadableStreamFulfillReadRequest(stream, filledView, done); + } + else { + ReadableStreamFulfillReadIntoRequest(stream, filledView, done); + } +} +function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { + const bytesFilled = pullIntoDescriptor.bytesFilled; + const elementSize = pullIntoDescriptor.elementSize; + return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); +} +function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { + controller._queue.push({ buffer, byteOffset, byteLength }); + controller._queueTotalSize += byteLength; +} +function ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, buffer, byteOffset, byteLength) { + let clonedChunk; + try { + clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength); + } + catch (cloneE) { + ReadableByteStreamControllerError(controller, cloneE); + throw cloneE; + } + ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength); +} +function ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstDescriptor) { + if (firstDescriptor.bytesFilled > 0) { + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, firstDescriptor.buffer, firstDescriptor.byteOffset, firstDescriptor.bytesFilled); + } + ReadableByteStreamControllerShiftPendingPullInto(controller); +} +function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { + const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); + const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; + let totalBytesToCopyRemaining = maxBytesToCopy; + let ready = false; + const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize; + const maxAlignedBytes = maxBytesFilled - remainderBytes; + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) { + totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; + ready = true; + } + const queue = controller._queue; + while (totalBytesToCopyRemaining > 0) { + const headOfQueue = queue.peek(); + const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); + const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); + if (headOfQueue.byteLength === bytesToCopy) { + queue.shift(); + } + else { + headOfQueue.byteOffset += bytesToCopy; + headOfQueue.byteLength -= bytesToCopy; + } + controller._queueTotalSize -= bytesToCopy; + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); + totalBytesToCopyRemaining -= bytesToCopy; + } + return ready; +} +function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { + pullIntoDescriptor.bytesFilled += size; +} +function ReadableByteStreamControllerHandleQueueDrain(controller) { + if (controller._queueTotalSize === 0 && controller._closeRequested) { + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(controller._controlledReadableByteStream); + } + else { + ReadableByteStreamControllerCallPullIfNeeded(controller); + } +} +function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { + if (controller._byobRequest === null) { + return; + } + controller._byobRequest._associatedReadableByteStreamController = undefined; + controller._byobRequest._view = null; + controller._byobRequest = null; +} +function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { + while (controller._pendingPullIntos.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const pullIntoDescriptor = controller._pendingPullIntos.peek(); + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + } + } +} +function ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller) { + const reader = controller._controlledReadableByteStream._reader; + while (reader._readRequests.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const readRequest = reader._readRequests.shift(); + ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest); + } +} +function ReadableByteStreamControllerPullInto(controller, view, min, readIntoRequest) { + const stream = controller._controlledReadableByteStream; + const ctor = view.constructor; + const elementSize = arrayBufferViewElementSize(ctor); + const { byteOffset, byteLength } = view; + const minimumFill = min * elementSize; + let buffer; + try { + buffer = TransferArrayBuffer(view.buffer); + } + catch (e) { + readIntoRequest._errorSteps(e); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: buffer.byteLength, + byteOffset, + byteLength, + bytesFilled: 0, + minimumFill, + elementSize, + viewConstructor: ctor, + readerType: 'byob' + }; + if (controller._pendingPullIntos.length > 0) { + controller._pendingPullIntos.push(pullIntoDescriptor); + // No ReadableByteStreamControllerCallPullIfNeeded() call since: + // - No change happens on desiredSize + // - The source has already been notified of that there's at least 1 pending read(view) + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + return; + } + if (stream._state === 'closed') { + const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); + readIntoRequest._closeSteps(emptyView); + return; + } + if (controller._queueTotalSize > 0) { + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + ReadableByteStreamControllerHandleQueueDrain(controller); + readIntoRequest._chunkSteps(filledView); + return; + } + if (controller._closeRequested) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + readIntoRequest._errorSteps(e); + return; + } + } + controller._pendingPullIntos.push(pullIntoDescriptor); + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { + if (firstDescriptor.readerType === 'none') { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const stream = controller._controlledReadableByteStream; + if (ReadableStreamHasBYOBReader(stream)) { + while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { + const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); + } + } +} +function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + return; + } + if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) { + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + return; + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; + if (remainderSize > 0) { + const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor.buffer, end - remainderSize, remainderSize); + } + pullIntoDescriptor.bytesFilled -= remainderSize; + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); +} +function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor); + } + else { + ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerShiftPendingPullInto(controller) { + const descriptor = controller._pendingPullIntos.shift(); + return descriptor; +} +function ReadableByteStreamControllerShouldCallPull(controller) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return false; + } + if (controller._closeRequested) { + return false; + } + if (!controller._started) { + return false; + } + if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; +} +function ReadableByteStreamControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; +} +// A client of ReadableByteStreamController may use these functions directly to bypass state check. +function ReadableByteStreamControllerClose(controller) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + if (controller._queueTotalSize > 0) { + controller._closeRequested = true; + return; + } + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + throw e; + } + } + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(stream); +} +function ReadableByteStreamControllerEnqueue(controller, chunk) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + const { buffer, byteOffset, byteLength } = chunk; + if (IsDetachedBuffer(buffer)) { + throw new TypeError('chunk\'s buffer is detached and so cannot be enqueued'); + } + const transferredBuffer = TransferArrayBuffer(buffer); + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (IsDetachedBuffer(firstPendingPullInto.buffer)) { + throw new TypeError('The BYOB request\'s buffer has been detached and so cannot be filled with an enqueued chunk'); + } + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer); + if (firstPendingPullInto.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto); + } + } + if (ReadableStreamHasDefaultReader(stream)) { + ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller); + if (ReadableStreamGetNumReadRequests(stream) === 0) { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + else { + if (controller._pendingPullIntos.length > 0) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); + ReadableStreamFulfillReadRequest(stream, transferredView, false); + } + } + else if (ReadableStreamHasBYOBReader(stream)) { + // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully. + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + else { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerError(controller, e) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return; + } + ReadableByteStreamControllerClearPendingPullIntos(controller); + ResetQueue(controller); + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); +} +function ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest) { + const entry = controller._queue.shift(); + controller._queueTotalSize -= entry.byteLength; + ReadableByteStreamControllerHandleQueueDrain(controller); + const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); + readRequest._chunkSteps(view); +} +function ReadableByteStreamControllerGetBYOBRequest(controller) { + if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); + const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); + SetUpReadableStreamBYOBRequest(byobRequest, controller, view); + controller._byobRequest = byobRequest; + } + return controller._byobRequest; +} +function ReadableByteStreamControllerGetDesiredSize(controller) { + const state = controller._controlledReadableByteStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; +} +function ReadableByteStreamControllerRespond(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (bytesWritten !== 0) { + throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream'); + } + } + else { + if (bytesWritten === 0) { + throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream'); + } + if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) { + throw new RangeError('bytesWritten out of range'); + } + } + firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); + ReadableByteStreamControllerRespondInternal(controller, bytesWritten); +} +function ReadableByteStreamControllerRespondWithNewView(controller, view) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (view.byteLength !== 0) { + throw new TypeError('The view\'s length must be 0 when calling respondWithNewView() on a closed stream'); + } + } + else { + if (view.byteLength === 0) { + throw new TypeError('The view\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'); + } + } + if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { + throw new RangeError('The region specified by view does not match byobRequest'); + } + if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) { + throw new RangeError('The buffer of view has different capacity than byobRequest'); + } + if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) { + throw new RangeError('The region specified by view is larger than byobRequest'); + } + const viewByteLength = view.byteLength; + firstDescriptor.buffer = TransferArrayBuffer(view.buffer); + ReadableByteStreamControllerRespondInternal(controller, viewByteLength); +} +function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { + controller._controlledReadableByteStream = stream; + controller._pullAgain = false; + controller._pulling = false; + controller._byobRequest = null; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._closeRequested = false; + controller._started = false; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._autoAllocateChunkSize = autoAllocateChunkSize; + controller._pendingPullIntos = new SimpleQueue(); + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableByteStreamControllerCallPullIfNeeded(controller); + return null; + }, r => { + ReadableByteStreamControllerError(controller, r); + return null; + }); +} +function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { + const controller = Object.create(ReadableByteStreamController.prototype); + let startAlgorithm; + let pullAlgorithm; + let cancelAlgorithm; + if (underlyingByteSource.start !== undefined) { + startAlgorithm = () => underlyingByteSource.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingByteSource.pull !== undefined) { + pullAlgorithm = () => underlyingByteSource.pull(controller); + } + else { + pullAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingByteSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingByteSource.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; + if (autoAllocateChunkSize === 0) { + throw new TypeError('autoAllocateChunkSize must be greater than 0'); + } + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); +} +function SetUpReadableStreamBYOBRequest(request, controller, view) { + request._associatedReadableByteStreamController = controller; + request._view = view; +} +// Helper functions for the ReadableStreamBYOBRequest. +function byobRequestBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`); +} +// Helper functions for the ReadableByteStreamController. +function byteStreamControllerBrandCheckException(name) { + return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`); +} + +function convertReaderOptions(options, context) { + assertDictionary(options, context); + const mode = options === null || options === void 0 ? void 0 : options.mode; + return { + mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`) + }; +} +function convertReadableStreamReaderMode(mode, context) { + mode = `${mode}`; + if (mode !== 'byob') { + throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`); + } + return mode; +} +function convertByobReadOptions(options, context) { + var _a; + assertDictionary(options, context); + const min = (_a = options === null || options === void 0 ? void 0 : options.min) !== null && _a !== void 0 ? _a : 1; + return { + min: convertUnsignedLongLongWithEnforceRange(min, `${context} has member 'min' that`) + }; +} + +// Abstract operations for the ReadableStream. +function AcquireReadableStreamBYOBReader(stream) { + return new ReadableStreamBYOBReader(stream); +} +// ReadableStream API exposed for controllers. +function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { + stream._reader._readIntoRequests.push(readIntoRequest); +} +function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { + const reader = stream._reader; + const readIntoRequest = reader._readIntoRequests.shift(); + if (done) { + readIntoRequest._closeSteps(chunk); + } + else { + readIntoRequest._chunkSteps(chunk); + } +} +function ReadableStreamGetNumReadIntoRequests(stream) { + return stream._reader._readIntoRequests.length; +} +function ReadableStreamHasBYOBReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamBYOBReader(reader)) { + return false; + } + return true; +} +/** + * A BYOB reader vended by a {@link ReadableStream}. + * + * @public + */ +class ReadableStreamBYOBReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + if (!IsReadableByteStreamController(stream._readableStreamController)) { + throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' + + 'source'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readIntoRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + read(view, rawOptions = {}) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('read')); + } + if (!ArrayBuffer.isView(view)) { + return promiseRejectedWith(new TypeError('view must be an array buffer view')); + } + if (view.byteLength === 0) { + return promiseRejectedWith(new TypeError('view must have non-zero byteLength')); + } + if (view.buffer.byteLength === 0) { + return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`)); + } + if (IsDetachedBuffer(view.buffer)) { + return promiseRejectedWith(new TypeError('view\'s buffer has been detached')); + } + let options; + try { + options = convertByobReadOptions(rawOptions, 'options'); + } + catch (e) { + return promiseRejectedWith(e); + } + const min = options.min; + if (min === 0) { + return promiseRejectedWith(new TypeError('options.min must be greater than 0')); + } + if (!isDataView(view)) { + if (min > view.length) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s length')); + } + } + else if (min > view.byteLength) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s byteLength')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readIntoRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: chunk => resolvePromise({ value: chunk, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamBYOBReader(this)) { + throw byobReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamBYOBReaderRelease(this); + } +} +Object.defineProperties(ReadableStreamBYOBReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } +}); +setFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel'); +setFunctionName(ReadableStreamBYOBReader.prototype.read, 'read'); +setFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, { + value: 'ReadableStreamBYOBReader', + configurable: true + }); +} +// Abstract operations for the readers. +function IsReadableStreamBYOBReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) { + return false; + } + return x instanceof ReadableStreamBYOBReader; +} +function ReadableStreamBYOBReaderRead(reader, view, min, readIntoRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'errored') { + readIntoRequest._errorSteps(stream._storedError); + } + else { + ReadableByteStreamControllerPullInto(stream._readableStreamController, view, min, readIntoRequest); + } +} +function ReadableStreamBYOBReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + const e = new TypeError('Reader was released'); + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); +} +function ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e) { + const readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._errorSteps(e); + }); +} +// Helper functions for the ReadableStreamBYOBReader. +function byobReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`); +} + +function ExtractHighWaterMark(strategy, defaultHWM) { + const { highWaterMark } = strategy; + if (highWaterMark === undefined) { + return defaultHWM; + } + if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { + throw new RangeError('Invalid highWaterMark'); + } + return highWaterMark; +} +function ExtractSizeAlgorithm(strategy) { + const { size } = strategy; + if (!size) { + return () => 1; + } + return size; +} + +function convertQueuingStrategy(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + const size = init === null || init === void 0 ? void 0 : init.size; + return { + highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark), + size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`) + }; +} +function convertQueuingStrategySize(fn, context) { + assertFunction(fn, context); + return chunk => convertUnrestrictedDouble(fn(chunk)); +} + +function convertUnderlyingSink(original, context) { + assertDictionary(original, context); + const abort = original === null || original === void 0 ? void 0 : original.abort; + const close = original === null || original === void 0 ? void 0 : original.close; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + const write = original === null || original === void 0 ? void 0 : original.write; + return { + abort: abort === undefined ? + undefined : + convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`), + close: close === undefined ? + undefined : + convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`), + start: start === undefined ? + undefined : + convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`), + write: write === undefined ? + undefined : + convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`), + type + }; +} +function convertUnderlyingSinkAbortCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); +} +function convertUnderlyingSinkCloseCallback(fn, original, context) { + assertFunction(fn, context); + return () => promiseCall(fn, original, []); +} +function convertUnderlyingSinkStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); +} +function convertUnderlyingSinkWriteCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); +} + +function assertWritableStream(x, context) { + if (!IsWritableStream(x)) { + throw new TypeError(`${context} is not a WritableStream.`); + } +} + +function isAbortSignal(value) { + if (typeof value !== 'object' || value === null) { + return false; + } + try { + return typeof value.aborted === 'boolean'; + } + catch (_a) { + // AbortSignal.prototype.aborted throws if its brand check fails + return false; + } +} +const supportsAbortController = typeof AbortController === 'function'; +/** + * Construct a new AbortController, if supported by the platform. + * + * @internal + */ +function createAbortController() { + if (supportsAbortController) { + return new AbortController(); + } + return undefined; +} + +/** + * A writable stream represents a destination for data, into which you can write. + * + * @public + */ +class WritableStream { + constructor(rawUnderlyingSink = {}, rawStrategy = {}) { + if (rawUnderlyingSink === undefined) { + rawUnderlyingSink = null; + } + else { + assertObject(rawUnderlyingSink, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter'); + InitializeWritableStream(this); + const type = underlyingSink.type; + if (type !== undefined) { + throw new RangeError('Invalid type is specified'); + } + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); + } + /** + * Returns whether or not the writable stream is locked to a writer. + */ + get locked() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('locked'); + } + return IsWritableStreamLocked(this); + } + /** + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort + * mechanism of the underlying sink. + * + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel + * the stream) if the stream is currently locked. + */ + abort(reason = undefined) { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('abort')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer')); + } + return WritableStreamAbort(this, reason); + } + /** + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its + * close behavior. During this time any further attempts to write will fail (without erroring the stream). + * + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + */ + close() { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('close')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer')); + } + if (WritableStreamCloseQueuedOrInFlight(this)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamClose(this); + } + /** + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream + * is locked, no other writer can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at + * the same time, which would cause the resulting written data to be unpredictable and probably useless. + */ + getWriter() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('getWriter'); + } + return AcquireWritableStreamDefaultWriter(this); + } +} +Object.defineProperties(WritableStream.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + getWriter: { enumerable: true }, + locked: { enumerable: true } +}); +setFunctionName(WritableStream.prototype.abort, 'abort'); +setFunctionName(WritableStream.prototype.close, 'close'); +setFunctionName(WritableStream.prototype.getWriter, 'getWriter'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, { + value: 'WritableStream', + configurable: true + }); +} +// Abstract operations for the WritableStream. +function AcquireWritableStreamDefaultWriter(stream) { + return new WritableStreamDefaultWriter(stream); +} +// Throws if and only if startAlgorithm throws. +function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(WritableStream.prototype); + InitializeWritableStream(stream); + const controller = Object.create(WritableStreamDefaultController.prototype); + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + return stream; +} +function InitializeWritableStream(stream) { + stream._state = 'writable'; + // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is + // 'erroring' or 'errored'. May be set to an undefined value. + stream._storedError = undefined; + stream._writer = undefined; + // Initialize to undefined first because the constructor of the controller checks this + // variable to validate the caller. + stream._writableStreamController = undefined; + // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data + // producer without waiting for the queued writes to finish. + stream._writeRequests = new SimpleQueue(); + // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents + // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here. + stream._inFlightWriteRequest = undefined; + // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer + // has been detached. + stream._closeRequest = undefined; + // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it + // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here. + stream._inFlightCloseRequest = undefined; + // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached. + stream._pendingAbortRequest = undefined; + // The backpressure signal set by the controller. + stream._backpressure = false; +} +function IsWritableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) { + return false; + } + return x instanceof WritableStream; +} +function IsWritableStreamLocked(stream) { + if (stream._writer === undefined) { + return false; + } + return true; +} +function WritableStreamAbort(stream, reason) { + var _a; + if (stream._state === 'closed' || stream._state === 'errored') { + return promiseResolvedWith(undefined); + } + stream._writableStreamController._abortReason = reason; + (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort(reason); + // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring', + // but it doesn't know that signaling abort runs author code that might have changed the state. + // Widen the type again by casting to WritableStreamState. + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseResolvedWith(undefined); + } + if (stream._pendingAbortRequest !== undefined) { + return stream._pendingAbortRequest._promise; + } + let wasAlreadyErroring = false; + if (state === 'erroring') { + wasAlreadyErroring = true; + // reason will not be used, so don't keep a reference to it. + reason = undefined; + } + const promise = newPromise((resolve, reject) => { + stream._pendingAbortRequest = { + _promise: undefined, + _resolve: resolve, + _reject: reject, + _reason: reason, + _wasAlreadyErroring: wasAlreadyErroring + }; + }); + stream._pendingAbortRequest._promise = promise; + if (!wasAlreadyErroring) { + WritableStreamStartErroring(stream, reason); + } + return promise; +} +function WritableStreamClose(stream) { + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`)); + } + const promise = newPromise((resolve, reject) => { + const closeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._closeRequest = closeRequest; + }); + const writer = stream._writer; + if (writer !== undefined && stream._backpressure && state === 'writable') { + defaultWriterReadyPromiseResolve(writer); + } + WritableStreamDefaultControllerClose(stream._writableStreamController); + return promise; +} +// WritableStream API exposed for controllers. +function WritableStreamAddWriteRequest(stream) { + const promise = newPromise((resolve, reject) => { + const writeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._writeRequests.push(writeRequest); + }); + return promise; +} +function WritableStreamDealWithRejection(stream, error) { + const state = stream._state; + if (state === 'writable') { + WritableStreamStartErroring(stream, error); + return; + } + WritableStreamFinishErroring(stream); +} +function WritableStreamStartErroring(stream, reason) { + const controller = stream._writableStreamController; + stream._state = 'erroring'; + stream._storedError = reason; + const writer = stream._writer; + if (writer !== undefined) { + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); + } + if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { + WritableStreamFinishErroring(stream); + } +} +function WritableStreamFinishErroring(stream) { + stream._state = 'errored'; + stream._writableStreamController[ErrorSteps](); + const storedError = stream._storedError; + stream._writeRequests.forEach(writeRequest => { + writeRequest._reject(storedError); + }); + stream._writeRequests = new SimpleQueue(); + if (stream._pendingAbortRequest === undefined) { + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const abortRequest = stream._pendingAbortRequest; + stream._pendingAbortRequest = undefined; + if (abortRequest._wasAlreadyErroring) { + abortRequest._reject(storedError); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const promise = stream._writableStreamController[AbortSteps](abortRequest._reason); + uponPromise(promise, () => { + abortRequest._resolve(); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }, (reason) => { + abortRequest._reject(reason); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }); +} +function WritableStreamFinishInFlightWrite(stream) { + stream._inFlightWriteRequest._resolve(undefined); + stream._inFlightWriteRequest = undefined; +} +function WritableStreamFinishInFlightWriteWithError(stream, error) { + stream._inFlightWriteRequest._reject(error); + stream._inFlightWriteRequest = undefined; + WritableStreamDealWithRejection(stream, error); +} +function WritableStreamFinishInFlightClose(stream) { + stream._inFlightCloseRequest._resolve(undefined); + stream._inFlightCloseRequest = undefined; + const state = stream._state; + if (state === 'erroring') { + // The error was too late to do anything, so it is ignored. + stream._storedError = undefined; + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._resolve(); + stream._pendingAbortRequest = undefined; + } + } + stream._state = 'closed'; + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseResolve(writer); + } +} +function WritableStreamFinishInFlightCloseWithError(stream, error) { + stream._inFlightCloseRequest._reject(error); + stream._inFlightCloseRequest = undefined; + // Never execute sink abort() after sink close(). + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._reject(error); + stream._pendingAbortRequest = undefined; + } + WritableStreamDealWithRejection(stream, error); +} +// TODO(ricea): Fix alphabetical order. +function WritableStreamCloseQueuedOrInFlight(stream) { + if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; +} +function WritableStreamHasOperationMarkedInFlight(stream) { + if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; +} +function WritableStreamMarkCloseRequestInFlight(stream) { + stream._inFlightCloseRequest = stream._closeRequest; + stream._closeRequest = undefined; +} +function WritableStreamMarkFirstWriteRequestInFlight(stream) { + stream._inFlightWriteRequest = stream._writeRequests.shift(); +} +function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { + if (stream._closeRequest !== undefined) { + stream._closeRequest._reject(stream._storedError); + stream._closeRequest = undefined; + } + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseReject(writer, stream._storedError); + } +} +function WritableStreamUpdateBackpressure(stream, backpressure) { + const writer = stream._writer; + if (writer !== undefined && backpressure !== stream._backpressure) { + if (backpressure) { + defaultWriterReadyPromiseReset(writer); + } + else { + defaultWriterReadyPromiseResolve(writer); + } + } + stream._backpressure = backpressure; +} +/** + * A default writer vended by a {@link WritableStream}. + * + * @public + */ +class WritableStreamDefaultWriter { + constructor(stream) { + assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter'); + assertWritableStream(stream, 'First parameter'); + if (IsWritableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive writing by another writer'); + } + this._ownerWritableStream = stream; + stream._writer = this; + const state = stream._state; + if (state === 'writable') { + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { + defaultWriterReadyPromiseInitialize(this); + } + else { + defaultWriterReadyPromiseInitializeAsResolved(this); + } + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'erroring') { + defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'closed') { + defaultWriterReadyPromiseInitializeAsResolved(this); + defaultWriterClosedPromiseInitializeAsResolved(this); + } + else { + const storedError = stream._storedError; + defaultWriterReadyPromiseInitializeAsRejected(this, storedError); + defaultWriterClosedPromiseInitializeAsRejected(this, storedError); + } + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the writer’s lock is released before the stream finishes closing. + */ + get closed() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. + * A producer can use this information to determine the right amount of data to write. + * + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when + * the writer’s lock is released. + */ + get desiredSize() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('desiredSize'); + } + if (this._ownerWritableStream === undefined) { + throw defaultWriterLockException('desiredSize'); + } + return WritableStreamDefaultWriterGetDesiredSize(this); + } + /** + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips + * back to zero or below, the getter will return a new promise that stays pending until the next transition. + * + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become + * rejected. + */ + get ready() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('ready')); + } + return this._readyPromise; + } + /** + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + */ + abort(reason = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('abort')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('abort')); + } + return WritableStreamDefaultWriterAbort(this, reason); + } + /** + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + */ + close() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('close')); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return promiseRejectedWith(defaultWriterLockException('close')); + } + if (WritableStreamCloseQueuedOrInFlight(stream)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamDefaultWriterClose(this); + } + /** + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from + * now on; otherwise, the writer will appear closed. + * + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents + * other producers from writing in an interleaved manner. + */ + releaseLock() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('releaseLock'); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return; + } + WritableStreamDefaultWriterRelease(this); + } + write(chunk = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('write')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + return WritableStreamDefaultWriterWrite(this, chunk); + } +} +Object.defineProperties(WritableStreamDefaultWriter.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + releaseLock: { enumerable: true }, + write: { enumerable: true }, + closed: { enumerable: true }, + desiredSize: { enumerable: true }, + ready: { enumerable: true } +}); +setFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort'); +setFunctionName(WritableStreamDefaultWriter.prototype.close, 'close'); +setFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock'); +setFunctionName(WritableStreamDefaultWriter.prototype.write, 'write'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, { + value: 'WritableStreamDefaultWriter', + configurable: true + }); +} +// Abstract operations for the WritableStreamDefaultWriter. +function IsWritableStreamDefaultWriter(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultWriter; +} +// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check. +function WritableStreamDefaultWriterAbort(writer, reason) { + const stream = writer._ownerWritableStream; + return WritableStreamAbort(stream, reason); +} +function WritableStreamDefaultWriterClose(writer) { + const stream = writer._ownerWritableStream; + return WritableStreamClose(stream); +} +function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseResolvedWith(undefined); + } + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + return WritableStreamDefaultWriterClose(writer); +} +function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { + if (writer._closedPromiseState === 'pending') { + defaultWriterClosedPromiseReject(writer, error); + } + else { + defaultWriterClosedPromiseResetToRejected(writer, error); + } +} +function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { + if (writer._readyPromiseState === 'pending') { + defaultWriterReadyPromiseReject(writer, error); + } + else { + defaultWriterReadyPromiseResetToRejected(writer, error); + } +} +function WritableStreamDefaultWriterGetDesiredSize(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (state === 'errored' || state === 'erroring') { + return null; + } + if (state === 'closed') { + return 0; + } + return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); +} +function WritableStreamDefaultWriterRelease(writer) { + const stream = writer._ownerWritableStream; + const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`); + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); + // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not + // rejected until afterwards. This means that simply testing state will not work. + WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); + stream._writer = undefined; + writer._ownerWritableStream = undefined; +} +function WritableStreamDefaultWriterWrite(writer, chunk) { + const stream = writer._ownerWritableStream; + const controller = stream._writableStreamController; + const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); + if (stream !== writer._ownerWritableStream) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + const state = stream._state; + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to')); + } + if (state === 'erroring') { + return promiseRejectedWith(stream._storedError); + } + const promise = WritableStreamAddWriteRequest(stream); + WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); + return promise; +} +const closeSentinel = {}; +/** + * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. + * + * @public + */ +class WritableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. + * + * @deprecated + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. + */ + get abortReason() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('abortReason'); + } + return this._abortReason; + } + /** + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. + */ + get signal() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('signal'); + } + if (this._abortController === undefined) { + // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`. + // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill, + // so instead we only implement support for `signal` if we find a global `AbortController` constructor. + throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported'); + } + return this._abortController.signal; + } + /** + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. + * + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the + * normal lifecycle of interactions with the underlying sink. + */ + error(e = undefined) { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('error'); + } + const state = this._controlledWritableStream._state; + if (state !== 'writable') { + // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so + // just treat it as a no-op. + return; + } + WritableStreamDefaultControllerError(this, e); + } + /** @internal */ + [AbortSteps](reason) { + const result = this._abortAlgorithm(reason); + WritableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [ErrorSteps]() { + ResetQueue(this); + } +} +Object.defineProperties(WritableStreamDefaultController.prototype, { + abortReason: { enumerable: true }, + signal: { enumerable: true }, + error: { enumerable: true } +}); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, { + value: 'WritableStreamDefaultController', + configurable: true + }); +} +// Abstract operations implementing interface required by the WritableStream. +function IsWritableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultController; +} +function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledWritableStream = stream; + stream._writableStreamController = controller; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._abortReason = undefined; + controller._abortController = createAbortController(); + controller._started = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._writeAlgorithm = writeAlgorithm; + controller._closeAlgorithm = closeAlgorithm; + controller._abortAlgorithm = abortAlgorithm; + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + const startResult = startAlgorithm(); + const startPromise = promiseResolvedWith(startResult); + uponPromise(startPromise, () => { + controller._started = true; + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, r => { + controller._started = true; + WritableStreamDealWithRejection(stream, r); + return null; + }); +} +function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { + const controller = Object.create(WritableStreamDefaultController.prototype); + let startAlgorithm; + let writeAlgorithm; + let closeAlgorithm; + let abortAlgorithm; + if (underlyingSink.start !== undefined) { + startAlgorithm = () => underlyingSink.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingSink.write !== undefined) { + writeAlgorithm = chunk => underlyingSink.write(chunk, controller); + } + else { + writeAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSink.close !== undefined) { + closeAlgorithm = () => underlyingSink.close(); + } + else { + closeAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSink.abort !== undefined) { + abortAlgorithm = reason => underlyingSink.abort(reason); + } + else { + abortAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); +} +// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls. +function WritableStreamDefaultControllerClearAlgorithms(controller) { + controller._writeAlgorithm = undefined; + controller._closeAlgorithm = undefined; + controller._abortAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; +} +function WritableStreamDefaultControllerClose(controller) { + EnqueueValueWithSize(controller, closeSentinel, 0); + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); +} +function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { + try { + return controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); + return 1; + } +} +function WritableStreamDefaultControllerGetDesiredSize(controller) { + return controller._strategyHWM - controller._queueTotalSize; +} +function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); + return; + } + const stream = controller._controlledWritableStream; + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); +} +// Abstract operations for the WritableStreamDefaultController. +function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { + const stream = controller._controlledWritableStream; + if (!controller._started) { + return; + } + if (stream._inFlightWriteRequest !== undefined) { + return; + } + const state = stream._state; + if (state === 'erroring') { + WritableStreamFinishErroring(stream); + return; + } + if (controller._queue.length === 0) { + return; + } + const value = PeekQueueValue(controller); + if (value === closeSentinel) { + WritableStreamDefaultControllerProcessClose(controller); + } + else { + WritableStreamDefaultControllerProcessWrite(controller, value); + } +} +function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { + if (controller._controlledWritableStream._state === 'writable') { + WritableStreamDefaultControllerError(controller, error); + } +} +function WritableStreamDefaultControllerProcessClose(controller) { + const stream = controller._controlledWritableStream; + WritableStreamMarkCloseRequestInFlight(stream); + DequeueValue(controller); + const sinkClosePromise = controller._closeAlgorithm(); + WritableStreamDefaultControllerClearAlgorithms(controller); + uponPromise(sinkClosePromise, () => { + WritableStreamFinishInFlightClose(stream); + return null; + }, reason => { + WritableStreamFinishInFlightCloseWithError(stream, reason); + return null; + }); +} +function WritableStreamDefaultControllerProcessWrite(controller, chunk) { + const stream = controller._controlledWritableStream; + WritableStreamMarkFirstWriteRequestInFlight(stream); + const sinkWritePromise = controller._writeAlgorithm(chunk); + uponPromise(sinkWritePromise, () => { + WritableStreamFinishInFlightWrite(stream); + const state = stream._state; + DequeueValue(controller); + if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, reason => { + if (stream._state === 'writable') { + WritableStreamDefaultControllerClearAlgorithms(controller); + } + WritableStreamFinishInFlightWriteWithError(stream, reason); + return null; + }); +} +function WritableStreamDefaultControllerGetBackpressure(controller) { + const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); + return desiredSize <= 0; +} +// A client of WritableStreamDefaultController may use these functions directly to bypass state check. +function WritableStreamDefaultControllerError(controller, error) { + const stream = controller._controlledWritableStream; + WritableStreamDefaultControllerClearAlgorithms(controller); + WritableStreamStartErroring(stream, error); +} +// Helper functions for the WritableStream. +function streamBrandCheckException$2(name) { + return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`); +} +// Helper functions for the WritableStreamDefaultController. +function defaultControllerBrandCheckException$2(name) { + return new TypeError(`WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`); +} +// Helper functions for the WritableStreamDefaultWriter. +function defaultWriterBrandCheckException(name) { + return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`); +} +function defaultWriterLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released writer'); +} +function defaultWriterClosedPromiseInitialize(writer) { + writer._closedPromise = newPromise((resolve, reject) => { + writer._closedPromise_resolve = resolve; + writer._closedPromise_reject = reject; + writer._closedPromiseState = 'pending'; + }); +} +function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseReject(writer, reason); +} +function defaultWriterClosedPromiseInitializeAsResolved(writer) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseResolve(writer); +} +function defaultWriterClosedPromiseReject(writer, reason) { + if (writer._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._closedPromise); + writer._closedPromise_reject(reason); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'rejected'; +} +function defaultWriterClosedPromiseResetToRejected(writer, reason) { + defaultWriterClosedPromiseInitializeAsRejected(writer, reason); +} +function defaultWriterClosedPromiseResolve(writer) { + if (writer._closedPromise_resolve === undefined) { + return; + } + writer._closedPromise_resolve(undefined); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'resolved'; +} +function defaultWriterReadyPromiseInitialize(writer) { + writer._readyPromise = newPromise((resolve, reject) => { + writer._readyPromise_resolve = resolve; + writer._readyPromise_reject = reject; + }); + writer._readyPromiseState = 'pending'; +} +function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseReject(writer, reason); +} +function defaultWriterReadyPromiseInitializeAsResolved(writer) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseResolve(writer); +} +function defaultWriterReadyPromiseReject(writer, reason) { + if (writer._readyPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._readyPromise); + writer._readyPromise_reject(reason); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'rejected'; +} +function defaultWriterReadyPromiseReset(writer) { + defaultWriterReadyPromiseInitialize(writer); +} +function defaultWriterReadyPromiseResetToRejected(writer, reason) { + defaultWriterReadyPromiseInitializeAsRejected(writer, reason); +} +function defaultWriterReadyPromiseResolve(writer) { + if (writer._readyPromise_resolve === undefined) { + return; + } + writer._readyPromise_resolve(undefined); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'fulfilled'; +} + +/// +function getGlobals() { + if (typeof globalThis !== 'undefined') { + return globalThis; + } + else if (typeof self !== 'undefined') { + return self; + } + else if (typeof global !== 'undefined') { + return global; + } + return undefined; +} +const globals = getGlobals(); + +/// +function isDOMExceptionConstructor(ctor) { + if (!(typeof ctor === 'function' || typeof ctor === 'object')) { + return false; + } + if (ctor.name !== 'DOMException') { + return false; + } + try { + new ctor(); + return true; + } + catch (_a) { + return false; + } +} +/** + * Support: + * - Web browsers + * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87) + */ +function getFromGlobal() { + const ctor = globals === null || globals === void 0 ? void 0 : globals.DOMException; + return isDOMExceptionConstructor(ctor) ? ctor : undefined; +} +/** + * Support: + * - All platforms + */ +function createPolyfill() { + // eslint-disable-next-line @typescript-eslint/no-shadow + const ctor = function DOMException(message, name) { + this.message = message || ''; + this.name = name || 'Error'; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + }; + setFunctionName(ctor, 'DOMException'); + ctor.prototype = Object.create(Error.prototype); + Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true }); + return ctor; +} +// eslint-disable-next-line @typescript-eslint/no-redeclare +const DOMException = getFromGlobal() || createPolyfill(); + +function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { + const reader = AcquireReadableStreamDefaultReader(source); + const writer = AcquireWritableStreamDefaultWriter(dest); + source._disturbed = true; + let shuttingDown = false; + // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown. + let currentWrite = promiseResolvedWith(undefined); + return newPromise((resolve, reject) => { + let abortAlgorithm; + if (signal !== undefined) { + abortAlgorithm = () => { + const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError'); + const actions = []; + if (!preventAbort) { + actions.push(() => { + if (dest._state === 'writable') { + return WritableStreamAbort(dest, error); + } + return promiseResolvedWith(undefined); + }); + } + if (!preventCancel) { + actions.push(() => { + if (source._state === 'readable') { + return ReadableStreamCancel(source, error); + } + return promiseResolvedWith(undefined); + }); + } + shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error); + }; + if (signal.aborted) { + abortAlgorithm(); + return; + } + signal.addEventListener('abort', abortAlgorithm); + } + // Using reader and writer, read all chunks from this and write them to dest + // - Backpressure must be enforced + // - Shutdown must stop all activity + function pipeLoop() { + return newPromise((resolveLoop, rejectLoop) => { + function next(done) { + if (done) { + resolveLoop(); + } + else { + // Use `PerformPromiseThen` instead of `uponPromise` to avoid + // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers + PerformPromiseThen(pipeStep(), next, rejectLoop); + } + } + next(false); + }); + } + function pipeStep() { + if (shuttingDown) { + return promiseResolvedWith(true); + } + return PerformPromiseThen(writer._readyPromise, () => { + return newPromise((resolveRead, rejectRead) => { + ReadableStreamDefaultReaderRead(reader, { + _chunkSteps: chunk => { + currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop); + resolveRead(false); + }, + _closeSteps: () => resolveRead(true), + _errorSteps: rejectRead + }); + }); + }); + } + // Errors must be propagated forward + isOrBecomesErrored(source, reader._closedPromise, storedError => { + if (!preventAbort) { + shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Errors must be propagated backward + isOrBecomesErrored(dest, writer._closedPromise, storedError => { + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Closing must be propagated forward + isOrBecomesClosed(source, reader._closedPromise, () => { + if (!preventClose) { + shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer)); + } + else { + shutdown(); + } + return null; + }); + // Closing must be propagated backward + if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') { + const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it'); + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed); + } + else { + shutdown(true, destClosed); + } + } + setPromiseIsHandledToTrue(pipeLoop()); + function waitForWritesToFinish() { + // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait + // for that too. + const oldCurrentWrite = currentWrite; + return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined); + } + function isOrBecomesErrored(stream, promise, action) { + if (stream._state === 'errored') { + action(stream._storedError); + } + else { + uponRejection(promise, action); + } + } + function isOrBecomesClosed(stream, promise, action) { + if (stream._state === 'closed') { + action(); + } + else { + uponFulfillment(promise, action); + } + } + function shutdownWithAction(action, originalIsError, originalError) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), doTheRest); + } + else { + doTheRest(); + } + function doTheRest() { + uponPromise(action(), () => finalize(originalIsError, originalError), newError => finalize(true, newError)); + return null; + } + } + function shutdown(isError, error) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error)); + } + else { + finalize(isError, error); + } + } + function finalize(isError, error) { + WritableStreamDefaultWriterRelease(writer); + ReadableStreamReaderGenericRelease(reader); + if (signal !== undefined) { + signal.removeEventListener('abort', abortAlgorithm); + } + if (isError) { + reject(error); + } + else { + resolve(undefined); + } + return null; + } + }); +} + +/** + * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. + * + * @public + */ +class ReadableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('desiredSize'); + } + return ReadableStreamDefaultControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('close'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits close'); + } + ReadableStreamDefaultControllerClose(this); + } + enqueue(chunk = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('enqueue'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits enqueue'); + } + return ReadableStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('error'); + } + ReadableStreamDefaultControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableStream; + if (this._queue.length > 0) { + const chunk = DequeueValue(this); + if (this._closeRequested && this._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(this); + ReadableStreamClose(stream); + } + else { + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + readRequest._chunkSteps(chunk); + } + else { + ReadableStreamAddReadRequest(stream, readRequest); + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + } + /** @internal */ + [ReleaseSteps]() { + // Do nothing. + } +} +Object.defineProperties(ReadableStreamDefaultController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + desiredSize: { enumerable: true } +}); +setFunctionName(ReadableStreamDefaultController.prototype.close, 'close'); +setFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue'); +setFunctionName(ReadableStreamDefaultController.prototype.error, 'error'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, { + value: 'ReadableStreamDefaultController', + configurable: true + }); +} +// Abstract operations for the ReadableStreamDefaultController. +function IsReadableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) { + return false; + } + return x instanceof ReadableStreamDefaultController; +} +function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + return null; + }, e => { + ReadableStreamDefaultControllerError(controller, e); + return null; + }); +} +function ReadableStreamDefaultControllerShouldCallPull(controller) { + const stream = controller._controlledReadableStream; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return false; + } + if (!controller._started) { + return false; + } + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; +} +function ReadableStreamDefaultControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; +} +// A client of ReadableStreamDefaultController may use these functions directly to bypass state check. +function ReadableStreamDefaultControllerClose(controller) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + controller._closeRequested = true; + if (controller._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } +} +function ReadableStreamDefaultControllerEnqueue(controller, chunk) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + ReadableStreamFulfillReadRequest(stream, chunk, false); + } + else { + let chunkSize; + try { + chunkSize = controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + ReadableStreamDefaultControllerError(controller, chunkSizeE); + throw chunkSizeE; + } + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + ReadableStreamDefaultControllerError(controller, enqueueE); + throw enqueueE; + } + } + ReadableStreamDefaultControllerCallPullIfNeeded(controller); +} +function ReadableStreamDefaultControllerError(controller, e) { + const stream = controller._controlledReadableStream; + if (stream._state !== 'readable') { + return; + } + ResetQueue(controller); + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); +} +function ReadableStreamDefaultControllerGetDesiredSize(controller) { + const state = controller._controlledReadableStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; +} +// This is used in the implementation of TransformStream. +function ReadableStreamDefaultControllerHasBackpressure(controller) { + if (ReadableStreamDefaultControllerShouldCallPull(controller)) { + return false; + } + return true; +} +function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { + const state = controller._controlledReadableStream._state; + if (!controller._closeRequested && state === 'readable') { + return true; + } + return false; +} +function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledReadableStream = stream; + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._started = false; + controller._closeRequested = false; + controller._pullAgain = false; + controller._pulling = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + return null; + }, r => { + ReadableStreamDefaultControllerError(controller, r); + return null; + }); +} +function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { + const controller = Object.create(ReadableStreamDefaultController.prototype); + let startAlgorithm; + let pullAlgorithm; + let cancelAlgorithm; + if (underlyingSource.start !== undefined) { + startAlgorithm = () => underlyingSource.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingSource.pull !== undefined) { + pullAlgorithm = () => underlyingSource.pull(controller); + } + else { + pullAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingSource.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); +} +// Helper functions for the ReadableStreamDefaultController. +function defaultControllerBrandCheckException$1(name) { + return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`); +} + +function ReadableStreamTee(stream, cloneForBranch2) { + if (IsReadableByteStreamController(stream._readableStreamController)) { + return ReadableByteStreamTee(stream); + } + return ReadableStreamDefaultTee(stream); +} +function ReadableStreamDefaultTee(stream, cloneForBranch2) { + const reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgain = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function pullAlgorithm() { + if (reading) { + readAgain = true; + return promiseResolvedWith(undefined); + } + reading = true; + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgain = false; + const chunk1 = chunk; + const chunk2 = chunk; + // There is no way to access the cloning code right now in the reference implementation. + // If we add one then we'll need an implementation for serializable objects. + // if (!canceled2 && cloneForBranch2) { + // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2)); + // } + if (!canceled1) { + ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgain) { + pullAlgorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableStreamDefaultControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableStreamDefaultControllerClose(branch2._readableStreamController); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + // do nothing + } + branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); + branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); + uponRejection(reader._closedPromise, (r) => { + ReadableStreamDefaultControllerError(branch1._readableStreamController, r); + ReadableStreamDefaultControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + return [branch1, branch2]; +} +function ReadableByteStreamTee(stream) { + let reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgainForBranch1 = false; + let readAgainForBranch2 = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function forwardReaderError(thisReader) { + uponRejection(thisReader._closedPromise, r => { + if (thisReader !== reader) { + return null; + } + ReadableByteStreamControllerError(branch1._readableStreamController, r); + ReadableByteStreamControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + } + function pullWithDefaultReader() { + if (IsReadableStreamBYOBReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamDefaultReader(stream); + forwardReaderError(reader); + } + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const chunk1 = chunk; + let chunk2 = chunk; + if (!canceled1 && !canceled2) { + try { + chunk2 = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(branch1._readableStreamController, cloneE); + ReadableByteStreamControllerError(branch2._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + } + if (!canceled1) { + ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableByteStreamControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableByteStreamControllerClose(branch2._readableStreamController); + } + if (branch1._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch1._readableStreamController, 0); + } + if (branch2._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch2._readableStreamController, 0); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + } + function pullWithBYOBReader(view, forBranch2) { + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamBYOBReader(stream); + forwardReaderError(reader); + } + const byobBranch = forBranch2 ? branch2 : branch1; + const otherBranch = forBranch2 ? branch1 : branch2; + const readIntoRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!otherCanceled) { + let clonedChunk; + try { + clonedChunk = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE); + ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk); + } + else if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: chunk => { + reading = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!byobCanceled) { + ReadableByteStreamControllerClose(byobBranch._readableStreamController); + } + if (!otherCanceled) { + ReadableByteStreamControllerClose(otherBranch._readableStreamController); + } + if (chunk !== undefined) { + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0); + } + } + if (!byobCanceled || !otherCanceled) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest); + } + function pull1Algorithm() { + if (reading) { + readAgainForBranch1 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, false); + } + return promiseResolvedWith(undefined); + } + function pull2Algorithm() { + if (reading) { + readAgainForBranch2 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, true); + } + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + return; + } + branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm); + branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm); + forwardReaderError(reader); + return [branch1, branch2]; +} + +function isReadableStreamLike(stream) { + return typeIsObject(stream) && typeof stream.getReader !== 'undefined'; +} + +function ReadableStreamFrom(source) { + if (isReadableStreamLike(source)) { + return ReadableStreamFromDefaultReader(source.getReader()); + } + return ReadableStreamFromIterable(source); +} +function ReadableStreamFromIterable(asyncIterable) { + let stream; + const iteratorRecord = GetIterator(asyncIterable, 'async'); + const startAlgorithm = noop; + function pullAlgorithm() { + let nextResult; + try { + nextResult = IteratorNext(iteratorRecord); + } + catch (e) { + return promiseRejectedWith(e); + } + const nextPromise = promiseResolvedWith(nextResult); + return transformPromiseWith(nextPromise, iterResult => { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object'); + } + const done = IteratorComplete(iterResult); + if (done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + const value = IteratorValue(iterResult); + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + const iterator = iteratorRecord.iterator; + let returnMethod; + try { + returnMethod = GetMethod(iterator, 'return'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (returnMethod === undefined) { + return promiseResolvedWith(undefined); + } + let returnResult; + try { + returnResult = reflectCall(returnMethod, iterator, [reason]); + } + catch (e) { + return promiseRejectedWith(e); + } + const returnPromise = promiseResolvedWith(returnResult); + return transformPromiseWith(returnPromise, iterResult => { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object'); + } + return undefined; + }); + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; +} +function ReadableStreamFromDefaultReader(reader) { + let stream; + const startAlgorithm = noop; + function pullAlgorithm() { + let readPromise; + try { + readPromise = reader.read(); + } + catch (e) { + return promiseRejectedWith(e); + } + return transformPromiseWith(readPromise, readResult => { + if (!typeIsObject(readResult)) { + throw new TypeError('The promise returned by the reader.read() method must fulfill with an object'); + } + if (readResult.done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + const value = readResult.value; + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + try { + return promiseResolvedWith(reader.cancel(reason)); + } + catch (e) { + return promiseRejectedWith(e); + } + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; +} + +function convertUnderlyingDefaultOrByteSource(source, context) { + assertDictionary(source, context); + const original = source; + const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; + const cancel = original === null || original === void 0 ? void 0 : original.cancel; + const pull = original === null || original === void 0 ? void 0 : original.pull; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + return { + autoAllocateChunkSize: autoAllocateChunkSize === undefined ? + undefined : + convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`), + cancel: cancel === undefined ? + undefined : + convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`), + pull: pull === undefined ? + undefined : + convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`), + start: start === undefined ? + undefined : + convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`), + type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`) + }; +} +function convertUnderlyingSourceCancelCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); +} +function convertUnderlyingSourcePullCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); +} +function convertUnderlyingSourceStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); +} +function convertReadableStreamType(type, context) { + type = `${type}`; + if (type !== 'bytes') { + throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`); + } + return type; +} + +function convertIteratorOptions(options, context) { + assertDictionary(options, context); + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + return { preventCancel: Boolean(preventCancel) }; +} + +function convertPipeOptions(options, context) { + assertDictionary(options, context); + const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort; + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + const preventClose = options === null || options === void 0 ? void 0 : options.preventClose; + const signal = options === null || options === void 0 ? void 0 : options.signal; + if (signal !== undefined) { + assertAbortSignal(signal, `${context} has member 'signal' that`); + } + return { + preventAbort: Boolean(preventAbort), + preventCancel: Boolean(preventCancel), + preventClose: Boolean(preventClose), + signal + }; +} +function assertAbortSignal(signal, context) { + if (!isAbortSignal(signal)) { + throw new TypeError(`${context} is not an AbortSignal.`); + } +} + +function convertReadableWritablePair(pair, context) { + assertDictionary(pair, context); + const readable = pair === null || pair === void 0 ? void 0 : pair.readable; + assertRequiredField(readable, 'readable', 'ReadableWritablePair'); + assertReadableStream(readable, `${context} has member 'readable' that`); + const writable = pair === null || pair === void 0 ? void 0 : pair.writable; + assertRequiredField(writable, 'writable', 'ReadableWritablePair'); + assertWritableStream(writable, `${context} has member 'writable' that`); + return { readable, writable }; +} + +/** + * A readable stream represents a source of data, from which you can read. + * + * @public + */ +class ReadableStream { + constructor(rawUnderlyingSource = {}, rawStrategy = {}) { + if (rawUnderlyingSource === undefined) { + rawUnderlyingSource = null; + } + else { + assertObject(rawUnderlyingSource, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter'); + InitializeReadableStream(this); + if (underlyingSource.type === 'bytes') { + if (strategy.size !== undefined) { + throw new RangeError('The strategy for a byte stream cannot have a size function'); + } + const highWaterMark = ExtractHighWaterMark(strategy, 0); + SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); + } + else { + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); + } + } + /** + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. + */ + get locked() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('locked'); + } + return IsReadableStreamLocked(this); + } + /** + * Cancels the stream, signaling a loss of interest in the stream by a consumer. + * + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} + * method, which might or might not use it. + */ + cancel(reason = undefined) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('cancel')); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader')); + } + return ReadableStreamCancel(this, reason); + } + getReader(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('getReader'); + } + const options = convertReaderOptions(rawOptions, 'First parameter'); + if (options.mode === undefined) { + return AcquireReadableStreamDefaultReader(this); + } + return AcquireReadableStreamBYOBReader(this); + } + pipeThrough(rawTransform, rawOptions = {}) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('pipeThrough'); + } + assertRequiredArgument(rawTransform, 1, 'pipeThrough'); + const transform = convertReadableWritablePair(rawTransform, 'First parameter'); + const options = convertPipeOptions(rawOptions, 'Second parameter'); + if (IsReadableStreamLocked(this)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream'); + } + if (IsWritableStreamLocked(transform.writable)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream'); + } + const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + setPromiseIsHandledToTrue(promise); + return transform.readable; + } + pipeTo(destination, rawOptions = {}) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('pipeTo')); + } + if (destination === undefined) { + return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`); + } + if (!IsWritableStream(destination)) { + return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)); + } + let options; + try { + options = convertPipeOptions(rawOptions, 'Second parameter'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')); + } + if (IsWritableStreamLocked(destination)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')); + } + return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + } + /** + * Tees this readable stream, returning a two-element array containing the two resulting branches as + * new {@link ReadableStream} instances. + * + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be + * propagated to the stream's underlying source. + * + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, + * this could allow interference between the two branches. + */ + tee() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('tee'); + } + const branches = ReadableStreamTee(this); + return CreateArrayFromList(branches); + } + values(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('values'); + } + const options = convertIteratorOptions(rawOptions, 'First parameter'); + return AcquireReadableStreamAsyncIterator(this, options.preventCancel); + } + [SymbolAsyncIterator](options) { + // Stub implementation, overridden below + return this.values(options); + } + /** + * Creates a new ReadableStream wrapping the provided iterable or async iterable. + * + * This can be used to adapt various kinds of objects into a readable stream, + * such as an array, an async generator, or a Node.js readable stream. + */ + static from(asyncIterable) { + return ReadableStreamFrom(asyncIterable); + } +} +Object.defineProperties(ReadableStream, { + from: { enumerable: true } +}); +Object.defineProperties(ReadableStream.prototype, { + cancel: { enumerable: true }, + getReader: { enumerable: true }, + pipeThrough: { enumerable: true }, + pipeTo: { enumerable: true }, + tee: { enumerable: true }, + values: { enumerable: true }, + locked: { enumerable: true } +}); +setFunctionName(ReadableStream.from, 'from'); +setFunctionName(ReadableStream.prototype.cancel, 'cancel'); +setFunctionName(ReadableStream.prototype.getReader, 'getReader'); +setFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough'); +setFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo'); +setFunctionName(ReadableStream.prototype.tee, 'tee'); +setFunctionName(ReadableStream.prototype.values, 'values'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, { + value: 'ReadableStream', + configurable: true + }); +} +Object.defineProperty(ReadableStream.prototype, SymbolAsyncIterator, { + value: ReadableStream.prototype.values, + writable: true, + configurable: true +}); +// Abstract operations for the ReadableStream. +// Throws if and only if startAlgorithm throws. +function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableStreamDefaultController.prototype); + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + return stream; +} +// Throws if and only if startAlgorithm throws. +function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableByteStreamController.prototype); + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined); + return stream; +} +function InitializeReadableStream(stream) { + stream._state = 'readable'; + stream._reader = undefined; + stream._storedError = undefined; + stream._disturbed = false; +} +function IsReadableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) { + return false; + } + return x instanceof ReadableStream; +} +function IsReadableStreamLocked(stream) { + if (stream._reader === undefined) { + return false; + } + return true; +} +// ReadableStream API exposed for controllers. +function ReadableStreamCancel(stream, reason) { + stream._disturbed = true; + if (stream._state === 'closed') { + return promiseResolvedWith(undefined); + } + if (stream._state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + ReadableStreamClose(stream); + const reader = stream._reader; + if (reader !== undefined && IsReadableStreamBYOBReader(reader)) { + const readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._closeSteps(undefined); + }); + } + const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); + return transformPromiseWith(sourceCancelPromise, noop); +} +function ReadableStreamClose(stream) { + stream._state = 'closed'; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseResolve(reader); + if (IsReadableStreamDefaultReader(reader)) { + const readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(readRequest => { + readRequest._closeSteps(); + }); + } +} +function ReadableStreamError(stream, e) { + stream._state = 'errored'; + stream._storedError = e; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseReject(reader, e); + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamDefaultReaderErrorReadRequests(reader, e); + } + else { + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); + } +} +// Helper functions for the ReadableStream. +function streamBrandCheckException$1(name) { + return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`); +} + +function convertQueuingStrategyInit(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit'); + return { + highWaterMark: convertUnrestrictedDouble(highWaterMark) + }; +} + +// The size function must not have a prototype property nor be a constructor +const byteLengthSizeFunction = (chunk) => { + return chunk.byteLength; +}; +setFunctionName(byteLengthSizeFunction, 'size'); +/** + * A queuing strategy that counts the number of bytes in each chunk. + * + * @public + */ +class ByteLengthQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('highWaterMark'); + } + return this._byteLengthQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by returning the value of its `byteLength` property. + */ + get size() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('size'); + } + return byteLengthSizeFunction; + } +} +Object.defineProperties(ByteLengthQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } +}); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, { + value: 'ByteLengthQueuingStrategy', + configurable: true + }); +} +// Helper functions for the ByteLengthQueuingStrategy. +function byteLengthBrandCheckException(name) { + return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`); +} +function IsByteLengthQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof ByteLengthQueuingStrategy; +} + +// The size function must not have a prototype property nor be a constructor +const countSizeFunction = () => { + return 1; +}; +setFunctionName(countSizeFunction, 'size'); +/** + * A queuing strategy that counts the number of chunks. + * + * @public + */ +class CountQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'CountQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._countQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('highWaterMark'); + } + return this._countQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by always returning 1. + * This ensures that the total queue size is a count of the number of chunks in the queue. + */ + get size() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('size'); + } + return countSizeFunction; + } +} +Object.defineProperties(CountQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } +}); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, { + value: 'CountQueuingStrategy', + configurable: true + }); +} +// Helper functions for the CountQueuingStrategy. +function countBrandCheckException(name) { + return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`); +} +function IsCountQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof CountQueuingStrategy; +} + +function convertTransformer(original, context) { + assertDictionary(original, context); + const cancel = original === null || original === void 0 ? void 0 : original.cancel; + const flush = original === null || original === void 0 ? void 0 : original.flush; + const readableType = original === null || original === void 0 ? void 0 : original.readableType; + const start = original === null || original === void 0 ? void 0 : original.start; + const transform = original === null || original === void 0 ? void 0 : original.transform; + const writableType = original === null || original === void 0 ? void 0 : original.writableType; + return { + cancel: cancel === undefined ? + undefined : + convertTransformerCancelCallback(cancel, original, `${context} has member 'cancel' that`), + flush: flush === undefined ? + undefined : + convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`), + readableType, + start: start === undefined ? + undefined : + convertTransformerStartCallback(start, original, `${context} has member 'start' that`), + transform: transform === undefined ? + undefined : + convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`), + writableType + }; +} +function convertTransformerFlushCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); +} +function convertTransformerStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); +} +function convertTransformerTransformCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); +} +function convertTransformerCancelCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); +} + +// Class TransformStream +/** + * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, + * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. + * In a manner specific to the transform stream in question, writes to the writable side result in new data being + * made available for reading from the readable side. + * + * @public + */ +class TransformStream { + constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) { + if (rawTransformer === undefined) { + rawTransformer = null; + } + const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter'); + const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter'); + const transformer = convertTransformer(rawTransformer, 'First parameter'); + if (transformer.readableType !== undefined) { + throw new RangeError('Invalid readableType specified'); + } + if (transformer.writableType !== undefined) { + throw new RangeError('Invalid writableType specified'); + } + const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); + const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); + const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); + const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); + let startPromise_resolve; + const startPromise = newPromise(resolve => { + startPromise_resolve = resolve; + }); + InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); + if (transformer.start !== undefined) { + startPromise_resolve(transformer.start(this._transformStreamController)); + } + else { + startPromise_resolve(undefined); + } + } + /** + * The readable side of the transform stream. + */ + get readable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('readable'); + } + return this._readable; + } + /** + * The writable side of the transform stream. + */ + get writable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('writable'); + } + return this._writable; + } +} +Object.defineProperties(TransformStream.prototype, { + readable: { enumerable: true }, + writable: { enumerable: true } +}); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, { + value: 'TransformStream', + configurable: true + }); +} +function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { + function startAlgorithm() { + return startPromise; + } + function writeAlgorithm(chunk) { + return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); + } + function abortAlgorithm(reason) { + return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); + } + function closeAlgorithm() { + return TransformStreamDefaultSinkCloseAlgorithm(stream); + } + stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); + function pullAlgorithm() { + return TransformStreamDefaultSourcePullAlgorithm(stream); + } + function cancelAlgorithm(reason) { + return TransformStreamDefaultSourceCancelAlgorithm(stream, reason); + } + stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure. + stream._backpressure = undefined; + stream._backpressureChangePromise = undefined; + stream._backpressureChangePromise_resolve = undefined; + TransformStreamSetBackpressure(stream, true); + stream._transformStreamController = undefined; +} +function IsTransformStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) { + return false; + } + return x instanceof TransformStream; +} +// This is a no-op if both sides are already errored. +function TransformStreamError(stream, e) { + ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e); + TransformStreamErrorWritableAndUnblockWrite(stream, e); +} +function TransformStreamErrorWritableAndUnblockWrite(stream, e) { + TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); + WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e); + TransformStreamUnblockWrite(stream); +} +function TransformStreamUnblockWrite(stream) { + if (stream._backpressure) { + // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure() + // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time + // _backpressure is set. + TransformStreamSetBackpressure(stream, false); + } +} +function TransformStreamSetBackpressure(stream, backpressure) { + // Passes also when called during construction. + if (stream._backpressureChangePromise !== undefined) { + stream._backpressureChangePromise_resolve(); + } + stream._backpressureChangePromise = newPromise(resolve => { + stream._backpressureChangePromise_resolve = resolve; + }); + stream._backpressure = backpressure; +} +// Class TransformStreamDefaultController +/** + * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. + * + * @public + */ +class TransformStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. + */ + get desiredSize() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('desiredSize'); + } + const readableController = this._controlledTransformStream._readable._readableStreamController; + return ReadableStreamDefaultControllerGetDesiredSize(readableController); + } + enqueue(chunk = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('enqueue'); + } + TransformStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors both the readable side and the writable side of the controlled transform stream, making all future + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. + */ + error(reason = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('error'); + } + TransformStreamDefaultControllerError(this, reason); + } + /** + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the + * transformer only needs to consume a portion of the chunks written to the writable side. + */ + terminate() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('terminate'); + } + TransformStreamDefaultControllerTerminate(this); + } +} +Object.defineProperties(TransformStreamDefaultController.prototype, { + enqueue: { enumerable: true }, + error: { enumerable: true }, + terminate: { enumerable: true }, + desiredSize: { enumerable: true } +}); +setFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue'); +setFunctionName(TransformStreamDefaultController.prototype.error, 'error'); +setFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, { + value: 'TransformStreamDefaultController', + configurable: true + }); +} +// Transform Stream Default Controller Abstract Operations +function IsTransformStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) { + return false; + } + return x instanceof TransformStreamDefaultController; +} +function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm) { + controller._controlledTransformStream = stream; + stream._transformStreamController = controller; + controller._transformAlgorithm = transformAlgorithm; + controller._flushAlgorithm = flushAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._finishPromise = undefined; + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; +} +function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { + const controller = Object.create(TransformStreamDefaultController.prototype); + let transformAlgorithm; + let flushAlgorithm; + let cancelAlgorithm; + if (transformer.transform !== undefined) { + transformAlgorithm = chunk => transformer.transform(chunk, controller); + } + else { + transformAlgorithm = chunk => { + try { + TransformStreamDefaultControllerEnqueue(controller, chunk); + return promiseResolvedWith(undefined); + } + catch (transformResultE) { + return promiseRejectedWith(transformResultE); + } + }; + } + if (transformer.flush !== undefined) { + flushAlgorithm = () => transformer.flush(controller); + } + else { + flushAlgorithm = () => promiseResolvedWith(undefined); + } + if (transformer.cancel !== undefined) { + cancelAlgorithm = reason => transformer.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm); +} +function TransformStreamDefaultControllerClearAlgorithms(controller) { + controller._transformAlgorithm = undefined; + controller._flushAlgorithm = undefined; + controller._cancelAlgorithm = undefined; +} +function TransformStreamDefaultControllerEnqueue(controller, chunk) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { + throw new TypeError('Readable side is not in a state that permits enqueue'); + } + // We throttle transform invocations based on the backpressure of the ReadableStream, but we still + // accept TransformStreamDefaultControllerEnqueue() calls. + try { + ReadableStreamDefaultControllerEnqueue(readableController, chunk); + } + catch (e) { + // This happens when readableStrategy.size() throws. + TransformStreamErrorWritableAndUnblockWrite(stream, e); + throw stream._readable._storedError; + } + const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); + if (backpressure !== stream._backpressure) { + TransformStreamSetBackpressure(stream, true); + } +} +function TransformStreamDefaultControllerError(controller, e) { + TransformStreamError(controller._controlledTransformStream, e); +} +function TransformStreamDefaultControllerPerformTransform(controller, chunk) { + const transformPromise = controller._transformAlgorithm(chunk); + return transformPromiseWith(transformPromise, undefined, r => { + TransformStreamError(controller._controlledTransformStream, r); + throw r; + }); +} +function TransformStreamDefaultControllerTerminate(controller) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + ReadableStreamDefaultControllerClose(readableController); + const error = new TypeError('TransformStream terminated'); + TransformStreamErrorWritableAndUnblockWrite(stream, error); +} +// TransformStreamDefaultSink Algorithms +function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { + const controller = stream._transformStreamController; + if (stream._backpressure) { + const backpressureChangePromise = stream._backpressureChangePromise; + return transformPromiseWith(backpressureChangePromise, () => { + const writable = stream._writable; + const state = writable._state; + if (state === 'erroring') { + throw writable._storedError; + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + }); + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); +} +function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + const readable = stream._readable; + // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally, + // we don't run the _cancelAlgorithm again. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, () => { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerError(readable._readableStreamController, reason); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; +} +function TransformStreamDefaultSinkCloseAlgorithm(stream) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + const readable = stream._readable; + // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally, + // we don't also run the _cancelAlgorithm. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const flushPromise = controller._flushAlgorithm(); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(flushPromise, () => { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerClose(readable._readableStreamController); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; +} +// TransformStreamDefaultSource Algorithms +function TransformStreamDefaultSourcePullAlgorithm(stream) { + // Invariant. Enforced by the promises returned by start() and pull(). + TransformStreamSetBackpressure(stream, false); + // Prevent the next pull() call until there is backpressure. + return stream._backpressureChangePromise; +} +function TransformStreamDefaultSourceCancelAlgorithm(stream, reason) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._writable cannot change after construction, so caching it across a call to user code is safe. + const writable = stream._writable; + // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or + // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the + // _flushAlgorithm. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, () => { + if (writable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, writable._storedError); + } + else { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; +} +// Helper functions for the TransformStreamDefaultController. +function defaultControllerBrandCheckException(name) { + return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`); +} +function defaultControllerFinishPromiseResolve(controller) { + if (controller._finishPromise_resolve === undefined) { + return; + } + controller._finishPromise_resolve(); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; +} +function defaultControllerFinishPromiseReject(controller, reason) { + if (controller._finishPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(controller._finishPromise); + controller._finishPromise_reject(reason); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; +} +// Helper functions for the TransformStream. +function streamBrandCheckException(name) { + return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`); +} + +export { ByteLengthQueuingStrategy, CountQueuingStrategy, ReadableByteStreamController, ReadableStream, ReadableStreamBYOBReader, ReadableStreamBYOBRequest, ReadableStreamDefaultController, ReadableStreamDefaultReader, TransformStream, TransformStreamDefaultController, WritableStream, WritableStreamDefaultController, WritableStreamDefaultWriter }; +//# sourceMappingURL=ponyfill.es2018.mjs.map diff --git a/backend/node_modules/web-streams-polyfill/dist/ponyfill.es2018.mjs.map b/backend/node_modules/web-streams-polyfill/dist/ponyfill.es2018.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..0a16b7c463940a805f3dfd90bcad92369095b2ad --- /dev/null +++ b/backend/node_modules/web-streams-polyfill/dist/ponyfill.es2018.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"ponyfill.es2018.mjs","sources":["../src/utils.ts","../src/lib/helpers/miscellaneous.ts","../src/lib/helpers/webidl.ts","../src/lib/simple-queue.ts","../src/lib/abstract-ops/internal-methods.ts","../src/lib/readable-stream/generic-reader.ts","../src/stub/number-isfinite.ts","../src/stub/math-trunc.ts","../src/lib/validators/basic.ts","../src/lib/validators/readable-stream.ts","../src/lib/readable-stream/default-reader.ts","../src/target/es2018/stub/async-iterator-prototype.ts","../src/lib/readable-stream/async-iterator.ts","../src/stub/number-isnan.ts","../src/lib/abstract-ops/ecmascript.ts","../src/lib/abstract-ops/miscellaneous.ts","../src/lib/abstract-ops/queue-with-sizes.ts","../src/lib/helpers/array-buffer-view.ts","../src/lib/readable-stream/byte-stream-controller.ts","../src/lib/validators/reader-options.ts","../src/lib/readable-stream/byob-reader.ts","../src/lib/abstract-ops/queuing-strategy.ts","../src/lib/validators/queuing-strategy.ts","../src/lib/validators/underlying-sink.ts","../src/lib/validators/writable-stream.ts","../src/lib/abort-signal.ts","../src/lib/writable-stream.ts","../src/globals.ts","../src/stub/dom-exception.ts","../src/lib/readable-stream/pipe.ts","../src/lib/readable-stream/default-controller.ts","../src/lib/readable-stream/tee.ts","../src/lib/readable-stream/readable-stream-like.ts","../src/lib/readable-stream/from.ts","../src/lib/validators/underlying-source.ts","../src/lib/validators/iterator-options.ts","../src/lib/validators/pipe-options.ts","../src/lib/validators/readable-writable-pair.ts","../src/lib/readable-stream.ts","../src/lib/validators/queuing-strategy-init.ts","../src/lib/byte-length-queuing-strategy.ts","../src/lib/count-queuing-strategy.ts","../src/lib/validators/transformer.ts","../src/lib/transform-stream.ts"],"sourcesContent":["export function noop(): undefined {\n return undefined;\n}\n","import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n\nexport function setFunctionName(fn: Function, name: string): void {\n try {\n Object.defineProperty(fn, 'name', {\n value: name,\n configurable: true\n });\n } catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n }\n}\n","import { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\n// https://webidl.spec.whatwg.org/#a-new-promise\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-resolved-with\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return newPromise(resolve => resolve(value));\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-rejected-with\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\n// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned\n// from that handler. To prevent this, return null instead of void from all handlers.\n// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => null | PromiseLike,\n onRejected?: (reason: any) => null | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => null | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => null | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nlet _queueMicrotask: (callback: () => void) => void = callback => {\n if (typeof queueMicrotask === 'function') {\n _queueMicrotask = queueMicrotask;\n } else {\n const resolvedPromise = promiseResolvedWith(undefined);\n _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb);\n }\n return _queueMicrotask(callback);\n};\n\nexport { _queueMicrotask as queueMicrotask };\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n","import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n","export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\nexport const ReleaseSteps = Symbol('[[ReleaseSteps]]');\n","import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, type ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\nimport { ReleaseSteps } from '../abstract-ops/internal-methods';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n assert(stream._reader === reader);\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n stream._readableStreamController[ReleaseSteps]();\n\n stream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n","import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n","import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamDefaultReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamDefaultReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\nexport function ReadableStreamDefaultReaderRelease(reader: ReadableStreamDefaultReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n}\n\nexport function ReadableStreamDefaultReaderErrorReadRequests(reader: ReadableStreamDefaultReader, e: any) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n","/// \n\n/* eslint-disable @typescript-eslint/no-empty-function */\nexport const AsyncIteratorPrototype: AsyncIterable =\n Object.getPrototypeOf(Object.getPrototypeOf(async function* (): AsyncIterableIterator {}).prototype);\n","/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadableStreamDefaultReadResult,\n type ReadRequest\n} from './default-reader';\nimport { ReadableStreamReaderGenericCancel, ReadableStreamReaderGenericRelease } from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterableIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ninterface ReadableStreamAsyncIteratorInstance extends ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nObject.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n","import { reflectCall } from 'lib/helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport assert from '../../stub/assert';\n\ndeclare global {\n interface ArrayBuffer {\n readonly detached: boolean;\n\n transfer(): ArrayBuffer;\n }\n\n function structuredClone(value: T, options: { transfer: ArrayBuffer[] }): T;\n}\n\nexport function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\nexport let TransferArrayBuffer = (O: ArrayBuffer): ArrayBuffer => {\n if (typeof O.transfer === 'function') {\n TransferArrayBuffer = buffer => buffer.transfer();\n } else if (typeof structuredClone === 'function') {\n TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] });\n } else {\n // Not implemented correctly\n TransferArrayBuffer = buffer => buffer;\n }\n return TransferArrayBuffer(O);\n};\n\nexport function CanTransferArrayBuffer(O: ArrayBuffer): boolean {\n return !IsDetachedBuffer(O);\n}\n\nexport let IsDetachedBuffer = (O: ArrayBuffer): boolean => {\n if (typeof O.detached === 'boolean') {\n IsDetachedBuffer = buffer => buffer.detached;\n } else {\n // Not implemented correctly\n IsDetachedBuffer = buffer => buffer.byteLength === 0;\n }\n return IsDetachedBuffer(O);\n};\n\nexport function ArrayBufferSlice(buffer: ArrayBuffer, begin: number, end: number): ArrayBuffer {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n\nexport type MethodName = {\n [P in keyof T]: T[P] extends Function | undefined ? P : never;\n}[keyof T];\n\nexport function GetMethod>(receiver: T, prop: K): T[K] | undefined {\n const func = receiver[prop];\n if (func === undefined || func === null) {\n return undefined;\n }\n if (typeof func !== 'function') {\n throw new TypeError(`${String(prop)} is not a function`);\n }\n return func;\n}\n\nexport interface SyncIteratorRecord {\n iterator: Iterator,\n nextMethod: Iterator['next'],\n done: boolean;\n}\n\nexport interface AsyncIteratorRecord {\n iterator: AsyncIterator,\n nextMethod: AsyncIterator['next'],\n done: boolean;\n}\n\nexport type SyncOrAsyncIteratorRecord = SyncIteratorRecord | AsyncIteratorRecord;\n\nexport function CreateAsyncFromSyncIterator(syncIteratorRecord: SyncIteratorRecord): AsyncIteratorRecord {\n // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%,\n // we use yield* inside an async generator function to achieve the same result.\n\n // Wrap the sync iterator inside a sync iterable, so we can use it with yield*.\n const syncIterable = {\n [Symbol.iterator]: () => syncIteratorRecord.iterator\n };\n // Create an async generator function and immediately invoke it.\n const asyncIterator = (async function* () {\n return yield* syncIterable;\n }());\n // Return as an async iterator record.\n const nextMethod = asyncIterator.next;\n return { iterator: asyncIterator, nextMethod, done: false };\n}\n\n// Aligns with core-js/modules/es.symbol.async-iterator.js\nexport const SymbolAsyncIterator: (typeof Symbol)['asyncIterator'] =\n Symbol.asyncIterator ??\n Symbol.for?.('Symbol.asyncIterator') ??\n '@@asyncIterator';\n\nexport type SyncOrAsyncIterable = Iterable | AsyncIterable;\nexport type SyncOrAsyncIteratorMethod = () => (Iterator | AsyncIterator);\n\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint: 'async',\n method?: SyncOrAsyncIteratorMethod\n): AsyncIteratorRecord;\nfunction GetIterator(\n obj: Iterable,\n hint: 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncIteratorRecord;\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint = 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncOrAsyncIteratorRecord {\n assert(hint === 'sync' || hint === 'async');\n if (method === undefined) {\n if (hint === 'async') {\n method = GetMethod(obj as AsyncIterable, SymbolAsyncIterator);\n if (method === undefined) {\n const syncMethod = GetMethod(obj as Iterable, Symbol.iterator);\n const syncIteratorRecord = GetIterator(obj as Iterable, 'sync', syncMethod);\n return CreateAsyncFromSyncIterator(syncIteratorRecord);\n }\n } else {\n method = GetMethod(obj as Iterable, Symbol.iterator);\n }\n }\n if (method === undefined) {\n throw new TypeError('The object is not iterable');\n }\n const iterator = reflectCall(method, obj, []);\n if (!typeIsObject(iterator)) {\n throw new TypeError('The iterator method must return an object');\n }\n const nextMethod = iterator.next;\n return { iterator, nextMethod, done: false } as SyncOrAsyncIteratorRecord;\n}\n\nexport { GetIterator };\n\nexport function IteratorNext(iteratorRecord: AsyncIteratorRecord): Promise> {\n const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []);\n if (!typeIsObject(result)) {\n throw new TypeError('The iterator.next() method must return an object');\n }\n return result;\n}\n\nexport function IteratorComplete(\n iterResult: IteratorResult\n): iterResult is IteratorReturnResult {\n assert(typeIsObject(iterResult));\n return Boolean(iterResult.done);\n}\n\nexport function IteratorValue(iterResult: IteratorYieldResult): T {\n assert(typeIsObject(iterResult));\n return iterResult.value;\n}\n","import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: NonShared): NonShared {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer) as NonShared;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n","export type TypedArray =\n | Int8Array\n | Uint8Array\n | Uint8ClampedArray\n | Int16Array\n | Uint16Array\n | Int32Array\n | Uint32Array\n | Float32Array\n | Float64Array;\n\nexport type NonShared = T & {\n buffer: ArrayBuffer;\n}\n\nexport interface ArrayBufferViewConstructor {\n new(buffer: ArrayBuffer, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n}\n\nexport interface TypedArrayConstructor extends ArrayBufferViewConstructor {\n readonly BYTES_PER_ELEMENT: number;\n}\n\nexport type DataViewConstructor = ArrayBufferViewConstructor;\n\nfunction isDataViewConstructor(ctor: Function): ctor is DataViewConstructor {\n return ctor === DataView;\n}\n\nexport function isDataView(view: ArrayBufferView): view is DataView {\n return isDataViewConstructor(view.constructor);\n}\n\nexport function arrayBufferViewElementSize(ctor: ArrayBufferViewConstructor): number {\n if (isDataViewConstructor(ctor)) {\n return 1;\n }\n return (ctor as unknown as TypedArrayConstructor).BYTES_PER_ELEMENT;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n IsReadableStreamDefaultReader,\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n type ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n type ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n type ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport type { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\nimport {\n type ArrayBufferViewConstructor,\n arrayBufferViewElementSize,\n type NonShared,\n type TypedArrayConstructor\n} from '../helpers/array-buffer-view';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: NonShared | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: NonShared): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond');\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBuffer;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor = NonShared> =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: TypedArrayConstructor;\n readerType: 'default' | 'none';\n}\n\ninterface BYOBPullIntoDescriptor = NonShared> {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob' | 'none';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: NonShared): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest>): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n minimumFill: 1,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n if (this._pendingPullIntos.length > 0) {\n const firstPullInto = this._pendingPullIntos.peek();\n firstPullInto.readerType = 'none';\n\n this._pendingPullIntos = new SimpleQueue();\n this._pendingPullIntos.push(firstPullInto);\n }\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableByteStreamController.prototype.close, 'close');\nsetFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableByteStreamController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor>(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n assert(pullIntoDescriptor.readerType !== 'none');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as NonShared, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor>(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n let clonedChunk;\n try {\n clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength);\n } catch (cloneE) {\n ReadableByteStreamControllerError(controller, cloneE);\n throw cloneE;\n }\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength);\n}\n\nfunction ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.readerType === 'none');\n if (firstDescriptor.bytesFilled > 0) {\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n firstDescriptor.buffer,\n firstDescriptor.byteOffset,\n firstDescriptor.bytesFilled\n );\n }\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize;\n const maxAlignedBytes = maxBytesFilled - remainderBytes;\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n assert(pullIntoDescriptor.readerType !== 'none');\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nfunction ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller: ReadableByteStreamController) {\n const reader = controller._controlledReadableByteStream._reader;\n assert(IsReadableStreamDefaultReader(reader));\n while (reader._readRequests.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n const readRequest = reader._readRequests.shift();\n ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest);\n }\n}\n\nexport function ReadableByteStreamControllerPullInto>(\n controller: ReadableByteStreamController,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n const elementSize = arrayBufferViewElementSize(ctor);\n\n const { byteOffset, byteLength } = view;\n\n const minimumFill = min * elementSize;\n assert(minimumFill >= elementSize && minimumFill <= byteLength);\n assert(minimumFill % elementSize === 0);\n\n let buffer: ArrayBuffer;\n try {\n buffer = TransferArrayBuffer(view.buffer);\n } catch (e) {\n readIntoRequest._errorSteps(e);\n return;\n }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset,\n byteLength,\n bytesFilled: 0,\n minimumFill,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled % firstDescriptor.elementSize === 0);\n\n if (firstDescriptor.readerType === 'none') {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n return;\n }\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) {\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n pullIntoDescriptor.buffer,\n end - remainderSize,\n remainderSize\n );\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(\n controller: ReadableByteStreamController,\n chunk: NonShared\n) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const { buffer, byteOffset, byteLength } = chunk;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n if (firstPendingPullInto.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto);\n }\n }\n\n if (ReadableStreamHasDefaultReader(stream)) {\n ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller);\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView as NonShared, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerFillReadRequestFromQueue(\n controller: ReadableByteStreamController,\n readRequest: ReadRequest>\n) {\n assert(controller._queueTotalSize > 0);\n\n const entry = controller._queue.shift();\n controller._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n readRequest._chunkSteps(view as NonShared);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view as NonShared);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: NonShared) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: NonShared) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n","import { assertDictionary, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n\nexport function convertByobReadOptions(\n options: ReadableStreamBYOBReaderReadOptions | null | undefined,\n context: string\n): ValidatedReadableStreamBYOBReaderReadOptions {\n assertDictionary(options, context);\n const min = options?.min ?? 1;\n return {\n min: convertUnsignedLongLongWithEnforceRange(\n min,\n `${context} has member 'min' that`\n )\n };\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, type ReadableByteStream, type ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from './reader-options';\nimport { convertByobReadOptions } from '../validators/reader-options';\nimport { isDataView, type NonShared, type TypedArray } from '../helpers/array-buffer-view';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream as ReadableStream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest>(\n stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest\n): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest> {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(\n view: T,\n options?: ReadableStreamBYOBReaderReadOptions\n ): Promise>;\n read>(\n view: T,\n rawOptions: ReadableStreamBYOBReaderReadOptions | null | undefined = {}\n ): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n let options: ValidatedReadableStreamBYOBReaderReadOptions;\n try {\n options = convertByobReadOptions(rawOptions, 'options');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const min = options.min;\n if (min === 0) {\n return promiseRejectedWith(new TypeError('options.min must be greater than 0'));\n }\n if (!isDataView(view)) {\n if (min > (view as unknown as TypedArray).length) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s length'));\n }\n } else if (min > view.byteLength) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s byteLength'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamBYOBReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamBYOBReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead>(\n reader: ReadableStreamBYOBReader,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n min,\n readIntoRequest\n );\n }\n}\n\nexport function ReadableStreamBYOBReaderRelease(reader: ReadableStreamBYOBReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n}\n\nexport function ReadableStreamBYOBReaderErrorReadIntoRequests(reader: ReadableStreamBYOBReader, e: any) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n","/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * If aborted, returns the reason for aborting.\n */\n readonly reason?: any;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(reason?: any): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n type QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { type AbortController, type AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(WritableStream.prototype.abort, 'abort');\nsetFunctionName(WritableStream.prototype.close, 'close');\nsetFunctionName(WritableStream.prototype.getWriter, 'getWriter');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight\n};\n\nexport type {\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort(reason);\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nsetFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort');\nsetFunctionName(WritableStreamDefaultWriter.prototype.close, 'close');\nsetFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock');\nsetFunctionName(WritableStreamDefaultWriter.prototype.write, 'write');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n return null;\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let writeAlgorithm: (chunk: W) => Promise;\n let closeAlgorithm: () => Promise;\n let abortAlgorithm: (reason: any) => Promise;\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n } else {\n writeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n } else {\n closeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n } else {\n abortAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n return null;\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n","/// \n\nfunction getGlobals(): typeof globalThis | undefined {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n } else if (typeof self !== 'undefined') {\n return self;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n","/// \nimport { globals } from '../globals';\nimport { setFunctionName } from '../lib/helpers/miscellaneous';\n\ninterface DOMException extends Error {\n name: string;\n message: string;\n}\n\ntype DOMExceptionConstructor = new (message?: string, name?: string) => DOMException;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n if ((ctor as DOMExceptionConstructor).name !== 'DOMException') {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Support:\n * - Web browsers\n * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87)\n */\nfunction getFromGlobal(): DOMExceptionConstructor | undefined {\n const ctor = globals?.DOMException;\n return isDOMExceptionConstructor(ctor) ? ctor : undefined;\n}\n\n/**\n * Support:\n * - All platforms\n */\nfunction createPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line @typescript-eslint/no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n setFunctionName(ctor, 'DOMException');\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nconst DOMException: DOMExceptionConstructor = getFromGlobal() || createPolyfill();\n\nexport { DOMException };\n","import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n return null;\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => null) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => null) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest(): null {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n return null;\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any): null {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n\n return null;\n }\n });\n}\n","import type { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, type QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n type ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport type { ValidatedUnderlyingSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n // Do nothing.\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultController.prototype.close, 'close');\nsetFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableStreamDefaultController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n","import {\n CreateReadableByteStream,\n CreateReadableStream,\n type DefaultReadableStream,\n IsReadableStream,\n type ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n type ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n type ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(\n stream: ReadableStream,\n cloneForBranch2: boolean\n): [DefaultReadableStream, DefaultReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: DefaultReadableStream;\n let branch2: DefaultReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader> = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader>) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return null;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: NonShared, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader>(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n","import { typeIsObject } from '../helpers/miscellaneous';\nimport type { ReadableStreamDefaultReadResult } from './default-reader';\n\n/**\n * A common interface for a `ReadadableStream` implementation.\n *\n * @public\n */\nexport interface ReadableStreamLike {\n readonly locked: boolean;\n\n getReader(): ReadableStreamDefaultReaderLike;\n}\n\n/**\n * A common interface for a `ReadableStreamDefaultReader` implementation.\n *\n * @public\n */\nexport interface ReadableStreamDefaultReaderLike {\n readonly closed: Promise;\n\n cancel(reason?: any): Promise;\n\n read(): Promise>;\n\n releaseLock(): void;\n}\n\nexport function isReadableStreamLike(stream: unknown): stream is ReadableStreamLike {\n return typeIsObject(stream) && typeof (stream as ReadableStreamLike).getReader !== 'undefined';\n}\n","import { CreateReadableStream, type DefaultReadableStream } from '../readable-stream';\nimport {\n isReadableStreamLike,\n type ReadableStreamDefaultReaderLike,\n type ReadableStreamLike\n} from './readable-stream-like';\nimport { ReadableStreamDefaultControllerClose, ReadableStreamDefaultControllerEnqueue } from './default-controller';\nimport { GetIterator, GetMethod, IteratorComplete, IteratorNext, IteratorValue } from '../abstract-ops/ecmascript';\nimport { promiseRejectedWith, promiseResolvedWith, reflectCall, transformPromiseWith } from '../helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { noop } from '../../utils';\n\nexport function ReadableStreamFrom(\n source: Iterable | AsyncIterable | ReadableStreamLike\n): DefaultReadableStream {\n if (isReadableStreamLike(source)) {\n return ReadableStreamFromDefaultReader(source.getReader());\n }\n return ReadableStreamFromIterable(source);\n}\n\nexport function ReadableStreamFromIterable(asyncIterable: Iterable | AsyncIterable): DefaultReadableStream {\n let stream: DefaultReadableStream;\n const iteratorRecord = GetIterator(asyncIterable, 'async');\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let nextResult;\n try {\n nextResult = IteratorNext(iteratorRecord);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const nextPromise = promiseResolvedWith(nextResult);\n return transformPromiseWith(nextPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object');\n }\n const done = IteratorComplete(iterResult);\n if (done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = IteratorValue(iterResult);\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n const iterator = iteratorRecord.iterator;\n let returnMethod: (typeof iterator)['return'] | undefined;\n try {\n returnMethod = GetMethod(iterator, 'return');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n if (returnMethod === undefined) {\n return promiseResolvedWith(undefined);\n }\n let returnResult: IteratorResult | Promise>;\n try {\n returnResult = reflectCall(returnMethod, iterator, [reason]);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const returnPromise = promiseResolvedWith(returnResult);\n return transformPromiseWith(returnPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object');\n }\n return undefined;\n });\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n\nexport function ReadableStreamFromDefaultReader(\n reader: ReadableStreamDefaultReaderLike\n): DefaultReadableStream {\n let stream: DefaultReadableStream;\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let readPromise;\n try {\n readPromise = reader.read();\n } catch (e) {\n return promiseRejectedWith(e);\n }\n return transformPromiseWith(readPromise, readResult => {\n if (!typeIsObject(readResult)) {\n throw new TypeError('The promise returned by the reader.read() method must fulfill with an object');\n }\n if (readResult.done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = readResult.value;\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n try {\n return promiseResolvedWith(reader.cancel(reason));\n } catch (e) {\n return promiseRejectedWith(e);\n }\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n","import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n","import { assertDictionary } from './basic';\nimport type {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n","import { assertDictionary } from './basic';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n","import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n","import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, type ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderErrorReadRequests,\n type ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReaderErrorReadIntoRequests,\n type ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { ReadableStreamFrom } from './readable-stream/from';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport type {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList, SymbolAsyncIterator } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions\n} from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport type { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport type { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\nimport type { ReadableStreamDefaultReaderLike, ReadableStreamLike } from './readable-stream/readable-stream-like';\nimport type { NonShared } from './helpers/array-buffer-view';\n\nexport type DefaultReadableStream = ReadableStream & {\n _readableStreamController: ReadableStreamDefaultController\n};\n\nexport type ReadableByteStream = ReadableStream> & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream implements AsyncIterable {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n\n [SymbolAsyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator {\n // Stub implementation, overridden below\n return this.values(options);\n }\n\n /**\n * Creates a new ReadableStream wrapping the provided iterable or async iterable.\n *\n * This can be used to adapt various kinds of objects into a readable stream,\n * such as an array, an async generator, or a Node.js readable stream.\n */\n static from(asyncIterable: Iterable | AsyncIterable | ReadableStreamLike): ReadableStream {\n return ReadableStreamFrom(asyncIterable);\n }\n}\n\nObject.defineProperties(ReadableStream, {\n from: { enumerable: true }\n});\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(ReadableStream.from, 'from');\nsetFunctionName(ReadableStream.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStream.prototype.getReader, 'getReader');\nsetFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough');\nsetFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo');\nsetFunctionName(ReadableStream.prototype.tee, 'tee');\nsetFunctionName(ReadableStream.prototype.values, 'values');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nObject.defineProperty(ReadableStream.prototype, SymbolAsyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n});\n\nexport type {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n ReadableStreamBYOBReaderReadOptions,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions,\n ReadableStreamLike,\n ReadableStreamDefaultReaderLike\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1\n): DefaultReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: DefaultReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n","import type { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\nsetFunctionName(byteLengthSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\nsetFunctionName(countSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const cancel = original?.cancel;\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n cancel: cancel === undefined ?\n undefined :\n convertTransformerCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n\nfunction convertTransformerCancelCallback(\n fn: TransformerCancelCallback,\n original: Transformer,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith,\n uponPromise\n} from './helpers/webidl';\nimport { CreateReadableStream, type DefaultReadableStream, ReadableStream } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: DefaultReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport type {\n Transformer,\n TransformerCancelCallback,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSourceCancelAlgorithm(stream, reason);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n TransformStreamUnblockWrite(stream);\n}\n\nfunction TransformStreamUnblockWrite(stream: TransformStream) {\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _finishPromise: Promise | undefined;\n /** @internal */\n _finishPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _finishPromise_reject?: (reason: any) => void;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n /** @internal */\n _cancelAlgorithm: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(TransformStreamDefaultController.prototype.error, 'error');\nsetFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._finishPromise = undefined;\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm: (chunk: I) => Promise;\n let flushAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n } else {\n transformAlgorithm = chunk => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n }\n\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n } else {\n flushAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n if (transformer.cancel !== undefined) {\n cancelAlgorithm = reason => transformer.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally,\n // we don't run the _cancelAlgorithm again.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerError(readable._readableStreamController, reason);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally,\n // we don't also run the _cancelAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(flushPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerClose(readable._readableStreamController);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\nfunction TransformStreamDefaultSourceCancelAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._writable cannot change after construction, so caching it across a call to user code is safe.\n const writable = stream._writable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or\n // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the\n // _flushAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (writable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, writable._storedError);\n } else {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\nexport function defaultControllerFinishPromiseResolve(controller: TransformStreamDefaultController) {\n if (controller._finishPromise_resolve === undefined) {\n return;\n }\n\n controller._finishPromise_resolve();\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nexport function defaultControllerFinishPromiseReject(controller: TransformStreamDefaultController, reason: any) {\n if (controller._finishPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(controller._finishPromise!);\n controller._finishPromise_reject(reason);\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n"],"names":["queueMicrotask","streamBrandCheckException","defaultControllerBrandCheckException"],"mappings":";;;;;;;SAAgB,IAAI,GAAA;AAClB,IAAA,OAAO,SAAS,CAAC;AACnB;;ACCM,SAAU,YAAY,CAAC,CAAM,EAAA;AACjC,IAAA,OAAO,CAAC,OAAO,CAAC,KAAK,QAA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ACpD,QAAA,OAAO,IAAI,CAAC;AACd,KAAC,CAAC,CAAC;IAEH,OAAO,UAAU,CAAC,cAAc,CAAC;AACnC,CAAC;AAED;AAEA,SAAS,oCAAoC,CAAC,IAAY,EAAA;AACxD,IAAA,OAAO,IAAI,SAAS,CAClB,8CAA8C,IAAI,CAAA,uDAAA,CAAyD,CAAC,CAAC;AACjH,CAAC;AAEK,SAAU,qCAAqC,CAAC,UAAiD,EAAA;AACrG,IAAA,IAAI,UAAU,CAAC,sBAAsB,KAAK,SAAS,EAAE;QACnD,OAAO;KACR;IAED,UAAU,CAAC,sBAAsB,EAAE,CAAC;AACpC,IAAA,UAAU,CAAC,sBAAsB,GAAG,SAAS,CAAC;AAC9C,IAAA,UAAU,CAAC,qBAAqB,GAAG,SAAS,CAAC;AAC/C,CAAC;AAEe,SAAA,oCAAoC,CAAC,UAAiD,EAAE,MAAW,EAAA;AACjH,IAAA,IAAI,UAAU,CAAC,qBAAqB,KAAK,SAAS,EAAE;QAClD,OAAO;KACR;AAED,IAAA,yBAAyB,CAAC,UAAU,CAAC,cAAe,CAAC,CAAC;AACtD,IAAA,UAAU,CAAC,qBAAqB,CAAC,MAAM,CAAC,CAAC;AACzC,IAAA,UAAU,CAAC,sBAAsB,GAAG,SAAS,CAAC;AAC9C,IAAA,UAAU,CAAC,qBAAqB,GAAG,SAAS,CAAC;AAC/C,CAAC;AAED;AAEA,SAAS,yBAAyB,CAAC,IAAY,EAAA;AAC7C,IAAA,OAAO,IAAI,SAAS,CAClB,6BAA6B,IAAI,CAAA,sCAAA,CAAwC,CAAC,CAAC;AAC/E;;;;"} \ No newline at end of file diff --git a/backend/node_modules/web-streams-polyfill/dist/ponyfill.es6.js b/backend/node_modules/web-streams-polyfill/dist/ponyfill.es6.js new file mode 100644 index 0000000000000000000000000000000000000000..4e4206d80a39661b143d2da39fb7ac49569706fb --- /dev/null +++ b/backend/node_modules/web-streams-polyfill/dist/ponyfill.es6.js @@ -0,0 +1,4810 @@ +/** + * @license + * web-streams-polyfill v3.3.3 + * Copyright 2024 Mattias Buelens, Diwank Singh Tomer and other contributors. + * This code is released under the MIT license. + * SPDX-License-Identifier: MIT + */ +(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.WebStreamsPolyfill = {})); +})(this, (function (exports) { 'use strict'; + + function noop() { + return undefined; + } + + function typeIsObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; + } + const rethrowAssertionErrorRejection = noop; + function setFunctionName(fn, name) { + try { + Object.defineProperty(fn, 'name', { + value: name, + configurable: true + }); + } + catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility + } + } + + const originalPromise = Promise; + const originalPromiseThen = Promise.prototype.then; + const originalPromiseReject = Promise.reject.bind(originalPromise); + // https://webidl.spec.whatwg.org/#a-new-promise + function newPromise(executor) { + return new originalPromise(executor); + } + // https://webidl.spec.whatwg.org/#a-promise-resolved-with + function promiseResolvedWith(value) { + return newPromise(resolve => resolve(value)); + } + // https://webidl.spec.whatwg.org/#a-promise-rejected-with + function promiseRejectedWith(reason) { + return originalPromiseReject(reason); + } + function PerformPromiseThen(promise, onFulfilled, onRejected) { + // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an + // approximation. + return originalPromiseThen.call(promise, onFulfilled, onRejected); + } + // Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned + // from that handler. To prevent this, return null instead of void from all handlers. + // http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it + function uponPromise(promise, onFulfilled, onRejected) { + PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection); + } + function uponFulfillment(promise, onFulfilled) { + uponPromise(promise, onFulfilled); + } + function uponRejection(promise, onRejected) { + uponPromise(promise, undefined, onRejected); + } + function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { + return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); + } + function setPromiseIsHandledToTrue(promise) { + PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection); + } + let _queueMicrotask = callback => { + if (typeof queueMicrotask === 'function') { + _queueMicrotask = queueMicrotask; + } + else { + const resolvedPromise = promiseResolvedWith(undefined); + _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb); + } + return _queueMicrotask(callback); + }; + function reflectCall(F, V, args) { + if (typeof F !== 'function') { + throw new TypeError('Argument is not a function'); + } + return Function.prototype.apply.call(F, V, args); + } + function promiseCall(F, V, args) { + try { + return promiseResolvedWith(reflectCall(F, V, args)); + } + catch (value) { + return promiseRejectedWith(value); + } + } + + // Original from Chromium + // https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js + const QUEUE_MAX_ARRAY_SIZE = 16384; + /** + * Simple queue structure. + * + * Avoids scalability issues with using a packed array directly by using + * multiple arrays in a linked list and keeping the array size bounded. + */ + class SimpleQueue { + constructor() { + this._cursor = 0; + this._size = 0; + // _front and _back are always defined. + this._front = { + _elements: [], + _next: undefined + }; + this._back = this._front; + // The cursor is used to avoid calling Array.shift(). + // It contains the index of the front element of the array inside the + // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE). + this._cursor = 0; + // When there is only one node, size === elements.length - cursor. + this._size = 0; + } + get length() { + return this._size; + } + // For exception safety, this method is structured in order: + // 1. Read state + // 2. Calculate required state mutations + // 3. Perform state mutations + push(element) { + const oldBack = this._back; + let newBack = oldBack; + if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { + newBack = { + _elements: [], + _next: undefined + }; + } + // push() is the mutation most likely to throw an exception, so it + // goes first. + oldBack._elements.push(element); + if (newBack !== oldBack) { + this._back = newBack; + oldBack._next = newBack; + } + ++this._size; + } + // Like push(), shift() follows the read -> calculate -> mutate pattern for + // exception safety. + shift() { // must not be called on an empty queue + const oldFront = this._front; + let newFront = oldFront; + const oldCursor = this._cursor; + let newCursor = oldCursor + 1; + const elements = oldFront._elements; + const element = elements[oldCursor]; + if (newCursor === QUEUE_MAX_ARRAY_SIZE) { + newFront = oldFront._next; + newCursor = 0; + } + // No mutations before this point. + --this._size; + this._cursor = newCursor; + if (oldFront !== newFront) { + this._front = newFront; + } + // Permit shifted element to be garbage collected. + elements[oldCursor] = undefined; + return element; + } + // The tricky thing about forEach() is that it can be called + // re-entrantly. The queue may be mutated inside the callback. It is easy to + // see that push() within the callback has no negative effects since the end + // of the queue is checked for on every iteration. If shift() is called + // repeatedly within the callback then the next iteration may return an + // element that has been removed. In this case the callback will be called + // with undefined values until we either "catch up" with elements that still + // exist or reach the back of the queue. + forEach(callback) { + let i = this._cursor; + let node = this._front; + let elements = node._elements; + while (i !== elements.length || node._next !== undefined) { + if (i === elements.length) { + node = node._next; + elements = node._elements; + i = 0; + if (elements.length === 0) { + break; + } + } + callback(elements[i]); + ++i; + } + } + // Return the element that would be returned if shift() was called now, + // without modifying the queue. + peek() { // must not be called on an empty queue + const front = this._front; + const cursor = this._cursor; + return front._elements[cursor]; + } + } + + const AbortSteps = Symbol('[[AbortSteps]]'); + const ErrorSteps = Symbol('[[ErrorSteps]]'); + const CancelSteps = Symbol('[[CancelSteps]]'); + const PullSteps = Symbol('[[PullSteps]]'); + const ReleaseSteps = Symbol('[[ReleaseSteps]]'); + + function ReadableStreamReaderGenericInitialize(reader, stream) { + reader._ownerReadableStream = stream; + stream._reader = reader; + if (stream._state === 'readable') { + defaultReaderClosedPromiseInitialize(reader); + } + else if (stream._state === 'closed') { + defaultReaderClosedPromiseInitializeAsResolved(reader); + } + else { + defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); + } + } + // A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state + // check. + function ReadableStreamReaderGenericCancel(reader, reason) { + const stream = reader._ownerReadableStream; + return ReadableStreamCancel(stream, reason); + } + function ReadableStreamReaderGenericRelease(reader) { + const stream = reader._ownerReadableStream; + if (stream._state === 'readable') { + defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + else { + defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + stream._readableStreamController[ReleaseSteps](); + stream._reader = undefined; + reader._ownerReadableStream = undefined; + } + // Helper functions for the readers. + function readerLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released reader'); + } + // Helper functions for the ReadableStreamDefaultReader. + function defaultReaderClosedPromiseInitialize(reader) { + reader._closedPromise = newPromise((resolve, reject) => { + reader._closedPromise_resolve = resolve; + reader._closedPromise_reject = reject; + }); + } + function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseReject(reader, reason); + } + function defaultReaderClosedPromiseInitializeAsResolved(reader) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseResolve(reader); + } + function defaultReaderClosedPromiseReject(reader, reason) { + if (reader._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(reader._closedPromise); + reader._closedPromise_reject(reason); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; + } + function defaultReaderClosedPromiseResetToRejected(reader, reason) { + defaultReaderClosedPromiseInitializeAsRejected(reader, reason); + } + function defaultReaderClosedPromiseResolve(reader) { + if (reader._closedPromise_resolve === undefined) { + return; + } + reader._closedPromise_resolve(undefined); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; + } + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill + const NumberIsFinite = Number.isFinite || function (x) { + return typeof x === 'number' && isFinite(x); + }; + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill + const MathTrunc = Math.trunc || function (v) { + return v < 0 ? Math.ceil(v) : Math.floor(v); + }; + + // https://heycam.github.io/webidl/#idl-dictionaries + function isDictionary(x) { + return typeof x === 'object' || typeof x === 'function'; + } + function assertDictionary(obj, context) { + if (obj !== undefined && !isDictionary(obj)) { + throw new TypeError(`${context} is not an object.`); + } + } + // https://heycam.github.io/webidl/#idl-callback-functions + function assertFunction(x, context) { + if (typeof x !== 'function') { + throw new TypeError(`${context} is not a function.`); + } + } + // https://heycam.github.io/webidl/#idl-object + function isObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; + } + function assertObject(x, context) { + if (!isObject(x)) { + throw new TypeError(`${context} is not an object.`); + } + } + function assertRequiredArgument(x, position, context) { + if (x === undefined) { + throw new TypeError(`Parameter ${position} is required in '${context}'.`); + } + } + function assertRequiredField(x, field, context) { + if (x === undefined) { + throw new TypeError(`${field} is required in '${context}'.`); + } + } + // https://heycam.github.io/webidl/#idl-unrestricted-double + function convertUnrestrictedDouble(value) { + return Number(value); + } + function censorNegativeZero(x) { + return x === 0 ? 0 : x; + } + function integerPart(x) { + return censorNegativeZero(MathTrunc(x)); + } + // https://heycam.github.io/webidl/#idl-unsigned-long-long + function convertUnsignedLongLongWithEnforceRange(value, context) { + const lowerBound = 0; + const upperBound = Number.MAX_SAFE_INTEGER; + let x = Number(value); + x = censorNegativeZero(x); + if (!NumberIsFinite(x)) { + throw new TypeError(`${context} is not a finite number`); + } + x = integerPart(x); + if (x < lowerBound || x > upperBound) { + throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`); + } + if (!NumberIsFinite(x) || x === 0) { + return 0; + } + // TODO Use BigInt if supported? + // let xBigInt = BigInt(integerPart(x)); + // xBigInt = BigInt.asUintN(64, xBigInt); + // return Number(xBigInt); + return x; + } + + function assertReadableStream(x, context) { + if (!IsReadableStream(x)) { + throw new TypeError(`${context} is not a ReadableStream.`); + } + } + + // Abstract operations for the ReadableStream. + function AcquireReadableStreamDefaultReader(stream) { + return new ReadableStreamDefaultReader(stream); + } + // ReadableStream API exposed for controllers. + function ReadableStreamAddReadRequest(stream, readRequest) { + stream._reader._readRequests.push(readRequest); + } + function ReadableStreamFulfillReadRequest(stream, chunk, done) { + const reader = stream._reader; + const readRequest = reader._readRequests.shift(); + if (done) { + readRequest._closeSteps(); + } + else { + readRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadRequests(stream) { + return stream._reader._readRequests.length; + } + function ReadableStreamHasDefaultReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamDefaultReader(reader)) { + return false; + } + return true; + } + /** + * A default reader vended by a {@link ReadableStream}. + * + * @public + */ + class ReadableStreamDefaultReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + /** + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('read')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: () => resolvePromise({ value: undefined, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamDefaultReaderRead(this, readRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamDefaultReader(this)) { + throw defaultReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamDefaultReaderRelease(this); + } + } + Object.defineProperties(ReadableStreamDefaultReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + setFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel'); + setFunctionName(ReadableStreamDefaultReader.prototype.read, 'read'); + setFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, { + value: 'ReadableStreamDefaultReader', + configurable: true + }); + } + // Abstract operations for the readers. + function IsReadableStreamDefaultReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) { + return false; + } + return x instanceof ReadableStreamDefaultReader; + } + function ReadableStreamDefaultReaderRead(reader, readRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'closed') { + readRequest._closeSteps(); + } + else if (stream._state === 'errored') { + readRequest._errorSteps(stream._storedError); + } + else { + stream._readableStreamController[PullSteps](readRequest); + } + } + function ReadableStreamDefaultReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + const e = new TypeError('Reader was released'); + ReadableStreamDefaultReaderErrorReadRequests(reader, e); + } + function ReadableStreamDefaultReaderErrorReadRequests(reader, e) { + const readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(readRequest => { + readRequest._errorSteps(e); + }); + } + // Helper functions for the ReadableStreamDefaultReader. + function defaultReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`); + } + + /****************************************************************************** + 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 */ + + + function __values(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + } + + function __await(v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); + } + + function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } + } + + function __asyncDelegator(o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } + } + + function __asyncValues(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } + } + + 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 _a, _b, _c; + function CreateArrayFromList(elements) { + // We use arrays to represent lists, so this is basically a no-op. + // Do a slice though just in case we happen to depend on the unique-ness. + return elements.slice(); + } + function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { + new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); + } + let TransferArrayBuffer = (O) => { + if (typeof O.transfer === 'function') { + TransferArrayBuffer = buffer => buffer.transfer(); + } + else if (typeof structuredClone === 'function') { + TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] }); + } + else { + // Not implemented correctly + TransferArrayBuffer = buffer => buffer; + } + return TransferArrayBuffer(O); + }; + let IsDetachedBuffer = (O) => { + if (typeof O.detached === 'boolean') { + IsDetachedBuffer = buffer => buffer.detached; + } + else { + // Not implemented correctly + IsDetachedBuffer = buffer => buffer.byteLength === 0; + } + return IsDetachedBuffer(O); + }; + function ArrayBufferSlice(buffer, begin, end) { + // ArrayBuffer.prototype.slice is not available on IE10 + // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice + if (buffer.slice) { + return buffer.slice(begin, end); + } + const length = end - begin; + const slice = new ArrayBuffer(length); + CopyDataBlockBytes(slice, 0, buffer, begin, length); + return slice; + } + function GetMethod(receiver, prop) { + const func = receiver[prop]; + if (func === undefined || func === null) { + return undefined; + } + if (typeof func !== 'function') { + throw new TypeError(`${String(prop)} is not a function`); + } + return func; + } + function CreateAsyncFromSyncIterator(syncIteratorRecord) { + // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%, + // we use yield* inside an async generator function to achieve the same result. + // Wrap the sync iterator inside a sync iterable, so we can use it with yield*. + const syncIterable = { + [Symbol.iterator]: () => syncIteratorRecord.iterator + }; + // Create an async generator function and immediately invoke it. + const asyncIterator = (function () { + return __asyncGenerator(this, arguments, function* () { + return yield __await(yield __await(yield* __asyncDelegator(__asyncValues(syncIterable)))); + }); + }()); + // Return as an async iterator record. + const nextMethod = asyncIterator.next; + return { iterator: asyncIterator, nextMethod, done: false }; + } + // Aligns with core-js/modules/es.symbol.async-iterator.js + const SymbolAsyncIterator = (_c = (_a = Symbol.asyncIterator) !== null && _a !== void 0 ? _a : (_b = Symbol.for) === null || _b === void 0 ? void 0 : _b.call(Symbol, 'Symbol.asyncIterator')) !== null && _c !== void 0 ? _c : '@@asyncIterator'; + function GetIterator(obj, hint = 'sync', method) { + if (method === undefined) { + if (hint === 'async') { + method = GetMethod(obj, SymbolAsyncIterator); + if (method === undefined) { + const syncMethod = GetMethod(obj, Symbol.iterator); + const syncIteratorRecord = GetIterator(obj, 'sync', syncMethod); + return CreateAsyncFromSyncIterator(syncIteratorRecord); + } + } + else { + method = GetMethod(obj, Symbol.iterator); + } + } + if (method === undefined) { + throw new TypeError('The object is not iterable'); + } + const iterator = reflectCall(method, obj, []); + if (!typeIsObject(iterator)) { + throw new TypeError('The iterator method must return an object'); + } + const nextMethod = iterator.next; + return { iterator, nextMethod, done: false }; + } + function IteratorNext(iteratorRecord) { + const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []); + if (!typeIsObject(result)) { + throw new TypeError('The iterator.next() method must return an object'); + } + return result; + } + function IteratorComplete(iterResult) { + return Boolean(iterResult.done); + } + function IteratorValue(iterResult) { + return iterResult.value; + } + + /// + // We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it. + const AsyncIteratorPrototype = { + // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( ) + // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator + [SymbolAsyncIterator]() { + return this; + } + }; + Object.defineProperty(AsyncIteratorPrototype, SymbolAsyncIterator, { enumerable: false }); + + /// + class ReadableStreamAsyncIteratorImpl { + constructor(reader, preventCancel) { + this._ongoingPromise = undefined; + this._isFinished = false; + this._reader = reader; + this._preventCancel = preventCancel; + } + next() { + const nextSteps = () => this._nextSteps(); + this._ongoingPromise = this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : + nextSteps(); + return this._ongoingPromise; + } + return(value) { + const returnSteps = () => this._returnSteps(value); + return this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : + returnSteps(); + } + _nextSteps() { + if (this._isFinished) { + return Promise.resolve({ value: undefined, done: true }); + } + const reader = this._reader; + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => { + this._ongoingPromise = undefined; + // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test. + // FIXME Is this a bug in the specification, or in the test? + _queueMicrotask(() => resolvePromise({ value: chunk, done: false })); + }, + _closeSteps: () => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + resolvePromise({ value: undefined, done: true }); + }, + _errorSteps: reason => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + rejectPromise(reason); + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promise; + } + _returnSteps(value) { + if (this._isFinished) { + return Promise.resolve({ value, done: true }); + } + this._isFinished = true; + const reader = this._reader; + if (!this._preventCancel) { + const result = ReadableStreamReaderGenericCancel(reader, value); + ReadableStreamReaderGenericRelease(reader); + return transformPromiseWith(result, () => ({ value, done: true })); + } + ReadableStreamReaderGenericRelease(reader); + return promiseResolvedWith({ value, done: true }); + } + } + const ReadableStreamAsyncIteratorPrototype = { + next() { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next')); + } + return this._asyncIteratorImpl.next(); + }, + return(value) { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return')); + } + return this._asyncIteratorImpl.return(value); + } + }; + Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); + // Abstract operations for the ReadableStream. + function AcquireReadableStreamAsyncIterator(stream, preventCancel) { + const reader = AcquireReadableStreamDefaultReader(stream); + const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); + const iterator = Object.create(ReadableStreamAsyncIteratorPrototype); + iterator._asyncIteratorImpl = impl; + return iterator; + } + function IsReadableStreamAsyncIterator(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) { + return false; + } + try { + // noinspection SuspiciousTypeOfGuard + return x._asyncIteratorImpl instanceof + ReadableStreamAsyncIteratorImpl; + } + catch (_a) { + return false; + } + } + // Helper functions for the ReadableStream. + function streamAsyncIteratorBrandCheckException(name) { + return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`); + } + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill + const NumberIsNaN = Number.isNaN || function (x) { + // eslint-disable-next-line no-self-compare + return x !== x; + }; + + function IsNonNegativeNumber(v) { + if (typeof v !== 'number') { + return false; + } + if (NumberIsNaN(v)) { + return false; + } + if (v < 0) { + return false; + } + return true; + } + function CloneAsUint8Array(O) { + const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength); + return new Uint8Array(buffer); + } + + function DequeueValue(container) { + const pair = container._queue.shift(); + container._queueTotalSize -= pair.size; + if (container._queueTotalSize < 0) { + container._queueTotalSize = 0; + } + return pair.value; + } + function EnqueueValueWithSize(container, value, size) { + if (!IsNonNegativeNumber(size) || size === Infinity) { + throw new RangeError('Size must be a finite, non-NaN, non-negative number.'); + } + container._queue.push({ value, size }); + container._queueTotalSize += size; + } + function PeekQueueValue(container) { + const pair = container._queue.peek(); + return pair.value; + } + function ResetQueue(container) { + container._queue = new SimpleQueue(); + container._queueTotalSize = 0; + } + + function isDataViewConstructor(ctor) { + return ctor === DataView; + } + function isDataView(view) { + return isDataViewConstructor(view.constructor); + } + function arrayBufferViewElementSize(ctor) { + if (isDataViewConstructor(ctor)) { + return 1; + } + return ctor.BYTES_PER_ELEMENT; + } + + /** + * A pull-into request in a {@link ReadableByteStreamController}. + * + * @public + */ + class ReadableStreamBYOBRequest { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. + */ + get view() { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('view'); + } + return this._view; + } + respond(bytesWritten) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respond'); + } + assertRequiredArgument(bytesWritten, 1, 'respond'); + bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter'); + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(this._view.buffer)) { + throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`); + } + ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); + } + respondWithNewView(view) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respondWithNewView'); + } + assertRequiredArgument(view, 1, 'respondWithNewView'); + if (!ArrayBuffer.isView(view)) { + throw new TypeError('You can only respond with array buffer views'); + } + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(view.buffer)) { + throw new TypeError('The given view\'s buffer has been detached and so cannot be used as a response'); + } + ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); + } + } + Object.defineProperties(ReadableStreamBYOBRequest.prototype, { + respond: { enumerable: true }, + respondWithNewView: { enumerable: true }, + view: { enumerable: true } + }); + setFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond'); + setFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, { + value: 'ReadableStreamBYOBRequest', + configurable: true + }); + } + /** + * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. + * + * @public + */ + class ReadableByteStreamController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the current BYOB pull request, or `null` if there isn't one. + */ + get byobRequest() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('byobRequest'); + } + return ReadableByteStreamControllerGetBYOBRequest(this); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('desiredSize'); + } + return ReadableByteStreamControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('close'); + } + if (this._closeRequested) { + throw new TypeError('The stream has already been closed; do not close it again!'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`); + } + ReadableByteStreamControllerClose(this); + } + enqueue(chunk) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('enqueue'); + } + assertRequiredArgument(chunk, 1, 'enqueue'); + if (!ArrayBuffer.isView(chunk)) { + throw new TypeError('chunk must be an array buffer view'); + } + if (chunk.byteLength === 0) { + throw new TypeError('chunk must have non-zero byteLength'); + } + if (chunk.buffer.byteLength === 0) { + throw new TypeError(`chunk's buffer must have non-zero byteLength`); + } + if (this._closeRequested) { + throw new TypeError('stream is closed or draining'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`); + } + ReadableByteStreamControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('error'); + } + ReadableByteStreamControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ReadableByteStreamControllerClearPendingPullIntos(this); + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableByteStreamControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableByteStream; + if (this._queueTotalSize > 0) { + ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest); + return; + } + const autoAllocateChunkSize = this._autoAllocateChunkSize; + if (autoAllocateChunkSize !== undefined) { + let buffer; + try { + buffer = new ArrayBuffer(autoAllocateChunkSize); + } + catch (bufferE) { + readRequest._errorSteps(bufferE); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: autoAllocateChunkSize, + byteOffset: 0, + byteLength: autoAllocateChunkSize, + bytesFilled: 0, + minimumFill: 1, + elementSize: 1, + viewConstructor: Uint8Array, + readerType: 'default' + }; + this._pendingPullIntos.push(pullIntoDescriptor); + } + ReadableStreamAddReadRequest(stream, readRequest); + ReadableByteStreamControllerCallPullIfNeeded(this); + } + /** @internal */ + [ReleaseSteps]() { + if (this._pendingPullIntos.length > 0) { + const firstPullInto = this._pendingPullIntos.peek(); + firstPullInto.readerType = 'none'; + this._pendingPullIntos = new SimpleQueue(); + this._pendingPullIntos.push(firstPullInto); + } + } + } + Object.defineProperties(ReadableByteStreamController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + byobRequest: { enumerable: true }, + desiredSize: { enumerable: true } + }); + setFunctionName(ReadableByteStreamController.prototype.close, 'close'); + setFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue'); + setFunctionName(ReadableByteStreamController.prototype.error, 'error'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, { + value: 'ReadableByteStreamController', + configurable: true + }); + } + // Abstract operations for the ReadableByteStreamController. + function IsReadableByteStreamController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) { + return false; + } + return x instanceof ReadableByteStreamController; + } + function IsReadableStreamBYOBRequest(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) { + return false; + } + return x instanceof ReadableStreamBYOBRequest; + } + function ReadableByteStreamControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableByteStreamControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + // TODO: Test controller argument + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + return null; + }, e => { + ReadableByteStreamControllerError(controller, e); + return null; + }); + } + function ReadableByteStreamControllerClearPendingPullIntos(controller) { + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + controller._pendingPullIntos = new SimpleQueue(); + } + function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { + let done = false; + if (stream._state === 'closed') { + done = true; + } + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'default') { + ReadableStreamFulfillReadRequest(stream, filledView, done); + } + else { + ReadableStreamFulfillReadIntoRequest(stream, filledView, done); + } + } + function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { + const bytesFilled = pullIntoDescriptor.bytesFilled; + const elementSize = pullIntoDescriptor.elementSize; + return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); + } + function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { + controller._queue.push({ buffer, byteOffset, byteLength }); + controller._queueTotalSize += byteLength; + } + function ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, buffer, byteOffset, byteLength) { + let clonedChunk; + try { + clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength); + } + catch (cloneE) { + ReadableByteStreamControllerError(controller, cloneE); + throw cloneE; + } + ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength); + } + function ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstDescriptor) { + if (firstDescriptor.bytesFilled > 0) { + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, firstDescriptor.buffer, firstDescriptor.byteOffset, firstDescriptor.bytesFilled); + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { + const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); + const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; + let totalBytesToCopyRemaining = maxBytesToCopy; + let ready = false; + const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize; + const maxAlignedBytes = maxBytesFilled - remainderBytes; + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) { + totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; + ready = true; + } + const queue = controller._queue; + while (totalBytesToCopyRemaining > 0) { + const headOfQueue = queue.peek(); + const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); + const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); + if (headOfQueue.byteLength === bytesToCopy) { + queue.shift(); + } + else { + headOfQueue.byteOffset += bytesToCopy; + headOfQueue.byteLength -= bytesToCopy; + } + controller._queueTotalSize -= bytesToCopy; + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); + totalBytesToCopyRemaining -= bytesToCopy; + } + return ready; + } + function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { + pullIntoDescriptor.bytesFilled += size; + } + function ReadableByteStreamControllerHandleQueueDrain(controller) { + if (controller._queueTotalSize === 0 && controller._closeRequested) { + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(controller._controlledReadableByteStream); + } + else { + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + } + function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { + if (controller._byobRequest === null) { + return; + } + controller._byobRequest._associatedReadableByteStreamController = undefined; + controller._byobRequest._view = null; + controller._byobRequest = null; + } + function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { + while (controller._pendingPullIntos.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const pullIntoDescriptor = controller._pendingPullIntos.peek(); + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller) { + const reader = controller._controlledReadableByteStream._reader; + while (reader._readRequests.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const readRequest = reader._readRequests.shift(); + ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest); + } + } + function ReadableByteStreamControllerPullInto(controller, view, min, readIntoRequest) { + const stream = controller._controlledReadableByteStream; + const ctor = view.constructor; + const elementSize = arrayBufferViewElementSize(ctor); + const { byteOffset, byteLength } = view; + const minimumFill = min * elementSize; + let buffer; + try { + buffer = TransferArrayBuffer(view.buffer); + } + catch (e) { + readIntoRequest._errorSteps(e); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: buffer.byteLength, + byteOffset, + byteLength, + bytesFilled: 0, + minimumFill, + elementSize, + viewConstructor: ctor, + readerType: 'byob' + }; + if (controller._pendingPullIntos.length > 0) { + controller._pendingPullIntos.push(pullIntoDescriptor); + // No ReadableByteStreamControllerCallPullIfNeeded() call since: + // - No change happens on desiredSize + // - The source has already been notified of that there's at least 1 pending read(view) + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + return; + } + if (stream._state === 'closed') { + const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); + readIntoRequest._closeSteps(emptyView); + return; + } + if (controller._queueTotalSize > 0) { + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + ReadableByteStreamControllerHandleQueueDrain(controller); + readIntoRequest._chunkSteps(filledView); + return; + } + if (controller._closeRequested) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + readIntoRequest._errorSteps(e); + return; + } + } + controller._pendingPullIntos.push(pullIntoDescriptor); + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { + if (firstDescriptor.readerType === 'none') { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const stream = controller._controlledReadableByteStream; + if (ReadableStreamHasBYOBReader(stream)) { + while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { + const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + return; + } + if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) { + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + return; + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; + if (remainderSize > 0) { + const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor.buffer, end - remainderSize, remainderSize); + } + pullIntoDescriptor.bytesFilled -= remainderSize; + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor); + } + else { + ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerShiftPendingPullInto(controller) { + const descriptor = controller._pendingPullIntos.shift(); + return descriptor; + } + function ReadableByteStreamControllerShouldCallPull(controller) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return false; + } + if (controller._closeRequested) { + return false; + } + if (!controller._started) { + return false; + } + if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; + } + function ReadableByteStreamControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + } + // A client of ReadableByteStreamController may use these functions directly to bypass state check. + function ReadableByteStreamControllerClose(controller) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + if (controller._queueTotalSize > 0) { + controller._closeRequested = true; + return; + } + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + throw e; + } + } + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } + function ReadableByteStreamControllerEnqueue(controller, chunk) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + const { buffer, byteOffset, byteLength } = chunk; + if (IsDetachedBuffer(buffer)) { + throw new TypeError('chunk\'s buffer is detached and so cannot be enqueued'); + } + const transferredBuffer = TransferArrayBuffer(buffer); + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (IsDetachedBuffer(firstPendingPullInto.buffer)) { + throw new TypeError('The BYOB request\'s buffer has been detached and so cannot be filled with an enqueued chunk'); + } + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer); + if (firstPendingPullInto.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto); + } + } + if (ReadableStreamHasDefaultReader(stream)) { + ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller); + if (ReadableStreamGetNumReadRequests(stream) === 0) { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + else { + if (controller._pendingPullIntos.length > 0) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); + ReadableStreamFulfillReadRequest(stream, transferredView, false); + } + } + else if (ReadableStreamHasBYOBReader(stream)) { + // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully. + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + else { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerError(controller, e) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return; + } + ReadableByteStreamControllerClearPendingPullIntos(controller); + ResetQueue(controller); + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); + } + function ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest) { + const entry = controller._queue.shift(); + controller._queueTotalSize -= entry.byteLength; + ReadableByteStreamControllerHandleQueueDrain(controller); + const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); + readRequest._chunkSteps(view); + } + function ReadableByteStreamControllerGetBYOBRequest(controller) { + if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); + const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); + SetUpReadableStreamBYOBRequest(byobRequest, controller, view); + controller._byobRequest = byobRequest; + } + return controller._byobRequest; + } + function ReadableByteStreamControllerGetDesiredSize(controller) { + const state = controller._controlledReadableByteStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; + } + function ReadableByteStreamControllerRespond(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (bytesWritten !== 0) { + throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream'); + } + } + else { + if (bytesWritten === 0) { + throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream'); + } + if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) { + throw new RangeError('bytesWritten out of range'); + } + } + firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); + ReadableByteStreamControllerRespondInternal(controller, bytesWritten); + } + function ReadableByteStreamControllerRespondWithNewView(controller, view) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (view.byteLength !== 0) { + throw new TypeError('The view\'s length must be 0 when calling respondWithNewView() on a closed stream'); + } + } + else { + if (view.byteLength === 0) { + throw new TypeError('The view\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'); + } + } + if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { + throw new RangeError('The region specified by view does not match byobRequest'); + } + if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) { + throw new RangeError('The buffer of view has different capacity than byobRequest'); + } + if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) { + throw new RangeError('The region specified by view is larger than byobRequest'); + } + const viewByteLength = view.byteLength; + firstDescriptor.buffer = TransferArrayBuffer(view.buffer); + ReadableByteStreamControllerRespondInternal(controller, viewByteLength); + } + function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { + controller._controlledReadableByteStream = stream; + controller._pullAgain = false; + controller._pulling = false; + controller._byobRequest = null; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._closeRequested = false; + controller._started = false; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._autoAllocateChunkSize = autoAllocateChunkSize; + controller._pendingPullIntos = new SimpleQueue(); + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableByteStreamControllerCallPullIfNeeded(controller); + return null; + }, r => { + ReadableByteStreamControllerError(controller, r); + return null; + }); + } + function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { + const controller = Object.create(ReadableByteStreamController.prototype); + let startAlgorithm; + let pullAlgorithm; + let cancelAlgorithm; + if (underlyingByteSource.start !== undefined) { + startAlgorithm = () => underlyingByteSource.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingByteSource.pull !== undefined) { + pullAlgorithm = () => underlyingByteSource.pull(controller); + } + else { + pullAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingByteSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingByteSource.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; + if (autoAllocateChunkSize === 0) { + throw new TypeError('autoAllocateChunkSize must be greater than 0'); + } + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); + } + function SetUpReadableStreamBYOBRequest(request, controller, view) { + request._associatedReadableByteStreamController = controller; + request._view = view; + } + // Helper functions for the ReadableStreamBYOBRequest. + function byobRequestBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`); + } + // Helper functions for the ReadableByteStreamController. + function byteStreamControllerBrandCheckException(name) { + return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`); + } + + function convertReaderOptions(options, context) { + assertDictionary(options, context); + const mode = options === null || options === void 0 ? void 0 : options.mode; + return { + mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`) + }; + } + function convertReadableStreamReaderMode(mode, context) { + mode = `${mode}`; + if (mode !== 'byob') { + throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`); + } + return mode; + } + function convertByobReadOptions(options, context) { + var _a; + assertDictionary(options, context); + const min = (_a = options === null || options === void 0 ? void 0 : options.min) !== null && _a !== void 0 ? _a : 1; + return { + min: convertUnsignedLongLongWithEnforceRange(min, `${context} has member 'min' that`) + }; + } + + // Abstract operations for the ReadableStream. + function AcquireReadableStreamBYOBReader(stream) { + return new ReadableStreamBYOBReader(stream); + } + // ReadableStream API exposed for controllers. + function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { + stream._reader._readIntoRequests.push(readIntoRequest); + } + function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { + const reader = stream._reader; + const readIntoRequest = reader._readIntoRequests.shift(); + if (done) { + readIntoRequest._closeSteps(chunk); + } + else { + readIntoRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadIntoRequests(stream) { + return stream._reader._readIntoRequests.length; + } + function ReadableStreamHasBYOBReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamBYOBReader(reader)) { + return false; + } + return true; + } + /** + * A BYOB reader vended by a {@link ReadableStream}. + * + * @public + */ + class ReadableStreamBYOBReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + if (!IsReadableByteStreamController(stream._readableStreamController)) { + throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' + + 'source'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readIntoRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + read(view, rawOptions = {}) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('read')); + } + if (!ArrayBuffer.isView(view)) { + return promiseRejectedWith(new TypeError('view must be an array buffer view')); + } + if (view.byteLength === 0) { + return promiseRejectedWith(new TypeError('view must have non-zero byteLength')); + } + if (view.buffer.byteLength === 0) { + return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`)); + } + if (IsDetachedBuffer(view.buffer)) { + return promiseRejectedWith(new TypeError('view\'s buffer has been detached')); + } + let options; + try { + options = convertByobReadOptions(rawOptions, 'options'); + } + catch (e) { + return promiseRejectedWith(e); + } + const min = options.min; + if (min === 0) { + return promiseRejectedWith(new TypeError('options.min must be greater than 0')); + } + if (!isDataView(view)) { + if (min > view.length) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s length')); + } + } + else if (min > view.byteLength) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s byteLength')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readIntoRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: chunk => resolvePromise({ value: chunk, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamBYOBReader(this)) { + throw byobReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamBYOBReaderRelease(this); + } + } + Object.defineProperties(ReadableStreamBYOBReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + setFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel'); + setFunctionName(ReadableStreamBYOBReader.prototype.read, 'read'); + setFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, { + value: 'ReadableStreamBYOBReader', + configurable: true + }); + } + // Abstract operations for the readers. + function IsReadableStreamBYOBReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) { + return false; + } + return x instanceof ReadableStreamBYOBReader; + } + function ReadableStreamBYOBReaderRead(reader, view, min, readIntoRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'errored') { + readIntoRequest._errorSteps(stream._storedError); + } + else { + ReadableByteStreamControllerPullInto(stream._readableStreamController, view, min, readIntoRequest); + } + } + function ReadableStreamBYOBReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + const e = new TypeError('Reader was released'); + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); + } + function ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e) { + const readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._errorSteps(e); + }); + } + // Helper functions for the ReadableStreamBYOBReader. + function byobReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`); + } + + function ExtractHighWaterMark(strategy, defaultHWM) { + const { highWaterMark } = strategy; + if (highWaterMark === undefined) { + return defaultHWM; + } + if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { + throw new RangeError('Invalid highWaterMark'); + } + return highWaterMark; + } + function ExtractSizeAlgorithm(strategy) { + const { size } = strategy; + if (!size) { + return () => 1; + } + return size; + } + + function convertQueuingStrategy(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + const size = init === null || init === void 0 ? void 0 : init.size; + return { + highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark), + size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`) + }; + } + function convertQueuingStrategySize(fn, context) { + assertFunction(fn, context); + return chunk => convertUnrestrictedDouble(fn(chunk)); + } + + function convertUnderlyingSink(original, context) { + assertDictionary(original, context); + const abort = original === null || original === void 0 ? void 0 : original.abort; + const close = original === null || original === void 0 ? void 0 : original.close; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + const write = original === null || original === void 0 ? void 0 : original.write; + return { + abort: abort === undefined ? + undefined : + convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`), + close: close === undefined ? + undefined : + convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`), + start: start === undefined ? + undefined : + convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`), + write: write === undefined ? + undefined : + convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`), + type + }; + } + function convertUnderlyingSinkAbortCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); + } + function convertUnderlyingSinkCloseCallback(fn, original, context) { + assertFunction(fn, context); + return () => promiseCall(fn, original, []); + } + function convertUnderlyingSinkStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertUnderlyingSinkWriteCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); + } + + function assertWritableStream(x, context) { + if (!IsWritableStream(x)) { + throw new TypeError(`${context} is not a WritableStream.`); + } + } + + function isAbortSignal(value) { + if (typeof value !== 'object' || value === null) { + return false; + } + try { + return typeof value.aborted === 'boolean'; + } + catch (_a) { + // AbortSignal.prototype.aborted throws if its brand check fails + return false; + } + } + const supportsAbortController = typeof AbortController === 'function'; + /** + * Construct a new AbortController, if supported by the platform. + * + * @internal + */ + function createAbortController() { + if (supportsAbortController) { + return new AbortController(); + } + return undefined; + } + + /** + * A writable stream represents a destination for data, into which you can write. + * + * @public + */ + class WritableStream { + constructor(rawUnderlyingSink = {}, rawStrategy = {}) { + if (rawUnderlyingSink === undefined) { + rawUnderlyingSink = null; + } + else { + assertObject(rawUnderlyingSink, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter'); + InitializeWritableStream(this); + const type = underlyingSink.type; + if (type !== undefined) { + throw new RangeError('Invalid type is specified'); + } + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); + } + /** + * Returns whether or not the writable stream is locked to a writer. + */ + get locked() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('locked'); + } + return IsWritableStreamLocked(this); + } + /** + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort + * mechanism of the underlying sink. + * + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel + * the stream) if the stream is currently locked. + */ + abort(reason = undefined) { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('abort')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer')); + } + return WritableStreamAbort(this, reason); + } + /** + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its + * close behavior. During this time any further attempts to write will fail (without erroring the stream). + * + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + */ + close() { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('close')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer')); + } + if (WritableStreamCloseQueuedOrInFlight(this)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamClose(this); + } + /** + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream + * is locked, no other writer can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at + * the same time, which would cause the resulting written data to be unpredictable and probably useless. + */ + getWriter() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('getWriter'); + } + return AcquireWritableStreamDefaultWriter(this); + } + } + Object.defineProperties(WritableStream.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + getWriter: { enumerable: true }, + locked: { enumerable: true } + }); + setFunctionName(WritableStream.prototype.abort, 'abort'); + setFunctionName(WritableStream.prototype.close, 'close'); + setFunctionName(WritableStream.prototype.getWriter, 'getWriter'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, { + value: 'WritableStream', + configurable: true + }); + } + // Abstract operations for the WritableStream. + function AcquireWritableStreamDefaultWriter(stream) { + return new WritableStreamDefaultWriter(stream); + } + // Throws if and only if startAlgorithm throws. + function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(WritableStream.prototype); + InitializeWritableStream(stream); + const controller = Object.create(WritableStreamDefaultController.prototype); + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + return stream; + } + function InitializeWritableStream(stream) { + stream._state = 'writable'; + // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is + // 'erroring' or 'errored'. May be set to an undefined value. + stream._storedError = undefined; + stream._writer = undefined; + // Initialize to undefined first because the constructor of the controller checks this + // variable to validate the caller. + stream._writableStreamController = undefined; + // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data + // producer without waiting for the queued writes to finish. + stream._writeRequests = new SimpleQueue(); + // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents + // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here. + stream._inFlightWriteRequest = undefined; + // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer + // has been detached. + stream._closeRequest = undefined; + // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it + // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here. + stream._inFlightCloseRequest = undefined; + // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached. + stream._pendingAbortRequest = undefined; + // The backpressure signal set by the controller. + stream._backpressure = false; + } + function IsWritableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) { + return false; + } + return x instanceof WritableStream; + } + function IsWritableStreamLocked(stream) { + if (stream._writer === undefined) { + return false; + } + return true; + } + function WritableStreamAbort(stream, reason) { + var _a; + if (stream._state === 'closed' || stream._state === 'errored') { + return promiseResolvedWith(undefined); + } + stream._writableStreamController._abortReason = reason; + (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort(reason); + // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring', + // but it doesn't know that signaling abort runs author code that might have changed the state. + // Widen the type again by casting to WritableStreamState. + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseResolvedWith(undefined); + } + if (stream._pendingAbortRequest !== undefined) { + return stream._pendingAbortRequest._promise; + } + let wasAlreadyErroring = false; + if (state === 'erroring') { + wasAlreadyErroring = true; + // reason will not be used, so don't keep a reference to it. + reason = undefined; + } + const promise = newPromise((resolve, reject) => { + stream._pendingAbortRequest = { + _promise: undefined, + _resolve: resolve, + _reject: reject, + _reason: reason, + _wasAlreadyErroring: wasAlreadyErroring + }; + }); + stream._pendingAbortRequest._promise = promise; + if (!wasAlreadyErroring) { + WritableStreamStartErroring(stream, reason); + } + return promise; + } + function WritableStreamClose(stream) { + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`)); + } + const promise = newPromise((resolve, reject) => { + const closeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._closeRequest = closeRequest; + }); + const writer = stream._writer; + if (writer !== undefined && stream._backpressure && state === 'writable') { + defaultWriterReadyPromiseResolve(writer); + } + WritableStreamDefaultControllerClose(stream._writableStreamController); + return promise; + } + // WritableStream API exposed for controllers. + function WritableStreamAddWriteRequest(stream) { + const promise = newPromise((resolve, reject) => { + const writeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._writeRequests.push(writeRequest); + }); + return promise; + } + function WritableStreamDealWithRejection(stream, error) { + const state = stream._state; + if (state === 'writable') { + WritableStreamStartErroring(stream, error); + return; + } + WritableStreamFinishErroring(stream); + } + function WritableStreamStartErroring(stream, reason) { + const controller = stream._writableStreamController; + stream._state = 'erroring'; + stream._storedError = reason; + const writer = stream._writer; + if (writer !== undefined) { + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); + } + if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { + WritableStreamFinishErroring(stream); + } + } + function WritableStreamFinishErroring(stream) { + stream._state = 'errored'; + stream._writableStreamController[ErrorSteps](); + const storedError = stream._storedError; + stream._writeRequests.forEach(writeRequest => { + writeRequest._reject(storedError); + }); + stream._writeRequests = new SimpleQueue(); + if (stream._pendingAbortRequest === undefined) { + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const abortRequest = stream._pendingAbortRequest; + stream._pendingAbortRequest = undefined; + if (abortRequest._wasAlreadyErroring) { + abortRequest._reject(storedError); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const promise = stream._writableStreamController[AbortSteps](abortRequest._reason); + uponPromise(promise, () => { + abortRequest._resolve(); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }, (reason) => { + abortRequest._reject(reason); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }); + } + function WritableStreamFinishInFlightWrite(stream) { + stream._inFlightWriteRequest._resolve(undefined); + stream._inFlightWriteRequest = undefined; + } + function WritableStreamFinishInFlightWriteWithError(stream, error) { + stream._inFlightWriteRequest._reject(error); + stream._inFlightWriteRequest = undefined; + WritableStreamDealWithRejection(stream, error); + } + function WritableStreamFinishInFlightClose(stream) { + stream._inFlightCloseRequest._resolve(undefined); + stream._inFlightCloseRequest = undefined; + const state = stream._state; + if (state === 'erroring') { + // The error was too late to do anything, so it is ignored. + stream._storedError = undefined; + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._resolve(); + stream._pendingAbortRequest = undefined; + } + } + stream._state = 'closed'; + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseResolve(writer); + } + } + function WritableStreamFinishInFlightCloseWithError(stream, error) { + stream._inFlightCloseRequest._reject(error); + stream._inFlightCloseRequest = undefined; + // Never execute sink abort() after sink close(). + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._reject(error); + stream._pendingAbortRequest = undefined; + } + WritableStreamDealWithRejection(stream, error); + } + // TODO(ricea): Fix alphabetical order. + function WritableStreamCloseQueuedOrInFlight(stream) { + if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; + } + function WritableStreamHasOperationMarkedInFlight(stream) { + if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; + } + function WritableStreamMarkCloseRequestInFlight(stream) { + stream._inFlightCloseRequest = stream._closeRequest; + stream._closeRequest = undefined; + } + function WritableStreamMarkFirstWriteRequestInFlight(stream) { + stream._inFlightWriteRequest = stream._writeRequests.shift(); + } + function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { + if (stream._closeRequest !== undefined) { + stream._closeRequest._reject(stream._storedError); + stream._closeRequest = undefined; + } + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseReject(writer, stream._storedError); + } + } + function WritableStreamUpdateBackpressure(stream, backpressure) { + const writer = stream._writer; + if (writer !== undefined && backpressure !== stream._backpressure) { + if (backpressure) { + defaultWriterReadyPromiseReset(writer); + } + else { + defaultWriterReadyPromiseResolve(writer); + } + } + stream._backpressure = backpressure; + } + /** + * A default writer vended by a {@link WritableStream}. + * + * @public + */ + class WritableStreamDefaultWriter { + constructor(stream) { + assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter'); + assertWritableStream(stream, 'First parameter'); + if (IsWritableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive writing by another writer'); + } + this._ownerWritableStream = stream; + stream._writer = this; + const state = stream._state; + if (state === 'writable') { + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { + defaultWriterReadyPromiseInitialize(this); + } + else { + defaultWriterReadyPromiseInitializeAsResolved(this); + } + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'erroring') { + defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'closed') { + defaultWriterReadyPromiseInitializeAsResolved(this); + defaultWriterClosedPromiseInitializeAsResolved(this); + } + else { + const storedError = stream._storedError; + defaultWriterReadyPromiseInitializeAsRejected(this, storedError); + defaultWriterClosedPromiseInitializeAsRejected(this, storedError); + } + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the writer’s lock is released before the stream finishes closing. + */ + get closed() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. + * A producer can use this information to determine the right amount of data to write. + * + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when + * the writer’s lock is released. + */ + get desiredSize() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('desiredSize'); + } + if (this._ownerWritableStream === undefined) { + throw defaultWriterLockException('desiredSize'); + } + return WritableStreamDefaultWriterGetDesiredSize(this); + } + /** + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips + * back to zero or below, the getter will return a new promise that stays pending until the next transition. + * + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become + * rejected. + */ + get ready() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('ready')); + } + return this._readyPromise; + } + /** + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + */ + abort(reason = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('abort')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('abort')); + } + return WritableStreamDefaultWriterAbort(this, reason); + } + /** + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + */ + close() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('close')); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return promiseRejectedWith(defaultWriterLockException('close')); + } + if (WritableStreamCloseQueuedOrInFlight(stream)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamDefaultWriterClose(this); + } + /** + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from + * now on; otherwise, the writer will appear closed. + * + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents + * other producers from writing in an interleaved manner. + */ + releaseLock() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('releaseLock'); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return; + } + WritableStreamDefaultWriterRelease(this); + } + write(chunk = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('write')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + return WritableStreamDefaultWriterWrite(this, chunk); + } + } + Object.defineProperties(WritableStreamDefaultWriter.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + releaseLock: { enumerable: true }, + write: { enumerable: true }, + closed: { enumerable: true }, + desiredSize: { enumerable: true }, + ready: { enumerable: true } + }); + setFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort'); + setFunctionName(WritableStreamDefaultWriter.prototype.close, 'close'); + setFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock'); + setFunctionName(WritableStreamDefaultWriter.prototype.write, 'write'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, { + value: 'WritableStreamDefaultWriter', + configurable: true + }); + } + // Abstract operations for the WritableStreamDefaultWriter. + function IsWritableStreamDefaultWriter(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultWriter; + } + // A client of WritableStreamDefaultWriter may use these functions directly to bypass state check. + function WritableStreamDefaultWriterAbort(writer, reason) { + const stream = writer._ownerWritableStream; + return WritableStreamAbort(stream, reason); + } + function WritableStreamDefaultWriterClose(writer) { + const stream = writer._ownerWritableStream; + return WritableStreamClose(stream); + } + function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseResolvedWith(undefined); + } + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + return WritableStreamDefaultWriterClose(writer); + } + function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { + if (writer._closedPromiseState === 'pending') { + defaultWriterClosedPromiseReject(writer, error); + } + else { + defaultWriterClosedPromiseResetToRejected(writer, error); + } + } + function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { + if (writer._readyPromiseState === 'pending') { + defaultWriterReadyPromiseReject(writer, error); + } + else { + defaultWriterReadyPromiseResetToRejected(writer, error); + } + } + function WritableStreamDefaultWriterGetDesiredSize(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (state === 'errored' || state === 'erroring') { + return null; + } + if (state === 'closed') { + return 0; + } + return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); + } + function WritableStreamDefaultWriterRelease(writer) { + const stream = writer._ownerWritableStream; + const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`); + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); + // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not + // rejected until afterwards. This means that simply testing state will not work. + WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); + stream._writer = undefined; + writer._ownerWritableStream = undefined; + } + function WritableStreamDefaultWriterWrite(writer, chunk) { + const stream = writer._ownerWritableStream; + const controller = stream._writableStreamController; + const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); + if (stream !== writer._ownerWritableStream) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + const state = stream._state; + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to')); + } + if (state === 'erroring') { + return promiseRejectedWith(stream._storedError); + } + const promise = WritableStreamAddWriteRequest(stream); + WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); + return promise; + } + const closeSentinel = {}; + /** + * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. + * + * @public + */ + class WritableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. + * + * @deprecated + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. + */ + get abortReason() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('abortReason'); + } + return this._abortReason; + } + /** + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. + */ + get signal() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('signal'); + } + if (this._abortController === undefined) { + // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`. + // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill, + // so instead we only implement support for `signal` if we find a global `AbortController` constructor. + throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported'); + } + return this._abortController.signal; + } + /** + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. + * + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the + * normal lifecycle of interactions with the underlying sink. + */ + error(e = undefined) { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('error'); + } + const state = this._controlledWritableStream._state; + if (state !== 'writable') { + // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so + // just treat it as a no-op. + return; + } + WritableStreamDefaultControllerError(this, e); + } + /** @internal */ + [AbortSteps](reason) { + const result = this._abortAlgorithm(reason); + WritableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [ErrorSteps]() { + ResetQueue(this); + } + } + Object.defineProperties(WritableStreamDefaultController.prototype, { + abortReason: { enumerable: true }, + signal: { enumerable: true }, + error: { enumerable: true } + }); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, { + value: 'WritableStreamDefaultController', + configurable: true + }); + } + // Abstract operations implementing interface required by the WritableStream. + function IsWritableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultController; + } + function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledWritableStream = stream; + stream._writableStreamController = controller; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._abortReason = undefined; + controller._abortController = createAbortController(); + controller._started = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._writeAlgorithm = writeAlgorithm; + controller._closeAlgorithm = closeAlgorithm; + controller._abortAlgorithm = abortAlgorithm; + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + const startResult = startAlgorithm(); + const startPromise = promiseResolvedWith(startResult); + uponPromise(startPromise, () => { + controller._started = true; + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, r => { + controller._started = true; + WritableStreamDealWithRejection(stream, r); + return null; + }); + } + function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { + const controller = Object.create(WritableStreamDefaultController.prototype); + let startAlgorithm; + let writeAlgorithm; + let closeAlgorithm; + let abortAlgorithm; + if (underlyingSink.start !== undefined) { + startAlgorithm = () => underlyingSink.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingSink.write !== undefined) { + writeAlgorithm = chunk => underlyingSink.write(chunk, controller); + } + else { + writeAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSink.close !== undefined) { + closeAlgorithm = () => underlyingSink.close(); + } + else { + closeAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSink.abort !== undefined) { + abortAlgorithm = reason => underlyingSink.abort(reason); + } + else { + abortAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + } + // ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls. + function WritableStreamDefaultControllerClearAlgorithms(controller) { + controller._writeAlgorithm = undefined; + controller._closeAlgorithm = undefined; + controller._abortAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; + } + function WritableStreamDefaultControllerClose(controller) { + EnqueueValueWithSize(controller, closeSentinel, 0); + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + } + function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { + try { + return controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); + return 1; + } + } + function WritableStreamDefaultControllerGetDesiredSize(controller) { + return controller._strategyHWM - controller._queueTotalSize; + } + function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); + return; + } + const stream = controller._controlledWritableStream; + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + } + // Abstract operations for the WritableStreamDefaultController. + function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { + const stream = controller._controlledWritableStream; + if (!controller._started) { + return; + } + if (stream._inFlightWriteRequest !== undefined) { + return; + } + const state = stream._state; + if (state === 'erroring') { + WritableStreamFinishErroring(stream); + return; + } + if (controller._queue.length === 0) { + return; + } + const value = PeekQueueValue(controller); + if (value === closeSentinel) { + WritableStreamDefaultControllerProcessClose(controller); + } + else { + WritableStreamDefaultControllerProcessWrite(controller, value); + } + } + function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { + if (controller._controlledWritableStream._state === 'writable') { + WritableStreamDefaultControllerError(controller, error); + } + } + function WritableStreamDefaultControllerProcessClose(controller) { + const stream = controller._controlledWritableStream; + WritableStreamMarkCloseRequestInFlight(stream); + DequeueValue(controller); + const sinkClosePromise = controller._closeAlgorithm(); + WritableStreamDefaultControllerClearAlgorithms(controller); + uponPromise(sinkClosePromise, () => { + WritableStreamFinishInFlightClose(stream); + return null; + }, reason => { + WritableStreamFinishInFlightCloseWithError(stream, reason); + return null; + }); + } + function WritableStreamDefaultControllerProcessWrite(controller, chunk) { + const stream = controller._controlledWritableStream; + WritableStreamMarkFirstWriteRequestInFlight(stream); + const sinkWritePromise = controller._writeAlgorithm(chunk); + uponPromise(sinkWritePromise, () => { + WritableStreamFinishInFlightWrite(stream); + const state = stream._state; + DequeueValue(controller); + if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, reason => { + if (stream._state === 'writable') { + WritableStreamDefaultControllerClearAlgorithms(controller); + } + WritableStreamFinishInFlightWriteWithError(stream, reason); + return null; + }); + } + function WritableStreamDefaultControllerGetBackpressure(controller) { + const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); + return desiredSize <= 0; + } + // A client of WritableStreamDefaultController may use these functions directly to bypass state check. + function WritableStreamDefaultControllerError(controller, error) { + const stream = controller._controlledWritableStream; + WritableStreamDefaultControllerClearAlgorithms(controller); + WritableStreamStartErroring(stream, error); + } + // Helper functions for the WritableStream. + function streamBrandCheckException$2(name) { + return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`); + } + // Helper functions for the WritableStreamDefaultController. + function defaultControllerBrandCheckException$2(name) { + return new TypeError(`WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`); + } + // Helper functions for the WritableStreamDefaultWriter. + function defaultWriterBrandCheckException(name) { + return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`); + } + function defaultWriterLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released writer'); + } + function defaultWriterClosedPromiseInitialize(writer) { + writer._closedPromise = newPromise((resolve, reject) => { + writer._closedPromise_resolve = resolve; + writer._closedPromise_reject = reject; + writer._closedPromiseState = 'pending'; + }); + } + function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseReject(writer, reason); + } + function defaultWriterClosedPromiseInitializeAsResolved(writer) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseResolve(writer); + } + function defaultWriterClosedPromiseReject(writer, reason) { + if (writer._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._closedPromise); + writer._closedPromise_reject(reason); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'rejected'; + } + function defaultWriterClosedPromiseResetToRejected(writer, reason) { + defaultWriterClosedPromiseInitializeAsRejected(writer, reason); + } + function defaultWriterClosedPromiseResolve(writer) { + if (writer._closedPromise_resolve === undefined) { + return; + } + writer._closedPromise_resolve(undefined); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'resolved'; + } + function defaultWriterReadyPromiseInitialize(writer) { + writer._readyPromise = newPromise((resolve, reject) => { + writer._readyPromise_resolve = resolve; + writer._readyPromise_reject = reject; + }); + writer._readyPromiseState = 'pending'; + } + function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseReject(writer, reason); + } + function defaultWriterReadyPromiseInitializeAsResolved(writer) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseResolve(writer); + } + function defaultWriterReadyPromiseReject(writer, reason) { + if (writer._readyPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._readyPromise); + writer._readyPromise_reject(reason); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'rejected'; + } + function defaultWriterReadyPromiseReset(writer) { + defaultWriterReadyPromiseInitialize(writer); + } + function defaultWriterReadyPromiseResetToRejected(writer, reason) { + defaultWriterReadyPromiseInitializeAsRejected(writer, reason); + } + function defaultWriterReadyPromiseResolve(writer) { + if (writer._readyPromise_resolve === undefined) { + return; + } + writer._readyPromise_resolve(undefined); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'fulfilled'; + } + + /// + function getGlobals() { + if (typeof globalThis !== 'undefined') { + return globalThis; + } + else if (typeof self !== 'undefined') { + return self; + } + else if (typeof global !== 'undefined') { + return global; + } + return undefined; + } + const globals = getGlobals(); + + /// + function isDOMExceptionConstructor(ctor) { + if (!(typeof ctor === 'function' || typeof ctor === 'object')) { + return false; + } + if (ctor.name !== 'DOMException') { + return false; + } + try { + new ctor(); + return true; + } + catch (_a) { + return false; + } + } + /** + * Support: + * - Web browsers + * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87) + */ + function getFromGlobal() { + const ctor = globals === null || globals === void 0 ? void 0 : globals.DOMException; + return isDOMExceptionConstructor(ctor) ? ctor : undefined; + } + /** + * Support: + * - All platforms + */ + function createPolyfill() { + // eslint-disable-next-line @typescript-eslint/no-shadow + const ctor = function DOMException(message, name) { + this.message = message || ''; + this.name = name || 'Error'; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + }; + setFunctionName(ctor, 'DOMException'); + ctor.prototype = Object.create(Error.prototype); + Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true }); + return ctor; + } + // eslint-disable-next-line @typescript-eslint/no-redeclare + const DOMException = getFromGlobal() || createPolyfill(); + + function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { + const reader = AcquireReadableStreamDefaultReader(source); + const writer = AcquireWritableStreamDefaultWriter(dest); + source._disturbed = true; + let shuttingDown = false; + // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown. + let currentWrite = promiseResolvedWith(undefined); + return newPromise((resolve, reject) => { + let abortAlgorithm; + if (signal !== undefined) { + abortAlgorithm = () => { + const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError'); + const actions = []; + if (!preventAbort) { + actions.push(() => { + if (dest._state === 'writable') { + return WritableStreamAbort(dest, error); + } + return promiseResolvedWith(undefined); + }); + } + if (!preventCancel) { + actions.push(() => { + if (source._state === 'readable') { + return ReadableStreamCancel(source, error); + } + return promiseResolvedWith(undefined); + }); + } + shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error); + }; + if (signal.aborted) { + abortAlgorithm(); + return; + } + signal.addEventListener('abort', abortAlgorithm); + } + // Using reader and writer, read all chunks from this and write them to dest + // - Backpressure must be enforced + // - Shutdown must stop all activity + function pipeLoop() { + return newPromise((resolveLoop, rejectLoop) => { + function next(done) { + if (done) { + resolveLoop(); + } + else { + // Use `PerformPromiseThen` instead of `uponPromise` to avoid + // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers + PerformPromiseThen(pipeStep(), next, rejectLoop); + } + } + next(false); + }); + } + function pipeStep() { + if (shuttingDown) { + return promiseResolvedWith(true); + } + return PerformPromiseThen(writer._readyPromise, () => { + return newPromise((resolveRead, rejectRead) => { + ReadableStreamDefaultReaderRead(reader, { + _chunkSteps: chunk => { + currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop); + resolveRead(false); + }, + _closeSteps: () => resolveRead(true), + _errorSteps: rejectRead + }); + }); + }); + } + // Errors must be propagated forward + isOrBecomesErrored(source, reader._closedPromise, storedError => { + if (!preventAbort) { + shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Errors must be propagated backward + isOrBecomesErrored(dest, writer._closedPromise, storedError => { + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Closing must be propagated forward + isOrBecomesClosed(source, reader._closedPromise, () => { + if (!preventClose) { + shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer)); + } + else { + shutdown(); + } + return null; + }); + // Closing must be propagated backward + if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') { + const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it'); + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed); + } + else { + shutdown(true, destClosed); + } + } + setPromiseIsHandledToTrue(pipeLoop()); + function waitForWritesToFinish() { + // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait + // for that too. + const oldCurrentWrite = currentWrite; + return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined); + } + function isOrBecomesErrored(stream, promise, action) { + if (stream._state === 'errored') { + action(stream._storedError); + } + else { + uponRejection(promise, action); + } + } + function isOrBecomesClosed(stream, promise, action) { + if (stream._state === 'closed') { + action(); + } + else { + uponFulfillment(promise, action); + } + } + function shutdownWithAction(action, originalIsError, originalError) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), doTheRest); + } + else { + doTheRest(); + } + function doTheRest() { + uponPromise(action(), () => finalize(originalIsError, originalError), newError => finalize(true, newError)); + return null; + } + } + function shutdown(isError, error) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error)); + } + else { + finalize(isError, error); + } + } + function finalize(isError, error) { + WritableStreamDefaultWriterRelease(writer); + ReadableStreamReaderGenericRelease(reader); + if (signal !== undefined) { + signal.removeEventListener('abort', abortAlgorithm); + } + if (isError) { + reject(error); + } + else { + resolve(undefined); + } + return null; + } + }); + } + + /** + * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. + * + * @public + */ + class ReadableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('desiredSize'); + } + return ReadableStreamDefaultControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('close'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits close'); + } + ReadableStreamDefaultControllerClose(this); + } + enqueue(chunk = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('enqueue'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits enqueue'); + } + return ReadableStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('error'); + } + ReadableStreamDefaultControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableStream; + if (this._queue.length > 0) { + const chunk = DequeueValue(this); + if (this._closeRequested && this._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(this); + ReadableStreamClose(stream); + } + else { + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + readRequest._chunkSteps(chunk); + } + else { + ReadableStreamAddReadRequest(stream, readRequest); + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + } + /** @internal */ + [ReleaseSteps]() { + // Do nothing. + } + } + Object.defineProperties(ReadableStreamDefaultController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + desiredSize: { enumerable: true } + }); + setFunctionName(ReadableStreamDefaultController.prototype.close, 'close'); + setFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue'); + setFunctionName(ReadableStreamDefaultController.prototype.error, 'error'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, { + value: 'ReadableStreamDefaultController', + configurable: true + }); + } + // Abstract operations for the ReadableStreamDefaultController. + function IsReadableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) { + return false; + } + return x instanceof ReadableStreamDefaultController; + } + function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + return null; + }, e => { + ReadableStreamDefaultControllerError(controller, e); + return null; + }); + } + function ReadableStreamDefaultControllerShouldCallPull(controller) { + const stream = controller._controlledReadableStream; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return false; + } + if (!controller._started) { + return false; + } + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; + } + function ReadableStreamDefaultControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; + } + // A client of ReadableStreamDefaultController may use these functions directly to bypass state check. + function ReadableStreamDefaultControllerClose(controller) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + controller._closeRequested = true; + if (controller._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } + } + function ReadableStreamDefaultControllerEnqueue(controller, chunk) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + ReadableStreamFulfillReadRequest(stream, chunk, false); + } + else { + let chunkSize; + try { + chunkSize = controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + ReadableStreamDefaultControllerError(controller, chunkSizeE); + throw chunkSizeE; + } + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + ReadableStreamDefaultControllerError(controller, enqueueE); + throw enqueueE; + } + } + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + function ReadableStreamDefaultControllerError(controller, e) { + const stream = controller._controlledReadableStream; + if (stream._state !== 'readable') { + return; + } + ResetQueue(controller); + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); + } + function ReadableStreamDefaultControllerGetDesiredSize(controller) { + const state = controller._controlledReadableStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; + } + // This is used in the implementation of TransformStream. + function ReadableStreamDefaultControllerHasBackpressure(controller) { + if (ReadableStreamDefaultControllerShouldCallPull(controller)) { + return false; + } + return true; + } + function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { + const state = controller._controlledReadableStream._state; + if (!controller._closeRequested && state === 'readable') { + return true; + } + return false; + } + function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledReadableStream = stream; + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._started = false; + controller._closeRequested = false; + controller._pullAgain = false; + controller._pulling = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + return null; + }, r => { + ReadableStreamDefaultControllerError(controller, r); + return null; + }); + } + function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { + const controller = Object.create(ReadableStreamDefaultController.prototype); + let startAlgorithm; + let pullAlgorithm; + let cancelAlgorithm; + if (underlyingSource.start !== undefined) { + startAlgorithm = () => underlyingSource.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingSource.pull !== undefined) { + pullAlgorithm = () => underlyingSource.pull(controller); + } + else { + pullAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingSource.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + } + // Helper functions for the ReadableStreamDefaultController. + function defaultControllerBrandCheckException$1(name) { + return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`); + } + + function ReadableStreamTee(stream, cloneForBranch2) { + if (IsReadableByteStreamController(stream._readableStreamController)) { + return ReadableByteStreamTee(stream); + } + return ReadableStreamDefaultTee(stream); + } + function ReadableStreamDefaultTee(stream, cloneForBranch2) { + const reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgain = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function pullAlgorithm() { + if (reading) { + readAgain = true; + return promiseResolvedWith(undefined); + } + reading = true; + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgain = false; + const chunk1 = chunk; + const chunk2 = chunk; + // There is no way to access the cloning code right now in the reference implementation. + // If we add one then we'll need an implementation for serializable objects. + // if (!canceled2 && cloneForBranch2) { + // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2)); + // } + if (!canceled1) { + ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgain) { + pullAlgorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableStreamDefaultControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableStreamDefaultControllerClose(branch2._readableStreamController); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + // do nothing + } + branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); + branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); + uponRejection(reader._closedPromise, (r) => { + ReadableStreamDefaultControllerError(branch1._readableStreamController, r); + ReadableStreamDefaultControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + return [branch1, branch2]; + } + function ReadableByteStreamTee(stream) { + let reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgainForBranch1 = false; + let readAgainForBranch2 = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function forwardReaderError(thisReader) { + uponRejection(thisReader._closedPromise, r => { + if (thisReader !== reader) { + return null; + } + ReadableByteStreamControllerError(branch1._readableStreamController, r); + ReadableByteStreamControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + } + function pullWithDefaultReader() { + if (IsReadableStreamBYOBReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamDefaultReader(stream); + forwardReaderError(reader); + } + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const chunk1 = chunk; + let chunk2 = chunk; + if (!canceled1 && !canceled2) { + try { + chunk2 = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(branch1._readableStreamController, cloneE); + ReadableByteStreamControllerError(branch2._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + } + if (!canceled1) { + ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableByteStreamControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableByteStreamControllerClose(branch2._readableStreamController); + } + if (branch1._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch1._readableStreamController, 0); + } + if (branch2._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch2._readableStreamController, 0); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + } + function pullWithBYOBReader(view, forBranch2) { + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamBYOBReader(stream); + forwardReaderError(reader); + } + const byobBranch = forBranch2 ? branch2 : branch1; + const otherBranch = forBranch2 ? branch1 : branch2; + const readIntoRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!otherCanceled) { + let clonedChunk; + try { + clonedChunk = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE); + ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk); + } + else if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: chunk => { + reading = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!byobCanceled) { + ReadableByteStreamControllerClose(byobBranch._readableStreamController); + } + if (!otherCanceled) { + ReadableByteStreamControllerClose(otherBranch._readableStreamController); + } + if (chunk !== undefined) { + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0); + } + } + if (!byobCanceled || !otherCanceled) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest); + } + function pull1Algorithm() { + if (reading) { + readAgainForBranch1 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, false); + } + return promiseResolvedWith(undefined); + } + function pull2Algorithm() { + if (reading) { + readAgainForBranch2 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, true); + } + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + return; + } + branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm); + branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm); + forwardReaderError(reader); + return [branch1, branch2]; + } + + function isReadableStreamLike(stream) { + return typeIsObject(stream) && typeof stream.getReader !== 'undefined'; + } + + function ReadableStreamFrom(source) { + if (isReadableStreamLike(source)) { + return ReadableStreamFromDefaultReader(source.getReader()); + } + return ReadableStreamFromIterable(source); + } + function ReadableStreamFromIterable(asyncIterable) { + let stream; + const iteratorRecord = GetIterator(asyncIterable, 'async'); + const startAlgorithm = noop; + function pullAlgorithm() { + let nextResult; + try { + nextResult = IteratorNext(iteratorRecord); + } + catch (e) { + return promiseRejectedWith(e); + } + const nextPromise = promiseResolvedWith(nextResult); + return transformPromiseWith(nextPromise, iterResult => { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object'); + } + const done = IteratorComplete(iterResult); + if (done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + const value = IteratorValue(iterResult); + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + const iterator = iteratorRecord.iterator; + let returnMethod; + try { + returnMethod = GetMethod(iterator, 'return'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (returnMethod === undefined) { + return promiseResolvedWith(undefined); + } + let returnResult; + try { + returnResult = reflectCall(returnMethod, iterator, [reason]); + } + catch (e) { + return promiseRejectedWith(e); + } + const returnPromise = promiseResolvedWith(returnResult); + return transformPromiseWith(returnPromise, iterResult => { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object'); + } + return undefined; + }); + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; + } + function ReadableStreamFromDefaultReader(reader) { + let stream; + const startAlgorithm = noop; + function pullAlgorithm() { + let readPromise; + try { + readPromise = reader.read(); + } + catch (e) { + return promiseRejectedWith(e); + } + return transformPromiseWith(readPromise, readResult => { + if (!typeIsObject(readResult)) { + throw new TypeError('The promise returned by the reader.read() method must fulfill with an object'); + } + if (readResult.done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + const value = readResult.value; + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + try { + return promiseResolvedWith(reader.cancel(reason)); + } + catch (e) { + return promiseRejectedWith(e); + } + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; + } + + function convertUnderlyingDefaultOrByteSource(source, context) { + assertDictionary(source, context); + const original = source; + const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; + const cancel = original === null || original === void 0 ? void 0 : original.cancel; + const pull = original === null || original === void 0 ? void 0 : original.pull; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + return { + autoAllocateChunkSize: autoAllocateChunkSize === undefined ? + undefined : + convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`), + cancel: cancel === undefined ? + undefined : + convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`), + pull: pull === undefined ? + undefined : + convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`), + start: start === undefined ? + undefined : + convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`), + type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`) + }; + } + function convertUnderlyingSourceCancelCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); + } + function convertUnderlyingSourcePullCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); + } + function convertUnderlyingSourceStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertReadableStreamType(type, context) { + type = `${type}`; + if (type !== 'bytes') { + throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`); + } + return type; + } + + function convertIteratorOptions(options, context) { + assertDictionary(options, context); + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + return { preventCancel: Boolean(preventCancel) }; + } + + function convertPipeOptions(options, context) { + assertDictionary(options, context); + const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort; + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + const preventClose = options === null || options === void 0 ? void 0 : options.preventClose; + const signal = options === null || options === void 0 ? void 0 : options.signal; + if (signal !== undefined) { + assertAbortSignal(signal, `${context} has member 'signal' that`); + } + return { + preventAbort: Boolean(preventAbort), + preventCancel: Boolean(preventCancel), + preventClose: Boolean(preventClose), + signal + }; + } + function assertAbortSignal(signal, context) { + if (!isAbortSignal(signal)) { + throw new TypeError(`${context} is not an AbortSignal.`); + } + } + + function convertReadableWritablePair(pair, context) { + assertDictionary(pair, context); + const readable = pair === null || pair === void 0 ? void 0 : pair.readable; + assertRequiredField(readable, 'readable', 'ReadableWritablePair'); + assertReadableStream(readable, `${context} has member 'readable' that`); + const writable = pair === null || pair === void 0 ? void 0 : pair.writable; + assertRequiredField(writable, 'writable', 'ReadableWritablePair'); + assertWritableStream(writable, `${context} has member 'writable' that`); + return { readable, writable }; + } + + /** + * A readable stream represents a source of data, from which you can read. + * + * @public + */ + class ReadableStream { + constructor(rawUnderlyingSource = {}, rawStrategy = {}) { + if (rawUnderlyingSource === undefined) { + rawUnderlyingSource = null; + } + else { + assertObject(rawUnderlyingSource, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter'); + InitializeReadableStream(this); + if (underlyingSource.type === 'bytes') { + if (strategy.size !== undefined) { + throw new RangeError('The strategy for a byte stream cannot have a size function'); + } + const highWaterMark = ExtractHighWaterMark(strategy, 0); + SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); + } + else { + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); + } + } + /** + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. + */ + get locked() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('locked'); + } + return IsReadableStreamLocked(this); + } + /** + * Cancels the stream, signaling a loss of interest in the stream by a consumer. + * + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} + * method, which might or might not use it. + */ + cancel(reason = undefined) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('cancel')); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader')); + } + return ReadableStreamCancel(this, reason); + } + getReader(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('getReader'); + } + const options = convertReaderOptions(rawOptions, 'First parameter'); + if (options.mode === undefined) { + return AcquireReadableStreamDefaultReader(this); + } + return AcquireReadableStreamBYOBReader(this); + } + pipeThrough(rawTransform, rawOptions = {}) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('pipeThrough'); + } + assertRequiredArgument(rawTransform, 1, 'pipeThrough'); + const transform = convertReadableWritablePair(rawTransform, 'First parameter'); + const options = convertPipeOptions(rawOptions, 'Second parameter'); + if (IsReadableStreamLocked(this)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream'); + } + if (IsWritableStreamLocked(transform.writable)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream'); + } + const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + setPromiseIsHandledToTrue(promise); + return transform.readable; + } + pipeTo(destination, rawOptions = {}) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('pipeTo')); + } + if (destination === undefined) { + return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`); + } + if (!IsWritableStream(destination)) { + return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)); + } + let options; + try { + options = convertPipeOptions(rawOptions, 'Second parameter'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')); + } + if (IsWritableStreamLocked(destination)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')); + } + return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + } + /** + * Tees this readable stream, returning a two-element array containing the two resulting branches as + * new {@link ReadableStream} instances. + * + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be + * propagated to the stream's underlying source. + * + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, + * this could allow interference between the two branches. + */ + tee() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('tee'); + } + const branches = ReadableStreamTee(this); + return CreateArrayFromList(branches); + } + values(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('values'); + } + const options = convertIteratorOptions(rawOptions, 'First parameter'); + return AcquireReadableStreamAsyncIterator(this, options.preventCancel); + } + [SymbolAsyncIterator](options) { + // Stub implementation, overridden below + return this.values(options); + } + /** + * Creates a new ReadableStream wrapping the provided iterable or async iterable. + * + * This can be used to adapt various kinds of objects into a readable stream, + * such as an array, an async generator, or a Node.js readable stream. + */ + static from(asyncIterable) { + return ReadableStreamFrom(asyncIterable); + } + } + Object.defineProperties(ReadableStream, { + from: { enumerable: true } + }); + Object.defineProperties(ReadableStream.prototype, { + cancel: { enumerable: true }, + getReader: { enumerable: true }, + pipeThrough: { enumerable: true }, + pipeTo: { enumerable: true }, + tee: { enumerable: true }, + values: { enumerable: true }, + locked: { enumerable: true } + }); + setFunctionName(ReadableStream.from, 'from'); + setFunctionName(ReadableStream.prototype.cancel, 'cancel'); + setFunctionName(ReadableStream.prototype.getReader, 'getReader'); + setFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough'); + setFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo'); + setFunctionName(ReadableStream.prototype.tee, 'tee'); + setFunctionName(ReadableStream.prototype.values, 'values'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, { + value: 'ReadableStream', + configurable: true + }); + } + Object.defineProperty(ReadableStream.prototype, SymbolAsyncIterator, { + value: ReadableStream.prototype.values, + writable: true, + configurable: true + }); + // Abstract operations for the ReadableStream. + // Throws if and only if startAlgorithm throws. + function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableStreamDefaultController.prototype); + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + return stream; + } + // Throws if and only if startAlgorithm throws. + function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableByteStreamController.prototype); + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined); + return stream; + } + function InitializeReadableStream(stream) { + stream._state = 'readable'; + stream._reader = undefined; + stream._storedError = undefined; + stream._disturbed = false; + } + function IsReadableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) { + return false; + } + return x instanceof ReadableStream; + } + function IsReadableStreamLocked(stream) { + if (stream._reader === undefined) { + return false; + } + return true; + } + // ReadableStream API exposed for controllers. + function ReadableStreamCancel(stream, reason) { + stream._disturbed = true; + if (stream._state === 'closed') { + return promiseResolvedWith(undefined); + } + if (stream._state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + ReadableStreamClose(stream); + const reader = stream._reader; + if (reader !== undefined && IsReadableStreamBYOBReader(reader)) { + const readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._closeSteps(undefined); + }); + } + const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); + return transformPromiseWith(sourceCancelPromise, noop); + } + function ReadableStreamClose(stream) { + stream._state = 'closed'; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseResolve(reader); + if (IsReadableStreamDefaultReader(reader)) { + const readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(readRequest => { + readRequest._closeSteps(); + }); + } + } + function ReadableStreamError(stream, e) { + stream._state = 'errored'; + stream._storedError = e; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseReject(reader, e); + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamDefaultReaderErrorReadRequests(reader, e); + } + else { + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); + } + } + // Helper functions for the ReadableStream. + function streamBrandCheckException$1(name) { + return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`); + } + + function convertQueuingStrategyInit(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit'); + return { + highWaterMark: convertUnrestrictedDouble(highWaterMark) + }; + } + + // The size function must not have a prototype property nor be a constructor + const byteLengthSizeFunction = (chunk) => { + return chunk.byteLength; + }; + setFunctionName(byteLengthSizeFunction, 'size'); + /** + * A queuing strategy that counts the number of bytes in each chunk. + * + * @public + */ + class ByteLengthQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('highWaterMark'); + } + return this._byteLengthQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by returning the value of its `byteLength` property. + */ + get size() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('size'); + } + return byteLengthSizeFunction; + } + } + Object.defineProperties(ByteLengthQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, { + value: 'ByteLengthQueuingStrategy', + configurable: true + }); + } + // Helper functions for the ByteLengthQueuingStrategy. + function byteLengthBrandCheckException(name) { + return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`); + } + function IsByteLengthQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof ByteLengthQueuingStrategy; + } + + // The size function must not have a prototype property nor be a constructor + const countSizeFunction = () => { + return 1; + }; + setFunctionName(countSizeFunction, 'size'); + /** + * A queuing strategy that counts the number of chunks. + * + * @public + */ + class CountQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'CountQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._countQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('highWaterMark'); + } + return this._countQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by always returning 1. + * This ensures that the total queue size is a count of the number of chunks in the queue. + */ + get size() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('size'); + } + return countSizeFunction; + } + } + Object.defineProperties(CountQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, { + value: 'CountQueuingStrategy', + configurable: true + }); + } + // Helper functions for the CountQueuingStrategy. + function countBrandCheckException(name) { + return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`); + } + function IsCountQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof CountQueuingStrategy; + } + + function convertTransformer(original, context) { + assertDictionary(original, context); + const cancel = original === null || original === void 0 ? void 0 : original.cancel; + const flush = original === null || original === void 0 ? void 0 : original.flush; + const readableType = original === null || original === void 0 ? void 0 : original.readableType; + const start = original === null || original === void 0 ? void 0 : original.start; + const transform = original === null || original === void 0 ? void 0 : original.transform; + const writableType = original === null || original === void 0 ? void 0 : original.writableType; + return { + cancel: cancel === undefined ? + undefined : + convertTransformerCancelCallback(cancel, original, `${context} has member 'cancel' that`), + flush: flush === undefined ? + undefined : + convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`), + readableType, + start: start === undefined ? + undefined : + convertTransformerStartCallback(start, original, `${context} has member 'start' that`), + transform: transform === undefined ? + undefined : + convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`), + writableType + }; + } + function convertTransformerFlushCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); + } + function convertTransformerStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertTransformerTransformCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); + } + function convertTransformerCancelCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); + } + + // Class TransformStream + /** + * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, + * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. + * In a manner specific to the transform stream in question, writes to the writable side result in new data being + * made available for reading from the readable side. + * + * @public + */ + class TransformStream { + constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) { + if (rawTransformer === undefined) { + rawTransformer = null; + } + const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter'); + const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter'); + const transformer = convertTransformer(rawTransformer, 'First parameter'); + if (transformer.readableType !== undefined) { + throw new RangeError('Invalid readableType specified'); + } + if (transformer.writableType !== undefined) { + throw new RangeError('Invalid writableType specified'); + } + const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); + const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); + const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); + const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); + let startPromise_resolve; + const startPromise = newPromise(resolve => { + startPromise_resolve = resolve; + }); + InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); + if (transformer.start !== undefined) { + startPromise_resolve(transformer.start(this._transformStreamController)); + } + else { + startPromise_resolve(undefined); + } + } + /** + * The readable side of the transform stream. + */ + get readable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('readable'); + } + return this._readable; + } + /** + * The writable side of the transform stream. + */ + get writable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('writable'); + } + return this._writable; + } + } + Object.defineProperties(TransformStream.prototype, { + readable: { enumerable: true }, + writable: { enumerable: true } + }); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, { + value: 'TransformStream', + configurable: true + }); + } + function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { + function startAlgorithm() { + return startPromise; + } + function writeAlgorithm(chunk) { + return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); + } + function abortAlgorithm(reason) { + return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); + } + function closeAlgorithm() { + return TransformStreamDefaultSinkCloseAlgorithm(stream); + } + stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); + function pullAlgorithm() { + return TransformStreamDefaultSourcePullAlgorithm(stream); + } + function cancelAlgorithm(reason) { + return TransformStreamDefaultSourceCancelAlgorithm(stream, reason); + } + stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure. + stream._backpressure = undefined; + stream._backpressureChangePromise = undefined; + stream._backpressureChangePromise_resolve = undefined; + TransformStreamSetBackpressure(stream, true); + stream._transformStreamController = undefined; + } + function IsTransformStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) { + return false; + } + return x instanceof TransformStream; + } + // This is a no-op if both sides are already errored. + function TransformStreamError(stream, e) { + ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e); + TransformStreamErrorWritableAndUnblockWrite(stream, e); + } + function TransformStreamErrorWritableAndUnblockWrite(stream, e) { + TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); + WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e); + TransformStreamUnblockWrite(stream); + } + function TransformStreamUnblockWrite(stream) { + if (stream._backpressure) { + // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure() + // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time + // _backpressure is set. + TransformStreamSetBackpressure(stream, false); + } + } + function TransformStreamSetBackpressure(stream, backpressure) { + // Passes also when called during construction. + if (stream._backpressureChangePromise !== undefined) { + stream._backpressureChangePromise_resolve(); + } + stream._backpressureChangePromise = newPromise(resolve => { + stream._backpressureChangePromise_resolve = resolve; + }); + stream._backpressure = backpressure; + } + // Class TransformStreamDefaultController + /** + * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. + * + * @public + */ + class TransformStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. + */ + get desiredSize() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('desiredSize'); + } + const readableController = this._controlledTransformStream._readable._readableStreamController; + return ReadableStreamDefaultControllerGetDesiredSize(readableController); + } + enqueue(chunk = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('enqueue'); + } + TransformStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors both the readable side and the writable side of the controlled transform stream, making all future + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. + */ + error(reason = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('error'); + } + TransformStreamDefaultControllerError(this, reason); + } + /** + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the + * transformer only needs to consume a portion of the chunks written to the writable side. + */ + terminate() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('terminate'); + } + TransformStreamDefaultControllerTerminate(this); + } + } + Object.defineProperties(TransformStreamDefaultController.prototype, { + enqueue: { enumerable: true }, + error: { enumerable: true }, + terminate: { enumerable: true }, + desiredSize: { enumerable: true } + }); + setFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue'); + setFunctionName(TransformStreamDefaultController.prototype.error, 'error'); + setFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate'); + if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, { + value: 'TransformStreamDefaultController', + configurable: true + }); + } + // Transform Stream Default Controller Abstract Operations + function IsTransformStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) { + return false; + } + return x instanceof TransformStreamDefaultController; + } + function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm) { + controller._controlledTransformStream = stream; + stream._transformStreamController = controller; + controller._transformAlgorithm = transformAlgorithm; + controller._flushAlgorithm = flushAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._finishPromise = undefined; + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; + } + function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { + const controller = Object.create(TransformStreamDefaultController.prototype); + let transformAlgorithm; + let flushAlgorithm; + let cancelAlgorithm; + if (transformer.transform !== undefined) { + transformAlgorithm = chunk => transformer.transform(chunk, controller); + } + else { + transformAlgorithm = chunk => { + try { + TransformStreamDefaultControllerEnqueue(controller, chunk); + return promiseResolvedWith(undefined); + } + catch (transformResultE) { + return promiseRejectedWith(transformResultE); + } + }; + } + if (transformer.flush !== undefined) { + flushAlgorithm = () => transformer.flush(controller); + } + else { + flushAlgorithm = () => promiseResolvedWith(undefined); + } + if (transformer.cancel !== undefined) { + cancelAlgorithm = reason => transformer.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm); + } + function TransformStreamDefaultControllerClearAlgorithms(controller) { + controller._transformAlgorithm = undefined; + controller._flushAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + } + function TransformStreamDefaultControllerEnqueue(controller, chunk) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { + throw new TypeError('Readable side is not in a state that permits enqueue'); + } + // We throttle transform invocations based on the backpressure of the ReadableStream, but we still + // accept TransformStreamDefaultControllerEnqueue() calls. + try { + ReadableStreamDefaultControllerEnqueue(readableController, chunk); + } + catch (e) { + // This happens when readableStrategy.size() throws. + TransformStreamErrorWritableAndUnblockWrite(stream, e); + throw stream._readable._storedError; + } + const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); + if (backpressure !== stream._backpressure) { + TransformStreamSetBackpressure(stream, true); + } + } + function TransformStreamDefaultControllerError(controller, e) { + TransformStreamError(controller._controlledTransformStream, e); + } + function TransformStreamDefaultControllerPerformTransform(controller, chunk) { + const transformPromise = controller._transformAlgorithm(chunk); + return transformPromiseWith(transformPromise, undefined, r => { + TransformStreamError(controller._controlledTransformStream, r); + throw r; + }); + } + function TransformStreamDefaultControllerTerminate(controller) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + ReadableStreamDefaultControllerClose(readableController); + const error = new TypeError('TransformStream terminated'); + TransformStreamErrorWritableAndUnblockWrite(stream, error); + } + // TransformStreamDefaultSink Algorithms + function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { + const controller = stream._transformStreamController; + if (stream._backpressure) { + const backpressureChangePromise = stream._backpressureChangePromise; + return transformPromiseWith(backpressureChangePromise, () => { + const writable = stream._writable; + const state = writable._state; + if (state === 'erroring') { + throw writable._storedError; + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + }); + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + } + function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + const readable = stream._readable; + // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally, + // we don't run the _cancelAlgorithm again. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, () => { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerError(readable._readableStreamController, reason); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; + } + function TransformStreamDefaultSinkCloseAlgorithm(stream) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + const readable = stream._readable; + // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally, + // we don't also run the _cancelAlgorithm. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const flushPromise = controller._flushAlgorithm(); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(flushPromise, () => { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerClose(readable._readableStreamController); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; + } + // TransformStreamDefaultSource Algorithms + function TransformStreamDefaultSourcePullAlgorithm(stream) { + // Invariant. Enforced by the promises returned by start() and pull(). + TransformStreamSetBackpressure(stream, false); + // Prevent the next pull() call until there is backpressure. + return stream._backpressureChangePromise; + } + function TransformStreamDefaultSourceCancelAlgorithm(stream, reason) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._writable cannot change after construction, so caching it across a call to user code is safe. + const writable = stream._writable; + // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or + // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the + // _flushAlgorithm. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, () => { + if (writable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, writable._storedError); + } + else { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; + } + // Helper functions for the TransformStreamDefaultController. + function defaultControllerBrandCheckException(name) { + return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`); + } + function defaultControllerFinishPromiseResolve(controller) { + if (controller._finishPromise_resolve === undefined) { + return; + } + controller._finishPromise_resolve(); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; + } + function defaultControllerFinishPromiseReject(controller, reason) { + if (controller._finishPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(controller._finishPromise); + controller._finishPromise_reject(reason); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; + } + // Helper functions for the TransformStream. + function streamBrandCheckException(name) { + return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`); + } + + exports.ByteLengthQueuingStrategy = ByteLengthQueuingStrategy; + exports.CountQueuingStrategy = CountQueuingStrategy; + exports.ReadableByteStreamController = ReadableByteStreamController; + exports.ReadableStream = ReadableStream; + exports.ReadableStreamBYOBReader = ReadableStreamBYOBReader; + exports.ReadableStreamBYOBRequest = ReadableStreamBYOBRequest; + exports.ReadableStreamDefaultController = ReadableStreamDefaultController; + exports.ReadableStreamDefaultReader = ReadableStreamDefaultReader; + exports.TransformStream = TransformStream; + exports.TransformStreamDefaultController = TransformStreamDefaultController; + exports.WritableStream = WritableStream; + exports.WritableStreamDefaultController = WritableStreamDefaultController; + exports.WritableStreamDefaultWriter = WritableStreamDefaultWriter; + +})); +//# sourceMappingURL=ponyfill.es6.js.map diff --git a/backend/node_modules/web-streams-polyfill/dist/ponyfill.es6.js.map b/backend/node_modules/web-streams-polyfill/dist/ponyfill.es6.js.map new file mode 100644 index 0000000000000000000000000000000000000000..1f0b1873d8933147c8519ac0cad15a58df31419d --- /dev/null +++ b/backend/node_modules/web-streams-polyfill/dist/ponyfill.es6.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ponyfill.es6.js","sources":["../src/utils.ts","../src/lib/helpers/miscellaneous.ts","../src/lib/helpers/webidl.ts","../src/lib/simple-queue.ts","../src/lib/abstract-ops/internal-methods.ts","../src/lib/readable-stream/generic-reader.ts","../src/stub/number-isfinite.ts","../src/stub/math-trunc.ts","../src/lib/validators/basic.ts","../src/lib/validators/readable-stream.ts","../src/lib/readable-stream/default-reader.ts","../node_modules/tslib/tslib.es6.js","../src/lib/abstract-ops/ecmascript.ts","../src/target/es5/stub/async-iterator-prototype.ts","../src/lib/readable-stream/async-iterator.ts","../src/stub/number-isnan.ts","../src/lib/abstract-ops/miscellaneous.ts","../src/lib/abstract-ops/queue-with-sizes.ts","../src/lib/helpers/array-buffer-view.ts","../src/lib/readable-stream/byte-stream-controller.ts","../src/lib/validators/reader-options.ts","../src/lib/readable-stream/byob-reader.ts","../src/lib/abstract-ops/queuing-strategy.ts","../src/lib/validators/queuing-strategy.ts","../src/lib/validators/underlying-sink.ts","../src/lib/validators/writable-stream.ts","../src/lib/abort-signal.ts","../src/lib/writable-stream.ts","../src/globals.ts","../src/stub/dom-exception.ts","../src/lib/readable-stream/pipe.ts","../src/lib/readable-stream/default-controller.ts","../src/lib/readable-stream/tee.ts","../src/lib/readable-stream/readable-stream-like.ts","../src/lib/readable-stream/from.ts","../src/lib/validators/underlying-source.ts","../src/lib/validators/iterator-options.ts","../src/lib/validators/pipe-options.ts","../src/lib/validators/readable-writable-pair.ts","../src/lib/readable-stream.ts","../src/lib/validators/queuing-strategy-init.ts","../src/lib/byte-length-queuing-strategy.ts","../src/lib/count-queuing-strategy.ts","../src/lib/validators/transformer.ts","../src/lib/transform-stream.ts"],"sourcesContent":["export function noop(): undefined {\n return undefined;\n}\n","import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n\nexport function setFunctionName(fn: Function, name: string): void {\n try {\n Object.defineProperty(fn, 'name', {\n value: name,\n configurable: true\n });\n } catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n }\n}\n","import { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\n// https://webidl.spec.whatwg.org/#a-new-promise\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-resolved-with\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return newPromise(resolve => resolve(value));\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-rejected-with\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\n// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned\n// from that handler. To prevent this, return null instead of void from all handlers.\n// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => null | PromiseLike,\n onRejected?: (reason: any) => null | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => null | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => null | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nlet _queueMicrotask: (callback: () => void) => void = callback => {\n if (typeof queueMicrotask === 'function') {\n _queueMicrotask = queueMicrotask;\n } else {\n const resolvedPromise = promiseResolvedWith(undefined);\n _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb);\n }\n return _queueMicrotask(callback);\n};\n\nexport { _queueMicrotask as queueMicrotask };\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n","import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n","export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\nexport const ReleaseSteps = Symbol('[[ReleaseSteps]]');\n","import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, type ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\nimport { ReleaseSteps } from '../abstract-ops/internal-methods';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n assert(stream._reader === reader);\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n stream._readableStreamController[ReleaseSteps]();\n\n stream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n","import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n","import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamDefaultReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamDefaultReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\nexport function ReadableStreamDefaultReaderRelease(reader: ReadableStreamDefaultReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n}\n\nexport function ReadableStreamDefaultReaderErrorReadRequests(reader: ReadableStreamDefaultReader, e: any) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n","/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise, SuppressedError, Symbol */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\r\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\r\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\r\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\r\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\r\n var _, done = false;\r\n for (var i = decorators.length - 1; i >= 0; i--) {\r\n var context = {};\r\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\r\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\r\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\r\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\r\n if (kind === \"accessor\") {\r\n if (result === void 0) continue;\r\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\r\n if (_ = accept(result.get)) descriptor.get = _;\r\n if (_ = accept(result.set)) descriptor.set = _;\r\n if (_ = accept(result.init)) initializers.unshift(_);\r\n }\r\n else if (_ = accept(result)) {\r\n if (kind === \"field\") initializers.unshift(_);\r\n else descriptor[key] = _;\r\n }\r\n }\r\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\r\n done = true;\r\n};\r\n\r\nexport function __runInitializers(thisArg, initializers, value) {\r\n var useValue = arguments.length > 2;\r\n for (var i = 0; i < initializers.length; i++) {\r\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\r\n }\r\n return useValue ? value : void 0;\r\n};\r\n\r\nexport function __propKey(x) {\r\n return typeof x === \"symbol\" ? x : \"\".concat(x);\r\n};\r\n\r\nexport function __setFunctionName(f, name, prefix) {\r\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\r\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\r\n};\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n var desc = Object.getOwnPropertyDescriptor(m, k);\r\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\r\n desc = { enumerable: true, get: function() { return m[k]; } };\r\n }\r\n Object.defineProperty(o, k2, desc);\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\nexport function __classPrivateFieldIn(state, receiver) {\r\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\r\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\r\n}\r\n\r\nexport function __addDisposableResource(env, value, async) {\r\n if (value !== null && value !== void 0) {\r\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\r\n var dispose;\r\n if (async) {\r\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\r\n dispose = value[Symbol.asyncDispose];\r\n }\r\n if (dispose === void 0) {\r\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\r\n dispose = value[Symbol.dispose];\r\n }\r\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\r\n env.stack.push({ value: value, dispose: dispose, async: async });\r\n }\r\n else if (async) {\r\n env.stack.push({ async: true });\r\n }\r\n return value;\r\n}\r\n\r\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n};\r\n\r\nexport function __disposeResources(env) {\r\n function fail(e) {\r\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\r\n env.hasError = true;\r\n }\r\n function next() {\r\n while (env.stack.length) {\r\n var rec = env.stack.pop();\r\n try {\r\n var result = rec.dispose && rec.dispose.call(rec.value);\r\n if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\r\n }\r\n catch (e) {\r\n fail(e);\r\n }\r\n }\r\n if (env.hasError) throw env.error;\r\n }\r\n return next();\r\n}\r\n\r\nexport default {\r\n __extends: __extends,\r\n __assign: __assign,\r\n __rest: __rest,\r\n __decorate: __decorate,\r\n __param: __param,\r\n __metadata: __metadata,\r\n __awaiter: __awaiter,\r\n __generator: __generator,\r\n __createBinding: __createBinding,\r\n __exportStar: __exportStar,\r\n __values: __values,\r\n __read: __read,\r\n __spread: __spread,\r\n __spreadArrays: __spreadArrays,\r\n __spreadArray: __spreadArray,\r\n __await: __await,\r\n __asyncGenerator: __asyncGenerator,\r\n __asyncDelegator: __asyncDelegator,\r\n __asyncValues: __asyncValues,\r\n __makeTemplateObject: __makeTemplateObject,\r\n __importStar: __importStar,\r\n __importDefault: __importDefault,\r\n __classPrivateFieldGet: __classPrivateFieldGet,\r\n __classPrivateFieldSet: __classPrivateFieldSet,\r\n __classPrivateFieldIn: __classPrivateFieldIn,\r\n __addDisposableResource: __addDisposableResource,\r\n __disposeResources: __disposeResources,\r\n};\r\n","import { reflectCall } from 'lib/helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport assert from '../../stub/assert';\n\ndeclare global {\n interface ArrayBuffer {\n readonly detached: boolean;\n\n transfer(): ArrayBuffer;\n }\n\n function structuredClone(value: T, options: { transfer: ArrayBuffer[] }): T;\n}\n\nexport function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\nexport let TransferArrayBuffer = (O: ArrayBuffer): ArrayBuffer => {\n if (typeof O.transfer === 'function') {\n TransferArrayBuffer = buffer => buffer.transfer();\n } else if (typeof structuredClone === 'function') {\n TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] });\n } else {\n // Not implemented correctly\n TransferArrayBuffer = buffer => buffer;\n }\n return TransferArrayBuffer(O);\n};\n\nexport function CanTransferArrayBuffer(O: ArrayBuffer): boolean {\n return !IsDetachedBuffer(O);\n}\n\nexport let IsDetachedBuffer = (O: ArrayBuffer): boolean => {\n if (typeof O.detached === 'boolean') {\n IsDetachedBuffer = buffer => buffer.detached;\n } else {\n // Not implemented correctly\n IsDetachedBuffer = buffer => buffer.byteLength === 0;\n }\n return IsDetachedBuffer(O);\n};\n\nexport function ArrayBufferSlice(buffer: ArrayBuffer, begin: number, end: number): ArrayBuffer {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n\nexport type MethodName = {\n [P in keyof T]: T[P] extends Function | undefined ? P : never;\n}[keyof T];\n\nexport function GetMethod>(receiver: T, prop: K): T[K] | undefined {\n const func = receiver[prop];\n if (func === undefined || func === null) {\n return undefined;\n }\n if (typeof func !== 'function') {\n throw new TypeError(`${String(prop)} is not a function`);\n }\n return func;\n}\n\nexport interface SyncIteratorRecord {\n iterator: Iterator,\n nextMethod: Iterator['next'],\n done: boolean;\n}\n\nexport interface AsyncIteratorRecord {\n iterator: AsyncIterator,\n nextMethod: AsyncIterator['next'],\n done: boolean;\n}\n\nexport type SyncOrAsyncIteratorRecord = SyncIteratorRecord | AsyncIteratorRecord;\n\nexport function CreateAsyncFromSyncIterator(syncIteratorRecord: SyncIteratorRecord): AsyncIteratorRecord {\n // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%,\n // we use yield* inside an async generator function to achieve the same result.\n\n // Wrap the sync iterator inside a sync iterable, so we can use it with yield*.\n const syncIterable = {\n [Symbol.iterator]: () => syncIteratorRecord.iterator\n };\n // Create an async generator function and immediately invoke it.\n const asyncIterator = (async function* () {\n return yield* syncIterable;\n }());\n // Return as an async iterator record.\n const nextMethod = asyncIterator.next;\n return { iterator: asyncIterator, nextMethod, done: false };\n}\n\n// Aligns with core-js/modules/es.symbol.async-iterator.js\nexport const SymbolAsyncIterator: (typeof Symbol)['asyncIterator'] =\n Symbol.asyncIterator ??\n Symbol.for?.('Symbol.asyncIterator') ??\n '@@asyncIterator';\n\nexport type SyncOrAsyncIterable = Iterable | AsyncIterable;\nexport type SyncOrAsyncIteratorMethod = () => (Iterator | AsyncIterator);\n\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint: 'async',\n method?: SyncOrAsyncIteratorMethod\n): AsyncIteratorRecord;\nfunction GetIterator(\n obj: Iterable,\n hint: 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncIteratorRecord;\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint = 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncOrAsyncIteratorRecord {\n assert(hint === 'sync' || hint === 'async');\n if (method === undefined) {\n if (hint === 'async') {\n method = GetMethod(obj as AsyncIterable, SymbolAsyncIterator);\n if (method === undefined) {\n const syncMethod = GetMethod(obj as Iterable, Symbol.iterator);\n const syncIteratorRecord = GetIterator(obj as Iterable, 'sync', syncMethod);\n return CreateAsyncFromSyncIterator(syncIteratorRecord);\n }\n } else {\n method = GetMethod(obj as Iterable, Symbol.iterator);\n }\n }\n if (method === undefined) {\n throw new TypeError('The object is not iterable');\n }\n const iterator = reflectCall(method, obj, []);\n if (!typeIsObject(iterator)) {\n throw new TypeError('The iterator method must return an object');\n }\n const nextMethod = iterator.next;\n return { iterator, nextMethod, done: false } as SyncOrAsyncIteratorRecord;\n}\n\nexport { GetIterator };\n\nexport function IteratorNext(iteratorRecord: AsyncIteratorRecord): Promise> {\n const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []);\n if (!typeIsObject(result)) {\n throw new TypeError('The iterator.next() method must return an object');\n }\n return result;\n}\n\nexport function IteratorComplete(\n iterResult: IteratorResult\n): iterResult is IteratorReturnResult {\n assert(typeIsObject(iterResult));\n return Boolean(iterResult.done);\n}\n\nexport function IteratorValue(iterResult: IteratorYieldResult): T {\n assert(typeIsObject(iterResult));\n return iterResult.value;\n}\n","/// \n\nimport { SymbolAsyncIterator } from '../../../lib/abstract-ops/ecmascript';\n\n// We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it.\nexport const AsyncIteratorPrototype: AsyncIterable = {\n // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( )\n // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator\n [SymbolAsyncIterator](this: AsyncIterator) {\n return this;\n }\n};\nObject.defineProperty(AsyncIteratorPrototype, SymbolAsyncIterator, { enumerable: false });\n","/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadableStreamDefaultReadResult,\n type ReadRequest\n} from './default-reader';\nimport { ReadableStreamReaderGenericCancel, ReadableStreamReaderGenericRelease } from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterableIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ninterface ReadableStreamAsyncIteratorInstance extends ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nObject.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n","import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: NonShared): NonShared {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer) as NonShared;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n","export type TypedArray =\n | Int8Array\n | Uint8Array\n | Uint8ClampedArray\n | Int16Array\n | Uint16Array\n | Int32Array\n | Uint32Array\n | Float32Array\n | Float64Array;\n\nexport type NonShared = T & {\n buffer: ArrayBuffer;\n}\n\nexport interface ArrayBufferViewConstructor {\n new(buffer: ArrayBuffer, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n}\n\nexport interface TypedArrayConstructor extends ArrayBufferViewConstructor {\n readonly BYTES_PER_ELEMENT: number;\n}\n\nexport type DataViewConstructor = ArrayBufferViewConstructor;\n\nfunction isDataViewConstructor(ctor: Function): ctor is DataViewConstructor {\n return ctor === DataView;\n}\n\nexport function isDataView(view: ArrayBufferView): view is DataView {\n return isDataViewConstructor(view.constructor);\n}\n\nexport function arrayBufferViewElementSize(ctor: ArrayBufferViewConstructor): number {\n if (isDataViewConstructor(ctor)) {\n return 1;\n }\n return (ctor as unknown as TypedArrayConstructor).BYTES_PER_ELEMENT;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n IsReadableStreamDefaultReader,\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n type ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n type ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n type ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport type { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\nimport {\n type ArrayBufferViewConstructor,\n arrayBufferViewElementSize,\n type NonShared,\n type TypedArrayConstructor\n} from '../helpers/array-buffer-view';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: NonShared | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: NonShared): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond');\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBuffer;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor = NonShared> =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: TypedArrayConstructor;\n readerType: 'default' | 'none';\n}\n\ninterface BYOBPullIntoDescriptor = NonShared> {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob' | 'none';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: NonShared): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest>): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n minimumFill: 1,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n if (this._pendingPullIntos.length > 0) {\n const firstPullInto = this._pendingPullIntos.peek();\n firstPullInto.readerType = 'none';\n\n this._pendingPullIntos = new SimpleQueue();\n this._pendingPullIntos.push(firstPullInto);\n }\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableByteStreamController.prototype.close, 'close');\nsetFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableByteStreamController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor>(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n assert(pullIntoDescriptor.readerType !== 'none');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as NonShared, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor>(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n let clonedChunk;\n try {\n clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength);\n } catch (cloneE) {\n ReadableByteStreamControllerError(controller, cloneE);\n throw cloneE;\n }\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength);\n}\n\nfunction ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.readerType === 'none');\n if (firstDescriptor.bytesFilled > 0) {\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n firstDescriptor.buffer,\n firstDescriptor.byteOffset,\n firstDescriptor.bytesFilled\n );\n }\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize;\n const maxAlignedBytes = maxBytesFilled - remainderBytes;\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n assert(pullIntoDescriptor.readerType !== 'none');\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nfunction ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller: ReadableByteStreamController) {\n const reader = controller._controlledReadableByteStream._reader;\n assert(IsReadableStreamDefaultReader(reader));\n while (reader._readRequests.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n const readRequest = reader._readRequests.shift();\n ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest);\n }\n}\n\nexport function ReadableByteStreamControllerPullInto>(\n controller: ReadableByteStreamController,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n const elementSize = arrayBufferViewElementSize(ctor);\n\n const { byteOffset, byteLength } = view;\n\n const minimumFill = min * elementSize;\n assert(minimumFill >= elementSize && minimumFill <= byteLength);\n assert(minimumFill % elementSize === 0);\n\n let buffer: ArrayBuffer;\n try {\n buffer = TransferArrayBuffer(view.buffer);\n } catch (e) {\n readIntoRequest._errorSteps(e);\n return;\n }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset,\n byteLength,\n bytesFilled: 0,\n minimumFill,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled % firstDescriptor.elementSize === 0);\n\n if (firstDescriptor.readerType === 'none') {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n return;\n }\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) {\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n pullIntoDescriptor.buffer,\n end - remainderSize,\n remainderSize\n );\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(\n controller: ReadableByteStreamController,\n chunk: NonShared\n) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const { buffer, byteOffset, byteLength } = chunk;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n if (firstPendingPullInto.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto);\n }\n }\n\n if (ReadableStreamHasDefaultReader(stream)) {\n ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller);\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView as NonShared, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerFillReadRequestFromQueue(\n controller: ReadableByteStreamController,\n readRequest: ReadRequest>\n) {\n assert(controller._queueTotalSize > 0);\n\n const entry = controller._queue.shift();\n controller._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n readRequest._chunkSteps(view as NonShared);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view as NonShared);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: NonShared) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: NonShared) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n","import { assertDictionary, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n\nexport function convertByobReadOptions(\n options: ReadableStreamBYOBReaderReadOptions | null | undefined,\n context: string\n): ValidatedReadableStreamBYOBReaderReadOptions {\n assertDictionary(options, context);\n const min = options?.min ?? 1;\n return {\n min: convertUnsignedLongLongWithEnforceRange(\n min,\n `${context} has member 'min' that`\n )\n };\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, type ReadableByteStream, type ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from './reader-options';\nimport { convertByobReadOptions } from '../validators/reader-options';\nimport { isDataView, type NonShared, type TypedArray } from '../helpers/array-buffer-view';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream as ReadableStream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest>(\n stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest\n): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest> {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(\n view: T,\n options?: ReadableStreamBYOBReaderReadOptions\n ): Promise>;\n read>(\n view: T,\n rawOptions: ReadableStreamBYOBReaderReadOptions | null | undefined = {}\n ): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n let options: ValidatedReadableStreamBYOBReaderReadOptions;\n try {\n options = convertByobReadOptions(rawOptions, 'options');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const min = options.min;\n if (min === 0) {\n return promiseRejectedWith(new TypeError('options.min must be greater than 0'));\n }\n if (!isDataView(view)) {\n if (min > (view as unknown as TypedArray).length) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s length'));\n }\n } else if (min > view.byteLength) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s byteLength'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamBYOBReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamBYOBReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead>(\n reader: ReadableStreamBYOBReader,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n min,\n readIntoRequest\n );\n }\n}\n\nexport function ReadableStreamBYOBReaderRelease(reader: ReadableStreamBYOBReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n}\n\nexport function ReadableStreamBYOBReaderErrorReadIntoRequests(reader: ReadableStreamBYOBReader, e: any) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n","/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * If aborted, returns the reason for aborting.\n */\n readonly reason?: any;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(reason?: any): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n type QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { type AbortController, type AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(WritableStream.prototype.abort, 'abort');\nsetFunctionName(WritableStream.prototype.close, 'close');\nsetFunctionName(WritableStream.prototype.getWriter, 'getWriter');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight\n};\n\nexport type {\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort(reason);\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nsetFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort');\nsetFunctionName(WritableStreamDefaultWriter.prototype.close, 'close');\nsetFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock');\nsetFunctionName(WritableStreamDefaultWriter.prototype.write, 'write');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n return null;\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let writeAlgorithm: (chunk: W) => Promise;\n let closeAlgorithm: () => Promise;\n let abortAlgorithm: (reason: any) => Promise;\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n } else {\n writeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n } else {\n closeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n } else {\n abortAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n return null;\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n","/// \n\nfunction getGlobals(): typeof globalThis | undefined {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n } else if (typeof self !== 'undefined') {\n return self;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n","/// \nimport { globals } from '../globals';\nimport { setFunctionName } from '../lib/helpers/miscellaneous';\n\ninterface DOMException extends Error {\n name: string;\n message: string;\n}\n\ntype DOMExceptionConstructor = new (message?: string, name?: string) => DOMException;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n if ((ctor as DOMExceptionConstructor).name !== 'DOMException') {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Support:\n * - Web browsers\n * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87)\n */\nfunction getFromGlobal(): DOMExceptionConstructor | undefined {\n const ctor = globals?.DOMException;\n return isDOMExceptionConstructor(ctor) ? ctor : undefined;\n}\n\n/**\n * Support:\n * - All platforms\n */\nfunction createPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line @typescript-eslint/no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n setFunctionName(ctor, 'DOMException');\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nconst DOMException: DOMExceptionConstructor = getFromGlobal() || createPolyfill();\n\nexport { DOMException };\n","import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n return null;\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => null) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => null) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest(): null {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n return null;\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any): null {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n\n return null;\n }\n });\n}\n","import type { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, type QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n type ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport type { ValidatedUnderlyingSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n // Do nothing.\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultController.prototype.close, 'close');\nsetFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableStreamDefaultController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n","import {\n CreateReadableByteStream,\n CreateReadableStream,\n type DefaultReadableStream,\n IsReadableStream,\n type ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n type ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n type ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(\n stream: ReadableStream,\n cloneForBranch2: boolean\n): [DefaultReadableStream, DefaultReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: DefaultReadableStream;\n let branch2: DefaultReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader> = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader>) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return null;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: NonShared, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader>(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n","import { typeIsObject } from '../helpers/miscellaneous';\nimport type { ReadableStreamDefaultReadResult } from './default-reader';\n\n/**\n * A common interface for a `ReadadableStream` implementation.\n *\n * @public\n */\nexport interface ReadableStreamLike {\n readonly locked: boolean;\n\n getReader(): ReadableStreamDefaultReaderLike;\n}\n\n/**\n * A common interface for a `ReadableStreamDefaultReader` implementation.\n *\n * @public\n */\nexport interface ReadableStreamDefaultReaderLike {\n readonly closed: Promise;\n\n cancel(reason?: any): Promise;\n\n read(): Promise>;\n\n releaseLock(): void;\n}\n\nexport function isReadableStreamLike(stream: unknown): stream is ReadableStreamLike {\n return typeIsObject(stream) && typeof (stream as ReadableStreamLike).getReader !== 'undefined';\n}\n","import { CreateReadableStream, type DefaultReadableStream } from '../readable-stream';\nimport {\n isReadableStreamLike,\n type ReadableStreamDefaultReaderLike,\n type ReadableStreamLike\n} from './readable-stream-like';\nimport { ReadableStreamDefaultControllerClose, ReadableStreamDefaultControllerEnqueue } from './default-controller';\nimport { GetIterator, GetMethod, IteratorComplete, IteratorNext, IteratorValue } from '../abstract-ops/ecmascript';\nimport { promiseRejectedWith, promiseResolvedWith, reflectCall, transformPromiseWith } from '../helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { noop } from '../../utils';\n\nexport function ReadableStreamFrom(\n source: Iterable | AsyncIterable | ReadableStreamLike\n): DefaultReadableStream {\n if (isReadableStreamLike(source)) {\n return ReadableStreamFromDefaultReader(source.getReader());\n }\n return ReadableStreamFromIterable(source);\n}\n\nexport function ReadableStreamFromIterable(asyncIterable: Iterable | AsyncIterable): DefaultReadableStream {\n let stream: DefaultReadableStream;\n const iteratorRecord = GetIterator(asyncIterable, 'async');\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let nextResult;\n try {\n nextResult = IteratorNext(iteratorRecord);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const nextPromise = promiseResolvedWith(nextResult);\n return transformPromiseWith(nextPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object');\n }\n const done = IteratorComplete(iterResult);\n if (done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = IteratorValue(iterResult);\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n const iterator = iteratorRecord.iterator;\n let returnMethod: (typeof iterator)['return'] | undefined;\n try {\n returnMethod = GetMethod(iterator, 'return');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n if (returnMethod === undefined) {\n return promiseResolvedWith(undefined);\n }\n let returnResult: IteratorResult | Promise>;\n try {\n returnResult = reflectCall(returnMethod, iterator, [reason]);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const returnPromise = promiseResolvedWith(returnResult);\n return transformPromiseWith(returnPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object');\n }\n return undefined;\n });\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n\nexport function ReadableStreamFromDefaultReader(\n reader: ReadableStreamDefaultReaderLike\n): DefaultReadableStream {\n let stream: DefaultReadableStream;\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let readPromise;\n try {\n readPromise = reader.read();\n } catch (e) {\n return promiseRejectedWith(e);\n }\n return transformPromiseWith(readPromise, readResult => {\n if (!typeIsObject(readResult)) {\n throw new TypeError('The promise returned by the reader.read() method must fulfill with an object');\n }\n if (readResult.done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = readResult.value;\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n try {\n return promiseResolvedWith(reader.cancel(reason));\n } catch (e) {\n return promiseRejectedWith(e);\n }\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n","import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n","import { assertDictionary } from './basic';\nimport type {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n","import { assertDictionary } from './basic';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n","import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n","import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, type ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderErrorReadRequests,\n type ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReaderErrorReadIntoRequests,\n type ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { ReadableStreamFrom } from './readable-stream/from';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport type {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList, SymbolAsyncIterator } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions\n} from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport type { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport type { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\nimport type { ReadableStreamDefaultReaderLike, ReadableStreamLike } from './readable-stream/readable-stream-like';\nimport type { NonShared } from './helpers/array-buffer-view';\n\nexport type DefaultReadableStream = ReadableStream & {\n _readableStreamController: ReadableStreamDefaultController\n};\n\nexport type ReadableByteStream = ReadableStream> & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream implements AsyncIterable {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n\n [SymbolAsyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator {\n // Stub implementation, overridden below\n return this.values(options);\n }\n\n /**\n * Creates a new ReadableStream wrapping the provided iterable or async iterable.\n *\n * This can be used to adapt various kinds of objects into a readable stream,\n * such as an array, an async generator, or a Node.js readable stream.\n */\n static from(asyncIterable: Iterable | AsyncIterable | ReadableStreamLike): ReadableStream {\n return ReadableStreamFrom(asyncIterable);\n }\n}\n\nObject.defineProperties(ReadableStream, {\n from: { enumerable: true }\n});\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(ReadableStream.from, 'from');\nsetFunctionName(ReadableStream.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStream.prototype.getReader, 'getReader');\nsetFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough');\nsetFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo');\nsetFunctionName(ReadableStream.prototype.tee, 'tee');\nsetFunctionName(ReadableStream.prototype.values, 'values');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nObject.defineProperty(ReadableStream.prototype, SymbolAsyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n});\n\nexport type {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n ReadableStreamBYOBReaderReadOptions,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions,\n ReadableStreamLike,\n ReadableStreamDefaultReaderLike\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1\n): DefaultReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: DefaultReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n","import type { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\nsetFunctionName(byteLengthSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\nsetFunctionName(countSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const cancel = original?.cancel;\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n cancel: cancel === undefined ?\n undefined :\n convertTransformerCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n\nfunction convertTransformerCancelCallback(\n fn: TransformerCancelCallback,\n original: Transformer,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith,\n uponPromise\n} from './helpers/webidl';\nimport { CreateReadableStream, type DefaultReadableStream, ReadableStream } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: DefaultReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport type {\n Transformer,\n TransformerCancelCallback,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSourceCancelAlgorithm(stream, reason);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n TransformStreamUnblockWrite(stream);\n}\n\nfunction TransformStreamUnblockWrite(stream: TransformStream) {\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _finishPromise: Promise | undefined;\n /** @internal */\n _finishPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _finishPromise_reject?: (reason: any) => void;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n /** @internal */\n _cancelAlgorithm: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(TransformStreamDefaultController.prototype.error, 'error');\nsetFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._finishPromise = undefined;\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm: (chunk: I) => Promise;\n let flushAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n } else {\n transformAlgorithm = chunk => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n }\n\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n } else {\n flushAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n if (transformer.cancel !== undefined) {\n cancelAlgorithm = reason => transformer.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally,\n // we don't run the _cancelAlgorithm again.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerError(readable._readableStreamController, reason);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally,\n // we don't also run the _cancelAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(flushPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerClose(readable._readableStreamController);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\nfunction TransformStreamDefaultSourceCancelAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._writable cannot change after construction, so caching it across a call to user code is safe.\n const writable = stream._writable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or\n // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the\n // _flushAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (writable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, writable._storedError);\n } else {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\nexport function defaultControllerFinishPromiseResolve(controller: TransformStreamDefaultController) {\n if (controller._finishPromise_resolve === undefined) {\n return;\n }\n\n controller._finishPromise_resolve();\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nexport function defaultControllerFinishPromiseReject(controller: TransformStreamDefaultController, reason: any) {\n if (controller._finishPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(controller._finishPromise!);\n controller._finishPromise_reject(reason);\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n"],"names":["queueMicrotask","streamBrandCheckException","defaultControllerBrandCheckException"],"mappings":";;;;;;;;;;;;;aAAgB,IAAI,GAAA;IAClB,IAAA,OAAO,SAAS,CAAC;IACnB;;ICCM,SAAU,YAAY,CAAC,CAAM,EAAA;IACjC,IAAA,OAAO,CAAC,OAAO,CAAC,KAAK,QAAQ,IAAI,CAAC,KAAK,IAAI,KAAK,OAAO,CAAC,KAAK,UAAU,CAAC;IAC1E,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AC;IAC/C,CAAC;IAEe,SAAA,oCAAoC,CAAC,UAAiD,EAAE,MAAW,EAAA;IACjH,IAAA,IAAI,UAAU,CAAC,qBAAqB,KAAK,SAAS,EAAE;YAClD,OAAO;SACR;IAED,IAAA,yBAAyB,CAAC,UAAU,CAAC,cAAe,CAAC,CAAC;IACtD,IAAA,UAAU,CAAC,qBAAqB,CAAC,MAAM,CAAC,CAAC;IACzC,IAAA,UAAU,CAAC,sBAAsB,GAAG,SAAS,CAAC;IAC9C,IAAA,UAAU,CAAC,qBAAqB,GAAG,SAAS,CAAC;IAC/C,CAAC;IAED;IAEA,SAAS,yBAAyB,CAAC,IAAY,EAAA;IAC7C,IAAA,OAAO,IAAI,SAAS,CAClB,6BAA6B,IAAI,CAAA,sCAAA,CAAwC,CAAC,CAAC;IAC/E;;;;;;;;;;;;;;;;;;;;","x_google_ignoreList":[11]} \ No newline at end of file diff --git a/backend/node_modules/web-streams-polyfill/dist/ponyfill.es6.mjs b/backend/node_modules/web-streams-polyfill/dist/ponyfill.es6.mjs new file mode 100644 index 0000000000000000000000000000000000000000..1d4d6899db94f11bea19fe08ff29596e73ce872c --- /dev/null +++ b/backend/node_modules/web-streams-polyfill/dist/ponyfill.es6.mjs @@ -0,0 +1,4790 @@ +/** + * @license + * web-streams-polyfill v3.3.3 + * Copyright 2024 Mattias Buelens, Diwank Singh Tomer and other contributors. + * This code is released under the MIT license. + * SPDX-License-Identifier: MIT + */ +function noop() { + return undefined; +} + +function typeIsObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; +} +const rethrowAssertionErrorRejection = noop; +function setFunctionName(fn, name) { + try { + Object.defineProperty(fn, 'name', { + value: name, + configurable: true + }); + } + catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility + } +} + +const originalPromise = Promise; +const originalPromiseThen = Promise.prototype.then; +const originalPromiseReject = Promise.reject.bind(originalPromise); +// https://webidl.spec.whatwg.org/#a-new-promise +function newPromise(executor) { + return new originalPromise(executor); +} +// https://webidl.spec.whatwg.org/#a-promise-resolved-with +function promiseResolvedWith(value) { + return newPromise(resolve => resolve(value)); +} +// https://webidl.spec.whatwg.org/#a-promise-rejected-with +function promiseRejectedWith(reason) { + return originalPromiseReject(reason); +} +function PerformPromiseThen(promise, onFulfilled, onRejected) { + // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an + // approximation. + return originalPromiseThen.call(promise, onFulfilled, onRejected); +} +// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned +// from that handler. To prevent this, return null instead of void from all handlers. +// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it +function uponPromise(promise, onFulfilled, onRejected) { + PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection); +} +function uponFulfillment(promise, onFulfilled) { + uponPromise(promise, onFulfilled); +} +function uponRejection(promise, onRejected) { + uponPromise(promise, undefined, onRejected); +} +function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { + return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); +} +function setPromiseIsHandledToTrue(promise) { + PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection); +} +let _queueMicrotask = callback => { + if (typeof queueMicrotask === 'function') { + _queueMicrotask = queueMicrotask; + } + else { + const resolvedPromise = promiseResolvedWith(undefined); + _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb); + } + return _queueMicrotask(callback); +}; +function reflectCall(F, V, args) { + if (typeof F !== 'function') { + throw new TypeError('Argument is not a function'); + } + return Function.prototype.apply.call(F, V, args); +} +function promiseCall(F, V, args) { + try { + return promiseResolvedWith(reflectCall(F, V, args)); + } + catch (value) { + return promiseRejectedWith(value); + } +} + +// Original from Chromium +// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js +const QUEUE_MAX_ARRAY_SIZE = 16384; +/** + * Simple queue structure. + * + * Avoids scalability issues with using a packed array directly by using + * multiple arrays in a linked list and keeping the array size bounded. + */ +class SimpleQueue { + constructor() { + this._cursor = 0; + this._size = 0; + // _front and _back are always defined. + this._front = { + _elements: [], + _next: undefined + }; + this._back = this._front; + // The cursor is used to avoid calling Array.shift(). + // It contains the index of the front element of the array inside the + // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE). + this._cursor = 0; + // When there is only one node, size === elements.length - cursor. + this._size = 0; + } + get length() { + return this._size; + } + // For exception safety, this method is structured in order: + // 1. Read state + // 2. Calculate required state mutations + // 3. Perform state mutations + push(element) { + const oldBack = this._back; + let newBack = oldBack; + if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { + newBack = { + _elements: [], + _next: undefined + }; + } + // push() is the mutation most likely to throw an exception, so it + // goes first. + oldBack._elements.push(element); + if (newBack !== oldBack) { + this._back = newBack; + oldBack._next = newBack; + } + ++this._size; + } + // Like push(), shift() follows the read -> calculate -> mutate pattern for + // exception safety. + shift() { // must not be called on an empty queue + const oldFront = this._front; + let newFront = oldFront; + const oldCursor = this._cursor; + let newCursor = oldCursor + 1; + const elements = oldFront._elements; + const element = elements[oldCursor]; + if (newCursor === QUEUE_MAX_ARRAY_SIZE) { + newFront = oldFront._next; + newCursor = 0; + } + // No mutations before this point. + --this._size; + this._cursor = newCursor; + if (oldFront !== newFront) { + this._front = newFront; + } + // Permit shifted element to be garbage collected. + elements[oldCursor] = undefined; + return element; + } + // The tricky thing about forEach() is that it can be called + // re-entrantly. The queue may be mutated inside the callback. It is easy to + // see that push() within the callback has no negative effects since the end + // of the queue is checked for on every iteration. If shift() is called + // repeatedly within the callback then the next iteration may return an + // element that has been removed. In this case the callback will be called + // with undefined values until we either "catch up" with elements that still + // exist or reach the back of the queue. + forEach(callback) { + let i = this._cursor; + let node = this._front; + let elements = node._elements; + while (i !== elements.length || node._next !== undefined) { + if (i === elements.length) { + node = node._next; + elements = node._elements; + i = 0; + if (elements.length === 0) { + break; + } + } + callback(elements[i]); + ++i; + } + } + // Return the element that would be returned if shift() was called now, + // without modifying the queue. + peek() { // must not be called on an empty queue + const front = this._front; + const cursor = this._cursor; + return front._elements[cursor]; + } +} + +const AbortSteps = Symbol('[[AbortSteps]]'); +const ErrorSteps = Symbol('[[ErrorSteps]]'); +const CancelSteps = Symbol('[[CancelSteps]]'); +const PullSteps = Symbol('[[PullSteps]]'); +const ReleaseSteps = Symbol('[[ReleaseSteps]]'); + +function ReadableStreamReaderGenericInitialize(reader, stream) { + reader._ownerReadableStream = stream; + stream._reader = reader; + if (stream._state === 'readable') { + defaultReaderClosedPromiseInitialize(reader); + } + else if (stream._state === 'closed') { + defaultReaderClosedPromiseInitializeAsResolved(reader); + } + else { + defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); + } +} +// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state +// check. +function ReadableStreamReaderGenericCancel(reader, reason) { + const stream = reader._ownerReadableStream; + return ReadableStreamCancel(stream, reason); +} +function ReadableStreamReaderGenericRelease(reader) { + const stream = reader._ownerReadableStream; + if (stream._state === 'readable') { + defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + else { + defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + stream._readableStreamController[ReleaseSteps](); + stream._reader = undefined; + reader._ownerReadableStream = undefined; +} +// Helper functions for the readers. +function readerLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released reader'); +} +// Helper functions for the ReadableStreamDefaultReader. +function defaultReaderClosedPromiseInitialize(reader) { + reader._closedPromise = newPromise((resolve, reject) => { + reader._closedPromise_resolve = resolve; + reader._closedPromise_reject = reject; + }); +} +function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseReject(reader, reason); +} +function defaultReaderClosedPromiseInitializeAsResolved(reader) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseResolve(reader); +} +function defaultReaderClosedPromiseReject(reader, reason) { + if (reader._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(reader._closedPromise); + reader._closedPromise_reject(reason); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; +} +function defaultReaderClosedPromiseResetToRejected(reader, reason) { + defaultReaderClosedPromiseInitializeAsRejected(reader, reason); +} +function defaultReaderClosedPromiseResolve(reader) { + if (reader._closedPromise_resolve === undefined) { + return; + } + reader._closedPromise_resolve(undefined); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; +} + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill +const NumberIsFinite = Number.isFinite || function (x) { + return typeof x === 'number' && isFinite(x); +}; + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill +const MathTrunc = Math.trunc || function (v) { + return v < 0 ? Math.ceil(v) : Math.floor(v); +}; + +// https://heycam.github.io/webidl/#idl-dictionaries +function isDictionary(x) { + return typeof x === 'object' || typeof x === 'function'; +} +function assertDictionary(obj, context) { + if (obj !== undefined && !isDictionary(obj)) { + throw new TypeError(`${context} is not an object.`); + } +} +// https://heycam.github.io/webidl/#idl-callback-functions +function assertFunction(x, context) { + if (typeof x !== 'function') { + throw new TypeError(`${context} is not a function.`); + } +} +// https://heycam.github.io/webidl/#idl-object +function isObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; +} +function assertObject(x, context) { + if (!isObject(x)) { + throw new TypeError(`${context} is not an object.`); + } +} +function assertRequiredArgument(x, position, context) { + if (x === undefined) { + throw new TypeError(`Parameter ${position} is required in '${context}'.`); + } +} +function assertRequiredField(x, field, context) { + if (x === undefined) { + throw new TypeError(`${field} is required in '${context}'.`); + } +} +// https://heycam.github.io/webidl/#idl-unrestricted-double +function convertUnrestrictedDouble(value) { + return Number(value); +} +function censorNegativeZero(x) { + return x === 0 ? 0 : x; +} +function integerPart(x) { + return censorNegativeZero(MathTrunc(x)); +} +// https://heycam.github.io/webidl/#idl-unsigned-long-long +function convertUnsignedLongLongWithEnforceRange(value, context) { + const lowerBound = 0; + const upperBound = Number.MAX_SAFE_INTEGER; + let x = Number(value); + x = censorNegativeZero(x); + if (!NumberIsFinite(x)) { + throw new TypeError(`${context} is not a finite number`); + } + x = integerPart(x); + if (x < lowerBound || x > upperBound) { + throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`); + } + if (!NumberIsFinite(x) || x === 0) { + return 0; + } + // TODO Use BigInt if supported? + // let xBigInt = BigInt(integerPart(x)); + // xBigInt = BigInt.asUintN(64, xBigInt); + // return Number(xBigInt); + return x; +} + +function assertReadableStream(x, context) { + if (!IsReadableStream(x)) { + throw new TypeError(`${context} is not a ReadableStream.`); + } +} + +// Abstract operations for the ReadableStream. +function AcquireReadableStreamDefaultReader(stream) { + return new ReadableStreamDefaultReader(stream); +} +// ReadableStream API exposed for controllers. +function ReadableStreamAddReadRequest(stream, readRequest) { + stream._reader._readRequests.push(readRequest); +} +function ReadableStreamFulfillReadRequest(stream, chunk, done) { + const reader = stream._reader; + const readRequest = reader._readRequests.shift(); + if (done) { + readRequest._closeSteps(); + } + else { + readRequest._chunkSteps(chunk); + } +} +function ReadableStreamGetNumReadRequests(stream) { + return stream._reader._readRequests.length; +} +function ReadableStreamHasDefaultReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamDefaultReader(reader)) { + return false; + } + return true; +} +/** + * A default reader vended by a {@link ReadableStream}. + * + * @public + */ +class ReadableStreamDefaultReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + /** + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('read')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: () => resolvePromise({ value: undefined, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamDefaultReaderRead(this, readRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamDefaultReader(this)) { + throw defaultReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamDefaultReaderRelease(this); + } +} +Object.defineProperties(ReadableStreamDefaultReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } +}); +setFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel'); +setFunctionName(ReadableStreamDefaultReader.prototype.read, 'read'); +setFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, { + value: 'ReadableStreamDefaultReader', + configurable: true + }); +} +// Abstract operations for the readers. +function IsReadableStreamDefaultReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) { + return false; + } + return x instanceof ReadableStreamDefaultReader; +} +function ReadableStreamDefaultReaderRead(reader, readRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'closed') { + readRequest._closeSteps(); + } + else if (stream._state === 'errored') { + readRequest._errorSteps(stream._storedError); + } + else { + stream._readableStreamController[PullSteps](readRequest); + } +} +function ReadableStreamDefaultReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + const e = new TypeError('Reader was released'); + ReadableStreamDefaultReaderErrorReadRequests(reader, e); +} +function ReadableStreamDefaultReaderErrorReadRequests(reader, e) { + const readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(readRequest => { + readRequest._errorSteps(e); + }); +} +// Helper functions for the ReadableStreamDefaultReader. +function defaultReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`); +} + +/****************************************************************************** +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 */ + + +function __values(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); +} + +function __await(v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); +} + +function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } +} + +function __asyncDelegator(o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } +} + +function __asyncValues(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } +} + +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 _a, _b, _c; +function CreateArrayFromList(elements) { + // We use arrays to represent lists, so this is basically a no-op. + // Do a slice though just in case we happen to depend on the unique-ness. + return elements.slice(); +} +function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { + new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); +} +let TransferArrayBuffer = (O) => { + if (typeof O.transfer === 'function') { + TransferArrayBuffer = buffer => buffer.transfer(); + } + else if (typeof structuredClone === 'function') { + TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] }); + } + else { + // Not implemented correctly + TransferArrayBuffer = buffer => buffer; + } + return TransferArrayBuffer(O); +}; +let IsDetachedBuffer = (O) => { + if (typeof O.detached === 'boolean') { + IsDetachedBuffer = buffer => buffer.detached; + } + else { + // Not implemented correctly + IsDetachedBuffer = buffer => buffer.byteLength === 0; + } + return IsDetachedBuffer(O); +}; +function ArrayBufferSlice(buffer, begin, end) { + // ArrayBuffer.prototype.slice is not available on IE10 + // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice + if (buffer.slice) { + return buffer.slice(begin, end); + } + const length = end - begin; + const slice = new ArrayBuffer(length); + CopyDataBlockBytes(slice, 0, buffer, begin, length); + return slice; +} +function GetMethod(receiver, prop) { + const func = receiver[prop]; + if (func === undefined || func === null) { + return undefined; + } + if (typeof func !== 'function') { + throw new TypeError(`${String(prop)} is not a function`); + } + return func; +} +function CreateAsyncFromSyncIterator(syncIteratorRecord) { + // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%, + // we use yield* inside an async generator function to achieve the same result. + // Wrap the sync iterator inside a sync iterable, so we can use it with yield*. + const syncIterable = { + [Symbol.iterator]: () => syncIteratorRecord.iterator + }; + // Create an async generator function and immediately invoke it. + const asyncIterator = (function () { + return __asyncGenerator(this, arguments, function* () { + return yield __await(yield __await(yield* __asyncDelegator(__asyncValues(syncIterable)))); + }); + }()); + // Return as an async iterator record. + const nextMethod = asyncIterator.next; + return { iterator: asyncIterator, nextMethod, done: false }; +} +// Aligns with core-js/modules/es.symbol.async-iterator.js +const SymbolAsyncIterator = (_c = (_a = Symbol.asyncIterator) !== null && _a !== void 0 ? _a : (_b = Symbol.for) === null || _b === void 0 ? void 0 : _b.call(Symbol, 'Symbol.asyncIterator')) !== null && _c !== void 0 ? _c : '@@asyncIterator'; +function GetIterator(obj, hint = 'sync', method) { + if (method === undefined) { + if (hint === 'async') { + method = GetMethod(obj, SymbolAsyncIterator); + if (method === undefined) { + const syncMethod = GetMethod(obj, Symbol.iterator); + const syncIteratorRecord = GetIterator(obj, 'sync', syncMethod); + return CreateAsyncFromSyncIterator(syncIteratorRecord); + } + } + else { + method = GetMethod(obj, Symbol.iterator); + } + } + if (method === undefined) { + throw new TypeError('The object is not iterable'); + } + const iterator = reflectCall(method, obj, []); + if (!typeIsObject(iterator)) { + throw new TypeError('The iterator method must return an object'); + } + const nextMethod = iterator.next; + return { iterator, nextMethod, done: false }; +} +function IteratorNext(iteratorRecord) { + const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []); + if (!typeIsObject(result)) { + throw new TypeError('The iterator.next() method must return an object'); + } + return result; +} +function IteratorComplete(iterResult) { + return Boolean(iterResult.done); +} +function IteratorValue(iterResult) { + return iterResult.value; +} + +/// +// We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it. +const AsyncIteratorPrototype = { + // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( ) + // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator + [SymbolAsyncIterator]() { + return this; + } +}; +Object.defineProperty(AsyncIteratorPrototype, SymbolAsyncIterator, { enumerable: false }); + +/// +class ReadableStreamAsyncIteratorImpl { + constructor(reader, preventCancel) { + this._ongoingPromise = undefined; + this._isFinished = false; + this._reader = reader; + this._preventCancel = preventCancel; + } + next() { + const nextSteps = () => this._nextSteps(); + this._ongoingPromise = this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : + nextSteps(); + return this._ongoingPromise; + } + return(value) { + const returnSteps = () => this._returnSteps(value); + return this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : + returnSteps(); + } + _nextSteps() { + if (this._isFinished) { + return Promise.resolve({ value: undefined, done: true }); + } + const reader = this._reader; + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => { + this._ongoingPromise = undefined; + // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test. + // FIXME Is this a bug in the specification, or in the test? + _queueMicrotask(() => resolvePromise({ value: chunk, done: false })); + }, + _closeSteps: () => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + resolvePromise({ value: undefined, done: true }); + }, + _errorSteps: reason => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + rejectPromise(reason); + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promise; + } + _returnSteps(value) { + if (this._isFinished) { + return Promise.resolve({ value, done: true }); + } + this._isFinished = true; + const reader = this._reader; + if (!this._preventCancel) { + const result = ReadableStreamReaderGenericCancel(reader, value); + ReadableStreamReaderGenericRelease(reader); + return transformPromiseWith(result, () => ({ value, done: true })); + } + ReadableStreamReaderGenericRelease(reader); + return promiseResolvedWith({ value, done: true }); + } +} +const ReadableStreamAsyncIteratorPrototype = { + next() { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next')); + } + return this._asyncIteratorImpl.next(); + }, + return(value) { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return')); + } + return this._asyncIteratorImpl.return(value); + } +}; +Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); +// Abstract operations for the ReadableStream. +function AcquireReadableStreamAsyncIterator(stream, preventCancel) { + const reader = AcquireReadableStreamDefaultReader(stream); + const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); + const iterator = Object.create(ReadableStreamAsyncIteratorPrototype); + iterator._asyncIteratorImpl = impl; + return iterator; +} +function IsReadableStreamAsyncIterator(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) { + return false; + } + try { + // noinspection SuspiciousTypeOfGuard + return x._asyncIteratorImpl instanceof + ReadableStreamAsyncIteratorImpl; + } + catch (_a) { + return false; + } +} +// Helper functions for the ReadableStream. +function streamAsyncIteratorBrandCheckException(name) { + return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`); +} + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill +const NumberIsNaN = Number.isNaN || function (x) { + // eslint-disable-next-line no-self-compare + return x !== x; +}; + +function IsNonNegativeNumber(v) { + if (typeof v !== 'number') { + return false; + } + if (NumberIsNaN(v)) { + return false; + } + if (v < 0) { + return false; + } + return true; +} +function CloneAsUint8Array(O) { + const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength); + return new Uint8Array(buffer); +} + +function DequeueValue(container) { + const pair = container._queue.shift(); + container._queueTotalSize -= pair.size; + if (container._queueTotalSize < 0) { + container._queueTotalSize = 0; + } + return pair.value; +} +function EnqueueValueWithSize(container, value, size) { + if (!IsNonNegativeNumber(size) || size === Infinity) { + throw new RangeError('Size must be a finite, non-NaN, non-negative number.'); + } + container._queue.push({ value, size }); + container._queueTotalSize += size; +} +function PeekQueueValue(container) { + const pair = container._queue.peek(); + return pair.value; +} +function ResetQueue(container) { + container._queue = new SimpleQueue(); + container._queueTotalSize = 0; +} + +function isDataViewConstructor(ctor) { + return ctor === DataView; +} +function isDataView(view) { + return isDataViewConstructor(view.constructor); +} +function arrayBufferViewElementSize(ctor) { + if (isDataViewConstructor(ctor)) { + return 1; + } + return ctor.BYTES_PER_ELEMENT; +} + +/** + * A pull-into request in a {@link ReadableByteStreamController}. + * + * @public + */ +class ReadableStreamBYOBRequest { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. + */ + get view() { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('view'); + } + return this._view; + } + respond(bytesWritten) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respond'); + } + assertRequiredArgument(bytesWritten, 1, 'respond'); + bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter'); + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(this._view.buffer)) { + throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`); + } + ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); + } + respondWithNewView(view) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respondWithNewView'); + } + assertRequiredArgument(view, 1, 'respondWithNewView'); + if (!ArrayBuffer.isView(view)) { + throw new TypeError('You can only respond with array buffer views'); + } + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(view.buffer)) { + throw new TypeError('The given view\'s buffer has been detached and so cannot be used as a response'); + } + ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); + } +} +Object.defineProperties(ReadableStreamBYOBRequest.prototype, { + respond: { enumerable: true }, + respondWithNewView: { enumerable: true }, + view: { enumerable: true } +}); +setFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond'); +setFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, { + value: 'ReadableStreamBYOBRequest', + configurable: true + }); +} +/** + * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. + * + * @public + */ +class ReadableByteStreamController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the current BYOB pull request, or `null` if there isn't one. + */ + get byobRequest() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('byobRequest'); + } + return ReadableByteStreamControllerGetBYOBRequest(this); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('desiredSize'); + } + return ReadableByteStreamControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('close'); + } + if (this._closeRequested) { + throw new TypeError('The stream has already been closed; do not close it again!'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`); + } + ReadableByteStreamControllerClose(this); + } + enqueue(chunk) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('enqueue'); + } + assertRequiredArgument(chunk, 1, 'enqueue'); + if (!ArrayBuffer.isView(chunk)) { + throw new TypeError('chunk must be an array buffer view'); + } + if (chunk.byteLength === 0) { + throw new TypeError('chunk must have non-zero byteLength'); + } + if (chunk.buffer.byteLength === 0) { + throw new TypeError(`chunk's buffer must have non-zero byteLength`); + } + if (this._closeRequested) { + throw new TypeError('stream is closed or draining'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`); + } + ReadableByteStreamControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('error'); + } + ReadableByteStreamControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ReadableByteStreamControllerClearPendingPullIntos(this); + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableByteStreamControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableByteStream; + if (this._queueTotalSize > 0) { + ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest); + return; + } + const autoAllocateChunkSize = this._autoAllocateChunkSize; + if (autoAllocateChunkSize !== undefined) { + let buffer; + try { + buffer = new ArrayBuffer(autoAllocateChunkSize); + } + catch (bufferE) { + readRequest._errorSteps(bufferE); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: autoAllocateChunkSize, + byteOffset: 0, + byteLength: autoAllocateChunkSize, + bytesFilled: 0, + minimumFill: 1, + elementSize: 1, + viewConstructor: Uint8Array, + readerType: 'default' + }; + this._pendingPullIntos.push(pullIntoDescriptor); + } + ReadableStreamAddReadRequest(stream, readRequest); + ReadableByteStreamControllerCallPullIfNeeded(this); + } + /** @internal */ + [ReleaseSteps]() { + if (this._pendingPullIntos.length > 0) { + const firstPullInto = this._pendingPullIntos.peek(); + firstPullInto.readerType = 'none'; + this._pendingPullIntos = new SimpleQueue(); + this._pendingPullIntos.push(firstPullInto); + } + } +} +Object.defineProperties(ReadableByteStreamController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + byobRequest: { enumerable: true }, + desiredSize: { enumerable: true } +}); +setFunctionName(ReadableByteStreamController.prototype.close, 'close'); +setFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue'); +setFunctionName(ReadableByteStreamController.prototype.error, 'error'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, { + value: 'ReadableByteStreamController', + configurable: true + }); +} +// Abstract operations for the ReadableByteStreamController. +function IsReadableByteStreamController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) { + return false; + } + return x instanceof ReadableByteStreamController; +} +function IsReadableStreamBYOBRequest(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) { + return false; + } + return x instanceof ReadableStreamBYOBRequest; +} +function ReadableByteStreamControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableByteStreamControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + // TODO: Test controller argument + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + return null; + }, e => { + ReadableByteStreamControllerError(controller, e); + return null; + }); +} +function ReadableByteStreamControllerClearPendingPullIntos(controller) { + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + controller._pendingPullIntos = new SimpleQueue(); +} +function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { + let done = false; + if (stream._state === 'closed') { + done = true; + } + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'default') { + ReadableStreamFulfillReadRequest(stream, filledView, done); + } + else { + ReadableStreamFulfillReadIntoRequest(stream, filledView, done); + } +} +function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { + const bytesFilled = pullIntoDescriptor.bytesFilled; + const elementSize = pullIntoDescriptor.elementSize; + return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); +} +function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { + controller._queue.push({ buffer, byteOffset, byteLength }); + controller._queueTotalSize += byteLength; +} +function ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, buffer, byteOffset, byteLength) { + let clonedChunk; + try { + clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength); + } + catch (cloneE) { + ReadableByteStreamControllerError(controller, cloneE); + throw cloneE; + } + ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength); +} +function ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstDescriptor) { + if (firstDescriptor.bytesFilled > 0) { + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, firstDescriptor.buffer, firstDescriptor.byteOffset, firstDescriptor.bytesFilled); + } + ReadableByteStreamControllerShiftPendingPullInto(controller); +} +function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { + const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); + const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; + let totalBytesToCopyRemaining = maxBytesToCopy; + let ready = false; + const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize; + const maxAlignedBytes = maxBytesFilled - remainderBytes; + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) { + totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; + ready = true; + } + const queue = controller._queue; + while (totalBytesToCopyRemaining > 0) { + const headOfQueue = queue.peek(); + const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); + const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); + if (headOfQueue.byteLength === bytesToCopy) { + queue.shift(); + } + else { + headOfQueue.byteOffset += bytesToCopy; + headOfQueue.byteLength -= bytesToCopy; + } + controller._queueTotalSize -= bytesToCopy; + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); + totalBytesToCopyRemaining -= bytesToCopy; + } + return ready; +} +function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { + pullIntoDescriptor.bytesFilled += size; +} +function ReadableByteStreamControllerHandleQueueDrain(controller) { + if (controller._queueTotalSize === 0 && controller._closeRequested) { + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(controller._controlledReadableByteStream); + } + else { + ReadableByteStreamControllerCallPullIfNeeded(controller); + } +} +function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { + if (controller._byobRequest === null) { + return; + } + controller._byobRequest._associatedReadableByteStreamController = undefined; + controller._byobRequest._view = null; + controller._byobRequest = null; +} +function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { + while (controller._pendingPullIntos.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const pullIntoDescriptor = controller._pendingPullIntos.peek(); + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + } + } +} +function ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller) { + const reader = controller._controlledReadableByteStream._reader; + while (reader._readRequests.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const readRequest = reader._readRequests.shift(); + ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest); + } +} +function ReadableByteStreamControllerPullInto(controller, view, min, readIntoRequest) { + const stream = controller._controlledReadableByteStream; + const ctor = view.constructor; + const elementSize = arrayBufferViewElementSize(ctor); + const { byteOffset, byteLength } = view; + const minimumFill = min * elementSize; + let buffer; + try { + buffer = TransferArrayBuffer(view.buffer); + } + catch (e) { + readIntoRequest._errorSteps(e); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: buffer.byteLength, + byteOffset, + byteLength, + bytesFilled: 0, + minimumFill, + elementSize, + viewConstructor: ctor, + readerType: 'byob' + }; + if (controller._pendingPullIntos.length > 0) { + controller._pendingPullIntos.push(pullIntoDescriptor); + // No ReadableByteStreamControllerCallPullIfNeeded() call since: + // - No change happens on desiredSize + // - The source has already been notified of that there's at least 1 pending read(view) + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + return; + } + if (stream._state === 'closed') { + const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); + readIntoRequest._closeSteps(emptyView); + return; + } + if (controller._queueTotalSize > 0) { + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + ReadableByteStreamControllerHandleQueueDrain(controller); + readIntoRequest._chunkSteps(filledView); + return; + } + if (controller._closeRequested) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + readIntoRequest._errorSteps(e); + return; + } + } + controller._pendingPullIntos.push(pullIntoDescriptor); + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { + if (firstDescriptor.readerType === 'none') { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const stream = controller._controlledReadableByteStream; + if (ReadableStreamHasBYOBReader(stream)) { + while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { + const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); + } + } +} +function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + return; + } + if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) { + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + return; + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; + if (remainderSize > 0) { + const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor.buffer, end - remainderSize, remainderSize); + } + pullIntoDescriptor.bytesFilled -= remainderSize; + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); +} +function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor); + } + else { + ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerShiftPendingPullInto(controller) { + const descriptor = controller._pendingPullIntos.shift(); + return descriptor; +} +function ReadableByteStreamControllerShouldCallPull(controller) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return false; + } + if (controller._closeRequested) { + return false; + } + if (!controller._started) { + return false; + } + if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; +} +function ReadableByteStreamControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; +} +// A client of ReadableByteStreamController may use these functions directly to bypass state check. +function ReadableByteStreamControllerClose(controller) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + if (controller._queueTotalSize > 0) { + controller._closeRequested = true; + return; + } + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + throw e; + } + } + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(stream); +} +function ReadableByteStreamControllerEnqueue(controller, chunk) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + const { buffer, byteOffset, byteLength } = chunk; + if (IsDetachedBuffer(buffer)) { + throw new TypeError('chunk\'s buffer is detached and so cannot be enqueued'); + } + const transferredBuffer = TransferArrayBuffer(buffer); + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (IsDetachedBuffer(firstPendingPullInto.buffer)) { + throw new TypeError('The BYOB request\'s buffer has been detached and so cannot be filled with an enqueued chunk'); + } + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer); + if (firstPendingPullInto.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto); + } + } + if (ReadableStreamHasDefaultReader(stream)) { + ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller); + if (ReadableStreamGetNumReadRequests(stream) === 0) { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + else { + if (controller._pendingPullIntos.length > 0) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); + ReadableStreamFulfillReadRequest(stream, transferredView, false); + } + } + else if (ReadableStreamHasBYOBReader(stream)) { + // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully. + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + else { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerError(controller, e) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return; + } + ReadableByteStreamControllerClearPendingPullIntos(controller); + ResetQueue(controller); + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); +} +function ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest) { + const entry = controller._queue.shift(); + controller._queueTotalSize -= entry.byteLength; + ReadableByteStreamControllerHandleQueueDrain(controller); + const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); + readRequest._chunkSteps(view); +} +function ReadableByteStreamControllerGetBYOBRequest(controller) { + if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); + const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); + SetUpReadableStreamBYOBRequest(byobRequest, controller, view); + controller._byobRequest = byobRequest; + } + return controller._byobRequest; +} +function ReadableByteStreamControllerGetDesiredSize(controller) { + const state = controller._controlledReadableByteStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; +} +function ReadableByteStreamControllerRespond(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (bytesWritten !== 0) { + throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream'); + } + } + else { + if (bytesWritten === 0) { + throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream'); + } + if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) { + throw new RangeError('bytesWritten out of range'); + } + } + firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); + ReadableByteStreamControllerRespondInternal(controller, bytesWritten); +} +function ReadableByteStreamControllerRespondWithNewView(controller, view) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (view.byteLength !== 0) { + throw new TypeError('The view\'s length must be 0 when calling respondWithNewView() on a closed stream'); + } + } + else { + if (view.byteLength === 0) { + throw new TypeError('The view\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'); + } + } + if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { + throw new RangeError('The region specified by view does not match byobRequest'); + } + if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) { + throw new RangeError('The buffer of view has different capacity than byobRequest'); + } + if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) { + throw new RangeError('The region specified by view is larger than byobRequest'); + } + const viewByteLength = view.byteLength; + firstDescriptor.buffer = TransferArrayBuffer(view.buffer); + ReadableByteStreamControllerRespondInternal(controller, viewByteLength); +} +function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { + controller._controlledReadableByteStream = stream; + controller._pullAgain = false; + controller._pulling = false; + controller._byobRequest = null; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._closeRequested = false; + controller._started = false; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._autoAllocateChunkSize = autoAllocateChunkSize; + controller._pendingPullIntos = new SimpleQueue(); + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableByteStreamControllerCallPullIfNeeded(controller); + return null; + }, r => { + ReadableByteStreamControllerError(controller, r); + return null; + }); +} +function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { + const controller = Object.create(ReadableByteStreamController.prototype); + let startAlgorithm; + let pullAlgorithm; + let cancelAlgorithm; + if (underlyingByteSource.start !== undefined) { + startAlgorithm = () => underlyingByteSource.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingByteSource.pull !== undefined) { + pullAlgorithm = () => underlyingByteSource.pull(controller); + } + else { + pullAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingByteSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingByteSource.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; + if (autoAllocateChunkSize === 0) { + throw new TypeError('autoAllocateChunkSize must be greater than 0'); + } + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); +} +function SetUpReadableStreamBYOBRequest(request, controller, view) { + request._associatedReadableByteStreamController = controller; + request._view = view; +} +// Helper functions for the ReadableStreamBYOBRequest. +function byobRequestBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`); +} +// Helper functions for the ReadableByteStreamController. +function byteStreamControllerBrandCheckException(name) { + return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`); +} + +function convertReaderOptions(options, context) { + assertDictionary(options, context); + const mode = options === null || options === void 0 ? void 0 : options.mode; + return { + mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`) + }; +} +function convertReadableStreamReaderMode(mode, context) { + mode = `${mode}`; + if (mode !== 'byob') { + throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`); + } + return mode; +} +function convertByobReadOptions(options, context) { + var _a; + assertDictionary(options, context); + const min = (_a = options === null || options === void 0 ? void 0 : options.min) !== null && _a !== void 0 ? _a : 1; + return { + min: convertUnsignedLongLongWithEnforceRange(min, `${context} has member 'min' that`) + }; +} + +// Abstract operations for the ReadableStream. +function AcquireReadableStreamBYOBReader(stream) { + return new ReadableStreamBYOBReader(stream); +} +// ReadableStream API exposed for controllers. +function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { + stream._reader._readIntoRequests.push(readIntoRequest); +} +function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { + const reader = stream._reader; + const readIntoRequest = reader._readIntoRequests.shift(); + if (done) { + readIntoRequest._closeSteps(chunk); + } + else { + readIntoRequest._chunkSteps(chunk); + } +} +function ReadableStreamGetNumReadIntoRequests(stream) { + return stream._reader._readIntoRequests.length; +} +function ReadableStreamHasBYOBReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamBYOBReader(reader)) { + return false; + } + return true; +} +/** + * A BYOB reader vended by a {@link ReadableStream}. + * + * @public + */ +class ReadableStreamBYOBReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + if (!IsReadableByteStreamController(stream._readableStreamController)) { + throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' + + 'source'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readIntoRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + read(view, rawOptions = {}) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('read')); + } + if (!ArrayBuffer.isView(view)) { + return promiseRejectedWith(new TypeError('view must be an array buffer view')); + } + if (view.byteLength === 0) { + return promiseRejectedWith(new TypeError('view must have non-zero byteLength')); + } + if (view.buffer.byteLength === 0) { + return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`)); + } + if (IsDetachedBuffer(view.buffer)) { + return promiseRejectedWith(new TypeError('view\'s buffer has been detached')); + } + let options; + try { + options = convertByobReadOptions(rawOptions, 'options'); + } + catch (e) { + return promiseRejectedWith(e); + } + const min = options.min; + if (min === 0) { + return promiseRejectedWith(new TypeError('options.min must be greater than 0')); + } + if (!isDataView(view)) { + if (min > view.length) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s length')); + } + } + else if (min > view.byteLength) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s byteLength')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readIntoRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: chunk => resolvePromise({ value: chunk, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamBYOBReader(this)) { + throw byobReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamBYOBReaderRelease(this); + } +} +Object.defineProperties(ReadableStreamBYOBReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } +}); +setFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel'); +setFunctionName(ReadableStreamBYOBReader.prototype.read, 'read'); +setFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, { + value: 'ReadableStreamBYOBReader', + configurable: true + }); +} +// Abstract operations for the readers. +function IsReadableStreamBYOBReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) { + return false; + } + return x instanceof ReadableStreamBYOBReader; +} +function ReadableStreamBYOBReaderRead(reader, view, min, readIntoRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'errored') { + readIntoRequest._errorSteps(stream._storedError); + } + else { + ReadableByteStreamControllerPullInto(stream._readableStreamController, view, min, readIntoRequest); + } +} +function ReadableStreamBYOBReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + const e = new TypeError('Reader was released'); + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); +} +function ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e) { + const readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._errorSteps(e); + }); +} +// Helper functions for the ReadableStreamBYOBReader. +function byobReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`); +} + +function ExtractHighWaterMark(strategy, defaultHWM) { + const { highWaterMark } = strategy; + if (highWaterMark === undefined) { + return defaultHWM; + } + if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { + throw new RangeError('Invalid highWaterMark'); + } + return highWaterMark; +} +function ExtractSizeAlgorithm(strategy) { + const { size } = strategy; + if (!size) { + return () => 1; + } + return size; +} + +function convertQueuingStrategy(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + const size = init === null || init === void 0 ? void 0 : init.size; + return { + highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark), + size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`) + }; +} +function convertQueuingStrategySize(fn, context) { + assertFunction(fn, context); + return chunk => convertUnrestrictedDouble(fn(chunk)); +} + +function convertUnderlyingSink(original, context) { + assertDictionary(original, context); + const abort = original === null || original === void 0 ? void 0 : original.abort; + const close = original === null || original === void 0 ? void 0 : original.close; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + const write = original === null || original === void 0 ? void 0 : original.write; + return { + abort: abort === undefined ? + undefined : + convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`), + close: close === undefined ? + undefined : + convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`), + start: start === undefined ? + undefined : + convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`), + write: write === undefined ? + undefined : + convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`), + type + }; +} +function convertUnderlyingSinkAbortCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); +} +function convertUnderlyingSinkCloseCallback(fn, original, context) { + assertFunction(fn, context); + return () => promiseCall(fn, original, []); +} +function convertUnderlyingSinkStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); +} +function convertUnderlyingSinkWriteCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); +} + +function assertWritableStream(x, context) { + if (!IsWritableStream(x)) { + throw new TypeError(`${context} is not a WritableStream.`); + } +} + +function isAbortSignal(value) { + if (typeof value !== 'object' || value === null) { + return false; + } + try { + return typeof value.aborted === 'boolean'; + } + catch (_a) { + // AbortSignal.prototype.aborted throws if its brand check fails + return false; + } +} +const supportsAbortController = typeof AbortController === 'function'; +/** + * Construct a new AbortController, if supported by the platform. + * + * @internal + */ +function createAbortController() { + if (supportsAbortController) { + return new AbortController(); + } + return undefined; +} + +/** + * A writable stream represents a destination for data, into which you can write. + * + * @public + */ +class WritableStream { + constructor(rawUnderlyingSink = {}, rawStrategy = {}) { + if (rawUnderlyingSink === undefined) { + rawUnderlyingSink = null; + } + else { + assertObject(rawUnderlyingSink, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter'); + InitializeWritableStream(this); + const type = underlyingSink.type; + if (type !== undefined) { + throw new RangeError('Invalid type is specified'); + } + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); + } + /** + * Returns whether or not the writable stream is locked to a writer. + */ + get locked() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('locked'); + } + return IsWritableStreamLocked(this); + } + /** + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort + * mechanism of the underlying sink. + * + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel + * the stream) if the stream is currently locked. + */ + abort(reason = undefined) { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('abort')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer')); + } + return WritableStreamAbort(this, reason); + } + /** + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its + * close behavior. During this time any further attempts to write will fail (without erroring the stream). + * + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + */ + close() { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('close')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer')); + } + if (WritableStreamCloseQueuedOrInFlight(this)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamClose(this); + } + /** + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream + * is locked, no other writer can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at + * the same time, which would cause the resulting written data to be unpredictable and probably useless. + */ + getWriter() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('getWriter'); + } + return AcquireWritableStreamDefaultWriter(this); + } +} +Object.defineProperties(WritableStream.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + getWriter: { enumerable: true }, + locked: { enumerable: true } +}); +setFunctionName(WritableStream.prototype.abort, 'abort'); +setFunctionName(WritableStream.prototype.close, 'close'); +setFunctionName(WritableStream.prototype.getWriter, 'getWriter'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, { + value: 'WritableStream', + configurable: true + }); +} +// Abstract operations for the WritableStream. +function AcquireWritableStreamDefaultWriter(stream) { + return new WritableStreamDefaultWriter(stream); +} +// Throws if and only if startAlgorithm throws. +function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(WritableStream.prototype); + InitializeWritableStream(stream); + const controller = Object.create(WritableStreamDefaultController.prototype); + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + return stream; +} +function InitializeWritableStream(stream) { + stream._state = 'writable'; + // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is + // 'erroring' or 'errored'. May be set to an undefined value. + stream._storedError = undefined; + stream._writer = undefined; + // Initialize to undefined first because the constructor of the controller checks this + // variable to validate the caller. + stream._writableStreamController = undefined; + // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data + // producer without waiting for the queued writes to finish. + stream._writeRequests = new SimpleQueue(); + // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents + // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here. + stream._inFlightWriteRequest = undefined; + // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer + // has been detached. + stream._closeRequest = undefined; + // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it + // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here. + stream._inFlightCloseRequest = undefined; + // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached. + stream._pendingAbortRequest = undefined; + // The backpressure signal set by the controller. + stream._backpressure = false; +} +function IsWritableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) { + return false; + } + return x instanceof WritableStream; +} +function IsWritableStreamLocked(stream) { + if (stream._writer === undefined) { + return false; + } + return true; +} +function WritableStreamAbort(stream, reason) { + var _a; + if (stream._state === 'closed' || stream._state === 'errored') { + return promiseResolvedWith(undefined); + } + stream._writableStreamController._abortReason = reason; + (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort(reason); + // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring', + // but it doesn't know that signaling abort runs author code that might have changed the state. + // Widen the type again by casting to WritableStreamState. + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseResolvedWith(undefined); + } + if (stream._pendingAbortRequest !== undefined) { + return stream._pendingAbortRequest._promise; + } + let wasAlreadyErroring = false; + if (state === 'erroring') { + wasAlreadyErroring = true; + // reason will not be used, so don't keep a reference to it. + reason = undefined; + } + const promise = newPromise((resolve, reject) => { + stream._pendingAbortRequest = { + _promise: undefined, + _resolve: resolve, + _reject: reject, + _reason: reason, + _wasAlreadyErroring: wasAlreadyErroring + }; + }); + stream._pendingAbortRequest._promise = promise; + if (!wasAlreadyErroring) { + WritableStreamStartErroring(stream, reason); + } + return promise; +} +function WritableStreamClose(stream) { + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`)); + } + const promise = newPromise((resolve, reject) => { + const closeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._closeRequest = closeRequest; + }); + const writer = stream._writer; + if (writer !== undefined && stream._backpressure && state === 'writable') { + defaultWriterReadyPromiseResolve(writer); + } + WritableStreamDefaultControllerClose(stream._writableStreamController); + return promise; +} +// WritableStream API exposed for controllers. +function WritableStreamAddWriteRequest(stream) { + const promise = newPromise((resolve, reject) => { + const writeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._writeRequests.push(writeRequest); + }); + return promise; +} +function WritableStreamDealWithRejection(stream, error) { + const state = stream._state; + if (state === 'writable') { + WritableStreamStartErroring(stream, error); + return; + } + WritableStreamFinishErroring(stream); +} +function WritableStreamStartErroring(stream, reason) { + const controller = stream._writableStreamController; + stream._state = 'erroring'; + stream._storedError = reason; + const writer = stream._writer; + if (writer !== undefined) { + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); + } + if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { + WritableStreamFinishErroring(stream); + } +} +function WritableStreamFinishErroring(stream) { + stream._state = 'errored'; + stream._writableStreamController[ErrorSteps](); + const storedError = stream._storedError; + stream._writeRequests.forEach(writeRequest => { + writeRequest._reject(storedError); + }); + stream._writeRequests = new SimpleQueue(); + if (stream._pendingAbortRequest === undefined) { + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const abortRequest = stream._pendingAbortRequest; + stream._pendingAbortRequest = undefined; + if (abortRequest._wasAlreadyErroring) { + abortRequest._reject(storedError); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const promise = stream._writableStreamController[AbortSteps](abortRequest._reason); + uponPromise(promise, () => { + abortRequest._resolve(); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }, (reason) => { + abortRequest._reject(reason); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }); +} +function WritableStreamFinishInFlightWrite(stream) { + stream._inFlightWriteRequest._resolve(undefined); + stream._inFlightWriteRequest = undefined; +} +function WritableStreamFinishInFlightWriteWithError(stream, error) { + stream._inFlightWriteRequest._reject(error); + stream._inFlightWriteRequest = undefined; + WritableStreamDealWithRejection(stream, error); +} +function WritableStreamFinishInFlightClose(stream) { + stream._inFlightCloseRequest._resolve(undefined); + stream._inFlightCloseRequest = undefined; + const state = stream._state; + if (state === 'erroring') { + // The error was too late to do anything, so it is ignored. + stream._storedError = undefined; + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._resolve(); + stream._pendingAbortRequest = undefined; + } + } + stream._state = 'closed'; + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseResolve(writer); + } +} +function WritableStreamFinishInFlightCloseWithError(stream, error) { + stream._inFlightCloseRequest._reject(error); + stream._inFlightCloseRequest = undefined; + // Never execute sink abort() after sink close(). + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._reject(error); + stream._pendingAbortRequest = undefined; + } + WritableStreamDealWithRejection(stream, error); +} +// TODO(ricea): Fix alphabetical order. +function WritableStreamCloseQueuedOrInFlight(stream) { + if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; +} +function WritableStreamHasOperationMarkedInFlight(stream) { + if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; +} +function WritableStreamMarkCloseRequestInFlight(stream) { + stream._inFlightCloseRequest = stream._closeRequest; + stream._closeRequest = undefined; +} +function WritableStreamMarkFirstWriteRequestInFlight(stream) { + stream._inFlightWriteRequest = stream._writeRequests.shift(); +} +function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { + if (stream._closeRequest !== undefined) { + stream._closeRequest._reject(stream._storedError); + stream._closeRequest = undefined; + } + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseReject(writer, stream._storedError); + } +} +function WritableStreamUpdateBackpressure(stream, backpressure) { + const writer = stream._writer; + if (writer !== undefined && backpressure !== stream._backpressure) { + if (backpressure) { + defaultWriterReadyPromiseReset(writer); + } + else { + defaultWriterReadyPromiseResolve(writer); + } + } + stream._backpressure = backpressure; +} +/** + * A default writer vended by a {@link WritableStream}. + * + * @public + */ +class WritableStreamDefaultWriter { + constructor(stream) { + assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter'); + assertWritableStream(stream, 'First parameter'); + if (IsWritableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive writing by another writer'); + } + this._ownerWritableStream = stream; + stream._writer = this; + const state = stream._state; + if (state === 'writable') { + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { + defaultWriterReadyPromiseInitialize(this); + } + else { + defaultWriterReadyPromiseInitializeAsResolved(this); + } + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'erroring') { + defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'closed') { + defaultWriterReadyPromiseInitializeAsResolved(this); + defaultWriterClosedPromiseInitializeAsResolved(this); + } + else { + const storedError = stream._storedError; + defaultWriterReadyPromiseInitializeAsRejected(this, storedError); + defaultWriterClosedPromiseInitializeAsRejected(this, storedError); + } + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the writer’s lock is released before the stream finishes closing. + */ + get closed() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. + * A producer can use this information to determine the right amount of data to write. + * + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when + * the writer’s lock is released. + */ + get desiredSize() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('desiredSize'); + } + if (this._ownerWritableStream === undefined) { + throw defaultWriterLockException('desiredSize'); + } + return WritableStreamDefaultWriterGetDesiredSize(this); + } + /** + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips + * back to zero or below, the getter will return a new promise that stays pending until the next transition. + * + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become + * rejected. + */ + get ready() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('ready')); + } + return this._readyPromise; + } + /** + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + */ + abort(reason = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('abort')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('abort')); + } + return WritableStreamDefaultWriterAbort(this, reason); + } + /** + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + */ + close() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('close')); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return promiseRejectedWith(defaultWriterLockException('close')); + } + if (WritableStreamCloseQueuedOrInFlight(stream)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamDefaultWriterClose(this); + } + /** + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from + * now on; otherwise, the writer will appear closed. + * + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents + * other producers from writing in an interleaved manner. + */ + releaseLock() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('releaseLock'); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return; + } + WritableStreamDefaultWriterRelease(this); + } + write(chunk = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('write')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + return WritableStreamDefaultWriterWrite(this, chunk); + } +} +Object.defineProperties(WritableStreamDefaultWriter.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + releaseLock: { enumerable: true }, + write: { enumerable: true }, + closed: { enumerable: true }, + desiredSize: { enumerable: true }, + ready: { enumerable: true } +}); +setFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort'); +setFunctionName(WritableStreamDefaultWriter.prototype.close, 'close'); +setFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock'); +setFunctionName(WritableStreamDefaultWriter.prototype.write, 'write'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, { + value: 'WritableStreamDefaultWriter', + configurable: true + }); +} +// Abstract operations for the WritableStreamDefaultWriter. +function IsWritableStreamDefaultWriter(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultWriter; +} +// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check. +function WritableStreamDefaultWriterAbort(writer, reason) { + const stream = writer._ownerWritableStream; + return WritableStreamAbort(stream, reason); +} +function WritableStreamDefaultWriterClose(writer) { + const stream = writer._ownerWritableStream; + return WritableStreamClose(stream); +} +function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseResolvedWith(undefined); + } + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + return WritableStreamDefaultWriterClose(writer); +} +function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { + if (writer._closedPromiseState === 'pending') { + defaultWriterClosedPromiseReject(writer, error); + } + else { + defaultWriterClosedPromiseResetToRejected(writer, error); + } +} +function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { + if (writer._readyPromiseState === 'pending') { + defaultWriterReadyPromiseReject(writer, error); + } + else { + defaultWriterReadyPromiseResetToRejected(writer, error); + } +} +function WritableStreamDefaultWriterGetDesiredSize(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (state === 'errored' || state === 'erroring') { + return null; + } + if (state === 'closed') { + return 0; + } + return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); +} +function WritableStreamDefaultWriterRelease(writer) { + const stream = writer._ownerWritableStream; + const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`); + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); + // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not + // rejected until afterwards. This means that simply testing state will not work. + WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); + stream._writer = undefined; + writer._ownerWritableStream = undefined; +} +function WritableStreamDefaultWriterWrite(writer, chunk) { + const stream = writer._ownerWritableStream; + const controller = stream._writableStreamController; + const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); + if (stream !== writer._ownerWritableStream) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + const state = stream._state; + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to')); + } + if (state === 'erroring') { + return promiseRejectedWith(stream._storedError); + } + const promise = WritableStreamAddWriteRequest(stream); + WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); + return promise; +} +const closeSentinel = {}; +/** + * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. + * + * @public + */ +class WritableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. + * + * @deprecated + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. + */ + get abortReason() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('abortReason'); + } + return this._abortReason; + } + /** + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. + */ + get signal() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('signal'); + } + if (this._abortController === undefined) { + // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`. + // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill, + // so instead we only implement support for `signal` if we find a global `AbortController` constructor. + throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported'); + } + return this._abortController.signal; + } + /** + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. + * + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the + * normal lifecycle of interactions with the underlying sink. + */ + error(e = undefined) { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('error'); + } + const state = this._controlledWritableStream._state; + if (state !== 'writable') { + // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so + // just treat it as a no-op. + return; + } + WritableStreamDefaultControllerError(this, e); + } + /** @internal */ + [AbortSteps](reason) { + const result = this._abortAlgorithm(reason); + WritableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [ErrorSteps]() { + ResetQueue(this); + } +} +Object.defineProperties(WritableStreamDefaultController.prototype, { + abortReason: { enumerable: true }, + signal: { enumerable: true }, + error: { enumerable: true } +}); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, { + value: 'WritableStreamDefaultController', + configurable: true + }); +} +// Abstract operations implementing interface required by the WritableStream. +function IsWritableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultController; +} +function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledWritableStream = stream; + stream._writableStreamController = controller; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._abortReason = undefined; + controller._abortController = createAbortController(); + controller._started = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._writeAlgorithm = writeAlgorithm; + controller._closeAlgorithm = closeAlgorithm; + controller._abortAlgorithm = abortAlgorithm; + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + const startResult = startAlgorithm(); + const startPromise = promiseResolvedWith(startResult); + uponPromise(startPromise, () => { + controller._started = true; + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, r => { + controller._started = true; + WritableStreamDealWithRejection(stream, r); + return null; + }); +} +function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { + const controller = Object.create(WritableStreamDefaultController.prototype); + let startAlgorithm; + let writeAlgorithm; + let closeAlgorithm; + let abortAlgorithm; + if (underlyingSink.start !== undefined) { + startAlgorithm = () => underlyingSink.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingSink.write !== undefined) { + writeAlgorithm = chunk => underlyingSink.write(chunk, controller); + } + else { + writeAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSink.close !== undefined) { + closeAlgorithm = () => underlyingSink.close(); + } + else { + closeAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSink.abort !== undefined) { + abortAlgorithm = reason => underlyingSink.abort(reason); + } + else { + abortAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); +} +// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls. +function WritableStreamDefaultControllerClearAlgorithms(controller) { + controller._writeAlgorithm = undefined; + controller._closeAlgorithm = undefined; + controller._abortAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; +} +function WritableStreamDefaultControllerClose(controller) { + EnqueueValueWithSize(controller, closeSentinel, 0); + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); +} +function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { + try { + return controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); + return 1; + } +} +function WritableStreamDefaultControllerGetDesiredSize(controller) { + return controller._strategyHWM - controller._queueTotalSize; +} +function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); + return; + } + const stream = controller._controlledWritableStream; + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); +} +// Abstract operations for the WritableStreamDefaultController. +function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { + const stream = controller._controlledWritableStream; + if (!controller._started) { + return; + } + if (stream._inFlightWriteRequest !== undefined) { + return; + } + const state = stream._state; + if (state === 'erroring') { + WritableStreamFinishErroring(stream); + return; + } + if (controller._queue.length === 0) { + return; + } + const value = PeekQueueValue(controller); + if (value === closeSentinel) { + WritableStreamDefaultControllerProcessClose(controller); + } + else { + WritableStreamDefaultControllerProcessWrite(controller, value); + } +} +function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { + if (controller._controlledWritableStream._state === 'writable') { + WritableStreamDefaultControllerError(controller, error); + } +} +function WritableStreamDefaultControllerProcessClose(controller) { + const stream = controller._controlledWritableStream; + WritableStreamMarkCloseRequestInFlight(stream); + DequeueValue(controller); + const sinkClosePromise = controller._closeAlgorithm(); + WritableStreamDefaultControllerClearAlgorithms(controller); + uponPromise(sinkClosePromise, () => { + WritableStreamFinishInFlightClose(stream); + return null; + }, reason => { + WritableStreamFinishInFlightCloseWithError(stream, reason); + return null; + }); +} +function WritableStreamDefaultControllerProcessWrite(controller, chunk) { + const stream = controller._controlledWritableStream; + WritableStreamMarkFirstWriteRequestInFlight(stream); + const sinkWritePromise = controller._writeAlgorithm(chunk); + uponPromise(sinkWritePromise, () => { + WritableStreamFinishInFlightWrite(stream); + const state = stream._state; + DequeueValue(controller); + if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, reason => { + if (stream._state === 'writable') { + WritableStreamDefaultControllerClearAlgorithms(controller); + } + WritableStreamFinishInFlightWriteWithError(stream, reason); + return null; + }); +} +function WritableStreamDefaultControllerGetBackpressure(controller) { + const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); + return desiredSize <= 0; +} +// A client of WritableStreamDefaultController may use these functions directly to bypass state check. +function WritableStreamDefaultControllerError(controller, error) { + const stream = controller._controlledWritableStream; + WritableStreamDefaultControllerClearAlgorithms(controller); + WritableStreamStartErroring(stream, error); +} +// Helper functions for the WritableStream. +function streamBrandCheckException$2(name) { + return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`); +} +// Helper functions for the WritableStreamDefaultController. +function defaultControllerBrandCheckException$2(name) { + return new TypeError(`WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`); +} +// Helper functions for the WritableStreamDefaultWriter. +function defaultWriterBrandCheckException(name) { + return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`); +} +function defaultWriterLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released writer'); +} +function defaultWriterClosedPromiseInitialize(writer) { + writer._closedPromise = newPromise((resolve, reject) => { + writer._closedPromise_resolve = resolve; + writer._closedPromise_reject = reject; + writer._closedPromiseState = 'pending'; + }); +} +function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseReject(writer, reason); +} +function defaultWriterClosedPromiseInitializeAsResolved(writer) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseResolve(writer); +} +function defaultWriterClosedPromiseReject(writer, reason) { + if (writer._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._closedPromise); + writer._closedPromise_reject(reason); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'rejected'; +} +function defaultWriterClosedPromiseResetToRejected(writer, reason) { + defaultWriterClosedPromiseInitializeAsRejected(writer, reason); +} +function defaultWriterClosedPromiseResolve(writer) { + if (writer._closedPromise_resolve === undefined) { + return; + } + writer._closedPromise_resolve(undefined); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'resolved'; +} +function defaultWriterReadyPromiseInitialize(writer) { + writer._readyPromise = newPromise((resolve, reject) => { + writer._readyPromise_resolve = resolve; + writer._readyPromise_reject = reject; + }); + writer._readyPromiseState = 'pending'; +} +function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseReject(writer, reason); +} +function defaultWriterReadyPromiseInitializeAsResolved(writer) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseResolve(writer); +} +function defaultWriterReadyPromiseReject(writer, reason) { + if (writer._readyPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._readyPromise); + writer._readyPromise_reject(reason); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'rejected'; +} +function defaultWriterReadyPromiseReset(writer) { + defaultWriterReadyPromiseInitialize(writer); +} +function defaultWriterReadyPromiseResetToRejected(writer, reason) { + defaultWriterReadyPromiseInitializeAsRejected(writer, reason); +} +function defaultWriterReadyPromiseResolve(writer) { + if (writer._readyPromise_resolve === undefined) { + return; + } + writer._readyPromise_resolve(undefined); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'fulfilled'; +} + +/// +function getGlobals() { + if (typeof globalThis !== 'undefined') { + return globalThis; + } + else if (typeof self !== 'undefined') { + return self; + } + else if (typeof global !== 'undefined') { + return global; + } + return undefined; +} +const globals = getGlobals(); + +/// +function isDOMExceptionConstructor(ctor) { + if (!(typeof ctor === 'function' || typeof ctor === 'object')) { + return false; + } + if (ctor.name !== 'DOMException') { + return false; + } + try { + new ctor(); + return true; + } + catch (_a) { + return false; + } +} +/** + * Support: + * - Web browsers + * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87) + */ +function getFromGlobal() { + const ctor = globals === null || globals === void 0 ? void 0 : globals.DOMException; + return isDOMExceptionConstructor(ctor) ? ctor : undefined; +} +/** + * Support: + * - All platforms + */ +function createPolyfill() { + // eslint-disable-next-line @typescript-eslint/no-shadow + const ctor = function DOMException(message, name) { + this.message = message || ''; + this.name = name || 'Error'; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + }; + setFunctionName(ctor, 'DOMException'); + ctor.prototype = Object.create(Error.prototype); + Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true }); + return ctor; +} +// eslint-disable-next-line @typescript-eslint/no-redeclare +const DOMException = getFromGlobal() || createPolyfill(); + +function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { + const reader = AcquireReadableStreamDefaultReader(source); + const writer = AcquireWritableStreamDefaultWriter(dest); + source._disturbed = true; + let shuttingDown = false; + // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown. + let currentWrite = promiseResolvedWith(undefined); + return newPromise((resolve, reject) => { + let abortAlgorithm; + if (signal !== undefined) { + abortAlgorithm = () => { + const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError'); + const actions = []; + if (!preventAbort) { + actions.push(() => { + if (dest._state === 'writable') { + return WritableStreamAbort(dest, error); + } + return promiseResolvedWith(undefined); + }); + } + if (!preventCancel) { + actions.push(() => { + if (source._state === 'readable') { + return ReadableStreamCancel(source, error); + } + return promiseResolvedWith(undefined); + }); + } + shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error); + }; + if (signal.aborted) { + abortAlgorithm(); + return; + } + signal.addEventListener('abort', abortAlgorithm); + } + // Using reader and writer, read all chunks from this and write them to dest + // - Backpressure must be enforced + // - Shutdown must stop all activity + function pipeLoop() { + return newPromise((resolveLoop, rejectLoop) => { + function next(done) { + if (done) { + resolveLoop(); + } + else { + // Use `PerformPromiseThen` instead of `uponPromise` to avoid + // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers + PerformPromiseThen(pipeStep(), next, rejectLoop); + } + } + next(false); + }); + } + function pipeStep() { + if (shuttingDown) { + return promiseResolvedWith(true); + } + return PerformPromiseThen(writer._readyPromise, () => { + return newPromise((resolveRead, rejectRead) => { + ReadableStreamDefaultReaderRead(reader, { + _chunkSteps: chunk => { + currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop); + resolveRead(false); + }, + _closeSteps: () => resolveRead(true), + _errorSteps: rejectRead + }); + }); + }); + } + // Errors must be propagated forward + isOrBecomesErrored(source, reader._closedPromise, storedError => { + if (!preventAbort) { + shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Errors must be propagated backward + isOrBecomesErrored(dest, writer._closedPromise, storedError => { + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Closing must be propagated forward + isOrBecomesClosed(source, reader._closedPromise, () => { + if (!preventClose) { + shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer)); + } + else { + shutdown(); + } + return null; + }); + // Closing must be propagated backward + if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') { + const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it'); + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed); + } + else { + shutdown(true, destClosed); + } + } + setPromiseIsHandledToTrue(pipeLoop()); + function waitForWritesToFinish() { + // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait + // for that too. + const oldCurrentWrite = currentWrite; + return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined); + } + function isOrBecomesErrored(stream, promise, action) { + if (stream._state === 'errored') { + action(stream._storedError); + } + else { + uponRejection(promise, action); + } + } + function isOrBecomesClosed(stream, promise, action) { + if (stream._state === 'closed') { + action(); + } + else { + uponFulfillment(promise, action); + } + } + function shutdownWithAction(action, originalIsError, originalError) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), doTheRest); + } + else { + doTheRest(); + } + function doTheRest() { + uponPromise(action(), () => finalize(originalIsError, originalError), newError => finalize(true, newError)); + return null; + } + } + function shutdown(isError, error) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error)); + } + else { + finalize(isError, error); + } + } + function finalize(isError, error) { + WritableStreamDefaultWriterRelease(writer); + ReadableStreamReaderGenericRelease(reader); + if (signal !== undefined) { + signal.removeEventListener('abort', abortAlgorithm); + } + if (isError) { + reject(error); + } + else { + resolve(undefined); + } + return null; + } + }); +} + +/** + * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. + * + * @public + */ +class ReadableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('desiredSize'); + } + return ReadableStreamDefaultControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('close'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits close'); + } + ReadableStreamDefaultControllerClose(this); + } + enqueue(chunk = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('enqueue'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits enqueue'); + } + return ReadableStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('error'); + } + ReadableStreamDefaultControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableStream; + if (this._queue.length > 0) { + const chunk = DequeueValue(this); + if (this._closeRequested && this._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(this); + ReadableStreamClose(stream); + } + else { + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + readRequest._chunkSteps(chunk); + } + else { + ReadableStreamAddReadRequest(stream, readRequest); + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + } + /** @internal */ + [ReleaseSteps]() { + // Do nothing. + } +} +Object.defineProperties(ReadableStreamDefaultController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + desiredSize: { enumerable: true } +}); +setFunctionName(ReadableStreamDefaultController.prototype.close, 'close'); +setFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue'); +setFunctionName(ReadableStreamDefaultController.prototype.error, 'error'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, { + value: 'ReadableStreamDefaultController', + configurable: true + }); +} +// Abstract operations for the ReadableStreamDefaultController. +function IsReadableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) { + return false; + } + return x instanceof ReadableStreamDefaultController; +} +function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + return null; + }, e => { + ReadableStreamDefaultControllerError(controller, e); + return null; + }); +} +function ReadableStreamDefaultControllerShouldCallPull(controller) { + const stream = controller._controlledReadableStream; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return false; + } + if (!controller._started) { + return false; + } + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; +} +function ReadableStreamDefaultControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; +} +// A client of ReadableStreamDefaultController may use these functions directly to bypass state check. +function ReadableStreamDefaultControllerClose(controller) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + controller._closeRequested = true; + if (controller._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } +} +function ReadableStreamDefaultControllerEnqueue(controller, chunk) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + ReadableStreamFulfillReadRequest(stream, chunk, false); + } + else { + let chunkSize; + try { + chunkSize = controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + ReadableStreamDefaultControllerError(controller, chunkSizeE); + throw chunkSizeE; + } + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + ReadableStreamDefaultControllerError(controller, enqueueE); + throw enqueueE; + } + } + ReadableStreamDefaultControllerCallPullIfNeeded(controller); +} +function ReadableStreamDefaultControllerError(controller, e) { + const stream = controller._controlledReadableStream; + if (stream._state !== 'readable') { + return; + } + ResetQueue(controller); + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); +} +function ReadableStreamDefaultControllerGetDesiredSize(controller) { + const state = controller._controlledReadableStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; +} +// This is used in the implementation of TransformStream. +function ReadableStreamDefaultControllerHasBackpressure(controller) { + if (ReadableStreamDefaultControllerShouldCallPull(controller)) { + return false; + } + return true; +} +function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { + const state = controller._controlledReadableStream._state; + if (!controller._closeRequested && state === 'readable') { + return true; + } + return false; +} +function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledReadableStream = stream; + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._started = false; + controller._closeRequested = false; + controller._pullAgain = false; + controller._pulling = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + return null; + }, r => { + ReadableStreamDefaultControllerError(controller, r); + return null; + }); +} +function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { + const controller = Object.create(ReadableStreamDefaultController.prototype); + let startAlgorithm; + let pullAlgorithm; + let cancelAlgorithm; + if (underlyingSource.start !== undefined) { + startAlgorithm = () => underlyingSource.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingSource.pull !== undefined) { + pullAlgorithm = () => underlyingSource.pull(controller); + } + else { + pullAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingSource.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); +} +// Helper functions for the ReadableStreamDefaultController. +function defaultControllerBrandCheckException$1(name) { + return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`); +} + +function ReadableStreamTee(stream, cloneForBranch2) { + if (IsReadableByteStreamController(stream._readableStreamController)) { + return ReadableByteStreamTee(stream); + } + return ReadableStreamDefaultTee(stream); +} +function ReadableStreamDefaultTee(stream, cloneForBranch2) { + const reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgain = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function pullAlgorithm() { + if (reading) { + readAgain = true; + return promiseResolvedWith(undefined); + } + reading = true; + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgain = false; + const chunk1 = chunk; + const chunk2 = chunk; + // There is no way to access the cloning code right now in the reference implementation. + // If we add one then we'll need an implementation for serializable objects. + // if (!canceled2 && cloneForBranch2) { + // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2)); + // } + if (!canceled1) { + ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgain) { + pullAlgorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableStreamDefaultControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableStreamDefaultControllerClose(branch2._readableStreamController); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + // do nothing + } + branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); + branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); + uponRejection(reader._closedPromise, (r) => { + ReadableStreamDefaultControllerError(branch1._readableStreamController, r); + ReadableStreamDefaultControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + return [branch1, branch2]; +} +function ReadableByteStreamTee(stream) { + let reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgainForBranch1 = false; + let readAgainForBranch2 = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function forwardReaderError(thisReader) { + uponRejection(thisReader._closedPromise, r => { + if (thisReader !== reader) { + return null; + } + ReadableByteStreamControllerError(branch1._readableStreamController, r); + ReadableByteStreamControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + } + function pullWithDefaultReader() { + if (IsReadableStreamBYOBReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamDefaultReader(stream); + forwardReaderError(reader); + } + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const chunk1 = chunk; + let chunk2 = chunk; + if (!canceled1 && !canceled2) { + try { + chunk2 = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(branch1._readableStreamController, cloneE); + ReadableByteStreamControllerError(branch2._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + } + if (!canceled1) { + ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableByteStreamControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableByteStreamControllerClose(branch2._readableStreamController); + } + if (branch1._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch1._readableStreamController, 0); + } + if (branch2._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch2._readableStreamController, 0); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + } + function pullWithBYOBReader(view, forBranch2) { + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamBYOBReader(stream); + forwardReaderError(reader); + } + const byobBranch = forBranch2 ? branch2 : branch1; + const otherBranch = forBranch2 ? branch1 : branch2; + const readIntoRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!otherCanceled) { + let clonedChunk; + try { + clonedChunk = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE); + ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk); + } + else if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: chunk => { + reading = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!byobCanceled) { + ReadableByteStreamControllerClose(byobBranch._readableStreamController); + } + if (!otherCanceled) { + ReadableByteStreamControllerClose(otherBranch._readableStreamController); + } + if (chunk !== undefined) { + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0); + } + } + if (!byobCanceled || !otherCanceled) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest); + } + function pull1Algorithm() { + if (reading) { + readAgainForBranch1 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, false); + } + return promiseResolvedWith(undefined); + } + function pull2Algorithm() { + if (reading) { + readAgainForBranch2 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, true); + } + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + return; + } + branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm); + branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm); + forwardReaderError(reader); + return [branch1, branch2]; +} + +function isReadableStreamLike(stream) { + return typeIsObject(stream) && typeof stream.getReader !== 'undefined'; +} + +function ReadableStreamFrom(source) { + if (isReadableStreamLike(source)) { + return ReadableStreamFromDefaultReader(source.getReader()); + } + return ReadableStreamFromIterable(source); +} +function ReadableStreamFromIterable(asyncIterable) { + let stream; + const iteratorRecord = GetIterator(asyncIterable, 'async'); + const startAlgorithm = noop; + function pullAlgorithm() { + let nextResult; + try { + nextResult = IteratorNext(iteratorRecord); + } + catch (e) { + return promiseRejectedWith(e); + } + const nextPromise = promiseResolvedWith(nextResult); + return transformPromiseWith(nextPromise, iterResult => { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object'); + } + const done = IteratorComplete(iterResult); + if (done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + const value = IteratorValue(iterResult); + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + const iterator = iteratorRecord.iterator; + let returnMethod; + try { + returnMethod = GetMethod(iterator, 'return'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (returnMethod === undefined) { + return promiseResolvedWith(undefined); + } + let returnResult; + try { + returnResult = reflectCall(returnMethod, iterator, [reason]); + } + catch (e) { + return promiseRejectedWith(e); + } + const returnPromise = promiseResolvedWith(returnResult); + return transformPromiseWith(returnPromise, iterResult => { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object'); + } + return undefined; + }); + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; +} +function ReadableStreamFromDefaultReader(reader) { + let stream; + const startAlgorithm = noop; + function pullAlgorithm() { + let readPromise; + try { + readPromise = reader.read(); + } + catch (e) { + return promiseRejectedWith(e); + } + return transformPromiseWith(readPromise, readResult => { + if (!typeIsObject(readResult)) { + throw new TypeError('The promise returned by the reader.read() method must fulfill with an object'); + } + if (readResult.done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + const value = readResult.value; + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + try { + return promiseResolvedWith(reader.cancel(reason)); + } + catch (e) { + return promiseRejectedWith(e); + } + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; +} + +function convertUnderlyingDefaultOrByteSource(source, context) { + assertDictionary(source, context); + const original = source; + const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; + const cancel = original === null || original === void 0 ? void 0 : original.cancel; + const pull = original === null || original === void 0 ? void 0 : original.pull; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + return { + autoAllocateChunkSize: autoAllocateChunkSize === undefined ? + undefined : + convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`), + cancel: cancel === undefined ? + undefined : + convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`), + pull: pull === undefined ? + undefined : + convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`), + start: start === undefined ? + undefined : + convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`), + type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`) + }; +} +function convertUnderlyingSourceCancelCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); +} +function convertUnderlyingSourcePullCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); +} +function convertUnderlyingSourceStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); +} +function convertReadableStreamType(type, context) { + type = `${type}`; + if (type !== 'bytes') { + throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`); + } + return type; +} + +function convertIteratorOptions(options, context) { + assertDictionary(options, context); + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + return { preventCancel: Boolean(preventCancel) }; +} + +function convertPipeOptions(options, context) { + assertDictionary(options, context); + const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort; + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + const preventClose = options === null || options === void 0 ? void 0 : options.preventClose; + const signal = options === null || options === void 0 ? void 0 : options.signal; + if (signal !== undefined) { + assertAbortSignal(signal, `${context} has member 'signal' that`); + } + return { + preventAbort: Boolean(preventAbort), + preventCancel: Boolean(preventCancel), + preventClose: Boolean(preventClose), + signal + }; +} +function assertAbortSignal(signal, context) { + if (!isAbortSignal(signal)) { + throw new TypeError(`${context} is not an AbortSignal.`); + } +} + +function convertReadableWritablePair(pair, context) { + assertDictionary(pair, context); + const readable = pair === null || pair === void 0 ? void 0 : pair.readable; + assertRequiredField(readable, 'readable', 'ReadableWritablePair'); + assertReadableStream(readable, `${context} has member 'readable' that`); + const writable = pair === null || pair === void 0 ? void 0 : pair.writable; + assertRequiredField(writable, 'writable', 'ReadableWritablePair'); + assertWritableStream(writable, `${context} has member 'writable' that`); + return { readable, writable }; +} + +/** + * A readable stream represents a source of data, from which you can read. + * + * @public + */ +class ReadableStream { + constructor(rawUnderlyingSource = {}, rawStrategy = {}) { + if (rawUnderlyingSource === undefined) { + rawUnderlyingSource = null; + } + else { + assertObject(rawUnderlyingSource, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter'); + InitializeReadableStream(this); + if (underlyingSource.type === 'bytes') { + if (strategy.size !== undefined) { + throw new RangeError('The strategy for a byte stream cannot have a size function'); + } + const highWaterMark = ExtractHighWaterMark(strategy, 0); + SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); + } + else { + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); + } + } + /** + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. + */ + get locked() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('locked'); + } + return IsReadableStreamLocked(this); + } + /** + * Cancels the stream, signaling a loss of interest in the stream by a consumer. + * + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} + * method, which might or might not use it. + */ + cancel(reason = undefined) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('cancel')); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader')); + } + return ReadableStreamCancel(this, reason); + } + getReader(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('getReader'); + } + const options = convertReaderOptions(rawOptions, 'First parameter'); + if (options.mode === undefined) { + return AcquireReadableStreamDefaultReader(this); + } + return AcquireReadableStreamBYOBReader(this); + } + pipeThrough(rawTransform, rawOptions = {}) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('pipeThrough'); + } + assertRequiredArgument(rawTransform, 1, 'pipeThrough'); + const transform = convertReadableWritablePair(rawTransform, 'First parameter'); + const options = convertPipeOptions(rawOptions, 'Second parameter'); + if (IsReadableStreamLocked(this)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream'); + } + if (IsWritableStreamLocked(transform.writable)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream'); + } + const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + setPromiseIsHandledToTrue(promise); + return transform.readable; + } + pipeTo(destination, rawOptions = {}) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('pipeTo')); + } + if (destination === undefined) { + return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`); + } + if (!IsWritableStream(destination)) { + return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)); + } + let options; + try { + options = convertPipeOptions(rawOptions, 'Second parameter'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')); + } + if (IsWritableStreamLocked(destination)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')); + } + return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + } + /** + * Tees this readable stream, returning a two-element array containing the two resulting branches as + * new {@link ReadableStream} instances. + * + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be + * propagated to the stream's underlying source. + * + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, + * this could allow interference between the two branches. + */ + tee() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('tee'); + } + const branches = ReadableStreamTee(this); + return CreateArrayFromList(branches); + } + values(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('values'); + } + const options = convertIteratorOptions(rawOptions, 'First parameter'); + return AcquireReadableStreamAsyncIterator(this, options.preventCancel); + } + [SymbolAsyncIterator](options) { + // Stub implementation, overridden below + return this.values(options); + } + /** + * Creates a new ReadableStream wrapping the provided iterable or async iterable. + * + * This can be used to adapt various kinds of objects into a readable stream, + * such as an array, an async generator, or a Node.js readable stream. + */ + static from(asyncIterable) { + return ReadableStreamFrom(asyncIterable); + } +} +Object.defineProperties(ReadableStream, { + from: { enumerable: true } +}); +Object.defineProperties(ReadableStream.prototype, { + cancel: { enumerable: true }, + getReader: { enumerable: true }, + pipeThrough: { enumerable: true }, + pipeTo: { enumerable: true }, + tee: { enumerable: true }, + values: { enumerable: true }, + locked: { enumerable: true } +}); +setFunctionName(ReadableStream.from, 'from'); +setFunctionName(ReadableStream.prototype.cancel, 'cancel'); +setFunctionName(ReadableStream.prototype.getReader, 'getReader'); +setFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough'); +setFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo'); +setFunctionName(ReadableStream.prototype.tee, 'tee'); +setFunctionName(ReadableStream.prototype.values, 'values'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, { + value: 'ReadableStream', + configurable: true + }); +} +Object.defineProperty(ReadableStream.prototype, SymbolAsyncIterator, { + value: ReadableStream.prototype.values, + writable: true, + configurable: true +}); +// Abstract operations for the ReadableStream. +// Throws if and only if startAlgorithm throws. +function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableStreamDefaultController.prototype); + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + return stream; +} +// Throws if and only if startAlgorithm throws. +function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableByteStreamController.prototype); + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined); + return stream; +} +function InitializeReadableStream(stream) { + stream._state = 'readable'; + stream._reader = undefined; + stream._storedError = undefined; + stream._disturbed = false; +} +function IsReadableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) { + return false; + } + return x instanceof ReadableStream; +} +function IsReadableStreamLocked(stream) { + if (stream._reader === undefined) { + return false; + } + return true; +} +// ReadableStream API exposed for controllers. +function ReadableStreamCancel(stream, reason) { + stream._disturbed = true; + if (stream._state === 'closed') { + return promiseResolvedWith(undefined); + } + if (stream._state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + ReadableStreamClose(stream); + const reader = stream._reader; + if (reader !== undefined && IsReadableStreamBYOBReader(reader)) { + const readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._closeSteps(undefined); + }); + } + const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); + return transformPromiseWith(sourceCancelPromise, noop); +} +function ReadableStreamClose(stream) { + stream._state = 'closed'; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseResolve(reader); + if (IsReadableStreamDefaultReader(reader)) { + const readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(readRequest => { + readRequest._closeSteps(); + }); + } +} +function ReadableStreamError(stream, e) { + stream._state = 'errored'; + stream._storedError = e; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseReject(reader, e); + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamDefaultReaderErrorReadRequests(reader, e); + } + else { + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); + } +} +// Helper functions for the ReadableStream. +function streamBrandCheckException$1(name) { + return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`); +} + +function convertQueuingStrategyInit(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit'); + return { + highWaterMark: convertUnrestrictedDouble(highWaterMark) + }; +} + +// The size function must not have a prototype property nor be a constructor +const byteLengthSizeFunction = (chunk) => { + return chunk.byteLength; +}; +setFunctionName(byteLengthSizeFunction, 'size'); +/** + * A queuing strategy that counts the number of bytes in each chunk. + * + * @public + */ +class ByteLengthQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('highWaterMark'); + } + return this._byteLengthQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by returning the value of its `byteLength` property. + */ + get size() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('size'); + } + return byteLengthSizeFunction; + } +} +Object.defineProperties(ByteLengthQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } +}); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, { + value: 'ByteLengthQueuingStrategy', + configurable: true + }); +} +// Helper functions for the ByteLengthQueuingStrategy. +function byteLengthBrandCheckException(name) { + return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`); +} +function IsByteLengthQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof ByteLengthQueuingStrategy; +} + +// The size function must not have a prototype property nor be a constructor +const countSizeFunction = () => { + return 1; +}; +setFunctionName(countSizeFunction, 'size'); +/** + * A queuing strategy that counts the number of chunks. + * + * @public + */ +class CountQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'CountQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._countQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('highWaterMark'); + } + return this._countQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by always returning 1. + * This ensures that the total queue size is a count of the number of chunks in the queue. + */ + get size() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('size'); + } + return countSizeFunction; + } +} +Object.defineProperties(CountQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } +}); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, { + value: 'CountQueuingStrategy', + configurable: true + }); +} +// Helper functions for the CountQueuingStrategy. +function countBrandCheckException(name) { + return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`); +} +function IsCountQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof CountQueuingStrategy; +} + +function convertTransformer(original, context) { + assertDictionary(original, context); + const cancel = original === null || original === void 0 ? void 0 : original.cancel; + const flush = original === null || original === void 0 ? void 0 : original.flush; + const readableType = original === null || original === void 0 ? void 0 : original.readableType; + const start = original === null || original === void 0 ? void 0 : original.start; + const transform = original === null || original === void 0 ? void 0 : original.transform; + const writableType = original === null || original === void 0 ? void 0 : original.writableType; + return { + cancel: cancel === undefined ? + undefined : + convertTransformerCancelCallback(cancel, original, `${context} has member 'cancel' that`), + flush: flush === undefined ? + undefined : + convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`), + readableType, + start: start === undefined ? + undefined : + convertTransformerStartCallback(start, original, `${context} has member 'start' that`), + transform: transform === undefined ? + undefined : + convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`), + writableType + }; +} +function convertTransformerFlushCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); +} +function convertTransformerStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); +} +function convertTransformerTransformCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); +} +function convertTransformerCancelCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); +} + +// Class TransformStream +/** + * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, + * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. + * In a manner specific to the transform stream in question, writes to the writable side result in new data being + * made available for reading from the readable side. + * + * @public + */ +class TransformStream { + constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) { + if (rawTransformer === undefined) { + rawTransformer = null; + } + const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter'); + const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter'); + const transformer = convertTransformer(rawTransformer, 'First parameter'); + if (transformer.readableType !== undefined) { + throw new RangeError('Invalid readableType specified'); + } + if (transformer.writableType !== undefined) { + throw new RangeError('Invalid writableType specified'); + } + const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); + const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); + const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); + const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); + let startPromise_resolve; + const startPromise = newPromise(resolve => { + startPromise_resolve = resolve; + }); + InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); + if (transformer.start !== undefined) { + startPromise_resolve(transformer.start(this._transformStreamController)); + } + else { + startPromise_resolve(undefined); + } + } + /** + * The readable side of the transform stream. + */ + get readable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('readable'); + } + return this._readable; + } + /** + * The writable side of the transform stream. + */ + get writable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('writable'); + } + return this._writable; + } +} +Object.defineProperties(TransformStream.prototype, { + readable: { enumerable: true }, + writable: { enumerable: true } +}); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, { + value: 'TransformStream', + configurable: true + }); +} +function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { + function startAlgorithm() { + return startPromise; + } + function writeAlgorithm(chunk) { + return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); + } + function abortAlgorithm(reason) { + return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); + } + function closeAlgorithm() { + return TransformStreamDefaultSinkCloseAlgorithm(stream); + } + stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); + function pullAlgorithm() { + return TransformStreamDefaultSourcePullAlgorithm(stream); + } + function cancelAlgorithm(reason) { + return TransformStreamDefaultSourceCancelAlgorithm(stream, reason); + } + stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure. + stream._backpressure = undefined; + stream._backpressureChangePromise = undefined; + stream._backpressureChangePromise_resolve = undefined; + TransformStreamSetBackpressure(stream, true); + stream._transformStreamController = undefined; +} +function IsTransformStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) { + return false; + } + return x instanceof TransformStream; +} +// This is a no-op if both sides are already errored. +function TransformStreamError(stream, e) { + ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e); + TransformStreamErrorWritableAndUnblockWrite(stream, e); +} +function TransformStreamErrorWritableAndUnblockWrite(stream, e) { + TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); + WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e); + TransformStreamUnblockWrite(stream); +} +function TransformStreamUnblockWrite(stream) { + if (stream._backpressure) { + // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure() + // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time + // _backpressure is set. + TransformStreamSetBackpressure(stream, false); + } +} +function TransformStreamSetBackpressure(stream, backpressure) { + // Passes also when called during construction. + if (stream._backpressureChangePromise !== undefined) { + stream._backpressureChangePromise_resolve(); + } + stream._backpressureChangePromise = newPromise(resolve => { + stream._backpressureChangePromise_resolve = resolve; + }); + stream._backpressure = backpressure; +} +// Class TransformStreamDefaultController +/** + * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. + * + * @public + */ +class TransformStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. + */ + get desiredSize() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('desiredSize'); + } + const readableController = this._controlledTransformStream._readable._readableStreamController; + return ReadableStreamDefaultControllerGetDesiredSize(readableController); + } + enqueue(chunk = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('enqueue'); + } + TransformStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors both the readable side and the writable side of the controlled transform stream, making all future + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. + */ + error(reason = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('error'); + } + TransformStreamDefaultControllerError(this, reason); + } + /** + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the + * transformer only needs to consume a portion of the chunks written to the writable side. + */ + terminate() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('terminate'); + } + TransformStreamDefaultControllerTerminate(this); + } +} +Object.defineProperties(TransformStreamDefaultController.prototype, { + enqueue: { enumerable: true }, + error: { enumerable: true }, + terminate: { enumerable: true }, + desiredSize: { enumerable: true } +}); +setFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue'); +setFunctionName(TransformStreamDefaultController.prototype.error, 'error'); +setFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate'); +if (typeof Symbol.toStringTag === 'symbol') { + Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, { + value: 'TransformStreamDefaultController', + configurable: true + }); +} +// Transform Stream Default Controller Abstract Operations +function IsTransformStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) { + return false; + } + return x instanceof TransformStreamDefaultController; +} +function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm) { + controller._controlledTransformStream = stream; + stream._transformStreamController = controller; + controller._transformAlgorithm = transformAlgorithm; + controller._flushAlgorithm = flushAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._finishPromise = undefined; + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; +} +function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { + const controller = Object.create(TransformStreamDefaultController.prototype); + let transformAlgorithm; + let flushAlgorithm; + let cancelAlgorithm; + if (transformer.transform !== undefined) { + transformAlgorithm = chunk => transformer.transform(chunk, controller); + } + else { + transformAlgorithm = chunk => { + try { + TransformStreamDefaultControllerEnqueue(controller, chunk); + return promiseResolvedWith(undefined); + } + catch (transformResultE) { + return promiseRejectedWith(transformResultE); + } + }; + } + if (transformer.flush !== undefined) { + flushAlgorithm = () => transformer.flush(controller); + } + else { + flushAlgorithm = () => promiseResolvedWith(undefined); + } + if (transformer.cancel !== undefined) { + cancelAlgorithm = reason => transformer.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm); +} +function TransformStreamDefaultControllerClearAlgorithms(controller) { + controller._transformAlgorithm = undefined; + controller._flushAlgorithm = undefined; + controller._cancelAlgorithm = undefined; +} +function TransformStreamDefaultControllerEnqueue(controller, chunk) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { + throw new TypeError('Readable side is not in a state that permits enqueue'); + } + // We throttle transform invocations based on the backpressure of the ReadableStream, but we still + // accept TransformStreamDefaultControllerEnqueue() calls. + try { + ReadableStreamDefaultControllerEnqueue(readableController, chunk); + } + catch (e) { + // This happens when readableStrategy.size() throws. + TransformStreamErrorWritableAndUnblockWrite(stream, e); + throw stream._readable._storedError; + } + const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); + if (backpressure !== stream._backpressure) { + TransformStreamSetBackpressure(stream, true); + } +} +function TransformStreamDefaultControllerError(controller, e) { + TransformStreamError(controller._controlledTransformStream, e); +} +function TransformStreamDefaultControllerPerformTransform(controller, chunk) { + const transformPromise = controller._transformAlgorithm(chunk); + return transformPromiseWith(transformPromise, undefined, r => { + TransformStreamError(controller._controlledTransformStream, r); + throw r; + }); +} +function TransformStreamDefaultControllerTerminate(controller) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + ReadableStreamDefaultControllerClose(readableController); + const error = new TypeError('TransformStream terminated'); + TransformStreamErrorWritableAndUnblockWrite(stream, error); +} +// TransformStreamDefaultSink Algorithms +function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { + const controller = stream._transformStreamController; + if (stream._backpressure) { + const backpressureChangePromise = stream._backpressureChangePromise; + return transformPromiseWith(backpressureChangePromise, () => { + const writable = stream._writable; + const state = writable._state; + if (state === 'erroring') { + throw writable._storedError; + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + }); + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); +} +function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + const readable = stream._readable; + // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally, + // we don't run the _cancelAlgorithm again. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, () => { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerError(readable._readableStreamController, reason); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; +} +function TransformStreamDefaultSinkCloseAlgorithm(stream) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + const readable = stream._readable; + // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally, + // we don't also run the _cancelAlgorithm. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const flushPromise = controller._flushAlgorithm(); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(flushPromise, () => { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerClose(readable._readableStreamController); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; +} +// TransformStreamDefaultSource Algorithms +function TransformStreamDefaultSourcePullAlgorithm(stream) { + // Invariant. Enforced by the promises returned by start() and pull(). + TransformStreamSetBackpressure(stream, false); + // Prevent the next pull() call until there is backpressure. + return stream._backpressureChangePromise; +} +function TransformStreamDefaultSourceCancelAlgorithm(stream, reason) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._writable cannot change after construction, so caching it across a call to user code is safe. + const writable = stream._writable; + // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or + // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the + // _flushAlgorithm. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, () => { + if (writable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, writable._storedError); + } + else { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; +} +// Helper functions for the TransformStreamDefaultController. +function defaultControllerBrandCheckException(name) { + return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`); +} +function defaultControllerFinishPromiseResolve(controller) { + if (controller._finishPromise_resolve === undefined) { + return; + } + controller._finishPromise_resolve(); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; +} +function defaultControllerFinishPromiseReject(controller, reason) { + if (controller._finishPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(controller._finishPromise); + controller._finishPromise_reject(reason); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; +} +// Helper functions for the TransformStream. +function streamBrandCheckException(name) { + return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`); +} + +export { ByteLengthQueuingStrategy, CountQueuingStrategy, ReadableByteStreamController, ReadableStream, ReadableStreamBYOBReader, ReadableStreamBYOBRequest, ReadableStreamDefaultController, ReadableStreamDefaultReader, TransformStream, TransformStreamDefaultController, WritableStream, WritableStreamDefaultController, WritableStreamDefaultWriter }; +//# sourceMappingURL=ponyfill.es6.mjs.map diff --git a/backend/node_modules/web-streams-polyfill/dist/ponyfill.es6.mjs.map b/backend/node_modules/web-streams-polyfill/dist/ponyfill.es6.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..929200b5365c8f884f1d1ba5dd236447acb324fc --- /dev/null +++ b/backend/node_modules/web-streams-polyfill/dist/ponyfill.es6.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"ponyfill.es6.mjs","sources":["../src/utils.ts","../src/lib/helpers/miscellaneous.ts","../src/lib/helpers/webidl.ts","../src/lib/simple-queue.ts","../src/lib/abstract-ops/internal-methods.ts","../src/lib/readable-stream/generic-reader.ts","../src/stub/number-isfinite.ts","../src/stub/math-trunc.ts","../src/lib/validators/basic.ts","../src/lib/validators/readable-stream.ts","../src/lib/readable-stream/default-reader.ts","../node_modules/tslib/tslib.es6.js","../src/lib/abstract-ops/ecmascript.ts","../src/target/es5/stub/async-iterator-prototype.ts","../src/lib/readable-stream/async-iterator.ts","../src/stub/number-isnan.ts","../src/lib/abstract-ops/miscellaneous.ts","../src/lib/abstract-ops/queue-with-sizes.ts","../src/lib/helpers/array-buffer-view.ts","../src/lib/readable-stream/byte-stream-controller.ts","../src/lib/validators/reader-options.ts","../src/lib/readable-stream/byob-reader.ts","../src/lib/abstract-ops/queuing-strategy.ts","../src/lib/validators/queuing-strategy.ts","../src/lib/validators/underlying-sink.ts","../src/lib/validators/writable-stream.ts","../src/lib/abort-signal.ts","../src/lib/writable-stream.ts","../src/globals.ts","../src/stub/dom-exception.ts","../src/lib/readable-stream/pipe.ts","../src/lib/readable-stream/default-controller.ts","../src/lib/readable-stream/tee.ts","../src/lib/readable-stream/readable-stream-like.ts","../src/lib/readable-stream/from.ts","../src/lib/validators/underlying-source.ts","../src/lib/validators/iterator-options.ts","../src/lib/validators/pipe-options.ts","../src/lib/validators/readable-writable-pair.ts","../src/lib/readable-stream.ts","../src/lib/validators/queuing-strategy-init.ts","../src/lib/byte-length-queuing-strategy.ts","../src/lib/count-queuing-strategy.ts","../src/lib/validators/transformer.ts","../src/lib/transform-stream.ts"],"sourcesContent":["export function noop(): undefined {\n return undefined;\n}\n","import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n\nexport function setFunctionName(fn: Function, name: string): void {\n try {\n Object.defineProperty(fn, 'name', {\n value: name,\n configurable: true\n });\n } catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n }\n}\n","import { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\n// https://webidl.spec.whatwg.org/#a-new-promise\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-resolved-with\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return newPromise(resolve => resolve(value));\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-rejected-with\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\n// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned\n// from that handler. To prevent this, return null instead of void from all handlers.\n// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => null | PromiseLike,\n onRejected?: (reason: any) => null | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => null | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => null | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nlet _queueMicrotask: (callback: () => void) => void = callback => {\n if (typeof queueMicrotask === 'function') {\n _queueMicrotask = queueMicrotask;\n } else {\n const resolvedPromise = promiseResolvedWith(undefined);\n _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb);\n }\n return _queueMicrotask(callback);\n};\n\nexport { _queueMicrotask as queueMicrotask };\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n","import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n","export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\nexport const ReleaseSteps = Symbol('[[ReleaseSteps]]');\n","import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, type ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\nimport { ReleaseSteps } from '../abstract-ops/internal-methods';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n assert(stream._reader === reader);\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n stream._readableStreamController[ReleaseSteps]();\n\n stream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n","import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n","import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamDefaultReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamDefaultReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\nexport function ReadableStreamDefaultReaderRelease(reader: ReadableStreamDefaultReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n}\n\nexport function ReadableStreamDefaultReaderErrorReadRequests(reader: ReadableStreamDefaultReader, e: any) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n","/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise, SuppressedError, Symbol */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\r\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\r\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\r\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\r\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\r\n var _, done = false;\r\n for (var i = decorators.length - 1; i >= 0; i--) {\r\n var context = {};\r\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\r\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\r\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\r\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\r\n if (kind === \"accessor\") {\r\n if (result === void 0) continue;\r\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\r\n if (_ = accept(result.get)) descriptor.get = _;\r\n if (_ = accept(result.set)) descriptor.set = _;\r\n if (_ = accept(result.init)) initializers.unshift(_);\r\n }\r\n else if (_ = accept(result)) {\r\n if (kind === \"field\") initializers.unshift(_);\r\n else descriptor[key] = _;\r\n }\r\n }\r\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\r\n done = true;\r\n};\r\n\r\nexport function __runInitializers(thisArg, initializers, value) {\r\n var useValue = arguments.length > 2;\r\n for (var i = 0; i < initializers.length; i++) {\r\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\r\n }\r\n return useValue ? value : void 0;\r\n};\r\n\r\nexport function __propKey(x) {\r\n return typeof x === \"symbol\" ? x : \"\".concat(x);\r\n};\r\n\r\nexport function __setFunctionName(f, name, prefix) {\r\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\r\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\r\n};\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n var desc = Object.getOwnPropertyDescriptor(m, k);\r\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\r\n desc = { enumerable: true, get: function() { return m[k]; } };\r\n }\r\n Object.defineProperty(o, k2, desc);\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\nexport function __classPrivateFieldIn(state, receiver) {\r\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\r\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\r\n}\r\n\r\nexport function __addDisposableResource(env, value, async) {\r\n if (value !== null && value !== void 0) {\r\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\r\n var dispose;\r\n if (async) {\r\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\r\n dispose = value[Symbol.asyncDispose];\r\n }\r\n if (dispose === void 0) {\r\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\r\n dispose = value[Symbol.dispose];\r\n }\r\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\r\n env.stack.push({ value: value, dispose: dispose, async: async });\r\n }\r\n else if (async) {\r\n env.stack.push({ async: true });\r\n }\r\n return value;\r\n}\r\n\r\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n};\r\n\r\nexport function __disposeResources(env) {\r\n function fail(e) {\r\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\r\n env.hasError = true;\r\n }\r\n function next() {\r\n while (env.stack.length) {\r\n var rec = env.stack.pop();\r\n try {\r\n var result = rec.dispose && rec.dispose.call(rec.value);\r\n if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\r\n }\r\n catch (e) {\r\n fail(e);\r\n }\r\n }\r\n if (env.hasError) throw env.error;\r\n }\r\n return next();\r\n}\r\n\r\nexport default {\r\n __extends: __extends,\r\n __assign: __assign,\r\n __rest: __rest,\r\n __decorate: __decorate,\r\n __param: __param,\r\n __metadata: __metadata,\r\n __awaiter: __awaiter,\r\n __generator: __generator,\r\n __createBinding: __createBinding,\r\n __exportStar: __exportStar,\r\n __values: __values,\r\n __read: __read,\r\n __spread: __spread,\r\n __spreadArrays: __spreadArrays,\r\n __spreadArray: __spreadArray,\r\n __await: __await,\r\n __asyncGenerator: __asyncGenerator,\r\n __asyncDelegator: __asyncDelegator,\r\n __asyncValues: __asyncValues,\r\n __makeTemplateObject: __makeTemplateObject,\r\n __importStar: __importStar,\r\n __importDefault: __importDefault,\r\n __classPrivateFieldGet: __classPrivateFieldGet,\r\n __classPrivateFieldSet: __classPrivateFieldSet,\r\n __classPrivateFieldIn: __classPrivateFieldIn,\r\n __addDisposableResource: __addDisposableResource,\r\n __disposeResources: __disposeResources,\r\n};\r\n","import { reflectCall } from 'lib/helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport assert from '../../stub/assert';\n\ndeclare global {\n interface ArrayBuffer {\n readonly detached: boolean;\n\n transfer(): ArrayBuffer;\n }\n\n function structuredClone(value: T, options: { transfer: ArrayBuffer[] }): T;\n}\n\nexport function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\nexport let TransferArrayBuffer = (O: ArrayBuffer): ArrayBuffer => {\n if (typeof O.transfer === 'function') {\n TransferArrayBuffer = buffer => buffer.transfer();\n } else if (typeof structuredClone === 'function') {\n TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] });\n } else {\n // Not implemented correctly\n TransferArrayBuffer = buffer => buffer;\n }\n return TransferArrayBuffer(O);\n};\n\nexport function CanTransferArrayBuffer(O: ArrayBuffer): boolean {\n return !IsDetachedBuffer(O);\n}\n\nexport let IsDetachedBuffer = (O: ArrayBuffer): boolean => {\n if (typeof O.detached === 'boolean') {\n IsDetachedBuffer = buffer => buffer.detached;\n } else {\n // Not implemented correctly\n IsDetachedBuffer = buffer => buffer.byteLength === 0;\n }\n return IsDetachedBuffer(O);\n};\n\nexport function ArrayBufferSlice(buffer: ArrayBuffer, begin: number, end: number): ArrayBuffer {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n\nexport type MethodName = {\n [P in keyof T]: T[P] extends Function | undefined ? P : never;\n}[keyof T];\n\nexport function GetMethod>(receiver: T, prop: K): T[K] | undefined {\n const func = receiver[prop];\n if (func === undefined || func === null) {\n return undefined;\n }\n if (typeof func !== 'function') {\n throw new TypeError(`${String(prop)} is not a function`);\n }\n return func;\n}\n\nexport interface SyncIteratorRecord {\n iterator: Iterator,\n nextMethod: Iterator['next'],\n done: boolean;\n}\n\nexport interface AsyncIteratorRecord {\n iterator: AsyncIterator,\n nextMethod: AsyncIterator['next'],\n done: boolean;\n}\n\nexport type SyncOrAsyncIteratorRecord = SyncIteratorRecord | AsyncIteratorRecord;\n\nexport function CreateAsyncFromSyncIterator(syncIteratorRecord: SyncIteratorRecord): AsyncIteratorRecord {\n // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%,\n // we use yield* inside an async generator function to achieve the same result.\n\n // Wrap the sync iterator inside a sync iterable, so we can use it with yield*.\n const syncIterable = {\n [Symbol.iterator]: () => syncIteratorRecord.iterator\n };\n // Create an async generator function and immediately invoke it.\n const asyncIterator = (async function* () {\n return yield* syncIterable;\n }());\n // Return as an async iterator record.\n const nextMethod = asyncIterator.next;\n return { iterator: asyncIterator, nextMethod, done: false };\n}\n\n// Aligns with core-js/modules/es.symbol.async-iterator.js\nexport const SymbolAsyncIterator: (typeof Symbol)['asyncIterator'] =\n Symbol.asyncIterator ??\n Symbol.for?.('Symbol.asyncIterator') ??\n '@@asyncIterator';\n\nexport type SyncOrAsyncIterable = Iterable | AsyncIterable;\nexport type SyncOrAsyncIteratorMethod = () => (Iterator | AsyncIterator);\n\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint: 'async',\n method?: SyncOrAsyncIteratorMethod\n): AsyncIteratorRecord;\nfunction GetIterator(\n obj: Iterable,\n hint: 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncIteratorRecord;\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint = 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncOrAsyncIteratorRecord {\n assert(hint === 'sync' || hint === 'async');\n if (method === undefined) {\n if (hint === 'async') {\n method = GetMethod(obj as AsyncIterable, SymbolAsyncIterator);\n if (method === undefined) {\n const syncMethod = GetMethod(obj as Iterable, Symbol.iterator);\n const syncIteratorRecord = GetIterator(obj as Iterable, 'sync', syncMethod);\n return CreateAsyncFromSyncIterator(syncIteratorRecord);\n }\n } else {\n method = GetMethod(obj as Iterable, Symbol.iterator);\n }\n }\n if (method === undefined) {\n throw new TypeError('The object is not iterable');\n }\n const iterator = reflectCall(method, obj, []);\n if (!typeIsObject(iterator)) {\n throw new TypeError('The iterator method must return an object');\n }\n const nextMethod = iterator.next;\n return { iterator, nextMethod, done: false } as SyncOrAsyncIteratorRecord;\n}\n\nexport { GetIterator };\n\nexport function IteratorNext(iteratorRecord: AsyncIteratorRecord): Promise> {\n const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []);\n if (!typeIsObject(result)) {\n throw new TypeError('The iterator.next() method must return an object');\n }\n return result;\n}\n\nexport function IteratorComplete(\n iterResult: IteratorResult\n): iterResult is IteratorReturnResult {\n assert(typeIsObject(iterResult));\n return Boolean(iterResult.done);\n}\n\nexport function IteratorValue(iterResult: IteratorYieldResult): T {\n assert(typeIsObject(iterResult));\n return iterResult.value;\n}\n","/// \n\nimport { SymbolAsyncIterator } from '../../../lib/abstract-ops/ecmascript';\n\n// We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it.\nexport const AsyncIteratorPrototype: AsyncIterable = {\n // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( )\n // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator\n [SymbolAsyncIterator](this: AsyncIterator) {\n return this;\n }\n};\nObject.defineProperty(AsyncIteratorPrototype, SymbolAsyncIterator, { enumerable: false });\n","/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadableStreamDefaultReadResult,\n type ReadRequest\n} from './default-reader';\nimport { ReadableStreamReaderGenericCancel, ReadableStreamReaderGenericRelease } from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterableIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ninterface ReadableStreamAsyncIteratorInstance extends ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nObject.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n","import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: NonShared): NonShared {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer) as NonShared;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n","export type TypedArray =\n | Int8Array\n | Uint8Array\n | Uint8ClampedArray\n | Int16Array\n | Uint16Array\n | Int32Array\n | Uint32Array\n | Float32Array\n | Float64Array;\n\nexport type NonShared = T & {\n buffer: ArrayBuffer;\n}\n\nexport interface ArrayBufferViewConstructor {\n new(buffer: ArrayBuffer, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n}\n\nexport interface TypedArrayConstructor extends ArrayBufferViewConstructor {\n readonly BYTES_PER_ELEMENT: number;\n}\n\nexport type DataViewConstructor = ArrayBufferViewConstructor;\n\nfunction isDataViewConstructor(ctor: Function): ctor is DataViewConstructor {\n return ctor === DataView;\n}\n\nexport function isDataView(view: ArrayBufferView): view is DataView {\n return isDataViewConstructor(view.constructor);\n}\n\nexport function arrayBufferViewElementSize(ctor: ArrayBufferViewConstructor): number {\n if (isDataViewConstructor(ctor)) {\n return 1;\n }\n return (ctor as unknown as TypedArrayConstructor).BYTES_PER_ELEMENT;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n IsReadableStreamDefaultReader,\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n type ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n type ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n type ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport type { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\nimport {\n type ArrayBufferViewConstructor,\n arrayBufferViewElementSize,\n type NonShared,\n type TypedArrayConstructor\n} from '../helpers/array-buffer-view';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: NonShared | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: NonShared): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond');\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBuffer;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor = NonShared> =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: TypedArrayConstructor;\n readerType: 'default' | 'none';\n}\n\ninterface BYOBPullIntoDescriptor = NonShared> {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob' | 'none';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: NonShared): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest>): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n minimumFill: 1,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n if (this._pendingPullIntos.length > 0) {\n const firstPullInto = this._pendingPullIntos.peek();\n firstPullInto.readerType = 'none';\n\n this._pendingPullIntos = new SimpleQueue();\n this._pendingPullIntos.push(firstPullInto);\n }\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableByteStreamController.prototype.close, 'close');\nsetFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableByteStreamController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor>(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n assert(pullIntoDescriptor.readerType !== 'none');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as NonShared, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor>(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n let clonedChunk;\n try {\n clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength);\n } catch (cloneE) {\n ReadableByteStreamControllerError(controller, cloneE);\n throw cloneE;\n }\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength);\n}\n\nfunction ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.readerType === 'none');\n if (firstDescriptor.bytesFilled > 0) {\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n firstDescriptor.buffer,\n firstDescriptor.byteOffset,\n firstDescriptor.bytesFilled\n );\n }\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize;\n const maxAlignedBytes = maxBytesFilled - remainderBytes;\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n assert(pullIntoDescriptor.readerType !== 'none');\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nfunction ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller: ReadableByteStreamController) {\n const reader = controller._controlledReadableByteStream._reader;\n assert(IsReadableStreamDefaultReader(reader));\n while (reader._readRequests.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n const readRequest = reader._readRequests.shift();\n ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest);\n }\n}\n\nexport function ReadableByteStreamControllerPullInto>(\n controller: ReadableByteStreamController,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n const elementSize = arrayBufferViewElementSize(ctor);\n\n const { byteOffset, byteLength } = view;\n\n const minimumFill = min * elementSize;\n assert(minimumFill >= elementSize && minimumFill <= byteLength);\n assert(minimumFill % elementSize === 0);\n\n let buffer: ArrayBuffer;\n try {\n buffer = TransferArrayBuffer(view.buffer);\n } catch (e) {\n readIntoRequest._errorSteps(e);\n return;\n }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset,\n byteLength,\n bytesFilled: 0,\n minimumFill,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled % firstDescriptor.elementSize === 0);\n\n if (firstDescriptor.readerType === 'none') {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n return;\n }\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) {\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n pullIntoDescriptor.buffer,\n end - remainderSize,\n remainderSize\n );\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(\n controller: ReadableByteStreamController,\n chunk: NonShared\n) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const { buffer, byteOffset, byteLength } = chunk;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n if (firstPendingPullInto.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto);\n }\n }\n\n if (ReadableStreamHasDefaultReader(stream)) {\n ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller);\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView as NonShared, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerFillReadRequestFromQueue(\n controller: ReadableByteStreamController,\n readRequest: ReadRequest>\n) {\n assert(controller._queueTotalSize > 0);\n\n const entry = controller._queue.shift();\n controller._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n readRequest._chunkSteps(view as NonShared);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view as NonShared);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: NonShared) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: NonShared) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n","import { assertDictionary, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n\nexport function convertByobReadOptions(\n options: ReadableStreamBYOBReaderReadOptions | null | undefined,\n context: string\n): ValidatedReadableStreamBYOBReaderReadOptions {\n assertDictionary(options, context);\n const min = options?.min ?? 1;\n return {\n min: convertUnsignedLongLongWithEnforceRange(\n min,\n `${context} has member 'min' that`\n )\n };\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, type ReadableByteStream, type ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from './reader-options';\nimport { convertByobReadOptions } from '../validators/reader-options';\nimport { isDataView, type NonShared, type TypedArray } from '../helpers/array-buffer-view';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream as ReadableStream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest>(\n stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest\n): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest> {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(\n view: T,\n options?: ReadableStreamBYOBReaderReadOptions\n ): Promise>;\n read>(\n view: T,\n rawOptions: ReadableStreamBYOBReaderReadOptions | null | undefined = {}\n ): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n let options: ValidatedReadableStreamBYOBReaderReadOptions;\n try {\n options = convertByobReadOptions(rawOptions, 'options');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const min = options.min;\n if (min === 0) {\n return promiseRejectedWith(new TypeError('options.min must be greater than 0'));\n }\n if (!isDataView(view)) {\n if (min > (view as unknown as TypedArray).length) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s length'));\n }\n } else if (min > view.byteLength) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s byteLength'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamBYOBReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamBYOBReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead>(\n reader: ReadableStreamBYOBReader,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n min,\n readIntoRequest\n );\n }\n}\n\nexport function ReadableStreamBYOBReaderRelease(reader: ReadableStreamBYOBReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n}\n\nexport function ReadableStreamBYOBReaderErrorReadIntoRequests(reader: ReadableStreamBYOBReader, e: any) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n","/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * If aborted, returns the reason for aborting.\n */\n readonly reason?: any;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(reason?: any): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n type QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { type AbortController, type AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(WritableStream.prototype.abort, 'abort');\nsetFunctionName(WritableStream.prototype.close, 'close');\nsetFunctionName(WritableStream.prototype.getWriter, 'getWriter');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight\n};\n\nexport type {\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort(reason);\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nsetFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort');\nsetFunctionName(WritableStreamDefaultWriter.prototype.close, 'close');\nsetFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock');\nsetFunctionName(WritableStreamDefaultWriter.prototype.write, 'write');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n return null;\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let writeAlgorithm: (chunk: W) => Promise;\n let closeAlgorithm: () => Promise;\n let abortAlgorithm: (reason: any) => Promise;\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n } else {\n writeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n } else {\n closeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n } else {\n abortAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n return null;\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n","/// \n\nfunction getGlobals(): typeof globalThis | undefined {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n } else if (typeof self !== 'undefined') {\n return self;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n","/// \nimport { globals } from '../globals';\nimport { setFunctionName } from '../lib/helpers/miscellaneous';\n\ninterface DOMException extends Error {\n name: string;\n message: string;\n}\n\ntype DOMExceptionConstructor = new (message?: string, name?: string) => DOMException;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n if ((ctor as DOMExceptionConstructor).name !== 'DOMException') {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Support:\n * - Web browsers\n * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87)\n */\nfunction getFromGlobal(): DOMExceptionConstructor | undefined {\n const ctor = globals?.DOMException;\n return isDOMExceptionConstructor(ctor) ? ctor : undefined;\n}\n\n/**\n * Support:\n * - All platforms\n */\nfunction createPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line @typescript-eslint/no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n setFunctionName(ctor, 'DOMException');\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nconst DOMException: DOMExceptionConstructor = getFromGlobal() || createPolyfill();\n\nexport { DOMException };\n","import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n return null;\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => null) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => null) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest(): null {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n return null;\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any): null {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n\n return null;\n }\n });\n}\n","import type { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, type QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n type ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport type { ValidatedUnderlyingSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n // Do nothing.\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultController.prototype.close, 'close');\nsetFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableStreamDefaultController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n","import {\n CreateReadableByteStream,\n CreateReadableStream,\n type DefaultReadableStream,\n IsReadableStream,\n type ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n type ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n type ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(\n stream: ReadableStream,\n cloneForBranch2: boolean\n): [DefaultReadableStream, DefaultReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: DefaultReadableStream;\n let branch2: DefaultReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader> = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader>) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return null;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: NonShared, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader>(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n","import { typeIsObject } from '../helpers/miscellaneous';\nimport type { ReadableStreamDefaultReadResult } from './default-reader';\n\n/**\n * A common interface for a `ReadadableStream` implementation.\n *\n * @public\n */\nexport interface ReadableStreamLike {\n readonly locked: boolean;\n\n getReader(): ReadableStreamDefaultReaderLike;\n}\n\n/**\n * A common interface for a `ReadableStreamDefaultReader` implementation.\n *\n * @public\n */\nexport interface ReadableStreamDefaultReaderLike {\n readonly closed: Promise;\n\n cancel(reason?: any): Promise;\n\n read(): Promise>;\n\n releaseLock(): void;\n}\n\nexport function isReadableStreamLike(stream: unknown): stream is ReadableStreamLike {\n return typeIsObject(stream) && typeof (stream as ReadableStreamLike).getReader !== 'undefined';\n}\n","import { CreateReadableStream, type DefaultReadableStream } from '../readable-stream';\nimport {\n isReadableStreamLike,\n type ReadableStreamDefaultReaderLike,\n type ReadableStreamLike\n} from './readable-stream-like';\nimport { ReadableStreamDefaultControllerClose, ReadableStreamDefaultControllerEnqueue } from './default-controller';\nimport { GetIterator, GetMethod, IteratorComplete, IteratorNext, IteratorValue } from '../abstract-ops/ecmascript';\nimport { promiseRejectedWith, promiseResolvedWith, reflectCall, transformPromiseWith } from '../helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { noop } from '../../utils';\n\nexport function ReadableStreamFrom(\n source: Iterable | AsyncIterable | ReadableStreamLike\n): DefaultReadableStream {\n if (isReadableStreamLike(source)) {\n return ReadableStreamFromDefaultReader(source.getReader());\n }\n return ReadableStreamFromIterable(source);\n}\n\nexport function ReadableStreamFromIterable(asyncIterable: Iterable | AsyncIterable): DefaultReadableStream {\n let stream: DefaultReadableStream;\n const iteratorRecord = GetIterator(asyncIterable, 'async');\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let nextResult;\n try {\n nextResult = IteratorNext(iteratorRecord);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const nextPromise = promiseResolvedWith(nextResult);\n return transformPromiseWith(nextPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object');\n }\n const done = IteratorComplete(iterResult);\n if (done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = IteratorValue(iterResult);\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n const iterator = iteratorRecord.iterator;\n let returnMethod: (typeof iterator)['return'] | undefined;\n try {\n returnMethod = GetMethod(iterator, 'return');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n if (returnMethod === undefined) {\n return promiseResolvedWith(undefined);\n }\n let returnResult: IteratorResult | Promise>;\n try {\n returnResult = reflectCall(returnMethod, iterator, [reason]);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const returnPromise = promiseResolvedWith(returnResult);\n return transformPromiseWith(returnPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object');\n }\n return undefined;\n });\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n\nexport function ReadableStreamFromDefaultReader(\n reader: ReadableStreamDefaultReaderLike\n): DefaultReadableStream {\n let stream: DefaultReadableStream;\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let readPromise;\n try {\n readPromise = reader.read();\n } catch (e) {\n return promiseRejectedWith(e);\n }\n return transformPromiseWith(readPromise, readResult => {\n if (!typeIsObject(readResult)) {\n throw new TypeError('The promise returned by the reader.read() method must fulfill with an object');\n }\n if (readResult.done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = readResult.value;\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n try {\n return promiseResolvedWith(reader.cancel(reason));\n } catch (e) {\n return promiseRejectedWith(e);\n }\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n","import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n","import { assertDictionary } from './basic';\nimport type {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n","import { assertDictionary } from './basic';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n","import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n","import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, type ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderErrorReadRequests,\n type ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReaderErrorReadIntoRequests,\n type ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { ReadableStreamFrom } from './readable-stream/from';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport type {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList, SymbolAsyncIterator } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions\n} from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport type { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport type { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\nimport type { ReadableStreamDefaultReaderLike, ReadableStreamLike } from './readable-stream/readable-stream-like';\nimport type { NonShared } from './helpers/array-buffer-view';\n\nexport type DefaultReadableStream = ReadableStream & {\n _readableStreamController: ReadableStreamDefaultController\n};\n\nexport type ReadableByteStream = ReadableStream> & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream implements AsyncIterable {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n\n [SymbolAsyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator {\n // Stub implementation, overridden below\n return this.values(options);\n }\n\n /**\n * Creates a new ReadableStream wrapping the provided iterable or async iterable.\n *\n * This can be used to adapt various kinds of objects into a readable stream,\n * such as an array, an async generator, or a Node.js readable stream.\n */\n static from(asyncIterable: Iterable | AsyncIterable | ReadableStreamLike): ReadableStream {\n return ReadableStreamFrom(asyncIterable);\n }\n}\n\nObject.defineProperties(ReadableStream, {\n from: { enumerable: true }\n});\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(ReadableStream.from, 'from');\nsetFunctionName(ReadableStream.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStream.prototype.getReader, 'getReader');\nsetFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough');\nsetFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo');\nsetFunctionName(ReadableStream.prototype.tee, 'tee');\nsetFunctionName(ReadableStream.prototype.values, 'values');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nObject.defineProperty(ReadableStream.prototype, SymbolAsyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n});\n\nexport type {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n ReadableStreamBYOBReaderReadOptions,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions,\n ReadableStreamLike,\n ReadableStreamDefaultReaderLike\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1\n): DefaultReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: DefaultReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n","import type { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\nsetFunctionName(byteLengthSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\nsetFunctionName(countSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const cancel = original?.cancel;\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n cancel: cancel === undefined ?\n undefined :\n convertTransformerCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n\nfunction convertTransformerCancelCallback(\n fn: TransformerCancelCallback,\n original: Transformer,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith,\n uponPromise\n} from './helpers/webidl';\nimport { CreateReadableStream, type DefaultReadableStream, ReadableStream } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: DefaultReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport type {\n Transformer,\n TransformerCancelCallback,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSourceCancelAlgorithm(stream, reason);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n TransformStreamUnblockWrite(stream);\n}\n\nfunction TransformStreamUnblockWrite(stream: TransformStream) {\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _finishPromise: Promise | undefined;\n /** @internal */\n _finishPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _finishPromise_reject?: (reason: any) => void;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n /** @internal */\n _cancelAlgorithm: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(TransformStreamDefaultController.prototype.error, 'error');\nsetFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._finishPromise = undefined;\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm: (chunk: I) => Promise;\n let flushAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n } else {\n transformAlgorithm = chunk => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n }\n\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n } else {\n flushAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n if (transformer.cancel !== undefined) {\n cancelAlgorithm = reason => transformer.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally,\n // we don't run the _cancelAlgorithm again.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerError(readable._readableStreamController, reason);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally,\n // we don't also run the _cancelAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(flushPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerClose(readable._readableStreamController);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\nfunction TransformStreamDefaultSourceCancelAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._writable cannot change after construction, so caching it across a call to user code is safe.\n const writable = stream._writable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or\n // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the\n // _flushAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (writable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, writable._storedError);\n } else {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\nexport function defaultControllerFinishPromiseResolve(controller: TransformStreamDefaultController) {\n if (controller._finishPromise_resolve === undefined) {\n return;\n }\n\n controller._finishPromise_resolve();\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nexport function defaultControllerFinishPromiseReject(controller: TransformStreamDefaultController, reason: any) {\n if (controller._finishPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(controller._finishPromise!);\n controller._finishPromise_reject(reason);\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n"],"names":["queueMicrotask","streamBrandCheckException","defaultControllerBrandCheckException"],"mappings":";;;;;;;SAAgB,IAAI,GAAA;AAClB,IAAA,OAAO,SAAS,CAAC;AACnB;;ACCM,SAAU,YAAY,CAAC,CAAM,EAAA;AACjC,IAAA,OAAO,CAAC,OAAO,CAAC,KAAK,QAAQ,IAAI,CAAC,KAAK,IAAI,KAAK,OAAO,CAAC,KAAK,UAAU,CAAC;AAC1E,CAAC;AAEM,MAAM,8BAA8B,GAUrC,IAAI,CAAC;AAEK,SAAA,eAAe,CAAC,EAAY,EAAE,IAAY,EAAA;AACxD,IAAA,IAAI;AACF,QAAA,MAAM,CAAC,cAAc,CAAC,EAAE,EAAE,MAAM,EAAE;AAChC,YAAA,KAAK,EAAE,IAAI;AACX,YAAA,YAAY,EAAE,IAAI;AACnB,SAAA,CAAC,CAAC;KACJ;AAAC,IAAA,OAAA,EAAA,EAAM;;;KAGP;AACH;;AC1BA,MAAM,eAAe,GAAG,OAAO,CAAC;AAChC,MAAM,mBAAmB,GAAG,OAAO,CAAC,SAAS,CAAC,IAAI,CAAC;AACnD,MAAM,qBAAqB,GAAG,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC;AAEnE;AACM,SAAU,UAAU,CAAI,QAGrB,EAAA;AACP,IAAA,OAAO,IAAI,eAAe,CAAC,QAAQ,CAAC,CAAC;AACvC,CAAC;AAED;AACM,SAAU,mBAAmB,CAAI,KAAyB,EAAA;IAC9D,OAAO,UAAU,CAAC,OAAO,IAAI,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC;AAC/C,CAAC;AAED;AACM,SAAU,mBAAmB,CAAY,MAAW,EAAA;AACxD,IAAA,OAAO,qBAAqB,CAAC,MAAM,CAAC,CAAC;AACvC,CAAC;SAEe,kBAAkB,CAChC,OAA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CAAC,sBAAsB,EAAE,CAAC;AACpC,IAAA,UAAU,CAAC,sBAAsB,GAAG,SAAS,CAAC;AAC9C,IAAA,UAAU,CAAC,qBAAqB,GAAG,SAAS,CAAC;AAC/C,CAAC;AAEe,SAAA,oCAAoC,CAAC,UAAiD,EAAE,MAAW,EAAA;AACjH,IAAA,IAAI,UAAU,CAAC,qBAAqB,KAAK,SAAS,EAAE;QAClD,OAAO;KACR;AAED,IAAA,yBAAyB,CAAC,UAAU,CAAC,cAAe,CAAC,CAAC;AACtD,IAAA,UAAU,CAAC,qBAAqB,CAAC,MAAM,CAAC,CAAC;AACzC,IAAA,UAAU,CAAC,sBAAsB,GAAG,SAAS,CAAC;AAC9C,IAAA,UAAU,CAAC,qBAAqB,GAAG,SAAS,CAAC;AAC/C,CAAC;AAED;AAEA,SAAS,yBAAyB,CAAC,IAAY,EAAA;AAC7C,IAAA,OAAO,IAAI,SAAS,CAClB,6BAA6B,IAAI,CAAA,sCAAA,CAAwC,CAAC,CAAC;AAC/E;;;;","x_google_ignoreList":[11]} \ No newline at end of file diff --git a/backend/node_modules/web-streams-polyfill/dist/ponyfill.js b/backend/node_modules/web-streams-polyfill/dist/ponyfill.js new file mode 100644 index 0000000000000000000000000000000000000000..69fd00ddff868ea90c1843513008a56d9e7741ce --- /dev/null +++ b/backend/node_modules/web-streams-polyfill/dist/ponyfill.js @@ -0,0 +1,4983 @@ +/** + * @license + * web-streams-polyfill v3.3.3 + * Copyright 2024 Mattias Buelens, Diwank Singh Tomer and other contributors. + * This code is released under the MIT license. + * SPDX-License-Identifier: MIT + */ +(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.WebStreamsPolyfill = {})); +})(this, (function (exports) { 'use strict'; + + /// + var SymbolPolyfill = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? + Symbol : + function (description) { return "Symbol(".concat(description, ")"); }; + + /****************************************************************************** + 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 */ + + + function __generator(thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (g && (g = 0, op[0] && (_ = 0)), _) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + } + + function __values(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + } + + function __await(v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); + } + + function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } + } + + function __asyncDelegator(o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } + } + + function __asyncValues(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } + } + + typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; + }; + + function noop() { + return undefined; + } + + function typeIsObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; + } + var rethrowAssertionErrorRejection = noop; + function setFunctionName(fn, name) { + try { + Object.defineProperty(fn, 'name', { + value: name, + configurable: true + }); + } + catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility + } + } + + var originalPromise = Promise; + var originalPromiseThen = Promise.prototype.then; + var originalPromiseReject = Promise.reject.bind(originalPromise); + // https://webidl.spec.whatwg.org/#a-new-promise + function newPromise(executor) { + return new originalPromise(executor); + } + // https://webidl.spec.whatwg.org/#a-promise-resolved-with + function promiseResolvedWith(value) { + return newPromise(function (resolve) { return resolve(value); }); + } + // https://webidl.spec.whatwg.org/#a-promise-rejected-with + function promiseRejectedWith(reason) { + return originalPromiseReject(reason); + } + function PerformPromiseThen(promise, onFulfilled, onRejected) { + // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an + // approximation. + return originalPromiseThen.call(promise, onFulfilled, onRejected); + } + // Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned + // from that handler. To prevent this, return null instead of void from all handlers. + // http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it + function uponPromise(promise, onFulfilled, onRejected) { + PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection); + } + function uponFulfillment(promise, onFulfilled) { + uponPromise(promise, onFulfilled); + } + function uponRejection(promise, onRejected) { + uponPromise(promise, undefined, onRejected); + } + function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { + return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); + } + function setPromiseIsHandledToTrue(promise) { + PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection); + } + var _queueMicrotask = function (callback) { + if (typeof queueMicrotask === 'function') { + _queueMicrotask = queueMicrotask; + } + else { + var resolvedPromise_1 = promiseResolvedWith(undefined); + _queueMicrotask = function (cb) { return PerformPromiseThen(resolvedPromise_1, cb); }; + } + return _queueMicrotask(callback); + }; + function reflectCall(F, V, args) { + if (typeof F !== 'function') { + throw new TypeError('Argument is not a function'); + } + return Function.prototype.apply.call(F, V, args); + } + function promiseCall(F, V, args) { + try { + return promiseResolvedWith(reflectCall(F, V, args)); + } + catch (value) { + return promiseRejectedWith(value); + } + } + + // Original from Chromium + // https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js + var QUEUE_MAX_ARRAY_SIZE = 16384; + /** + * Simple queue structure. + * + * Avoids scalability issues with using a packed array directly by using + * multiple arrays in a linked list and keeping the array size bounded. + */ + var SimpleQueue = /** @class */ (function () { + function SimpleQueue() { + this._cursor = 0; + this._size = 0; + // _front and _back are always defined. + this._front = { + _elements: [], + _next: undefined + }; + this._back = this._front; + // The cursor is used to avoid calling Array.shift(). + // It contains the index of the front element of the array inside the + // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE). + this._cursor = 0; + // When there is only one node, size === elements.length - cursor. + this._size = 0; + } + Object.defineProperty(SimpleQueue.prototype, "length", { + get: function () { + return this._size; + }, + enumerable: false, + configurable: true + }); + // For exception safety, this method is structured in order: + // 1. Read state + // 2. Calculate required state mutations + // 3. Perform state mutations + SimpleQueue.prototype.push = function (element) { + var oldBack = this._back; + var newBack = oldBack; + if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { + newBack = { + _elements: [], + _next: undefined + }; + } + // push() is the mutation most likely to throw an exception, so it + // goes first. + oldBack._elements.push(element); + if (newBack !== oldBack) { + this._back = newBack; + oldBack._next = newBack; + } + ++this._size; + }; + // Like push(), shift() follows the read -> calculate -> mutate pattern for + // exception safety. + SimpleQueue.prototype.shift = function () { // must not be called on an empty queue + var oldFront = this._front; + var newFront = oldFront; + var oldCursor = this._cursor; + var newCursor = oldCursor + 1; + var elements = oldFront._elements; + var element = elements[oldCursor]; + if (newCursor === QUEUE_MAX_ARRAY_SIZE) { + newFront = oldFront._next; + newCursor = 0; + } + // No mutations before this point. + --this._size; + this._cursor = newCursor; + if (oldFront !== newFront) { + this._front = newFront; + } + // Permit shifted element to be garbage collected. + elements[oldCursor] = undefined; + return element; + }; + // The tricky thing about forEach() is that it can be called + // re-entrantly. The queue may be mutated inside the callback. It is easy to + // see that push() within the callback has no negative effects since the end + // of the queue is checked for on every iteration. If shift() is called + // repeatedly within the callback then the next iteration may return an + // element that has been removed. In this case the callback will be called + // with undefined values until we either "catch up" with elements that still + // exist or reach the back of the queue. + SimpleQueue.prototype.forEach = function (callback) { + var i = this._cursor; + var node = this._front; + var elements = node._elements; + while (i !== elements.length || node._next !== undefined) { + if (i === elements.length) { + node = node._next; + elements = node._elements; + i = 0; + if (elements.length === 0) { + break; + } + } + callback(elements[i]); + ++i; + } + }; + // Return the element that would be returned if shift() was called now, + // without modifying the queue. + SimpleQueue.prototype.peek = function () { // must not be called on an empty queue + var front = this._front; + var cursor = this._cursor; + return front._elements[cursor]; + }; + return SimpleQueue; + }()); + + var AbortSteps = SymbolPolyfill('[[AbortSteps]]'); + var ErrorSteps = SymbolPolyfill('[[ErrorSteps]]'); + var CancelSteps = SymbolPolyfill('[[CancelSteps]]'); + var PullSteps = SymbolPolyfill('[[PullSteps]]'); + var ReleaseSteps = SymbolPolyfill('[[ReleaseSteps]]'); + + function ReadableStreamReaderGenericInitialize(reader, stream) { + reader._ownerReadableStream = stream; + stream._reader = reader; + if (stream._state === 'readable') { + defaultReaderClosedPromiseInitialize(reader); + } + else if (stream._state === 'closed') { + defaultReaderClosedPromiseInitializeAsResolved(reader); + } + else { + defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); + } + } + // A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state + // check. + function ReadableStreamReaderGenericCancel(reader, reason) { + var stream = reader._ownerReadableStream; + return ReadableStreamCancel(stream, reason); + } + function ReadableStreamReaderGenericRelease(reader) { + var stream = reader._ownerReadableStream; + if (stream._state === 'readable') { + defaultReaderClosedPromiseReject(reader, new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")); + } + else { + defaultReaderClosedPromiseResetToRejected(reader, new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")); + } + stream._readableStreamController[ReleaseSteps](); + stream._reader = undefined; + reader._ownerReadableStream = undefined; + } + // Helper functions for the readers. + function readerLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released reader'); + } + // Helper functions for the ReadableStreamDefaultReader. + function defaultReaderClosedPromiseInitialize(reader) { + reader._closedPromise = newPromise(function (resolve, reject) { + reader._closedPromise_resolve = resolve; + reader._closedPromise_reject = reject; + }); + } + function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseReject(reader, reason); + } + function defaultReaderClosedPromiseInitializeAsResolved(reader) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseResolve(reader); + } + function defaultReaderClosedPromiseReject(reader, reason) { + if (reader._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(reader._closedPromise); + reader._closedPromise_reject(reason); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; + } + function defaultReaderClosedPromiseResetToRejected(reader, reason) { + defaultReaderClosedPromiseInitializeAsRejected(reader, reason); + } + function defaultReaderClosedPromiseResolve(reader) { + if (reader._closedPromise_resolve === undefined) { + return; + } + reader._closedPromise_resolve(undefined); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; + } + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill + var NumberIsFinite = Number.isFinite || function (x) { + return typeof x === 'number' && isFinite(x); + }; + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill + var MathTrunc = Math.trunc || function (v) { + return v < 0 ? Math.ceil(v) : Math.floor(v); + }; + + // https://heycam.github.io/webidl/#idl-dictionaries + function isDictionary(x) { + return typeof x === 'object' || typeof x === 'function'; + } + function assertDictionary(obj, context) { + if (obj !== undefined && !isDictionary(obj)) { + throw new TypeError("".concat(context, " is not an object.")); + } + } + // https://heycam.github.io/webidl/#idl-callback-functions + function assertFunction(x, context) { + if (typeof x !== 'function') { + throw new TypeError("".concat(context, " is not a function.")); + } + } + // https://heycam.github.io/webidl/#idl-object + function isObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; + } + function assertObject(x, context) { + if (!isObject(x)) { + throw new TypeError("".concat(context, " is not an object.")); + } + } + function assertRequiredArgument(x, position, context) { + if (x === undefined) { + throw new TypeError("Parameter ".concat(position, " is required in '").concat(context, "'.")); + } + } + function assertRequiredField(x, field, context) { + if (x === undefined) { + throw new TypeError("".concat(field, " is required in '").concat(context, "'.")); + } + } + // https://heycam.github.io/webidl/#idl-unrestricted-double + function convertUnrestrictedDouble(value) { + return Number(value); + } + function censorNegativeZero(x) { + return x === 0 ? 0 : x; + } + function integerPart(x) { + return censorNegativeZero(MathTrunc(x)); + } + // https://heycam.github.io/webidl/#idl-unsigned-long-long + function convertUnsignedLongLongWithEnforceRange(value, context) { + var lowerBound = 0; + var upperBound = Number.MAX_SAFE_INTEGER; + var x = Number(value); + x = censorNegativeZero(x); + if (!NumberIsFinite(x)) { + throw new TypeError("".concat(context, " is not a finite number")); + } + x = integerPart(x); + if (x < lowerBound || x > upperBound) { + throw new TypeError("".concat(context, " is outside the accepted range of ").concat(lowerBound, " to ").concat(upperBound, ", inclusive")); + } + if (!NumberIsFinite(x) || x === 0) { + return 0; + } + // TODO Use BigInt if supported? + // let xBigInt = BigInt(integerPart(x)); + // xBigInt = BigInt.asUintN(64, xBigInt); + // return Number(xBigInt); + return x; + } + + function assertReadableStream(x, context) { + if (!IsReadableStream(x)) { + throw new TypeError("".concat(context, " is not a ReadableStream.")); + } + } + + // Abstract operations for the ReadableStream. + function AcquireReadableStreamDefaultReader(stream) { + return new ReadableStreamDefaultReader(stream); + } + // ReadableStream API exposed for controllers. + function ReadableStreamAddReadRequest(stream, readRequest) { + stream._reader._readRequests.push(readRequest); + } + function ReadableStreamFulfillReadRequest(stream, chunk, done) { + var reader = stream._reader; + var readRequest = reader._readRequests.shift(); + if (done) { + readRequest._closeSteps(); + } + else { + readRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadRequests(stream) { + return stream._reader._readRequests.length; + } + function ReadableStreamHasDefaultReader(stream) { + var reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamDefaultReader(reader)) { + return false; + } + return true; + } + /** + * A default reader vended by a {@link ReadableStream}. + * + * @public + */ + var ReadableStreamDefaultReader = /** @class */ (function () { + function ReadableStreamDefaultReader(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readRequests = new SimpleQueue(); + } + Object.defineProperty(ReadableStreamDefaultReader.prototype, "closed", { + /** + * Returns a promise that will be fulfilled when the stream becomes closed, + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + */ + get: function () { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('closed')); + } + return this._closedPromise; + }, + enumerable: false, + configurable: true + }); + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + ReadableStreamDefaultReader.prototype.cancel = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + }; + /** + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + ReadableStreamDefaultReader.prototype.read = function () { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('read')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + var resolvePromise; + var rejectPromise; + var promise = newPromise(function (resolve, reject) { + resolvePromise = resolve; + rejectPromise = reject; + }); + var readRequest = { + _chunkSteps: function (chunk) { return resolvePromise({ value: chunk, done: false }); }, + _closeSteps: function () { return resolvePromise({ value: undefined, done: true }); }, + _errorSteps: function (e) { return rejectPromise(e); } + }; + ReadableStreamDefaultReaderRead(this, readRequest); + return promise; + }; + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + ReadableStreamDefaultReader.prototype.releaseLock = function () { + if (!IsReadableStreamDefaultReader(this)) { + throw defaultReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamDefaultReaderRelease(this); + }; + return ReadableStreamDefaultReader; + }()); + Object.defineProperties(ReadableStreamDefaultReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + setFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel'); + setFunctionName(ReadableStreamDefaultReader.prototype.read, 'read'); + setFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultReader', + configurable: true + }); + } + // Abstract operations for the readers. + function IsReadableStreamDefaultReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) { + return false; + } + return x instanceof ReadableStreamDefaultReader; + } + function ReadableStreamDefaultReaderRead(reader, readRequest) { + var stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'closed') { + readRequest._closeSteps(); + } + else if (stream._state === 'errored') { + readRequest._errorSteps(stream._storedError); + } + else { + stream._readableStreamController[PullSteps](readRequest); + } + } + function ReadableStreamDefaultReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + var e = new TypeError('Reader was released'); + ReadableStreamDefaultReaderErrorReadRequests(reader, e); + } + function ReadableStreamDefaultReaderErrorReadRequests(reader, e) { + var readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(function (readRequest) { + readRequest._errorSteps(e); + }); + } + // Helper functions for the ReadableStreamDefaultReader. + function defaultReaderBrandCheckException(name) { + return new TypeError("ReadableStreamDefaultReader.prototype.".concat(name, " can only be used on a ReadableStreamDefaultReader")); + } + + var _a$1, _b, _c; + function CreateArrayFromList(elements) { + // We use arrays to represent lists, so this is basically a no-op. + // Do a slice though just in case we happen to depend on the unique-ness. + return elements.slice(); + } + function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { + new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); + } + var TransferArrayBuffer = function (O) { + if (typeof O.transfer === 'function') { + TransferArrayBuffer = function (buffer) { return buffer.transfer(); }; + } + else if (typeof structuredClone === 'function') { + TransferArrayBuffer = function (buffer) { return structuredClone(buffer, { transfer: [buffer] }); }; + } + else { + // Not implemented correctly + TransferArrayBuffer = function (buffer) { return buffer; }; + } + return TransferArrayBuffer(O); + }; + var IsDetachedBuffer = function (O) { + if (typeof O.detached === 'boolean') { + IsDetachedBuffer = function (buffer) { return buffer.detached; }; + } + else { + // Not implemented correctly + IsDetachedBuffer = function (buffer) { return buffer.byteLength === 0; }; + } + return IsDetachedBuffer(O); + }; + function ArrayBufferSlice(buffer, begin, end) { + // ArrayBuffer.prototype.slice is not available on IE10 + // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice + if (buffer.slice) { + return buffer.slice(begin, end); + } + var length = end - begin; + var slice = new ArrayBuffer(length); + CopyDataBlockBytes(slice, 0, buffer, begin, length); + return slice; + } + function GetMethod(receiver, prop) { + var func = receiver[prop]; + if (func === undefined || func === null) { + return undefined; + } + if (typeof func !== 'function') { + throw new TypeError("".concat(String(prop), " is not a function")); + } + return func; + } + function CreateAsyncFromSyncIterator(syncIteratorRecord) { + // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%, + // we use yield* inside an async generator function to achieve the same result. + var _a; + // Wrap the sync iterator inside a sync iterable, so we can use it with yield*. + var syncIterable = (_a = {}, + _a[SymbolPolyfill.iterator] = function () { return syncIteratorRecord.iterator; }, + _a); + // Create an async generator function and immediately invoke it. + var asyncIterator = (function () { + return __asyncGenerator(this, arguments, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [5 /*yield**/, __values(__asyncDelegator(__asyncValues(syncIterable)))]; + case 1: return [4 /*yield*/, __await.apply(void 0, [_a.sent()])]; + case 2: return [4 /*yield*/, __await.apply(void 0, [_a.sent()])]; + case 3: return [2 /*return*/, _a.sent()]; + } + }); + }); + }()); + // Return as an async iterator record. + var nextMethod = asyncIterator.next; + return { iterator: asyncIterator, nextMethod: nextMethod, done: false }; + } + // Aligns with core-js/modules/es.symbol.async-iterator.js + var SymbolAsyncIterator = (_c = (_a$1 = SymbolPolyfill.asyncIterator) !== null && _a$1 !== void 0 ? _a$1 : (_b = SymbolPolyfill.for) === null || _b === void 0 ? void 0 : _b.call(SymbolPolyfill, 'Symbol.asyncIterator')) !== null && _c !== void 0 ? _c : '@@asyncIterator'; + function GetIterator(obj, hint, method) { + if (hint === void 0) { hint = 'sync'; } + if (method === undefined) { + if (hint === 'async') { + method = GetMethod(obj, SymbolAsyncIterator); + if (method === undefined) { + var syncMethod = GetMethod(obj, SymbolPolyfill.iterator); + var syncIteratorRecord = GetIterator(obj, 'sync', syncMethod); + return CreateAsyncFromSyncIterator(syncIteratorRecord); + } + } + else { + method = GetMethod(obj, SymbolPolyfill.iterator); + } + } + if (method === undefined) { + throw new TypeError('The object is not iterable'); + } + var iterator = reflectCall(method, obj, []); + if (!typeIsObject(iterator)) { + throw new TypeError('The iterator method must return an object'); + } + var nextMethod = iterator.next; + return { iterator: iterator, nextMethod: nextMethod, done: false }; + } + function IteratorNext(iteratorRecord) { + var result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []); + if (!typeIsObject(result)) { + throw new TypeError('The iterator.next() method must return an object'); + } + return result; + } + function IteratorComplete(iterResult) { + return Boolean(iterResult.done); + } + function IteratorValue(iterResult) { + return iterResult.value; + } + + /// + var _a; + // We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it. + var AsyncIteratorPrototype = (_a = {}, + // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( ) + // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator + _a[SymbolAsyncIterator] = function () { + return this; + }, + _a); + Object.defineProperty(AsyncIteratorPrototype, SymbolAsyncIterator, { enumerable: false }); + + /// + var ReadableStreamAsyncIteratorImpl = /** @class */ (function () { + function ReadableStreamAsyncIteratorImpl(reader, preventCancel) { + this._ongoingPromise = undefined; + this._isFinished = false; + this._reader = reader; + this._preventCancel = preventCancel; + } + ReadableStreamAsyncIteratorImpl.prototype.next = function () { + var _this = this; + var nextSteps = function () { return _this._nextSteps(); }; + this._ongoingPromise = this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : + nextSteps(); + return this._ongoingPromise; + }; + ReadableStreamAsyncIteratorImpl.prototype.return = function (value) { + var _this = this; + var returnSteps = function () { return _this._returnSteps(value); }; + return this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : + returnSteps(); + }; + ReadableStreamAsyncIteratorImpl.prototype._nextSteps = function () { + var _this = this; + if (this._isFinished) { + return Promise.resolve({ value: undefined, done: true }); + } + var reader = this._reader; + var resolvePromise; + var rejectPromise; + var promise = newPromise(function (resolve, reject) { + resolvePromise = resolve; + rejectPromise = reject; + }); + var readRequest = { + _chunkSteps: function (chunk) { + _this._ongoingPromise = undefined; + // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test. + // FIXME Is this a bug in the specification, or in the test? + _queueMicrotask(function () { return resolvePromise({ value: chunk, done: false }); }); + }, + _closeSteps: function () { + _this._ongoingPromise = undefined; + _this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + resolvePromise({ value: undefined, done: true }); + }, + _errorSteps: function (reason) { + _this._ongoingPromise = undefined; + _this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + rejectPromise(reason); + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promise; + }; + ReadableStreamAsyncIteratorImpl.prototype._returnSteps = function (value) { + if (this._isFinished) { + return Promise.resolve({ value: value, done: true }); + } + this._isFinished = true; + var reader = this._reader; + if (!this._preventCancel) { + var result = ReadableStreamReaderGenericCancel(reader, value); + ReadableStreamReaderGenericRelease(reader); + return transformPromiseWith(result, function () { return ({ value: value, done: true }); }); + } + ReadableStreamReaderGenericRelease(reader); + return promiseResolvedWith({ value: value, done: true }); + }; + return ReadableStreamAsyncIteratorImpl; + }()); + var ReadableStreamAsyncIteratorPrototype = { + next: function () { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next')); + } + return this._asyncIteratorImpl.next(); + }, + return: function (value) { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return')); + } + return this._asyncIteratorImpl.return(value); + } + }; + Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); + // Abstract operations for the ReadableStream. + function AcquireReadableStreamAsyncIterator(stream, preventCancel) { + var reader = AcquireReadableStreamDefaultReader(stream); + var impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); + var iterator = Object.create(ReadableStreamAsyncIteratorPrototype); + iterator._asyncIteratorImpl = impl; + return iterator; + } + function IsReadableStreamAsyncIterator(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) { + return false; + } + try { + // noinspection SuspiciousTypeOfGuard + return x._asyncIteratorImpl instanceof + ReadableStreamAsyncIteratorImpl; + } + catch (_a) { + return false; + } + } + // Helper functions for the ReadableStream. + function streamAsyncIteratorBrandCheckException(name) { + return new TypeError("ReadableStreamAsyncIterator.".concat(name, " can only be used on a ReadableSteamAsyncIterator")); + } + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill + var NumberIsNaN = Number.isNaN || function (x) { + // eslint-disable-next-line no-self-compare + return x !== x; + }; + + function IsNonNegativeNumber(v) { + if (typeof v !== 'number') { + return false; + } + if (NumberIsNaN(v)) { + return false; + } + if (v < 0) { + return false; + } + return true; + } + function CloneAsUint8Array(O) { + var buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength); + return new Uint8Array(buffer); + } + + function DequeueValue(container) { + var pair = container._queue.shift(); + container._queueTotalSize -= pair.size; + if (container._queueTotalSize < 0) { + container._queueTotalSize = 0; + } + return pair.value; + } + function EnqueueValueWithSize(container, value, size) { + if (!IsNonNegativeNumber(size) || size === Infinity) { + throw new RangeError('Size must be a finite, non-NaN, non-negative number.'); + } + container._queue.push({ value: value, size: size }); + container._queueTotalSize += size; + } + function PeekQueueValue(container) { + var pair = container._queue.peek(); + return pair.value; + } + function ResetQueue(container) { + container._queue = new SimpleQueue(); + container._queueTotalSize = 0; + } + + function isDataViewConstructor(ctor) { + return ctor === DataView; + } + function isDataView(view) { + return isDataViewConstructor(view.constructor); + } + function arrayBufferViewElementSize(ctor) { + if (isDataViewConstructor(ctor)) { + return 1; + } + return ctor.BYTES_PER_ELEMENT; + } + + /** + * A pull-into request in a {@link ReadableByteStreamController}. + * + * @public + */ + var ReadableStreamBYOBRequest = /** @class */ (function () { + function ReadableStreamBYOBRequest() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(ReadableStreamBYOBRequest.prototype, "view", { + /** + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. + */ + get: function () { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('view'); + } + return this._view; + }, + enumerable: false, + configurable: true + }); + ReadableStreamBYOBRequest.prototype.respond = function (bytesWritten) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respond'); + } + assertRequiredArgument(bytesWritten, 1, 'respond'); + bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter'); + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(this._view.buffer)) { + throw new TypeError("The BYOB request's buffer has been detached and so cannot be used as a response"); + } + ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); + }; + ReadableStreamBYOBRequest.prototype.respondWithNewView = function (view) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respondWithNewView'); + } + assertRequiredArgument(view, 1, 'respondWithNewView'); + if (!ArrayBuffer.isView(view)) { + throw new TypeError('You can only respond with array buffer views'); + } + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(view.buffer)) { + throw new TypeError('The given view\'s buffer has been detached and so cannot be used as a response'); + } + ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); + }; + return ReadableStreamBYOBRequest; + }()); + Object.defineProperties(ReadableStreamBYOBRequest.prototype, { + respond: { enumerable: true }, + respondWithNewView: { enumerable: true }, + view: { enumerable: true } + }); + setFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond'); + setFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBRequest', + configurable: true + }); + } + /** + * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. + * + * @public + */ + var ReadableByteStreamController = /** @class */ (function () { + function ReadableByteStreamController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(ReadableByteStreamController.prototype, "byobRequest", { + /** + * Returns the current BYOB pull request, or `null` if there isn't one. + */ + get: function () { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('byobRequest'); + } + return ReadableByteStreamControllerGetBYOBRequest(this); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ReadableByteStreamController.prototype, "desiredSize", { + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + */ + get: function () { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('desiredSize'); + } + return ReadableByteStreamControllerGetDesiredSize(this); + }, + enumerable: false, + configurable: true + }); + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + ReadableByteStreamController.prototype.close = function () { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('close'); + } + if (this._closeRequested) { + throw new TypeError('The stream has already been closed; do not close it again!'); + } + var state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError("The stream (in ".concat(state, " state) is not in the readable state and cannot be closed")); + } + ReadableByteStreamControllerClose(this); + }; + ReadableByteStreamController.prototype.enqueue = function (chunk) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('enqueue'); + } + assertRequiredArgument(chunk, 1, 'enqueue'); + if (!ArrayBuffer.isView(chunk)) { + throw new TypeError('chunk must be an array buffer view'); + } + if (chunk.byteLength === 0) { + throw new TypeError('chunk must have non-zero byteLength'); + } + if (chunk.buffer.byteLength === 0) { + throw new TypeError("chunk's buffer must have non-zero byteLength"); + } + if (this._closeRequested) { + throw new TypeError('stream is closed or draining'); + } + var state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError("The stream (in ".concat(state, " state) is not in the readable state and cannot be enqueued to")); + } + ReadableByteStreamControllerEnqueue(this, chunk); + }; + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + ReadableByteStreamController.prototype.error = function (e) { + if (e === void 0) { e = undefined; } + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('error'); + } + ReadableByteStreamControllerError(this, e); + }; + /** @internal */ + ReadableByteStreamController.prototype[CancelSteps] = function (reason) { + ReadableByteStreamControllerClearPendingPullIntos(this); + ResetQueue(this); + var result = this._cancelAlgorithm(reason); + ReadableByteStreamControllerClearAlgorithms(this); + return result; + }; + /** @internal */ + ReadableByteStreamController.prototype[PullSteps] = function (readRequest) { + var stream = this._controlledReadableByteStream; + if (this._queueTotalSize > 0) { + ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest); + return; + } + var autoAllocateChunkSize = this._autoAllocateChunkSize; + if (autoAllocateChunkSize !== undefined) { + var buffer = void 0; + try { + buffer = new ArrayBuffer(autoAllocateChunkSize); + } + catch (bufferE) { + readRequest._errorSteps(bufferE); + return; + } + var pullIntoDescriptor = { + buffer: buffer, + bufferByteLength: autoAllocateChunkSize, + byteOffset: 0, + byteLength: autoAllocateChunkSize, + bytesFilled: 0, + minimumFill: 1, + elementSize: 1, + viewConstructor: Uint8Array, + readerType: 'default' + }; + this._pendingPullIntos.push(pullIntoDescriptor); + } + ReadableStreamAddReadRequest(stream, readRequest); + ReadableByteStreamControllerCallPullIfNeeded(this); + }; + /** @internal */ + ReadableByteStreamController.prototype[ReleaseSteps] = function () { + if (this._pendingPullIntos.length > 0) { + var firstPullInto = this._pendingPullIntos.peek(); + firstPullInto.readerType = 'none'; + this._pendingPullIntos = new SimpleQueue(); + this._pendingPullIntos.push(firstPullInto); + } + }; + return ReadableByteStreamController; + }()); + Object.defineProperties(ReadableByteStreamController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + byobRequest: { enumerable: true }, + desiredSize: { enumerable: true } + }); + setFunctionName(ReadableByteStreamController.prototype.close, 'close'); + setFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue'); + setFunctionName(ReadableByteStreamController.prototype.error, 'error'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableByteStreamController', + configurable: true + }); + } + // Abstract operations for the ReadableByteStreamController. + function IsReadableByteStreamController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) { + return false; + } + return x instanceof ReadableByteStreamController; + } + function IsReadableStreamBYOBRequest(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) { + return false; + } + return x instanceof ReadableStreamBYOBRequest; + } + function ReadableByteStreamControllerCallPullIfNeeded(controller) { + var shouldPull = ReadableByteStreamControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + // TODO: Test controller argument + var pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, function () { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + return null; + }, function (e) { + ReadableByteStreamControllerError(controller, e); + return null; + }); + } + function ReadableByteStreamControllerClearPendingPullIntos(controller) { + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + controller._pendingPullIntos = new SimpleQueue(); + } + function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { + var done = false; + if (stream._state === 'closed') { + done = true; + } + var filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'default') { + ReadableStreamFulfillReadRequest(stream, filledView, done); + } + else { + ReadableStreamFulfillReadIntoRequest(stream, filledView, done); + } + } + function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { + var bytesFilled = pullIntoDescriptor.bytesFilled; + var elementSize = pullIntoDescriptor.elementSize; + return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); + } + function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { + controller._queue.push({ buffer: buffer, byteOffset: byteOffset, byteLength: byteLength }); + controller._queueTotalSize += byteLength; + } + function ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, buffer, byteOffset, byteLength) { + var clonedChunk; + try { + clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength); + } + catch (cloneE) { + ReadableByteStreamControllerError(controller, cloneE); + throw cloneE; + } + ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength); + } + function ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstDescriptor) { + if (firstDescriptor.bytesFilled > 0) { + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, firstDescriptor.buffer, firstDescriptor.byteOffset, firstDescriptor.bytesFilled); + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { + var maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); + var maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; + var totalBytesToCopyRemaining = maxBytesToCopy; + var ready = false; + var remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize; + var maxAlignedBytes = maxBytesFilled - remainderBytes; + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) { + totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; + ready = true; + } + var queue = controller._queue; + while (totalBytesToCopyRemaining > 0) { + var headOfQueue = queue.peek(); + var bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); + var destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); + if (headOfQueue.byteLength === bytesToCopy) { + queue.shift(); + } + else { + headOfQueue.byteOffset += bytesToCopy; + headOfQueue.byteLength -= bytesToCopy; + } + controller._queueTotalSize -= bytesToCopy; + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); + totalBytesToCopyRemaining -= bytesToCopy; + } + return ready; + } + function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { + pullIntoDescriptor.bytesFilled += size; + } + function ReadableByteStreamControllerHandleQueueDrain(controller) { + if (controller._queueTotalSize === 0 && controller._closeRequested) { + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(controller._controlledReadableByteStream); + } + else { + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + } + function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { + if (controller._byobRequest === null) { + return; + } + controller._byobRequest._associatedReadableByteStreamController = undefined; + controller._byobRequest._view = null; + controller._byobRequest = null; + } + function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { + while (controller._pendingPullIntos.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + var pullIntoDescriptor = controller._pendingPullIntos.peek(); + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller) { + var reader = controller._controlledReadableByteStream._reader; + while (reader._readRequests.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + var readRequest = reader._readRequests.shift(); + ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest); + } + } + function ReadableByteStreamControllerPullInto(controller, view, min, readIntoRequest) { + var stream = controller._controlledReadableByteStream; + var ctor = view.constructor; + var elementSize = arrayBufferViewElementSize(ctor); + var byteOffset = view.byteOffset, byteLength = view.byteLength; + var minimumFill = min * elementSize; + var buffer; + try { + buffer = TransferArrayBuffer(view.buffer); + } + catch (e) { + readIntoRequest._errorSteps(e); + return; + } + var pullIntoDescriptor = { + buffer: buffer, + bufferByteLength: buffer.byteLength, + byteOffset: byteOffset, + byteLength: byteLength, + bytesFilled: 0, + minimumFill: minimumFill, + elementSize: elementSize, + viewConstructor: ctor, + readerType: 'byob' + }; + if (controller._pendingPullIntos.length > 0) { + controller._pendingPullIntos.push(pullIntoDescriptor); + // No ReadableByteStreamControllerCallPullIfNeeded() call since: + // - No change happens on desiredSize + // - The source has already been notified of that there's at least 1 pending read(view) + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + return; + } + if (stream._state === 'closed') { + var emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); + readIntoRequest._closeSteps(emptyView); + return; + } + if (controller._queueTotalSize > 0) { + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + var filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + ReadableByteStreamControllerHandleQueueDrain(controller); + readIntoRequest._chunkSteps(filledView); + return; + } + if (controller._closeRequested) { + var e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + readIntoRequest._errorSteps(e); + return; + } + } + controller._pendingPullIntos.push(pullIntoDescriptor); + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { + if (firstDescriptor.readerType === 'none') { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + var stream = controller._controlledReadableByteStream; + if (ReadableStreamHasBYOBReader(stream)) { + while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { + var pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + return; + } + if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) { + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + return; + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + var remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; + if (remainderSize > 0) { + var end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor.buffer, end - remainderSize, remainderSize); + } + pullIntoDescriptor.bytesFilled -= remainderSize; + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { + var firstDescriptor = controller._pendingPullIntos.peek(); + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + var state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor); + } + else { + ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerShiftPendingPullInto(controller) { + var descriptor = controller._pendingPullIntos.shift(); + return descriptor; + } + function ReadableByteStreamControllerShouldCallPull(controller) { + var stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return false; + } + if (controller._closeRequested) { + return false; + } + if (!controller._started) { + return false; + } + if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { + return true; + } + var desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; + } + function ReadableByteStreamControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + } + // A client of ReadableByteStreamController may use these functions directly to bypass state check. + function ReadableByteStreamControllerClose(controller) { + var stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + if (controller._queueTotalSize > 0) { + controller._closeRequested = true; + return; + } + if (controller._pendingPullIntos.length > 0) { + var firstPendingPullInto = controller._pendingPullIntos.peek(); + if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) { + var e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + throw e; + } + } + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } + function ReadableByteStreamControllerEnqueue(controller, chunk) { + var stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + var buffer = chunk.buffer, byteOffset = chunk.byteOffset, byteLength = chunk.byteLength; + if (IsDetachedBuffer(buffer)) { + throw new TypeError('chunk\'s buffer is detached and so cannot be enqueued'); + } + var transferredBuffer = TransferArrayBuffer(buffer); + if (controller._pendingPullIntos.length > 0) { + var firstPendingPullInto = controller._pendingPullIntos.peek(); + if (IsDetachedBuffer(firstPendingPullInto.buffer)) { + throw new TypeError('The BYOB request\'s buffer has been detached and so cannot be filled with an enqueued chunk'); + } + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer); + if (firstPendingPullInto.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto); + } + } + if (ReadableStreamHasDefaultReader(stream)) { + ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller); + if (ReadableStreamGetNumReadRequests(stream) === 0) { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + else { + if (controller._pendingPullIntos.length > 0) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + var transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); + ReadableStreamFulfillReadRequest(stream, transferredView, false); + } + } + else if (ReadableStreamHasBYOBReader(stream)) { + // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully. + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + else { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerError(controller, e) { + var stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return; + } + ReadableByteStreamControllerClearPendingPullIntos(controller); + ResetQueue(controller); + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); + } + function ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest) { + var entry = controller._queue.shift(); + controller._queueTotalSize -= entry.byteLength; + ReadableByteStreamControllerHandleQueueDrain(controller); + var view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); + readRequest._chunkSteps(view); + } + function ReadableByteStreamControllerGetBYOBRequest(controller) { + if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) { + var firstDescriptor = controller._pendingPullIntos.peek(); + var view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); + var byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); + SetUpReadableStreamBYOBRequest(byobRequest, controller, view); + controller._byobRequest = byobRequest; + } + return controller._byobRequest; + } + function ReadableByteStreamControllerGetDesiredSize(controller) { + var state = controller._controlledReadableByteStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; + } + function ReadableByteStreamControllerRespond(controller, bytesWritten) { + var firstDescriptor = controller._pendingPullIntos.peek(); + var state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (bytesWritten !== 0) { + throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream'); + } + } + else { + if (bytesWritten === 0) { + throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream'); + } + if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) { + throw new RangeError('bytesWritten out of range'); + } + } + firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); + ReadableByteStreamControllerRespondInternal(controller, bytesWritten); + } + function ReadableByteStreamControllerRespondWithNewView(controller, view) { + var firstDescriptor = controller._pendingPullIntos.peek(); + var state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (view.byteLength !== 0) { + throw new TypeError('The view\'s length must be 0 when calling respondWithNewView() on a closed stream'); + } + } + else { + if (view.byteLength === 0) { + throw new TypeError('The view\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'); + } + } + if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { + throw new RangeError('The region specified by view does not match byobRequest'); + } + if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) { + throw new RangeError('The buffer of view has different capacity than byobRequest'); + } + if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) { + throw new RangeError('The region specified by view is larger than byobRequest'); + } + var viewByteLength = view.byteLength; + firstDescriptor.buffer = TransferArrayBuffer(view.buffer); + ReadableByteStreamControllerRespondInternal(controller, viewByteLength); + } + function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { + controller._controlledReadableByteStream = stream; + controller._pullAgain = false; + controller._pulling = false; + controller._byobRequest = null; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._closeRequested = false; + controller._started = false; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._autoAllocateChunkSize = autoAllocateChunkSize; + controller._pendingPullIntos = new SimpleQueue(); + stream._readableStreamController = controller; + var startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), function () { + controller._started = true; + ReadableByteStreamControllerCallPullIfNeeded(controller); + return null; + }, function (r) { + ReadableByteStreamControllerError(controller, r); + return null; + }); + } + function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { + var controller = Object.create(ReadableByteStreamController.prototype); + var startAlgorithm; + var pullAlgorithm; + var cancelAlgorithm; + if (underlyingByteSource.start !== undefined) { + startAlgorithm = function () { return underlyingByteSource.start(controller); }; + } + else { + startAlgorithm = function () { return undefined; }; + } + if (underlyingByteSource.pull !== undefined) { + pullAlgorithm = function () { return underlyingByteSource.pull(controller); }; + } + else { + pullAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + if (underlyingByteSource.cancel !== undefined) { + cancelAlgorithm = function (reason) { return underlyingByteSource.cancel(reason); }; + } + else { + cancelAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + var autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; + if (autoAllocateChunkSize === 0) { + throw new TypeError('autoAllocateChunkSize must be greater than 0'); + } + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); + } + function SetUpReadableStreamBYOBRequest(request, controller, view) { + request._associatedReadableByteStreamController = controller; + request._view = view; + } + // Helper functions for the ReadableStreamBYOBRequest. + function byobRequestBrandCheckException(name) { + return new TypeError("ReadableStreamBYOBRequest.prototype.".concat(name, " can only be used on a ReadableStreamBYOBRequest")); + } + // Helper functions for the ReadableByteStreamController. + function byteStreamControllerBrandCheckException(name) { + return new TypeError("ReadableByteStreamController.prototype.".concat(name, " can only be used on a ReadableByteStreamController")); + } + + function convertReaderOptions(options, context) { + assertDictionary(options, context); + var mode = options === null || options === void 0 ? void 0 : options.mode; + return { + mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, "".concat(context, " has member 'mode' that")) + }; + } + function convertReadableStreamReaderMode(mode, context) { + mode = "".concat(mode); + if (mode !== 'byob') { + throw new TypeError("".concat(context, " '").concat(mode, "' is not a valid enumeration value for ReadableStreamReaderMode")); + } + return mode; + } + function convertByobReadOptions(options, context) { + var _a; + assertDictionary(options, context); + var min = (_a = options === null || options === void 0 ? void 0 : options.min) !== null && _a !== void 0 ? _a : 1; + return { + min: convertUnsignedLongLongWithEnforceRange(min, "".concat(context, " has member 'min' that")) + }; + } + + // Abstract operations for the ReadableStream. + function AcquireReadableStreamBYOBReader(stream) { + return new ReadableStreamBYOBReader(stream); + } + // ReadableStream API exposed for controllers. + function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { + stream._reader._readIntoRequests.push(readIntoRequest); + } + function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { + var reader = stream._reader; + var readIntoRequest = reader._readIntoRequests.shift(); + if (done) { + readIntoRequest._closeSteps(chunk); + } + else { + readIntoRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadIntoRequests(stream) { + return stream._reader._readIntoRequests.length; + } + function ReadableStreamHasBYOBReader(stream) { + var reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamBYOBReader(reader)) { + return false; + } + return true; + } + /** + * A BYOB reader vended by a {@link ReadableStream}. + * + * @public + */ + var ReadableStreamBYOBReader = /** @class */ (function () { + function ReadableStreamBYOBReader(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + if (!IsReadableByteStreamController(stream._readableStreamController)) { + throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' + + 'source'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readIntoRequests = new SimpleQueue(); + } + Object.defineProperty(ReadableStreamBYOBReader.prototype, "closed", { + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the reader's lock is released before the stream finishes closing. + */ + get: function () { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('closed')); + } + return this._closedPromise; + }, + enumerable: false, + configurable: true + }); + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + ReadableStreamBYOBReader.prototype.cancel = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + }; + ReadableStreamBYOBReader.prototype.read = function (view, rawOptions) { + if (rawOptions === void 0) { rawOptions = {}; } + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('read')); + } + if (!ArrayBuffer.isView(view)) { + return promiseRejectedWith(new TypeError('view must be an array buffer view')); + } + if (view.byteLength === 0) { + return promiseRejectedWith(new TypeError('view must have non-zero byteLength')); + } + if (view.buffer.byteLength === 0) { + return promiseRejectedWith(new TypeError("view's buffer must have non-zero byteLength")); + } + if (IsDetachedBuffer(view.buffer)) { + return promiseRejectedWith(new TypeError('view\'s buffer has been detached')); + } + var options; + try { + options = convertByobReadOptions(rawOptions, 'options'); + } + catch (e) { + return promiseRejectedWith(e); + } + var min = options.min; + if (min === 0) { + return promiseRejectedWith(new TypeError('options.min must be greater than 0')); + } + if (!isDataView(view)) { + if (min > view.length) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s length')); + } + } + else if (min > view.byteLength) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s byteLength')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + var resolvePromise; + var rejectPromise; + var promise = newPromise(function (resolve, reject) { + resolvePromise = resolve; + rejectPromise = reject; + }); + var readIntoRequest = { + _chunkSteps: function (chunk) { return resolvePromise({ value: chunk, done: false }); }, + _closeSteps: function (chunk) { return resolvePromise({ value: chunk, done: true }); }, + _errorSteps: function (e) { return rejectPromise(e); } + }; + ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest); + return promise; + }; + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + ReadableStreamBYOBReader.prototype.releaseLock = function () { + if (!IsReadableStreamBYOBReader(this)) { + throw byobReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamBYOBReaderRelease(this); + }; + return ReadableStreamBYOBReader; + }()); + Object.defineProperties(ReadableStreamBYOBReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + setFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel'); + setFunctionName(ReadableStreamBYOBReader.prototype.read, 'read'); + setFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBReader', + configurable: true + }); + } + // Abstract operations for the readers. + function IsReadableStreamBYOBReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) { + return false; + } + return x instanceof ReadableStreamBYOBReader; + } + function ReadableStreamBYOBReaderRead(reader, view, min, readIntoRequest) { + var stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'errored') { + readIntoRequest._errorSteps(stream._storedError); + } + else { + ReadableByteStreamControllerPullInto(stream._readableStreamController, view, min, readIntoRequest); + } + } + function ReadableStreamBYOBReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + var e = new TypeError('Reader was released'); + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); + } + function ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e) { + var readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(function (readIntoRequest) { + readIntoRequest._errorSteps(e); + }); + } + // Helper functions for the ReadableStreamBYOBReader. + function byobReaderBrandCheckException(name) { + return new TypeError("ReadableStreamBYOBReader.prototype.".concat(name, " can only be used on a ReadableStreamBYOBReader")); + } + + function ExtractHighWaterMark(strategy, defaultHWM) { + var highWaterMark = strategy.highWaterMark; + if (highWaterMark === undefined) { + return defaultHWM; + } + if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { + throw new RangeError('Invalid highWaterMark'); + } + return highWaterMark; + } + function ExtractSizeAlgorithm(strategy) { + var size = strategy.size; + if (!size) { + return function () { return 1; }; + } + return size; + } + + function convertQueuingStrategy(init, context) { + assertDictionary(init, context); + var highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + var size = init === null || init === void 0 ? void 0 : init.size; + return { + highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark), + size: size === undefined ? undefined : convertQueuingStrategySize(size, "".concat(context, " has member 'size' that")) + }; + } + function convertQueuingStrategySize(fn, context) { + assertFunction(fn, context); + return function (chunk) { return convertUnrestrictedDouble(fn(chunk)); }; + } + + function convertUnderlyingSink(original, context) { + assertDictionary(original, context); + var abort = original === null || original === void 0 ? void 0 : original.abort; + var close = original === null || original === void 0 ? void 0 : original.close; + var start = original === null || original === void 0 ? void 0 : original.start; + var type = original === null || original === void 0 ? void 0 : original.type; + var write = original === null || original === void 0 ? void 0 : original.write; + return { + abort: abort === undefined ? + undefined : + convertUnderlyingSinkAbortCallback(abort, original, "".concat(context, " has member 'abort' that")), + close: close === undefined ? + undefined : + convertUnderlyingSinkCloseCallback(close, original, "".concat(context, " has member 'close' that")), + start: start === undefined ? + undefined : + convertUnderlyingSinkStartCallback(start, original, "".concat(context, " has member 'start' that")), + write: write === undefined ? + undefined : + convertUnderlyingSinkWriteCallback(write, original, "".concat(context, " has member 'write' that")), + type: type + }; + } + function convertUnderlyingSinkAbortCallback(fn, original, context) { + assertFunction(fn, context); + return function (reason) { return promiseCall(fn, original, [reason]); }; + } + function convertUnderlyingSinkCloseCallback(fn, original, context) { + assertFunction(fn, context); + return function () { return promiseCall(fn, original, []); }; + } + function convertUnderlyingSinkStartCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return reflectCall(fn, original, [controller]); }; + } + function convertUnderlyingSinkWriteCallback(fn, original, context) { + assertFunction(fn, context); + return function (chunk, controller) { return promiseCall(fn, original, [chunk, controller]); }; + } + + function assertWritableStream(x, context) { + if (!IsWritableStream(x)) { + throw new TypeError("".concat(context, " is not a WritableStream.")); + } + } + + function isAbortSignal(value) { + if (typeof value !== 'object' || value === null) { + return false; + } + try { + return typeof value.aborted === 'boolean'; + } + catch (_a) { + // AbortSignal.prototype.aborted throws if its brand check fails + return false; + } + } + var supportsAbortController = typeof AbortController === 'function'; + /** + * Construct a new AbortController, if supported by the platform. + * + * @internal + */ + function createAbortController() { + if (supportsAbortController) { + return new AbortController(); + } + return undefined; + } + + /** + * A writable stream represents a destination for data, into which you can write. + * + * @public + */ + var WritableStream = /** @class */ (function () { + function WritableStream(rawUnderlyingSink, rawStrategy) { + if (rawUnderlyingSink === void 0) { rawUnderlyingSink = {}; } + if (rawStrategy === void 0) { rawStrategy = {}; } + if (rawUnderlyingSink === undefined) { + rawUnderlyingSink = null; + } + else { + assertObject(rawUnderlyingSink, 'First parameter'); + } + var strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + var underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter'); + InitializeWritableStream(this); + var type = underlyingSink.type; + if (type !== undefined) { + throw new RangeError('Invalid type is specified'); + } + var sizeAlgorithm = ExtractSizeAlgorithm(strategy); + var highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); + } + Object.defineProperty(WritableStream.prototype, "locked", { + /** + * Returns whether or not the writable stream is locked to a writer. + */ + get: function () { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('locked'); + } + return IsWritableStreamLocked(this); + }, + enumerable: false, + configurable: true + }); + /** + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort + * mechanism of the underlying sink. + * + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel + * the stream) if the stream is currently locked. + */ + WritableStream.prototype.abort = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('abort')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer')); + } + return WritableStreamAbort(this, reason); + }; + /** + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its + * close behavior. During this time any further attempts to write will fail (without erroring the stream). + * + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + */ + WritableStream.prototype.close = function () { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('close')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer')); + } + if (WritableStreamCloseQueuedOrInFlight(this)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamClose(this); + }; + /** + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream + * is locked, no other writer can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at + * the same time, which would cause the resulting written data to be unpredictable and probably useless. + */ + WritableStream.prototype.getWriter = function () { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('getWriter'); + } + return AcquireWritableStreamDefaultWriter(this); + }; + return WritableStream; + }()); + Object.defineProperties(WritableStream.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + getWriter: { enumerable: true }, + locked: { enumerable: true } + }); + setFunctionName(WritableStream.prototype.abort, 'abort'); + setFunctionName(WritableStream.prototype.close, 'close'); + setFunctionName(WritableStream.prototype.getWriter, 'getWriter'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStream', + configurable: true + }); + } + // Abstract operations for the WritableStream. + function AcquireWritableStreamDefaultWriter(stream) { + return new WritableStreamDefaultWriter(stream); + } + // Throws if and only if startAlgorithm throws. + function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + if (highWaterMark === void 0) { highWaterMark = 1; } + if (sizeAlgorithm === void 0) { sizeAlgorithm = function () { return 1; }; } + var stream = Object.create(WritableStream.prototype); + InitializeWritableStream(stream); + var controller = Object.create(WritableStreamDefaultController.prototype); + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + return stream; + } + function InitializeWritableStream(stream) { + stream._state = 'writable'; + // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is + // 'erroring' or 'errored'. May be set to an undefined value. + stream._storedError = undefined; + stream._writer = undefined; + // Initialize to undefined first because the constructor of the controller checks this + // variable to validate the caller. + stream._writableStreamController = undefined; + // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data + // producer without waiting for the queued writes to finish. + stream._writeRequests = new SimpleQueue(); + // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents + // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here. + stream._inFlightWriteRequest = undefined; + // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer + // has been detached. + stream._closeRequest = undefined; + // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it + // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here. + stream._inFlightCloseRequest = undefined; + // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached. + stream._pendingAbortRequest = undefined; + // The backpressure signal set by the controller. + stream._backpressure = false; + } + function IsWritableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) { + return false; + } + return x instanceof WritableStream; + } + function IsWritableStreamLocked(stream) { + if (stream._writer === undefined) { + return false; + } + return true; + } + function WritableStreamAbort(stream, reason) { + var _a; + if (stream._state === 'closed' || stream._state === 'errored') { + return promiseResolvedWith(undefined); + } + stream._writableStreamController._abortReason = reason; + (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort(reason); + // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring', + // but it doesn't know that signaling abort runs author code that might have changed the state. + // Widen the type again by casting to WritableStreamState. + var state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseResolvedWith(undefined); + } + if (stream._pendingAbortRequest !== undefined) { + return stream._pendingAbortRequest._promise; + } + var wasAlreadyErroring = false; + if (state === 'erroring') { + wasAlreadyErroring = true; + // reason will not be used, so don't keep a reference to it. + reason = undefined; + } + var promise = newPromise(function (resolve, reject) { + stream._pendingAbortRequest = { + _promise: undefined, + _resolve: resolve, + _reject: reject, + _reason: reason, + _wasAlreadyErroring: wasAlreadyErroring + }; + }); + stream._pendingAbortRequest._promise = promise; + if (!wasAlreadyErroring) { + WritableStreamStartErroring(stream, reason); + } + return promise; + } + function WritableStreamClose(stream) { + var state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseRejectedWith(new TypeError("The stream (in ".concat(state, " state) is not in the writable state and cannot be closed"))); + } + var promise = newPromise(function (resolve, reject) { + var closeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._closeRequest = closeRequest; + }); + var writer = stream._writer; + if (writer !== undefined && stream._backpressure && state === 'writable') { + defaultWriterReadyPromiseResolve(writer); + } + WritableStreamDefaultControllerClose(stream._writableStreamController); + return promise; + } + // WritableStream API exposed for controllers. + function WritableStreamAddWriteRequest(stream) { + var promise = newPromise(function (resolve, reject) { + var writeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._writeRequests.push(writeRequest); + }); + return promise; + } + function WritableStreamDealWithRejection(stream, error) { + var state = stream._state; + if (state === 'writable') { + WritableStreamStartErroring(stream, error); + return; + } + WritableStreamFinishErroring(stream); + } + function WritableStreamStartErroring(stream, reason) { + var controller = stream._writableStreamController; + stream._state = 'erroring'; + stream._storedError = reason; + var writer = stream._writer; + if (writer !== undefined) { + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); + } + if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { + WritableStreamFinishErroring(stream); + } + } + function WritableStreamFinishErroring(stream) { + stream._state = 'errored'; + stream._writableStreamController[ErrorSteps](); + var storedError = stream._storedError; + stream._writeRequests.forEach(function (writeRequest) { + writeRequest._reject(storedError); + }); + stream._writeRequests = new SimpleQueue(); + if (stream._pendingAbortRequest === undefined) { + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + var abortRequest = stream._pendingAbortRequest; + stream._pendingAbortRequest = undefined; + if (abortRequest._wasAlreadyErroring) { + abortRequest._reject(storedError); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + var promise = stream._writableStreamController[AbortSteps](abortRequest._reason); + uponPromise(promise, function () { + abortRequest._resolve(); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }, function (reason) { + abortRequest._reject(reason); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }); + } + function WritableStreamFinishInFlightWrite(stream) { + stream._inFlightWriteRequest._resolve(undefined); + stream._inFlightWriteRequest = undefined; + } + function WritableStreamFinishInFlightWriteWithError(stream, error) { + stream._inFlightWriteRequest._reject(error); + stream._inFlightWriteRequest = undefined; + WritableStreamDealWithRejection(stream, error); + } + function WritableStreamFinishInFlightClose(stream) { + stream._inFlightCloseRequest._resolve(undefined); + stream._inFlightCloseRequest = undefined; + var state = stream._state; + if (state === 'erroring') { + // The error was too late to do anything, so it is ignored. + stream._storedError = undefined; + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._resolve(); + stream._pendingAbortRequest = undefined; + } + } + stream._state = 'closed'; + var writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseResolve(writer); + } + } + function WritableStreamFinishInFlightCloseWithError(stream, error) { + stream._inFlightCloseRequest._reject(error); + stream._inFlightCloseRequest = undefined; + // Never execute sink abort() after sink close(). + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._reject(error); + stream._pendingAbortRequest = undefined; + } + WritableStreamDealWithRejection(stream, error); + } + // TODO(ricea): Fix alphabetical order. + function WritableStreamCloseQueuedOrInFlight(stream) { + if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; + } + function WritableStreamHasOperationMarkedInFlight(stream) { + if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; + } + function WritableStreamMarkCloseRequestInFlight(stream) { + stream._inFlightCloseRequest = stream._closeRequest; + stream._closeRequest = undefined; + } + function WritableStreamMarkFirstWriteRequestInFlight(stream) { + stream._inFlightWriteRequest = stream._writeRequests.shift(); + } + function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { + if (stream._closeRequest !== undefined) { + stream._closeRequest._reject(stream._storedError); + stream._closeRequest = undefined; + } + var writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseReject(writer, stream._storedError); + } + } + function WritableStreamUpdateBackpressure(stream, backpressure) { + var writer = stream._writer; + if (writer !== undefined && backpressure !== stream._backpressure) { + if (backpressure) { + defaultWriterReadyPromiseReset(writer); + } + else { + defaultWriterReadyPromiseResolve(writer); + } + } + stream._backpressure = backpressure; + } + /** + * A default writer vended by a {@link WritableStream}. + * + * @public + */ + var WritableStreamDefaultWriter = /** @class */ (function () { + function WritableStreamDefaultWriter(stream) { + assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter'); + assertWritableStream(stream, 'First parameter'); + if (IsWritableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive writing by another writer'); + } + this._ownerWritableStream = stream; + stream._writer = this; + var state = stream._state; + if (state === 'writable') { + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { + defaultWriterReadyPromiseInitialize(this); + } + else { + defaultWriterReadyPromiseInitializeAsResolved(this); + } + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'erroring') { + defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'closed') { + defaultWriterReadyPromiseInitializeAsResolved(this); + defaultWriterClosedPromiseInitializeAsResolved(this); + } + else { + var storedError = stream._storedError; + defaultWriterReadyPromiseInitializeAsRejected(this, storedError); + defaultWriterClosedPromiseInitializeAsRejected(this, storedError); + } + } + Object.defineProperty(WritableStreamDefaultWriter.prototype, "closed", { + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the writer’s lock is released before the stream finishes closing. + */ + get: function () { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('closed')); + } + return this._closedPromise; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(WritableStreamDefaultWriter.prototype, "desiredSize", { + /** + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. + * A producer can use this information to determine the right amount of data to write. + * + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when + * the writer’s lock is released. + */ + get: function () { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('desiredSize'); + } + if (this._ownerWritableStream === undefined) { + throw defaultWriterLockException('desiredSize'); + } + return WritableStreamDefaultWriterGetDesiredSize(this); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(WritableStreamDefaultWriter.prototype, "ready", { + /** + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips + * back to zero or below, the getter will return a new promise that stays pending until the next transition. + * + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become + * rejected. + */ + get: function () { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('ready')); + } + return this._readyPromise; + }, + enumerable: false, + configurable: true + }); + /** + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + */ + WritableStreamDefaultWriter.prototype.abort = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('abort')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('abort')); + } + return WritableStreamDefaultWriterAbort(this, reason); + }; + /** + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + */ + WritableStreamDefaultWriter.prototype.close = function () { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('close')); + } + var stream = this._ownerWritableStream; + if (stream === undefined) { + return promiseRejectedWith(defaultWriterLockException('close')); + } + if (WritableStreamCloseQueuedOrInFlight(stream)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamDefaultWriterClose(this); + }; + /** + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from + * now on; otherwise, the writer will appear closed. + * + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents + * other producers from writing in an interleaved manner. + */ + WritableStreamDefaultWriter.prototype.releaseLock = function () { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('releaseLock'); + } + var stream = this._ownerWritableStream; + if (stream === undefined) { + return; + } + WritableStreamDefaultWriterRelease(this); + }; + WritableStreamDefaultWriter.prototype.write = function (chunk) { + if (chunk === void 0) { chunk = undefined; } + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('write')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + return WritableStreamDefaultWriterWrite(this, chunk); + }; + return WritableStreamDefaultWriter; + }()); + Object.defineProperties(WritableStreamDefaultWriter.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + releaseLock: { enumerable: true }, + write: { enumerable: true }, + closed: { enumerable: true }, + desiredSize: { enumerable: true }, + ready: { enumerable: true } + }); + setFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort'); + setFunctionName(WritableStreamDefaultWriter.prototype.close, 'close'); + setFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock'); + setFunctionName(WritableStreamDefaultWriter.prototype.write, 'write'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultWriter', + configurable: true + }); + } + // Abstract operations for the WritableStreamDefaultWriter. + function IsWritableStreamDefaultWriter(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultWriter; + } + // A client of WritableStreamDefaultWriter may use these functions directly to bypass state check. + function WritableStreamDefaultWriterAbort(writer, reason) { + var stream = writer._ownerWritableStream; + return WritableStreamAbort(stream, reason); + } + function WritableStreamDefaultWriterClose(writer) { + var stream = writer._ownerWritableStream; + return WritableStreamClose(stream); + } + function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { + var stream = writer._ownerWritableStream; + var state = stream._state; + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseResolvedWith(undefined); + } + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + return WritableStreamDefaultWriterClose(writer); + } + function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { + if (writer._closedPromiseState === 'pending') { + defaultWriterClosedPromiseReject(writer, error); + } + else { + defaultWriterClosedPromiseResetToRejected(writer, error); + } + } + function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { + if (writer._readyPromiseState === 'pending') { + defaultWriterReadyPromiseReject(writer, error); + } + else { + defaultWriterReadyPromiseResetToRejected(writer, error); + } + } + function WritableStreamDefaultWriterGetDesiredSize(writer) { + var stream = writer._ownerWritableStream; + var state = stream._state; + if (state === 'errored' || state === 'erroring') { + return null; + } + if (state === 'closed') { + return 0; + } + return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); + } + function WritableStreamDefaultWriterRelease(writer) { + var stream = writer._ownerWritableStream; + var releasedError = new TypeError("Writer was released and can no longer be used to monitor the stream's closedness"); + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); + // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not + // rejected until afterwards. This means that simply testing state will not work. + WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); + stream._writer = undefined; + writer._ownerWritableStream = undefined; + } + function WritableStreamDefaultWriterWrite(writer, chunk) { + var stream = writer._ownerWritableStream; + var controller = stream._writableStreamController; + var chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); + if (stream !== writer._ownerWritableStream) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + var state = stream._state; + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to')); + } + if (state === 'erroring') { + return promiseRejectedWith(stream._storedError); + } + var promise = WritableStreamAddWriteRequest(stream); + WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); + return promise; + } + var closeSentinel = {}; + /** + * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. + * + * @public + */ + var WritableStreamDefaultController = /** @class */ (function () { + function WritableStreamDefaultController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(WritableStreamDefaultController.prototype, "abortReason", { + /** + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. + * + * @deprecated + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. + */ + get: function () { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('abortReason'); + } + return this._abortReason; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(WritableStreamDefaultController.prototype, "signal", { + /** + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. + */ + get: function () { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('signal'); + } + if (this._abortController === undefined) { + // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`. + // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill, + // so instead we only implement support for `signal` if we find a global `AbortController` constructor. + throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported'); + } + return this._abortController.signal; + }, + enumerable: false, + configurable: true + }); + /** + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. + * + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the + * normal lifecycle of interactions with the underlying sink. + */ + WritableStreamDefaultController.prototype.error = function (e) { + if (e === void 0) { e = undefined; } + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('error'); + } + var state = this._controlledWritableStream._state; + if (state !== 'writable') { + // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so + // just treat it as a no-op. + return; + } + WritableStreamDefaultControllerError(this, e); + }; + /** @internal */ + WritableStreamDefaultController.prototype[AbortSteps] = function (reason) { + var result = this._abortAlgorithm(reason); + WritableStreamDefaultControllerClearAlgorithms(this); + return result; + }; + /** @internal */ + WritableStreamDefaultController.prototype[ErrorSteps] = function () { + ResetQueue(this); + }; + return WritableStreamDefaultController; + }()); + Object.defineProperties(WritableStreamDefaultController.prototype, { + abortReason: { enumerable: true }, + signal: { enumerable: true }, + error: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultController', + configurable: true + }); + } + // Abstract operations implementing interface required by the WritableStream. + function IsWritableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultController; + } + function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledWritableStream = stream; + stream._writableStreamController = controller; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._abortReason = undefined; + controller._abortController = createAbortController(); + controller._started = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._writeAlgorithm = writeAlgorithm; + controller._closeAlgorithm = closeAlgorithm; + controller._abortAlgorithm = abortAlgorithm; + var backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + var startResult = startAlgorithm(); + var startPromise = promiseResolvedWith(startResult); + uponPromise(startPromise, function () { + controller._started = true; + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, function (r) { + controller._started = true; + WritableStreamDealWithRejection(stream, r); + return null; + }); + } + function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { + var controller = Object.create(WritableStreamDefaultController.prototype); + var startAlgorithm; + var writeAlgorithm; + var closeAlgorithm; + var abortAlgorithm; + if (underlyingSink.start !== undefined) { + startAlgorithm = function () { return underlyingSink.start(controller); }; + } + else { + startAlgorithm = function () { return undefined; }; + } + if (underlyingSink.write !== undefined) { + writeAlgorithm = function (chunk) { return underlyingSink.write(chunk, controller); }; + } + else { + writeAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + if (underlyingSink.close !== undefined) { + closeAlgorithm = function () { return underlyingSink.close(); }; + } + else { + closeAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + if (underlyingSink.abort !== undefined) { + abortAlgorithm = function (reason) { return underlyingSink.abort(reason); }; + } + else { + abortAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + } + // ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls. + function WritableStreamDefaultControllerClearAlgorithms(controller) { + controller._writeAlgorithm = undefined; + controller._closeAlgorithm = undefined; + controller._abortAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; + } + function WritableStreamDefaultControllerClose(controller) { + EnqueueValueWithSize(controller, closeSentinel, 0); + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + } + function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { + try { + return controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); + return 1; + } + } + function WritableStreamDefaultControllerGetDesiredSize(controller) { + return controller._strategyHWM - controller._queueTotalSize; + } + function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); + return; + } + var stream = controller._controlledWritableStream; + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') { + var backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + } + // Abstract operations for the WritableStreamDefaultController. + function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { + var stream = controller._controlledWritableStream; + if (!controller._started) { + return; + } + if (stream._inFlightWriteRequest !== undefined) { + return; + } + var state = stream._state; + if (state === 'erroring') { + WritableStreamFinishErroring(stream); + return; + } + if (controller._queue.length === 0) { + return; + } + var value = PeekQueueValue(controller); + if (value === closeSentinel) { + WritableStreamDefaultControllerProcessClose(controller); + } + else { + WritableStreamDefaultControllerProcessWrite(controller, value); + } + } + function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { + if (controller._controlledWritableStream._state === 'writable') { + WritableStreamDefaultControllerError(controller, error); + } + } + function WritableStreamDefaultControllerProcessClose(controller) { + var stream = controller._controlledWritableStream; + WritableStreamMarkCloseRequestInFlight(stream); + DequeueValue(controller); + var sinkClosePromise = controller._closeAlgorithm(); + WritableStreamDefaultControllerClearAlgorithms(controller); + uponPromise(sinkClosePromise, function () { + WritableStreamFinishInFlightClose(stream); + return null; + }, function (reason) { + WritableStreamFinishInFlightCloseWithError(stream, reason); + return null; + }); + } + function WritableStreamDefaultControllerProcessWrite(controller, chunk) { + var stream = controller._controlledWritableStream; + WritableStreamMarkFirstWriteRequestInFlight(stream); + var sinkWritePromise = controller._writeAlgorithm(chunk); + uponPromise(sinkWritePromise, function () { + WritableStreamFinishInFlightWrite(stream); + var state = stream._state; + DequeueValue(controller); + if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') { + var backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, function (reason) { + if (stream._state === 'writable') { + WritableStreamDefaultControllerClearAlgorithms(controller); + } + WritableStreamFinishInFlightWriteWithError(stream, reason); + return null; + }); + } + function WritableStreamDefaultControllerGetBackpressure(controller) { + var desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); + return desiredSize <= 0; + } + // A client of WritableStreamDefaultController may use these functions directly to bypass state check. + function WritableStreamDefaultControllerError(controller, error) { + var stream = controller._controlledWritableStream; + WritableStreamDefaultControllerClearAlgorithms(controller); + WritableStreamStartErroring(stream, error); + } + // Helper functions for the WritableStream. + function streamBrandCheckException$2(name) { + return new TypeError("WritableStream.prototype.".concat(name, " can only be used on a WritableStream")); + } + // Helper functions for the WritableStreamDefaultController. + function defaultControllerBrandCheckException$2(name) { + return new TypeError("WritableStreamDefaultController.prototype.".concat(name, " can only be used on a WritableStreamDefaultController")); + } + // Helper functions for the WritableStreamDefaultWriter. + function defaultWriterBrandCheckException(name) { + return new TypeError("WritableStreamDefaultWriter.prototype.".concat(name, " can only be used on a WritableStreamDefaultWriter")); + } + function defaultWriterLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released writer'); + } + function defaultWriterClosedPromiseInitialize(writer) { + writer._closedPromise = newPromise(function (resolve, reject) { + writer._closedPromise_resolve = resolve; + writer._closedPromise_reject = reject; + writer._closedPromiseState = 'pending'; + }); + } + function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseReject(writer, reason); + } + function defaultWriterClosedPromiseInitializeAsResolved(writer) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseResolve(writer); + } + function defaultWriterClosedPromiseReject(writer, reason) { + if (writer._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._closedPromise); + writer._closedPromise_reject(reason); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'rejected'; + } + function defaultWriterClosedPromiseResetToRejected(writer, reason) { + defaultWriterClosedPromiseInitializeAsRejected(writer, reason); + } + function defaultWriterClosedPromiseResolve(writer) { + if (writer._closedPromise_resolve === undefined) { + return; + } + writer._closedPromise_resolve(undefined); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'resolved'; + } + function defaultWriterReadyPromiseInitialize(writer) { + writer._readyPromise = newPromise(function (resolve, reject) { + writer._readyPromise_resolve = resolve; + writer._readyPromise_reject = reject; + }); + writer._readyPromiseState = 'pending'; + } + function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseReject(writer, reason); + } + function defaultWriterReadyPromiseInitializeAsResolved(writer) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseResolve(writer); + } + function defaultWriterReadyPromiseReject(writer, reason) { + if (writer._readyPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._readyPromise); + writer._readyPromise_reject(reason); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'rejected'; + } + function defaultWriterReadyPromiseReset(writer) { + defaultWriterReadyPromiseInitialize(writer); + } + function defaultWriterReadyPromiseResetToRejected(writer, reason) { + defaultWriterReadyPromiseInitializeAsRejected(writer, reason); + } + function defaultWriterReadyPromiseResolve(writer) { + if (writer._readyPromise_resolve === undefined) { + return; + } + writer._readyPromise_resolve(undefined); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'fulfilled'; + } + + /// + function getGlobals() { + if (typeof globalThis !== 'undefined') { + return globalThis; + } + else if (typeof self !== 'undefined') { + return self; + } + else if (typeof global !== 'undefined') { + return global; + } + return undefined; + } + var globals = getGlobals(); + + /// + function isDOMExceptionConstructor(ctor) { + if (!(typeof ctor === 'function' || typeof ctor === 'object')) { + return false; + } + if (ctor.name !== 'DOMException') { + return false; + } + try { + new ctor(); + return true; + } + catch (_a) { + return false; + } + } + /** + * Support: + * - Web browsers + * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87) + */ + function getFromGlobal() { + var ctor = globals === null || globals === void 0 ? void 0 : globals.DOMException; + return isDOMExceptionConstructor(ctor) ? ctor : undefined; + } + /** + * Support: + * - All platforms + */ + function createPolyfill() { + // eslint-disable-next-line @typescript-eslint/no-shadow + var ctor = function DOMException(message, name) { + this.message = message || ''; + this.name = name || 'Error'; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + }; + setFunctionName(ctor, 'DOMException'); + ctor.prototype = Object.create(Error.prototype); + Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true }); + return ctor; + } + // eslint-disable-next-line @typescript-eslint/no-redeclare + var DOMException = getFromGlobal() || createPolyfill(); + + function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { + var reader = AcquireReadableStreamDefaultReader(source); + var writer = AcquireWritableStreamDefaultWriter(dest); + source._disturbed = true; + var shuttingDown = false; + // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown. + var currentWrite = promiseResolvedWith(undefined); + return newPromise(function (resolve, reject) { + var abortAlgorithm; + if (signal !== undefined) { + abortAlgorithm = function () { + var error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError'); + var actions = []; + if (!preventAbort) { + actions.push(function () { + if (dest._state === 'writable') { + return WritableStreamAbort(dest, error); + } + return promiseResolvedWith(undefined); + }); + } + if (!preventCancel) { + actions.push(function () { + if (source._state === 'readable') { + return ReadableStreamCancel(source, error); + } + return promiseResolvedWith(undefined); + }); + } + shutdownWithAction(function () { return Promise.all(actions.map(function (action) { return action(); })); }, true, error); + }; + if (signal.aborted) { + abortAlgorithm(); + return; + } + signal.addEventListener('abort', abortAlgorithm); + } + // Using reader and writer, read all chunks from this and write them to dest + // - Backpressure must be enforced + // - Shutdown must stop all activity + function pipeLoop() { + return newPromise(function (resolveLoop, rejectLoop) { + function next(done) { + if (done) { + resolveLoop(); + } + else { + // Use `PerformPromiseThen` instead of `uponPromise` to avoid + // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers + PerformPromiseThen(pipeStep(), next, rejectLoop); + } + } + next(false); + }); + } + function pipeStep() { + if (shuttingDown) { + return promiseResolvedWith(true); + } + return PerformPromiseThen(writer._readyPromise, function () { + return newPromise(function (resolveRead, rejectRead) { + ReadableStreamDefaultReaderRead(reader, { + _chunkSteps: function (chunk) { + currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop); + resolveRead(false); + }, + _closeSteps: function () { return resolveRead(true); }, + _errorSteps: rejectRead + }); + }); + }); + } + // Errors must be propagated forward + isOrBecomesErrored(source, reader._closedPromise, function (storedError) { + if (!preventAbort) { + shutdownWithAction(function () { return WritableStreamAbort(dest, storedError); }, true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Errors must be propagated backward + isOrBecomesErrored(dest, writer._closedPromise, function (storedError) { + if (!preventCancel) { + shutdownWithAction(function () { return ReadableStreamCancel(source, storedError); }, true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Closing must be propagated forward + isOrBecomesClosed(source, reader._closedPromise, function () { + if (!preventClose) { + shutdownWithAction(function () { return WritableStreamDefaultWriterCloseWithErrorPropagation(writer); }); + } + else { + shutdown(); + } + return null; + }); + // Closing must be propagated backward + if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') { + var destClosed_1 = new TypeError('the destination writable stream closed before all data could be piped to it'); + if (!preventCancel) { + shutdownWithAction(function () { return ReadableStreamCancel(source, destClosed_1); }, true, destClosed_1); + } + else { + shutdown(true, destClosed_1); + } + } + setPromiseIsHandledToTrue(pipeLoop()); + function waitForWritesToFinish() { + // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait + // for that too. + var oldCurrentWrite = currentWrite; + return PerformPromiseThen(currentWrite, function () { return oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined; }); + } + function isOrBecomesErrored(stream, promise, action) { + if (stream._state === 'errored') { + action(stream._storedError); + } + else { + uponRejection(promise, action); + } + } + function isOrBecomesClosed(stream, promise, action) { + if (stream._state === 'closed') { + action(); + } + else { + uponFulfillment(promise, action); + } + } + function shutdownWithAction(action, originalIsError, originalError) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), doTheRest); + } + else { + doTheRest(); + } + function doTheRest() { + uponPromise(action(), function () { return finalize(originalIsError, originalError); }, function (newError) { return finalize(true, newError); }); + return null; + } + } + function shutdown(isError, error) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), function () { return finalize(isError, error); }); + } + else { + finalize(isError, error); + } + } + function finalize(isError, error) { + WritableStreamDefaultWriterRelease(writer); + ReadableStreamReaderGenericRelease(reader); + if (signal !== undefined) { + signal.removeEventListener('abort', abortAlgorithm); + } + if (isError) { + reject(error); + } + else { + resolve(undefined); + } + return null; + } + }); + } + + /** + * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. + * + * @public + */ + var ReadableStreamDefaultController = /** @class */ (function () { + function ReadableStreamDefaultController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(ReadableStreamDefaultController.prototype, "desiredSize", { + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + */ + get: function () { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('desiredSize'); + } + return ReadableStreamDefaultControllerGetDesiredSize(this); + }, + enumerable: false, + configurable: true + }); + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + ReadableStreamDefaultController.prototype.close = function () { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('close'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits close'); + } + ReadableStreamDefaultControllerClose(this); + }; + ReadableStreamDefaultController.prototype.enqueue = function (chunk) { + if (chunk === void 0) { chunk = undefined; } + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('enqueue'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits enqueue'); + } + return ReadableStreamDefaultControllerEnqueue(this, chunk); + }; + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + ReadableStreamDefaultController.prototype.error = function (e) { + if (e === void 0) { e = undefined; } + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('error'); + } + ReadableStreamDefaultControllerError(this, e); + }; + /** @internal */ + ReadableStreamDefaultController.prototype[CancelSteps] = function (reason) { + ResetQueue(this); + var result = this._cancelAlgorithm(reason); + ReadableStreamDefaultControllerClearAlgorithms(this); + return result; + }; + /** @internal */ + ReadableStreamDefaultController.prototype[PullSteps] = function (readRequest) { + var stream = this._controlledReadableStream; + if (this._queue.length > 0) { + var chunk = DequeueValue(this); + if (this._closeRequested && this._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(this); + ReadableStreamClose(stream); + } + else { + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + readRequest._chunkSteps(chunk); + } + else { + ReadableStreamAddReadRequest(stream, readRequest); + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + }; + /** @internal */ + ReadableStreamDefaultController.prototype[ReleaseSteps] = function () { + // Do nothing. + }; + return ReadableStreamDefaultController; + }()); + Object.defineProperties(ReadableStreamDefaultController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + desiredSize: { enumerable: true } + }); + setFunctionName(ReadableStreamDefaultController.prototype.close, 'close'); + setFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue'); + setFunctionName(ReadableStreamDefaultController.prototype.error, 'error'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultController', + configurable: true + }); + } + // Abstract operations for the ReadableStreamDefaultController. + function IsReadableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) { + return false; + } + return x instanceof ReadableStreamDefaultController; + } + function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { + var shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + var pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, function () { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + return null; + }, function (e) { + ReadableStreamDefaultControllerError(controller, e); + return null; + }); + } + function ReadableStreamDefaultControllerShouldCallPull(controller) { + var stream = controller._controlledReadableStream; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return false; + } + if (!controller._started) { + return false; + } + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + var desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; + } + function ReadableStreamDefaultControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; + } + // A client of ReadableStreamDefaultController may use these functions directly to bypass state check. + function ReadableStreamDefaultControllerClose(controller) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + var stream = controller._controlledReadableStream; + controller._closeRequested = true; + if (controller._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } + } + function ReadableStreamDefaultControllerEnqueue(controller, chunk) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + var stream = controller._controlledReadableStream; + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + ReadableStreamFulfillReadRequest(stream, chunk, false); + } + else { + var chunkSize = void 0; + try { + chunkSize = controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + ReadableStreamDefaultControllerError(controller, chunkSizeE); + throw chunkSizeE; + } + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + ReadableStreamDefaultControllerError(controller, enqueueE); + throw enqueueE; + } + } + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + function ReadableStreamDefaultControllerError(controller, e) { + var stream = controller._controlledReadableStream; + if (stream._state !== 'readable') { + return; + } + ResetQueue(controller); + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); + } + function ReadableStreamDefaultControllerGetDesiredSize(controller) { + var state = controller._controlledReadableStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; + } + // This is used in the implementation of TransformStream. + function ReadableStreamDefaultControllerHasBackpressure(controller) { + if (ReadableStreamDefaultControllerShouldCallPull(controller)) { + return false; + } + return true; + } + function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { + var state = controller._controlledReadableStream._state; + if (!controller._closeRequested && state === 'readable') { + return true; + } + return false; + } + function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledReadableStream = stream; + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._started = false; + controller._closeRequested = false; + controller._pullAgain = false; + controller._pulling = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + stream._readableStreamController = controller; + var startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), function () { + controller._started = true; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + return null; + }, function (r) { + ReadableStreamDefaultControllerError(controller, r); + return null; + }); + } + function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { + var controller = Object.create(ReadableStreamDefaultController.prototype); + var startAlgorithm; + var pullAlgorithm; + var cancelAlgorithm; + if (underlyingSource.start !== undefined) { + startAlgorithm = function () { return underlyingSource.start(controller); }; + } + else { + startAlgorithm = function () { return undefined; }; + } + if (underlyingSource.pull !== undefined) { + pullAlgorithm = function () { return underlyingSource.pull(controller); }; + } + else { + pullAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + if (underlyingSource.cancel !== undefined) { + cancelAlgorithm = function (reason) { return underlyingSource.cancel(reason); }; + } + else { + cancelAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + } + // Helper functions for the ReadableStreamDefaultController. + function defaultControllerBrandCheckException$1(name) { + return new TypeError("ReadableStreamDefaultController.prototype.".concat(name, " can only be used on a ReadableStreamDefaultController")); + } + + function ReadableStreamTee(stream, cloneForBranch2) { + if (IsReadableByteStreamController(stream._readableStreamController)) { + return ReadableByteStreamTee(stream); + } + return ReadableStreamDefaultTee(stream); + } + function ReadableStreamDefaultTee(stream, cloneForBranch2) { + var reader = AcquireReadableStreamDefaultReader(stream); + var reading = false; + var readAgain = false; + var canceled1 = false; + var canceled2 = false; + var reason1; + var reason2; + var branch1; + var branch2; + var resolveCancelPromise; + var cancelPromise = newPromise(function (resolve) { + resolveCancelPromise = resolve; + }); + function pullAlgorithm() { + if (reading) { + readAgain = true; + return promiseResolvedWith(undefined); + } + reading = true; + var readRequest = { + _chunkSteps: function (chunk) { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(function () { + readAgain = false; + var chunk1 = chunk; + var chunk2 = chunk; + // There is no way to access the cloning code right now in the reference implementation. + // If we add one then we'll need an implementation for serializable objects. + // if (!canceled2 && cloneForBranch2) { + // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2)); + // } + if (!canceled1) { + ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgain) { + pullAlgorithm(); + } + }); + }, + _closeSteps: function () { + reading = false; + if (!canceled1) { + ReadableStreamDefaultControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableStreamDefaultControllerClose(branch2._readableStreamController); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: function () { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + // do nothing + } + branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); + branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); + uponRejection(reader._closedPromise, function (r) { + ReadableStreamDefaultControllerError(branch1._readableStreamController, r); + ReadableStreamDefaultControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + return [branch1, branch2]; + } + function ReadableByteStreamTee(stream) { + var reader = AcquireReadableStreamDefaultReader(stream); + var reading = false; + var readAgainForBranch1 = false; + var readAgainForBranch2 = false; + var canceled1 = false; + var canceled2 = false; + var reason1; + var reason2; + var branch1; + var branch2; + var resolveCancelPromise; + var cancelPromise = newPromise(function (resolve) { + resolveCancelPromise = resolve; + }); + function forwardReaderError(thisReader) { + uponRejection(thisReader._closedPromise, function (r) { + if (thisReader !== reader) { + return null; + } + ReadableByteStreamControllerError(branch1._readableStreamController, r); + ReadableByteStreamControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + } + function pullWithDefaultReader() { + if (IsReadableStreamBYOBReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamDefaultReader(stream); + forwardReaderError(reader); + } + var readRequest = { + _chunkSteps: function (chunk) { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(function () { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + var chunk1 = chunk; + var chunk2 = chunk; + if (!canceled1 && !canceled2) { + try { + chunk2 = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(branch1._readableStreamController, cloneE); + ReadableByteStreamControllerError(branch2._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + } + if (!canceled1) { + ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: function () { + reading = false; + if (!canceled1) { + ReadableByteStreamControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableByteStreamControllerClose(branch2._readableStreamController); + } + if (branch1._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch1._readableStreamController, 0); + } + if (branch2._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch2._readableStreamController, 0); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: function () { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + } + function pullWithBYOBReader(view, forBranch2) { + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamBYOBReader(stream); + forwardReaderError(reader); + } + var byobBranch = forBranch2 ? branch2 : branch1; + var otherBranch = forBranch2 ? branch1 : branch2; + var readIntoRequest = { + _chunkSteps: function (chunk) { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(function () { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + var byobCanceled = forBranch2 ? canceled2 : canceled1; + var otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!otherCanceled) { + var clonedChunk = void 0; + try { + clonedChunk = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE); + ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk); + } + else if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: function (chunk) { + reading = false; + var byobCanceled = forBranch2 ? canceled2 : canceled1; + var otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!byobCanceled) { + ReadableByteStreamControllerClose(byobBranch._readableStreamController); + } + if (!otherCanceled) { + ReadableByteStreamControllerClose(otherBranch._readableStreamController); + } + if (chunk !== undefined) { + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0); + } + } + if (!byobCanceled || !otherCanceled) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: function () { + reading = false; + } + }; + ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest); + } + function pull1Algorithm() { + if (reading) { + readAgainForBranch1 = true; + return promiseResolvedWith(undefined); + } + reading = true; + var byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, false); + } + return promiseResolvedWith(undefined); + } + function pull2Algorithm() { + if (reading) { + readAgainForBranch2 = true; + return promiseResolvedWith(undefined); + } + reading = true; + var byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, true); + } + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + return; + } + branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm); + branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm); + forwardReaderError(reader); + return [branch1, branch2]; + } + + function isReadableStreamLike(stream) { + return typeIsObject(stream) && typeof stream.getReader !== 'undefined'; + } + + function ReadableStreamFrom(source) { + if (isReadableStreamLike(source)) { + return ReadableStreamFromDefaultReader(source.getReader()); + } + return ReadableStreamFromIterable(source); + } + function ReadableStreamFromIterable(asyncIterable) { + var stream; + var iteratorRecord = GetIterator(asyncIterable, 'async'); + var startAlgorithm = noop; + function pullAlgorithm() { + var nextResult; + try { + nextResult = IteratorNext(iteratorRecord); + } + catch (e) { + return promiseRejectedWith(e); + } + var nextPromise = promiseResolvedWith(nextResult); + return transformPromiseWith(nextPromise, function (iterResult) { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object'); + } + var done = IteratorComplete(iterResult); + if (done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + var value = IteratorValue(iterResult); + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + var iterator = iteratorRecord.iterator; + var returnMethod; + try { + returnMethod = GetMethod(iterator, 'return'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (returnMethod === undefined) { + return promiseResolvedWith(undefined); + } + var returnResult; + try { + returnResult = reflectCall(returnMethod, iterator, [reason]); + } + catch (e) { + return promiseRejectedWith(e); + } + var returnPromise = promiseResolvedWith(returnResult); + return transformPromiseWith(returnPromise, function (iterResult) { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object'); + } + return undefined; + }); + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; + } + function ReadableStreamFromDefaultReader(reader) { + var stream; + var startAlgorithm = noop; + function pullAlgorithm() { + var readPromise; + try { + readPromise = reader.read(); + } + catch (e) { + return promiseRejectedWith(e); + } + return transformPromiseWith(readPromise, function (readResult) { + if (!typeIsObject(readResult)) { + throw new TypeError('The promise returned by the reader.read() method must fulfill with an object'); + } + if (readResult.done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + var value = readResult.value; + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + try { + return promiseResolvedWith(reader.cancel(reason)); + } + catch (e) { + return promiseRejectedWith(e); + } + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; + } + + function convertUnderlyingDefaultOrByteSource(source, context) { + assertDictionary(source, context); + var original = source; + var autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; + var cancel = original === null || original === void 0 ? void 0 : original.cancel; + var pull = original === null || original === void 0 ? void 0 : original.pull; + var start = original === null || original === void 0 ? void 0 : original.start; + var type = original === null || original === void 0 ? void 0 : original.type; + return { + autoAllocateChunkSize: autoAllocateChunkSize === undefined ? + undefined : + convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, "".concat(context, " has member 'autoAllocateChunkSize' that")), + cancel: cancel === undefined ? + undefined : + convertUnderlyingSourceCancelCallback(cancel, original, "".concat(context, " has member 'cancel' that")), + pull: pull === undefined ? + undefined : + convertUnderlyingSourcePullCallback(pull, original, "".concat(context, " has member 'pull' that")), + start: start === undefined ? + undefined : + convertUnderlyingSourceStartCallback(start, original, "".concat(context, " has member 'start' that")), + type: type === undefined ? undefined : convertReadableStreamType(type, "".concat(context, " has member 'type' that")) + }; + } + function convertUnderlyingSourceCancelCallback(fn, original, context) { + assertFunction(fn, context); + return function (reason) { return promiseCall(fn, original, [reason]); }; + } + function convertUnderlyingSourcePullCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return promiseCall(fn, original, [controller]); }; + } + function convertUnderlyingSourceStartCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return reflectCall(fn, original, [controller]); }; + } + function convertReadableStreamType(type, context) { + type = "".concat(type); + if (type !== 'bytes') { + throw new TypeError("".concat(context, " '").concat(type, "' is not a valid enumeration value for ReadableStreamType")); + } + return type; + } + + function convertIteratorOptions(options, context) { + assertDictionary(options, context); + var preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + return { preventCancel: Boolean(preventCancel) }; + } + + function convertPipeOptions(options, context) { + assertDictionary(options, context); + var preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort; + var preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + var preventClose = options === null || options === void 0 ? void 0 : options.preventClose; + var signal = options === null || options === void 0 ? void 0 : options.signal; + if (signal !== undefined) { + assertAbortSignal(signal, "".concat(context, " has member 'signal' that")); + } + return { + preventAbort: Boolean(preventAbort), + preventCancel: Boolean(preventCancel), + preventClose: Boolean(preventClose), + signal: signal + }; + } + function assertAbortSignal(signal, context) { + if (!isAbortSignal(signal)) { + throw new TypeError("".concat(context, " is not an AbortSignal.")); + } + } + + function convertReadableWritablePair(pair, context) { + assertDictionary(pair, context); + var readable = pair === null || pair === void 0 ? void 0 : pair.readable; + assertRequiredField(readable, 'readable', 'ReadableWritablePair'); + assertReadableStream(readable, "".concat(context, " has member 'readable' that")); + var writable = pair === null || pair === void 0 ? void 0 : pair.writable; + assertRequiredField(writable, 'writable', 'ReadableWritablePair'); + assertWritableStream(writable, "".concat(context, " has member 'writable' that")); + return { readable: readable, writable: writable }; + } + + /** + * A readable stream represents a source of data, from which you can read. + * + * @public + */ + var ReadableStream = /** @class */ (function () { + function ReadableStream(rawUnderlyingSource, rawStrategy) { + if (rawUnderlyingSource === void 0) { rawUnderlyingSource = {}; } + if (rawStrategy === void 0) { rawStrategy = {}; } + if (rawUnderlyingSource === undefined) { + rawUnderlyingSource = null; + } + else { + assertObject(rawUnderlyingSource, 'First parameter'); + } + var strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + var underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter'); + InitializeReadableStream(this); + if (underlyingSource.type === 'bytes') { + if (strategy.size !== undefined) { + throw new RangeError('The strategy for a byte stream cannot have a size function'); + } + var highWaterMark = ExtractHighWaterMark(strategy, 0); + SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); + } + else { + var sizeAlgorithm = ExtractSizeAlgorithm(strategy); + var highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); + } + } + Object.defineProperty(ReadableStream.prototype, "locked", { + /** + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. + */ + get: function () { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('locked'); + } + return IsReadableStreamLocked(this); + }, + enumerable: false, + configurable: true + }); + /** + * Cancels the stream, signaling a loss of interest in the stream by a consumer. + * + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} + * method, which might or might not use it. + */ + ReadableStream.prototype.cancel = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('cancel')); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader')); + } + return ReadableStreamCancel(this, reason); + }; + ReadableStream.prototype.getReader = function (rawOptions) { + if (rawOptions === void 0) { rawOptions = undefined; } + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('getReader'); + } + var options = convertReaderOptions(rawOptions, 'First parameter'); + if (options.mode === undefined) { + return AcquireReadableStreamDefaultReader(this); + } + return AcquireReadableStreamBYOBReader(this); + }; + ReadableStream.prototype.pipeThrough = function (rawTransform, rawOptions) { + if (rawOptions === void 0) { rawOptions = {}; } + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('pipeThrough'); + } + assertRequiredArgument(rawTransform, 1, 'pipeThrough'); + var transform = convertReadableWritablePair(rawTransform, 'First parameter'); + var options = convertPipeOptions(rawOptions, 'Second parameter'); + if (IsReadableStreamLocked(this)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream'); + } + if (IsWritableStreamLocked(transform.writable)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream'); + } + var promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + setPromiseIsHandledToTrue(promise); + return transform.readable; + }; + ReadableStream.prototype.pipeTo = function (destination, rawOptions) { + if (rawOptions === void 0) { rawOptions = {}; } + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('pipeTo')); + } + if (destination === undefined) { + return promiseRejectedWith("Parameter 1 is required in 'pipeTo'."); + } + if (!IsWritableStream(destination)) { + return promiseRejectedWith(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream")); + } + var options; + try { + options = convertPipeOptions(rawOptions, 'Second parameter'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')); + } + if (IsWritableStreamLocked(destination)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')); + } + return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + }; + /** + * Tees this readable stream, returning a two-element array containing the two resulting branches as + * new {@link ReadableStream} instances. + * + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be + * propagated to the stream's underlying source. + * + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, + * this could allow interference between the two branches. + */ + ReadableStream.prototype.tee = function () { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('tee'); + } + var branches = ReadableStreamTee(this); + return CreateArrayFromList(branches); + }; + ReadableStream.prototype.values = function (rawOptions) { + if (rawOptions === void 0) { rawOptions = undefined; } + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('values'); + } + var options = convertIteratorOptions(rawOptions, 'First parameter'); + return AcquireReadableStreamAsyncIterator(this, options.preventCancel); + }; + ReadableStream.prototype[SymbolAsyncIterator] = function (options) { + // Stub implementation, overridden below + return this.values(options); + }; + /** + * Creates a new ReadableStream wrapping the provided iterable or async iterable. + * + * This can be used to adapt various kinds of objects into a readable stream, + * such as an array, an async generator, or a Node.js readable stream. + */ + ReadableStream.from = function (asyncIterable) { + return ReadableStreamFrom(asyncIterable); + }; + return ReadableStream; + }()); + Object.defineProperties(ReadableStream, { + from: { enumerable: true } + }); + Object.defineProperties(ReadableStream.prototype, { + cancel: { enumerable: true }, + getReader: { enumerable: true }, + pipeThrough: { enumerable: true }, + pipeTo: { enumerable: true }, + tee: { enumerable: true }, + values: { enumerable: true }, + locked: { enumerable: true } + }); + setFunctionName(ReadableStream.from, 'from'); + setFunctionName(ReadableStream.prototype.cancel, 'cancel'); + setFunctionName(ReadableStream.prototype.getReader, 'getReader'); + setFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough'); + setFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo'); + setFunctionName(ReadableStream.prototype.tee, 'tee'); + setFunctionName(ReadableStream.prototype.values, 'values'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStream', + configurable: true + }); + } + Object.defineProperty(ReadableStream.prototype, SymbolAsyncIterator, { + value: ReadableStream.prototype.values, + writable: true, + configurable: true + }); + // Abstract operations for the ReadableStream. + // Throws if and only if startAlgorithm throws. + function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + if (highWaterMark === void 0) { highWaterMark = 1; } + if (sizeAlgorithm === void 0) { sizeAlgorithm = function () { return 1; }; } + var stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + var controller = Object.create(ReadableStreamDefaultController.prototype); + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + return stream; + } + // Throws if and only if startAlgorithm throws. + function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) { + var stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + var controller = Object.create(ReadableByteStreamController.prototype); + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined); + return stream; + } + function InitializeReadableStream(stream) { + stream._state = 'readable'; + stream._reader = undefined; + stream._storedError = undefined; + stream._disturbed = false; + } + function IsReadableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) { + return false; + } + return x instanceof ReadableStream; + } + function IsReadableStreamLocked(stream) { + if (stream._reader === undefined) { + return false; + } + return true; + } + // ReadableStream API exposed for controllers. + function ReadableStreamCancel(stream, reason) { + stream._disturbed = true; + if (stream._state === 'closed') { + return promiseResolvedWith(undefined); + } + if (stream._state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + ReadableStreamClose(stream); + var reader = stream._reader; + if (reader !== undefined && IsReadableStreamBYOBReader(reader)) { + var readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(function (readIntoRequest) { + readIntoRequest._closeSteps(undefined); + }); + } + var sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); + return transformPromiseWith(sourceCancelPromise, noop); + } + function ReadableStreamClose(stream) { + stream._state = 'closed'; + var reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseResolve(reader); + if (IsReadableStreamDefaultReader(reader)) { + var readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(function (readRequest) { + readRequest._closeSteps(); + }); + } + } + function ReadableStreamError(stream, e) { + stream._state = 'errored'; + stream._storedError = e; + var reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseReject(reader, e); + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamDefaultReaderErrorReadRequests(reader, e); + } + else { + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); + } + } + // Helper functions for the ReadableStream. + function streamBrandCheckException$1(name) { + return new TypeError("ReadableStream.prototype.".concat(name, " can only be used on a ReadableStream")); + } + + function convertQueuingStrategyInit(init, context) { + assertDictionary(init, context); + var highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit'); + return { + highWaterMark: convertUnrestrictedDouble(highWaterMark) + }; + } + + // The size function must not have a prototype property nor be a constructor + var byteLengthSizeFunction = function (chunk) { + return chunk.byteLength; + }; + setFunctionName(byteLengthSizeFunction, 'size'); + /** + * A queuing strategy that counts the number of bytes in each chunk. + * + * @public + */ + var ByteLengthQueuingStrategy = /** @class */ (function () { + function ByteLengthQueuingStrategy(options) { + assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; + } + Object.defineProperty(ByteLengthQueuingStrategy.prototype, "highWaterMark", { + /** + * Returns the high water mark provided to the constructor. + */ + get: function () { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('highWaterMark'); + } + return this._byteLengthQueuingStrategyHighWaterMark; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ByteLengthQueuingStrategy.prototype, "size", { + /** + * Measures the size of `chunk` by returning the value of its `byteLength` property. + */ + get: function () { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('size'); + } + return byteLengthSizeFunction; + }, + enumerable: false, + configurable: true + }); + return ByteLengthQueuingStrategy; + }()); + Object.defineProperties(ByteLengthQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ByteLengthQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'ByteLengthQueuingStrategy', + configurable: true + }); + } + // Helper functions for the ByteLengthQueuingStrategy. + function byteLengthBrandCheckException(name) { + return new TypeError("ByteLengthQueuingStrategy.prototype.".concat(name, " can only be used on a ByteLengthQueuingStrategy")); + } + function IsByteLengthQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof ByteLengthQueuingStrategy; + } + + // The size function must not have a prototype property nor be a constructor + var countSizeFunction = function () { + return 1; + }; + setFunctionName(countSizeFunction, 'size'); + /** + * A queuing strategy that counts the number of chunks. + * + * @public + */ + var CountQueuingStrategy = /** @class */ (function () { + function CountQueuingStrategy(options) { + assertRequiredArgument(options, 1, 'CountQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._countQueuingStrategyHighWaterMark = options.highWaterMark; + } + Object.defineProperty(CountQueuingStrategy.prototype, "highWaterMark", { + /** + * Returns the high water mark provided to the constructor. + */ + get: function () { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('highWaterMark'); + } + return this._countQueuingStrategyHighWaterMark; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(CountQueuingStrategy.prototype, "size", { + /** + * Measures the size of `chunk` by always returning 1. + * This ensures that the total queue size is a count of the number of chunks in the queue. + */ + get: function () { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('size'); + } + return countSizeFunction; + }, + enumerable: false, + configurable: true + }); + return CountQueuingStrategy; + }()); + Object.defineProperties(CountQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(CountQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'CountQueuingStrategy', + configurable: true + }); + } + // Helper functions for the CountQueuingStrategy. + function countBrandCheckException(name) { + return new TypeError("CountQueuingStrategy.prototype.".concat(name, " can only be used on a CountQueuingStrategy")); + } + function IsCountQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof CountQueuingStrategy; + } + + function convertTransformer(original, context) { + assertDictionary(original, context); + var cancel = original === null || original === void 0 ? void 0 : original.cancel; + var flush = original === null || original === void 0 ? void 0 : original.flush; + var readableType = original === null || original === void 0 ? void 0 : original.readableType; + var start = original === null || original === void 0 ? void 0 : original.start; + var transform = original === null || original === void 0 ? void 0 : original.transform; + var writableType = original === null || original === void 0 ? void 0 : original.writableType; + return { + cancel: cancel === undefined ? + undefined : + convertTransformerCancelCallback(cancel, original, "".concat(context, " has member 'cancel' that")), + flush: flush === undefined ? + undefined : + convertTransformerFlushCallback(flush, original, "".concat(context, " has member 'flush' that")), + readableType: readableType, + start: start === undefined ? + undefined : + convertTransformerStartCallback(start, original, "".concat(context, " has member 'start' that")), + transform: transform === undefined ? + undefined : + convertTransformerTransformCallback(transform, original, "".concat(context, " has member 'transform' that")), + writableType: writableType + }; + } + function convertTransformerFlushCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return promiseCall(fn, original, [controller]); }; + } + function convertTransformerStartCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return reflectCall(fn, original, [controller]); }; + } + function convertTransformerTransformCallback(fn, original, context) { + assertFunction(fn, context); + return function (chunk, controller) { return promiseCall(fn, original, [chunk, controller]); }; + } + function convertTransformerCancelCallback(fn, original, context) { + assertFunction(fn, context); + return function (reason) { return promiseCall(fn, original, [reason]); }; + } + + // Class TransformStream + /** + * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, + * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. + * In a manner specific to the transform stream in question, writes to the writable side result in new data being + * made available for reading from the readable side. + * + * @public + */ + var TransformStream = /** @class */ (function () { + function TransformStream(rawTransformer, rawWritableStrategy, rawReadableStrategy) { + if (rawTransformer === void 0) { rawTransformer = {}; } + if (rawWritableStrategy === void 0) { rawWritableStrategy = {}; } + if (rawReadableStrategy === void 0) { rawReadableStrategy = {}; } + if (rawTransformer === undefined) { + rawTransformer = null; + } + var writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter'); + var readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter'); + var transformer = convertTransformer(rawTransformer, 'First parameter'); + if (transformer.readableType !== undefined) { + throw new RangeError('Invalid readableType specified'); + } + if (transformer.writableType !== undefined) { + throw new RangeError('Invalid writableType specified'); + } + var readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); + var readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); + var writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); + var writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); + var startPromise_resolve; + var startPromise = newPromise(function (resolve) { + startPromise_resolve = resolve; + }); + InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); + if (transformer.start !== undefined) { + startPromise_resolve(transformer.start(this._transformStreamController)); + } + else { + startPromise_resolve(undefined); + } + } + Object.defineProperty(TransformStream.prototype, "readable", { + /** + * The readable side of the transform stream. + */ + get: function () { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('readable'); + } + return this._readable; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TransformStream.prototype, "writable", { + /** + * The writable side of the transform stream. + */ + get: function () { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('writable'); + } + return this._writable; + }, + enumerable: false, + configurable: true + }); + return TransformStream; + }()); + Object.defineProperties(TransformStream.prototype, { + readable: { enumerable: true }, + writable: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStream.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStream', + configurable: true + }); + } + function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { + function startAlgorithm() { + return startPromise; + } + function writeAlgorithm(chunk) { + return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); + } + function abortAlgorithm(reason) { + return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); + } + function closeAlgorithm() { + return TransformStreamDefaultSinkCloseAlgorithm(stream); + } + stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); + function pullAlgorithm() { + return TransformStreamDefaultSourcePullAlgorithm(stream); + } + function cancelAlgorithm(reason) { + return TransformStreamDefaultSourceCancelAlgorithm(stream, reason); + } + stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure. + stream._backpressure = undefined; + stream._backpressureChangePromise = undefined; + stream._backpressureChangePromise_resolve = undefined; + TransformStreamSetBackpressure(stream, true); + stream._transformStreamController = undefined; + } + function IsTransformStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) { + return false; + } + return x instanceof TransformStream; + } + // This is a no-op if both sides are already errored. + function TransformStreamError(stream, e) { + ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e); + TransformStreamErrorWritableAndUnblockWrite(stream, e); + } + function TransformStreamErrorWritableAndUnblockWrite(stream, e) { + TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); + WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e); + TransformStreamUnblockWrite(stream); + } + function TransformStreamUnblockWrite(stream) { + if (stream._backpressure) { + // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure() + // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time + // _backpressure is set. + TransformStreamSetBackpressure(stream, false); + } + } + function TransformStreamSetBackpressure(stream, backpressure) { + // Passes also when called during construction. + if (stream._backpressureChangePromise !== undefined) { + stream._backpressureChangePromise_resolve(); + } + stream._backpressureChangePromise = newPromise(function (resolve) { + stream._backpressureChangePromise_resolve = resolve; + }); + stream._backpressure = backpressure; + } + // Class TransformStreamDefaultController + /** + * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. + * + * @public + */ + var TransformStreamDefaultController = /** @class */ (function () { + function TransformStreamDefaultController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(TransformStreamDefaultController.prototype, "desiredSize", { + /** + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. + */ + get: function () { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('desiredSize'); + } + var readableController = this._controlledTransformStream._readable._readableStreamController; + return ReadableStreamDefaultControllerGetDesiredSize(readableController); + }, + enumerable: false, + configurable: true + }); + TransformStreamDefaultController.prototype.enqueue = function (chunk) { + if (chunk === void 0) { chunk = undefined; } + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('enqueue'); + } + TransformStreamDefaultControllerEnqueue(this, chunk); + }; + /** + * Errors both the readable side and the writable side of the controlled transform stream, making all future + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. + */ + TransformStreamDefaultController.prototype.error = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('error'); + } + TransformStreamDefaultControllerError(this, reason); + }; + /** + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the + * transformer only needs to consume a portion of the chunks written to the writable side. + */ + TransformStreamDefaultController.prototype.terminate = function () { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('terminate'); + } + TransformStreamDefaultControllerTerminate(this); + }; + return TransformStreamDefaultController; + }()); + Object.defineProperties(TransformStreamDefaultController.prototype, { + enqueue: { enumerable: true }, + error: { enumerable: true }, + terminate: { enumerable: true }, + desiredSize: { enumerable: true } + }); + setFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue'); + setFunctionName(TransformStreamDefaultController.prototype.error, 'error'); + setFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStreamDefaultController', + configurable: true + }); + } + // Transform Stream Default Controller Abstract Operations + function IsTransformStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) { + return false; + } + return x instanceof TransformStreamDefaultController; + } + function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm) { + controller._controlledTransformStream = stream; + stream._transformStreamController = controller; + controller._transformAlgorithm = transformAlgorithm; + controller._flushAlgorithm = flushAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._finishPromise = undefined; + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; + } + function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { + var controller = Object.create(TransformStreamDefaultController.prototype); + var transformAlgorithm; + var flushAlgorithm; + var cancelAlgorithm; + if (transformer.transform !== undefined) { + transformAlgorithm = function (chunk) { return transformer.transform(chunk, controller); }; + } + else { + transformAlgorithm = function (chunk) { + try { + TransformStreamDefaultControllerEnqueue(controller, chunk); + return promiseResolvedWith(undefined); + } + catch (transformResultE) { + return promiseRejectedWith(transformResultE); + } + }; + } + if (transformer.flush !== undefined) { + flushAlgorithm = function () { return transformer.flush(controller); }; + } + else { + flushAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + if (transformer.cancel !== undefined) { + cancelAlgorithm = function (reason) { return transformer.cancel(reason); }; + } + else { + cancelAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm); + } + function TransformStreamDefaultControllerClearAlgorithms(controller) { + controller._transformAlgorithm = undefined; + controller._flushAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + } + function TransformStreamDefaultControllerEnqueue(controller, chunk) { + var stream = controller._controlledTransformStream; + var readableController = stream._readable._readableStreamController; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { + throw new TypeError('Readable side is not in a state that permits enqueue'); + } + // We throttle transform invocations based on the backpressure of the ReadableStream, but we still + // accept TransformStreamDefaultControllerEnqueue() calls. + try { + ReadableStreamDefaultControllerEnqueue(readableController, chunk); + } + catch (e) { + // This happens when readableStrategy.size() throws. + TransformStreamErrorWritableAndUnblockWrite(stream, e); + throw stream._readable._storedError; + } + var backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); + if (backpressure !== stream._backpressure) { + TransformStreamSetBackpressure(stream, true); + } + } + function TransformStreamDefaultControllerError(controller, e) { + TransformStreamError(controller._controlledTransformStream, e); + } + function TransformStreamDefaultControllerPerformTransform(controller, chunk) { + var transformPromise = controller._transformAlgorithm(chunk); + return transformPromiseWith(transformPromise, undefined, function (r) { + TransformStreamError(controller._controlledTransformStream, r); + throw r; + }); + } + function TransformStreamDefaultControllerTerminate(controller) { + var stream = controller._controlledTransformStream; + var readableController = stream._readable._readableStreamController; + ReadableStreamDefaultControllerClose(readableController); + var error = new TypeError('TransformStream terminated'); + TransformStreamErrorWritableAndUnblockWrite(stream, error); + } + // TransformStreamDefaultSink Algorithms + function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { + var controller = stream._transformStreamController; + if (stream._backpressure) { + var backpressureChangePromise = stream._backpressureChangePromise; + return transformPromiseWith(backpressureChangePromise, function () { + var writable = stream._writable; + var state = writable._state; + if (state === 'erroring') { + throw writable._storedError; + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + }); + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + } + function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { + var controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + var readable = stream._readable; + // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally, + // we don't run the _cancelAlgorithm again. + controller._finishPromise = newPromise(function (resolve, reject) { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + var cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, function () { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerError(readable._readableStreamController, reason); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, function (r) { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; + } + function TransformStreamDefaultSinkCloseAlgorithm(stream) { + var controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + var readable = stream._readable; + // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally, + // we don't also run the _cancelAlgorithm. + controller._finishPromise = newPromise(function (resolve, reject) { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + var flushPromise = controller._flushAlgorithm(); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(flushPromise, function () { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerClose(readable._readableStreamController); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, function (r) { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; + } + // TransformStreamDefaultSource Algorithms + function TransformStreamDefaultSourcePullAlgorithm(stream) { + // Invariant. Enforced by the promises returned by start() and pull(). + TransformStreamSetBackpressure(stream, false); + // Prevent the next pull() call until there is backpressure. + return stream._backpressureChangePromise; + } + function TransformStreamDefaultSourceCancelAlgorithm(stream, reason) { + var controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._writable cannot change after construction, so caching it across a call to user code is safe. + var writable = stream._writable; + // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or + // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the + // _flushAlgorithm. + controller._finishPromise = newPromise(function (resolve, reject) { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + var cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, function () { + if (writable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, writable._storedError); + } + else { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, function (r) { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; + } + // Helper functions for the TransformStreamDefaultController. + function defaultControllerBrandCheckException(name) { + return new TypeError("TransformStreamDefaultController.prototype.".concat(name, " can only be used on a TransformStreamDefaultController")); + } + function defaultControllerFinishPromiseResolve(controller) { + if (controller._finishPromise_resolve === undefined) { + return; + } + controller._finishPromise_resolve(); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; + } + function defaultControllerFinishPromiseReject(controller, reason) { + if (controller._finishPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(controller._finishPromise); + controller._finishPromise_reject(reason); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; + } + // Helper functions for the TransformStream. + function streamBrandCheckException(name) { + return new TypeError("TransformStream.prototype.".concat(name, " can only be used on a TransformStream")); + } + + exports.ByteLengthQueuingStrategy = ByteLengthQueuingStrategy; + exports.CountQueuingStrategy = CountQueuingStrategy; + exports.ReadableByteStreamController = ReadableByteStreamController; + exports.ReadableStream = ReadableStream; + exports.ReadableStreamBYOBReader = ReadableStreamBYOBReader; + exports.ReadableStreamBYOBRequest = ReadableStreamBYOBRequest; + exports.ReadableStreamDefaultController = ReadableStreamDefaultController; + exports.ReadableStreamDefaultReader = ReadableStreamDefaultReader; + exports.TransformStream = TransformStream; + exports.TransformStreamDefaultController = TransformStreamDefaultController; + exports.WritableStream = WritableStream; + exports.WritableStreamDefaultController = WritableStreamDefaultController; + exports.WritableStreamDefaultWriter = WritableStreamDefaultWriter; + +})); +//# sourceMappingURL=ponyfill.js.map diff --git a/backend/node_modules/web-streams-polyfill/dist/ponyfill.js.map b/backend/node_modules/web-streams-polyfill/dist/ponyfill.js.map new file mode 100644 index 0000000000000000000000000000000000000000..d151897be054f0eba1b196e8df9a30aa5e0910b7 --- /dev/null +++ b/backend/node_modules/web-streams-polyfill/dist/ponyfill.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ponyfill.js","sources":["../src/stub/symbol.ts","../node_modules/tslib/tslib.es6.js","../src/utils.ts","../src/lib/helpers/miscellaneous.ts","../src/lib/helpers/webidl.ts","../src/lib/simple-queue.ts","../src/lib/abstract-ops/internal-methods.ts","../src/lib/readable-stream/generic-reader.ts","../src/stub/number-isfinite.ts","../src/stub/math-trunc.ts","../src/lib/validators/basic.ts","../src/lib/validators/readable-stream.ts","../src/lib/readable-stream/default-reader.ts","../src/lib/abstract-ops/ecmascript.ts","../src/target/es5/stub/async-iterator-prototype.ts","../src/lib/readable-stream/async-iterator.ts","../src/stub/number-isnan.ts","../src/lib/abstract-ops/miscellaneous.ts","../src/lib/abstract-ops/queue-with-sizes.ts","../src/lib/helpers/array-buffer-view.ts","../src/lib/readable-stream/byte-stream-controller.ts","../src/lib/validators/reader-options.ts","../src/lib/readable-stream/byob-reader.ts","../src/lib/abstract-ops/queuing-strategy.ts","../src/lib/validators/queuing-strategy.ts","../src/lib/validators/underlying-sink.ts","../src/lib/validators/writable-stream.ts","../src/lib/abort-signal.ts","../src/lib/writable-stream.ts","../src/globals.ts","../src/stub/dom-exception.ts","../src/lib/readable-stream/pipe.ts","../src/lib/readable-stream/default-controller.ts","../src/lib/readable-stream/tee.ts","../src/lib/readable-stream/readable-stream-like.ts","../src/lib/readable-stream/from.ts","../src/lib/validators/underlying-source.ts","../src/lib/validators/iterator-options.ts","../src/lib/validators/pipe-options.ts","../src/lib/validators/readable-writable-pair.ts","../src/lib/readable-stream.ts","../src/lib/validators/queuing-strategy-init.ts","../src/lib/byte-length-queuing-strategy.ts","../src/lib/count-queuing-strategy.ts","../src/lib/validators/transformer.ts","../src/lib/transform-stream.ts"],"sourcesContent":["/// \n\nconst SymbolPolyfill: (description?: string) => symbol =\n typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ?\n Symbol :\n description => `Symbol(${description})` as any as symbol;\n\nexport default SymbolPolyfill;\n","/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise, SuppressedError, Symbol */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\r\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\r\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\r\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\r\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\r\n var _, done = false;\r\n for (var i = decorators.length - 1; i >= 0; i--) {\r\n var context = {};\r\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\r\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\r\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\r\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\r\n if (kind === \"accessor\") {\r\n if (result === void 0) continue;\r\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\r\n if (_ = accept(result.get)) descriptor.get = _;\r\n if (_ = accept(result.set)) descriptor.set = _;\r\n if (_ = accept(result.init)) initializers.unshift(_);\r\n }\r\n else if (_ = accept(result)) {\r\n if (kind === \"field\") initializers.unshift(_);\r\n else descriptor[key] = _;\r\n }\r\n }\r\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\r\n done = true;\r\n};\r\n\r\nexport function __runInitializers(thisArg, initializers, value) {\r\n var useValue = arguments.length > 2;\r\n for (var i = 0; i < initializers.length; i++) {\r\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\r\n }\r\n return useValue ? value : void 0;\r\n};\r\n\r\nexport function __propKey(x) {\r\n return typeof x === \"symbol\" ? x : \"\".concat(x);\r\n};\r\n\r\nexport function __setFunctionName(f, name, prefix) {\r\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\r\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\r\n};\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n var desc = Object.getOwnPropertyDescriptor(m, k);\r\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\r\n desc = { enumerable: true, get: function() { return m[k]; } };\r\n }\r\n Object.defineProperty(o, k2, desc);\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\nexport function __classPrivateFieldIn(state, receiver) {\r\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\r\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\r\n}\r\n\r\nexport function __addDisposableResource(env, value, async) {\r\n if (value !== null && value !== void 0) {\r\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\r\n var dispose;\r\n if (async) {\r\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\r\n dispose = value[Symbol.asyncDispose];\r\n }\r\n if (dispose === void 0) {\r\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\r\n dispose = value[Symbol.dispose];\r\n }\r\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\r\n env.stack.push({ value: value, dispose: dispose, async: async });\r\n }\r\n else if (async) {\r\n env.stack.push({ async: true });\r\n }\r\n return value;\r\n}\r\n\r\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n};\r\n\r\nexport function __disposeResources(env) {\r\n function fail(e) {\r\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\r\n env.hasError = true;\r\n }\r\n function next() {\r\n while (env.stack.length) {\r\n var rec = env.stack.pop();\r\n try {\r\n var result = rec.dispose && rec.dispose.call(rec.value);\r\n if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\r\n }\r\n catch (e) {\r\n fail(e);\r\n }\r\n }\r\n if (env.hasError) throw env.error;\r\n }\r\n return next();\r\n}\r\n\r\nexport default {\r\n __extends: __extends,\r\n __assign: __assign,\r\n __rest: __rest,\r\n __decorate: __decorate,\r\n __param: __param,\r\n __metadata: __metadata,\r\n __awaiter: __awaiter,\r\n __generator: __generator,\r\n __createBinding: __createBinding,\r\n __exportStar: __exportStar,\r\n __values: __values,\r\n __read: __read,\r\n __spread: __spread,\r\n __spreadArrays: __spreadArrays,\r\n __spreadArray: __spreadArray,\r\n __await: __await,\r\n __asyncGenerator: __asyncGenerator,\r\n __asyncDelegator: __asyncDelegator,\r\n __asyncValues: __asyncValues,\r\n __makeTemplateObject: __makeTemplateObject,\r\n __importStar: __importStar,\r\n __importDefault: __importDefault,\r\n __classPrivateFieldGet: __classPrivateFieldGet,\r\n __classPrivateFieldSet: __classPrivateFieldSet,\r\n __classPrivateFieldIn: __classPrivateFieldIn,\r\n __addDisposableResource: __addDisposableResource,\r\n __disposeResources: __disposeResources,\r\n};\r\n","export function noop(): undefined {\n return undefined;\n}\n","import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n\nexport function setFunctionName(fn: Function, name: string): void {\n try {\n Object.defineProperty(fn, 'name', {\n value: name,\n configurable: true\n });\n } catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n }\n}\n","import { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\n// https://webidl.spec.whatwg.org/#a-new-promise\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-resolved-with\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return newPromise(resolve => resolve(value));\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-rejected-with\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\n// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned\n// from that handler. To prevent this, return null instead of void from all handlers.\n// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => null | PromiseLike,\n onRejected?: (reason: any) => null | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => null | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => null | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nlet _queueMicrotask: (callback: () => void) => void = callback => {\n if (typeof queueMicrotask === 'function') {\n _queueMicrotask = queueMicrotask;\n } else {\n const resolvedPromise = promiseResolvedWith(undefined);\n _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb);\n }\n return _queueMicrotask(callback);\n};\n\nexport { _queueMicrotask as queueMicrotask };\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n","import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n","export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\nexport const ReleaseSteps = Symbol('[[ReleaseSteps]]');\n","import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, type ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\nimport { ReleaseSteps } from '../abstract-ops/internal-methods';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n assert(stream._reader === reader);\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n stream._readableStreamController[ReleaseSteps]();\n\n stream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n","import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n","import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamDefaultReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamDefaultReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\nexport function ReadableStreamDefaultReaderRelease(reader: ReadableStreamDefaultReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n}\n\nexport function ReadableStreamDefaultReaderErrorReadRequests(reader: ReadableStreamDefaultReader, e: any) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n","import { reflectCall } from 'lib/helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport assert from '../../stub/assert';\n\ndeclare global {\n interface ArrayBuffer {\n readonly detached: boolean;\n\n transfer(): ArrayBuffer;\n }\n\n function structuredClone(value: T, options: { transfer: ArrayBuffer[] }): T;\n}\n\nexport function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\nexport let TransferArrayBuffer = (O: ArrayBuffer): ArrayBuffer => {\n if (typeof O.transfer === 'function') {\n TransferArrayBuffer = buffer => buffer.transfer();\n } else if (typeof structuredClone === 'function') {\n TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] });\n } else {\n // Not implemented correctly\n TransferArrayBuffer = buffer => buffer;\n }\n return TransferArrayBuffer(O);\n};\n\nexport function CanTransferArrayBuffer(O: ArrayBuffer): boolean {\n return !IsDetachedBuffer(O);\n}\n\nexport let IsDetachedBuffer = (O: ArrayBuffer): boolean => {\n if (typeof O.detached === 'boolean') {\n IsDetachedBuffer = buffer => buffer.detached;\n } else {\n // Not implemented correctly\n IsDetachedBuffer = buffer => buffer.byteLength === 0;\n }\n return IsDetachedBuffer(O);\n};\n\nexport function ArrayBufferSlice(buffer: ArrayBuffer, begin: number, end: number): ArrayBuffer {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n\nexport type MethodName = {\n [P in keyof T]: T[P] extends Function | undefined ? P : never;\n}[keyof T];\n\nexport function GetMethod>(receiver: T, prop: K): T[K] | undefined {\n const func = receiver[prop];\n if (func === undefined || func === null) {\n return undefined;\n }\n if (typeof func !== 'function') {\n throw new TypeError(`${String(prop)} is not a function`);\n }\n return func;\n}\n\nexport interface SyncIteratorRecord {\n iterator: Iterator,\n nextMethod: Iterator['next'],\n done: boolean;\n}\n\nexport interface AsyncIteratorRecord {\n iterator: AsyncIterator,\n nextMethod: AsyncIterator['next'],\n done: boolean;\n}\n\nexport type SyncOrAsyncIteratorRecord = SyncIteratorRecord | AsyncIteratorRecord;\n\nexport function CreateAsyncFromSyncIterator(syncIteratorRecord: SyncIteratorRecord): AsyncIteratorRecord {\n // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%,\n // we use yield* inside an async generator function to achieve the same result.\n\n // Wrap the sync iterator inside a sync iterable, so we can use it with yield*.\n const syncIterable = {\n [Symbol.iterator]: () => syncIteratorRecord.iterator\n };\n // Create an async generator function and immediately invoke it.\n const asyncIterator = (async function* () {\n return yield* syncIterable;\n }());\n // Return as an async iterator record.\n const nextMethod = asyncIterator.next;\n return { iterator: asyncIterator, nextMethod, done: false };\n}\n\n// Aligns with core-js/modules/es.symbol.async-iterator.js\nexport const SymbolAsyncIterator: (typeof Symbol)['asyncIterator'] =\n Symbol.asyncIterator ??\n Symbol.for?.('Symbol.asyncIterator') ??\n '@@asyncIterator';\n\nexport type SyncOrAsyncIterable = Iterable | AsyncIterable;\nexport type SyncOrAsyncIteratorMethod = () => (Iterator | AsyncIterator);\n\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint: 'async',\n method?: SyncOrAsyncIteratorMethod\n): AsyncIteratorRecord;\nfunction GetIterator(\n obj: Iterable,\n hint: 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncIteratorRecord;\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint = 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncOrAsyncIteratorRecord {\n assert(hint === 'sync' || hint === 'async');\n if (method === undefined) {\n if (hint === 'async') {\n method = GetMethod(obj as AsyncIterable, SymbolAsyncIterator);\n if (method === undefined) {\n const syncMethod = GetMethod(obj as Iterable, Symbol.iterator);\n const syncIteratorRecord = GetIterator(obj as Iterable, 'sync', syncMethod);\n return CreateAsyncFromSyncIterator(syncIteratorRecord);\n }\n } else {\n method = GetMethod(obj as Iterable, Symbol.iterator);\n }\n }\n if (method === undefined) {\n throw new TypeError('The object is not iterable');\n }\n const iterator = reflectCall(method, obj, []);\n if (!typeIsObject(iterator)) {\n throw new TypeError('The iterator method must return an object');\n }\n const nextMethod = iterator.next;\n return { iterator, nextMethod, done: false } as SyncOrAsyncIteratorRecord;\n}\n\nexport { GetIterator };\n\nexport function IteratorNext(iteratorRecord: AsyncIteratorRecord): Promise> {\n const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []);\n if (!typeIsObject(result)) {\n throw new TypeError('The iterator.next() method must return an object');\n }\n return result;\n}\n\nexport function IteratorComplete(\n iterResult: IteratorResult\n): iterResult is IteratorReturnResult {\n assert(typeIsObject(iterResult));\n return Boolean(iterResult.done);\n}\n\nexport function IteratorValue(iterResult: IteratorYieldResult): T {\n assert(typeIsObject(iterResult));\n return iterResult.value;\n}\n","/// \n\nimport { SymbolAsyncIterator } from '../../../lib/abstract-ops/ecmascript';\n\n// We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it.\nexport const AsyncIteratorPrototype: AsyncIterable = {\n // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( )\n // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator\n [SymbolAsyncIterator](this: AsyncIterator) {\n return this;\n }\n};\nObject.defineProperty(AsyncIteratorPrototype, SymbolAsyncIterator, { enumerable: false });\n","/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadableStreamDefaultReadResult,\n type ReadRequest\n} from './default-reader';\nimport { ReadableStreamReaderGenericCancel, ReadableStreamReaderGenericRelease } from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterableIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ninterface ReadableStreamAsyncIteratorInstance extends ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nObject.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n","import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: NonShared): NonShared {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer) as NonShared;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n","export type TypedArray =\n | Int8Array\n | Uint8Array\n | Uint8ClampedArray\n | Int16Array\n | Uint16Array\n | Int32Array\n | Uint32Array\n | Float32Array\n | Float64Array;\n\nexport type NonShared = T & {\n buffer: ArrayBuffer;\n}\n\nexport interface ArrayBufferViewConstructor {\n new(buffer: ArrayBuffer, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n}\n\nexport interface TypedArrayConstructor extends ArrayBufferViewConstructor {\n readonly BYTES_PER_ELEMENT: number;\n}\n\nexport type DataViewConstructor = ArrayBufferViewConstructor;\n\nfunction isDataViewConstructor(ctor: Function): ctor is DataViewConstructor {\n return ctor === DataView;\n}\n\nexport function isDataView(view: ArrayBufferView): view is DataView {\n return isDataViewConstructor(view.constructor);\n}\n\nexport function arrayBufferViewElementSize(ctor: ArrayBufferViewConstructor): number {\n if (isDataViewConstructor(ctor)) {\n return 1;\n }\n return (ctor as unknown as TypedArrayConstructor).BYTES_PER_ELEMENT;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n IsReadableStreamDefaultReader,\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n type ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n type ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n type ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport type { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\nimport {\n type ArrayBufferViewConstructor,\n arrayBufferViewElementSize,\n type NonShared,\n type TypedArrayConstructor\n} from '../helpers/array-buffer-view';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: NonShared | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: NonShared): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond');\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBuffer;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor = NonShared> =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: TypedArrayConstructor;\n readerType: 'default' | 'none';\n}\n\ninterface BYOBPullIntoDescriptor = NonShared> {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob' | 'none';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: NonShared): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest>): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n minimumFill: 1,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n if (this._pendingPullIntos.length > 0) {\n const firstPullInto = this._pendingPullIntos.peek();\n firstPullInto.readerType = 'none';\n\n this._pendingPullIntos = new SimpleQueue();\n this._pendingPullIntos.push(firstPullInto);\n }\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableByteStreamController.prototype.close, 'close');\nsetFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableByteStreamController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor>(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n assert(pullIntoDescriptor.readerType !== 'none');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as NonShared, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor>(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n let clonedChunk;\n try {\n clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength);\n } catch (cloneE) {\n ReadableByteStreamControllerError(controller, cloneE);\n throw cloneE;\n }\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength);\n}\n\nfunction ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.readerType === 'none');\n if (firstDescriptor.bytesFilled > 0) {\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n firstDescriptor.buffer,\n firstDescriptor.byteOffset,\n firstDescriptor.bytesFilled\n );\n }\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize;\n const maxAlignedBytes = maxBytesFilled - remainderBytes;\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n assert(pullIntoDescriptor.readerType !== 'none');\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nfunction ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller: ReadableByteStreamController) {\n const reader = controller._controlledReadableByteStream._reader;\n assert(IsReadableStreamDefaultReader(reader));\n while (reader._readRequests.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n const readRequest = reader._readRequests.shift();\n ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest);\n }\n}\n\nexport function ReadableByteStreamControllerPullInto>(\n controller: ReadableByteStreamController,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n const elementSize = arrayBufferViewElementSize(ctor);\n\n const { byteOffset, byteLength } = view;\n\n const minimumFill = min * elementSize;\n assert(minimumFill >= elementSize && minimumFill <= byteLength);\n assert(minimumFill % elementSize === 0);\n\n let buffer: ArrayBuffer;\n try {\n buffer = TransferArrayBuffer(view.buffer);\n } catch (e) {\n readIntoRequest._errorSteps(e);\n return;\n }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset,\n byteLength,\n bytesFilled: 0,\n minimumFill,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled % firstDescriptor.elementSize === 0);\n\n if (firstDescriptor.readerType === 'none') {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n return;\n }\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) {\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n pullIntoDescriptor.buffer,\n end - remainderSize,\n remainderSize\n );\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(\n controller: ReadableByteStreamController,\n chunk: NonShared\n) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const { buffer, byteOffset, byteLength } = chunk;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n if (firstPendingPullInto.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto);\n }\n }\n\n if (ReadableStreamHasDefaultReader(stream)) {\n ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller);\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView as NonShared, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerFillReadRequestFromQueue(\n controller: ReadableByteStreamController,\n readRequest: ReadRequest>\n) {\n assert(controller._queueTotalSize > 0);\n\n const entry = controller._queue.shift();\n controller._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n readRequest._chunkSteps(view as NonShared);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view as NonShared);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: NonShared) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: NonShared) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n","import { assertDictionary, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n\nexport function convertByobReadOptions(\n options: ReadableStreamBYOBReaderReadOptions | null | undefined,\n context: string\n): ValidatedReadableStreamBYOBReaderReadOptions {\n assertDictionary(options, context);\n const min = options?.min ?? 1;\n return {\n min: convertUnsignedLongLongWithEnforceRange(\n min,\n `${context} has member 'min' that`\n )\n };\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, type ReadableByteStream, type ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from './reader-options';\nimport { convertByobReadOptions } from '../validators/reader-options';\nimport { isDataView, type NonShared, type TypedArray } from '../helpers/array-buffer-view';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream as ReadableStream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest>(\n stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest\n): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest> {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(\n view: T,\n options?: ReadableStreamBYOBReaderReadOptions\n ): Promise>;\n read>(\n view: T,\n rawOptions: ReadableStreamBYOBReaderReadOptions | null | undefined = {}\n ): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n let options: ValidatedReadableStreamBYOBReaderReadOptions;\n try {\n options = convertByobReadOptions(rawOptions, 'options');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const min = options.min;\n if (min === 0) {\n return promiseRejectedWith(new TypeError('options.min must be greater than 0'));\n }\n if (!isDataView(view)) {\n if (min > (view as unknown as TypedArray).length) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s length'));\n }\n } else if (min > view.byteLength) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s byteLength'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamBYOBReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamBYOBReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead>(\n reader: ReadableStreamBYOBReader,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n min,\n readIntoRequest\n );\n }\n}\n\nexport function ReadableStreamBYOBReaderRelease(reader: ReadableStreamBYOBReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n}\n\nexport function ReadableStreamBYOBReaderErrorReadIntoRequests(reader: ReadableStreamBYOBReader, e: any) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n","/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * If aborted, returns the reason for aborting.\n */\n readonly reason?: any;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(reason?: any): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n type QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { type AbortController, type AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(WritableStream.prototype.abort, 'abort');\nsetFunctionName(WritableStream.prototype.close, 'close');\nsetFunctionName(WritableStream.prototype.getWriter, 'getWriter');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight\n};\n\nexport type {\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort(reason);\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nsetFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort');\nsetFunctionName(WritableStreamDefaultWriter.prototype.close, 'close');\nsetFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock');\nsetFunctionName(WritableStreamDefaultWriter.prototype.write, 'write');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n return null;\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let writeAlgorithm: (chunk: W) => Promise;\n let closeAlgorithm: () => Promise;\n let abortAlgorithm: (reason: any) => Promise;\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n } else {\n writeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n } else {\n closeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n } else {\n abortAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n return null;\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n","/// \n\nfunction getGlobals(): typeof globalThis | undefined {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n } else if (typeof self !== 'undefined') {\n return self;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n","/// \nimport { globals } from '../globals';\nimport { setFunctionName } from '../lib/helpers/miscellaneous';\n\ninterface DOMException extends Error {\n name: string;\n message: string;\n}\n\ntype DOMExceptionConstructor = new (message?: string, name?: string) => DOMException;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n if ((ctor as DOMExceptionConstructor).name !== 'DOMException') {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Support:\n * - Web browsers\n * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87)\n */\nfunction getFromGlobal(): DOMExceptionConstructor | undefined {\n const ctor = globals?.DOMException;\n return isDOMExceptionConstructor(ctor) ? ctor : undefined;\n}\n\n/**\n * Support:\n * - All platforms\n */\nfunction createPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line @typescript-eslint/no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n setFunctionName(ctor, 'DOMException');\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nconst DOMException: DOMExceptionConstructor = getFromGlobal() || createPolyfill();\n\nexport { DOMException };\n","import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n return null;\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => null) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => null) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest(): null {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n return null;\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any): null {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n\n return null;\n }\n });\n}\n","import type { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, type QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n type ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport type { ValidatedUnderlyingSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n // Do nothing.\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultController.prototype.close, 'close');\nsetFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableStreamDefaultController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n","import {\n CreateReadableByteStream,\n CreateReadableStream,\n type DefaultReadableStream,\n IsReadableStream,\n type ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n type ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n type ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(\n stream: ReadableStream,\n cloneForBranch2: boolean\n): [DefaultReadableStream, DefaultReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: DefaultReadableStream;\n let branch2: DefaultReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader> = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader>) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return null;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: NonShared, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader>(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n","import { typeIsObject } from '../helpers/miscellaneous';\nimport type { ReadableStreamDefaultReadResult } from './default-reader';\n\n/**\n * A common interface for a `ReadadableStream` implementation.\n *\n * @public\n */\nexport interface ReadableStreamLike {\n readonly locked: boolean;\n\n getReader(): ReadableStreamDefaultReaderLike;\n}\n\n/**\n * A common interface for a `ReadableStreamDefaultReader` implementation.\n *\n * @public\n */\nexport interface ReadableStreamDefaultReaderLike {\n readonly closed: Promise;\n\n cancel(reason?: any): Promise;\n\n read(): Promise>;\n\n releaseLock(): void;\n}\n\nexport function isReadableStreamLike(stream: unknown): stream is ReadableStreamLike {\n return typeIsObject(stream) && typeof (stream as ReadableStreamLike).getReader !== 'undefined';\n}\n","import { CreateReadableStream, type DefaultReadableStream } from '../readable-stream';\nimport {\n isReadableStreamLike,\n type ReadableStreamDefaultReaderLike,\n type ReadableStreamLike\n} from './readable-stream-like';\nimport { ReadableStreamDefaultControllerClose, ReadableStreamDefaultControllerEnqueue } from './default-controller';\nimport { GetIterator, GetMethod, IteratorComplete, IteratorNext, IteratorValue } from '../abstract-ops/ecmascript';\nimport { promiseRejectedWith, promiseResolvedWith, reflectCall, transformPromiseWith } from '../helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { noop } from '../../utils';\n\nexport function ReadableStreamFrom(\n source: Iterable | AsyncIterable | ReadableStreamLike\n): DefaultReadableStream {\n if (isReadableStreamLike(source)) {\n return ReadableStreamFromDefaultReader(source.getReader());\n }\n return ReadableStreamFromIterable(source);\n}\n\nexport function ReadableStreamFromIterable(asyncIterable: Iterable | AsyncIterable): DefaultReadableStream {\n let stream: DefaultReadableStream;\n const iteratorRecord = GetIterator(asyncIterable, 'async');\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let nextResult;\n try {\n nextResult = IteratorNext(iteratorRecord);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const nextPromise = promiseResolvedWith(nextResult);\n return transformPromiseWith(nextPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object');\n }\n const done = IteratorComplete(iterResult);\n if (done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = IteratorValue(iterResult);\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n const iterator = iteratorRecord.iterator;\n let returnMethod: (typeof iterator)['return'] | undefined;\n try {\n returnMethod = GetMethod(iterator, 'return');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n if (returnMethod === undefined) {\n return promiseResolvedWith(undefined);\n }\n let returnResult: IteratorResult | Promise>;\n try {\n returnResult = reflectCall(returnMethod, iterator, [reason]);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const returnPromise = promiseResolvedWith(returnResult);\n return transformPromiseWith(returnPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object');\n }\n return undefined;\n });\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n\nexport function ReadableStreamFromDefaultReader(\n reader: ReadableStreamDefaultReaderLike\n): DefaultReadableStream {\n let stream: DefaultReadableStream;\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let readPromise;\n try {\n readPromise = reader.read();\n } catch (e) {\n return promiseRejectedWith(e);\n }\n return transformPromiseWith(readPromise, readResult => {\n if (!typeIsObject(readResult)) {\n throw new TypeError('The promise returned by the reader.read() method must fulfill with an object');\n }\n if (readResult.done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = readResult.value;\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n try {\n return promiseResolvedWith(reader.cancel(reason));\n } catch (e) {\n return promiseRejectedWith(e);\n }\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n","import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n","import { assertDictionary } from './basic';\nimport type {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n","import { assertDictionary } from './basic';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n","import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n","import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, type ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderErrorReadRequests,\n type ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReaderErrorReadIntoRequests,\n type ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { ReadableStreamFrom } from './readable-stream/from';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport type {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList, SymbolAsyncIterator } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions\n} from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport type { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport type { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\nimport type { ReadableStreamDefaultReaderLike, ReadableStreamLike } from './readable-stream/readable-stream-like';\nimport type { NonShared } from './helpers/array-buffer-view';\n\nexport type DefaultReadableStream = ReadableStream & {\n _readableStreamController: ReadableStreamDefaultController\n};\n\nexport type ReadableByteStream = ReadableStream> & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream implements AsyncIterable {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n\n [SymbolAsyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator {\n // Stub implementation, overridden below\n return this.values(options);\n }\n\n /**\n * Creates a new ReadableStream wrapping the provided iterable or async iterable.\n *\n * This can be used to adapt various kinds of objects into a readable stream,\n * such as an array, an async generator, or a Node.js readable stream.\n */\n static from(asyncIterable: Iterable | AsyncIterable | ReadableStreamLike): ReadableStream {\n return ReadableStreamFrom(asyncIterable);\n }\n}\n\nObject.defineProperties(ReadableStream, {\n from: { enumerable: true }\n});\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(ReadableStream.from, 'from');\nsetFunctionName(ReadableStream.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStream.prototype.getReader, 'getReader');\nsetFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough');\nsetFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo');\nsetFunctionName(ReadableStream.prototype.tee, 'tee');\nsetFunctionName(ReadableStream.prototype.values, 'values');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nObject.defineProperty(ReadableStream.prototype, SymbolAsyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n});\n\nexport type {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n ReadableStreamBYOBReaderReadOptions,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions,\n ReadableStreamLike,\n ReadableStreamDefaultReaderLike\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1\n): DefaultReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: DefaultReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n","import type { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\nsetFunctionName(byteLengthSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\nsetFunctionName(countSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const cancel = original?.cancel;\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n cancel: cancel === undefined ?\n undefined :\n convertTransformerCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n\nfunction convertTransformerCancelCallback(\n fn: TransformerCancelCallback,\n original: Transformer,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith,\n uponPromise\n} from './helpers/webidl';\nimport { CreateReadableStream, type DefaultReadableStream, ReadableStream } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: DefaultReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport type {\n Transformer,\n TransformerCancelCallback,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSourceCancelAlgorithm(stream, reason);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n TransformStreamUnblockWrite(stream);\n}\n\nfunction TransformStreamUnblockWrite(stream: TransformStream) {\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _finishPromise: Promise | undefined;\n /** @internal */\n _finishPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _finishPromise_reject?: (reason: any) => void;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n /** @internal */\n _cancelAlgorithm: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(TransformStreamDefaultController.prototype.error, 'error');\nsetFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._finishPromise = undefined;\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm: (chunk: I) => Promise;\n let flushAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n } else {\n transformAlgorithm = chunk => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n }\n\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n } else {\n flushAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n if (transformer.cancel !== undefined) {\n cancelAlgorithm = reason => transformer.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally,\n // we don't run the _cancelAlgorithm again.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerError(readable._readableStreamController, reason);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally,\n // we don't also run the _cancelAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(flushPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerClose(readable._readableStreamController);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\nfunction TransformStreamDefaultSourceCancelAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._writable cannot change after construction, so caching it across a call to user code is safe.\n const writable = stream._writable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or\n // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the\n // _flushAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (writable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, writable._storedError);\n } else {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\nexport function defaultControllerFinishPromiseResolve(controller: TransformStreamDefaultController) {\n if (controller._finishPromise_resolve === undefined) {\n return;\n }\n\n controller._finishPromise_resolve();\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nexport function defaultControllerFinishPromiseReject(controller: TransformStreamDefaultController, reason: any) {\n if (controller._finishPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(controller._finishPromise!);\n controller._finishPromise_reject(reason);\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n"],"names":["Symbol","_a","queueMicrotask","streamBrandCheckException","defaultControllerBrandCheckException"],"mappings":";;;;;;;;;;;;;IAAA;IAEA,IAAM,cAAc,GAClB,OAAO,MAAM,KAAK,UAAU,IAAI,OAAO,MAAM,CAAC,QAAQ,KAAK,QAAQ;IACjE,IAAA,MAAM;QACN,UAAA,WAAW,IAAI,OAAA,SAAA,CAAA,MAAA,CAAU,WAAW,EAAoB,GAAA,CAAA,CAAA,EAAA;;ICL5D;IACA;AACA;IACA;IACA;AACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;AACA;AA4GA;IACO,SAAS,WAAW,CAAC,OAAO,EAAE,IAAI,EAAE;IAC3C,IAAI,IAAI,CAAC,GAAG,EAAE,KAAK,EAAE,CAAC,EAAE,IAAI,EAAE,WAAW,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,IAAI,EAAE,EAAE,E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,CAAC,CAAC;IACpC,QAAA,oCAAoC,CAAC,UAAU,EAAE,CAAC,CAAC,CAAC;IACpD,QAAA,OAAO,IAAI,CAAC;IACd,KAAC,CAAC,CAAC;QAEH,OAAO,UAAU,CAAC,cAAc,CAAC;IACnC,CAAC;IAED;IAEA,SAAS,oCAAoC,CAAC,IAAY,EAAA;IACxD,IAAA,OAAO,IAAI,SAAS,CAClB,qDAA8C,IAAI,EAAA,yDAAA,CAAyD,CAAC,CAAC;IACjH,CAAC;IAEK,SAAU,qCAAqC,CAAC,UAAiD,EAAA;IACrG,IAAA,IAAI,UAAU,CAAC,sBAAsB,KAAK,SAAS,EAAE;YACnD,OAAO;SACR;QAED,UAAU,CAAC,sBAAsB,EAAE,CAAC;IACpC,IAAA,UAAU,CAAC,sBAAsB,GAAG,SAAS,CAAC;IAC9C,IAAA,UAAU,CAAC,qBAAqB,GAAG,SAAS,CAAC;IAC/C,CAAC;IAEe,SAAA,oCAAoC,CAAC,UAAiD,EAAE,MAAW,EAAA;IACjH,IAAA,IAAI,UAAU,CAAC,qBAAqB,KAAK,SAAS,EAAE;YAClD,OAAO;SACR;IAED,IAAA,yBAAyB,CAAC,UAAU,CAAC,cAAe,CAAC,CAAC;IACtD,IAAA,UAAU,CAAC,qBAAqB,CAAC,MAAM,CAAC,CAAC;IACzC,IAAA,UAAU,CAAC,sBAAsB,GAAG,SAAS,CAAC;IAC9C,IAAA,UAAU,CAAC,qBAAqB,GAAG,SAAS,CAAC;IAC/C,CAAC;IAED;IAEA,SAAS,yBAAyB,CAAC,IAAY,EAAA;IAC7C,IAAA,OAAO,IAAI,SAAS,CAClB,oCAA6B,IAAI,EAAA,wCAAA,CAAwC,CAAC,CAAC;IAC/E;;;;;;;;;;;;;;;;;;;;","x_google_ignoreList":[1]} \ No newline at end of file diff --git a/backend/node_modules/web-streams-polyfill/dist/ponyfill.mjs b/backend/node_modules/web-streams-polyfill/dist/ponyfill.mjs new file mode 100644 index 0000000000000000000000000000000000000000..9f07fe89b65f2ec192efb79eee9f715dbd2c64a5 --- /dev/null +++ b/backend/node_modules/web-streams-polyfill/dist/ponyfill.mjs @@ -0,0 +1,4963 @@ +/** + * @license + * web-streams-polyfill v3.3.3 + * Copyright 2024 Mattias Buelens, Diwank Singh Tomer and other contributors. + * This code is released under the MIT license. + * SPDX-License-Identifier: MIT + */ +/// +var SymbolPolyfill = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? + Symbol : + function (description) { return "Symbol(".concat(description, ")"); }; + +/****************************************************************************** +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 */ + + +function __generator(thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (g && (g = 0, op[0] && (_ = 0)), _) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +} + +function __values(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); +} + +function __await(v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); +} + +function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } +} + +function __asyncDelegator(o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } +} + +function __asyncValues(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } +} + +typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; +}; + +function noop() { + return undefined; +} + +function typeIsObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; +} +var rethrowAssertionErrorRejection = noop; +function setFunctionName(fn, name) { + try { + Object.defineProperty(fn, 'name', { + value: name, + configurable: true + }); + } + catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility + } +} + +var originalPromise = Promise; +var originalPromiseThen = Promise.prototype.then; +var originalPromiseReject = Promise.reject.bind(originalPromise); +// https://webidl.spec.whatwg.org/#a-new-promise +function newPromise(executor) { + return new originalPromise(executor); +} +// https://webidl.spec.whatwg.org/#a-promise-resolved-with +function promiseResolvedWith(value) { + return newPromise(function (resolve) { return resolve(value); }); +} +// https://webidl.spec.whatwg.org/#a-promise-rejected-with +function promiseRejectedWith(reason) { + return originalPromiseReject(reason); +} +function PerformPromiseThen(promise, onFulfilled, onRejected) { + // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an + // approximation. + return originalPromiseThen.call(promise, onFulfilled, onRejected); +} +// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned +// from that handler. To prevent this, return null instead of void from all handlers. +// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it +function uponPromise(promise, onFulfilled, onRejected) { + PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection); +} +function uponFulfillment(promise, onFulfilled) { + uponPromise(promise, onFulfilled); +} +function uponRejection(promise, onRejected) { + uponPromise(promise, undefined, onRejected); +} +function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { + return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); +} +function setPromiseIsHandledToTrue(promise) { + PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection); +} +var _queueMicrotask = function (callback) { + if (typeof queueMicrotask === 'function') { + _queueMicrotask = queueMicrotask; + } + else { + var resolvedPromise_1 = promiseResolvedWith(undefined); + _queueMicrotask = function (cb) { return PerformPromiseThen(resolvedPromise_1, cb); }; + } + return _queueMicrotask(callback); +}; +function reflectCall(F, V, args) { + if (typeof F !== 'function') { + throw new TypeError('Argument is not a function'); + } + return Function.prototype.apply.call(F, V, args); +} +function promiseCall(F, V, args) { + try { + return promiseResolvedWith(reflectCall(F, V, args)); + } + catch (value) { + return promiseRejectedWith(value); + } +} + +// Original from Chromium +// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js +var QUEUE_MAX_ARRAY_SIZE = 16384; +/** + * Simple queue structure. + * + * Avoids scalability issues with using a packed array directly by using + * multiple arrays in a linked list and keeping the array size bounded. + */ +var SimpleQueue = /** @class */ (function () { + function SimpleQueue() { + this._cursor = 0; + this._size = 0; + // _front and _back are always defined. + this._front = { + _elements: [], + _next: undefined + }; + this._back = this._front; + // The cursor is used to avoid calling Array.shift(). + // It contains the index of the front element of the array inside the + // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE). + this._cursor = 0; + // When there is only one node, size === elements.length - cursor. + this._size = 0; + } + Object.defineProperty(SimpleQueue.prototype, "length", { + get: function () { + return this._size; + }, + enumerable: false, + configurable: true + }); + // For exception safety, this method is structured in order: + // 1. Read state + // 2. Calculate required state mutations + // 3. Perform state mutations + SimpleQueue.prototype.push = function (element) { + var oldBack = this._back; + var newBack = oldBack; + if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { + newBack = { + _elements: [], + _next: undefined + }; + } + // push() is the mutation most likely to throw an exception, so it + // goes first. + oldBack._elements.push(element); + if (newBack !== oldBack) { + this._back = newBack; + oldBack._next = newBack; + } + ++this._size; + }; + // Like push(), shift() follows the read -> calculate -> mutate pattern for + // exception safety. + SimpleQueue.prototype.shift = function () { // must not be called on an empty queue + var oldFront = this._front; + var newFront = oldFront; + var oldCursor = this._cursor; + var newCursor = oldCursor + 1; + var elements = oldFront._elements; + var element = elements[oldCursor]; + if (newCursor === QUEUE_MAX_ARRAY_SIZE) { + newFront = oldFront._next; + newCursor = 0; + } + // No mutations before this point. + --this._size; + this._cursor = newCursor; + if (oldFront !== newFront) { + this._front = newFront; + } + // Permit shifted element to be garbage collected. + elements[oldCursor] = undefined; + return element; + }; + // The tricky thing about forEach() is that it can be called + // re-entrantly. The queue may be mutated inside the callback. It is easy to + // see that push() within the callback has no negative effects since the end + // of the queue is checked for on every iteration. If shift() is called + // repeatedly within the callback then the next iteration may return an + // element that has been removed. In this case the callback will be called + // with undefined values until we either "catch up" with elements that still + // exist or reach the back of the queue. + SimpleQueue.prototype.forEach = function (callback) { + var i = this._cursor; + var node = this._front; + var elements = node._elements; + while (i !== elements.length || node._next !== undefined) { + if (i === elements.length) { + node = node._next; + elements = node._elements; + i = 0; + if (elements.length === 0) { + break; + } + } + callback(elements[i]); + ++i; + } + }; + // Return the element that would be returned if shift() was called now, + // without modifying the queue. + SimpleQueue.prototype.peek = function () { // must not be called on an empty queue + var front = this._front; + var cursor = this._cursor; + return front._elements[cursor]; + }; + return SimpleQueue; +}()); + +var AbortSteps = SymbolPolyfill('[[AbortSteps]]'); +var ErrorSteps = SymbolPolyfill('[[ErrorSteps]]'); +var CancelSteps = SymbolPolyfill('[[CancelSteps]]'); +var PullSteps = SymbolPolyfill('[[PullSteps]]'); +var ReleaseSteps = SymbolPolyfill('[[ReleaseSteps]]'); + +function ReadableStreamReaderGenericInitialize(reader, stream) { + reader._ownerReadableStream = stream; + stream._reader = reader; + if (stream._state === 'readable') { + defaultReaderClosedPromiseInitialize(reader); + } + else if (stream._state === 'closed') { + defaultReaderClosedPromiseInitializeAsResolved(reader); + } + else { + defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); + } +} +// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state +// check. +function ReadableStreamReaderGenericCancel(reader, reason) { + var stream = reader._ownerReadableStream; + return ReadableStreamCancel(stream, reason); +} +function ReadableStreamReaderGenericRelease(reader) { + var stream = reader._ownerReadableStream; + if (stream._state === 'readable') { + defaultReaderClosedPromiseReject(reader, new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")); + } + else { + defaultReaderClosedPromiseResetToRejected(reader, new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")); + } + stream._readableStreamController[ReleaseSteps](); + stream._reader = undefined; + reader._ownerReadableStream = undefined; +} +// Helper functions for the readers. +function readerLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released reader'); +} +// Helper functions for the ReadableStreamDefaultReader. +function defaultReaderClosedPromiseInitialize(reader) { + reader._closedPromise = newPromise(function (resolve, reject) { + reader._closedPromise_resolve = resolve; + reader._closedPromise_reject = reject; + }); +} +function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseReject(reader, reason); +} +function defaultReaderClosedPromiseInitializeAsResolved(reader) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseResolve(reader); +} +function defaultReaderClosedPromiseReject(reader, reason) { + if (reader._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(reader._closedPromise); + reader._closedPromise_reject(reason); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; +} +function defaultReaderClosedPromiseResetToRejected(reader, reason) { + defaultReaderClosedPromiseInitializeAsRejected(reader, reason); +} +function defaultReaderClosedPromiseResolve(reader) { + if (reader._closedPromise_resolve === undefined) { + return; + } + reader._closedPromise_resolve(undefined); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; +} + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill +var NumberIsFinite = Number.isFinite || function (x) { + return typeof x === 'number' && isFinite(x); +}; + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill +var MathTrunc = Math.trunc || function (v) { + return v < 0 ? Math.ceil(v) : Math.floor(v); +}; + +// https://heycam.github.io/webidl/#idl-dictionaries +function isDictionary(x) { + return typeof x === 'object' || typeof x === 'function'; +} +function assertDictionary(obj, context) { + if (obj !== undefined && !isDictionary(obj)) { + throw new TypeError("".concat(context, " is not an object.")); + } +} +// https://heycam.github.io/webidl/#idl-callback-functions +function assertFunction(x, context) { + if (typeof x !== 'function') { + throw new TypeError("".concat(context, " is not a function.")); + } +} +// https://heycam.github.io/webidl/#idl-object +function isObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; +} +function assertObject(x, context) { + if (!isObject(x)) { + throw new TypeError("".concat(context, " is not an object.")); + } +} +function assertRequiredArgument(x, position, context) { + if (x === undefined) { + throw new TypeError("Parameter ".concat(position, " is required in '").concat(context, "'.")); + } +} +function assertRequiredField(x, field, context) { + if (x === undefined) { + throw new TypeError("".concat(field, " is required in '").concat(context, "'.")); + } +} +// https://heycam.github.io/webidl/#idl-unrestricted-double +function convertUnrestrictedDouble(value) { + return Number(value); +} +function censorNegativeZero(x) { + return x === 0 ? 0 : x; +} +function integerPart(x) { + return censorNegativeZero(MathTrunc(x)); +} +// https://heycam.github.io/webidl/#idl-unsigned-long-long +function convertUnsignedLongLongWithEnforceRange(value, context) { + var lowerBound = 0; + var upperBound = Number.MAX_SAFE_INTEGER; + var x = Number(value); + x = censorNegativeZero(x); + if (!NumberIsFinite(x)) { + throw new TypeError("".concat(context, " is not a finite number")); + } + x = integerPart(x); + if (x < lowerBound || x > upperBound) { + throw new TypeError("".concat(context, " is outside the accepted range of ").concat(lowerBound, " to ").concat(upperBound, ", inclusive")); + } + if (!NumberIsFinite(x) || x === 0) { + return 0; + } + // TODO Use BigInt if supported? + // let xBigInt = BigInt(integerPart(x)); + // xBigInt = BigInt.asUintN(64, xBigInt); + // return Number(xBigInt); + return x; +} + +function assertReadableStream(x, context) { + if (!IsReadableStream(x)) { + throw new TypeError("".concat(context, " is not a ReadableStream.")); + } +} + +// Abstract operations for the ReadableStream. +function AcquireReadableStreamDefaultReader(stream) { + return new ReadableStreamDefaultReader(stream); +} +// ReadableStream API exposed for controllers. +function ReadableStreamAddReadRequest(stream, readRequest) { + stream._reader._readRequests.push(readRequest); +} +function ReadableStreamFulfillReadRequest(stream, chunk, done) { + var reader = stream._reader; + var readRequest = reader._readRequests.shift(); + if (done) { + readRequest._closeSteps(); + } + else { + readRequest._chunkSteps(chunk); + } +} +function ReadableStreamGetNumReadRequests(stream) { + return stream._reader._readRequests.length; +} +function ReadableStreamHasDefaultReader(stream) { + var reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamDefaultReader(reader)) { + return false; + } + return true; +} +/** + * A default reader vended by a {@link ReadableStream}. + * + * @public + */ +var ReadableStreamDefaultReader = /** @class */ (function () { + function ReadableStreamDefaultReader(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readRequests = new SimpleQueue(); + } + Object.defineProperty(ReadableStreamDefaultReader.prototype, "closed", { + /** + * Returns a promise that will be fulfilled when the stream becomes closed, + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + */ + get: function () { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('closed')); + } + return this._closedPromise; + }, + enumerable: false, + configurable: true + }); + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + ReadableStreamDefaultReader.prototype.cancel = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + }; + /** + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + ReadableStreamDefaultReader.prototype.read = function () { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('read')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + var resolvePromise; + var rejectPromise; + var promise = newPromise(function (resolve, reject) { + resolvePromise = resolve; + rejectPromise = reject; + }); + var readRequest = { + _chunkSteps: function (chunk) { return resolvePromise({ value: chunk, done: false }); }, + _closeSteps: function () { return resolvePromise({ value: undefined, done: true }); }, + _errorSteps: function (e) { return rejectPromise(e); } + }; + ReadableStreamDefaultReaderRead(this, readRequest); + return promise; + }; + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + ReadableStreamDefaultReader.prototype.releaseLock = function () { + if (!IsReadableStreamDefaultReader(this)) { + throw defaultReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamDefaultReaderRelease(this); + }; + return ReadableStreamDefaultReader; +}()); +Object.defineProperties(ReadableStreamDefaultReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } +}); +setFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel'); +setFunctionName(ReadableStreamDefaultReader.prototype.read, 'read'); +setFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultReader', + configurable: true + }); +} +// Abstract operations for the readers. +function IsReadableStreamDefaultReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) { + return false; + } + return x instanceof ReadableStreamDefaultReader; +} +function ReadableStreamDefaultReaderRead(reader, readRequest) { + var stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'closed') { + readRequest._closeSteps(); + } + else if (stream._state === 'errored') { + readRequest._errorSteps(stream._storedError); + } + else { + stream._readableStreamController[PullSteps](readRequest); + } +} +function ReadableStreamDefaultReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + var e = new TypeError('Reader was released'); + ReadableStreamDefaultReaderErrorReadRequests(reader, e); +} +function ReadableStreamDefaultReaderErrorReadRequests(reader, e) { + var readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(function (readRequest) { + readRequest._errorSteps(e); + }); +} +// Helper functions for the ReadableStreamDefaultReader. +function defaultReaderBrandCheckException(name) { + return new TypeError("ReadableStreamDefaultReader.prototype.".concat(name, " can only be used on a ReadableStreamDefaultReader")); +} + +var _a$1, _b, _c; +function CreateArrayFromList(elements) { + // We use arrays to represent lists, so this is basically a no-op. + // Do a slice though just in case we happen to depend on the unique-ness. + return elements.slice(); +} +function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { + new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); +} +var TransferArrayBuffer = function (O) { + if (typeof O.transfer === 'function') { + TransferArrayBuffer = function (buffer) { return buffer.transfer(); }; + } + else if (typeof structuredClone === 'function') { + TransferArrayBuffer = function (buffer) { return structuredClone(buffer, { transfer: [buffer] }); }; + } + else { + // Not implemented correctly + TransferArrayBuffer = function (buffer) { return buffer; }; + } + return TransferArrayBuffer(O); +}; +var IsDetachedBuffer = function (O) { + if (typeof O.detached === 'boolean') { + IsDetachedBuffer = function (buffer) { return buffer.detached; }; + } + else { + // Not implemented correctly + IsDetachedBuffer = function (buffer) { return buffer.byteLength === 0; }; + } + return IsDetachedBuffer(O); +}; +function ArrayBufferSlice(buffer, begin, end) { + // ArrayBuffer.prototype.slice is not available on IE10 + // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice + if (buffer.slice) { + return buffer.slice(begin, end); + } + var length = end - begin; + var slice = new ArrayBuffer(length); + CopyDataBlockBytes(slice, 0, buffer, begin, length); + return slice; +} +function GetMethod(receiver, prop) { + var func = receiver[prop]; + if (func === undefined || func === null) { + return undefined; + } + if (typeof func !== 'function') { + throw new TypeError("".concat(String(prop), " is not a function")); + } + return func; +} +function CreateAsyncFromSyncIterator(syncIteratorRecord) { + // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%, + // we use yield* inside an async generator function to achieve the same result. + var _a; + // Wrap the sync iterator inside a sync iterable, so we can use it with yield*. + var syncIterable = (_a = {}, + _a[SymbolPolyfill.iterator] = function () { return syncIteratorRecord.iterator; }, + _a); + // Create an async generator function and immediately invoke it. + var asyncIterator = (function () { + return __asyncGenerator(this, arguments, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [5 /*yield**/, __values(__asyncDelegator(__asyncValues(syncIterable)))]; + case 1: return [4 /*yield*/, __await.apply(void 0, [_a.sent()])]; + case 2: return [4 /*yield*/, __await.apply(void 0, [_a.sent()])]; + case 3: return [2 /*return*/, _a.sent()]; + } + }); + }); + }()); + // Return as an async iterator record. + var nextMethod = asyncIterator.next; + return { iterator: asyncIterator, nextMethod: nextMethod, done: false }; +} +// Aligns with core-js/modules/es.symbol.async-iterator.js +var SymbolAsyncIterator = (_c = (_a$1 = SymbolPolyfill.asyncIterator) !== null && _a$1 !== void 0 ? _a$1 : (_b = SymbolPolyfill.for) === null || _b === void 0 ? void 0 : _b.call(SymbolPolyfill, 'Symbol.asyncIterator')) !== null && _c !== void 0 ? _c : '@@asyncIterator'; +function GetIterator(obj, hint, method) { + if (hint === void 0) { hint = 'sync'; } + if (method === undefined) { + if (hint === 'async') { + method = GetMethod(obj, SymbolAsyncIterator); + if (method === undefined) { + var syncMethod = GetMethod(obj, SymbolPolyfill.iterator); + var syncIteratorRecord = GetIterator(obj, 'sync', syncMethod); + return CreateAsyncFromSyncIterator(syncIteratorRecord); + } + } + else { + method = GetMethod(obj, SymbolPolyfill.iterator); + } + } + if (method === undefined) { + throw new TypeError('The object is not iterable'); + } + var iterator = reflectCall(method, obj, []); + if (!typeIsObject(iterator)) { + throw new TypeError('The iterator method must return an object'); + } + var nextMethod = iterator.next; + return { iterator: iterator, nextMethod: nextMethod, done: false }; +} +function IteratorNext(iteratorRecord) { + var result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []); + if (!typeIsObject(result)) { + throw new TypeError('The iterator.next() method must return an object'); + } + return result; +} +function IteratorComplete(iterResult) { + return Boolean(iterResult.done); +} +function IteratorValue(iterResult) { + return iterResult.value; +} + +/// +var _a; +// We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it. +var AsyncIteratorPrototype = (_a = {}, + // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( ) + // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator + _a[SymbolAsyncIterator] = function () { + return this; + }, + _a); +Object.defineProperty(AsyncIteratorPrototype, SymbolAsyncIterator, { enumerable: false }); + +/// +var ReadableStreamAsyncIteratorImpl = /** @class */ (function () { + function ReadableStreamAsyncIteratorImpl(reader, preventCancel) { + this._ongoingPromise = undefined; + this._isFinished = false; + this._reader = reader; + this._preventCancel = preventCancel; + } + ReadableStreamAsyncIteratorImpl.prototype.next = function () { + var _this = this; + var nextSteps = function () { return _this._nextSteps(); }; + this._ongoingPromise = this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : + nextSteps(); + return this._ongoingPromise; + }; + ReadableStreamAsyncIteratorImpl.prototype.return = function (value) { + var _this = this; + var returnSteps = function () { return _this._returnSteps(value); }; + return this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : + returnSteps(); + }; + ReadableStreamAsyncIteratorImpl.prototype._nextSteps = function () { + var _this = this; + if (this._isFinished) { + return Promise.resolve({ value: undefined, done: true }); + } + var reader = this._reader; + var resolvePromise; + var rejectPromise; + var promise = newPromise(function (resolve, reject) { + resolvePromise = resolve; + rejectPromise = reject; + }); + var readRequest = { + _chunkSteps: function (chunk) { + _this._ongoingPromise = undefined; + // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test. + // FIXME Is this a bug in the specification, or in the test? + _queueMicrotask(function () { return resolvePromise({ value: chunk, done: false }); }); + }, + _closeSteps: function () { + _this._ongoingPromise = undefined; + _this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + resolvePromise({ value: undefined, done: true }); + }, + _errorSteps: function (reason) { + _this._ongoingPromise = undefined; + _this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + rejectPromise(reason); + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promise; + }; + ReadableStreamAsyncIteratorImpl.prototype._returnSteps = function (value) { + if (this._isFinished) { + return Promise.resolve({ value: value, done: true }); + } + this._isFinished = true; + var reader = this._reader; + if (!this._preventCancel) { + var result = ReadableStreamReaderGenericCancel(reader, value); + ReadableStreamReaderGenericRelease(reader); + return transformPromiseWith(result, function () { return ({ value: value, done: true }); }); + } + ReadableStreamReaderGenericRelease(reader); + return promiseResolvedWith({ value: value, done: true }); + }; + return ReadableStreamAsyncIteratorImpl; +}()); +var ReadableStreamAsyncIteratorPrototype = { + next: function () { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next')); + } + return this._asyncIteratorImpl.next(); + }, + return: function (value) { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return')); + } + return this._asyncIteratorImpl.return(value); + } +}; +Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); +// Abstract operations for the ReadableStream. +function AcquireReadableStreamAsyncIterator(stream, preventCancel) { + var reader = AcquireReadableStreamDefaultReader(stream); + var impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); + var iterator = Object.create(ReadableStreamAsyncIteratorPrototype); + iterator._asyncIteratorImpl = impl; + return iterator; +} +function IsReadableStreamAsyncIterator(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) { + return false; + } + try { + // noinspection SuspiciousTypeOfGuard + return x._asyncIteratorImpl instanceof + ReadableStreamAsyncIteratorImpl; + } + catch (_a) { + return false; + } +} +// Helper functions for the ReadableStream. +function streamAsyncIteratorBrandCheckException(name) { + return new TypeError("ReadableStreamAsyncIterator.".concat(name, " can only be used on a ReadableSteamAsyncIterator")); +} + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill +var NumberIsNaN = Number.isNaN || function (x) { + // eslint-disable-next-line no-self-compare + return x !== x; +}; + +function IsNonNegativeNumber(v) { + if (typeof v !== 'number') { + return false; + } + if (NumberIsNaN(v)) { + return false; + } + if (v < 0) { + return false; + } + return true; +} +function CloneAsUint8Array(O) { + var buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength); + return new Uint8Array(buffer); +} + +function DequeueValue(container) { + var pair = container._queue.shift(); + container._queueTotalSize -= pair.size; + if (container._queueTotalSize < 0) { + container._queueTotalSize = 0; + } + return pair.value; +} +function EnqueueValueWithSize(container, value, size) { + if (!IsNonNegativeNumber(size) || size === Infinity) { + throw new RangeError('Size must be a finite, non-NaN, non-negative number.'); + } + container._queue.push({ value: value, size: size }); + container._queueTotalSize += size; +} +function PeekQueueValue(container) { + var pair = container._queue.peek(); + return pair.value; +} +function ResetQueue(container) { + container._queue = new SimpleQueue(); + container._queueTotalSize = 0; +} + +function isDataViewConstructor(ctor) { + return ctor === DataView; +} +function isDataView(view) { + return isDataViewConstructor(view.constructor); +} +function arrayBufferViewElementSize(ctor) { + if (isDataViewConstructor(ctor)) { + return 1; + } + return ctor.BYTES_PER_ELEMENT; +} + +/** + * A pull-into request in a {@link ReadableByteStreamController}. + * + * @public + */ +var ReadableStreamBYOBRequest = /** @class */ (function () { + function ReadableStreamBYOBRequest() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(ReadableStreamBYOBRequest.prototype, "view", { + /** + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. + */ + get: function () { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('view'); + } + return this._view; + }, + enumerable: false, + configurable: true + }); + ReadableStreamBYOBRequest.prototype.respond = function (bytesWritten) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respond'); + } + assertRequiredArgument(bytesWritten, 1, 'respond'); + bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter'); + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(this._view.buffer)) { + throw new TypeError("The BYOB request's buffer has been detached and so cannot be used as a response"); + } + ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); + }; + ReadableStreamBYOBRequest.prototype.respondWithNewView = function (view) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respondWithNewView'); + } + assertRequiredArgument(view, 1, 'respondWithNewView'); + if (!ArrayBuffer.isView(view)) { + throw new TypeError('You can only respond with array buffer views'); + } + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(view.buffer)) { + throw new TypeError('The given view\'s buffer has been detached and so cannot be used as a response'); + } + ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); + }; + return ReadableStreamBYOBRequest; +}()); +Object.defineProperties(ReadableStreamBYOBRequest.prototype, { + respond: { enumerable: true }, + respondWithNewView: { enumerable: true }, + view: { enumerable: true } +}); +setFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond'); +setFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBRequest', + configurable: true + }); +} +/** + * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. + * + * @public + */ +var ReadableByteStreamController = /** @class */ (function () { + function ReadableByteStreamController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(ReadableByteStreamController.prototype, "byobRequest", { + /** + * Returns the current BYOB pull request, or `null` if there isn't one. + */ + get: function () { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('byobRequest'); + } + return ReadableByteStreamControllerGetBYOBRequest(this); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ReadableByteStreamController.prototype, "desiredSize", { + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + */ + get: function () { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('desiredSize'); + } + return ReadableByteStreamControllerGetDesiredSize(this); + }, + enumerable: false, + configurable: true + }); + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + ReadableByteStreamController.prototype.close = function () { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('close'); + } + if (this._closeRequested) { + throw new TypeError('The stream has already been closed; do not close it again!'); + } + var state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError("The stream (in ".concat(state, " state) is not in the readable state and cannot be closed")); + } + ReadableByteStreamControllerClose(this); + }; + ReadableByteStreamController.prototype.enqueue = function (chunk) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('enqueue'); + } + assertRequiredArgument(chunk, 1, 'enqueue'); + if (!ArrayBuffer.isView(chunk)) { + throw new TypeError('chunk must be an array buffer view'); + } + if (chunk.byteLength === 0) { + throw new TypeError('chunk must have non-zero byteLength'); + } + if (chunk.buffer.byteLength === 0) { + throw new TypeError("chunk's buffer must have non-zero byteLength"); + } + if (this._closeRequested) { + throw new TypeError('stream is closed or draining'); + } + var state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError("The stream (in ".concat(state, " state) is not in the readable state and cannot be enqueued to")); + } + ReadableByteStreamControllerEnqueue(this, chunk); + }; + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + ReadableByteStreamController.prototype.error = function (e) { + if (e === void 0) { e = undefined; } + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('error'); + } + ReadableByteStreamControllerError(this, e); + }; + /** @internal */ + ReadableByteStreamController.prototype[CancelSteps] = function (reason) { + ReadableByteStreamControllerClearPendingPullIntos(this); + ResetQueue(this); + var result = this._cancelAlgorithm(reason); + ReadableByteStreamControllerClearAlgorithms(this); + return result; + }; + /** @internal */ + ReadableByteStreamController.prototype[PullSteps] = function (readRequest) { + var stream = this._controlledReadableByteStream; + if (this._queueTotalSize > 0) { + ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest); + return; + } + var autoAllocateChunkSize = this._autoAllocateChunkSize; + if (autoAllocateChunkSize !== undefined) { + var buffer = void 0; + try { + buffer = new ArrayBuffer(autoAllocateChunkSize); + } + catch (bufferE) { + readRequest._errorSteps(bufferE); + return; + } + var pullIntoDescriptor = { + buffer: buffer, + bufferByteLength: autoAllocateChunkSize, + byteOffset: 0, + byteLength: autoAllocateChunkSize, + bytesFilled: 0, + minimumFill: 1, + elementSize: 1, + viewConstructor: Uint8Array, + readerType: 'default' + }; + this._pendingPullIntos.push(pullIntoDescriptor); + } + ReadableStreamAddReadRequest(stream, readRequest); + ReadableByteStreamControllerCallPullIfNeeded(this); + }; + /** @internal */ + ReadableByteStreamController.prototype[ReleaseSteps] = function () { + if (this._pendingPullIntos.length > 0) { + var firstPullInto = this._pendingPullIntos.peek(); + firstPullInto.readerType = 'none'; + this._pendingPullIntos = new SimpleQueue(); + this._pendingPullIntos.push(firstPullInto); + } + }; + return ReadableByteStreamController; +}()); +Object.defineProperties(ReadableByteStreamController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + byobRequest: { enumerable: true }, + desiredSize: { enumerable: true } +}); +setFunctionName(ReadableByteStreamController.prototype.close, 'close'); +setFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue'); +setFunctionName(ReadableByteStreamController.prototype.error, 'error'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableByteStreamController', + configurable: true + }); +} +// Abstract operations for the ReadableByteStreamController. +function IsReadableByteStreamController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) { + return false; + } + return x instanceof ReadableByteStreamController; +} +function IsReadableStreamBYOBRequest(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) { + return false; + } + return x instanceof ReadableStreamBYOBRequest; +} +function ReadableByteStreamControllerCallPullIfNeeded(controller) { + var shouldPull = ReadableByteStreamControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + // TODO: Test controller argument + var pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, function () { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + return null; + }, function (e) { + ReadableByteStreamControllerError(controller, e); + return null; + }); +} +function ReadableByteStreamControllerClearPendingPullIntos(controller) { + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + controller._pendingPullIntos = new SimpleQueue(); +} +function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { + var done = false; + if (stream._state === 'closed') { + done = true; + } + var filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'default') { + ReadableStreamFulfillReadRequest(stream, filledView, done); + } + else { + ReadableStreamFulfillReadIntoRequest(stream, filledView, done); + } +} +function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { + var bytesFilled = pullIntoDescriptor.bytesFilled; + var elementSize = pullIntoDescriptor.elementSize; + return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); +} +function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { + controller._queue.push({ buffer: buffer, byteOffset: byteOffset, byteLength: byteLength }); + controller._queueTotalSize += byteLength; +} +function ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, buffer, byteOffset, byteLength) { + var clonedChunk; + try { + clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength); + } + catch (cloneE) { + ReadableByteStreamControllerError(controller, cloneE); + throw cloneE; + } + ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength); +} +function ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstDescriptor) { + if (firstDescriptor.bytesFilled > 0) { + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, firstDescriptor.buffer, firstDescriptor.byteOffset, firstDescriptor.bytesFilled); + } + ReadableByteStreamControllerShiftPendingPullInto(controller); +} +function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { + var maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); + var maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; + var totalBytesToCopyRemaining = maxBytesToCopy; + var ready = false; + var remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize; + var maxAlignedBytes = maxBytesFilled - remainderBytes; + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) { + totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; + ready = true; + } + var queue = controller._queue; + while (totalBytesToCopyRemaining > 0) { + var headOfQueue = queue.peek(); + var bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); + var destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); + if (headOfQueue.byteLength === bytesToCopy) { + queue.shift(); + } + else { + headOfQueue.byteOffset += bytesToCopy; + headOfQueue.byteLength -= bytesToCopy; + } + controller._queueTotalSize -= bytesToCopy; + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); + totalBytesToCopyRemaining -= bytesToCopy; + } + return ready; +} +function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { + pullIntoDescriptor.bytesFilled += size; +} +function ReadableByteStreamControllerHandleQueueDrain(controller) { + if (controller._queueTotalSize === 0 && controller._closeRequested) { + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(controller._controlledReadableByteStream); + } + else { + ReadableByteStreamControllerCallPullIfNeeded(controller); + } +} +function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { + if (controller._byobRequest === null) { + return; + } + controller._byobRequest._associatedReadableByteStreamController = undefined; + controller._byobRequest._view = null; + controller._byobRequest = null; +} +function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { + while (controller._pendingPullIntos.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + var pullIntoDescriptor = controller._pendingPullIntos.peek(); + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + } + } +} +function ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller) { + var reader = controller._controlledReadableByteStream._reader; + while (reader._readRequests.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + var readRequest = reader._readRequests.shift(); + ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest); + } +} +function ReadableByteStreamControllerPullInto(controller, view, min, readIntoRequest) { + var stream = controller._controlledReadableByteStream; + var ctor = view.constructor; + var elementSize = arrayBufferViewElementSize(ctor); + var byteOffset = view.byteOffset, byteLength = view.byteLength; + var minimumFill = min * elementSize; + var buffer; + try { + buffer = TransferArrayBuffer(view.buffer); + } + catch (e) { + readIntoRequest._errorSteps(e); + return; + } + var pullIntoDescriptor = { + buffer: buffer, + bufferByteLength: buffer.byteLength, + byteOffset: byteOffset, + byteLength: byteLength, + bytesFilled: 0, + minimumFill: minimumFill, + elementSize: elementSize, + viewConstructor: ctor, + readerType: 'byob' + }; + if (controller._pendingPullIntos.length > 0) { + controller._pendingPullIntos.push(pullIntoDescriptor); + // No ReadableByteStreamControllerCallPullIfNeeded() call since: + // - No change happens on desiredSize + // - The source has already been notified of that there's at least 1 pending read(view) + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + return; + } + if (stream._state === 'closed') { + var emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); + readIntoRequest._closeSteps(emptyView); + return; + } + if (controller._queueTotalSize > 0) { + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + var filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + ReadableByteStreamControllerHandleQueueDrain(controller); + readIntoRequest._chunkSteps(filledView); + return; + } + if (controller._closeRequested) { + var e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + readIntoRequest._errorSteps(e); + return; + } + } + controller._pendingPullIntos.push(pullIntoDescriptor); + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { + if (firstDescriptor.readerType === 'none') { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + var stream = controller._controlledReadableByteStream; + if (ReadableStreamHasBYOBReader(stream)) { + while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { + var pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); + } + } +} +function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + return; + } + if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) { + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + return; + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + var remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; + if (remainderSize > 0) { + var end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor.buffer, end - remainderSize, remainderSize); + } + pullIntoDescriptor.bytesFilled -= remainderSize; + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); +} +function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { + var firstDescriptor = controller._pendingPullIntos.peek(); + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + var state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor); + } + else { + ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerShiftPendingPullInto(controller) { + var descriptor = controller._pendingPullIntos.shift(); + return descriptor; +} +function ReadableByteStreamControllerShouldCallPull(controller) { + var stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return false; + } + if (controller._closeRequested) { + return false; + } + if (!controller._started) { + return false; + } + if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { + return true; + } + var desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; +} +function ReadableByteStreamControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; +} +// A client of ReadableByteStreamController may use these functions directly to bypass state check. +function ReadableByteStreamControllerClose(controller) { + var stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + if (controller._queueTotalSize > 0) { + controller._closeRequested = true; + return; + } + if (controller._pendingPullIntos.length > 0) { + var firstPendingPullInto = controller._pendingPullIntos.peek(); + if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) { + var e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + throw e; + } + } + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(stream); +} +function ReadableByteStreamControllerEnqueue(controller, chunk) { + var stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + var buffer = chunk.buffer, byteOffset = chunk.byteOffset, byteLength = chunk.byteLength; + if (IsDetachedBuffer(buffer)) { + throw new TypeError('chunk\'s buffer is detached and so cannot be enqueued'); + } + var transferredBuffer = TransferArrayBuffer(buffer); + if (controller._pendingPullIntos.length > 0) { + var firstPendingPullInto = controller._pendingPullIntos.peek(); + if (IsDetachedBuffer(firstPendingPullInto.buffer)) { + throw new TypeError('The BYOB request\'s buffer has been detached and so cannot be filled with an enqueued chunk'); + } + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer); + if (firstPendingPullInto.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto); + } + } + if (ReadableStreamHasDefaultReader(stream)) { + ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller); + if (ReadableStreamGetNumReadRequests(stream) === 0) { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + else { + if (controller._pendingPullIntos.length > 0) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + var transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); + ReadableStreamFulfillReadRequest(stream, transferredView, false); + } + } + else if (ReadableStreamHasBYOBReader(stream)) { + // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully. + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + else { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerError(controller, e) { + var stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return; + } + ReadableByteStreamControllerClearPendingPullIntos(controller); + ResetQueue(controller); + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); +} +function ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest) { + var entry = controller._queue.shift(); + controller._queueTotalSize -= entry.byteLength; + ReadableByteStreamControllerHandleQueueDrain(controller); + var view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); + readRequest._chunkSteps(view); +} +function ReadableByteStreamControllerGetBYOBRequest(controller) { + if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) { + var firstDescriptor = controller._pendingPullIntos.peek(); + var view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); + var byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); + SetUpReadableStreamBYOBRequest(byobRequest, controller, view); + controller._byobRequest = byobRequest; + } + return controller._byobRequest; +} +function ReadableByteStreamControllerGetDesiredSize(controller) { + var state = controller._controlledReadableByteStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; +} +function ReadableByteStreamControllerRespond(controller, bytesWritten) { + var firstDescriptor = controller._pendingPullIntos.peek(); + var state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (bytesWritten !== 0) { + throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream'); + } + } + else { + if (bytesWritten === 0) { + throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream'); + } + if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) { + throw new RangeError('bytesWritten out of range'); + } + } + firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); + ReadableByteStreamControllerRespondInternal(controller, bytesWritten); +} +function ReadableByteStreamControllerRespondWithNewView(controller, view) { + var firstDescriptor = controller._pendingPullIntos.peek(); + var state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (view.byteLength !== 0) { + throw new TypeError('The view\'s length must be 0 when calling respondWithNewView() on a closed stream'); + } + } + else { + if (view.byteLength === 0) { + throw new TypeError('The view\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'); + } + } + if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { + throw new RangeError('The region specified by view does not match byobRequest'); + } + if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) { + throw new RangeError('The buffer of view has different capacity than byobRequest'); + } + if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) { + throw new RangeError('The region specified by view is larger than byobRequest'); + } + var viewByteLength = view.byteLength; + firstDescriptor.buffer = TransferArrayBuffer(view.buffer); + ReadableByteStreamControllerRespondInternal(controller, viewByteLength); +} +function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { + controller._controlledReadableByteStream = stream; + controller._pullAgain = false; + controller._pulling = false; + controller._byobRequest = null; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._closeRequested = false; + controller._started = false; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._autoAllocateChunkSize = autoAllocateChunkSize; + controller._pendingPullIntos = new SimpleQueue(); + stream._readableStreamController = controller; + var startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), function () { + controller._started = true; + ReadableByteStreamControllerCallPullIfNeeded(controller); + return null; + }, function (r) { + ReadableByteStreamControllerError(controller, r); + return null; + }); +} +function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { + var controller = Object.create(ReadableByteStreamController.prototype); + var startAlgorithm; + var pullAlgorithm; + var cancelAlgorithm; + if (underlyingByteSource.start !== undefined) { + startAlgorithm = function () { return underlyingByteSource.start(controller); }; + } + else { + startAlgorithm = function () { return undefined; }; + } + if (underlyingByteSource.pull !== undefined) { + pullAlgorithm = function () { return underlyingByteSource.pull(controller); }; + } + else { + pullAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + if (underlyingByteSource.cancel !== undefined) { + cancelAlgorithm = function (reason) { return underlyingByteSource.cancel(reason); }; + } + else { + cancelAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + var autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; + if (autoAllocateChunkSize === 0) { + throw new TypeError('autoAllocateChunkSize must be greater than 0'); + } + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); +} +function SetUpReadableStreamBYOBRequest(request, controller, view) { + request._associatedReadableByteStreamController = controller; + request._view = view; +} +// Helper functions for the ReadableStreamBYOBRequest. +function byobRequestBrandCheckException(name) { + return new TypeError("ReadableStreamBYOBRequest.prototype.".concat(name, " can only be used on a ReadableStreamBYOBRequest")); +} +// Helper functions for the ReadableByteStreamController. +function byteStreamControllerBrandCheckException(name) { + return new TypeError("ReadableByteStreamController.prototype.".concat(name, " can only be used on a ReadableByteStreamController")); +} + +function convertReaderOptions(options, context) { + assertDictionary(options, context); + var mode = options === null || options === void 0 ? void 0 : options.mode; + return { + mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, "".concat(context, " has member 'mode' that")) + }; +} +function convertReadableStreamReaderMode(mode, context) { + mode = "".concat(mode); + if (mode !== 'byob') { + throw new TypeError("".concat(context, " '").concat(mode, "' is not a valid enumeration value for ReadableStreamReaderMode")); + } + return mode; +} +function convertByobReadOptions(options, context) { + var _a; + assertDictionary(options, context); + var min = (_a = options === null || options === void 0 ? void 0 : options.min) !== null && _a !== void 0 ? _a : 1; + return { + min: convertUnsignedLongLongWithEnforceRange(min, "".concat(context, " has member 'min' that")) + }; +} + +// Abstract operations for the ReadableStream. +function AcquireReadableStreamBYOBReader(stream) { + return new ReadableStreamBYOBReader(stream); +} +// ReadableStream API exposed for controllers. +function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { + stream._reader._readIntoRequests.push(readIntoRequest); +} +function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { + var reader = stream._reader; + var readIntoRequest = reader._readIntoRequests.shift(); + if (done) { + readIntoRequest._closeSteps(chunk); + } + else { + readIntoRequest._chunkSteps(chunk); + } +} +function ReadableStreamGetNumReadIntoRequests(stream) { + return stream._reader._readIntoRequests.length; +} +function ReadableStreamHasBYOBReader(stream) { + var reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamBYOBReader(reader)) { + return false; + } + return true; +} +/** + * A BYOB reader vended by a {@link ReadableStream}. + * + * @public + */ +var ReadableStreamBYOBReader = /** @class */ (function () { + function ReadableStreamBYOBReader(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + if (!IsReadableByteStreamController(stream._readableStreamController)) { + throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' + + 'source'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readIntoRequests = new SimpleQueue(); + } + Object.defineProperty(ReadableStreamBYOBReader.prototype, "closed", { + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the reader's lock is released before the stream finishes closing. + */ + get: function () { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('closed')); + } + return this._closedPromise; + }, + enumerable: false, + configurable: true + }); + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + ReadableStreamBYOBReader.prototype.cancel = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + }; + ReadableStreamBYOBReader.prototype.read = function (view, rawOptions) { + if (rawOptions === void 0) { rawOptions = {}; } + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('read')); + } + if (!ArrayBuffer.isView(view)) { + return promiseRejectedWith(new TypeError('view must be an array buffer view')); + } + if (view.byteLength === 0) { + return promiseRejectedWith(new TypeError('view must have non-zero byteLength')); + } + if (view.buffer.byteLength === 0) { + return promiseRejectedWith(new TypeError("view's buffer must have non-zero byteLength")); + } + if (IsDetachedBuffer(view.buffer)) { + return promiseRejectedWith(new TypeError('view\'s buffer has been detached')); + } + var options; + try { + options = convertByobReadOptions(rawOptions, 'options'); + } + catch (e) { + return promiseRejectedWith(e); + } + var min = options.min; + if (min === 0) { + return promiseRejectedWith(new TypeError('options.min must be greater than 0')); + } + if (!isDataView(view)) { + if (min > view.length) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s length')); + } + } + else if (min > view.byteLength) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s byteLength')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + var resolvePromise; + var rejectPromise; + var promise = newPromise(function (resolve, reject) { + resolvePromise = resolve; + rejectPromise = reject; + }); + var readIntoRequest = { + _chunkSteps: function (chunk) { return resolvePromise({ value: chunk, done: false }); }, + _closeSteps: function (chunk) { return resolvePromise({ value: chunk, done: true }); }, + _errorSteps: function (e) { return rejectPromise(e); } + }; + ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest); + return promise; + }; + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + ReadableStreamBYOBReader.prototype.releaseLock = function () { + if (!IsReadableStreamBYOBReader(this)) { + throw byobReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamBYOBReaderRelease(this); + }; + return ReadableStreamBYOBReader; +}()); +Object.defineProperties(ReadableStreamBYOBReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } +}); +setFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel'); +setFunctionName(ReadableStreamBYOBReader.prototype.read, 'read'); +setFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBReader', + configurable: true + }); +} +// Abstract operations for the readers. +function IsReadableStreamBYOBReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) { + return false; + } + return x instanceof ReadableStreamBYOBReader; +} +function ReadableStreamBYOBReaderRead(reader, view, min, readIntoRequest) { + var stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'errored') { + readIntoRequest._errorSteps(stream._storedError); + } + else { + ReadableByteStreamControllerPullInto(stream._readableStreamController, view, min, readIntoRequest); + } +} +function ReadableStreamBYOBReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + var e = new TypeError('Reader was released'); + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); +} +function ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e) { + var readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(function (readIntoRequest) { + readIntoRequest._errorSteps(e); + }); +} +// Helper functions for the ReadableStreamBYOBReader. +function byobReaderBrandCheckException(name) { + return new TypeError("ReadableStreamBYOBReader.prototype.".concat(name, " can only be used on a ReadableStreamBYOBReader")); +} + +function ExtractHighWaterMark(strategy, defaultHWM) { + var highWaterMark = strategy.highWaterMark; + if (highWaterMark === undefined) { + return defaultHWM; + } + if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { + throw new RangeError('Invalid highWaterMark'); + } + return highWaterMark; +} +function ExtractSizeAlgorithm(strategy) { + var size = strategy.size; + if (!size) { + return function () { return 1; }; + } + return size; +} + +function convertQueuingStrategy(init, context) { + assertDictionary(init, context); + var highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + var size = init === null || init === void 0 ? void 0 : init.size; + return { + highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark), + size: size === undefined ? undefined : convertQueuingStrategySize(size, "".concat(context, " has member 'size' that")) + }; +} +function convertQueuingStrategySize(fn, context) { + assertFunction(fn, context); + return function (chunk) { return convertUnrestrictedDouble(fn(chunk)); }; +} + +function convertUnderlyingSink(original, context) { + assertDictionary(original, context); + var abort = original === null || original === void 0 ? void 0 : original.abort; + var close = original === null || original === void 0 ? void 0 : original.close; + var start = original === null || original === void 0 ? void 0 : original.start; + var type = original === null || original === void 0 ? void 0 : original.type; + var write = original === null || original === void 0 ? void 0 : original.write; + return { + abort: abort === undefined ? + undefined : + convertUnderlyingSinkAbortCallback(abort, original, "".concat(context, " has member 'abort' that")), + close: close === undefined ? + undefined : + convertUnderlyingSinkCloseCallback(close, original, "".concat(context, " has member 'close' that")), + start: start === undefined ? + undefined : + convertUnderlyingSinkStartCallback(start, original, "".concat(context, " has member 'start' that")), + write: write === undefined ? + undefined : + convertUnderlyingSinkWriteCallback(write, original, "".concat(context, " has member 'write' that")), + type: type + }; +} +function convertUnderlyingSinkAbortCallback(fn, original, context) { + assertFunction(fn, context); + return function (reason) { return promiseCall(fn, original, [reason]); }; +} +function convertUnderlyingSinkCloseCallback(fn, original, context) { + assertFunction(fn, context); + return function () { return promiseCall(fn, original, []); }; +} +function convertUnderlyingSinkStartCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return reflectCall(fn, original, [controller]); }; +} +function convertUnderlyingSinkWriteCallback(fn, original, context) { + assertFunction(fn, context); + return function (chunk, controller) { return promiseCall(fn, original, [chunk, controller]); }; +} + +function assertWritableStream(x, context) { + if (!IsWritableStream(x)) { + throw new TypeError("".concat(context, " is not a WritableStream.")); + } +} + +function isAbortSignal(value) { + if (typeof value !== 'object' || value === null) { + return false; + } + try { + return typeof value.aborted === 'boolean'; + } + catch (_a) { + // AbortSignal.prototype.aborted throws if its brand check fails + return false; + } +} +var supportsAbortController = typeof AbortController === 'function'; +/** + * Construct a new AbortController, if supported by the platform. + * + * @internal + */ +function createAbortController() { + if (supportsAbortController) { + return new AbortController(); + } + return undefined; +} + +/** + * A writable stream represents a destination for data, into which you can write. + * + * @public + */ +var WritableStream = /** @class */ (function () { + function WritableStream(rawUnderlyingSink, rawStrategy) { + if (rawUnderlyingSink === void 0) { rawUnderlyingSink = {}; } + if (rawStrategy === void 0) { rawStrategy = {}; } + if (rawUnderlyingSink === undefined) { + rawUnderlyingSink = null; + } + else { + assertObject(rawUnderlyingSink, 'First parameter'); + } + var strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + var underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter'); + InitializeWritableStream(this); + var type = underlyingSink.type; + if (type !== undefined) { + throw new RangeError('Invalid type is specified'); + } + var sizeAlgorithm = ExtractSizeAlgorithm(strategy); + var highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); + } + Object.defineProperty(WritableStream.prototype, "locked", { + /** + * Returns whether or not the writable stream is locked to a writer. + */ + get: function () { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('locked'); + } + return IsWritableStreamLocked(this); + }, + enumerable: false, + configurable: true + }); + /** + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort + * mechanism of the underlying sink. + * + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel + * the stream) if the stream is currently locked. + */ + WritableStream.prototype.abort = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('abort')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer')); + } + return WritableStreamAbort(this, reason); + }; + /** + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its + * close behavior. During this time any further attempts to write will fail (without erroring the stream). + * + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + */ + WritableStream.prototype.close = function () { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('close')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer')); + } + if (WritableStreamCloseQueuedOrInFlight(this)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamClose(this); + }; + /** + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream + * is locked, no other writer can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at + * the same time, which would cause the resulting written data to be unpredictable and probably useless. + */ + WritableStream.prototype.getWriter = function () { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('getWriter'); + } + return AcquireWritableStreamDefaultWriter(this); + }; + return WritableStream; +}()); +Object.defineProperties(WritableStream.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + getWriter: { enumerable: true }, + locked: { enumerable: true } +}); +setFunctionName(WritableStream.prototype.abort, 'abort'); +setFunctionName(WritableStream.prototype.close, 'close'); +setFunctionName(WritableStream.prototype.getWriter, 'getWriter'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStream', + configurable: true + }); +} +// Abstract operations for the WritableStream. +function AcquireWritableStreamDefaultWriter(stream) { + return new WritableStreamDefaultWriter(stream); +} +// Throws if and only if startAlgorithm throws. +function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + if (highWaterMark === void 0) { highWaterMark = 1; } + if (sizeAlgorithm === void 0) { sizeAlgorithm = function () { return 1; }; } + var stream = Object.create(WritableStream.prototype); + InitializeWritableStream(stream); + var controller = Object.create(WritableStreamDefaultController.prototype); + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + return stream; +} +function InitializeWritableStream(stream) { + stream._state = 'writable'; + // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is + // 'erroring' or 'errored'. May be set to an undefined value. + stream._storedError = undefined; + stream._writer = undefined; + // Initialize to undefined first because the constructor of the controller checks this + // variable to validate the caller. + stream._writableStreamController = undefined; + // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data + // producer without waiting for the queued writes to finish. + stream._writeRequests = new SimpleQueue(); + // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents + // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here. + stream._inFlightWriteRequest = undefined; + // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer + // has been detached. + stream._closeRequest = undefined; + // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it + // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here. + stream._inFlightCloseRequest = undefined; + // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached. + stream._pendingAbortRequest = undefined; + // The backpressure signal set by the controller. + stream._backpressure = false; +} +function IsWritableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) { + return false; + } + return x instanceof WritableStream; +} +function IsWritableStreamLocked(stream) { + if (stream._writer === undefined) { + return false; + } + return true; +} +function WritableStreamAbort(stream, reason) { + var _a; + if (stream._state === 'closed' || stream._state === 'errored') { + return promiseResolvedWith(undefined); + } + stream._writableStreamController._abortReason = reason; + (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort(reason); + // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring', + // but it doesn't know that signaling abort runs author code that might have changed the state. + // Widen the type again by casting to WritableStreamState. + var state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseResolvedWith(undefined); + } + if (stream._pendingAbortRequest !== undefined) { + return stream._pendingAbortRequest._promise; + } + var wasAlreadyErroring = false; + if (state === 'erroring') { + wasAlreadyErroring = true; + // reason will not be used, so don't keep a reference to it. + reason = undefined; + } + var promise = newPromise(function (resolve, reject) { + stream._pendingAbortRequest = { + _promise: undefined, + _resolve: resolve, + _reject: reject, + _reason: reason, + _wasAlreadyErroring: wasAlreadyErroring + }; + }); + stream._pendingAbortRequest._promise = promise; + if (!wasAlreadyErroring) { + WritableStreamStartErroring(stream, reason); + } + return promise; +} +function WritableStreamClose(stream) { + var state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseRejectedWith(new TypeError("The stream (in ".concat(state, " state) is not in the writable state and cannot be closed"))); + } + var promise = newPromise(function (resolve, reject) { + var closeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._closeRequest = closeRequest; + }); + var writer = stream._writer; + if (writer !== undefined && stream._backpressure && state === 'writable') { + defaultWriterReadyPromiseResolve(writer); + } + WritableStreamDefaultControllerClose(stream._writableStreamController); + return promise; +} +// WritableStream API exposed for controllers. +function WritableStreamAddWriteRequest(stream) { + var promise = newPromise(function (resolve, reject) { + var writeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._writeRequests.push(writeRequest); + }); + return promise; +} +function WritableStreamDealWithRejection(stream, error) { + var state = stream._state; + if (state === 'writable') { + WritableStreamStartErroring(stream, error); + return; + } + WritableStreamFinishErroring(stream); +} +function WritableStreamStartErroring(stream, reason) { + var controller = stream._writableStreamController; + stream._state = 'erroring'; + stream._storedError = reason; + var writer = stream._writer; + if (writer !== undefined) { + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); + } + if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { + WritableStreamFinishErroring(stream); + } +} +function WritableStreamFinishErroring(stream) { + stream._state = 'errored'; + stream._writableStreamController[ErrorSteps](); + var storedError = stream._storedError; + stream._writeRequests.forEach(function (writeRequest) { + writeRequest._reject(storedError); + }); + stream._writeRequests = new SimpleQueue(); + if (stream._pendingAbortRequest === undefined) { + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + var abortRequest = stream._pendingAbortRequest; + stream._pendingAbortRequest = undefined; + if (abortRequest._wasAlreadyErroring) { + abortRequest._reject(storedError); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + var promise = stream._writableStreamController[AbortSteps](abortRequest._reason); + uponPromise(promise, function () { + abortRequest._resolve(); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }, function (reason) { + abortRequest._reject(reason); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }); +} +function WritableStreamFinishInFlightWrite(stream) { + stream._inFlightWriteRequest._resolve(undefined); + stream._inFlightWriteRequest = undefined; +} +function WritableStreamFinishInFlightWriteWithError(stream, error) { + stream._inFlightWriteRequest._reject(error); + stream._inFlightWriteRequest = undefined; + WritableStreamDealWithRejection(stream, error); +} +function WritableStreamFinishInFlightClose(stream) { + stream._inFlightCloseRequest._resolve(undefined); + stream._inFlightCloseRequest = undefined; + var state = stream._state; + if (state === 'erroring') { + // The error was too late to do anything, so it is ignored. + stream._storedError = undefined; + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._resolve(); + stream._pendingAbortRequest = undefined; + } + } + stream._state = 'closed'; + var writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseResolve(writer); + } +} +function WritableStreamFinishInFlightCloseWithError(stream, error) { + stream._inFlightCloseRequest._reject(error); + stream._inFlightCloseRequest = undefined; + // Never execute sink abort() after sink close(). + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._reject(error); + stream._pendingAbortRequest = undefined; + } + WritableStreamDealWithRejection(stream, error); +} +// TODO(ricea): Fix alphabetical order. +function WritableStreamCloseQueuedOrInFlight(stream) { + if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; +} +function WritableStreamHasOperationMarkedInFlight(stream) { + if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; +} +function WritableStreamMarkCloseRequestInFlight(stream) { + stream._inFlightCloseRequest = stream._closeRequest; + stream._closeRequest = undefined; +} +function WritableStreamMarkFirstWriteRequestInFlight(stream) { + stream._inFlightWriteRequest = stream._writeRequests.shift(); +} +function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { + if (stream._closeRequest !== undefined) { + stream._closeRequest._reject(stream._storedError); + stream._closeRequest = undefined; + } + var writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseReject(writer, stream._storedError); + } +} +function WritableStreamUpdateBackpressure(stream, backpressure) { + var writer = stream._writer; + if (writer !== undefined && backpressure !== stream._backpressure) { + if (backpressure) { + defaultWriterReadyPromiseReset(writer); + } + else { + defaultWriterReadyPromiseResolve(writer); + } + } + stream._backpressure = backpressure; +} +/** + * A default writer vended by a {@link WritableStream}. + * + * @public + */ +var WritableStreamDefaultWriter = /** @class */ (function () { + function WritableStreamDefaultWriter(stream) { + assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter'); + assertWritableStream(stream, 'First parameter'); + if (IsWritableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive writing by another writer'); + } + this._ownerWritableStream = stream; + stream._writer = this; + var state = stream._state; + if (state === 'writable') { + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { + defaultWriterReadyPromiseInitialize(this); + } + else { + defaultWriterReadyPromiseInitializeAsResolved(this); + } + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'erroring') { + defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'closed') { + defaultWriterReadyPromiseInitializeAsResolved(this); + defaultWriterClosedPromiseInitializeAsResolved(this); + } + else { + var storedError = stream._storedError; + defaultWriterReadyPromiseInitializeAsRejected(this, storedError); + defaultWriterClosedPromiseInitializeAsRejected(this, storedError); + } + } + Object.defineProperty(WritableStreamDefaultWriter.prototype, "closed", { + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the writer’s lock is released before the stream finishes closing. + */ + get: function () { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('closed')); + } + return this._closedPromise; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(WritableStreamDefaultWriter.prototype, "desiredSize", { + /** + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. + * A producer can use this information to determine the right amount of data to write. + * + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when + * the writer’s lock is released. + */ + get: function () { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('desiredSize'); + } + if (this._ownerWritableStream === undefined) { + throw defaultWriterLockException('desiredSize'); + } + return WritableStreamDefaultWriterGetDesiredSize(this); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(WritableStreamDefaultWriter.prototype, "ready", { + /** + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips + * back to zero or below, the getter will return a new promise that stays pending until the next transition. + * + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become + * rejected. + */ + get: function () { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('ready')); + } + return this._readyPromise; + }, + enumerable: false, + configurable: true + }); + /** + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + */ + WritableStreamDefaultWriter.prototype.abort = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('abort')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('abort')); + } + return WritableStreamDefaultWriterAbort(this, reason); + }; + /** + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + */ + WritableStreamDefaultWriter.prototype.close = function () { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('close')); + } + var stream = this._ownerWritableStream; + if (stream === undefined) { + return promiseRejectedWith(defaultWriterLockException('close')); + } + if (WritableStreamCloseQueuedOrInFlight(stream)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamDefaultWriterClose(this); + }; + /** + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from + * now on; otherwise, the writer will appear closed. + * + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents + * other producers from writing in an interleaved manner. + */ + WritableStreamDefaultWriter.prototype.releaseLock = function () { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('releaseLock'); + } + var stream = this._ownerWritableStream; + if (stream === undefined) { + return; + } + WritableStreamDefaultWriterRelease(this); + }; + WritableStreamDefaultWriter.prototype.write = function (chunk) { + if (chunk === void 0) { chunk = undefined; } + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('write')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + return WritableStreamDefaultWriterWrite(this, chunk); + }; + return WritableStreamDefaultWriter; +}()); +Object.defineProperties(WritableStreamDefaultWriter.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + releaseLock: { enumerable: true }, + write: { enumerable: true }, + closed: { enumerable: true }, + desiredSize: { enumerable: true }, + ready: { enumerable: true } +}); +setFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort'); +setFunctionName(WritableStreamDefaultWriter.prototype.close, 'close'); +setFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock'); +setFunctionName(WritableStreamDefaultWriter.prototype.write, 'write'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultWriter', + configurable: true + }); +} +// Abstract operations for the WritableStreamDefaultWriter. +function IsWritableStreamDefaultWriter(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultWriter; +} +// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check. +function WritableStreamDefaultWriterAbort(writer, reason) { + var stream = writer._ownerWritableStream; + return WritableStreamAbort(stream, reason); +} +function WritableStreamDefaultWriterClose(writer) { + var stream = writer._ownerWritableStream; + return WritableStreamClose(stream); +} +function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { + var stream = writer._ownerWritableStream; + var state = stream._state; + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseResolvedWith(undefined); + } + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + return WritableStreamDefaultWriterClose(writer); +} +function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { + if (writer._closedPromiseState === 'pending') { + defaultWriterClosedPromiseReject(writer, error); + } + else { + defaultWriterClosedPromiseResetToRejected(writer, error); + } +} +function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { + if (writer._readyPromiseState === 'pending') { + defaultWriterReadyPromiseReject(writer, error); + } + else { + defaultWriterReadyPromiseResetToRejected(writer, error); + } +} +function WritableStreamDefaultWriterGetDesiredSize(writer) { + var stream = writer._ownerWritableStream; + var state = stream._state; + if (state === 'errored' || state === 'erroring') { + return null; + } + if (state === 'closed') { + return 0; + } + return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); +} +function WritableStreamDefaultWriterRelease(writer) { + var stream = writer._ownerWritableStream; + var releasedError = new TypeError("Writer was released and can no longer be used to monitor the stream's closedness"); + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); + // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not + // rejected until afterwards. This means that simply testing state will not work. + WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); + stream._writer = undefined; + writer._ownerWritableStream = undefined; +} +function WritableStreamDefaultWriterWrite(writer, chunk) { + var stream = writer._ownerWritableStream; + var controller = stream._writableStreamController; + var chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); + if (stream !== writer._ownerWritableStream) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + var state = stream._state; + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to')); + } + if (state === 'erroring') { + return promiseRejectedWith(stream._storedError); + } + var promise = WritableStreamAddWriteRequest(stream); + WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); + return promise; +} +var closeSentinel = {}; +/** + * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. + * + * @public + */ +var WritableStreamDefaultController = /** @class */ (function () { + function WritableStreamDefaultController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(WritableStreamDefaultController.prototype, "abortReason", { + /** + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. + * + * @deprecated + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. + */ + get: function () { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('abortReason'); + } + return this._abortReason; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(WritableStreamDefaultController.prototype, "signal", { + /** + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. + */ + get: function () { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('signal'); + } + if (this._abortController === undefined) { + // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`. + // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill, + // so instead we only implement support for `signal` if we find a global `AbortController` constructor. + throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported'); + } + return this._abortController.signal; + }, + enumerable: false, + configurable: true + }); + /** + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. + * + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the + * normal lifecycle of interactions with the underlying sink. + */ + WritableStreamDefaultController.prototype.error = function (e) { + if (e === void 0) { e = undefined; } + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('error'); + } + var state = this._controlledWritableStream._state; + if (state !== 'writable') { + // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so + // just treat it as a no-op. + return; + } + WritableStreamDefaultControllerError(this, e); + }; + /** @internal */ + WritableStreamDefaultController.prototype[AbortSteps] = function (reason) { + var result = this._abortAlgorithm(reason); + WritableStreamDefaultControllerClearAlgorithms(this); + return result; + }; + /** @internal */ + WritableStreamDefaultController.prototype[ErrorSteps] = function () { + ResetQueue(this); + }; + return WritableStreamDefaultController; +}()); +Object.defineProperties(WritableStreamDefaultController.prototype, { + abortReason: { enumerable: true }, + signal: { enumerable: true }, + error: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultController', + configurable: true + }); +} +// Abstract operations implementing interface required by the WritableStream. +function IsWritableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultController; +} +function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledWritableStream = stream; + stream._writableStreamController = controller; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._abortReason = undefined; + controller._abortController = createAbortController(); + controller._started = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._writeAlgorithm = writeAlgorithm; + controller._closeAlgorithm = closeAlgorithm; + controller._abortAlgorithm = abortAlgorithm; + var backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + var startResult = startAlgorithm(); + var startPromise = promiseResolvedWith(startResult); + uponPromise(startPromise, function () { + controller._started = true; + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, function (r) { + controller._started = true; + WritableStreamDealWithRejection(stream, r); + return null; + }); +} +function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { + var controller = Object.create(WritableStreamDefaultController.prototype); + var startAlgorithm; + var writeAlgorithm; + var closeAlgorithm; + var abortAlgorithm; + if (underlyingSink.start !== undefined) { + startAlgorithm = function () { return underlyingSink.start(controller); }; + } + else { + startAlgorithm = function () { return undefined; }; + } + if (underlyingSink.write !== undefined) { + writeAlgorithm = function (chunk) { return underlyingSink.write(chunk, controller); }; + } + else { + writeAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + if (underlyingSink.close !== undefined) { + closeAlgorithm = function () { return underlyingSink.close(); }; + } + else { + closeAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + if (underlyingSink.abort !== undefined) { + abortAlgorithm = function (reason) { return underlyingSink.abort(reason); }; + } + else { + abortAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); +} +// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls. +function WritableStreamDefaultControllerClearAlgorithms(controller) { + controller._writeAlgorithm = undefined; + controller._closeAlgorithm = undefined; + controller._abortAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; +} +function WritableStreamDefaultControllerClose(controller) { + EnqueueValueWithSize(controller, closeSentinel, 0); + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); +} +function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { + try { + return controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); + return 1; + } +} +function WritableStreamDefaultControllerGetDesiredSize(controller) { + return controller._strategyHWM - controller._queueTotalSize; +} +function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); + return; + } + var stream = controller._controlledWritableStream; + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') { + var backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); +} +// Abstract operations for the WritableStreamDefaultController. +function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { + var stream = controller._controlledWritableStream; + if (!controller._started) { + return; + } + if (stream._inFlightWriteRequest !== undefined) { + return; + } + var state = stream._state; + if (state === 'erroring') { + WritableStreamFinishErroring(stream); + return; + } + if (controller._queue.length === 0) { + return; + } + var value = PeekQueueValue(controller); + if (value === closeSentinel) { + WritableStreamDefaultControllerProcessClose(controller); + } + else { + WritableStreamDefaultControllerProcessWrite(controller, value); + } +} +function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { + if (controller._controlledWritableStream._state === 'writable') { + WritableStreamDefaultControllerError(controller, error); + } +} +function WritableStreamDefaultControllerProcessClose(controller) { + var stream = controller._controlledWritableStream; + WritableStreamMarkCloseRequestInFlight(stream); + DequeueValue(controller); + var sinkClosePromise = controller._closeAlgorithm(); + WritableStreamDefaultControllerClearAlgorithms(controller); + uponPromise(sinkClosePromise, function () { + WritableStreamFinishInFlightClose(stream); + return null; + }, function (reason) { + WritableStreamFinishInFlightCloseWithError(stream, reason); + return null; + }); +} +function WritableStreamDefaultControllerProcessWrite(controller, chunk) { + var stream = controller._controlledWritableStream; + WritableStreamMarkFirstWriteRequestInFlight(stream); + var sinkWritePromise = controller._writeAlgorithm(chunk); + uponPromise(sinkWritePromise, function () { + WritableStreamFinishInFlightWrite(stream); + var state = stream._state; + DequeueValue(controller); + if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') { + var backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, function (reason) { + if (stream._state === 'writable') { + WritableStreamDefaultControllerClearAlgorithms(controller); + } + WritableStreamFinishInFlightWriteWithError(stream, reason); + return null; + }); +} +function WritableStreamDefaultControllerGetBackpressure(controller) { + var desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); + return desiredSize <= 0; +} +// A client of WritableStreamDefaultController may use these functions directly to bypass state check. +function WritableStreamDefaultControllerError(controller, error) { + var stream = controller._controlledWritableStream; + WritableStreamDefaultControllerClearAlgorithms(controller); + WritableStreamStartErroring(stream, error); +} +// Helper functions for the WritableStream. +function streamBrandCheckException$2(name) { + return new TypeError("WritableStream.prototype.".concat(name, " can only be used on a WritableStream")); +} +// Helper functions for the WritableStreamDefaultController. +function defaultControllerBrandCheckException$2(name) { + return new TypeError("WritableStreamDefaultController.prototype.".concat(name, " can only be used on a WritableStreamDefaultController")); +} +// Helper functions for the WritableStreamDefaultWriter. +function defaultWriterBrandCheckException(name) { + return new TypeError("WritableStreamDefaultWriter.prototype.".concat(name, " can only be used on a WritableStreamDefaultWriter")); +} +function defaultWriterLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released writer'); +} +function defaultWriterClosedPromiseInitialize(writer) { + writer._closedPromise = newPromise(function (resolve, reject) { + writer._closedPromise_resolve = resolve; + writer._closedPromise_reject = reject; + writer._closedPromiseState = 'pending'; + }); +} +function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseReject(writer, reason); +} +function defaultWriterClosedPromiseInitializeAsResolved(writer) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseResolve(writer); +} +function defaultWriterClosedPromiseReject(writer, reason) { + if (writer._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._closedPromise); + writer._closedPromise_reject(reason); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'rejected'; +} +function defaultWriterClosedPromiseResetToRejected(writer, reason) { + defaultWriterClosedPromiseInitializeAsRejected(writer, reason); +} +function defaultWriterClosedPromiseResolve(writer) { + if (writer._closedPromise_resolve === undefined) { + return; + } + writer._closedPromise_resolve(undefined); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'resolved'; +} +function defaultWriterReadyPromiseInitialize(writer) { + writer._readyPromise = newPromise(function (resolve, reject) { + writer._readyPromise_resolve = resolve; + writer._readyPromise_reject = reject; + }); + writer._readyPromiseState = 'pending'; +} +function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseReject(writer, reason); +} +function defaultWriterReadyPromiseInitializeAsResolved(writer) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseResolve(writer); +} +function defaultWriterReadyPromiseReject(writer, reason) { + if (writer._readyPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._readyPromise); + writer._readyPromise_reject(reason); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'rejected'; +} +function defaultWriterReadyPromiseReset(writer) { + defaultWriterReadyPromiseInitialize(writer); +} +function defaultWriterReadyPromiseResetToRejected(writer, reason) { + defaultWriterReadyPromiseInitializeAsRejected(writer, reason); +} +function defaultWriterReadyPromiseResolve(writer) { + if (writer._readyPromise_resolve === undefined) { + return; + } + writer._readyPromise_resolve(undefined); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'fulfilled'; +} + +/// +function getGlobals() { + if (typeof globalThis !== 'undefined') { + return globalThis; + } + else if (typeof self !== 'undefined') { + return self; + } + else if (typeof global !== 'undefined') { + return global; + } + return undefined; +} +var globals = getGlobals(); + +/// +function isDOMExceptionConstructor(ctor) { + if (!(typeof ctor === 'function' || typeof ctor === 'object')) { + return false; + } + if (ctor.name !== 'DOMException') { + return false; + } + try { + new ctor(); + return true; + } + catch (_a) { + return false; + } +} +/** + * Support: + * - Web browsers + * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87) + */ +function getFromGlobal() { + var ctor = globals === null || globals === void 0 ? void 0 : globals.DOMException; + return isDOMExceptionConstructor(ctor) ? ctor : undefined; +} +/** + * Support: + * - All platforms + */ +function createPolyfill() { + // eslint-disable-next-line @typescript-eslint/no-shadow + var ctor = function DOMException(message, name) { + this.message = message || ''; + this.name = name || 'Error'; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + }; + setFunctionName(ctor, 'DOMException'); + ctor.prototype = Object.create(Error.prototype); + Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true }); + return ctor; +} +// eslint-disable-next-line @typescript-eslint/no-redeclare +var DOMException = getFromGlobal() || createPolyfill(); + +function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { + var reader = AcquireReadableStreamDefaultReader(source); + var writer = AcquireWritableStreamDefaultWriter(dest); + source._disturbed = true; + var shuttingDown = false; + // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown. + var currentWrite = promiseResolvedWith(undefined); + return newPromise(function (resolve, reject) { + var abortAlgorithm; + if (signal !== undefined) { + abortAlgorithm = function () { + var error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError'); + var actions = []; + if (!preventAbort) { + actions.push(function () { + if (dest._state === 'writable') { + return WritableStreamAbort(dest, error); + } + return promiseResolvedWith(undefined); + }); + } + if (!preventCancel) { + actions.push(function () { + if (source._state === 'readable') { + return ReadableStreamCancel(source, error); + } + return promiseResolvedWith(undefined); + }); + } + shutdownWithAction(function () { return Promise.all(actions.map(function (action) { return action(); })); }, true, error); + }; + if (signal.aborted) { + abortAlgorithm(); + return; + } + signal.addEventListener('abort', abortAlgorithm); + } + // Using reader and writer, read all chunks from this and write them to dest + // - Backpressure must be enforced + // - Shutdown must stop all activity + function pipeLoop() { + return newPromise(function (resolveLoop, rejectLoop) { + function next(done) { + if (done) { + resolveLoop(); + } + else { + // Use `PerformPromiseThen` instead of `uponPromise` to avoid + // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers + PerformPromiseThen(pipeStep(), next, rejectLoop); + } + } + next(false); + }); + } + function pipeStep() { + if (shuttingDown) { + return promiseResolvedWith(true); + } + return PerformPromiseThen(writer._readyPromise, function () { + return newPromise(function (resolveRead, rejectRead) { + ReadableStreamDefaultReaderRead(reader, { + _chunkSteps: function (chunk) { + currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop); + resolveRead(false); + }, + _closeSteps: function () { return resolveRead(true); }, + _errorSteps: rejectRead + }); + }); + }); + } + // Errors must be propagated forward + isOrBecomesErrored(source, reader._closedPromise, function (storedError) { + if (!preventAbort) { + shutdownWithAction(function () { return WritableStreamAbort(dest, storedError); }, true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Errors must be propagated backward + isOrBecomesErrored(dest, writer._closedPromise, function (storedError) { + if (!preventCancel) { + shutdownWithAction(function () { return ReadableStreamCancel(source, storedError); }, true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Closing must be propagated forward + isOrBecomesClosed(source, reader._closedPromise, function () { + if (!preventClose) { + shutdownWithAction(function () { return WritableStreamDefaultWriterCloseWithErrorPropagation(writer); }); + } + else { + shutdown(); + } + return null; + }); + // Closing must be propagated backward + if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') { + var destClosed_1 = new TypeError('the destination writable stream closed before all data could be piped to it'); + if (!preventCancel) { + shutdownWithAction(function () { return ReadableStreamCancel(source, destClosed_1); }, true, destClosed_1); + } + else { + shutdown(true, destClosed_1); + } + } + setPromiseIsHandledToTrue(pipeLoop()); + function waitForWritesToFinish() { + // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait + // for that too. + var oldCurrentWrite = currentWrite; + return PerformPromiseThen(currentWrite, function () { return oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined; }); + } + function isOrBecomesErrored(stream, promise, action) { + if (stream._state === 'errored') { + action(stream._storedError); + } + else { + uponRejection(promise, action); + } + } + function isOrBecomesClosed(stream, promise, action) { + if (stream._state === 'closed') { + action(); + } + else { + uponFulfillment(promise, action); + } + } + function shutdownWithAction(action, originalIsError, originalError) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), doTheRest); + } + else { + doTheRest(); + } + function doTheRest() { + uponPromise(action(), function () { return finalize(originalIsError, originalError); }, function (newError) { return finalize(true, newError); }); + return null; + } + } + function shutdown(isError, error) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), function () { return finalize(isError, error); }); + } + else { + finalize(isError, error); + } + } + function finalize(isError, error) { + WritableStreamDefaultWriterRelease(writer); + ReadableStreamReaderGenericRelease(reader); + if (signal !== undefined) { + signal.removeEventListener('abort', abortAlgorithm); + } + if (isError) { + reject(error); + } + else { + resolve(undefined); + } + return null; + } + }); +} + +/** + * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. + * + * @public + */ +var ReadableStreamDefaultController = /** @class */ (function () { + function ReadableStreamDefaultController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(ReadableStreamDefaultController.prototype, "desiredSize", { + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + */ + get: function () { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('desiredSize'); + } + return ReadableStreamDefaultControllerGetDesiredSize(this); + }, + enumerable: false, + configurable: true + }); + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + ReadableStreamDefaultController.prototype.close = function () { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('close'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits close'); + } + ReadableStreamDefaultControllerClose(this); + }; + ReadableStreamDefaultController.prototype.enqueue = function (chunk) { + if (chunk === void 0) { chunk = undefined; } + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('enqueue'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits enqueue'); + } + return ReadableStreamDefaultControllerEnqueue(this, chunk); + }; + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + ReadableStreamDefaultController.prototype.error = function (e) { + if (e === void 0) { e = undefined; } + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('error'); + } + ReadableStreamDefaultControllerError(this, e); + }; + /** @internal */ + ReadableStreamDefaultController.prototype[CancelSteps] = function (reason) { + ResetQueue(this); + var result = this._cancelAlgorithm(reason); + ReadableStreamDefaultControllerClearAlgorithms(this); + return result; + }; + /** @internal */ + ReadableStreamDefaultController.prototype[PullSteps] = function (readRequest) { + var stream = this._controlledReadableStream; + if (this._queue.length > 0) { + var chunk = DequeueValue(this); + if (this._closeRequested && this._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(this); + ReadableStreamClose(stream); + } + else { + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + readRequest._chunkSteps(chunk); + } + else { + ReadableStreamAddReadRequest(stream, readRequest); + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + }; + /** @internal */ + ReadableStreamDefaultController.prototype[ReleaseSteps] = function () { + // Do nothing. + }; + return ReadableStreamDefaultController; +}()); +Object.defineProperties(ReadableStreamDefaultController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + desiredSize: { enumerable: true } +}); +setFunctionName(ReadableStreamDefaultController.prototype.close, 'close'); +setFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue'); +setFunctionName(ReadableStreamDefaultController.prototype.error, 'error'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultController', + configurable: true + }); +} +// Abstract operations for the ReadableStreamDefaultController. +function IsReadableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) { + return false; + } + return x instanceof ReadableStreamDefaultController; +} +function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { + var shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + var pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, function () { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + return null; + }, function (e) { + ReadableStreamDefaultControllerError(controller, e); + return null; + }); +} +function ReadableStreamDefaultControllerShouldCallPull(controller) { + var stream = controller._controlledReadableStream; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return false; + } + if (!controller._started) { + return false; + } + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + var desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; +} +function ReadableStreamDefaultControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; +} +// A client of ReadableStreamDefaultController may use these functions directly to bypass state check. +function ReadableStreamDefaultControllerClose(controller) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + var stream = controller._controlledReadableStream; + controller._closeRequested = true; + if (controller._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } +} +function ReadableStreamDefaultControllerEnqueue(controller, chunk) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + var stream = controller._controlledReadableStream; + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + ReadableStreamFulfillReadRequest(stream, chunk, false); + } + else { + var chunkSize = void 0; + try { + chunkSize = controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + ReadableStreamDefaultControllerError(controller, chunkSizeE); + throw chunkSizeE; + } + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + ReadableStreamDefaultControllerError(controller, enqueueE); + throw enqueueE; + } + } + ReadableStreamDefaultControllerCallPullIfNeeded(controller); +} +function ReadableStreamDefaultControllerError(controller, e) { + var stream = controller._controlledReadableStream; + if (stream._state !== 'readable') { + return; + } + ResetQueue(controller); + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); +} +function ReadableStreamDefaultControllerGetDesiredSize(controller) { + var state = controller._controlledReadableStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; +} +// This is used in the implementation of TransformStream. +function ReadableStreamDefaultControllerHasBackpressure(controller) { + if (ReadableStreamDefaultControllerShouldCallPull(controller)) { + return false; + } + return true; +} +function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { + var state = controller._controlledReadableStream._state; + if (!controller._closeRequested && state === 'readable') { + return true; + } + return false; +} +function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledReadableStream = stream; + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._started = false; + controller._closeRequested = false; + controller._pullAgain = false; + controller._pulling = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + stream._readableStreamController = controller; + var startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), function () { + controller._started = true; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + return null; + }, function (r) { + ReadableStreamDefaultControllerError(controller, r); + return null; + }); +} +function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { + var controller = Object.create(ReadableStreamDefaultController.prototype); + var startAlgorithm; + var pullAlgorithm; + var cancelAlgorithm; + if (underlyingSource.start !== undefined) { + startAlgorithm = function () { return underlyingSource.start(controller); }; + } + else { + startAlgorithm = function () { return undefined; }; + } + if (underlyingSource.pull !== undefined) { + pullAlgorithm = function () { return underlyingSource.pull(controller); }; + } + else { + pullAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + if (underlyingSource.cancel !== undefined) { + cancelAlgorithm = function (reason) { return underlyingSource.cancel(reason); }; + } + else { + cancelAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); +} +// Helper functions for the ReadableStreamDefaultController. +function defaultControllerBrandCheckException$1(name) { + return new TypeError("ReadableStreamDefaultController.prototype.".concat(name, " can only be used on a ReadableStreamDefaultController")); +} + +function ReadableStreamTee(stream, cloneForBranch2) { + if (IsReadableByteStreamController(stream._readableStreamController)) { + return ReadableByteStreamTee(stream); + } + return ReadableStreamDefaultTee(stream); +} +function ReadableStreamDefaultTee(stream, cloneForBranch2) { + var reader = AcquireReadableStreamDefaultReader(stream); + var reading = false; + var readAgain = false; + var canceled1 = false; + var canceled2 = false; + var reason1; + var reason2; + var branch1; + var branch2; + var resolveCancelPromise; + var cancelPromise = newPromise(function (resolve) { + resolveCancelPromise = resolve; + }); + function pullAlgorithm() { + if (reading) { + readAgain = true; + return promiseResolvedWith(undefined); + } + reading = true; + var readRequest = { + _chunkSteps: function (chunk) { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(function () { + readAgain = false; + var chunk1 = chunk; + var chunk2 = chunk; + // There is no way to access the cloning code right now in the reference implementation. + // If we add one then we'll need an implementation for serializable objects. + // if (!canceled2 && cloneForBranch2) { + // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2)); + // } + if (!canceled1) { + ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgain) { + pullAlgorithm(); + } + }); + }, + _closeSteps: function () { + reading = false; + if (!canceled1) { + ReadableStreamDefaultControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableStreamDefaultControllerClose(branch2._readableStreamController); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: function () { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + // do nothing + } + branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); + branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); + uponRejection(reader._closedPromise, function (r) { + ReadableStreamDefaultControllerError(branch1._readableStreamController, r); + ReadableStreamDefaultControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + return [branch1, branch2]; +} +function ReadableByteStreamTee(stream) { + var reader = AcquireReadableStreamDefaultReader(stream); + var reading = false; + var readAgainForBranch1 = false; + var readAgainForBranch2 = false; + var canceled1 = false; + var canceled2 = false; + var reason1; + var reason2; + var branch1; + var branch2; + var resolveCancelPromise; + var cancelPromise = newPromise(function (resolve) { + resolveCancelPromise = resolve; + }); + function forwardReaderError(thisReader) { + uponRejection(thisReader._closedPromise, function (r) { + if (thisReader !== reader) { + return null; + } + ReadableByteStreamControllerError(branch1._readableStreamController, r); + ReadableByteStreamControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + } + function pullWithDefaultReader() { + if (IsReadableStreamBYOBReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamDefaultReader(stream); + forwardReaderError(reader); + } + var readRequest = { + _chunkSteps: function (chunk) { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(function () { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + var chunk1 = chunk; + var chunk2 = chunk; + if (!canceled1 && !canceled2) { + try { + chunk2 = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(branch1._readableStreamController, cloneE); + ReadableByteStreamControllerError(branch2._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + } + if (!canceled1) { + ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: function () { + reading = false; + if (!canceled1) { + ReadableByteStreamControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableByteStreamControllerClose(branch2._readableStreamController); + } + if (branch1._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch1._readableStreamController, 0); + } + if (branch2._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch2._readableStreamController, 0); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: function () { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + } + function pullWithBYOBReader(view, forBranch2) { + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamBYOBReader(stream); + forwardReaderError(reader); + } + var byobBranch = forBranch2 ? branch2 : branch1; + var otherBranch = forBranch2 ? branch1 : branch2; + var readIntoRequest = { + _chunkSteps: function (chunk) { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(function () { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + var byobCanceled = forBranch2 ? canceled2 : canceled1; + var otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!otherCanceled) { + var clonedChunk = void 0; + try { + clonedChunk = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE); + ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk); + } + else if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: function (chunk) { + reading = false; + var byobCanceled = forBranch2 ? canceled2 : canceled1; + var otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!byobCanceled) { + ReadableByteStreamControllerClose(byobBranch._readableStreamController); + } + if (!otherCanceled) { + ReadableByteStreamControllerClose(otherBranch._readableStreamController); + } + if (chunk !== undefined) { + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0); + } + } + if (!byobCanceled || !otherCanceled) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: function () { + reading = false; + } + }; + ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest); + } + function pull1Algorithm() { + if (reading) { + readAgainForBranch1 = true; + return promiseResolvedWith(undefined); + } + reading = true; + var byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, false); + } + return promiseResolvedWith(undefined); + } + function pull2Algorithm() { + if (reading) { + readAgainForBranch2 = true; + return promiseResolvedWith(undefined); + } + reading = true; + var byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, true); + } + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + return; + } + branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm); + branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm); + forwardReaderError(reader); + return [branch1, branch2]; +} + +function isReadableStreamLike(stream) { + return typeIsObject(stream) && typeof stream.getReader !== 'undefined'; +} + +function ReadableStreamFrom(source) { + if (isReadableStreamLike(source)) { + return ReadableStreamFromDefaultReader(source.getReader()); + } + return ReadableStreamFromIterable(source); +} +function ReadableStreamFromIterable(asyncIterable) { + var stream; + var iteratorRecord = GetIterator(asyncIterable, 'async'); + var startAlgorithm = noop; + function pullAlgorithm() { + var nextResult; + try { + nextResult = IteratorNext(iteratorRecord); + } + catch (e) { + return promiseRejectedWith(e); + } + var nextPromise = promiseResolvedWith(nextResult); + return transformPromiseWith(nextPromise, function (iterResult) { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object'); + } + var done = IteratorComplete(iterResult); + if (done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + var value = IteratorValue(iterResult); + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + var iterator = iteratorRecord.iterator; + var returnMethod; + try { + returnMethod = GetMethod(iterator, 'return'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (returnMethod === undefined) { + return promiseResolvedWith(undefined); + } + var returnResult; + try { + returnResult = reflectCall(returnMethod, iterator, [reason]); + } + catch (e) { + return promiseRejectedWith(e); + } + var returnPromise = promiseResolvedWith(returnResult); + return transformPromiseWith(returnPromise, function (iterResult) { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object'); + } + return undefined; + }); + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; +} +function ReadableStreamFromDefaultReader(reader) { + var stream; + var startAlgorithm = noop; + function pullAlgorithm() { + var readPromise; + try { + readPromise = reader.read(); + } + catch (e) { + return promiseRejectedWith(e); + } + return transformPromiseWith(readPromise, function (readResult) { + if (!typeIsObject(readResult)) { + throw new TypeError('The promise returned by the reader.read() method must fulfill with an object'); + } + if (readResult.done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + var value = readResult.value; + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + try { + return promiseResolvedWith(reader.cancel(reason)); + } + catch (e) { + return promiseRejectedWith(e); + } + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; +} + +function convertUnderlyingDefaultOrByteSource(source, context) { + assertDictionary(source, context); + var original = source; + var autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; + var cancel = original === null || original === void 0 ? void 0 : original.cancel; + var pull = original === null || original === void 0 ? void 0 : original.pull; + var start = original === null || original === void 0 ? void 0 : original.start; + var type = original === null || original === void 0 ? void 0 : original.type; + return { + autoAllocateChunkSize: autoAllocateChunkSize === undefined ? + undefined : + convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, "".concat(context, " has member 'autoAllocateChunkSize' that")), + cancel: cancel === undefined ? + undefined : + convertUnderlyingSourceCancelCallback(cancel, original, "".concat(context, " has member 'cancel' that")), + pull: pull === undefined ? + undefined : + convertUnderlyingSourcePullCallback(pull, original, "".concat(context, " has member 'pull' that")), + start: start === undefined ? + undefined : + convertUnderlyingSourceStartCallback(start, original, "".concat(context, " has member 'start' that")), + type: type === undefined ? undefined : convertReadableStreamType(type, "".concat(context, " has member 'type' that")) + }; +} +function convertUnderlyingSourceCancelCallback(fn, original, context) { + assertFunction(fn, context); + return function (reason) { return promiseCall(fn, original, [reason]); }; +} +function convertUnderlyingSourcePullCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return promiseCall(fn, original, [controller]); }; +} +function convertUnderlyingSourceStartCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return reflectCall(fn, original, [controller]); }; +} +function convertReadableStreamType(type, context) { + type = "".concat(type); + if (type !== 'bytes') { + throw new TypeError("".concat(context, " '").concat(type, "' is not a valid enumeration value for ReadableStreamType")); + } + return type; +} + +function convertIteratorOptions(options, context) { + assertDictionary(options, context); + var preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + return { preventCancel: Boolean(preventCancel) }; +} + +function convertPipeOptions(options, context) { + assertDictionary(options, context); + var preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort; + var preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + var preventClose = options === null || options === void 0 ? void 0 : options.preventClose; + var signal = options === null || options === void 0 ? void 0 : options.signal; + if (signal !== undefined) { + assertAbortSignal(signal, "".concat(context, " has member 'signal' that")); + } + return { + preventAbort: Boolean(preventAbort), + preventCancel: Boolean(preventCancel), + preventClose: Boolean(preventClose), + signal: signal + }; +} +function assertAbortSignal(signal, context) { + if (!isAbortSignal(signal)) { + throw new TypeError("".concat(context, " is not an AbortSignal.")); + } +} + +function convertReadableWritablePair(pair, context) { + assertDictionary(pair, context); + var readable = pair === null || pair === void 0 ? void 0 : pair.readable; + assertRequiredField(readable, 'readable', 'ReadableWritablePair'); + assertReadableStream(readable, "".concat(context, " has member 'readable' that")); + var writable = pair === null || pair === void 0 ? void 0 : pair.writable; + assertRequiredField(writable, 'writable', 'ReadableWritablePair'); + assertWritableStream(writable, "".concat(context, " has member 'writable' that")); + return { readable: readable, writable: writable }; +} + +/** + * A readable stream represents a source of data, from which you can read. + * + * @public + */ +var ReadableStream = /** @class */ (function () { + function ReadableStream(rawUnderlyingSource, rawStrategy) { + if (rawUnderlyingSource === void 0) { rawUnderlyingSource = {}; } + if (rawStrategy === void 0) { rawStrategy = {}; } + if (rawUnderlyingSource === undefined) { + rawUnderlyingSource = null; + } + else { + assertObject(rawUnderlyingSource, 'First parameter'); + } + var strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + var underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter'); + InitializeReadableStream(this); + if (underlyingSource.type === 'bytes') { + if (strategy.size !== undefined) { + throw new RangeError('The strategy for a byte stream cannot have a size function'); + } + var highWaterMark = ExtractHighWaterMark(strategy, 0); + SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); + } + else { + var sizeAlgorithm = ExtractSizeAlgorithm(strategy); + var highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); + } + } + Object.defineProperty(ReadableStream.prototype, "locked", { + /** + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. + */ + get: function () { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('locked'); + } + return IsReadableStreamLocked(this); + }, + enumerable: false, + configurable: true + }); + /** + * Cancels the stream, signaling a loss of interest in the stream by a consumer. + * + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} + * method, which might or might not use it. + */ + ReadableStream.prototype.cancel = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('cancel')); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader')); + } + return ReadableStreamCancel(this, reason); + }; + ReadableStream.prototype.getReader = function (rawOptions) { + if (rawOptions === void 0) { rawOptions = undefined; } + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('getReader'); + } + var options = convertReaderOptions(rawOptions, 'First parameter'); + if (options.mode === undefined) { + return AcquireReadableStreamDefaultReader(this); + } + return AcquireReadableStreamBYOBReader(this); + }; + ReadableStream.prototype.pipeThrough = function (rawTransform, rawOptions) { + if (rawOptions === void 0) { rawOptions = {}; } + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('pipeThrough'); + } + assertRequiredArgument(rawTransform, 1, 'pipeThrough'); + var transform = convertReadableWritablePair(rawTransform, 'First parameter'); + var options = convertPipeOptions(rawOptions, 'Second parameter'); + if (IsReadableStreamLocked(this)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream'); + } + if (IsWritableStreamLocked(transform.writable)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream'); + } + var promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + setPromiseIsHandledToTrue(promise); + return transform.readable; + }; + ReadableStream.prototype.pipeTo = function (destination, rawOptions) { + if (rawOptions === void 0) { rawOptions = {}; } + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('pipeTo')); + } + if (destination === undefined) { + return promiseRejectedWith("Parameter 1 is required in 'pipeTo'."); + } + if (!IsWritableStream(destination)) { + return promiseRejectedWith(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream")); + } + var options; + try { + options = convertPipeOptions(rawOptions, 'Second parameter'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')); + } + if (IsWritableStreamLocked(destination)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')); + } + return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + }; + /** + * Tees this readable stream, returning a two-element array containing the two resulting branches as + * new {@link ReadableStream} instances. + * + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be + * propagated to the stream's underlying source. + * + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, + * this could allow interference between the two branches. + */ + ReadableStream.prototype.tee = function () { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('tee'); + } + var branches = ReadableStreamTee(this); + return CreateArrayFromList(branches); + }; + ReadableStream.prototype.values = function (rawOptions) { + if (rawOptions === void 0) { rawOptions = undefined; } + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('values'); + } + var options = convertIteratorOptions(rawOptions, 'First parameter'); + return AcquireReadableStreamAsyncIterator(this, options.preventCancel); + }; + ReadableStream.prototype[SymbolAsyncIterator] = function (options) { + // Stub implementation, overridden below + return this.values(options); + }; + /** + * Creates a new ReadableStream wrapping the provided iterable or async iterable. + * + * This can be used to adapt various kinds of objects into a readable stream, + * such as an array, an async generator, or a Node.js readable stream. + */ + ReadableStream.from = function (asyncIterable) { + return ReadableStreamFrom(asyncIterable); + }; + return ReadableStream; +}()); +Object.defineProperties(ReadableStream, { + from: { enumerable: true } +}); +Object.defineProperties(ReadableStream.prototype, { + cancel: { enumerable: true }, + getReader: { enumerable: true }, + pipeThrough: { enumerable: true }, + pipeTo: { enumerable: true }, + tee: { enumerable: true }, + values: { enumerable: true }, + locked: { enumerable: true } +}); +setFunctionName(ReadableStream.from, 'from'); +setFunctionName(ReadableStream.prototype.cancel, 'cancel'); +setFunctionName(ReadableStream.prototype.getReader, 'getReader'); +setFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough'); +setFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo'); +setFunctionName(ReadableStream.prototype.tee, 'tee'); +setFunctionName(ReadableStream.prototype.values, 'values'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStream', + configurable: true + }); +} +Object.defineProperty(ReadableStream.prototype, SymbolAsyncIterator, { + value: ReadableStream.prototype.values, + writable: true, + configurable: true +}); +// Abstract operations for the ReadableStream. +// Throws if and only if startAlgorithm throws. +function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + if (highWaterMark === void 0) { highWaterMark = 1; } + if (sizeAlgorithm === void 0) { sizeAlgorithm = function () { return 1; }; } + var stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + var controller = Object.create(ReadableStreamDefaultController.prototype); + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + return stream; +} +// Throws if and only if startAlgorithm throws. +function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) { + var stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + var controller = Object.create(ReadableByteStreamController.prototype); + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined); + return stream; +} +function InitializeReadableStream(stream) { + stream._state = 'readable'; + stream._reader = undefined; + stream._storedError = undefined; + stream._disturbed = false; +} +function IsReadableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) { + return false; + } + return x instanceof ReadableStream; +} +function IsReadableStreamLocked(stream) { + if (stream._reader === undefined) { + return false; + } + return true; +} +// ReadableStream API exposed for controllers. +function ReadableStreamCancel(stream, reason) { + stream._disturbed = true; + if (stream._state === 'closed') { + return promiseResolvedWith(undefined); + } + if (stream._state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + ReadableStreamClose(stream); + var reader = stream._reader; + if (reader !== undefined && IsReadableStreamBYOBReader(reader)) { + var readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(function (readIntoRequest) { + readIntoRequest._closeSteps(undefined); + }); + } + var sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); + return transformPromiseWith(sourceCancelPromise, noop); +} +function ReadableStreamClose(stream) { + stream._state = 'closed'; + var reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseResolve(reader); + if (IsReadableStreamDefaultReader(reader)) { + var readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(function (readRequest) { + readRequest._closeSteps(); + }); + } +} +function ReadableStreamError(stream, e) { + stream._state = 'errored'; + stream._storedError = e; + var reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseReject(reader, e); + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamDefaultReaderErrorReadRequests(reader, e); + } + else { + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); + } +} +// Helper functions for the ReadableStream. +function streamBrandCheckException$1(name) { + return new TypeError("ReadableStream.prototype.".concat(name, " can only be used on a ReadableStream")); +} + +function convertQueuingStrategyInit(init, context) { + assertDictionary(init, context); + var highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit'); + return { + highWaterMark: convertUnrestrictedDouble(highWaterMark) + }; +} + +// The size function must not have a prototype property nor be a constructor +var byteLengthSizeFunction = function (chunk) { + return chunk.byteLength; +}; +setFunctionName(byteLengthSizeFunction, 'size'); +/** + * A queuing strategy that counts the number of bytes in each chunk. + * + * @public + */ +var ByteLengthQueuingStrategy = /** @class */ (function () { + function ByteLengthQueuingStrategy(options) { + assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; + } + Object.defineProperty(ByteLengthQueuingStrategy.prototype, "highWaterMark", { + /** + * Returns the high water mark provided to the constructor. + */ + get: function () { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('highWaterMark'); + } + return this._byteLengthQueuingStrategyHighWaterMark; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ByteLengthQueuingStrategy.prototype, "size", { + /** + * Measures the size of `chunk` by returning the value of its `byteLength` property. + */ + get: function () { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('size'); + } + return byteLengthSizeFunction; + }, + enumerable: false, + configurable: true + }); + return ByteLengthQueuingStrategy; +}()); +Object.defineProperties(ByteLengthQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ByteLengthQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'ByteLengthQueuingStrategy', + configurable: true + }); +} +// Helper functions for the ByteLengthQueuingStrategy. +function byteLengthBrandCheckException(name) { + return new TypeError("ByteLengthQueuingStrategy.prototype.".concat(name, " can only be used on a ByteLengthQueuingStrategy")); +} +function IsByteLengthQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof ByteLengthQueuingStrategy; +} + +// The size function must not have a prototype property nor be a constructor +var countSizeFunction = function () { + return 1; +}; +setFunctionName(countSizeFunction, 'size'); +/** + * A queuing strategy that counts the number of chunks. + * + * @public + */ +var CountQueuingStrategy = /** @class */ (function () { + function CountQueuingStrategy(options) { + assertRequiredArgument(options, 1, 'CountQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._countQueuingStrategyHighWaterMark = options.highWaterMark; + } + Object.defineProperty(CountQueuingStrategy.prototype, "highWaterMark", { + /** + * Returns the high water mark provided to the constructor. + */ + get: function () { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('highWaterMark'); + } + return this._countQueuingStrategyHighWaterMark; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(CountQueuingStrategy.prototype, "size", { + /** + * Measures the size of `chunk` by always returning 1. + * This ensures that the total queue size is a count of the number of chunks in the queue. + */ + get: function () { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('size'); + } + return countSizeFunction; + }, + enumerable: false, + configurable: true + }); + return CountQueuingStrategy; +}()); +Object.defineProperties(CountQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(CountQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'CountQueuingStrategy', + configurable: true + }); +} +// Helper functions for the CountQueuingStrategy. +function countBrandCheckException(name) { + return new TypeError("CountQueuingStrategy.prototype.".concat(name, " can only be used on a CountQueuingStrategy")); +} +function IsCountQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof CountQueuingStrategy; +} + +function convertTransformer(original, context) { + assertDictionary(original, context); + var cancel = original === null || original === void 0 ? void 0 : original.cancel; + var flush = original === null || original === void 0 ? void 0 : original.flush; + var readableType = original === null || original === void 0 ? void 0 : original.readableType; + var start = original === null || original === void 0 ? void 0 : original.start; + var transform = original === null || original === void 0 ? void 0 : original.transform; + var writableType = original === null || original === void 0 ? void 0 : original.writableType; + return { + cancel: cancel === undefined ? + undefined : + convertTransformerCancelCallback(cancel, original, "".concat(context, " has member 'cancel' that")), + flush: flush === undefined ? + undefined : + convertTransformerFlushCallback(flush, original, "".concat(context, " has member 'flush' that")), + readableType: readableType, + start: start === undefined ? + undefined : + convertTransformerStartCallback(start, original, "".concat(context, " has member 'start' that")), + transform: transform === undefined ? + undefined : + convertTransformerTransformCallback(transform, original, "".concat(context, " has member 'transform' that")), + writableType: writableType + }; +} +function convertTransformerFlushCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return promiseCall(fn, original, [controller]); }; +} +function convertTransformerStartCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return reflectCall(fn, original, [controller]); }; +} +function convertTransformerTransformCallback(fn, original, context) { + assertFunction(fn, context); + return function (chunk, controller) { return promiseCall(fn, original, [chunk, controller]); }; +} +function convertTransformerCancelCallback(fn, original, context) { + assertFunction(fn, context); + return function (reason) { return promiseCall(fn, original, [reason]); }; +} + +// Class TransformStream +/** + * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, + * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. + * In a manner specific to the transform stream in question, writes to the writable side result in new data being + * made available for reading from the readable side. + * + * @public + */ +var TransformStream = /** @class */ (function () { + function TransformStream(rawTransformer, rawWritableStrategy, rawReadableStrategy) { + if (rawTransformer === void 0) { rawTransformer = {}; } + if (rawWritableStrategy === void 0) { rawWritableStrategy = {}; } + if (rawReadableStrategy === void 0) { rawReadableStrategy = {}; } + if (rawTransformer === undefined) { + rawTransformer = null; + } + var writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter'); + var readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter'); + var transformer = convertTransformer(rawTransformer, 'First parameter'); + if (transformer.readableType !== undefined) { + throw new RangeError('Invalid readableType specified'); + } + if (transformer.writableType !== undefined) { + throw new RangeError('Invalid writableType specified'); + } + var readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); + var readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); + var writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); + var writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); + var startPromise_resolve; + var startPromise = newPromise(function (resolve) { + startPromise_resolve = resolve; + }); + InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); + if (transformer.start !== undefined) { + startPromise_resolve(transformer.start(this._transformStreamController)); + } + else { + startPromise_resolve(undefined); + } + } + Object.defineProperty(TransformStream.prototype, "readable", { + /** + * The readable side of the transform stream. + */ + get: function () { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('readable'); + } + return this._readable; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TransformStream.prototype, "writable", { + /** + * The writable side of the transform stream. + */ + get: function () { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('writable'); + } + return this._writable; + }, + enumerable: false, + configurable: true + }); + return TransformStream; +}()); +Object.defineProperties(TransformStream.prototype, { + readable: { enumerable: true }, + writable: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStream.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStream', + configurable: true + }); +} +function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { + function startAlgorithm() { + return startPromise; + } + function writeAlgorithm(chunk) { + return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); + } + function abortAlgorithm(reason) { + return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); + } + function closeAlgorithm() { + return TransformStreamDefaultSinkCloseAlgorithm(stream); + } + stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); + function pullAlgorithm() { + return TransformStreamDefaultSourcePullAlgorithm(stream); + } + function cancelAlgorithm(reason) { + return TransformStreamDefaultSourceCancelAlgorithm(stream, reason); + } + stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure. + stream._backpressure = undefined; + stream._backpressureChangePromise = undefined; + stream._backpressureChangePromise_resolve = undefined; + TransformStreamSetBackpressure(stream, true); + stream._transformStreamController = undefined; +} +function IsTransformStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) { + return false; + } + return x instanceof TransformStream; +} +// This is a no-op if both sides are already errored. +function TransformStreamError(stream, e) { + ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e); + TransformStreamErrorWritableAndUnblockWrite(stream, e); +} +function TransformStreamErrorWritableAndUnblockWrite(stream, e) { + TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); + WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e); + TransformStreamUnblockWrite(stream); +} +function TransformStreamUnblockWrite(stream) { + if (stream._backpressure) { + // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure() + // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time + // _backpressure is set. + TransformStreamSetBackpressure(stream, false); + } +} +function TransformStreamSetBackpressure(stream, backpressure) { + // Passes also when called during construction. + if (stream._backpressureChangePromise !== undefined) { + stream._backpressureChangePromise_resolve(); + } + stream._backpressureChangePromise = newPromise(function (resolve) { + stream._backpressureChangePromise_resolve = resolve; + }); + stream._backpressure = backpressure; +} +// Class TransformStreamDefaultController +/** + * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. + * + * @public + */ +var TransformStreamDefaultController = /** @class */ (function () { + function TransformStreamDefaultController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(TransformStreamDefaultController.prototype, "desiredSize", { + /** + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. + */ + get: function () { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('desiredSize'); + } + var readableController = this._controlledTransformStream._readable._readableStreamController; + return ReadableStreamDefaultControllerGetDesiredSize(readableController); + }, + enumerable: false, + configurable: true + }); + TransformStreamDefaultController.prototype.enqueue = function (chunk) { + if (chunk === void 0) { chunk = undefined; } + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('enqueue'); + } + TransformStreamDefaultControllerEnqueue(this, chunk); + }; + /** + * Errors both the readable side and the writable side of the controlled transform stream, making all future + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. + */ + TransformStreamDefaultController.prototype.error = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('error'); + } + TransformStreamDefaultControllerError(this, reason); + }; + /** + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the + * transformer only needs to consume a portion of the chunks written to the writable side. + */ + TransformStreamDefaultController.prototype.terminate = function () { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('terminate'); + } + TransformStreamDefaultControllerTerminate(this); + }; + return TransformStreamDefaultController; +}()); +Object.defineProperties(TransformStreamDefaultController.prototype, { + enqueue: { enumerable: true }, + error: { enumerable: true }, + terminate: { enumerable: true }, + desiredSize: { enumerable: true } +}); +setFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue'); +setFunctionName(TransformStreamDefaultController.prototype.error, 'error'); +setFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStreamDefaultController', + configurable: true + }); +} +// Transform Stream Default Controller Abstract Operations +function IsTransformStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) { + return false; + } + return x instanceof TransformStreamDefaultController; +} +function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm) { + controller._controlledTransformStream = stream; + stream._transformStreamController = controller; + controller._transformAlgorithm = transformAlgorithm; + controller._flushAlgorithm = flushAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._finishPromise = undefined; + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; +} +function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { + var controller = Object.create(TransformStreamDefaultController.prototype); + var transformAlgorithm; + var flushAlgorithm; + var cancelAlgorithm; + if (transformer.transform !== undefined) { + transformAlgorithm = function (chunk) { return transformer.transform(chunk, controller); }; + } + else { + transformAlgorithm = function (chunk) { + try { + TransformStreamDefaultControllerEnqueue(controller, chunk); + return promiseResolvedWith(undefined); + } + catch (transformResultE) { + return promiseRejectedWith(transformResultE); + } + }; + } + if (transformer.flush !== undefined) { + flushAlgorithm = function () { return transformer.flush(controller); }; + } + else { + flushAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + if (transformer.cancel !== undefined) { + cancelAlgorithm = function (reason) { return transformer.cancel(reason); }; + } + else { + cancelAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm); +} +function TransformStreamDefaultControllerClearAlgorithms(controller) { + controller._transformAlgorithm = undefined; + controller._flushAlgorithm = undefined; + controller._cancelAlgorithm = undefined; +} +function TransformStreamDefaultControllerEnqueue(controller, chunk) { + var stream = controller._controlledTransformStream; + var readableController = stream._readable._readableStreamController; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { + throw new TypeError('Readable side is not in a state that permits enqueue'); + } + // We throttle transform invocations based on the backpressure of the ReadableStream, but we still + // accept TransformStreamDefaultControllerEnqueue() calls. + try { + ReadableStreamDefaultControllerEnqueue(readableController, chunk); + } + catch (e) { + // This happens when readableStrategy.size() throws. + TransformStreamErrorWritableAndUnblockWrite(stream, e); + throw stream._readable._storedError; + } + var backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); + if (backpressure !== stream._backpressure) { + TransformStreamSetBackpressure(stream, true); + } +} +function TransformStreamDefaultControllerError(controller, e) { + TransformStreamError(controller._controlledTransformStream, e); +} +function TransformStreamDefaultControllerPerformTransform(controller, chunk) { + var transformPromise = controller._transformAlgorithm(chunk); + return transformPromiseWith(transformPromise, undefined, function (r) { + TransformStreamError(controller._controlledTransformStream, r); + throw r; + }); +} +function TransformStreamDefaultControllerTerminate(controller) { + var stream = controller._controlledTransformStream; + var readableController = stream._readable._readableStreamController; + ReadableStreamDefaultControllerClose(readableController); + var error = new TypeError('TransformStream terminated'); + TransformStreamErrorWritableAndUnblockWrite(stream, error); +} +// TransformStreamDefaultSink Algorithms +function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { + var controller = stream._transformStreamController; + if (stream._backpressure) { + var backpressureChangePromise = stream._backpressureChangePromise; + return transformPromiseWith(backpressureChangePromise, function () { + var writable = stream._writable; + var state = writable._state; + if (state === 'erroring') { + throw writable._storedError; + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + }); + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); +} +function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { + var controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + var readable = stream._readable; + // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally, + // we don't run the _cancelAlgorithm again. + controller._finishPromise = newPromise(function (resolve, reject) { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + var cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, function () { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerError(readable._readableStreamController, reason); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, function (r) { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; +} +function TransformStreamDefaultSinkCloseAlgorithm(stream) { + var controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + var readable = stream._readable; + // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally, + // we don't also run the _cancelAlgorithm. + controller._finishPromise = newPromise(function (resolve, reject) { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + var flushPromise = controller._flushAlgorithm(); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(flushPromise, function () { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerClose(readable._readableStreamController); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, function (r) { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; +} +// TransformStreamDefaultSource Algorithms +function TransformStreamDefaultSourcePullAlgorithm(stream) { + // Invariant. Enforced by the promises returned by start() and pull(). + TransformStreamSetBackpressure(stream, false); + // Prevent the next pull() call until there is backpressure. + return stream._backpressureChangePromise; +} +function TransformStreamDefaultSourceCancelAlgorithm(stream, reason) { + var controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._writable cannot change after construction, so caching it across a call to user code is safe. + var writable = stream._writable; + // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or + // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the + // _flushAlgorithm. + controller._finishPromise = newPromise(function (resolve, reject) { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + var cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, function () { + if (writable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, writable._storedError); + } + else { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, function (r) { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; +} +// Helper functions for the TransformStreamDefaultController. +function defaultControllerBrandCheckException(name) { + return new TypeError("TransformStreamDefaultController.prototype.".concat(name, " can only be used on a TransformStreamDefaultController")); +} +function defaultControllerFinishPromiseResolve(controller) { + if (controller._finishPromise_resolve === undefined) { + return; + } + controller._finishPromise_resolve(); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; +} +function defaultControllerFinishPromiseReject(controller, reason) { + if (controller._finishPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(controller._finishPromise); + controller._finishPromise_reject(reason); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; +} +// Helper functions for the TransformStream. +function streamBrandCheckException(name) { + return new TypeError("TransformStream.prototype.".concat(name, " can only be used on a TransformStream")); +} + +export { ByteLengthQueuingStrategy, CountQueuingStrategy, ReadableByteStreamController, ReadableStream, ReadableStreamBYOBReader, ReadableStreamBYOBRequest, ReadableStreamDefaultController, ReadableStreamDefaultReader, TransformStream, TransformStreamDefaultController, WritableStream, WritableStreamDefaultController, WritableStreamDefaultWriter }; +//# sourceMappingURL=ponyfill.mjs.map diff --git a/backend/node_modules/web-streams-polyfill/dist/ponyfill.mjs.map b/backend/node_modules/web-streams-polyfill/dist/ponyfill.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..d7df2bd493d98e712f70ffef3c3a7d5b48dd7bf0 --- /dev/null +++ b/backend/node_modules/web-streams-polyfill/dist/ponyfill.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"ponyfill.mjs","sources":["../src/stub/symbol.ts","../node_modules/tslib/tslib.es6.js","../src/utils.ts","../src/lib/helpers/miscellaneous.ts","../src/lib/helpers/webidl.ts","../src/lib/simple-queue.ts","../src/lib/abstract-ops/internal-methods.ts","../src/lib/readable-stream/generic-reader.ts","../src/stub/number-isfinite.ts","../src/stub/math-trunc.ts","../src/lib/validators/basic.ts","../src/lib/validators/readable-stream.ts","../src/lib/readable-stream/default-reader.ts","../src/lib/abstract-ops/ecmascript.ts","../src/target/es5/stub/async-iterator-prototype.ts","../src/lib/readable-stream/async-iterator.ts","../src/stub/number-isnan.ts","../src/lib/abstract-ops/miscellaneous.ts","../src/lib/abstract-ops/queue-with-sizes.ts","../src/lib/helpers/array-buffer-view.ts","../src/lib/readable-stream/byte-stream-controller.ts","../src/lib/validators/reader-options.ts","../src/lib/readable-stream/byob-reader.ts","../src/lib/abstract-ops/queuing-strategy.ts","../src/lib/validators/queuing-strategy.ts","../src/lib/validators/underlying-sink.ts","../src/lib/validators/writable-stream.ts","../src/lib/abort-signal.ts","../src/lib/writable-stream.ts","../src/globals.ts","../src/stub/dom-exception.ts","../src/lib/readable-stream/pipe.ts","../src/lib/readable-stream/default-controller.ts","../src/lib/readable-stream/tee.ts","../src/lib/readable-stream/readable-stream-like.ts","../src/lib/readable-stream/from.ts","../src/lib/validators/underlying-source.ts","../src/lib/validators/iterator-options.ts","../src/lib/validators/pipe-options.ts","../src/lib/validators/readable-writable-pair.ts","../src/lib/readable-stream.ts","../src/lib/validators/queuing-strategy-init.ts","../src/lib/byte-length-queuing-strategy.ts","../src/lib/count-queuing-strategy.ts","../src/lib/validators/transformer.ts","../src/lib/transform-stream.ts"],"sourcesContent":["/// \n\nconst SymbolPolyfill: (description?: string) => symbol =\n typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ?\n Symbol :\n description => `Symbol(${description})` as any as symbol;\n\nexport default SymbolPolyfill;\n","/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise, SuppressedError, Symbol */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\r\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\r\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\r\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\r\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\r\n var _, done = false;\r\n for (var i = decorators.length - 1; i >= 0; i--) {\r\n var context = {};\r\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\r\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\r\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\r\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\r\n if (kind === \"accessor\") {\r\n if (result === void 0) continue;\r\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\r\n if (_ = accept(result.get)) descriptor.get = _;\r\n if (_ = accept(result.set)) descriptor.set = _;\r\n if (_ = accept(result.init)) initializers.unshift(_);\r\n }\r\n else if (_ = accept(result)) {\r\n if (kind === \"field\") initializers.unshift(_);\r\n else descriptor[key] = _;\r\n }\r\n }\r\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\r\n done = true;\r\n};\r\n\r\nexport function __runInitializers(thisArg, initializers, value) {\r\n var useValue = arguments.length > 2;\r\n for (var i = 0; i < initializers.length; i++) {\r\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\r\n }\r\n return useValue ? value : void 0;\r\n};\r\n\r\nexport function __propKey(x) {\r\n return typeof x === \"symbol\" ? x : \"\".concat(x);\r\n};\r\n\r\nexport function __setFunctionName(f, name, prefix) {\r\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\r\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\r\n};\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n var desc = Object.getOwnPropertyDescriptor(m, k);\r\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\r\n desc = { enumerable: true, get: function() { return m[k]; } };\r\n }\r\n Object.defineProperty(o, k2, desc);\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\nexport function __classPrivateFieldIn(state, receiver) {\r\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\r\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\r\n}\r\n\r\nexport function __addDisposableResource(env, value, async) {\r\n if (value !== null && value !== void 0) {\r\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\r\n var dispose;\r\n if (async) {\r\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\r\n dispose = value[Symbol.asyncDispose];\r\n }\r\n if (dispose === void 0) {\r\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\r\n dispose = value[Symbol.dispose];\r\n }\r\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\r\n env.stack.push({ value: value, dispose: dispose, async: async });\r\n }\r\n else if (async) {\r\n env.stack.push({ async: true });\r\n }\r\n return value;\r\n}\r\n\r\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n};\r\n\r\nexport function __disposeResources(env) {\r\n function fail(e) {\r\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\r\n env.hasError = true;\r\n }\r\n function next() {\r\n while (env.stack.length) {\r\n var rec = env.stack.pop();\r\n try {\r\n var result = rec.dispose && rec.dispose.call(rec.value);\r\n if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\r\n }\r\n catch (e) {\r\n fail(e);\r\n }\r\n }\r\n if (env.hasError) throw env.error;\r\n }\r\n return next();\r\n}\r\n\r\nexport default {\r\n __extends: __extends,\r\n __assign: __assign,\r\n __rest: __rest,\r\n __decorate: __decorate,\r\n __param: __param,\r\n __metadata: __metadata,\r\n __awaiter: __awaiter,\r\n __generator: __generator,\r\n __createBinding: __createBinding,\r\n __exportStar: __exportStar,\r\n __values: __values,\r\n __read: __read,\r\n __spread: __spread,\r\n __spreadArrays: __spreadArrays,\r\n __spreadArray: __spreadArray,\r\n __await: __await,\r\n __asyncGenerator: __asyncGenerator,\r\n __asyncDelegator: __asyncDelegator,\r\n __asyncValues: __asyncValues,\r\n __makeTemplateObject: __makeTemplateObject,\r\n __importStar: __importStar,\r\n __importDefault: __importDefault,\r\n __classPrivateFieldGet: __classPrivateFieldGet,\r\n __classPrivateFieldSet: __classPrivateFieldSet,\r\n __classPrivateFieldIn: __classPrivateFieldIn,\r\n __addDisposableResource: __addDisposableResource,\r\n __disposeResources: __disposeResources,\r\n};\r\n","export function noop(): undefined {\n return undefined;\n}\n","import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n\nexport function setFunctionName(fn: Function, name: string): void {\n try {\n Object.defineProperty(fn, 'name', {\n value: name,\n configurable: true\n });\n } catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n }\n}\n","import { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\n// https://webidl.spec.whatwg.org/#a-new-promise\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-resolved-with\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return newPromise(resolve => resolve(value));\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-rejected-with\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\n// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned\n// from that handler. To prevent this, return null instead of void from all handlers.\n// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => null | PromiseLike,\n onRejected?: (reason: any) => null | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => null | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => null | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nlet _queueMicrotask: (callback: () => void) => void = callback => {\n if (typeof queueMicrotask === 'function') {\n _queueMicrotask = queueMicrotask;\n } else {\n const resolvedPromise = promiseResolvedWith(undefined);\n _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb);\n }\n return _queueMicrotask(callback);\n};\n\nexport { _queueMicrotask as queueMicrotask };\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n","import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n","export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\nexport const ReleaseSteps = Symbol('[[ReleaseSteps]]');\n","import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, type ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\nimport { ReleaseSteps } from '../abstract-ops/internal-methods';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n assert(stream._reader === reader);\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n stream._readableStreamController[ReleaseSteps]();\n\n stream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n","import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n","import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamDefaultReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamDefaultReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\nexport function ReadableStreamDefaultReaderRelease(reader: ReadableStreamDefaultReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n}\n\nexport function ReadableStreamDefaultReaderErrorReadRequests(reader: ReadableStreamDefaultReader, e: any) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n","import { reflectCall } from 'lib/helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport assert from '../../stub/assert';\n\ndeclare global {\n interface ArrayBuffer {\n readonly detached: boolean;\n\n transfer(): ArrayBuffer;\n }\n\n function structuredClone(value: T, options: { transfer: ArrayBuffer[] }): T;\n}\n\nexport function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\nexport let TransferArrayBuffer = (O: ArrayBuffer): ArrayBuffer => {\n if (typeof O.transfer === 'function') {\n TransferArrayBuffer = buffer => buffer.transfer();\n } else if (typeof structuredClone === 'function') {\n TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] });\n } else {\n // Not implemented correctly\n TransferArrayBuffer = buffer => buffer;\n }\n return TransferArrayBuffer(O);\n};\n\nexport function CanTransferArrayBuffer(O: ArrayBuffer): boolean {\n return !IsDetachedBuffer(O);\n}\n\nexport let IsDetachedBuffer = (O: ArrayBuffer): boolean => {\n if (typeof O.detached === 'boolean') {\n IsDetachedBuffer = buffer => buffer.detached;\n } else {\n // Not implemented correctly\n IsDetachedBuffer = buffer => buffer.byteLength === 0;\n }\n return IsDetachedBuffer(O);\n};\n\nexport function ArrayBufferSlice(buffer: ArrayBuffer, begin: number, end: number): ArrayBuffer {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n\nexport type MethodName = {\n [P in keyof T]: T[P] extends Function | undefined ? P : never;\n}[keyof T];\n\nexport function GetMethod>(receiver: T, prop: K): T[K] | undefined {\n const func = receiver[prop];\n if (func === undefined || func === null) {\n return undefined;\n }\n if (typeof func !== 'function') {\n throw new TypeError(`${String(prop)} is not a function`);\n }\n return func;\n}\n\nexport interface SyncIteratorRecord {\n iterator: Iterator,\n nextMethod: Iterator['next'],\n done: boolean;\n}\n\nexport interface AsyncIteratorRecord {\n iterator: AsyncIterator,\n nextMethod: AsyncIterator['next'],\n done: boolean;\n}\n\nexport type SyncOrAsyncIteratorRecord = SyncIteratorRecord | AsyncIteratorRecord;\n\nexport function CreateAsyncFromSyncIterator(syncIteratorRecord: SyncIteratorRecord): AsyncIteratorRecord {\n // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%,\n // we use yield* inside an async generator function to achieve the same result.\n\n // Wrap the sync iterator inside a sync iterable, so we can use it with yield*.\n const syncIterable = {\n [Symbol.iterator]: () => syncIteratorRecord.iterator\n };\n // Create an async generator function and immediately invoke it.\n const asyncIterator = (async function* () {\n return yield* syncIterable;\n }());\n // Return as an async iterator record.\n const nextMethod = asyncIterator.next;\n return { iterator: asyncIterator, nextMethod, done: false };\n}\n\n// Aligns with core-js/modules/es.symbol.async-iterator.js\nexport const SymbolAsyncIterator: (typeof Symbol)['asyncIterator'] =\n Symbol.asyncIterator ??\n Symbol.for?.('Symbol.asyncIterator') ??\n '@@asyncIterator';\n\nexport type SyncOrAsyncIterable = Iterable | AsyncIterable;\nexport type SyncOrAsyncIteratorMethod = () => (Iterator | AsyncIterator);\n\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint: 'async',\n method?: SyncOrAsyncIteratorMethod\n): AsyncIteratorRecord;\nfunction GetIterator(\n obj: Iterable,\n hint: 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncIteratorRecord;\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint = 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncOrAsyncIteratorRecord {\n assert(hint === 'sync' || hint === 'async');\n if (method === undefined) {\n if (hint === 'async') {\n method = GetMethod(obj as AsyncIterable, SymbolAsyncIterator);\n if (method === undefined) {\n const syncMethod = GetMethod(obj as Iterable, Symbol.iterator);\n const syncIteratorRecord = GetIterator(obj as Iterable, 'sync', syncMethod);\n return CreateAsyncFromSyncIterator(syncIteratorRecord);\n }\n } else {\n method = GetMethod(obj as Iterable, Symbol.iterator);\n }\n }\n if (method === undefined) {\n throw new TypeError('The object is not iterable');\n }\n const iterator = reflectCall(method, obj, []);\n if (!typeIsObject(iterator)) {\n throw new TypeError('The iterator method must return an object');\n }\n const nextMethod = iterator.next;\n return { iterator, nextMethod, done: false } as SyncOrAsyncIteratorRecord;\n}\n\nexport { GetIterator };\n\nexport function IteratorNext(iteratorRecord: AsyncIteratorRecord): Promise> {\n const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []);\n if (!typeIsObject(result)) {\n throw new TypeError('The iterator.next() method must return an object');\n }\n return result;\n}\n\nexport function IteratorComplete(\n iterResult: IteratorResult\n): iterResult is IteratorReturnResult {\n assert(typeIsObject(iterResult));\n return Boolean(iterResult.done);\n}\n\nexport function IteratorValue(iterResult: IteratorYieldResult): T {\n assert(typeIsObject(iterResult));\n return iterResult.value;\n}\n","/// \n\nimport { SymbolAsyncIterator } from '../../../lib/abstract-ops/ecmascript';\n\n// We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it.\nexport const AsyncIteratorPrototype: AsyncIterable = {\n // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( )\n // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator\n [SymbolAsyncIterator](this: AsyncIterator) {\n return this;\n }\n};\nObject.defineProperty(AsyncIteratorPrototype, SymbolAsyncIterator, { enumerable: false });\n","/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadableStreamDefaultReadResult,\n type ReadRequest\n} from './default-reader';\nimport { ReadableStreamReaderGenericCancel, ReadableStreamReaderGenericRelease } from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterableIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ninterface ReadableStreamAsyncIteratorInstance extends ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nObject.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n","import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: NonShared): NonShared {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer) as NonShared;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n","export type TypedArray =\n | Int8Array\n | Uint8Array\n | Uint8ClampedArray\n | Int16Array\n | Uint16Array\n | Int32Array\n | Uint32Array\n | Float32Array\n | Float64Array;\n\nexport type NonShared = T & {\n buffer: ArrayBuffer;\n}\n\nexport interface ArrayBufferViewConstructor {\n new(buffer: ArrayBuffer, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n}\n\nexport interface TypedArrayConstructor extends ArrayBufferViewConstructor {\n readonly BYTES_PER_ELEMENT: number;\n}\n\nexport type DataViewConstructor = ArrayBufferViewConstructor;\n\nfunction isDataViewConstructor(ctor: Function): ctor is DataViewConstructor {\n return ctor === DataView;\n}\n\nexport function isDataView(view: ArrayBufferView): view is DataView {\n return isDataViewConstructor(view.constructor);\n}\n\nexport function arrayBufferViewElementSize(ctor: ArrayBufferViewConstructor): number {\n if (isDataViewConstructor(ctor)) {\n return 1;\n }\n return (ctor as unknown as TypedArrayConstructor).BYTES_PER_ELEMENT;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n IsReadableStreamDefaultReader,\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n type ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n type ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n type ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport type { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\nimport {\n type ArrayBufferViewConstructor,\n arrayBufferViewElementSize,\n type NonShared,\n type TypedArrayConstructor\n} from '../helpers/array-buffer-view';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: NonShared | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: NonShared): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond');\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBuffer;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor = NonShared> =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: TypedArrayConstructor;\n readerType: 'default' | 'none';\n}\n\ninterface BYOBPullIntoDescriptor = NonShared> {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob' | 'none';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: NonShared): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest>): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n minimumFill: 1,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n if (this._pendingPullIntos.length > 0) {\n const firstPullInto = this._pendingPullIntos.peek();\n firstPullInto.readerType = 'none';\n\n this._pendingPullIntos = new SimpleQueue();\n this._pendingPullIntos.push(firstPullInto);\n }\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableByteStreamController.prototype.close, 'close');\nsetFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableByteStreamController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor>(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n assert(pullIntoDescriptor.readerType !== 'none');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as NonShared, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor>(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n let clonedChunk;\n try {\n clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength);\n } catch (cloneE) {\n ReadableByteStreamControllerError(controller, cloneE);\n throw cloneE;\n }\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength);\n}\n\nfunction ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.readerType === 'none');\n if (firstDescriptor.bytesFilled > 0) {\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n firstDescriptor.buffer,\n firstDescriptor.byteOffset,\n firstDescriptor.bytesFilled\n );\n }\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize;\n const maxAlignedBytes = maxBytesFilled - remainderBytes;\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n assert(pullIntoDescriptor.readerType !== 'none');\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nfunction ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller: ReadableByteStreamController) {\n const reader = controller._controlledReadableByteStream._reader;\n assert(IsReadableStreamDefaultReader(reader));\n while (reader._readRequests.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n const readRequest = reader._readRequests.shift();\n ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest);\n }\n}\n\nexport function ReadableByteStreamControllerPullInto>(\n controller: ReadableByteStreamController,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n const elementSize = arrayBufferViewElementSize(ctor);\n\n const { byteOffset, byteLength } = view;\n\n const minimumFill = min * elementSize;\n assert(minimumFill >= elementSize && minimumFill <= byteLength);\n assert(minimumFill % elementSize === 0);\n\n let buffer: ArrayBuffer;\n try {\n buffer = TransferArrayBuffer(view.buffer);\n } catch (e) {\n readIntoRequest._errorSteps(e);\n return;\n }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset,\n byteLength,\n bytesFilled: 0,\n minimumFill,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled % firstDescriptor.elementSize === 0);\n\n if (firstDescriptor.readerType === 'none') {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n return;\n }\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) {\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n pullIntoDescriptor.buffer,\n end - remainderSize,\n remainderSize\n );\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(\n controller: ReadableByteStreamController,\n chunk: NonShared\n) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const { buffer, byteOffset, byteLength } = chunk;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n if (firstPendingPullInto.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto);\n }\n }\n\n if (ReadableStreamHasDefaultReader(stream)) {\n ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller);\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView as NonShared, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerFillReadRequestFromQueue(\n controller: ReadableByteStreamController,\n readRequest: ReadRequest>\n) {\n assert(controller._queueTotalSize > 0);\n\n const entry = controller._queue.shift();\n controller._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n readRequest._chunkSteps(view as NonShared);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view as NonShared);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: NonShared) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: NonShared) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n","import { assertDictionary, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n\nexport function convertByobReadOptions(\n options: ReadableStreamBYOBReaderReadOptions | null | undefined,\n context: string\n): ValidatedReadableStreamBYOBReaderReadOptions {\n assertDictionary(options, context);\n const min = options?.min ?? 1;\n return {\n min: convertUnsignedLongLongWithEnforceRange(\n min,\n `${context} has member 'min' that`\n )\n };\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, type ReadableByteStream, type ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from './reader-options';\nimport { convertByobReadOptions } from '../validators/reader-options';\nimport { isDataView, type NonShared, type TypedArray } from '../helpers/array-buffer-view';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream as ReadableStream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest>(\n stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest\n): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest> {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(\n view: T,\n options?: ReadableStreamBYOBReaderReadOptions\n ): Promise>;\n read>(\n view: T,\n rawOptions: ReadableStreamBYOBReaderReadOptions | null | undefined = {}\n ): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n let options: ValidatedReadableStreamBYOBReaderReadOptions;\n try {\n options = convertByobReadOptions(rawOptions, 'options');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const min = options.min;\n if (min === 0) {\n return promiseRejectedWith(new TypeError('options.min must be greater than 0'));\n }\n if (!isDataView(view)) {\n if (min > (view as unknown as TypedArray).length) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s length'));\n }\n } else if (min > view.byteLength) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s byteLength'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamBYOBReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamBYOBReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead>(\n reader: ReadableStreamBYOBReader,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n min,\n readIntoRequest\n );\n }\n}\n\nexport function ReadableStreamBYOBReaderRelease(reader: ReadableStreamBYOBReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n}\n\nexport function ReadableStreamBYOBReaderErrorReadIntoRequests(reader: ReadableStreamBYOBReader, e: any) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n","/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * If aborted, returns the reason for aborting.\n */\n readonly reason?: any;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(reason?: any): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n type QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { type AbortController, type AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(WritableStream.prototype.abort, 'abort');\nsetFunctionName(WritableStream.prototype.close, 'close');\nsetFunctionName(WritableStream.prototype.getWriter, 'getWriter');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight\n};\n\nexport type {\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort(reason);\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nsetFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort');\nsetFunctionName(WritableStreamDefaultWriter.prototype.close, 'close');\nsetFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock');\nsetFunctionName(WritableStreamDefaultWriter.prototype.write, 'write');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n return null;\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let writeAlgorithm: (chunk: W) => Promise;\n let closeAlgorithm: () => Promise;\n let abortAlgorithm: (reason: any) => Promise;\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n } else {\n writeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n } else {\n closeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n } else {\n abortAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n return null;\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n","/// \n\nfunction getGlobals(): typeof globalThis | undefined {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n } else if (typeof self !== 'undefined') {\n return self;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n","/// \nimport { globals } from '../globals';\nimport { setFunctionName } from '../lib/helpers/miscellaneous';\n\ninterface DOMException extends Error {\n name: string;\n message: string;\n}\n\ntype DOMExceptionConstructor = new (message?: string, name?: string) => DOMException;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n if ((ctor as DOMExceptionConstructor).name !== 'DOMException') {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Support:\n * - Web browsers\n * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87)\n */\nfunction getFromGlobal(): DOMExceptionConstructor | undefined {\n const ctor = globals?.DOMException;\n return isDOMExceptionConstructor(ctor) ? ctor : undefined;\n}\n\n/**\n * Support:\n * - All platforms\n */\nfunction createPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line @typescript-eslint/no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n setFunctionName(ctor, 'DOMException');\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nconst DOMException: DOMExceptionConstructor = getFromGlobal() || createPolyfill();\n\nexport { DOMException };\n","import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n return null;\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => null) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => null) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest(): null {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n return null;\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any): null {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n\n return null;\n }\n });\n}\n","import type { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, type QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n type ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport type { ValidatedUnderlyingSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n // Do nothing.\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultController.prototype.close, 'close');\nsetFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableStreamDefaultController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n","import {\n CreateReadableByteStream,\n CreateReadableStream,\n type DefaultReadableStream,\n IsReadableStream,\n type ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n type ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n type ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(\n stream: ReadableStream,\n cloneForBranch2: boolean\n): [DefaultReadableStream, DefaultReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: DefaultReadableStream;\n let branch2: DefaultReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader> = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader>) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return null;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: NonShared, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader>(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n","import { typeIsObject } from '../helpers/miscellaneous';\nimport type { ReadableStreamDefaultReadResult } from './default-reader';\n\n/**\n * A common interface for a `ReadadableStream` implementation.\n *\n * @public\n */\nexport interface ReadableStreamLike {\n readonly locked: boolean;\n\n getReader(): ReadableStreamDefaultReaderLike;\n}\n\n/**\n * A common interface for a `ReadableStreamDefaultReader` implementation.\n *\n * @public\n */\nexport interface ReadableStreamDefaultReaderLike {\n readonly closed: Promise;\n\n cancel(reason?: any): Promise;\n\n read(): Promise>;\n\n releaseLock(): void;\n}\n\nexport function isReadableStreamLike(stream: unknown): stream is ReadableStreamLike {\n return typeIsObject(stream) && typeof (stream as ReadableStreamLike).getReader !== 'undefined';\n}\n","import { CreateReadableStream, type DefaultReadableStream } from '../readable-stream';\nimport {\n isReadableStreamLike,\n type ReadableStreamDefaultReaderLike,\n type ReadableStreamLike\n} from './readable-stream-like';\nimport { ReadableStreamDefaultControllerClose, ReadableStreamDefaultControllerEnqueue } from './default-controller';\nimport { GetIterator, GetMethod, IteratorComplete, IteratorNext, IteratorValue } from '../abstract-ops/ecmascript';\nimport { promiseRejectedWith, promiseResolvedWith, reflectCall, transformPromiseWith } from '../helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { noop } from '../../utils';\n\nexport function ReadableStreamFrom(\n source: Iterable | AsyncIterable | ReadableStreamLike\n): DefaultReadableStream {\n if (isReadableStreamLike(source)) {\n return ReadableStreamFromDefaultReader(source.getReader());\n }\n return ReadableStreamFromIterable(source);\n}\n\nexport function ReadableStreamFromIterable(asyncIterable: Iterable | AsyncIterable): DefaultReadableStream {\n let stream: DefaultReadableStream;\n const iteratorRecord = GetIterator(asyncIterable, 'async');\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let nextResult;\n try {\n nextResult = IteratorNext(iteratorRecord);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const nextPromise = promiseResolvedWith(nextResult);\n return transformPromiseWith(nextPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object');\n }\n const done = IteratorComplete(iterResult);\n if (done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = IteratorValue(iterResult);\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n const iterator = iteratorRecord.iterator;\n let returnMethod: (typeof iterator)['return'] | undefined;\n try {\n returnMethod = GetMethod(iterator, 'return');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n if (returnMethod === undefined) {\n return promiseResolvedWith(undefined);\n }\n let returnResult: IteratorResult | Promise>;\n try {\n returnResult = reflectCall(returnMethod, iterator, [reason]);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const returnPromise = promiseResolvedWith(returnResult);\n return transformPromiseWith(returnPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object');\n }\n return undefined;\n });\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n\nexport function ReadableStreamFromDefaultReader(\n reader: ReadableStreamDefaultReaderLike\n): DefaultReadableStream {\n let stream: DefaultReadableStream;\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let readPromise;\n try {\n readPromise = reader.read();\n } catch (e) {\n return promiseRejectedWith(e);\n }\n return transformPromiseWith(readPromise, readResult => {\n if (!typeIsObject(readResult)) {\n throw new TypeError('The promise returned by the reader.read() method must fulfill with an object');\n }\n if (readResult.done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = readResult.value;\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n try {\n return promiseResolvedWith(reader.cancel(reason));\n } catch (e) {\n return promiseRejectedWith(e);\n }\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n","import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n","import { assertDictionary } from './basic';\nimport type {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n","import { assertDictionary } from './basic';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n","import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n","import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, type ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderErrorReadRequests,\n type ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReaderErrorReadIntoRequests,\n type ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { ReadableStreamFrom } from './readable-stream/from';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport type {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList, SymbolAsyncIterator } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions\n} from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport type { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport type { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\nimport type { ReadableStreamDefaultReaderLike, ReadableStreamLike } from './readable-stream/readable-stream-like';\nimport type { NonShared } from './helpers/array-buffer-view';\n\nexport type DefaultReadableStream = ReadableStream & {\n _readableStreamController: ReadableStreamDefaultController\n};\n\nexport type ReadableByteStream = ReadableStream> & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream implements AsyncIterable {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n\n [SymbolAsyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator {\n // Stub implementation, overridden below\n return this.values(options);\n }\n\n /**\n * Creates a new ReadableStream wrapping the provided iterable or async iterable.\n *\n * This can be used to adapt various kinds of objects into a readable stream,\n * such as an array, an async generator, or a Node.js readable stream.\n */\n static from(asyncIterable: Iterable | AsyncIterable | ReadableStreamLike): ReadableStream {\n return ReadableStreamFrom(asyncIterable);\n }\n}\n\nObject.defineProperties(ReadableStream, {\n from: { enumerable: true }\n});\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(ReadableStream.from, 'from');\nsetFunctionName(ReadableStream.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStream.prototype.getReader, 'getReader');\nsetFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough');\nsetFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo');\nsetFunctionName(ReadableStream.prototype.tee, 'tee');\nsetFunctionName(ReadableStream.prototype.values, 'values');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nObject.defineProperty(ReadableStream.prototype, SymbolAsyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n});\n\nexport type {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n ReadableStreamBYOBReaderReadOptions,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions,\n ReadableStreamLike,\n ReadableStreamDefaultReaderLike\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1\n): DefaultReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: DefaultReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n","import type { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\nsetFunctionName(byteLengthSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\nsetFunctionName(countSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const cancel = original?.cancel;\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n cancel: cancel === undefined ?\n undefined :\n convertTransformerCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n\nfunction convertTransformerCancelCallback(\n fn: TransformerCancelCallback,\n original: Transformer,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith,\n uponPromise\n} from './helpers/webidl';\nimport { CreateReadableStream, type DefaultReadableStream, ReadableStream } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: DefaultReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport type {\n Transformer,\n TransformerCancelCallback,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSourceCancelAlgorithm(stream, reason);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n TransformStreamUnblockWrite(stream);\n}\n\nfunction TransformStreamUnblockWrite(stream: TransformStream) {\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _finishPromise: Promise | undefined;\n /** @internal */\n _finishPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _finishPromise_reject?: (reason: any) => void;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n /** @internal */\n _cancelAlgorithm: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(TransformStreamDefaultController.prototype.error, 'error');\nsetFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._finishPromise = undefined;\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm: (chunk: I) => Promise;\n let flushAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n } else {\n transformAlgorithm = chunk => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n }\n\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n } else {\n flushAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n if (transformer.cancel !== undefined) {\n cancelAlgorithm = reason => transformer.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally,\n // we don't run the _cancelAlgorithm again.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerError(readable._readableStreamController, reason);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally,\n // we don't also run the _cancelAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(flushPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerClose(readable._readableStreamController);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\nfunction TransformStreamDefaultSourceCancelAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._writable cannot change after construction, so caching it across a call to user code is safe.\n const writable = stream._writable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or\n // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the\n // _flushAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (writable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, writable._storedError);\n } else {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\nexport function defaultControllerFinishPromiseResolve(controller: TransformStreamDefaultController) {\n if (controller._finishPromise_resolve === undefined) {\n return;\n }\n\n controller._finishPromise_resolve();\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nexport function defaultControllerFinishPromiseReject(controller: TransformStreamDefaultController, reason: any) {\n if (controller._finishPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(controller._finishPromise!);\n controller._finishPromise_reject(reason);\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n"],"names":["Symbol","_a","queueMicrotask","streamBrandCheckException","defaultControllerBrandCheckException"],"mappings":";;;;;;;AAAA;AAEA,IAAM,cAAc,GAClB,OAAO,MAAM,KAAK,UAAU,IAAI,OAAO,MAAM,CAAC,QAAQ,KAAK,QAAQ;AACjE,IAAA,MAAM;IACN,UAAA,WAAW,IAAI,OAAA,SAAA,CAAA,MAAA,CAAU,WAAW,EAAoB,GAAA,CAAA,CAAA,EAAA;;ACL5D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AA4GA;AACO,SAAS,WAAW,CAAC,OAAO,EAAE,IAAI,EAAE;AAC3C,IAAI,IAAI,CAAC,GAAG,EAAE,KAAK,EAAE,CAAC,EAAE,IAAI,EAAE,WAAW,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO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A,OAAO,IAAI,SAAS,CAClB,qDAA8C,IAAI,EAAA,yDAAA,CAAyD,CAAC,CAAC;AACjH,CAAC;AAEK,SAAU,qCAAqC,CAAC,UAAiD,EAAA;AACrG,IAAA,IAAI,UAAU,CAAC,sBAAsB,KAAK,SAAS,EAAE;QACnD,OAAO;KACR;IAED,UAAU,CAAC,sBAAsB,EAAE,CAAC;AACpC,IAAA,UAAU,CAAC,sBAAsB,GAAG,SAAS,CAAC;AAC9C,IAAA,UAAU,CAAC,qBAAqB,GAAG,SAAS,CAAC;AAC/C,CAAC;AAEe,SAAA,oCAAoC,CAAC,UAAiD,EAAE,MAAW,EAAA;AACjH,IAAA,IAAI,UAAU,CAAC,qBAAqB,KAAK,SAAS,EAAE;QAClD,OAAO;KACR;AAED,IAAA,yBAAyB,CAAC,UAAU,CAAC,cAAe,CAAC,CAAC;AACtD,IAAA,UAAU,CAAC,qBAAqB,CAAC,MAAM,CAAC,CAAC;AACzC,IAAA,UAAU,CAAC,sBAAsB,GAAG,SAAS,CAAC;AAC9C,IAAA,UAAU,CAAC,qBAAqB,GAAG,SAAS,CAAC;AAC/C,CAAC;AAED;AAEA,SAAS,yBAAyB,CAAC,IAAY,EAAA;AAC7C,IAAA,OAAO,IAAI,SAAS,CAClB,oCAA6B,IAAI,EAAA,wCAAA,CAAwC,CAAC,CAAC;AAC/E;;;;","x_google_ignoreList":[1]} \ No newline at end of file diff --git a/backend/node_modules/web-streams-polyfill/dist/types/polyfill.d.ts b/backend/node_modules/web-streams-polyfill/dist/types/polyfill.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2d098357e941b2b97994854ed83d6a3bd4ba5379 --- /dev/null +++ b/backend/node_modules/web-streams-polyfill/dist/types/polyfill.d.ts @@ -0,0 +1,24 @@ +/// +/// +import { ReadableStreamAsyncIterator, ReadableStreamIteratorOptions } from './ponyfill'; +export * from './ponyfill'; +declare global { + interface ReadableStream extends AsyncIterable { + /** + * Asynchronously iterates over the chunks in the stream's internal queue. + * + * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader. + * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method + * is called, e.g. by breaking out of the loop. + * + * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also + * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing + * `true` for the `preventCancel` option. + */ + values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator; + /** + * {@inheritDoc ReadableStream.values} + */ + [Symbol.asyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator; + } +} diff --git a/backend/node_modules/web-streams-polyfill/dist/types/ponyfill.d.ts b/backend/node_modules/web-streams-polyfill/dist/types/ponyfill.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d31068b86513958efd0629a01b46f66456e3b5d3 --- /dev/null +++ b/backend/node_modules/web-streams-polyfill/dist/types/ponyfill.d.ts @@ -0,0 +1,780 @@ +/// +/** + * A signal object that allows you to communicate with a request and abort it if required + * via its associated `AbortController` object. + * + * @remarks + * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types. + * It is redefined here, so it can be polyfilled without a DOM, for example with + * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment. + * + * @public + */ +export declare interface AbortSignal { + /** + * Whether the request is aborted. + */ + readonly aborted: boolean; + /** + * If aborted, returns the reason for aborting. + */ + readonly reason?: any; + /** + * Add an event listener to be triggered when this signal becomes aborted. + */ + addEventListener(type: 'abort', listener: () => void): void; + /** + * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}. + */ + removeEventListener(type: 'abort', listener: () => void): void; +} +/** + * A queuing strategy that counts the number of bytes in each chunk. + * + * @public + */ +export declare class ByteLengthQueuingStrategy implements QueuingStrategy { + constructor(options: QueuingStrategyInit); + /* + * Returns the high water mark provided to the constructor. + */ + readonly highWaterMark: number; + /* + * Measures the size of `chunk` by returning the value of its `byteLength` property. + */ + readonly size: (chunk: ArrayBufferView) => number; +} +/** + * A queuing strategy that counts the number of chunks. + * + * @public + */ +export declare class CountQueuingStrategy implements QueuingStrategy { + constructor(options: QueuingStrategyInit); + /* + * Returns the high water mark provided to the constructor. + */ + readonly highWaterMark: number; + /* + * Measures the size of `chunk` by always returning 1. + * This ensures that the total queue size is a count of the number of chunks in the queue. + */ + readonly size: (chunk: any) => 1; +} +/** + * A queuing strategy. + * + * @public + */ +export declare interface QueuingStrategy { + /** + * A non-negative number indicating the high water mark of the stream using this queuing strategy. + */ + highWaterMark?: number; + /** + * A function that computes and returns the finite non-negative size of the given chunk value. + */ + size?: QueuingStrategySizeCallback; +} +/** + * @public + */ +export declare interface QueuingStrategyInit { + /** + * {@inheritDoc QueuingStrategy.highWaterMark} + */ + highWaterMark: number; +} +/** + * {@inheritDoc QueuingStrategy.size} + * @public + */ +export declare type QueuingStrategySizeCallback = (chunk: T) => number; +/** + * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. + * + * @public + */ +export declare class ReadableByteStreamController { + private constructor(); + /* + * Returns the current BYOB pull request, or `null` if there isn't one. + */ + readonly byobRequest: ReadableStreamBYOBRequest | null; + /* + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + */ + readonly desiredSize: number | null; + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close(): void; + /** + * Enqueues the given chunk chunk in the controlled readable stream. + * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown. + */ + enqueue(chunk: ArrayBufferView): void; + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e?: any): void; +} +/** + * A readable stream represents a source of data, from which you can read. + * + * @public + */ +export declare class ReadableStream implements AsyncIterable { + constructor(underlyingSource: UnderlyingByteSource, strategy?: { + highWaterMark?: number; + size?: undefined; + }); + constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy); + /* + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. + */ + readonly locked: boolean; + /** + * Cancels the stream, signaling a loss of interest in the stream by a consumer. + * + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} + * method, which might or might not use it. + */ + cancel(reason?: any): Promise; + /** + * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader. + * + * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams, + * i.e. streams which were constructed specifically with the ability to handle "bring your own buffer" reading. + * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its + * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise + * control over allocation. + */ + getReader({ mode }: { + mode: 'byob'; + }): ReadableStreamBYOBReader; + /** + * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader. + * While the stream is locked, no other reader can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to consume a stream + * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours + * or cancel the stream, which would interfere with your abstraction. + */ + getReader(): ReadableStreamDefaultReader; + /** + * Provides a convenient, chainable way of piping this readable stream through a transform stream + * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream + * into the writable side of the supplied pair, and returns the readable side for further use. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + */ + pipeThrough(transform: { + readable: RS; + writable: WritableStream; + }, options?: StreamPipeOptions): RS; + /** + * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under + * various error conditions can be customized with a number of passed options. It returns a promise that fulfills + * when the piping process completes successfully, or rejects if any errors were encountered. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + */ + pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise; + /** + * Tees this readable stream, returning a two-element array containing the two resulting branches as + * new {@link ReadableStream} instances. + * + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be + * propagated to the stream's underlying source. + * + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, + * this could allow interference between the two branches. + */ + tee(): [ + ReadableStream, + ReadableStream + ]; + /** + * Asynchronously iterates over the chunks in the stream's internal queue. + * + * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader. + * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method + * is called, e.g. by breaking out of the loop. + * + * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also + * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing + * `true` for the `preventCancel` option. + */ + values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator; + /** + * {@inheritDoc ReadableStream.values} + */ + [Symbol.asyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator; + /** + * Creates a new ReadableStream wrapping the provided iterable or async iterable. + * + * This can be used to adapt various kinds of objects into a readable stream, + * such as an array, an async generator, or a Node.js readable stream. + */ + static from(asyncIterable: Iterable | AsyncIterable | ReadableStreamLike): ReadableStream; +} +/** + * An async iterator returned by {@link ReadableStream.values}. + * + * @public + */ +export declare interface ReadableStreamAsyncIterator extends AsyncIterableIterator { + next(): Promise>; + return(value?: any): Promise>; +} +/** + * A BYOB reader vended by a {@link ReadableStream}. + * + * @public + */ +export declare class ReadableStreamBYOBReader { + constructor(stream: ReadableStream); + /* + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the reader's lock is released before the stream finishes closing. + */ + readonly closed: Promise; + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason?: any): Promise; + /** + * Attempts to reads bytes into view, and returns a promise resolved with the result. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read(view: T, options?: ReadableStreamBYOBReaderReadOptions): Promise>; + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock(): void; +} +/** + * Options for {@link ReadableStreamBYOBReader.read | reading} a stream + * with a {@link ReadableStreamBYOBReader | BYOB reader}. + * + * @public + */ +export declare interface ReadableStreamBYOBReaderReadOptions { + min?: number; +} +/** + * A result returned by {@link ReadableStreamBYOBReader.read}. + * + * @public + */ +export declare type ReadableStreamBYOBReadResult = { + done: false; + value: T; +} | { + done: true; + value: T | undefined; +}; +/** + * A pull-into request in a {@link ReadableByteStreamController}. + * + * @public + */ +export declare class ReadableStreamBYOBRequest { + private constructor(); + /* + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. + */ + readonly view: ArrayBufferView | null; + /** + * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into + * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer. + * + * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer + * modifiable. + */ + respond(bytesWritten: number): void; + /** + * Indicates to the associated readable byte stream that instead of writing into + * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`, + * which will be given to the consumer of the readable byte stream. + * + * After this method is called, `view` will be transferred and no longer modifiable. + */ + respondWithNewView(view: ArrayBufferView): void; +} +/** + * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. + * + * @public + */ +export declare class ReadableStreamDefaultController { + private constructor(); + /* + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + */ + readonly desiredSize: number | null; + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close(): void; + /** + * Enqueues the given chunk `chunk` in the controlled readable stream. + */ + enqueue(chunk: R): void; + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e?: any): void; +} +/** + * A default reader vended by a {@link ReadableStream}. + * + * @public + */ +export declare class ReadableStreamDefaultReader { + constructor(stream: ReadableStream); + /* + * Returns a promise that will be fulfilled when the stream becomes closed, + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + */ + readonly closed: Promise; + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason?: any): Promise; + /** + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read(): Promise>; + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock(): void; +} +/** + * A common interface for a `ReadableStreamDefaultReader` implementation. + * + * @public + */ +export declare interface ReadableStreamDefaultReaderLike { + readonly closed: Promise; + cancel(reason?: any): Promise; + read(): Promise>; + releaseLock(): void; +} +/** + * A result returned by {@link ReadableStreamDefaultReader.read}. + * + * @public + */ +export declare type ReadableStreamDefaultReadResult = { + done: false; + value: T; +} | { + done: true; + value?: undefined; +}; +/** + * Options for {@link ReadableStream.values | async iterating} a stream. + * + * @public + */ +export declare interface ReadableStreamIteratorOptions { + preventCancel?: boolean; +} +/** + * A common interface for a `ReadadableStream` implementation. + * + * @public + */ +export declare interface ReadableStreamLike { + readonly locked: boolean; + getReader(): ReadableStreamDefaultReaderLike; +} +/** + * A pair of a {@link ReadableStream | readable stream} and {@link WritableStream | writable stream} that can be passed + * to {@link ReadableStream.pipeThrough}. + * + * @public + */ +export declare interface ReadableWritablePair { + readable: ReadableStream; + writable: WritableStream; +} +/** + * Options for {@link ReadableStream.pipeTo | piping} a stream. + * + * @public + */ +export declare interface StreamPipeOptions { + /** + * If set to true, {@link ReadableStream.pipeTo} will not abort the writable stream if the readable stream errors. + */ + preventAbort?: boolean; + /** + * If set to true, {@link ReadableStream.pipeTo} will not cancel the readable stream if the writable stream closes + * or errors. + */ + preventCancel?: boolean; + /** + * If set to true, {@link ReadableStream.pipeTo} will not close the writable stream if the readable stream closes. + */ + preventClose?: boolean; + /** + * Can be set to an {@link AbortSignal} to allow aborting an ongoing pipe operation via the corresponding + * `AbortController`. In this case, the source readable stream will be canceled, and the destination writable stream + * aborted, unless the respective options `preventCancel` or `preventAbort` are set. + */ + signal?: AbortSignal; +} +/** + * A transformer for constructing a {@link TransformStream}. + * + * @public + */ +export declare interface Transformer { + /** + * A function that is called immediately during creation of the {@link TransformStream}. + */ + start?: TransformerStartCallback; + /** + * A function called when a new chunk originally written to the writable side is ready to be transformed. + */ + transform?: TransformerTransformCallback; + /** + * A function called after all chunks written to the writable side have been transformed by successfully passing + * through {@link Transformer.transform | transform()}, and the writable side is about to be closed. + */ + flush?: TransformerFlushCallback; + /** + * A function called when the readable side is cancelled, or when the writable side is aborted. + */ + cancel?: TransformerCancelCallback; + readableType?: undefined; + writableType?: undefined; +} +/** @public */ +export declare type TransformerCancelCallback = (reason: any) => void | PromiseLike; +/** @public */ +export declare type TransformerFlushCallback = (controller: TransformStreamDefaultController) => void | PromiseLike; +/** @public */ +export declare type TransformerStartCallback = (controller: TransformStreamDefaultController) => void | PromiseLike; +/** @public */ +export declare type TransformerTransformCallback = (chunk: I, controller: TransformStreamDefaultController) => void | PromiseLike; +/** + * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, + * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. + * In a manner specific to the transform stream in question, writes to the writable side result in new data being + * made available for reading from the readable side. + * + * @public + */ +export declare class TransformStream { + constructor(transformer?: Transformer, writableStrategy?: QueuingStrategy, readableStrategy?: QueuingStrategy); + /* + * The readable side of the transform stream. + */ + readonly readable: ReadableStream; + /* + * The writable side of the transform stream. + */ + readonly writable: WritableStream; +} +/** + * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. + * + * @public + */ +export declare class TransformStreamDefaultController { + private constructor(); + /* + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. + */ + readonly desiredSize: number | null; + /** + * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream. + */ + enqueue(chunk: O): void; + /** + * Errors both the readable side and the writable side of the controlled transform stream, making all future + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. + */ + error(reason?: any): void; + /** + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the + * transformer only needs to consume a portion of the chunks written to the writable side. + */ + terminate(): void; +} +/** + * An underlying byte source for constructing a {@link ReadableStream}. + * + * @public + */ +export declare interface UnderlyingByteSource { + /** + * {@inheritDoc UnderlyingSource.start} + */ + start?: UnderlyingByteSourceStartCallback; + /** + * {@inheritDoc UnderlyingSource.pull} + */ + pull?: UnderlyingByteSourcePullCallback; + /** + * {@inheritDoc UnderlyingSource.cancel} + */ + cancel?: UnderlyingSourceCancelCallback; + /** + * Can be set to "bytes" to signal that the constructed {@link ReadableStream} is a readable byte stream. + * This ensures that the resulting {@link ReadableStream} will successfully be able to vend BYOB readers via its + * {@link ReadableStream.(getReader:1) | getReader()} method. + * It also affects the controller argument passed to the {@link UnderlyingByteSource.start | start()} + * and {@link UnderlyingByteSource.pull | pull()} methods. + */ + type: 'bytes'; + /** + * Can be set to a positive integer to cause the implementation to automatically allocate buffers for the + * underlying source code to write into. In this case, when a consumer is using a default reader, the stream + * implementation will automatically allocate an ArrayBuffer of the given size, so that + * {@link ReadableByteStreamController.byobRequest | controller.byobRequest} is always present, + * as if the consumer was using a BYOB reader. + */ + autoAllocateChunkSize?: number; +} +/** @public */ +export declare type UnderlyingByteSourcePullCallback = (controller: ReadableByteStreamController) => void | PromiseLike; +/** @public */ +export declare type UnderlyingByteSourceStartCallback = (controller: ReadableByteStreamController) => void | PromiseLike; +/** + * An underlying sink for constructing a {@link WritableStream}. + * + * @public + */ +export declare interface UnderlyingSink { + /** + * A function that is called immediately during creation of the {@link WritableStream}. + */ + start?: UnderlyingSinkStartCallback; + /** + * A function that is called when a new chunk of data is ready to be written to the underlying sink. The stream + * implementation guarantees that this function will be called only after previous writes have succeeded, and never + * before {@link UnderlyingSink.start | start()} has succeeded or after {@link UnderlyingSink.close | close()} or + * {@link UnderlyingSink.abort | abort()} have been called. + * + * This function is used to actually send the data to the resource presented by the underlying sink, for example by + * calling a lower-level API. + */ + write?: UnderlyingSinkWriteCallback; + /** + * A function that is called after the producer signals, via + * {@link WritableStreamDefaultWriter.close | writer.close()}, that they are done writing chunks to the stream, and + * subsequently all queued-up writes have successfully completed. + * + * This function can perform any actions necessary to finalize or flush writes to the underlying sink, and release + * access to any held resources. + */ + close?: UnderlyingSinkCloseCallback; + /** + * A function that is called after the producer signals, via {@link WritableStream.abort | stream.abort()} or + * {@link WritableStreamDefaultWriter.abort | writer.abort()}, that they wish to abort the stream. It takes as its + * argument the same value as was passed to those methods by the producer. + * + * Writable streams can additionally be aborted under certain conditions during piping; see the definition of the + * {@link ReadableStream.pipeTo | pipeTo()} method for more details. + * + * This function can clean up any held resources, much like {@link UnderlyingSink.close | close()}, but perhaps with + * some custom handling. + */ + abort?: UnderlyingSinkAbortCallback; + type?: undefined; +} +/** @public */ +export declare type UnderlyingSinkAbortCallback = (reason: any) => void | PromiseLike; +/** @public */ +export declare type UnderlyingSinkCloseCallback = () => void | PromiseLike; +/** @public */ +export declare type UnderlyingSinkStartCallback = (controller: WritableStreamDefaultController) => void | PromiseLike; +/** @public */ +export declare type UnderlyingSinkWriteCallback = (chunk: W, controller: WritableStreamDefaultController) => void | PromiseLike; +/** + * An underlying source for constructing a {@link ReadableStream}. + * + * @public + */ +export declare interface UnderlyingSource { + /** + * A function that is called immediately during creation of the {@link ReadableStream}. + */ + start?: UnderlyingSourceStartCallback; + /** + * A function that is called whenever the stream’s internal queue of chunks becomes not full, + * i.e. whenever the queue’s desired size becomes positive. Generally, it will be called repeatedly + * until the queue reaches its high water mark (i.e. until the desired size becomes non-positive). + */ + pull?: UnderlyingSourcePullCallback; + /** + * A function that is called whenever the consumer cancels the stream, via + * {@link ReadableStream.cancel | stream.cancel()}, + * {@link ReadableStreamDefaultReader.cancel | defaultReader.cancel()}, or + * {@link ReadableStreamBYOBReader.cancel | byobReader.cancel()}. + * It takes as its argument the same value as was passed to those methods by the consumer. + */ + cancel?: UnderlyingSourceCancelCallback; + type?: undefined; +} +/** @public */ +export declare type UnderlyingSourceCancelCallback = (reason: any) => void | PromiseLike; +/** @public */ +export declare type UnderlyingSourcePullCallback = (controller: ReadableStreamDefaultController) => void | PromiseLike; +/** @public */ +export declare type UnderlyingSourceStartCallback = (controller: ReadableStreamDefaultController) => void | PromiseLike; +/** + * A writable stream represents a destination for data, into which you can write. + * + * @public + */ +export declare class WritableStream { + constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy); + /* + * Returns whether or not the writable stream is locked to a writer. + */ + readonly locked: boolean; + /** + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort + * mechanism of the underlying sink. + * + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel + * the stream) if the stream is currently locked. + */ + abort(reason?: any): Promise; + /** + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its + * close behavior. During this time any further attempts to write will fail (without erroring the stream). + * + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + */ + close(): Promise; + /** + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream + * is locked, no other writer can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at + * the same time, which would cause the resulting written data to be unpredictable and probably useless. + */ + getWriter(): WritableStreamDefaultWriter; +} +/** + * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. + * + * @public + */ +export declare class WritableStreamDefaultController { + private constructor(); + /* + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. + * + * @deprecated + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. + */ + readonly abortReason: any; + /* + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. + */ + readonly signal: AbortSignal; + /** + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. + * + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the + * normal lifecycle of interactions with the underlying sink. + */ + error(e?: any): void; +} +/** + * A default writer vended by a {@link WritableStream}. + * + * @public + */ +export declare class WritableStreamDefaultWriter { + constructor(stream: WritableStream); + /* + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the writer’s lock is released before the stream finishes closing. + */ + readonly closed: Promise; + /* + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. + * A producer can use this information to determine the right amount of data to write. + * + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when + * the writer’s lock is released. + */ + readonly desiredSize: number | null; + /* + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips + * back to zero or below, the getter will return a new promise that stays pending until the next transition. + * + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become + * rejected. + */ + readonly ready: Promise; + /** + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + */ + abort(reason?: any): Promise; + /** + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + */ + close(): Promise; + /** + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from + * now on; otherwise, the writer will appear closed. + * + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents + * other producers from writing in an interleaved manner. + */ + releaseLock(): void; + /** + * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully, + * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return + * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes + * errored before the writing process is initiated. + * + * Note that what "success" means is up to the underlying sink; it might indicate simply that the chunk has been + * accepted, and not necessarily that it is safely saved to its ultimate destination. + */ + write(chunk: W): Promise; +} +export {}; diff --git a/backend/node_modules/web-streams-polyfill/dist/types/ts3.6/polyfill.d.ts b/backend/node_modules/web-streams-polyfill/dist/types/ts3.6/polyfill.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1e24288d59a33e273cc16a19f58c49058042625b --- /dev/null +++ b/backend/node_modules/web-streams-polyfill/dist/types/ts3.6/polyfill.d.ts @@ -0,0 +1,28 @@ +/// +/// + +import type { ReadableStreamAsyncIterator, ReadableStreamIteratorOptions } from './ponyfill'; + +export * from './ponyfill'; + +declare global { + interface ReadableStream extends AsyncIterable { + /** + * Asynchronously iterates over the chunks in the stream's internal queue. + * + * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader. + * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method + * is called, e.g. by breaking out of the loop. + * + * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also + * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing + * `true` for the `preventCancel` option. + */ + values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator; + + /** + * {@inheritDoc ReadableStream.values} + */ + [Symbol.asyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator; + } +} diff --git a/backend/node_modules/web-streams-polyfill/dist/types/ts3.6/ponyfill.d.ts b/backend/node_modules/web-streams-polyfill/dist/types/ts3.6/ponyfill.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b1fd4aec2ffe6457d020ae3c312e8455269912c3 --- /dev/null +++ b/backend/node_modules/web-streams-polyfill/dist/types/ts3.6/ponyfill.d.ts @@ -0,0 +1,821 @@ +/// + +/** + * A signal object that allows you to communicate with a request and abort it if required + * via its associated `AbortController` object. + * + * @remarks + * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types. + * It is redefined here, so it can be polyfilled without a DOM, for example with + * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment. + * + * @public + */ +export declare interface AbortSignal { + /** + * Whether the request is aborted. + */ + readonly aborted: boolean; + /** + * If aborted, returns the reason for aborting. + */ + readonly reason?: any; + /** + * Add an event listener to be triggered when this signal becomes aborted. + */ + addEventListener(type: 'abort', listener: () => void): void; + /** + * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}. + */ + removeEventListener(type: 'abort', listener: () => void): void; +} + +/** + * A queuing strategy that counts the number of bytes in each chunk. + * + * @public + */ +export declare class ByteLengthQueuingStrategy implements QueuingStrategy { + constructor(options: QueuingStrategyInit); + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark(): number; + /** + * Measures the size of `chunk` by returning the value of its `byteLength` property. + */ + get size(): (chunk: ArrayBufferView) => number; +} + +/** + * A queuing strategy that counts the number of chunks. + * + * @public + */ +export declare class CountQueuingStrategy implements QueuingStrategy { + constructor(options: QueuingStrategyInit); + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark(): number; + /** + * Measures the size of `chunk` by always returning 1. + * This ensures that the total queue size is a count of the number of chunks in the queue. + */ + get size(): (chunk: any) => 1; +} + +/** + * A queuing strategy. + * + * @public + */ +export declare interface QueuingStrategy { + /** + * A non-negative number indicating the high water mark of the stream using this queuing strategy. + */ + highWaterMark?: number; + /** + * A function that computes and returns the finite non-negative size of the given chunk value. + */ + size?: QueuingStrategySizeCallback; +} + +/** + * @public + */ +export declare interface QueuingStrategyInit { + /** + * {@inheritDoc QueuingStrategy.highWaterMark} + */ + highWaterMark: number; +} + +/** + * {@inheritDoc QueuingStrategy.size} + * @public + */ +export declare type QueuingStrategySizeCallback = (chunk: T) => number; + +/** + * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. + * + * @public + */ +export declare class ReadableByteStreamController { + private constructor(); + /** + * Returns the current BYOB pull request, or `null` if there isn't one. + */ + get byobRequest(): ReadableStreamBYOBRequest | null; + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize(): number | null; + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close(): void; + /** + * Enqueues the given chunk chunk in the controlled readable stream. + * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown. + */ + enqueue(chunk: ArrayBufferView): void; + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e?: any): void; +} + +/** + * A readable stream represents a source of data, from which you can read. + * + * @public + */ +export declare class ReadableStream implements AsyncIterable { + constructor(underlyingSource: UnderlyingByteSource, strategy?: { + highWaterMark?: number; + size?: undefined; + }); + constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy); + /** + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. + */ + get locked(): boolean; + /** + * Cancels the stream, signaling a loss of interest in the stream by a consumer. + * + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} + * method, which might or might not use it. + */ + cancel(reason?: any): Promise; + /** + * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader. + * + * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams, + * i.e. streams which were constructed specifically with the ability to handle "bring your own buffer" reading. + * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its + * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise + * control over allocation. + */ + getReader({ mode }: { + mode: 'byob'; + }): ReadableStreamBYOBReader; + /** + * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader. + * While the stream is locked, no other reader can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to consume a stream + * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours + * or cancel the stream, which would interfere with your abstraction. + */ + getReader(): ReadableStreamDefaultReader; + /** + * Provides a convenient, chainable way of piping this readable stream through a transform stream + * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream + * into the writable side of the supplied pair, and returns the readable side for further use. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + */ + pipeThrough(transform: { + readable: RS; + writable: WritableStream; + }, options?: StreamPipeOptions): RS; + /** + * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under + * various error conditions can be customized with a number of passed options. It returns a promise that fulfills + * when the piping process completes successfully, or rejects if any errors were encountered. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + */ + pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise; + /** + * Tees this readable stream, returning a two-element array containing the two resulting branches as + * new {@link ReadableStream} instances. + * + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be + * propagated to the stream's underlying source. + * + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, + * this could allow interference between the two branches. + */ + tee(): [ReadableStream, ReadableStream]; + /** + * Asynchronously iterates over the chunks in the stream's internal queue. + * + * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader. + * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method + * is called, e.g. by breaking out of the loop. + * + * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also + * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing + * `true` for the `preventCancel` option. + */ + values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator; + /** + * {@inheritDoc ReadableStream.values} + */ + [Symbol.asyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator; + /** + * Creates a new ReadableStream wrapping the provided iterable or async iterable. + * + * This can be used to adapt various kinds of objects into a readable stream, + * such as an array, an async generator, or a Node.js readable stream. + */ + static from(asyncIterable: Iterable | AsyncIterable | ReadableStreamLike): ReadableStream; +} + +/** + * An async iterator returned by {@link ReadableStream.values}. + * + * @public + */ +export declare interface ReadableStreamAsyncIterator extends AsyncIterableIterator { + next(): Promise>; + return(value?: any): Promise>; +} + +/** + * A BYOB reader vended by a {@link ReadableStream}. + * + * @public + */ +export declare class ReadableStreamBYOBReader { + constructor(stream: ReadableStream); + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the reader's lock is released before the stream finishes closing. + */ + get closed(): Promise; + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason?: any): Promise; + /** + * Attempts to reads bytes into view, and returns a promise resolved with the result. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read(view: T, options?: ReadableStreamBYOBReaderReadOptions): Promise>; + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock(): void; +} + +/** + * Options for {@link ReadableStreamBYOBReader.read | reading} a stream + * with a {@link ReadableStreamBYOBReader | BYOB reader}. + * + * @public + */ +export declare interface ReadableStreamBYOBReaderReadOptions { + min?: number; +} + +/** + * A result returned by {@link ReadableStreamBYOBReader.read}. + * + * @public + */ +export declare type ReadableStreamBYOBReadResult = { + done: false; + value: T; +} | { + done: true; + value: T | undefined; +}; + +/** + * A pull-into request in a {@link ReadableByteStreamController}. + * + * @public + */ +export declare class ReadableStreamBYOBRequest { + private constructor(); + /** + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. + */ + get view(): ArrayBufferView | null; + /** + * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into + * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer. + * + * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer + * modifiable. + */ + respond(bytesWritten: number): void; + /** + * Indicates to the associated readable byte stream that instead of writing into + * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`, + * which will be given to the consumer of the readable byte stream. + * + * After this method is called, `view` will be transferred and no longer modifiable. + */ + respondWithNewView(view: ArrayBufferView): void; +} + +/** + * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. + * + * @public + */ +export declare class ReadableStreamDefaultController { + private constructor(); + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize(): number | null; + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close(): void; + /** + * Enqueues the given chunk `chunk` in the controlled readable stream. + */ + enqueue(chunk: R): void; + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e?: any): void; +} + +/** + * A default reader vended by a {@link ReadableStream}. + * + * @public + */ +export declare class ReadableStreamDefaultReader { + constructor(stream: ReadableStream); + /** + * Returns a promise that will be fulfilled when the stream becomes closed, + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + */ + get closed(): Promise; + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason?: any): Promise; + /** + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read(): Promise>; + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock(): void; +} + +/** + * A common interface for a `ReadableStreamDefaultReader` implementation. + * + * @public + */ +export declare interface ReadableStreamDefaultReaderLike { + readonly closed: Promise; + cancel(reason?: any): Promise; + read(): Promise>; + releaseLock(): void; +} + +/** + * A result returned by {@link ReadableStreamDefaultReader.read}. + * + * @public + */ +export declare type ReadableStreamDefaultReadResult = { + done: false; + value: T; +} | { + done: true; + value?: undefined; +}; + +/** + * Options for {@link ReadableStream.values | async iterating} a stream. + * + * @public + */ +export declare interface ReadableStreamIteratorOptions { + preventCancel?: boolean; +} + +/** + * A common interface for a `ReadadableStream` implementation. + * + * @public + */ +export declare interface ReadableStreamLike { + readonly locked: boolean; + getReader(): ReadableStreamDefaultReaderLike; +} + +/** + * A pair of a {@link ReadableStream | readable stream} and {@link WritableStream | writable stream} that can be passed + * to {@link ReadableStream.pipeThrough}. + * + * @public + */ +export declare interface ReadableWritablePair { + readable: ReadableStream; + writable: WritableStream; +} + +/** + * Options for {@link ReadableStream.pipeTo | piping} a stream. + * + * @public + */ +export declare interface StreamPipeOptions { + /** + * If set to true, {@link ReadableStream.pipeTo} will not abort the writable stream if the readable stream errors. + */ + preventAbort?: boolean; + /** + * If set to true, {@link ReadableStream.pipeTo} will not cancel the readable stream if the writable stream closes + * or errors. + */ + preventCancel?: boolean; + /** + * If set to true, {@link ReadableStream.pipeTo} will not close the writable stream if the readable stream closes. + */ + preventClose?: boolean; + /** + * Can be set to an {@link AbortSignal} to allow aborting an ongoing pipe operation via the corresponding + * `AbortController`. In this case, the source readable stream will be canceled, and the destination writable stream + * aborted, unless the respective options `preventCancel` or `preventAbort` are set. + */ + signal?: AbortSignal; +} + +/** + * A transformer for constructing a {@link TransformStream}. + * + * @public + */ +export declare interface Transformer { + /** + * A function that is called immediately during creation of the {@link TransformStream}. + */ + start?: TransformerStartCallback; + /** + * A function called when a new chunk originally written to the writable side is ready to be transformed. + */ + transform?: TransformerTransformCallback; + /** + * A function called after all chunks written to the writable side have been transformed by successfully passing + * through {@link Transformer.transform | transform()}, and the writable side is about to be closed. + */ + flush?: TransformerFlushCallback; + /** + * A function called when the readable side is cancelled, or when the writable side is aborted. + */ + cancel?: TransformerCancelCallback; + readableType?: undefined; + writableType?: undefined; +} + +/** @public */ +export declare type TransformerCancelCallback = (reason: any) => void | PromiseLike; + +/** @public */ +export declare type TransformerFlushCallback = (controller: TransformStreamDefaultController) => void | PromiseLike; + +/** @public */ +export declare type TransformerStartCallback = (controller: TransformStreamDefaultController) => void | PromiseLike; + +/** @public */ +export declare type TransformerTransformCallback = (chunk: I, controller: TransformStreamDefaultController) => void | PromiseLike; + +/** + * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, + * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. + * In a manner specific to the transform stream in question, writes to the writable side result in new data being + * made available for reading from the readable side. + * + * @public + */ +export declare class TransformStream { + constructor(transformer?: Transformer, writableStrategy?: QueuingStrategy, readableStrategy?: QueuingStrategy); + /** + * The readable side of the transform stream. + */ + get readable(): ReadableStream; + /** + * The writable side of the transform stream. + */ + get writable(): WritableStream; +} + +/** + * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. + * + * @public + */ +export declare class TransformStreamDefaultController { + private constructor(); + /** + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. + */ + get desiredSize(): number | null; + /** + * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream. + */ + enqueue(chunk: O): void; + /** + * Errors both the readable side and the writable side of the controlled transform stream, making all future + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. + */ + error(reason?: any): void; + /** + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the + * transformer only needs to consume a portion of the chunks written to the writable side. + */ + terminate(): void; +} + +/** + * An underlying byte source for constructing a {@link ReadableStream}. + * + * @public + */ +export declare interface UnderlyingByteSource { + /** + * {@inheritDoc UnderlyingSource.start} + */ + start?: UnderlyingByteSourceStartCallback; + /** + * {@inheritDoc UnderlyingSource.pull} + */ + pull?: UnderlyingByteSourcePullCallback; + /** + * {@inheritDoc UnderlyingSource.cancel} + */ + cancel?: UnderlyingSourceCancelCallback; + /** + * Can be set to "bytes" to signal that the constructed {@link ReadableStream} is a readable byte stream. + * This ensures that the resulting {@link ReadableStream} will successfully be able to vend BYOB readers via its + * {@link ReadableStream.(getReader:1) | getReader()} method. + * It also affects the controller argument passed to the {@link UnderlyingByteSource.start | start()} + * and {@link UnderlyingByteSource.pull | pull()} methods. + */ + type: 'bytes'; + /** + * Can be set to a positive integer to cause the implementation to automatically allocate buffers for the + * underlying source code to write into. In this case, when a consumer is using a default reader, the stream + * implementation will automatically allocate an ArrayBuffer of the given size, so that + * {@link ReadableByteStreamController.byobRequest | controller.byobRequest} is always present, + * as if the consumer was using a BYOB reader. + */ + autoAllocateChunkSize?: number; +} + +/** @public */ +export declare type UnderlyingByteSourcePullCallback = (controller: ReadableByteStreamController) => void | PromiseLike; + +/** @public */ +export declare type UnderlyingByteSourceStartCallback = (controller: ReadableByteStreamController) => void | PromiseLike; + +/** + * An underlying sink for constructing a {@link WritableStream}. + * + * @public + */ +export declare interface UnderlyingSink { + /** + * A function that is called immediately during creation of the {@link WritableStream}. + */ + start?: UnderlyingSinkStartCallback; + /** + * A function that is called when a new chunk of data is ready to be written to the underlying sink. The stream + * implementation guarantees that this function will be called only after previous writes have succeeded, and never + * before {@link UnderlyingSink.start | start()} has succeeded or after {@link UnderlyingSink.close | close()} or + * {@link UnderlyingSink.abort | abort()} have been called. + * + * This function is used to actually send the data to the resource presented by the underlying sink, for example by + * calling a lower-level API. + */ + write?: UnderlyingSinkWriteCallback; + /** + * A function that is called after the producer signals, via + * {@link WritableStreamDefaultWriter.close | writer.close()}, that they are done writing chunks to the stream, and + * subsequently all queued-up writes have successfully completed. + * + * This function can perform any actions necessary to finalize or flush writes to the underlying sink, and release + * access to any held resources. + */ + close?: UnderlyingSinkCloseCallback; + /** + * A function that is called after the producer signals, via {@link WritableStream.abort | stream.abort()} or + * {@link WritableStreamDefaultWriter.abort | writer.abort()}, that they wish to abort the stream. It takes as its + * argument the same value as was passed to those methods by the producer. + * + * Writable streams can additionally be aborted under certain conditions during piping; see the definition of the + * {@link ReadableStream.pipeTo | pipeTo()} method for more details. + * + * This function can clean up any held resources, much like {@link UnderlyingSink.close | close()}, but perhaps with + * some custom handling. + */ + abort?: UnderlyingSinkAbortCallback; + type?: undefined; +} + +/** @public */ +export declare type UnderlyingSinkAbortCallback = (reason: any) => void | PromiseLike; + +/** @public */ +export declare type UnderlyingSinkCloseCallback = () => void | PromiseLike; + +/** @public */ +export declare type UnderlyingSinkStartCallback = (controller: WritableStreamDefaultController) => void | PromiseLike; + +/** @public */ +export declare type UnderlyingSinkWriteCallback = (chunk: W, controller: WritableStreamDefaultController) => void | PromiseLike; + +/** + * An underlying source for constructing a {@link ReadableStream}. + * + * @public + */ +export declare interface UnderlyingSource { + /** + * A function that is called immediately during creation of the {@link ReadableStream}. + */ + start?: UnderlyingSourceStartCallback; + /** + * A function that is called whenever the stream’s internal queue of chunks becomes not full, + * i.e. whenever the queue’s desired size becomes positive. Generally, it will be called repeatedly + * until the queue reaches its high water mark (i.e. until the desired size becomes non-positive). + */ + pull?: UnderlyingSourcePullCallback; + /** + * A function that is called whenever the consumer cancels the stream, via + * {@link ReadableStream.cancel | stream.cancel()}, + * {@link ReadableStreamDefaultReader.cancel | defaultReader.cancel()}, or + * {@link ReadableStreamBYOBReader.cancel | byobReader.cancel()}. + * It takes as its argument the same value as was passed to those methods by the consumer. + */ + cancel?: UnderlyingSourceCancelCallback; + type?: undefined; +} + +/** @public */ +export declare type UnderlyingSourceCancelCallback = (reason: any) => void | PromiseLike; + +/** @public */ +export declare type UnderlyingSourcePullCallback = (controller: ReadableStreamDefaultController) => void | PromiseLike; + +/** @public */ +export declare type UnderlyingSourceStartCallback = (controller: ReadableStreamDefaultController) => void | PromiseLike; + +/** + * A writable stream represents a destination for data, into which you can write. + * + * @public + */ +export declare class WritableStream { + constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy); + /** + * Returns whether or not the writable stream is locked to a writer. + */ + get locked(): boolean; + /** + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort + * mechanism of the underlying sink. + * + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel + * the stream) if the stream is currently locked. + */ + abort(reason?: any): Promise; + /** + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its + * close behavior. During this time any further attempts to write will fail (without erroring the stream). + * + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + */ + close(): Promise; + /** + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream + * is locked, no other writer can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at + * the same time, which would cause the resulting written data to be unpredictable and probably useless. + */ + getWriter(): WritableStreamDefaultWriter; +} + +/** + * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. + * + * @public + */ +export declare class WritableStreamDefaultController { + private constructor(); + /** + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. + * + * @deprecated + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. + */ + get abortReason(): any; + /** + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. + */ + get signal(): AbortSignal; + /** + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. + * + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the + * normal lifecycle of interactions with the underlying sink. + */ + error(e?: any): void; +} + +/** + * A default writer vended by a {@link WritableStream}. + * + * @public + */ +export declare class WritableStreamDefaultWriter { + constructor(stream: WritableStream); + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the writer’s lock is released before the stream finishes closing. + */ + get closed(): Promise; + /** + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. + * A producer can use this information to determine the right amount of data to write. + * + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when + * the writer’s lock is released. + */ + get desiredSize(): number | null; + /** + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips + * back to zero or below, the getter will return a new promise that stays pending until the next transition. + * + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become + * rejected. + */ + get ready(): Promise; + /** + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + */ + abort(reason?: any): Promise; + /** + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + */ + close(): Promise; + /** + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from + * now on; otherwise, the writer will appear closed. + * + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents + * other producers from writing in an interleaved manner. + */ + releaseLock(): void; + /** + * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully, + * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return + * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes + * errored before the writing process is initiated. + * + * Note that what "success" means is up to the underlying sink; it might indicate simply that the chunk has been + * accepted, and not necessarily that it is safely saved to its ultimate destination. + */ + write(chunk: W): Promise; +} + +export { } diff --git a/backend/node_modules/web-streams-polyfill/dist/types/tsdoc-metadata.json b/backend/node_modules/web-streams-polyfill/dist/types/tsdoc-metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..b18fd2ae0cef00a1786b4920e988f70b86d2c029 --- /dev/null +++ b/backend/node_modules/web-streams-polyfill/dist/types/tsdoc-metadata.json @@ -0,0 +1,11 @@ +// This file is read by tools that parse documentation comments conforming to the TSDoc standard. +// It should be published with your NPM package. It should not be tracked by Git. +{ + "tsdocVersion": "0.12", + "toolPackages": [ + { + "packageName": "@microsoft/api-extractor", + "packageVersion": "7.39.1" + } + ] +} diff --git a/backend/node_modules/web-streams-polyfill/es2018/package.json b/backend/node_modules/web-streams-polyfill/es2018/package.json new file mode 100644 index 0000000000000000000000000000000000000000..97f8fb1b5ffb31c253cbeb8f76a0e19c2ab74643 --- /dev/null +++ b/backend/node_modules/web-streams-polyfill/es2018/package.json @@ -0,0 +1,14 @@ +{ + "name": "web-streams-polyfill-es2018", + "main": "../dist/polyfill.es2018", + "browser": "../dist/polyfill.es2018.min.js", + "module": "../dist/polyfill.es2018.mjs", + "types": "../dist/types/polyfill.d.ts", + "typesVersions": { + ">=3.6": { + "../dist/types/*": [ + "../dist/types/ts3.6/*" + ] + } + } +} diff --git a/backend/node_modules/web-streams-polyfill/es6/package.json b/backend/node_modules/web-streams-polyfill/es6/package.json new file mode 100644 index 0000000000000000000000000000000000000000..ca3909bc1e3fb3b343677997760a320f1a238996 --- /dev/null +++ b/backend/node_modules/web-streams-polyfill/es6/package.json @@ -0,0 +1,14 @@ +{ + "name": "web-streams-polyfill-es6", + "main": "../dist/polyfill.es6", + "browser": "../dist/polyfill.es6.min.js", + "module": "../dist/polyfill.es6.mjs", + "types": "../dist/types/polyfill.d.ts", + "typesVersions": { + ">=3.6": { + "../dist/types/*": [ + "../dist/types/ts3.6/*" + ] + } + } +} diff --git a/backend/node_modules/web-streams-polyfill/package.json b/backend/node_modules/web-streams-polyfill/package.json new file mode 100644 index 0000000000000000000000000000000000000000..fa7d164837be83b0fa58e036d448fa004c7ccfc6 --- /dev/null +++ b/backend/node_modules/web-streams-polyfill/package.json @@ -0,0 +1,83 @@ +{ + "name": "web-streams-polyfill", + "version": "3.3.3", + "description": "Web Streams, based on the WHATWG spec reference implementation", + "main": "dist/polyfill", + "browser": "dist/polyfill.min.js", + "module": "dist/polyfill.mjs", + "types": "dist/types/polyfill.d.ts", + "typesVersions": { + ">=3.6": { + "dist/types/*": [ + "dist/types/ts3.6/*" + ] + } + }, + "scripts": { + "test": "npm run test:types && npm run test:unit && npm run test:wpt", + "test:wpt": "npm run test:wpt:node && npm run test:wpt:chromium && npm run test:wpt:firefox", + "test:wpt:node": "node --expose_gc ./test/wpt/node/run.js", + "test:wpt:chromium": "node ./test/wpt/browser/run.js --browser chromium", + "test:wpt:firefox": "node ./test/wpt/browser/run.js --browser firefox", + "test:types": "tsc -p ./test/types/tsconfig.json", + "test:unit": "jasmine --config=test/unit/jasmine.json", + "lint": "eslint \"src/**/*.ts\"", + "build": "npm run build:bundle && npm run build:types", + "build:bundle": "rollup -c", + "build:types": "tsc --project . --emitDeclarationOnly --declarationDir ./lib && api-extractor run", + "accept:types": "npm run build:types -- --local", + "postbuild:types": "downlevel-dts ./dist/types/ts3.6/ ./dist/types/ --to=3.5 && node ./build/downlevel-dts.js", + "prepare": "npm run build" + }, + "files": [ + "dist", + "es6", + "es2018", + "ponyfill" + ], + "engines": { + "node": ">= 8" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/MattiasBuelens/web-streams-polyfill.git" + }, + "keywords": [ + "streams", + "whatwg", + "polyfill" + ], + "author": "Mattias Buelens ", + "contributors": [ + "Diwank Singh " + ], + "license": "MIT", + "bugs": { + "url": "https://github.com/MattiasBuelens/web-streams-polyfill/issues" + }, + "homepage": "https://github.com/MattiasBuelens/web-streams-polyfill#readme", + "devDependencies": { + "@microsoft/api-extractor": "^7.39.1", + "@rollup/plugin-inject": "^5.0.5", + "@rollup/plugin-replace": "^5.0.5", + "@rollup/plugin-strip": "^3.0.4", + "@rollup/plugin-terser": "^0.4.4", + "@rollup/plugin-typescript": "^11.1.5", + "@types/node": "^18.19.4", + "@typescript-eslint/eslint-plugin": "^6.17.0", + "@typescript-eslint/parser": "^6.17.0", + "@ungap/promise-all-settled": "^1.1.2", + "downlevel-dts": "^0.11.0", + "eslint": "^8.56.0", + "jasmine": "^5.1.0", + "micromatch": "^4.0.5", + "minimist": "^1.2.5", + "playwright": "^1.14.1", + "recursive-readdir": "^2.2.2", + "rollup": "^4.9.2", + "ts-morph": "^10.0.2", + "tslib": "^2.6.2", + "typescript": "^5.3.3", + "wpt-runner": "^5.0.0" + } +} diff --git a/backend/node_modules/web-streams-polyfill/ponyfill/es2018/package.json b/backend/node_modules/web-streams-polyfill/ponyfill/es2018/package.json new file mode 100644 index 0000000000000000000000000000000000000000..26816ac9b17377aa70259129b1ee87e119678533 --- /dev/null +++ b/backend/node_modules/web-streams-polyfill/ponyfill/es2018/package.json @@ -0,0 +1,13 @@ +{ + "name": "web-streams-ponyfill-es2018", + "main": "../../dist/ponyfill.es2018", + "module": "../../dist/ponyfill.es2018.mjs", + "types": "../../dist/types/ponyfill.d.ts", + "typesVersions": { + ">=3.6": { + "../../dist/types/*": [ + "../../dist/types/ts3.6/*" + ] + } + } +} diff --git a/backend/node_modules/web-streams-polyfill/ponyfill/es6/package.json b/backend/node_modules/web-streams-polyfill/ponyfill/es6/package.json new file mode 100644 index 0000000000000000000000000000000000000000..b54520daa9d73cd42a33f7d9d5e54b4e2def4e7d --- /dev/null +++ b/backend/node_modules/web-streams-polyfill/ponyfill/es6/package.json @@ -0,0 +1,13 @@ +{ + "name": "web-streams-ponyfill-es6", + "main": "../../dist/ponyfill.es6", + "module": "../../dist/ponyfill.es6.mjs", + "types": "../../dist/types/ponyfill.d.ts", + "typesVersions": { + ">=3.6": { + "../../dist/types/*": [ + "../../dist/types/ts3.6/*" + ] + } + } +} diff --git a/backend/node_modules/web-streams-polyfill/ponyfill/package.json b/backend/node_modules/web-streams-polyfill/ponyfill/package.json new file mode 100644 index 0000000000000000000000000000000000000000..36e9fbe43da0119195e6351b6f1a158628965ce4 --- /dev/null +++ b/backend/node_modules/web-streams-polyfill/ponyfill/package.json @@ -0,0 +1,13 @@ +{ + "name": "web-streams-ponyfill", + "main": "../dist/ponyfill", + "module": "../dist/ponyfill.mjs", + "types": "../dist/types/ponyfill.d.ts", + "typesVersions": { + ">=3.6": { + "../dist/types/*": [ + "../dist/types/ts3.6/*" + ] + } + } +} diff --git a/backend/node_modules/webidl-conversions/LICENSE.md b/backend/node_modules/webidl-conversions/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..d4a994f50bfa1ecc19489f03822a6e728d3e2a49 --- /dev/null +++ b/backend/node_modules/webidl-conversions/LICENSE.md @@ -0,0 +1,12 @@ +# The BSD 2-Clause License + +Copyright (c) 2014, Domenic Denicola +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/backend/node_modules/webidl-conversions/README.md b/backend/node_modules/webidl-conversions/README.md new file mode 100644 index 0000000000000000000000000000000000000000..3657890a186b14bf37ed8817d28a9a6a20bd397f --- /dev/null +++ b/backend/node_modules/webidl-conversions/README.md @@ -0,0 +1,53 @@ +# WebIDL Type Conversions on JavaScript Values + +This package implements, in JavaScript, the algorithms to convert a given JavaScript value according to a given [WebIDL](http://heycam.github.io/webidl/) [type](http://heycam.github.io/webidl/#idl-types). + +The goal is that you should be able to write code like + +```js +const conversions = require("webidl-conversions"); + +function doStuff(x, y) { + x = conversions["boolean"](x); + y = conversions["unsigned long"](y); + // actual algorithm code here +} +``` + +and your function `doStuff` will behave the same as a WebIDL operation declared as + +```webidl +void doStuff(boolean x, unsigned long y); +``` + +## API + +This package's main module's default export is an object with a variety of methods, each corresponding to a different WebIDL type. Each method, when invoked on a JavaScript value, will give back the new JavaScript value that results after passing through the WebIDL conversion rules. (See below for more details on what that means.) Alternately, the method could throw an error, if the WebIDL algorithm is specified to do so: for example `conversions["float"](NaN)` [will throw a `TypeError`](http://heycam.github.io/webidl/#es-float). + +## Status + +All of the numeric types are implemented (float being implemented as double) and some others are as well - check the source for all of them. This list will grow over time in service of the [HTML as Custom Elements](https://github.com/dglazkov/html-as-custom-elements) project, but in the meantime, pull requests welcome! + +I'm not sure yet what the strategy will be for modifiers, e.g. [`[Clamp]`](http://heycam.github.io/webidl/#Clamp). Maybe something like `conversions["unsigned long"](x, { clamp: true })`? We'll see. + +We might also want to extend the API to give better error messages, e.g. "Argument 1 of HTMLMediaElement.fastSeek is not a finite floating-point value" instead of "Argument is not a finite floating-point value." This would require passing in more information to the conversion functions than we currently do. + +## Background + +What's actually going on here, conceptually, is pretty weird. Let's try to explain. + +WebIDL, as part of its madness-inducing design, has its own type system. When people write algorithms in web platform specs, they usually operate on WebIDL values, i.e. instances of WebIDL types. For example, if they were specifying the algorithm for our `doStuff` operation above, they would treat `x` as a WebIDL value of [WebIDL type `boolean`](http://heycam.github.io/webidl/#idl-boolean). Crucially, they would _not_ treat `x` as a JavaScript variable whose value is either the JavaScript `true` or `false`. They're instead working in a different type system altogether, with its own rules. + +Separately from its type system, WebIDL defines a ["binding"](http://heycam.github.io/webidl/#ecmascript-binding) of the type system into JavaScript. This contains rules like: when you pass a JavaScript value to the JavaScript method that manifests a given WebIDL operation, how does that get converted into a WebIDL value? For example, a JavaScript `true` passed in the position of a WebIDL `boolean` argument becomes a WebIDL `true`. But, a JavaScript `true` passed in the position of a [WebIDL `unsigned long`](http://heycam.github.io/webidl/#idl-unsigned-long) becomes a WebIDL `1`. And so on. + +Finally, we have the actual implementation code. This is usually C++, although these days [some smart people are using Rust](https://github.com/servo/servo). The implementation, of course, has its own type system. So when they implement the WebIDL algorithms, they don't actually use WebIDL values, since those aren't "real" outside of specs. Instead, implementations apply the WebIDL binding rules in such a way as to convert incoming JavaScript values into C++ values. For example, if code in the browser called `doStuff(true, true)`, then the implementation code would eventually receive a C++ `bool` containing `true` and a C++ `uint32_t` containing `1`. + +The upside of all this is that implementations can abstract all the conversion logic away, letting WebIDL handle it, and focus on implementing the relevant methods in C++ with values of the correct type already provided. That is payoff of WebIDL, in a nutshell. + +And getting to that payoff is the goal of _this_ project—but for JavaScript implementations, instead of C++ ones. That is, this library is designed to make it easier for JavaScript developers to write functions that behave like a given WebIDL operation. So conceptually, the conversion pipeline, which in its general form is JavaScript values ↦ WebIDL values ↦ implementation-language values, in this case becomes JavaScript values ↦ WebIDL values ↦ JavaScript values. And that intermediate step is where all the logic is performed: a JavaScript `true` becomes a WebIDL `1` in an unsigned long context, which then becomes a JavaScript `1`. + +## Don't Use This + +Seriously, why would you ever use this? You really shouldn't. WebIDL is … not great, and you shouldn't be emulating its semantics. If you're looking for a generic argument-processing library, you should find one with better rules than those from WebIDL. In general, your JavaScript should not be trying to become more like WebIDL; if anything, we should fix WebIDL to make it more like JavaScript. + +The _only_ people who should use this are those trying to create faithful implementations (or polyfills) of web platform interfaces defined in WebIDL. diff --git a/backend/node_modules/webidl-conversions/lib/index.js b/backend/node_modules/webidl-conversions/lib/index.js new file mode 100644 index 0000000000000000000000000000000000000000..c5153a3abeb0a50b7f97ffb7123fec4b6130f1fc --- /dev/null +++ b/backend/node_modules/webidl-conversions/lib/index.js @@ -0,0 +1,189 @@ +"use strict"; + +var conversions = {}; +module.exports = conversions; + +function sign(x) { + return x < 0 ? -1 : 1; +} + +function evenRound(x) { + // Round x to the nearest integer, choosing the even integer if it lies halfway between two. + if ((x % 1) === 0.5 && (x & 1) === 0) { // [even number].5; round down (i.e. floor) + return Math.floor(x); + } else { + return Math.round(x); + } +} + +function createNumberConversion(bitLength, typeOpts) { + if (!typeOpts.unsigned) { + --bitLength; + } + const lowerBound = typeOpts.unsigned ? 0 : -Math.pow(2, bitLength); + const upperBound = Math.pow(2, bitLength) - 1; + + const moduloVal = typeOpts.moduloBitLength ? Math.pow(2, typeOpts.moduloBitLength) : Math.pow(2, bitLength); + const moduloBound = typeOpts.moduloBitLength ? Math.pow(2, typeOpts.moduloBitLength - 1) : Math.pow(2, bitLength - 1); + + return function(V, opts) { + if (!opts) opts = {}; + + let x = +V; + + if (opts.enforceRange) { + if (!Number.isFinite(x)) { + throw new TypeError("Argument is not a finite number"); + } + + x = sign(x) * Math.floor(Math.abs(x)); + if (x < lowerBound || x > upperBound) { + throw new TypeError("Argument is not in byte range"); + } + + return x; + } + + if (!isNaN(x) && opts.clamp) { + x = evenRound(x); + + if (x < lowerBound) x = lowerBound; + if (x > upperBound) x = upperBound; + return x; + } + + if (!Number.isFinite(x) || x === 0) { + return 0; + } + + x = sign(x) * Math.floor(Math.abs(x)); + x = x % moduloVal; + + if (!typeOpts.unsigned && x >= moduloBound) { + return x - moduloVal; + } else if (typeOpts.unsigned) { + if (x < 0) { + x += moduloVal; + } else if (x === -0) { // don't return negative zero + return 0; + } + } + + return x; + } +} + +conversions["void"] = function () { + return undefined; +}; + +conversions["boolean"] = function (val) { + return !!val; +}; + +conversions["byte"] = createNumberConversion(8, { unsigned: false }); +conversions["octet"] = createNumberConversion(8, { unsigned: true }); + +conversions["short"] = createNumberConversion(16, { unsigned: false }); +conversions["unsigned short"] = createNumberConversion(16, { unsigned: true }); + +conversions["long"] = createNumberConversion(32, { unsigned: false }); +conversions["unsigned long"] = createNumberConversion(32, { unsigned: true }); + +conversions["long long"] = createNumberConversion(32, { unsigned: false, moduloBitLength: 64 }); +conversions["unsigned long long"] = createNumberConversion(32, { unsigned: true, moduloBitLength: 64 }); + +conversions["double"] = function (V) { + const x = +V; + + if (!Number.isFinite(x)) { + throw new TypeError("Argument is not a finite floating-point value"); + } + + return x; +}; + +conversions["unrestricted double"] = function (V) { + const x = +V; + + if (isNaN(x)) { + throw new TypeError("Argument is NaN"); + } + + return x; +}; + +// not quite valid, but good enough for JS +conversions["float"] = conversions["double"]; +conversions["unrestricted float"] = conversions["unrestricted double"]; + +conversions["DOMString"] = function (V, opts) { + if (!opts) opts = {}; + + if (opts.treatNullAsEmptyString && V === null) { + return ""; + } + + return String(V); +}; + +conversions["ByteString"] = function (V, opts) { + const x = String(V); + let c = undefined; + for (let i = 0; (c = x.codePointAt(i)) !== undefined; ++i) { + if (c > 255) { + throw new TypeError("Argument is not a valid bytestring"); + } + } + + return x; +}; + +conversions["USVString"] = function (V) { + const S = String(V); + const n = S.length; + const U = []; + for (let i = 0; i < n; ++i) { + const c = S.charCodeAt(i); + if (c < 0xD800 || c > 0xDFFF) { + U.push(String.fromCodePoint(c)); + } else if (0xDC00 <= c && c <= 0xDFFF) { + U.push(String.fromCodePoint(0xFFFD)); + } else { + if (i === n - 1) { + U.push(String.fromCodePoint(0xFFFD)); + } else { + const d = S.charCodeAt(i + 1); + if (0xDC00 <= d && d <= 0xDFFF) { + const a = c & 0x3FF; + const b = d & 0x3FF; + U.push(String.fromCodePoint((2 << 15) + (2 << 9) * a + b)); + ++i; + } else { + U.push(String.fromCodePoint(0xFFFD)); + } + } + } + } + + return U.join(''); +}; + +conversions["Date"] = function (V, opts) { + if (!(V instanceof Date)) { + throw new TypeError("Argument is not a Date object"); + } + if (isNaN(V)) { + return undefined; + } + + return V; +}; + +conversions["RegExp"] = function (V, opts) { + if (!(V instanceof RegExp)) { + V = new RegExp(V); + } + + return V; +}; diff --git a/backend/node_modules/webidl-conversions/package.json b/backend/node_modules/webidl-conversions/package.json new file mode 100644 index 0000000000000000000000000000000000000000..c31bc074cd7403d170cffe490acb6a0436d3cf94 --- /dev/null +++ b/backend/node_modules/webidl-conversions/package.json @@ -0,0 +1,23 @@ +{ + "name": "webidl-conversions", + "version": "3.0.1", + "description": "Implements the WebIDL algorithms for converting to and from JavaScript values", + "main": "lib/index.js", + "scripts": { + "test": "mocha test/*.js" + }, + "repository": "jsdom/webidl-conversions", + "keywords": [ + "webidl", + "web", + "types" + ], + "files": [ + "lib/" + ], + "author": "Domenic Denicola (https://domenic.me/)", + "license": "BSD-2-Clause", + "devDependencies": { + "mocha": "^1.21.4" + } +} diff --git a/backend/node_modules/whatwg-url/LICENSE.txt b/backend/node_modules/whatwg-url/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..54dfac39d9f523b2c14548f4574076f587c767e2 --- /dev/null +++ b/backend/node_modules/whatwg-url/LICENSE.txt @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015–2016 Sebastian Mayr + +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/backend/node_modules/whatwg-url/README.md b/backend/node_modules/whatwg-url/README.md new file mode 100644 index 0000000000000000000000000000000000000000..4347a7fc5414b183a302f73aabe9b6a70d263e29 --- /dev/null +++ b/backend/node_modules/whatwg-url/README.md @@ -0,0 +1,67 @@ +# whatwg-url + +whatwg-url is a full implementation of the WHATWG [URL Standard](https://url.spec.whatwg.org/). It can be used standalone, but it also exposes a lot of the internal algorithms that are useful for integrating a URL parser into a project like [jsdom](https://github.com/tmpvar/jsdom). + +## Current Status + +whatwg-url is currently up to date with the URL spec up to commit [a62223](https://github.com/whatwg/url/commit/a622235308342c9adc7fc2fd1659ff059f7d5e2a). + +## API + +### The `URL` Constructor + +The main API is the [`URL`](https://url.spec.whatwg.org/#url) export, which follows the spec's behavior in all ways (including e.g. `USVString` conversion). Most consumers of this library will want to use this. + +### Low-level URL Standard API + +The following methods are exported for use by places like jsdom that need to implement things like [`HTMLHyperlinkElementUtils`](https://html.spec.whatwg.org/#htmlhyperlinkelementutils). They operate on or return an "internal URL" or ["URL record"](https://url.spec.whatwg.org/#concept-url) type. + +- [URL parser](https://url.spec.whatwg.org/#concept-url-parser): `parseURL(input, { baseURL, encodingOverride })` +- [Basic URL parser](https://url.spec.whatwg.org/#concept-basic-url-parser): `basicURLParse(input, { baseURL, encodingOverride, url, stateOverride })` +- [URL serializer](https://url.spec.whatwg.org/#concept-url-serializer): `serializeURL(urlRecord, excludeFragment)` +- [Host serializer](https://url.spec.whatwg.org/#concept-host-serializer): `serializeHost(hostFromURLRecord)` +- [Serialize an integer](https://url.spec.whatwg.org/#serialize-an-integer): `serializeInteger(number)` +- [Origin](https://url.spec.whatwg.org/#concept-url-origin) [serializer](https://html.spec.whatwg.org/multipage/browsers.html#serialization-of-an-origin): `serializeURLOrigin(urlRecord)` +- [Set the username](https://url.spec.whatwg.org/#set-the-username): `setTheUsername(urlRecord, usernameString)` +- [Set the password](https://url.spec.whatwg.org/#set-the-password): `setThePassword(urlRecord, passwordString)` +- [Cannot have a username/password/port](https://url.spec.whatwg.org/#cannot-have-a-username-password-port): `cannotHaveAUsernamePasswordPort(urlRecord)` + +The `stateOverride` parameter is one of the following strings: + +- [`"scheme start"`](https://url.spec.whatwg.org/#scheme-start-state) +- [`"scheme"`](https://url.spec.whatwg.org/#scheme-state) +- [`"no scheme"`](https://url.spec.whatwg.org/#no-scheme-state) +- [`"special relative or authority"`](https://url.spec.whatwg.org/#special-relative-or-authority-state) +- [`"path or authority"`](https://url.spec.whatwg.org/#path-or-authority-state) +- [`"relative"`](https://url.spec.whatwg.org/#relative-state) +- [`"relative slash"`](https://url.spec.whatwg.org/#relative-slash-state) +- [`"special authority slashes"`](https://url.spec.whatwg.org/#special-authority-slashes-state) +- [`"special authority ignore slashes"`](https://url.spec.whatwg.org/#special-authority-ignore-slashes-state) +- [`"authority"`](https://url.spec.whatwg.org/#authority-state) +- [`"host"`](https://url.spec.whatwg.org/#host-state) +- [`"hostname"`](https://url.spec.whatwg.org/#hostname-state) +- [`"port"`](https://url.spec.whatwg.org/#port-state) +- [`"file"`](https://url.spec.whatwg.org/#file-state) +- [`"file slash"`](https://url.spec.whatwg.org/#file-slash-state) +- [`"file host"`](https://url.spec.whatwg.org/#file-host-state) +- [`"path start"`](https://url.spec.whatwg.org/#path-start-state) +- [`"path"`](https://url.spec.whatwg.org/#path-state) +- [`"cannot-be-a-base-URL path"`](https://url.spec.whatwg.org/#cannot-be-a-base-url-path-state) +- [`"query"`](https://url.spec.whatwg.org/#query-state) +- [`"fragment"`](https://url.spec.whatwg.org/#fragment-state) + +The URL record type has the following API: + +- [`scheme`](https://url.spec.whatwg.org/#concept-url-scheme) +- [`username`](https://url.spec.whatwg.org/#concept-url-username) +- [`password`](https://url.spec.whatwg.org/#concept-url-password) +- [`host`](https://url.spec.whatwg.org/#concept-url-host) +- [`port`](https://url.spec.whatwg.org/#concept-url-port) +- [`path`](https://url.spec.whatwg.org/#concept-url-path) (as an array) +- [`query`](https://url.spec.whatwg.org/#concept-url-query) +- [`fragment`](https://url.spec.whatwg.org/#concept-url-fragment) +- [`cannotBeABaseURL`](https://url.spec.whatwg.org/#url-cannot-be-a-base-url-flag) (as a boolean) + +These properties should be treated with care, as in general changing them will cause the URL record to be in an inconsistent state until the appropriate invocation of `basicURLParse` is used to fix it up. You can see examples of this in the URL Standard, where there are many step sequences like "4. Set context object’s url’s fragment to the empty string. 5. Basic URL parse _input_ with context object’s url as _url_ and fragment state as _state override_." In between those two steps, a URL record is in an unusable state. + +The return value of "failure" in the spec is represented by the string `"failure"`. That is, functions like `parseURL` and `basicURLParse` can return _either_ a URL record _or_ the string `"failure"`. diff --git a/backend/node_modules/whatwg-url/lib/URL-impl.js b/backend/node_modules/whatwg-url/lib/URL-impl.js new file mode 100644 index 0000000000000000000000000000000000000000..dc7452cc5a4429c65d4e3289a8a8c1fc425453df --- /dev/null +++ b/backend/node_modules/whatwg-url/lib/URL-impl.js @@ -0,0 +1,200 @@ +"use strict"; +const usm = require("./url-state-machine"); + +exports.implementation = class URLImpl { + constructor(constructorArgs) { + const url = constructorArgs[0]; + const base = constructorArgs[1]; + + let parsedBase = null; + if (base !== undefined) { + parsedBase = usm.basicURLParse(base); + if (parsedBase === "failure") { + throw new TypeError("Invalid base URL"); + } + } + + const parsedURL = usm.basicURLParse(url, { baseURL: parsedBase }); + if (parsedURL === "failure") { + throw new TypeError("Invalid URL"); + } + + this._url = parsedURL; + + // TODO: query stuff + } + + get href() { + return usm.serializeURL(this._url); + } + + set href(v) { + const parsedURL = usm.basicURLParse(v); + if (parsedURL === "failure") { + throw new TypeError("Invalid URL"); + } + + this._url = parsedURL; + } + + get origin() { + return usm.serializeURLOrigin(this._url); + } + + get protocol() { + return this._url.scheme + ":"; + } + + set protocol(v) { + usm.basicURLParse(v + ":", { url: this._url, stateOverride: "scheme start" }); + } + + get username() { + return this._url.username; + } + + set username(v) { + if (usm.cannotHaveAUsernamePasswordPort(this._url)) { + return; + } + + usm.setTheUsername(this._url, v); + } + + get password() { + return this._url.password; + } + + set password(v) { + if (usm.cannotHaveAUsernamePasswordPort(this._url)) { + return; + } + + usm.setThePassword(this._url, v); + } + + get host() { + const url = this._url; + + if (url.host === null) { + return ""; + } + + if (url.port === null) { + return usm.serializeHost(url.host); + } + + return usm.serializeHost(url.host) + ":" + usm.serializeInteger(url.port); + } + + set host(v) { + if (this._url.cannotBeABaseURL) { + return; + } + + usm.basicURLParse(v, { url: this._url, stateOverride: "host" }); + } + + get hostname() { + if (this._url.host === null) { + return ""; + } + + return usm.serializeHost(this._url.host); + } + + set hostname(v) { + if (this._url.cannotBeABaseURL) { + return; + } + + usm.basicURLParse(v, { url: this._url, stateOverride: "hostname" }); + } + + get port() { + if (this._url.port === null) { + return ""; + } + + return usm.serializeInteger(this._url.port); + } + + set port(v) { + if (usm.cannotHaveAUsernamePasswordPort(this._url)) { + return; + } + + if (v === "") { + this._url.port = null; + } else { + usm.basicURLParse(v, { url: this._url, stateOverride: "port" }); + } + } + + get pathname() { + if (this._url.cannotBeABaseURL) { + return this._url.path[0]; + } + + if (this._url.path.length === 0) { + return ""; + } + + return "/" + this._url.path.join("/"); + } + + set pathname(v) { + if (this._url.cannotBeABaseURL) { + return; + } + + this._url.path = []; + usm.basicURLParse(v, { url: this._url, stateOverride: "path start" }); + } + + get search() { + if (this._url.query === null || this._url.query === "") { + return ""; + } + + return "?" + this._url.query; + } + + set search(v) { + // TODO: query stuff + + const url = this._url; + + if (v === "") { + url.query = null; + return; + } + + const input = v[0] === "?" ? v.substring(1) : v; + url.query = ""; + usm.basicURLParse(input, { url, stateOverride: "query" }); + } + + get hash() { + if (this._url.fragment === null || this._url.fragment === "") { + return ""; + } + + return "#" + this._url.fragment; + } + + set hash(v) { + if (v === "") { + this._url.fragment = null; + return; + } + + const input = v[0] === "#" ? v.substring(1) : v; + this._url.fragment = ""; + usm.basicURLParse(input, { url: this._url, stateOverride: "fragment" }); + } + + toJSON() { + return this.href; + } +}; diff --git a/backend/node_modules/whatwg-url/lib/URL.js b/backend/node_modules/whatwg-url/lib/URL.js new file mode 100644 index 0000000000000000000000000000000000000000..78c7207ef4d11bf6d9f11d673e45b09c706fe4a0 --- /dev/null +++ b/backend/node_modules/whatwg-url/lib/URL.js @@ -0,0 +1,196 @@ +"use strict"; + +const conversions = require("webidl-conversions"); +const utils = require("./utils.js"); +const Impl = require(".//URL-impl.js"); + +const impl = utils.implSymbol; + +function URL(url) { + if (!this || this[impl] || !(this instanceof URL)) { + throw new TypeError("Failed to construct 'URL': Please use the 'new' operator, this DOM object constructor cannot be called as a function."); + } + if (arguments.length < 1) { + throw new TypeError("Failed to construct 'URL': 1 argument required, but only " + arguments.length + " present."); + } + const args = []; + for (let i = 0; i < arguments.length && i < 2; ++i) { + args[i] = arguments[i]; + } + args[0] = conversions["USVString"](args[0]); + if (args[1] !== undefined) { + args[1] = conversions["USVString"](args[1]); + } + + module.exports.setup(this, args); +} + +URL.prototype.toJSON = function toJSON() { + if (!this || !module.exports.is(this)) { + throw new TypeError("Illegal invocation"); + } + const args = []; + for (let i = 0; i < arguments.length && i < 0; ++i) { + args[i] = arguments[i]; + } + return this[impl].toJSON.apply(this[impl], args); +}; +Object.defineProperty(URL.prototype, "href", { + get() { + return this[impl].href; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].href = V; + }, + enumerable: true, + configurable: true +}); + +URL.prototype.toString = function () { + if (!this || !module.exports.is(this)) { + throw new TypeError("Illegal invocation"); + } + return this.href; +}; + +Object.defineProperty(URL.prototype, "origin", { + get() { + return this[impl].origin; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "protocol", { + get() { + return this[impl].protocol; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].protocol = V; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "username", { + get() { + return this[impl].username; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].username = V; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "password", { + get() { + return this[impl].password; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].password = V; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "host", { + get() { + return this[impl].host; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].host = V; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "hostname", { + get() { + return this[impl].hostname; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].hostname = V; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "port", { + get() { + return this[impl].port; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].port = V; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "pathname", { + get() { + return this[impl].pathname; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].pathname = V; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "search", { + get() { + return this[impl].search; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].search = V; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "hash", { + get() { + return this[impl].hash; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].hash = V; + }, + enumerable: true, + configurable: true +}); + + +module.exports = { + is(obj) { + return !!obj && obj[impl] instanceof Impl.implementation; + }, + create(constructorArgs, privateData) { + let obj = Object.create(URL.prototype); + this.setup(obj, constructorArgs, privateData); + return obj; + }, + setup(obj, constructorArgs, privateData) { + if (!privateData) privateData = {}; + privateData.wrapper = obj; + + obj[impl] = new Impl.implementation(constructorArgs, privateData); + obj[impl][utils.wrapperSymbol] = obj; + }, + interface: URL, + expose: { + Window: { URL: URL }, + Worker: { URL: URL } + } +}; + diff --git a/backend/node_modules/whatwg-url/lib/public-api.js b/backend/node_modules/whatwg-url/lib/public-api.js new file mode 100644 index 0000000000000000000000000000000000000000..932dcada4bd4f19dc190bbd6e0742bb84f76f5cf --- /dev/null +++ b/backend/node_modules/whatwg-url/lib/public-api.js @@ -0,0 +1,11 @@ +"use strict"; + +exports.URL = require("./URL").interface; +exports.serializeURL = require("./url-state-machine").serializeURL; +exports.serializeURLOrigin = require("./url-state-machine").serializeURLOrigin; +exports.basicURLParse = require("./url-state-machine").basicURLParse; +exports.setTheUsername = require("./url-state-machine").setTheUsername; +exports.setThePassword = require("./url-state-machine").setThePassword; +exports.serializeHost = require("./url-state-machine").serializeHost; +exports.serializeInteger = require("./url-state-machine").serializeInteger; +exports.parseURL = require("./url-state-machine").parseURL; diff --git a/backend/node_modules/whatwg-url/lib/url-state-machine.js b/backend/node_modules/whatwg-url/lib/url-state-machine.js new file mode 100644 index 0000000000000000000000000000000000000000..c25dbc2c486289fbd7446baed24dc6343f0226f6 --- /dev/null +++ b/backend/node_modules/whatwg-url/lib/url-state-machine.js @@ -0,0 +1,1297 @@ +"use strict"; +const punycode = require("punycode"); +const tr46 = require("tr46"); + +const specialSchemes = { + ftp: 21, + file: null, + gopher: 70, + http: 80, + https: 443, + ws: 80, + wss: 443 +}; + +const failure = Symbol("failure"); + +function countSymbols(str) { + return punycode.ucs2.decode(str).length; +} + +function at(input, idx) { + const c = input[idx]; + return isNaN(c) ? undefined : String.fromCodePoint(c); +} + +function isASCIIDigit(c) { + return c >= 0x30 && c <= 0x39; +} + +function isASCIIAlpha(c) { + return (c >= 0x41 && c <= 0x5A) || (c >= 0x61 && c <= 0x7A); +} + +function isASCIIAlphanumeric(c) { + return isASCIIAlpha(c) || isASCIIDigit(c); +} + +function isASCIIHex(c) { + return isASCIIDigit(c) || (c >= 0x41 && c <= 0x46) || (c >= 0x61 && c <= 0x66); +} + +function isSingleDot(buffer) { + return buffer === "." || buffer.toLowerCase() === "%2e"; +} + +function isDoubleDot(buffer) { + buffer = buffer.toLowerCase(); + return buffer === ".." || buffer === "%2e." || buffer === ".%2e" || buffer === "%2e%2e"; +} + +function isWindowsDriveLetterCodePoints(cp1, cp2) { + return isASCIIAlpha(cp1) && (cp2 === 58 || cp2 === 124); +} + +function isWindowsDriveLetterString(string) { + return string.length === 2 && isASCIIAlpha(string.codePointAt(0)) && (string[1] === ":" || string[1] === "|"); +} + +function isNormalizedWindowsDriveLetterString(string) { + return string.length === 2 && isASCIIAlpha(string.codePointAt(0)) && string[1] === ":"; +} + +function containsForbiddenHostCodePoint(string) { + return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|%|\/|:|\?|@|\[|\\|\]/) !== -1; +} + +function containsForbiddenHostCodePointExcludingPercent(string) { + return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|\?|@|\[|\\|\]/) !== -1; +} + +function isSpecialScheme(scheme) { + return specialSchemes[scheme] !== undefined; +} + +function isSpecial(url) { + return isSpecialScheme(url.scheme); +} + +function defaultPort(scheme) { + return specialSchemes[scheme]; +} + +function percentEncode(c) { + let hex = c.toString(16).toUpperCase(); + if (hex.length === 1) { + hex = "0" + hex; + } + + return "%" + hex; +} + +function utf8PercentEncode(c) { + const buf = new Buffer(c); + + let str = ""; + + for (let i = 0; i < buf.length; ++i) { + str += percentEncode(buf[i]); + } + + return str; +} + +function utf8PercentDecode(str) { + const input = new Buffer(str); + const output = []; + for (let i = 0; i < input.length; ++i) { + if (input[i] !== 37) { + output.push(input[i]); + } else if (input[i] === 37 && isASCIIHex(input[i + 1]) && isASCIIHex(input[i + 2])) { + output.push(parseInt(input.slice(i + 1, i + 3).toString(), 16)); + i += 2; + } else { + output.push(input[i]); + } + } + return new Buffer(output).toString(); +} + +function isC0ControlPercentEncode(c) { + return c <= 0x1F || c > 0x7E; +} + +const extraPathPercentEncodeSet = new Set([32, 34, 35, 60, 62, 63, 96, 123, 125]); +function isPathPercentEncode(c) { + return isC0ControlPercentEncode(c) || extraPathPercentEncodeSet.has(c); +} + +const extraUserinfoPercentEncodeSet = + new Set([47, 58, 59, 61, 64, 91, 92, 93, 94, 124]); +function isUserinfoPercentEncode(c) { + return isPathPercentEncode(c) || extraUserinfoPercentEncodeSet.has(c); +} + +function percentEncodeChar(c, encodeSetPredicate) { + const cStr = String.fromCodePoint(c); + + if (encodeSetPredicate(c)) { + return utf8PercentEncode(cStr); + } + + return cStr; +} + +function parseIPv4Number(input) { + let R = 10; + + if (input.length >= 2 && input.charAt(0) === "0" && input.charAt(1).toLowerCase() === "x") { + input = input.substring(2); + R = 16; + } else if (input.length >= 2 && input.charAt(0) === "0") { + input = input.substring(1); + R = 8; + } + + if (input === "") { + return 0; + } + + const regex = R === 10 ? /[^0-9]/ : (R === 16 ? /[^0-9A-Fa-f]/ : /[^0-7]/); + if (regex.test(input)) { + return failure; + } + + return parseInt(input, R); +} + +function parseIPv4(input) { + const parts = input.split("."); + if (parts[parts.length - 1] === "") { + if (parts.length > 1) { + parts.pop(); + } + } + + if (parts.length > 4) { + return input; + } + + const numbers = []; + for (const part of parts) { + if (part === "") { + return input; + } + const n = parseIPv4Number(part); + if (n === failure) { + return input; + } + + numbers.push(n); + } + + for (let i = 0; i < numbers.length - 1; ++i) { + if (numbers[i] > 255) { + return failure; + } + } + if (numbers[numbers.length - 1] >= Math.pow(256, 5 - numbers.length)) { + return failure; + } + + let ipv4 = numbers.pop(); + let counter = 0; + + for (const n of numbers) { + ipv4 += n * Math.pow(256, 3 - counter); + ++counter; + } + + return ipv4; +} + +function serializeIPv4(address) { + let output = ""; + let n = address; + + for (let i = 1; i <= 4; ++i) { + output = String(n % 256) + output; + if (i !== 4) { + output = "." + output; + } + n = Math.floor(n / 256); + } + + return output; +} + +function parseIPv6(input) { + const address = [0, 0, 0, 0, 0, 0, 0, 0]; + let pieceIndex = 0; + let compress = null; + let pointer = 0; + + input = punycode.ucs2.decode(input); + + if (input[pointer] === 58) { + if (input[pointer + 1] !== 58) { + return failure; + } + + pointer += 2; + ++pieceIndex; + compress = pieceIndex; + } + + while (pointer < input.length) { + if (pieceIndex === 8) { + return failure; + } + + if (input[pointer] === 58) { + if (compress !== null) { + return failure; + } + ++pointer; + ++pieceIndex; + compress = pieceIndex; + continue; + } + + let value = 0; + let length = 0; + + while (length < 4 && isASCIIHex(input[pointer])) { + value = value * 0x10 + parseInt(at(input, pointer), 16); + ++pointer; + ++length; + } + + if (input[pointer] === 46) { + if (length === 0) { + return failure; + } + + pointer -= length; + + if (pieceIndex > 6) { + return failure; + } + + let numbersSeen = 0; + + while (input[pointer] !== undefined) { + let ipv4Piece = null; + + if (numbersSeen > 0) { + if (input[pointer] === 46 && numbersSeen < 4) { + ++pointer; + } else { + return failure; + } + } + + if (!isASCIIDigit(input[pointer])) { + return failure; + } + + while (isASCIIDigit(input[pointer])) { + const number = parseInt(at(input, pointer)); + if (ipv4Piece === null) { + ipv4Piece = number; + } else if (ipv4Piece === 0) { + return failure; + } else { + ipv4Piece = ipv4Piece * 10 + number; + } + if (ipv4Piece > 255) { + return failure; + } + ++pointer; + } + + address[pieceIndex] = address[pieceIndex] * 0x100 + ipv4Piece; + + ++numbersSeen; + + if (numbersSeen === 2 || numbersSeen === 4) { + ++pieceIndex; + } + } + + if (numbersSeen !== 4) { + return failure; + } + + break; + } else if (input[pointer] === 58) { + ++pointer; + if (input[pointer] === undefined) { + return failure; + } + } else if (input[pointer] !== undefined) { + return failure; + } + + address[pieceIndex] = value; + ++pieceIndex; + } + + if (compress !== null) { + let swaps = pieceIndex - compress; + pieceIndex = 7; + while (pieceIndex !== 0 && swaps > 0) { + const temp = address[compress + swaps - 1]; + address[compress + swaps - 1] = address[pieceIndex]; + address[pieceIndex] = temp; + --pieceIndex; + --swaps; + } + } else if (compress === null && pieceIndex !== 8) { + return failure; + } + + return address; +} + +function serializeIPv6(address) { + let output = ""; + const seqResult = findLongestZeroSequence(address); + const compress = seqResult.idx; + let ignore0 = false; + + for (let pieceIndex = 0; pieceIndex <= 7; ++pieceIndex) { + if (ignore0 && address[pieceIndex] === 0) { + continue; + } else if (ignore0) { + ignore0 = false; + } + + if (compress === pieceIndex) { + const separator = pieceIndex === 0 ? "::" : ":"; + output += separator; + ignore0 = true; + continue; + } + + output += address[pieceIndex].toString(16); + + if (pieceIndex !== 7) { + output += ":"; + } + } + + return output; +} + +function parseHost(input, isSpecialArg) { + if (input[0] === "[") { + if (input[input.length - 1] !== "]") { + return failure; + } + + return parseIPv6(input.substring(1, input.length - 1)); + } + + if (!isSpecialArg) { + return parseOpaqueHost(input); + } + + const domain = utf8PercentDecode(input); + const asciiDomain = tr46.toASCII(domain, false, tr46.PROCESSING_OPTIONS.NONTRANSITIONAL, false); + if (asciiDomain === null) { + return failure; + } + + if (containsForbiddenHostCodePoint(asciiDomain)) { + return failure; + } + + const ipv4Host = parseIPv4(asciiDomain); + if (typeof ipv4Host === "number" || ipv4Host === failure) { + return ipv4Host; + } + + return asciiDomain; +} + +function parseOpaqueHost(input) { + if (containsForbiddenHostCodePointExcludingPercent(input)) { + return failure; + } + + let output = ""; + const decoded = punycode.ucs2.decode(input); + for (let i = 0; i < decoded.length; ++i) { + output += percentEncodeChar(decoded[i], isC0ControlPercentEncode); + } + return output; +} + +function findLongestZeroSequence(arr) { + let maxIdx = null; + let maxLen = 1; // only find elements > 1 + let currStart = null; + let currLen = 0; + + for (let i = 0; i < arr.length; ++i) { + if (arr[i] !== 0) { + if (currLen > maxLen) { + maxIdx = currStart; + maxLen = currLen; + } + + currStart = null; + currLen = 0; + } else { + if (currStart === null) { + currStart = i; + } + ++currLen; + } + } + + // if trailing zeros + if (currLen > maxLen) { + maxIdx = currStart; + maxLen = currLen; + } + + return { + idx: maxIdx, + len: maxLen + }; +} + +function serializeHost(host) { + if (typeof host === "number") { + return serializeIPv4(host); + } + + // IPv6 serializer + if (host instanceof Array) { + return "[" + serializeIPv6(host) + "]"; + } + + return host; +} + +function trimControlChars(url) { + return url.replace(/^[\u0000-\u001F\u0020]+|[\u0000-\u001F\u0020]+$/g, ""); +} + +function trimTabAndNewline(url) { + return url.replace(/\u0009|\u000A|\u000D/g, ""); +} + +function shortenPath(url) { + const path = url.path; + if (path.length === 0) { + return; + } + if (url.scheme === "file" && path.length === 1 && isNormalizedWindowsDriveLetter(path[0])) { + return; + } + + path.pop(); +} + +function includesCredentials(url) { + return url.username !== "" || url.password !== ""; +} + +function cannotHaveAUsernamePasswordPort(url) { + return url.host === null || url.host === "" || url.cannotBeABaseURL || url.scheme === "file"; +} + +function isNormalizedWindowsDriveLetter(string) { + return /^[A-Za-z]:$/.test(string); +} + +function URLStateMachine(input, base, encodingOverride, url, stateOverride) { + this.pointer = 0; + this.input = input; + this.base = base || null; + this.encodingOverride = encodingOverride || "utf-8"; + this.stateOverride = stateOverride; + this.url = url; + this.failure = false; + this.parseError = false; + + if (!this.url) { + this.url = { + scheme: "", + username: "", + password: "", + host: null, + port: null, + path: [], + query: null, + fragment: null, + + cannotBeABaseURL: false + }; + + const res = trimControlChars(this.input); + if (res !== this.input) { + this.parseError = true; + } + this.input = res; + } + + const res = trimTabAndNewline(this.input); + if (res !== this.input) { + this.parseError = true; + } + this.input = res; + + this.state = stateOverride || "scheme start"; + + this.buffer = ""; + this.atFlag = false; + this.arrFlag = false; + this.passwordTokenSeenFlag = false; + + this.input = punycode.ucs2.decode(this.input); + + for (; this.pointer <= this.input.length; ++this.pointer) { + const c = this.input[this.pointer]; + const cStr = isNaN(c) ? undefined : String.fromCodePoint(c); + + // exec state machine + const ret = this["parse " + this.state](c, cStr); + if (!ret) { + break; // terminate algorithm + } else if (ret === failure) { + this.failure = true; + break; + } + } +} + +URLStateMachine.prototype["parse scheme start"] = function parseSchemeStart(c, cStr) { + if (isASCIIAlpha(c)) { + this.buffer += cStr.toLowerCase(); + this.state = "scheme"; + } else if (!this.stateOverride) { + this.state = "no scheme"; + --this.pointer; + } else { + this.parseError = true; + return failure; + } + + return true; +}; + +URLStateMachine.prototype["parse scheme"] = function parseScheme(c, cStr) { + if (isASCIIAlphanumeric(c) || c === 43 || c === 45 || c === 46) { + this.buffer += cStr.toLowerCase(); + } else if (c === 58) { + if (this.stateOverride) { + if (isSpecial(this.url) && !isSpecialScheme(this.buffer)) { + return false; + } + + if (!isSpecial(this.url) && isSpecialScheme(this.buffer)) { + return false; + } + + if ((includesCredentials(this.url) || this.url.port !== null) && this.buffer === "file") { + return false; + } + + if (this.url.scheme === "file" && (this.url.host === "" || this.url.host === null)) { + return false; + } + } + this.url.scheme = this.buffer; + this.buffer = ""; + if (this.stateOverride) { + return false; + } + if (this.url.scheme === "file") { + if (this.input[this.pointer + 1] !== 47 || this.input[this.pointer + 2] !== 47) { + this.parseError = true; + } + this.state = "file"; + } else if (isSpecial(this.url) && this.base !== null && this.base.scheme === this.url.scheme) { + this.state = "special relative or authority"; + } else if (isSpecial(this.url)) { + this.state = "special authority slashes"; + } else if (this.input[this.pointer + 1] === 47) { + this.state = "path or authority"; + ++this.pointer; + } else { + this.url.cannotBeABaseURL = true; + this.url.path.push(""); + this.state = "cannot-be-a-base-URL path"; + } + } else if (!this.stateOverride) { + this.buffer = ""; + this.state = "no scheme"; + this.pointer = -1; + } else { + this.parseError = true; + return failure; + } + + return true; +}; + +URLStateMachine.prototype["parse no scheme"] = function parseNoScheme(c) { + if (this.base === null || (this.base.cannotBeABaseURL && c !== 35)) { + return failure; + } else if (this.base.cannotBeABaseURL && c === 35) { + this.url.scheme = this.base.scheme; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + this.url.fragment = ""; + this.url.cannotBeABaseURL = true; + this.state = "fragment"; + } else if (this.base.scheme === "file") { + this.state = "file"; + --this.pointer; + } else { + this.state = "relative"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse special relative or authority"] = function parseSpecialRelativeOrAuthority(c) { + if (c === 47 && this.input[this.pointer + 1] === 47) { + this.state = "special authority ignore slashes"; + ++this.pointer; + } else { + this.parseError = true; + this.state = "relative"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse path or authority"] = function parsePathOrAuthority(c) { + if (c === 47) { + this.state = "authority"; + } else { + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse relative"] = function parseRelative(c) { + this.url.scheme = this.base.scheme; + if (isNaN(c)) { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + } else if (c === 47) { + this.state = "relative slash"; + } else if (c === 63) { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.url.path = this.base.path.slice(); + this.url.query = ""; + this.state = "query"; + } else if (c === 35) { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + this.url.fragment = ""; + this.state = "fragment"; + } else if (isSpecial(this.url) && c === 92) { + this.parseError = true; + this.state = "relative slash"; + } else { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.url.path = this.base.path.slice(0, this.base.path.length - 1); + + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse relative slash"] = function parseRelativeSlash(c) { + if (isSpecial(this.url) && (c === 47 || c === 92)) { + if (c === 92) { + this.parseError = true; + } + this.state = "special authority ignore slashes"; + } else if (c === 47) { + this.state = "authority"; + } else { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse special authority slashes"] = function parseSpecialAuthoritySlashes(c) { + if (c === 47 && this.input[this.pointer + 1] === 47) { + this.state = "special authority ignore slashes"; + ++this.pointer; + } else { + this.parseError = true; + this.state = "special authority ignore slashes"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse special authority ignore slashes"] = function parseSpecialAuthorityIgnoreSlashes(c) { + if (c !== 47 && c !== 92) { + this.state = "authority"; + --this.pointer; + } else { + this.parseError = true; + } + + return true; +}; + +URLStateMachine.prototype["parse authority"] = function parseAuthority(c, cStr) { + if (c === 64) { + this.parseError = true; + if (this.atFlag) { + this.buffer = "%40" + this.buffer; + } + this.atFlag = true; + + // careful, this is based on buffer and has its own pointer (this.pointer != pointer) and inner chars + const len = countSymbols(this.buffer); + for (let pointer = 0; pointer < len; ++pointer) { + const codePoint = this.buffer.codePointAt(pointer); + + if (codePoint === 58 && !this.passwordTokenSeenFlag) { + this.passwordTokenSeenFlag = true; + continue; + } + const encodedCodePoints = percentEncodeChar(codePoint, isUserinfoPercentEncode); + if (this.passwordTokenSeenFlag) { + this.url.password += encodedCodePoints; + } else { + this.url.username += encodedCodePoints; + } + } + this.buffer = ""; + } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || + (isSpecial(this.url) && c === 92)) { + if (this.atFlag && this.buffer === "") { + this.parseError = true; + return failure; + } + this.pointer -= countSymbols(this.buffer) + 1; + this.buffer = ""; + this.state = "host"; + } else { + this.buffer += cStr; + } + + return true; +}; + +URLStateMachine.prototype["parse hostname"] = +URLStateMachine.prototype["parse host"] = function parseHostName(c, cStr) { + if (this.stateOverride && this.url.scheme === "file") { + --this.pointer; + this.state = "file host"; + } else if (c === 58 && !this.arrFlag) { + if (this.buffer === "") { + this.parseError = true; + return failure; + } + + const host = parseHost(this.buffer, isSpecial(this.url)); + if (host === failure) { + return failure; + } + + this.url.host = host; + this.buffer = ""; + this.state = "port"; + if (this.stateOverride === "hostname") { + return false; + } + } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || + (isSpecial(this.url) && c === 92)) { + --this.pointer; + if (isSpecial(this.url) && this.buffer === "") { + this.parseError = true; + return failure; + } else if (this.stateOverride && this.buffer === "" && + (includesCredentials(this.url) || this.url.port !== null)) { + this.parseError = true; + return false; + } + + const host = parseHost(this.buffer, isSpecial(this.url)); + if (host === failure) { + return failure; + } + + this.url.host = host; + this.buffer = ""; + this.state = "path start"; + if (this.stateOverride) { + return false; + } + } else { + if (c === 91) { + this.arrFlag = true; + } else if (c === 93) { + this.arrFlag = false; + } + this.buffer += cStr; + } + + return true; +}; + +URLStateMachine.prototype["parse port"] = function parsePort(c, cStr) { + if (isASCIIDigit(c)) { + this.buffer += cStr; + } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || + (isSpecial(this.url) && c === 92) || + this.stateOverride) { + if (this.buffer !== "") { + const port = parseInt(this.buffer); + if (port > Math.pow(2, 16) - 1) { + this.parseError = true; + return failure; + } + this.url.port = port === defaultPort(this.url.scheme) ? null : port; + this.buffer = ""; + } + if (this.stateOverride) { + return false; + } + this.state = "path start"; + --this.pointer; + } else { + this.parseError = true; + return failure; + } + + return true; +}; + +const fileOtherwiseCodePoints = new Set([47, 92, 63, 35]); + +URLStateMachine.prototype["parse file"] = function parseFile(c) { + this.url.scheme = "file"; + + if (c === 47 || c === 92) { + if (c === 92) { + this.parseError = true; + } + this.state = "file slash"; + } else if (this.base !== null && this.base.scheme === "file") { + if (isNaN(c)) { + this.url.host = this.base.host; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + } else if (c === 63) { + this.url.host = this.base.host; + this.url.path = this.base.path.slice(); + this.url.query = ""; + this.state = "query"; + } else if (c === 35) { + this.url.host = this.base.host; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + this.url.fragment = ""; + this.state = "fragment"; + } else { + if (this.input.length - this.pointer - 1 === 0 || // remaining consists of 0 code points + !isWindowsDriveLetterCodePoints(c, this.input[this.pointer + 1]) || + (this.input.length - this.pointer - 1 >= 2 && // remaining has at least 2 code points + !fileOtherwiseCodePoints.has(this.input[this.pointer + 2]))) { + this.url.host = this.base.host; + this.url.path = this.base.path.slice(); + shortenPath(this.url); + } else { + this.parseError = true; + } + + this.state = "path"; + --this.pointer; + } + } else { + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse file slash"] = function parseFileSlash(c) { + if (c === 47 || c === 92) { + if (c === 92) { + this.parseError = true; + } + this.state = "file host"; + } else { + if (this.base !== null && this.base.scheme === "file") { + if (isNormalizedWindowsDriveLetterString(this.base.path[0])) { + this.url.path.push(this.base.path[0]); + } else { + this.url.host = this.base.host; + } + } + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse file host"] = function parseFileHost(c, cStr) { + if (isNaN(c) || c === 47 || c === 92 || c === 63 || c === 35) { + --this.pointer; + if (!this.stateOverride && isWindowsDriveLetterString(this.buffer)) { + this.parseError = true; + this.state = "path"; + } else if (this.buffer === "") { + this.url.host = ""; + if (this.stateOverride) { + return false; + } + this.state = "path start"; + } else { + let host = parseHost(this.buffer, isSpecial(this.url)); + if (host === failure) { + return failure; + } + if (host === "localhost") { + host = ""; + } + this.url.host = host; + + if (this.stateOverride) { + return false; + } + + this.buffer = ""; + this.state = "path start"; + } + } else { + this.buffer += cStr; + } + + return true; +}; + +URLStateMachine.prototype["parse path start"] = function parsePathStart(c) { + if (isSpecial(this.url)) { + if (c === 92) { + this.parseError = true; + } + this.state = "path"; + + if (c !== 47 && c !== 92) { + --this.pointer; + } + } else if (!this.stateOverride && c === 63) { + this.url.query = ""; + this.state = "query"; + } else if (!this.stateOverride && c === 35) { + this.url.fragment = ""; + this.state = "fragment"; + } else if (c !== undefined) { + this.state = "path"; + if (c !== 47) { + --this.pointer; + } + } + + return true; +}; + +URLStateMachine.prototype["parse path"] = function parsePath(c) { + if (isNaN(c) || c === 47 || (isSpecial(this.url) && c === 92) || + (!this.stateOverride && (c === 63 || c === 35))) { + if (isSpecial(this.url) && c === 92) { + this.parseError = true; + } + + if (isDoubleDot(this.buffer)) { + shortenPath(this.url); + if (c !== 47 && !(isSpecial(this.url) && c === 92)) { + this.url.path.push(""); + } + } else if (isSingleDot(this.buffer) && c !== 47 && + !(isSpecial(this.url) && c === 92)) { + this.url.path.push(""); + } else if (!isSingleDot(this.buffer)) { + if (this.url.scheme === "file" && this.url.path.length === 0 && isWindowsDriveLetterString(this.buffer)) { + if (this.url.host !== "" && this.url.host !== null) { + this.parseError = true; + this.url.host = ""; + } + this.buffer = this.buffer[0] + ":"; + } + this.url.path.push(this.buffer); + } + this.buffer = ""; + if (this.url.scheme === "file" && (c === undefined || c === 63 || c === 35)) { + while (this.url.path.length > 1 && this.url.path[0] === "") { + this.parseError = true; + this.url.path.shift(); + } + } + if (c === 63) { + this.url.query = ""; + this.state = "query"; + } + if (c === 35) { + this.url.fragment = ""; + this.state = "fragment"; + } + } else { + // TODO: If c is not a URL code point and not "%", parse error. + + if (c === 37 && + (!isASCIIHex(this.input[this.pointer + 1]) || + !isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + this.buffer += percentEncodeChar(c, isPathPercentEncode); + } + + return true; +}; + +URLStateMachine.prototype["parse cannot-be-a-base-URL path"] = function parseCannotBeABaseURLPath(c) { + if (c === 63) { + this.url.query = ""; + this.state = "query"; + } else if (c === 35) { + this.url.fragment = ""; + this.state = "fragment"; + } else { + // TODO: Add: not a URL code point + if (!isNaN(c) && c !== 37) { + this.parseError = true; + } + + if (c === 37 && + (!isASCIIHex(this.input[this.pointer + 1]) || + !isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + if (!isNaN(c)) { + this.url.path[0] = this.url.path[0] + percentEncodeChar(c, isC0ControlPercentEncode); + } + } + + return true; +}; + +URLStateMachine.prototype["parse query"] = function parseQuery(c, cStr) { + if (isNaN(c) || (!this.stateOverride && c === 35)) { + if (!isSpecial(this.url) || this.url.scheme === "ws" || this.url.scheme === "wss") { + this.encodingOverride = "utf-8"; + } + + const buffer = new Buffer(this.buffer); // TODO: Use encoding override instead + for (let i = 0; i < buffer.length; ++i) { + if (buffer[i] < 0x21 || buffer[i] > 0x7E || buffer[i] === 0x22 || buffer[i] === 0x23 || + buffer[i] === 0x3C || buffer[i] === 0x3E) { + this.url.query += percentEncode(buffer[i]); + } else { + this.url.query += String.fromCodePoint(buffer[i]); + } + } + + this.buffer = ""; + if (c === 35) { + this.url.fragment = ""; + this.state = "fragment"; + } + } else { + // TODO: If c is not a URL code point and not "%", parse error. + if (c === 37 && + (!isASCIIHex(this.input[this.pointer + 1]) || + !isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + this.buffer += cStr; + } + + return true; +}; + +URLStateMachine.prototype["parse fragment"] = function parseFragment(c) { + if (isNaN(c)) { // do nothing + } else if (c === 0x0) { + this.parseError = true; + } else { + // TODO: If c is not a URL code point and not "%", parse error. + if (c === 37 && + (!isASCIIHex(this.input[this.pointer + 1]) || + !isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + this.url.fragment += percentEncodeChar(c, isC0ControlPercentEncode); + } + + return true; +}; + +function serializeURL(url, excludeFragment) { + let output = url.scheme + ":"; + if (url.host !== null) { + output += "//"; + + if (url.username !== "" || url.password !== "") { + output += url.username; + if (url.password !== "") { + output += ":" + url.password; + } + output += "@"; + } + + output += serializeHost(url.host); + + if (url.port !== null) { + output += ":" + url.port; + } + } else if (url.host === null && url.scheme === "file") { + output += "//"; + } + + if (url.cannotBeABaseURL) { + output += url.path[0]; + } else { + for (const string of url.path) { + output += "/" + string; + } + } + + if (url.query !== null) { + output += "?" + url.query; + } + + if (!excludeFragment && url.fragment !== null) { + output += "#" + url.fragment; + } + + return output; +} + +function serializeOrigin(tuple) { + let result = tuple.scheme + "://"; + result += serializeHost(tuple.host); + + if (tuple.port !== null) { + result += ":" + tuple.port; + } + + return result; +} + +module.exports.serializeURL = serializeURL; + +module.exports.serializeURLOrigin = function (url) { + // https://url.spec.whatwg.org/#concept-url-origin + switch (url.scheme) { + case "blob": + try { + return module.exports.serializeURLOrigin(module.exports.parseURL(url.path[0])); + } catch (e) { + // serializing an opaque origin returns "null" + return "null"; + } + case "ftp": + case "gopher": + case "http": + case "https": + case "ws": + case "wss": + return serializeOrigin({ + scheme: url.scheme, + host: url.host, + port: url.port + }); + case "file": + // spec says "exercise to the reader", chrome says "file://" + return "file://"; + default: + // serializing an opaque origin returns "null" + return "null"; + } +}; + +module.exports.basicURLParse = function (input, options) { + if (options === undefined) { + options = {}; + } + + const usm = new URLStateMachine(input, options.baseURL, options.encodingOverride, options.url, options.stateOverride); + if (usm.failure) { + return "failure"; + } + + return usm.url; +}; + +module.exports.setTheUsername = function (url, username) { + url.username = ""; + const decoded = punycode.ucs2.decode(username); + for (let i = 0; i < decoded.length; ++i) { + url.username += percentEncodeChar(decoded[i], isUserinfoPercentEncode); + } +}; + +module.exports.setThePassword = function (url, password) { + url.password = ""; + const decoded = punycode.ucs2.decode(password); + for (let i = 0; i < decoded.length; ++i) { + url.password += percentEncodeChar(decoded[i], isUserinfoPercentEncode); + } +}; + +module.exports.serializeHost = serializeHost; + +module.exports.cannotHaveAUsernamePasswordPort = cannotHaveAUsernamePasswordPort; + +module.exports.serializeInteger = function (integer) { + return String(integer); +}; + +module.exports.parseURL = function (input, options) { + if (options === undefined) { + options = {}; + } + + // We don't handle blobs, so this just delegates: + return module.exports.basicURLParse(input, { baseURL: options.baseURL, encodingOverride: options.encodingOverride }); +}; diff --git a/backend/node_modules/whatwg-url/lib/utils.js b/backend/node_modules/whatwg-url/lib/utils.js new file mode 100644 index 0000000000000000000000000000000000000000..a562009c8c8772623a89c074a518cdf636fd87d5 --- /dev/null +++ b/backend/node_modules/whatwg-url/lib/utils.js @@ -0,0 +1,20 @@ +"use strict"; + +module.exports.mixin = function mixin(target, source) { + const keys = Object.getOwnPropertyNames(source); + for (let i = 0; i < keys.length; ++i) { + Object.defineProperty(target, keys[i], Object.getOwnPropertyDescriptor(source, keys[i])); + } +}; + +module.exports.wrapperSymbol = Symbol("wrapper"); +module.exports.implSymbol = Symbol("impl"); + +module.exports.wrapperForImpl = function (impl) { + return impl[module.exports.wrapperSymbol]; +}; + +module.exports.implForWrapper = function (wrapper) { + return wrapper[module.exports.implSymbol]; +}; + diff --git a/backend/node_modules/whatwg-url/package.json b/backend/node_modules/whatwg-url/package.json new file mode 100644 index 0000000000000000000000000000000000000000..fce35ae717615d6627275d5e0507e7538a9df385 --- /dev/null +++ b/backend/node_modules/whatwg-url/package.json @@ -0,0 +1,32 @@ +{ + "name": "whatwg-url", + "version": "5.0.0", + "description": "An implementation of the WHATWG URL Standard's URL API and parsing machinery", + "main": "lib/public-api.js", + "files": [ + "lib/" + ], + "author": "Sebastian Mayr ", + "license": "MIT", + "repository": "jsdom/whatwg-url", + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + }, + "devDependencies": { + "eslint": "^2.6.0", + "istanbul": "~0.4.3", + "mocha": "^2.2.4", + "recast": "~0.10.29", + "request": "^2.55.0", + "webidl2js": "^3.0.2" + }, + "scripts": { + "build": "node scripts/transform.js && node scripts/convert-idl.js", + "coverage": "istanbul cover node_modules/mocha/bin/_mocha", + "lint": "eslint .", + "prepublish": "npm run build", + "pretest": "node scripts/get-latest-platform-tests.js && npm run build", + "test": "mocha" + } +} diff --git a/backend/node_modules/xtend/.jshintrc b/backend/node_modules/xtend/.jshintrc new file mode 100644 index 0000000000000000000000000000000000000000..77887b5f0f2efc24bd55430cb6f95f8a0cad89d8 --- /dev/null +++ b/backend/node_modules/xtend/.jshintrc @@ -0,0 +1,30 @@ +{ + "maxdepth": 4, + "maxstatements": 200, + "maxcomplexity": 12, + "maxlen": 80, + "maxparams": 5, + + "curly": true, + "eqeqeq": true, + "immed": true, + "latedef": false, + "noarg": true, + "noempty": true, + "nonew": true, + "undef": true, + "unused": "vars", + "trailing": true, + + "quotmark": true, + "expr": true, + "asi": true, + + "browser": false, + "esnext": true, + "devel": false, + "node": false, + "nonstandard": false, + + "predef": ["require", "module", "__dirname", "__filename"] +} diff --git a/backend/node_modules/xtend/LICENSE b/backend/node_modules/xtend/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..0099f4f6c77f40ac409076408ad07449ffe246d3 --- /dev/null +++ b/backend/node_modules/xtend/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) +Copyright (c) 2012-2014 Raynos. + +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/backend/node_modules/xtend/README.md b/backend/node_modules/xtend/README.md new file mode 100644 index 0000000000000000000000000000000000000000..4a2703cff276b155e89c3abb7b09fbdfe90273f4 --- /dev/null +++ b/backend/node_modules/xtend/README.md @@ -0,0 +1,32 @@ +# xtend + +[![browser support][3]][4] + +[![locked](http://badges.github.io/stability-badges/dist/locked.svg)](http://github.com/badges/stability-badges) + +Extend like a boss + +xtend is a basic utility library which allows you to extend an object by appending all of the properties from each object in a list. When there are identical properties, the right-most property takes precedence. + +## Examples + +```js +var extend = require("xtend") + +// extend returns a new object. Does not mutate arguments +var combination = extend({ + a: "a", + b: "c" +}, { + b: "b" +}) +// { a: "a", b: "b" } +``` + +## Stability status: Locked + +## MIT Licensed + + + [3]: http://ci.testling.com/Raynos/xtend.png + [4]: http://ci.testling.com/Raynos/xtend diff --git a/backend/node_modules/xtend/immutable.js b/backend/node_modules/xtend/immutable.js new file mode 100644 index 0000000000000000000000000000000000000000..94889c9de11a181cec153de1713c8ae14ae4cb43 --- /dev/null +++ b/backend/node_modules/xtend/immutable.js @@ -0,0 +1,19 @@ +module.exports = extend + +var hasOwnProperty = Object.prototype.hasOwnProperty; + +function extend() { + var target = {} + + for (var i = 0; i < arguments.length; i++) { + var source = arguments[i] + + for (var key in source) { + if (hasOwnProperty.call(source, key)) { + target[key] = source[key] + } + } + } + + return target +} diff --git a/backend/node_modules/xtend/mutable.js b/backend/node_modules/xtend/mutable.js new file mode 100644 index 0000000000000000000000000000000000000000..72debede6ca58592fe93b5ab22d434311a76861b --- /dev/null +++ b/backend/node_modules/xtend/mutable.js @@ -0,0 +1,17 @@ +module.exports = extend + +var hasOwnProperty = Object.prototype.hasOwnProperty; + +function extend(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i] + + for (var key in source) { + if (hasOwnProperty.call(source, key)) { + target[key] = source[key] + } + } + } + + return target +} diff --git a/backend/node_modules/xtend/package.json b/backend/node_modules/xtend/package.json new file mode 100644 index 0000000000000000000000000000000000000000..f7a39d10af5f5ea48fcd948e72ba6af62e372d39 --- /dev/null +++ b/backend/node_modules/xtend/package.json @@ -0,0 +1,55 @@ +{ + "name": "xtend", + "version": "4.0.2", + "description": "extend like a boss", + "keywords": [ + "extend", + "merge", + "options", + "opts", + "object", + "array" + ], + "author": "Raynos ", + "repository": "git://github.com/Raynos/xtend.git", + "main": "immutable", + "scripts": { + "test": "node test" + }, + "dependencies": {}, + "devDependencies": { + "tape": "~1.1.0" + }, + "homepage": "https://github.com/Raynos/xtend", + "contributors": [ + { + "name": "Jake Verbaten" + }, + { + "name": "Matt Esch" + } + ], + "bugs": { + "url": "https://github.com/Raynos/xtend/issues", + "email": "raynos2@gmail.com" + }, + "license": "MIT", + "testling": { + "files": "test.js", + "browsers": [ + "ie/7..latest", + "firefox/16..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" + ] + }, + "engines": { + "node": ">=0.4" + } +} diff --git a/backend/node_modules/xtend/test.js b/backend/node_modules/xtend/test.js new file mode 100644 index 0000000000000000000000000000000000000000..b895b42b3f76804de7ee2ef0231a3343b2f461b3 --- /dev/null +++ b/backend/node_modules/xtend/test.js @@ -0,0 +1,103 @@ +var test = require("tape") +var extend = require("./") +var mutableExtend = require("./mutable") + +test("merge", function(assert) { + var a = { a: "foo" } + var b = { b: "bar" } + + assert.deepEqual(extend(a, b), { a: "foo", b: "bar" }) + assert.end() +}) + +test("replace", function(assert) { + var a = { a: "foo" } + var b = { a: "bar" } + + assert.deepEqual(extend(a, b), { a: "bar" }) + assert.end() +}) + +test("undefined", function(assert) { + var a = { a: undefined } + var b = { b: "foo" } + + assert.deepEqual(extend(a, b), { a: undefined, b: "foo" }) + assert.deepEqual(extend(b, a), { a: undefined, b: "foo" }) + assert.end() +}) + +test("handle 0", function(assert) { + var a = { a: "default" } + var b = { a: 0 } + + assert.deepEqual(extend(a, b), { a: 0 }) + assert.deepEqual(extend(b, a), { a: "default" }) + assert.end() +}) + +test("is immutable", function (assert) { + var record = {} + + extend(record, { foo: "bar" }) + assert.equal(record.foo, undefined) + assert.end() +}) + +test("null as argument", function (assert) { + var a = { foo: "bar" } + var b = null + var c = void 0 + + assert.deepEqual(extend(b, a, c), { foo: "bar" }) + assert.end() +}) + +test("mutable", function (assert) { + var a = { foo: "bar" } + + mutableExtend(a, { bar: "baz" }) + + assert.equal(a.bar, "baz") + assert.end() +}) + +test("null prototype", function(assert) { + var a = { a: "foo" } + var b = Object.create(null) + b.b = "bar"; + + assert.deepEqual(extend(a, b), { a: "foo", b: "bar" }) + assert.end() +}) + +test("null prototype mutable", function (assert) { + var a = { foo: "bar" } + var b = Object.create(null) + b.bar = "baz"; + + mutableExtend(a, b) + + assert.equal(a.bar, "baz") + assert.end() +}) + +test("prototype pollution", function (assert) { + var a = {} + var maliciousPayload = '{"__proto__":{"oops":"It works!"}}' + + assert.strictEqual(a.oops, undefined) + extend({}, maliciousPayload) + assert.strictEqual(a.oops, undefined) + assert.end() +}) + +test("prototype pollution mutable", function (assert) { + var a = {} + var maliciousPayload = '{"__proto__":{"oops":"It works!"}}' + + assert.strictEqual(a.oops, undefined) + mutableExtend({}, maliciousPayload) + assert.strictEqual(a.oops, undefined) + assert.end() +}) diff --git a/backend/package-lock.json b/backend/package-lock.json new file mode 100644 index 0000000000000000000000000000000000000000..e9999ce017dd80c0da16b5beaadc57c9306c5802 --- /dev/null +++ b/backend/package-lock.json @@ -0,0 +1,1162 @@ +{ + "name": "backend", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "dependencies": { + "@types/body-parser": "^1.19.5", + "body-parser": "^1.20.2", + "cors": "^2.8.5", + "express": "^4.19.2", + "multer": "^1.4.5-lts.1", + "openai": "^4.35.0" + }, + "devDependencies": { + "@types/express": "^4.17.21", + "@types/multer": "^1.4.11" + } + }, + "node_modules/@types/body-parser": { + "version": "1.19.5", + "resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.19.5.tgz", + "integrity": "sha512-fB3Zu92ucau0iQ0JMCFQE7b/dv8Ot07NI3KaZIkIUNXq82k4eBAqUaneXfleGY9JWskeS9y+u0nXMyspcuQrCg==", + "dependencies": { + "@types/connect": "*", + "@types/node": "*" + } + }, + "node_modules/@types/connect": { + "version": "3.4.38", + "resolved": "https://registry.npmjs.org/@types/connect/-/connect-3.4.38.tgz", + "integrity": "sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug==", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/express": { + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/@types/express/-/express-4.17.21.tgz", + "integrity": "sha512-ejlPM315qwLpaQlQDTjPdsUFSc6ZsP4AN6AlWnogPjQ7CVi7PYF3YVz+CY3jE2pwYf7E/7HlDAN0rV2GxTG0HQ==", + "dev": true, + "dependencies": { + "@types/body-parser": "*", + "@types/express-serve-static-core": "^4.17.33", + "@types/qs": "*", + "@types/serve-static": "*" + } + }, + "node_modules/@types/express-serve-static-core": { + "version": "4.19.0", + "resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-4.19.0.tgz", + "integrity": "sha512-bGyep3JqPCRry1wq+O5n7oiBgGWmeIJXPjXXCo8EK0u8duZGSYar7cGqd3ML2JUsLGeB7fmc06KYo9fLGWqPvQ==", + "dev": true, + "dependencies": { + "@types/node": "*", + "@types/qs": "*", + "@types/range-parser": "*", + "@types/send": "*" + } + }, + "node_modules/@types/http-errors": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/@types/http-errors/-/http-errors-2.0.4.tgz", + "integrity": "sha512-D0CFMMtydbJAegzOyHjtiKPLlvnm3iTZyZRSZoLq2mRhDdmLfIWOCYPfQJ4cu2erKghU++QvjcUjp/5h7hESpA==", + "dev": true + }, + "node_modules/@types/mime": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/@types/mime/-/mime-1.3.5.tgz", + "integrity": "sha512-/pyBZWSLD2n0dcHE3hq8s8ZvcETHtEuF+3E7XVt0Ig2nvsVQXdghHVcEkIWjy9A0wKfTn97a/PSDYohKIlnP/w==", + "dev": true + }, + "node_modules/@types/multer": { + "version": "1.4.11", + "resolved": "https://registry.npmjs.org/@types/multer/-/multer-1.4.11.tgz", + "integrity": "sha512-svK240gr6LVWvv3YGyhLlA+6LRRWA4mnGIU7RcNmgjBYFl6665wcXrRfxGp5tEPVHUNm5FMcmq7too9bxCwX/w==", + "dev": true, + "dependencies": { + "@types/express": "*" + } + }, + "node_modules/@types/node": { + "version": "18.19.31", + "resolved": "https://registry.npmjs.org/@types/node/-/node-18.19.31.tgz", + "integrity": "sha512-ArgCD39YpyyrtFKIqMDvjz79jto5fcI/SVUs2HwB+f0dAzq68yqOdyaSivLiLugSziTpNXLQrVb7RZFmdZzbhA==", + "dependencies": { + "undici-types": "~5.26.4" + } + }, + "node_modules/@types/node-fetch": { + "version": "2.6.11", + "resolved": "https://registry.npmjs.org/@types/node-fetch/-/node-fetch-2.6.11.tgz", + "integrity": "sha512-24xFj9R5+rfQJLRyM56qh+wnVSYhyXC2tkoBndtY0U+vubqNsYXGjufB2nn8Q6gt0LrARwL6UBtMCSVCwl4B1g==", + "dependencies": { + "@types/node": "*", + "form-data": "^4.0.0" + } + }, + "node_modules/@types/qs": { + "version": "6.9.15", + "resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.9.15.tgz", + "integrity": "sha512-uXHQKES6DQKKCLh441Xv/dwxOq1TVS3JPUMlEqoEglvlhR6Mxnlew/Xq/LRVHpLyk7iK3zODe1qYHIMltO7XGg==", + "dev": true + }, + "node_modules/@types/range-parser": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/@types/range-parser/-/range-parser-1.2.7.tgz", + "integrity": "sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ==", + "dev": true + }, + "node_modules/@types/send": { + "version": "0.17.4", + "resolved": "https://registry.npmjs.org/@types/send/-/send-0.17.4.tgz", + "integrity": "sha512-x2EM6TJOybec7c52BX0ZspPodMsQUd5L6PRwOunVyVUhXiBSKf3AezDL8Dgvgt5o0UfKNfuA0eMLr2wLT4AiBA==", + "dev": true, + "dependencies": { + "@types/mime": "^1", + "@types/node": "*" + } + }, + "node_modules/@types/serve-static": { + "version": "1.15.7", + "resolved": "https://registry.npmjs.org/@types/serve-static/-/serve-static-1.15.7.tgz", + "integrity": "sha512-W8Ym+h8nhuRwaKPaDw34QUkwsGi6Rc4yYqvKFo5rm2FUEhCFbzVWrxXUxuKK8TASjWsysJY0nsmNCGhCOIsrOw==", + "dev": true, + "dependencies": { + "@types/http-errors": "*", + "@types/node": "*", + "@types/send": "*" + } + }, + "node_modules/abort-controller": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz", + "integrity": "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==", + "dependencies": { + "event-target-shim": "^5.0.0" + }, + "engines": { + "node": ">=6.5" + } + }, + "node_modules/accepts": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", + "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", + "dependencies": { + "mime-types": "~2.1.34", + "negotiator": "0.6.3" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/agentkeepalive": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/agentkeepalive/-/agentkeepalive-4.5.0.tgz", + "integrity": "sha512-5GG/5IbQQpC9FpkRGsSvZI5QYeSCzlJHdpBQntCsuTOxhKD8lqKhrleg2Yi7yvMIf82Ycmmqln9U8V9qwEiJew==", + "dependencies": { + "humanize-ms": "^1.2.1" + }, + "engines": { + "node": ">= 8.0.0" + } + }, + "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==" + }, + "node_modules/array-flatten": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", + "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==" + }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==" + }, + "node_modules/body-parser": { + "version": "1.20.2", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.2.tgz", + "integrity": "sha512-ml9pReCu3M61kGlqoTm2umSXTlRTuGTx0bfYj+uIUKKYycG5NtSbeetV3faSU6R7ajOPw0g/J1PvK4qNy7s5bA==", + "dependencies": { + "bytes": "3.1.2", + "content-type": "~1.0.5", + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "http-errors": "2.0.0", + "iconv-lite": "0.4.24", + "on-finished": "2.4.1", + "qs": "6.11.0", + "raw-body": "2.5.2", + "type-is": "~1.6.18", + "unpipe": "1.0.0" + }, + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "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==" + }, + "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==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.7.tgz", + "integrity": "sha512-GHTSNSYICQ7scH7sZ+M2rFopRoLh8t2bLSW6BbgrtLsahOIB5iyAVJf9GjWK3cYTDaMj4XdBpM1cA6pIS0Kv2w==", + "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "set-function-length": "^1.2.1" + }, + "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==", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/concat-stream": { + "version": "1.6.2", + "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-1.6.2.tgz", + "integrity": "sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw==", + "engines": [ + "node >= 0.8" + ], + "dependencies": { + "buffer-from": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^2.2.2", + "typedarray": "^0.0.6" + } + }, + "node_modules/content-disposition": { + "version": "0.5.4", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", + "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==", + "dependencies": { + "safe-buffer": "5.2.1" + }, + "engines": { + "node": ">= 0.6" + } + }, + "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==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.6.0.tgz", + "integrity": "sha512-U71cyTamuh1CRNCfpGY6to28lxvNwPG4Guz/EVjgf3Jmzv0vlDp1atT9eS5dDjMYHucpHbWns6Lwf3BKz6svdw==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", + "integrity": "sha512-QADzlaHc8icV8I7vbaJXJwod9HWYp8uCqf1xa4OfNu1T7JVxQIrUgOWtHdNDtPiywmFbiS12VjotIXLrKM3orQ==" + }, + "node_modules/core-util-is": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", + "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==" + }, + "node_modules/cors": { + "version": "2.8.5", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz", + "integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==", + "dependencies": { + "object-assign": "^4", + "vary": "^1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/define-data-property": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz", + "integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==", + "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "gopd": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "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==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/destroy": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", + "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==", + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "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==" + }, + "node_modules/encodeurl": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", + "integrity": "sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/es-define-property": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.0.tgz", + "integrity": "sha512-jxayLKShrEqqzJ0eumQbVhTYQM27CfT1T35+gCgDFoL82JLsXqTJ76zv6A0YLOgEnLUMvLzsDsGIrl8NFpT2gQ==", + "dependencies": { + "get-intrinsic": "^1.2.4" + }, + "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==", + "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==" + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/event-target-shim": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz", + "integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==", + "engines": { + "node": ">=6" + } + }, + "node_modules/express": { + "version": "4.19.2", + "resolved": "https://registry.npmjs.org/express/-/express-4.19.2.tgz", + "integrity": "sha512-5T6nhjsT+EOMzuck8JjBHARTHfMht0POzlA60WV2pMD3gyXw2LZnZ+ueGdNxG+0calOJcWKbpFcuzLZ91YWq9Q==", + "dependencies": { + "accepts": "~1.3.8", + "array-flatten": "1.1.1", + "body-parser": "1.20.2", + "content-disposition": "0.5.4", + "content-type": "~1.0.4", + "cookie": "0.6.0", + "cookie-signature": "1.0.6", + "debug": "2.6.9", + "depd": "2.0.0", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "finalhandler": "1.2.0", + "fresh": "0.5.2", + "http-errors": "2.0.0", + "merge-descriptors": "1.0.1", + "methods": "~1.1.2", + "on-finished": "2.4.1", + "parseurl": "~1.3.3", + "path-to-regexp": "0.1.7", + "proxy-addr": "~2.0.7", + "qs": "6.11.0", + "range-parser": "~1.2.1", + "safe-buffer": "5.2.1", + "send": "0.18.0", + "serve-static": "1.15.0", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "type-is": "~1.6.18", + "utils-merge": "1.0.1", + "vary": "~1.1.2" + }, + "engines": { + "node": ">= 0.10.0" + } + }, + "node_modules/finalhandler": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.2.0.tgz", + "integrity": "sha512-5uXcUVftlQMFnWC9qu/svkWv3GTd2PfUhK/3PLkYNAe7FbqJMt3515HaxE6eRL74GdsriiwujiawdaB1BpEISg==", + "dependencies": { + "debug": "2.6.9", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "on-finished": "2.4.1", + "parseurl": "~1.3.3", + "statuses": "2.0.1", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/form-data": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz", + "integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "mime-types": "^2.1.12" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/form-data-encoder": { + "version": "1.7.2", + "resolved": "https://registry.npmjs.org/form-data-encoder/-/form-data-encoder-1.7.2.tgz", + "integrity": "sha512-qfqtYan3rxrnCk1VYaA4H+Ms9xdpPqvLZa6xmMgFvhO32x7/3J/ExcTd6qpxM0vH2GdMI+poehyBZvqfMTto8A==" + }, + "node_modules/formdata-node": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/formdata-node/-/formdata-node-4.4.1.tgz", + "integrity": "sha512-0iirZp3uVDjVGt9p49aTaqjk84TrglENEDuqfdlZQ1roC9CWlPk6Avf8EEnZNcAqPonwkG35x4n3ww/1THYAeQ==", + "dependencies": { + "node-domexception": "1.0.0", + "web-streams-polyfill": "4.0.0-beta.3" + }, + "engines": { + "node": ">= 12.20" + } + }, + "node_modules/formdata-node/node_modules/web-streams-polyfill": { + "version": "4.0.0-beta.3", + "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-4.0.0-beta.3.tgz", + "integrity": "sha512-QW95TCTaHmsYfHDybGMwO5IJIM93I/6vTRk+daHTWFPhwh+C8Cg7j7XyKrwrj8Ib6vYXe0ocYNrmzY4xAAN6ug==", + "engines": { + "node": ">= 14" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", + "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==", + "engines": { + "node": ">= 0.6" + } + }, + "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==", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.4.tgz", + "integrity": "sha512-5uYhsJH8VJBTv7oslg4BznJYhDoRI6waYCxMmCdnTrcCrHA/fCFKoTFz2JKKE0HdDFUF7/oQuhzumXJK7paBRQ==", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "has-proto": "^1.0.1", + "has-symbols": "^1.0.3", + "hasown": "^2.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/gopd": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.0.1.tgz", + "integrity": "sha512-d65bNlIadxvpb/A2abVdlqKqV563juRnZ1Wtk6s1sIR8uNsXR70xqIzVqxVf1eTqDunwT2MkczEeaezCKTZhwA==", + "dependencies": { + "get-intrinsic": "^1.1.3" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-property-descriptors": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz", + "integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==", + "dependencies": { + "es-define-property": "^1.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-proto": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has-proto/-/has-proto-1.0.3.tgz", + "integrity": "sha512-SJ1amZAJUiZS+PhsVLf5tGydlaVB8EdFpaSO4gmiUKUOxk8qzn5AIy4ZeJUmh22znIdk/uMAUT2pl3FxzVUH+Q==", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.3.tgz", + "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/http-errors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz", + "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", + "dependencies": { + "depd": "2.0.0", + "inherits": "2.0.4", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "toidentifier": "1.0.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/humanize-ms": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/humanize-ms/-/humanize-ms-1.2.1.tgz", + "integrity": "sha512-Fl70vYtsAFb/C06PTS9dZBo7ihau+Tu/DNCk/OyHhea07S+aeMWpFFkUaXRa8fI+ScZbEI8dfSxwY7gxZ9SAVQ==", + "dependencies": { + "ms": "^2.0.0" + } + }, + "node_modules/iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" + }, + "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==", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==" + }, + "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==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/merge-descriptors": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz", + "integrity": "sha512-cCi6g3/Zr1iqQi6ySbseM1Xvooa98N0w31jzUYrXPX2xqObmFGHJ0tQ5u74H3mVh7wLouTseZyYIq39g8cNp1w==" + }, + "node_modules/methods": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", + "integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", + "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4" + } + }, + "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==", + "engines": { + "node": ">= 0.6" + } + }, + "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==", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/mkdirp": { + "version": "0.5.6", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.6.tgz", + "integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==", + "dependencies": { + "minimist": "^1.2.6" + }, + "bin": { + "mkdirp": "bin/cmd.js" + } + }, + "node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==" + }, + "node_modules/multer": { + "version": "1.4.5-lts.1", + "resolved": "https://registry.npmjs.org/multer/-/multer-1.4.5-lts.1.tgz", + "integrity": "sha512-ywPWvcDMeH+z9gQq5qYHCCy+ethsk4goepZ45GLD63fOu0YcNecQxi64nDs3qluZB+murG3/D4dJ7+dGctcCQQ==", + "dependencies": { + "append-field": "^1.0.0", + "busboy": "^1.0.0", + "concat-stream": "^1.5.2", + "mkdirp": "^0.5.4", + "object-assign": "^4.1.1", + "type-is": "^1.6.4", + "xtend": "^4.0.0" + }, + "engines": { + "node": ">= 6.0.0" + } + }, + "node_modules/negotiator": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", + "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/node-domexception": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz", + "integrity": "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + }, + { + "type": "github", + "url": "https://paypal.me/jimmywarting" + } + ], + "engines": { + "node": ">=10.5.0" + } + }, + "node_modules/node-fetch": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", + "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "engines": { + "node": "4.x || >=6.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-inspect": { + "version": "1.13.1", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.1.tgz", + "integrity": "sha512-5qoj1RUiKOMsCCNLV1CBiPYE10sziTsnmNxkAI/rZhiD63CF7IqdFGC/XzjWjpSgLf0LxXX3bDFIh0E18f6UhQ==", + "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==", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/openai": { + "version": "4.35.0", + "resolved": "https://registry.npmjs.org/openai/-/openai-4.35.0.tgz", + "integrity": "sha512-K8GY7k4h+dT2GSmn3JGSjkwElpo8cPa4eQ6p++uK1HSrrIBp6NalD3A3DIamvX1AnIyrKqe8M//HoQWgjntUiA==", + "dependencies": { + "@types/node": "^18.11.18", + "@types/node-fetch": "^2.6.4", + "abort-controller": "^3.0.0", + "agentkeepalive": "^4.2.1", + "form-data-encoder": "1.7.2", + "formdata-node": "^4.3.2", + "node-fetch": "^2.6.7", + "web-streams-polyfill": "^3.2.1" + }, + "bin": { + "openai": "bin/cli" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-to-regexp": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz", + "integrity": "sha512-5DFkuoqlv1uYQKxy8omFBeJPQcdoE07Kv2sferDCrAq1ohOU+MSDswDIbnx3YAM60qIOnYa53wBhXW0EbMonrQ==" + }, + "node_modules/process-nextick-args": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", + "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==" + }, + "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==", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/qs": { + "version": "6.11.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.11.0.tgz", + "integrity": "sha512-MvjoMCJwEarSbUYk5O+nmoSzSutSsTwF85zcHPQ9OrlFoZOYIjaqBAJIqIXjptyD5vThxGq52Xu/MaJzRkIk4Q==", + "dependencies": { + "side-channel": "^1.0.4" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "2.5.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.2.tgz", + "integrity": "sha512-8zGqypfENjCIqGhgXToC8aB2r7YrBX+AQAfIPs/Mlk+BtPTztOvTS01NRW/3Eh60J+a48lt8qsCzirQ6loCVfA==", + "dependencies": { + "bytes": "3.1.2", + "http-errors": "2.0.0", + "iconv-lite": "0.4.24", + "unpipe": "1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/readable-stream": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz", + "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/readable-stream/node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==" + }, + "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" + } + ] + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" + }, + "node_modules/send": { + "version": "0.18.0", + "resolved": "https://registry.npmjs.org/send/-/send-0.18.0.tgz", + "integrity": "sha512-qqWzuOjSFOuqPjFe4NOsMLafToQQwBSOEpS+FwEt3A2V3vKubTquT3vmLTQpFgMXp8AlFWFuP1qKaJZOtPpVXg==", + "dependencies": { + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "fresh": "0.5.2", + "http-errors": "2.0.0", + "mime": "1.6.0", + "ms": "2.1.3", + "on-finished": "2.4.1", + "range-parser": "~1.2.1", + "statuses": "2.0.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/send/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==" + }, + "node_modules/serve-static": { + "version": "1.15.0", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.15.0.tgz", + "integrity": "sha512-XGuRDNjXUijsUL0vl6nSD7cwURuzEgglbOaFuZM9g3kwDXOWVTck0jLzjPzGD+TazWbboZYu52/9/XPdUgne9g==", + "dependencies": { + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "parseurl": "~1.3.3", + "send": "0.18.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/set-function-length": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz", + "integrity": "sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==", + "dependencies": { + "define-data-property": "^1.1.4", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "gopd": "^1.0.1", + "has-property-descriptors": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==" + }, + "node_modules/side-channel": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.6.tgz", + "integrity": "sha512-fDW/EZ6Q9RiO8eFG8Hj+7u/oW+XrPTIChwCOM2+th2A6OblDtYYIpve9m+KvI9Z4C9qSEXlaGR6bTEYHReuglA==", + "dependencies": { + "call-bind": "^1.0.7", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.4", + "object-inspect": "^1.13.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/statuses": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", + "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", + "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.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, + "node_modules/string_decoder/node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==" + }, + "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==", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/tr46": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", + "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==" + }, + "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==", + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + }, + "engines": { + "node": ">= 0.6" + } + }, + "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==" + }, + "node_modules/undici-types": { + "version": "5.26.5", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz", + "integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==" + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "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==" + }, + "node_modules/utils-merge": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", + "integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==", + "engines": { + "node": ">= 0.4.0" + } + }, + "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==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/web-streams-polyfill": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.3.3.tgz", + "integrity": "sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==", + "engines": { + "node": ">= 8" + } + }, + "node_modules/webidl-conversions": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", + "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==" + }, + "node_modules/whatwg-url": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", + "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + } + }, + "node_modules/xtend": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", + "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==", + "engines": { + "node": ">=0.4" + } + } + } +} diff --git a/backend/package.json b/backend/package.json new file mode 100644 index 0000000000000000000000000000000000000000..3e6bd3b9cea6d0ca1aaca4f3e98457b8ac879c81 --- /dev/null +++ b/backend/package.json @@ -0,0 +1,15 @@ +{ + "dependencies": { + "@types/body-parser": "^1.19.5", + "body-parser": "^1.20.2", + "cors": "^2.8.5", + "express": "^4.19.2", + "multer": "^1.4.5-lts.1", + "openai": "^4.35.0" + }, + "type": "module", + "devDependencies": { + "@types/express": "^4.17.21", + "@types/multer": "^1.4.11" + } +}